question
stringlengths
6
13.7k
text
stringlengths
1
25.8k
source
stringclasses
3 values
What is the reason that the windows of ships' bridges are always inclined as shown in the above picture?
Look at CandiedOrange's answer This answer was accepted, but CandiedOrange has the right answer. See this document page 21: The second way in which reflection can interfer e with controller’s vision is light sources within the cab (or direct sunlight that enters the cab), which can cause disturbing reflections during either day or night operations. The effects of these reflections can be a loss of contrast of the image being viewed, a masking effect of a competing image, or glare. The two ways to mitigate these effects are to reduce the reflection coefficient or to design the ATCT cab to reduce or eliminate the probability that any light source (artificial or natural, direct or indirect) can produce a reflection in the pathway of a controller’s view out of the cab windows. It controls glare. Whenever the sun hits a window, it reflects off of it. If the windows are vertical, its pretty hard to control where that glint could go. When the sun is near the horizon, it could even be seen by other ships, but at the very least it can blind workers on your own ship. Angling them doesn't prevent this from happening entirely, but it does substantially limit the places on the ship which can be hit by this glint to a small region around the bridge itself. This requirement appears in specifications such as these regulations from the UK: 1.9 Windows shall meet the following requirements: 1.9.1 To help avoid reflections, the bridge front windows shall be inclined from the vertical plane top out, at an angle of not less than 10° and not more than 25°. ... These same rules are also applied to air traffic control towers at airports:
https://api.stackexchange.com
Several gene set enrichment methods are available, the most famous/popular is the Broad Institute tool. Many other tools are available (See for example the biocView of GSE which list 82 different packages). There are several parameters in consideration : the statistic used to order the genes, if it competitive or self-contained, if it is supervised or not, and how is the enrichment score calculated. I am using the fgsea - Fast Gene Set Enrichment Analysis package to calculate the enrichment scores and someone told me that the numbers are different from the ones on the Broad Institute despite all the other parameters being equivalent. Are these two methods (fgsea and Broad Institute GSEA) equivalent to calculate the enrichment score? I looked to the algorithms of both papers, and they seem fairly similar, but I don't know if in real datasets they are equivalent or not. Is there any article reviewing and comparing how does the enrichment score method affect to the result?
According to the FGSEA preprint: We ran reference GSEA with default parameters. The permutation number was set to 1000, which means that for each input gene set 1000 independent samples were generated. The run took 100 seconds and resulted in 79 gene sets with GSEA-adjusted FDR q-value of less than 10−2. All significant gene sets were in a positive mode. First, to get a similar nominal p-values accuracy we ran FGSEA algorithm on 1000 permutations. This took 2 seconds, but resulted in no significant hits due after multiple testing correction (with FRD ≤ 1%). Thus, FGSEA and GSEA are not identical. And again in the conclusion: Consequently, gene sets can be ranked more precisely in the results and, which is even more important, standard multiple testing correction methods can be applied instead of approximate ones as in [GSEA]. The author argues that FGSEA is more accurate, so it can't be equivalent. If you are interested specifically in the enrichment score, that was addressed by the author in the preprint comments: Values of enrichment scores and normalized enrichment scores are the same for both broad version and fgsea. So that part seems to be the same.
https://api.stackexchange.com
Why are nearly all amino acids in organisms left-handed (exception is glycine which has no isomer) when abiotic samples typical have an even mix of left- and right-handed molecules?
I know that you are referring to the commonly ribosome-translated L-proteins, but I can't help but add that there are some peptides, called nonribosomal peptides, which are not dependent on the mRNA and can incorporate D-amino acids. They have very important pharmaceutical properties. I recommend this (1) review article if you are interested in the subject. It is also worth mentioning that D-alanine and D-glutamine are incorporated into the peptidoglycane of bacteria. I read several papers (2, 3, 4) that discuss the problem of chirality but all of them conclude that there is no apparent reason why we live in the L-world. The L-amino acids should not have chemical advantages over the D-amino acids, as biocs already pointed out. Reasons for the occurrence of the twenty coded protein amino acids (2) has an informative and interesting outline. This is the paragraph on the topic of chirality: This is related to the question of the origin of optical activity in living organisms on which there is a very large literature (Bonner 1972; Norden 1978; Brack and Spack 1980). We do not propose to deal with this question here, except to note that arguments presented in this paper would apply to organisms constructed from either D or L amino acids. It might be possible that both L and D lives were present (L/D-amino acids, L/D-enzymes recognizing L/D-substrates), but, by random chance the L-world outcompeted the D-world. I also found the same question in a forum where one of the answers seems intriguing. I cannot comment on the reliability of the answer, but hopefully someone will have the expertise to do so: One, our galaxy has a chiral spin and a magnetic orientation, which causes cosmic dust particles to polarize starlight as circularly polarized in one direction only. This circularly polarized light degrades D enantiomers of amino acids more than L enantiomers, and this effect is clear when analyzing the amino acids found on comets and meteors. This explains why, at least in the milky way, L enantiomers are preferred. Two, although gravity, electromagnetism, and the strong nuclear force are achiral, the weak nuclear force (radioactive decay) is chiral. During beta decay, the emitted electrons preferentially favor one kind of spin. That's right, the parity of the universe is not conserved in nuclear decay. These chiral electrons once again preferrentially degrade D amino acids vs. L amino acids. Thus due to the chirality of sunlight and the chirality of nuclear radiation, L amino acids are the more stable enantiomers and therefore are favored for abiogenesis. BIOSYNTHESIS OF NONRIBOSOMAL PEPTIDES Reasons for the occurrence of the twenty coded protein amino acids Molecular Basis for Chiral Selection in RNA Aminoacylation How nature deals with stereoisomers The adaptation of diastereomeric S-prolyl dipeptide derivatives to the quantitative estimation of R- and S-leucine enantiomers. Bonner WA, 1972 The asymmetry of life. Nordén B, 1978 Beta-Structures of polypeptides with L- and D-residues. Part III. Experimental evidences for enrichment in enantiomer. Brack A, Spach G, 1980
https://api.stackexchange.com
What is the difference between thermodynamic and kinetic stability? I'd like a basic explanation, but not too simple. For example, methane does not burn until lit -- why?
To understand the difference between kinetic and thermodynamic stability, you first have to understand potential energy surfaces, and how they are related to the state of a system. A potential energy surface is a representation of the potential energy of a system as a function of one or more of the other dimensions of a system. Most commonly, the other dimensions are spatial. Potential energy surfaces for chemical systems are usually very complex and hard to draw and visualize. Fortunately, we can make life easier by starting with simple 2-d models, and then extend that understanding to the generalized N-d case. So, we will start with the easiest type of potential energy to understand: gravitational potential energy. This is easy for us because we live on Earth and are affected by it every day. We have developed an intuitive sense that things tend to move from higher places to lower places, if given the opportunity. For example, if I show you this picture: You can guess that the rock is eventually going to roll downhill, and eventually come to rest at the bottom of the valley. However, you also intuitively know that it is not going to move unless something moves it. In other words, it needs some kinetic energy to get going. I could make it even harder for the rock to get moving by changing the surface a little bit: Now it is really obvious that the rock isn't going anywhere until it gains enough kinetic energy to overcome the little hill between the valley it is in, and the deeper valley to the right. We call the first valley a local minimum in the potential energy surface. In mathematical terms, this means that the first derivative of potential energy with respect to position is zero: $$\frac{\mathrm dE}{\mathrm dx} = 0$$ and the second derivative is positive: $$\frac{\mathrm d^2E}{\mathrm dx^2} \gt 0$$ In other words, the slope is zero and the shape is concave up (or convex). The deeper valley to the right is the global minimum (at least as far as we can tell). It has the same mathematical properties, but the magnitude of the energy is lower – the valley is deeper. If you put all of this together, (and can tolerate a little anthropomorphization) you could say that the rock wants to get to the global minimum, but whether or not it can get there is determined by the amount of kinetic energy it has. It needs at least enough kinetic energy to overcome all of the local maxima along the path between its current local minimum and the global minimum. If it doesn't have enough kinetic energy to move out of its current position, we say that it is kinetically stable or kinetically trapped. If it has reached the global minimum, we say it is thermodynamically stable. To apply this concept to chemical systems, we have to change the potential energy that we use to describe the system. Gravitational potential energy is too weak to play much of a role at the molecular level. For large systems of reacting molecules, we instead look at one of several thermodynamic potential energies. The one we choose depends on which state variables are constant. For macroscopic chemical reactions, there is usually a constant number of particles, constant temperature, and either constant pressure or volume (NPT or NVT), and so we use the Gibbs Free Energy ($G$ for NPT systems) or the Helmholtz Free Energy ($A$ for NVT systems). Each of these is a thermodynamic potential under the appropriate conditions, which means that it does the same thing that gravitational potential energy does: it allows us to predict where the system will go, if it gets the opportunity to do so. For kinetic energy, we don't have to change much - the main difference between the kinetic energy of a rock on a hill and the kinetic energy of a large collection of molecules is how we measure it. For single particles, we can measure it using the velocity, but for large groups of molecules, we have to measure it using temperature. In other words, increasing the temperature increases the kinetic energy of all molecules in a system. If we can describe the thermodynamic potential energy of a system in different states, we can figure out whether a transition between two states is thermodynamically favorable – we can calculate whether the potential energy would increase, decrease, or stay the same. If we look at all accessible states and decide that the one we are in has the lowest thermodynamic potential energy, then we are in a thermodynamically stable state. In your example using methane gas, we can look at Gibbs free energy for the reactants and products and decide that the products are more thermodynamically stable than the reactants, and therefore methane gas in the presence of oxygen at 1 atm and 298 K is thermodynamically unstable. However, you would have to wait a very long time for methane to react without some outside help. The reason is that the transition states along the lowest-energy reaction path have a much higher thermodynamic potential energy than the average kinetic energy of the reactants. The reactants are kinetically trapped - or stable just because they are stuck in a local minimum. The minimum amount of energy that you would need to provide in the form of heat (a lit match) to overcome that barrier is called the activation energy. We can apply this to lots of other systems as well. One of the most famous and still extensively researched examples is glasses. Glasses are interesting because they are examples of kinetic stability in physical phases. Usually, phase changes are governed by thermodynamic stability. In glassy solids, the molecules would have a lower potential energy if they were arranged in a crystalline structure, but because they don't have the energy needed to get out of the local minimum, they are "stuck" with a liquid-like disordered structure, even though the phase is a solid.
https://api.stackexchange.com
In "Surely You're Joking, Mr. Feynman!," Nobel-prize winning Physicist Richard Feynman said that he challenged his colleagues to give him an integral that they could evaluate with only complex methods that he could not do with real methods: One time I boasted, "I can do by other methods any integral anybody else needs contour integration to do." So Paul [Olum] puts up this tremendous damn integral he had obtained by starting out with a complex function that he knew the answer to, taking out the real part of it and leaving only the complex part. He had unwrapped it so it was only possible by contour integration! He was always deflating me like that. He was a very smart fellow. Does anyone happen to know what this integral was?
I doubt that we will ever know the exact integral that vexed Feynman. Here is something similar to what he describes. Suppose $f(z)$ is an analytic function on the unit disk. Then, by Cauchy's integral formula, $$\oint_\gamma \frac{f(z)}{z}dz = 2\pi i f(0),$$ where $\gamma$ traces out the unit circle in a counterclockwise manner. Let $z=e^{i\phi}$. Then $\int_0^{2\pi}f(e^{i\phi}) d\phi = 2\pi f(0).$ Taking the real part of each side we find $$\begin{equation*} \int_0^{2\pi} \mathrm{Re}(f(e^{i\phi}))d\phi = 2\pi \mathrm{Re}(f(0)).\tag{1} \end{equation*}$$ (We could just as well take the imaginary part.) Clearly we can build some terrible integrals by choosing $f$ appropriately. Example 1. Let $\displaystyle f(z) = \exp\frac{2+z}{3+z}$. This is a mild choice compared to what could be done ... In any case, $f$ is analytic on the disk. Applying (1), and after some manipulations of the integrand, we find $$\int_0^{2\pi} \exp\left(\frac{7+5 \cos\phi}{10+6\cos\phi}\right) \cos \left( \frac{\sin\phi}{10+6 \cos\phi} \right) d\phi = 2\pi e^{2/3}.$$ Example 2. Let $\displaystyle f(z) = \exp \exp \frac{2+z}{3+z}$. Then \begin{align*}\int_0^{2\pi} & \exp\left( \exp\left( \frac{7+5 \cos \phi}{10+6 \cos \phi} \right) \cos\left( \frac{\sin \phi}{10+6 \cos \phi} \right) \right) \\ & \times\cos\left( \exp\left( \frac{7+5 \cos \phi}{10+6 \cos \phi} \right) \sin\left( \frac{\sin \phi}{10+6 \cos \phi} \right) \right) = 2\pi e^{e^{2/3}}. \end{align*}
https://api.stackexchange.com
I have to do cross correlation of two audio file to prove they are similar. I have taken the FFT of the two audio files and have their power spectrum values in separate arrays. How should I proceed further to cross-correlate them and prove that they're similar? Is there a better way to do it? Any basic ideas will be helpful for me to learn and apply it.
Cross-correlation and convolution are closely related. In short, to do convolution with FFTs, you zero-pad the input signals a and b (add zeros to the end of each. The zero padding should fill the vectors until they reach a size of at least N = size(a)+size(b)-1) take the FFT of both signals multiply the results together (element-wise multiplication) do the inverse FFT conv(a, b) = ifft(fft(a_and_zeros) * fft(b_and_zeros)) You need to do the zero-padding because the FFT method is actually circular cross-correlation, meaning the signal wraps around at the ends. So you add enough zeros to get rid of the overlap, to simulate a signal that is zero out to infinity. To get cross-correlation instead of convolution, you either need to time-reverse one of the signals before doing the FFT, or take the complex conjugate of one of the signals after the FFT: corr(a, b) = ifft(fft(a_and_zeros) * fft(b_and_zeros[reversed])) corr(a, b) = ifft(fft(a_and_zeros) * conj(fft(b_and_zeros))) whichever is easier with your hardware/software. For autocorrelation (cross-correlation of a signal with itself), it's better to do the complex conjugate, because then you only need to calculate the FFT once. If the signals are real, you can use real FFTs (RFFT/IRFFT) and save half your computation time by only calculating half of the spectrum. Also you can save computation time by padding to a larger size that the FFT is optimized for (such as a 5-smooth number for FFTPACK, a ~13-smooth number for FFTW, or a power of 2 for a simple hardware implementation). Here's an example in Python of FFT correlation compared with brute-force correlation: This will give you the cross-correlation function, which is a measure of similarity vs offset. To get the offset at which the waves are "lined up" with each other, there will be a peak in the correlation function: The x value of the peak is the offset, which could be negative or positive. I've only seen this used to find the offset between two waves. You can get a more precise estimate of the offset (better than the resolution of your samples) by using parabolic/quadratic interpolation on the peak. To get a similarity value between -1 and 1 (a negative value indicating one of the signals decreases as the other increases) you'd need to scale the amplitude according to the length of the inputs, length of the FFT, your particular FFT implementation's scaling, etc. The autocorrelation of a wave with itself will give you the value of the maximum possible match. Note that this will only work on waves that have the same shape. If they've been sampled on different hardware or have some noise added, but otherwise still have the same shape, this comparison will work, but if the wave shape has been changed by filtering or phase shifts, they may sound the same, but won't correlate as well.
https://api.stackexchange.com
Last night my daughter was asking why a mirror "always does that" (referring to reflecting a spot of light). To help her figure it out, I grabbed my green laser pointer so she could see the light traveling from the source and reflecting off the mirror. But as we were playing, I noticed something strange. Rather than one spot, there were several. When I adjusted the angle to something fairly obtuse The effect became quite pronounced And when you looked closely, you could actually see several beams (Of course, the beams actually looked like beams in real life. The picture gives the beams an elongated hourglass shape because those parts are out of focus.) I made these observations: The shallower the angle, the greater the spread of the split beams and resulting dots. The directionality of the reflection is due to the orientation of the mirror, not the laser pointer itself. Indeed, by rotating the mirror 360° the string of dots would make a full rotation as well. I can count at least 8 individual dots on the wall, but I could only see 6 beams with the naked eye. If you look at the split beam picture you can see a vertical line above the most intense dots. I didn't observe any intense spots of light there. And when I looked closely at the spot where the beam hit the mirror you can see a double image. This was not due to camera shake, just the light reflecting off the dust on the surface of the glass, and a reflection of that light from the rear surface of the mirror. It's been a few years since college physics, I remembered doing things like the double split experiment. I also remembered that light seems like it does some strange things when it enters liquid/prisms. I also know that the green laser has a certain wavelength, and you can measure the speed of light with a chocolate bar and a microwave. Why does the mirror split the laser beam? How does that explain the effects that I saw? Is there any relation to the double split experiment, or the wavelength/speed of light?
You are getting reflections from the front (glass surface) and back (mirrored) surface, including (multiple) internal reflections: It should be obvious from this diagram that the spots will be further apart as you move to a more glancing angle of incidence. Depending on the polarization of the laser pointer, there is an angle (the Brewster angle) where you can make the front (glass) surface reflection disappear completely. This takes some experimenting. The exact details of the intensity as a function of angle of incidence are described by the Fresnel Equations. From that Wikipedia article, here is a diagram showing how the intensity of the (front) reflection changes with angle of incidence and polarization: This effect is independent of wavelength (except inasmuch as the refractive index is a weak function of wavelength... So different colors of light will have a slightly different Brewster angle); the only way in which laser light is different from "ordinary" light in this case is the fact that laser light is typically linearly polarized, so that the reflection coefficient for a particular angle can be changed simply by rotating the laser pointer. As Rainer P pointed out in a comment, if there is a coefficient of reflection $c$ at the front face, then $(1-c)$ of the intensity makes it to the back; and if the coefficient of reflection at the inside of the glass/air interface is $r$, then the successive reflected beams will have intensities that decrease geometrically: $$c, (1-c)(1-r), (1-c)(1-r)r, (1-c)(1-r)r^2, (1-c)(1-r)r^3, ...$$ Of course the reciprocity theorem tells us that when we reverse the direction of a beam, we get the same reflectivity, so $r=c$ . This means the above can be simplified; but I left it in this form to show better what interactions the rays undergo. The above also assumes perfect reflection at the silvered (back) face: it should be easy to see how you could add that term...
https://api.stackexchange.com
I do not remember precisely what the equations or who the relevant mathematicians and physicists were, but I recall being told the following story. I apologise in advance if I have misunderstood anything, or just have it plain wrong. The story is as follows. A quantum physicist created some equations to model what we already know about sub-atomic particles. His equations and models are amazingly accurate, but they only seem to be able to hold true if a mysterious particle, currently unknown to humanity, exists. More experiments are run and lo and behold, that 'mysterious particle' in actual fact exists! It was found to be a quark/dark-matter/anti-matter, or something of the sort. What similar occurrences in history have occurred, where the mathematical model was so accurate/good, that it 'accidentally' led to the discovery of something previously unknown? If you have an answer, could you please provide the specific equation(s), or the name of the equation(s), that directly led to this? I can recall one other example. Maxwell's equations predicted the existence of radio waves, which were then found by Hertz.
The planet Neptune's discovery was an example of something similar to this. It was known that Newtons's Equations gave the wrong description of the motion of Uranus and Mercury. Urbain Le Verrier sat down and tried to see what would happen if we assumed that the equations were right and the universe was wrong. He set up a complicated system of equations that incorporated a lot of ways contemporary knowledge of the universe could wrong, including the number of planets, the location and mass of the planets, and the presences of the forces other than gravity. He would eventually find a solution to the equations where the dominating error was the presence of another, as of yet undetected, planet. His equations gave the distance from the sun and the mass of the planet correctly, as well as enough detail about the planet's location in the sky that it was found with only an hour of searching. Mercury's orbit's issues would eventually be solved by General Relativity.
https://api.stackexchange.com
There is an obvious difference between finite difference and the finite volume method (moving from point definition of the equations to integral averages over cells). But I find FEM and FVM to be very similar; they both use integral form and average over cells. What is the FEM method doing that the FVM is not? I have read a little background on the FEM I understand that the equations are written in the weak form, this gives the method a slightly different stating point than the FVM. However, I don't understand on a conceptual level what the differences are. Does FEM make some assumption regarding how the unknown varies inside the cell, can't this also be done with FVM? I am mostly coming from 1D perspective so maybe FEM has advantages with more than one dimension? I haven't found much information available on this topic on the net. Wikipedia has a section on how the FEM is different from finite difference method, but that is about it,
Finite Element: volumetric integrals, internal polynomial order Classical finite element methods assume continuous or weakly continuous approximation spaces and ask for volumetric integrals of the weak form to be satisfied. The order of accuracy is increased by raising the approximation order within elements. The methods are not exactly conservative, thus often struggle with stability for discontinuous processes. Finite Volume: surface integrals, fluxes from discontinuous data, reconstruction order Finite volume methods use piecewise constant approximation spaces and ask for integrals against piecewise constant test functions to be satisfied. This yields exact conservation statements. The volume integral is converted to a surface integral and the entire physics is specified in terms of fluxes in those surface integrals. For first-order hyperbolic problems, this is a Riemann solve. Second order/elliptic fluxes are more subtle. Order of accuracy is increased by using neighbors to (conservatively) reconstruct higher order representations of the state inside elements (slope reconstruction/limiting) or by reconstructing fluxes (flux limiting). The reconstruction process is usually nonlinear to control oscillations around discontinuous features of the solution, see total variation diminishing (TVD) and essentially non-oscillatory (ENO/WENO) methods. A nonlinear discretization is necessary to simultaneously obtain both higher than first order accuracy in smooth regions and bounded total variation across discontinuities, see Godunov's theorem. Comments Both FE and FV are easy to define up to second order accuracy on unstructured grids. FE is easier to go beyond second order on unstructured grids. FV handles non-conforming meshes more easily and robustly. Combining FE and FV The methods can be married in multiple ways. Discontinuous Galerkin methods are finite element methods that use discontinuous basis functions, thus acquiring Riemann solvers and more robustness for discontinuous processes (especially hyperbolic). DG methods can be used with nonlinear limiters (usually with some reduction in accuracy), but satisfy a cell-wise entropy inequality without limiting and can thus be used without limiting for some problems where other schemes require limiters. (This is especially useful for adjoint-based optimization since it makes the discrete adjoint more representative of the continuous adjoint equations.) Mixed FE methods for elliptic problems use discontinuous basis functions and after some choices of quadrature, can be reinterpreted as standard finite volume methods, see this answer for more. Reconstruction DG methods (aka. $P_N P_M$ or "Recovery DG") use both FV-like conservative reconstruction and internal order enrichment, and are thus a superset of FV and DG methods.
https://api.stackexchange.com
I just came back from my Number Theory course, and during the lecture there was mention of the Collatz Conjecture. I'm sure that everyone here is familiar with it; it describes an operation on a natural number – $n/2$ if it is even, $3n+1$ if it is odd. The conjecture states that if this operation is repeated, all numbers will eventually wind up at $1$ (or rather, in an infinite loop of $1-4-2-1-4-2-1$). I fired up Python and ran a quick test on this for all numbers up to $5.76 \times 10^{18}$ (using the powers of cloud computing and dynamic programming magic). Which is millions of millions of millions. And all of them eventually ended up at $1$. Surely I am close to testing every natural number? How many natural numbers could there be? Surely not much more than millions of millions of millions. (I kid.) I explained this to my friend, who told me, "Why would numbers suddenly get different at a certain point? Wouldn't they all be expected to behave the same?" To which I said, "No, you are wrong! In fact, I am sure there are many conjectures which have been disproved by counterexamples that are extremely large!" And he said, "It is my conjecture that there are none! (and if any, they are rare)". Please help me, smart math people. Can you provide a counterexample to his conjecture? Perhaps, more convincingly, several? I've only managed to find one! (Polya's conjecture). One, out of the many thousands (I presume) of conjectures. It's also one that is hard to explain the finer points to the layman. Are there any more famous or accessible examples?
Another example: Euler's sum of powers conjecture, a generalization of Fermat's Last Theorem. It states: If the equation $\sum_{i=1}^kx_i^n=z^n$ has a solution in positive integers, then $n \leq k$ (unless $k=1$). Fermat's Last Theorem is the $k=2$ case of this conjecture. A counterexample for $n=5$ was found in 1966: it's $$ 61917364224=27^5+84^5+110^5+133^5=144^5 $$ The smallest counterexample for $n=4$ was found in 1988: $$ 31858749840007945920321 = 95800^4+217519^4+414560^4=422481^4 $$ This example used to be even more useful in the days before FLT was proved, as an answer to the question "Why do we need to prove FLT if it has been verified for thousands of numbers?" :-)
https://api.stackexchange.com
As Wikipedia says: [...] the kinetic energy of a non-rotating object of mass $m$ traveling at a speed $v$ is $\frac{1}{2}mv^2$. Why does this not increase linearly with speed? Why does it take so much more energy to go from $1\ \mathrm{m/s}$ to $2\ \mathrm{m/s}$ than it does to go from $0\ \mathrm{m/s}$ to $1\ \mathrm{m/s}$? My intuition is wrong here, please help it out!
The previous answers all restate the problem as "Work is force dot/times distance". But this is not really satisfying, because you could then ask "Why is work force dot distance?" and the mystery is the same. The only way to answer questions like this is to rely on symmetry principles, since these are more fundamental than the laws of motion. Using Galilean invariance, the symmetry that says that the laws of physics look the same to you on a moving train, you can explain why energy must be proportional to the mass times the velocity squared. First, you need to define kinetic energy. I will define it as follows: the kinetic energy $E(m,v)$ of a ball of clay of mass $m$ moving with velocity $v$ is the amount of calories of heat that it makes when it smacks into a wall. This definition does not make reference to any mechanical quantity, and it can be determined using thermometers. I will show that, assuming Galilean invariance, $E(v)$ must be the square of the velocity. $E(m,v)$, if it is invariant, must be proportional to the mass, because you can smack two clay balls side by side and get twice the heating, so $$ E(m,v) = m E(v)$$ Further, if you smack two identical clay balls of mass $m$ moving with velocity $v$ head-on into each other, both balls stop, by symmetry. The result is that each acts as a wall for the other, and you must get an amount of heating equal to $2m E(v)$. But now look at this in a train which is moving along with one of the balls before the collision. In this frame of reference, the first ball starts out stopped, the second ball hits it at $2v$, and the two-ball stuck system ends up moving with velocity $v$. The kinetic energy of the second ball is $mE(2v)$ at the start, and after the collision, you have $2mE(v)$ kinetic energy stored in the combined ball. But the heating generated by the collision is the same as in the earlier case. So there are now two $2mE(v)$ terms to consider: one representing the heat generated by the collision, which we saw earlier was $2mE(v)$, and the other representing the energy stored in the moving, double-mass ball, which is also $2mE(v)$. Due to conservation of energy, those two terms need to add up to the kinetic energy of the second ball before the collision: $$ mE(2v) = 2mE(v) + 2mE(v)$$ $$ E(2v) = 4 E(v)$$ which implies that $E$ is quadratic. Non-circular force-times-distance Here is the non-circular version of the force-times-distance argument that everyone seems to love so much, but is never done correctly. In order to argue that energy is quadratic in velocity, it is enough to establish two things: Potential energy on the Earth's surface is linear in height Objects falling on the Earth's surface have constant acceleration The result then follows. That the energy in a constant gravitational field is proportional to the height is established by statics. If you believe the law of the lever, an object will be in equilibrium with another object on a lever when the distances are inversely proportional to the masses (there are simple geometric demonstrations of this that require nothing more than the fact that equal mass objects balance at equal center-of-mass distances). Then if you tilt the lever a little bit, the mass-times-height gained by 1 is equal to the mass-times-height gained by the other. This allows you to lift objects and lower them with very little effort, so long as the mass-times-height added over all the objects is constant before and after.This is Archimedes' principle. Another way of saying the same thing uses an elevator, consisting of two platforms connected by a chain through a pulley, so that when one goes up, the other goes down. You can lift an object up, if you lower an equal amount of mass down the same amount. You can lift two objects a certain distance in two steps, if you drop an object twice as far. This establishes that for all reversible motions of the elevator, the ones that do not require you to do any work (in both the colloquial sense and the physics sense--- the two notions coincide here), the mass-times-height summed over all the objects is conserved. The "energy" can now be defined as that quantity of motion which is conserved when these objects are allowed to move with a non-infinitesimal velocity. This is Feynman's version of Archimedes. So the mass-times-height is a measure of the effort required to lift something, and it is a conserved quantity in statics. This quantity should be conserved even if there is dynamics in intermediate stages. By this I mean that if you let two weights drop while suspended on a string, let them do an elastic collision, and catch the two objects when they stop moving again, you did no work. The objects should then go up to the same total mass-times-height. This is the original demonstration of the laws of elastic collisions by Christian Huygens, who argued that if you drop two masses on pendulums, and let them collide, their center of mass has to go up to the same height, if you catch the balls at their maximum point. From this, Huygens generalized the law of conservation of potential energy implicit in Archimedes to derive the law of conservation of square-velocity in elastic collisions. His principle that the center of mass cannot be raised by dynamic collisions is the first statement of conservation of energy. For completeness, the fact that an object accelerates in a constant gravitational field with uniform acceleration is a consequence of Galilean invariance, and the assumption that a gravitational field is frame invariant to uniform motions up and down with a steady velocity. Once you know that motion in constant gravity is constant acceleration, you know that $$ mv^2/2 + mgh = C $$ so that Huygens dynamical quantity which is additively conserved along with Archimedes mass times height is the velocity squared.
https://api.stackexchange.com
I understand that GPUs are generally used to do LOTS of calculations in parallel. I understand why we would want to parallelize processes in order to speed things up. However, GPUs aren't always better than CPUs, as far as I know. What kinds of tasks are GPUs bad at? When would we prefer CPU over GPU for processing?
GPUs are bad at doing one thing at a time. A modern high-end GPU may have several thousand cores, but these are organized into SIMD blocks of 16 or 32. If you want to compute 2+2, you might have 32 cores each compute an addition operation, and then discard 31 of the results. GPUs are bad at doing individual things fast. GPUs only recently topped the one-gigahertz mark, something that CPUs did more than twenty years ago. If your task involves doing many things to one piece of data, rather than one thing to many pieces of data, a CPU is far better. GPUs are bad at dealing with data non-locality. The hardware is optimized for working on contiguous blocks of data. If your task involves picking up individual pieces of data scattered around your data set, the GPU's incredible memory bandwidth is mostly wasted.
https://api.stackexchange.com
Okay, so everyone knows the usual methods of solving integrals, namely u-substitution, integration by parts, partial fractions, trig substitutions, and reduction formulas. But what else is there? Every time I search for "Advanced Techniques of Symbolic Integration" or "Super Advanced Integration Techniques", I get the same results which end up only talking about the methods mentioned above. Are there any super obscure and interesting techniques for solving integrals? As an example of something that might be obscure, the formula for "general integration by parts " for $n$ functions $f_j, \ j = 1,\cdots,n$ is given by $$ \int{f_1'(x)\prod_{j=2}^n{f_j(x)}dx} = \prod_{i=1}^n{f_i(x)} - \sum_{i=2}^n{\int{f_i'(x)\prod_{\substack{j=1 \\ j \neq i}}^n{f_j(x)}dx}} $$ which is not necessarily useful nor difficult to derive, but is interesting nonetheless. So out of curiosity, are there any crazy unknown symbolic integration techniques?
Here are a few. The first one is included because it's not very well known and is not general, though the ones that follow are very general and very useful. A great but not very well known way to find the primitive of $f^{-1}$ in terms of the primitive of $f$, $F$, is (very easy to prove: just differentiate both sides and use the chain rule): $$ \int f^{-1}(x)\, dx = x \cdot f^{-1}(x)-(F \circ f^{-1})(x)+C. $$ Examples: $$ \begin{aligned} \displaystyle \int \arcsin(x)\, dx &= x \cdot \arcsin(x)- (-\cos\circ \arcsin)(x)+C \\ &=x \cdot \arcsin(x)+\sqrt{1-x^2}+C. \end{aligned} $$ $$ \begin{aligned} \int \log(x)\, dx &= x \cdot \log(x)-(\exp \circ \log)(x) + C \\ &= x \cdot \left( \log(x)-1 \right) + C. \end{aligned} $$ This one is more well known, and extremely powerful, it's called differentiating under the integral sign. It requires ingenuity most of the time to know when to apply, and how to apply it, but that only makes it more interesting. The technique uses the simple fact that $$ \frac{\mathrm d}{\mathrm d x} \int_a^b f \left({x, y}\right) \mathrm d y = \int_a^b \frac{\partial f}{\partial x} \left({x, y}\right) \mathrm d y. $$ Example: We want to calculate the integral $\int_{0}^{\infty} \frac{\sin(x)}{x} dx$. To do that, we unintuitively consider the more complicated integral $\int_{0}^{\infty} e^{-tx} \frac{\sin(x)}{x} dx$ instead. Let $$ I(t)=\int_{0}^{\infty} e^{-tx} \frac{\sin(x)}{x} dx,$$ then $$ I'(t)=-\int_{0}^{\infty} e^{-tx} \sin(x) dx=\frac{e^{-t x} (t \sin (x)+\cos (x))}{t^2+1}\bigg|_0^{\infty}=\frac{-1}{1+t^2}.$$ Since both $I(t)$ and $-\arctan(t)$ are primitives of $\frac{-1}{1+t^2}$, they must differ only by a constant, so that $I(t)+\arctan(t)=C$. Let $t\to \infty$, then $I(t) \to 0$ and $-\arctan(t) \to -\pi/2$, and hence $C=\pi/2$, and $I(t)=\frac{\pi}{2}-\arctan(t)$. Finally, $$ \int_{0}^{\infty} \frac{\sin(x)}{x} dx = I(0) = \frac{\pi}{2}-\arctan(0) = \boxed{\frac{\pi}{2}}. $$ This one is probably the most commonly used "advanced integration technique", and for good reasons. It's referred to as the "residue theorem" and it states that if $\gamma$ is a counterclockwise simple closed curve, then $\displaystyle \int_\gamma f(z) dz = 2\pi i \sum_{k=1}^n \operatorname{Res} ( f, a_k )$ . It will be difficult for you to understand this one without knowledge in complex analysis, but you can get the gist of it with the wiki article. Example: We want to compute $\int_{-\infty}^{\infty} \frac{x^2}{1+x^4} dx$. The poles of our function $f(z)=\frac{x^2}{1+x^4}$ in the upper half plane are $a_1=e^{i \frac{\pi}{4}}$ and $a_2=e^{i \frac{3\pi}{4}}$. The residues of our function at those points are $$\operatorname{Res}(f,a_1)=\lim_{z\to a_1} (z-a_1)f(z)=\frac{e^{i \frac{-\pi}{4}}}{4},$$ and $$\operatorname{Res}(f,a_2)=\lim_{z\to a_2} (z-a_2)f(z)=\frac{e^{i \frac{-3\pi}{4}}}{4}.$$ Let $\gamma$ be the closed path around the boundary of the semicircle of radius $R>1$ on the upper half plane, traversed in the counter-clockwise direction. Then the residue theorem gives us ${1 \over 2\pi i} \int_\gamma f(z)\,dz=\operatorname{Res}(f,a_1)+\operatorname{Res}(f,a_2)={1 \over 4}\left({1-i \over \sqrt{2}}+{-1-i \over \sqrt{2}}\right)={-i \over 2 \sqrt{2}}$ and $ \int_\gamma f(z)\,dz= {\pi \over \sqrt{2}}$. Now, by the definition of $\gamma$, we have: $$\int_\gamma f(z)\,dz = \int_{-R}^R \frac{x^2}{1+x^4} dx + \int_0^\pi {i (R e^{it})^3 \over 1+(R e^{it})^4} dz = {\pi \over \sqrt{2}}.$$ For the integral on the semicircle $$ \int_0^\pi {i (R e^{it})^3 \over 1+(R e^{it})^4} dz, $$ we have $$ \begin{aligned} \left| \int_0^\pi {i (R e^{it})^3 \over 1+(R e^{it})^4} dz \right| &\leq \int_0^\pi \left| {i (R e^{it})^3 \over 1+(R e^{it})^4} \right| dz \\ &\leq \int_0^\pi {R^3 \over R^4-1} dz={\pi R^3 \over R^4-1}. \end{aligned} $$ Hence, as $R\to \infty$, we have ${\pi R^3 \over R^4-1} \to 0$, and hence $\int_0^\pi {i (R e^{it})^3 \over 1+(R e^{it})^4} dz \to 0$. Finally, $$ \begin{aligned} \int_{-\infty}^\infty \frac{x^2}{1+x^4} dx &= \lim_{R\to \infty} \int_{-R}^R \frac{x^2}{1+x^4} dx \\ &= \lim_{R\to \infty} {\pi \over \sqrt{2}}-\int_0^\pi {i (R e^{it})^3 \over 1+(R e^{it})^4} dz =\boxed{{\pi \over \sqrt{2}}}. \end{aligned} $$ My final "technique" is the use of the mean value property for complex analytic functions, or Cauchy's integral formula in other words: $$ \begin{aligned} f(a) &= \frac{1}{2\pi i} \int_\gamma \frac{f(z)}{z-a}\, dz \\ &= \frac{1}{2\pi} \int_{0}^{2\pi} f\left(a+e^{ix}\right) dx. \end{aligned} $$ Example: We want to compute the very messy looking integral $\int_0^{2\pi} \cos (\cos (x)+1) \cosh (\sin (x)) dx$. We first notice that $$ \begin{aligned} &\hphantom{=} \cos [\cos (x)+1] \cosh [\sin (x)] \\ &=\Re\left\{ \cos [\cos (x)+1] \cosh [\sin (x)] -i\sin [\cos (x)+1] \sinh [\sin (x)] \right\} \\ &= \Re \left[ \cos \left( 1+e^{i x} \right) \right]. \end{aligned} $$ Then, we have $$ \begin{aligned} \int_0^{2\pi} \cos [\cos (x)+1] \cosh [\sin (x)] dx &= \int_0^{2\pi} \Re \left[ \cos \left( 1+e^{i x} \right) \right] dx \\ &= \Re \left[ \int_0^{2\pi} \cos \left( 1+e^{i x} \right) dx \right] \\ &= \Re \left( \cos(1) \cdot 2 \pi \right)= \boxed{2 \pi \cos(1)}. \end{aligned} $$
https://api.stackexchange.com
When people get sick, they often develop a fever. What is the effect of an increased body temperature on viruses and bacteria in the body? Is it beneficial to the infected body? Importantly, often fever-reducing agents like aspirin are prescribed when people are sick. Doesn't this counteract any benefits of fever?
Fever is a trait observed in warm and cold-blooded vertebrates that has been conserved for hundreds of millions of years (Evans, 2015). Elevated body temperature stimulates the body's immune response against infectious viruses and bacteria. It also makes the body less favorable as a host for replicating viruses and bacteria, which are temperature sensitive (Source: Sci Am). The innate system is stimulated by increasing the recruitment, activation and bacteriolytic activity of neutrophils. Likewise, natural killer cells' cytotoxic activity is enhanced and their recruitment is increased, including that to tumors. Macrophages and dendritic cells increase their activity in clearing up the mess associated with infection. Also the adaptive immune response is enhanced by elevated temperatures. For example, the circulation of T cells to the lymph nodes is increased and their proliferation is stimulated. In fact, taking pain killers that reduce fever have been shown to lead to poorer clearance of pathogens from the body (Evans, 2015). In adults, when body temperature reaches 104 oF (40 oC) it can become dangerous and fever reducing agents like aspirin are recommended (source: eMedicine) Reference - Evans, Nat Rev Immunol (2015); 15(6): 335–49
https://api.stackexchange.com
I have a bag of about 50 non-rechargeable AA batteries (1.5 V) that I have collected over the years. I bought a multimeter recently and would like to know the best way to test these batteries to determine which ones I should keep and which I should toss. Sometimes a battery will be useless for certain high-power devices (e.g. children's toys) but are still perfectly suitable for low-power devices such as TV remote controls. Ideally, I'd like to divide the batteries into several arbitrary categories: As-new condition (suitable for most devices) Suitable for low-powered devices such as remote controls Not worth keeping Should I be measuring voltage, current, power or a combination of several of these? Is there a simple metric I can use to determine what to keep and what to toss?
**WARNING: Lithium Ion cells ** While this question relates to non-rechargeable AA cells it is possible that someone may seek to extend the advice to testing other small cells. In the case Of Li-Ion rechargeable cells (AA, 18650, other) this can be a very bad idea in some cases. Shorting Lithium Ion cells as in test 2 is liable to be a very bad idea indeed. Depending on design, some Li-Ion cells will provide short circuit current of many times the cell mAh rating - eg perhaps 50+ amps for an 18650 cell, and perhaps 10's of amps for an AA size Li-Ion cell. This level of discharge can cause injury and worst case may destroy the cell, in some uncommon cases with substantial release of energy in the form of flame and hot material. AA non-rechargeable cells: 1) Ignore the funny answers Generally speaking, if a battery is more than 1 year old then only Alkaline batteries are worth keeping. Shelf life of non-Alkaline can be some years but they deteriorate badly with time. Modern Alkaline have gotten awesome, as they still retain a majority of charge at 3 to 5 years. Non brand name batteries are often (but not always) junk. Heft battery in hand. Learn to get the feel of what a "real" AA cell weighs. An Eveready or similar Alkaline will be around 30 grams/one ounce. An AA NiMH 2500 mAh will be similar. Anything under 25g is suspect. Under 20g is junk. Under 15g is not unknown. 2) Brutal but works Set multimeter to high current range (10A or 20A usually). Needs both dial setting and probe socket change in most meters. Use two sharpish probes. If battery has any light surface corrosion scratch a clean bright spot with probe tip. If it has more than surface corrosion consider binning it. Some Alkaline cells leak electrolyte over time, which is damaging to gear and annoying (at least) to skin. Press negative probe against battery base. Move slightly to make scratching contact. Press firmly. DO NOT slip so probe jumps off battery and punctures your other hand. Not advised. Ask me how I know. Press positive probe onto top of battery. Hold for maybe 1 second. Perhaps 2. Experience will show what is needed. This is thrashing the battery, decreasing its life and making it sad. Try not to do this often or for very long. Top AA Alkaline cells new will give 5-10 A. (NiMH AA will approach 10A for a good cell). Lightly used AA or ones which have had bursts of heavy use and then recovered will typically give a few amps. Deader again will be 1-3A. Anything under 1 A you probably want to discard unless you have a micropower application. Non Alkaline will usually be lower. I buy ONLY Alkaline primary cells as other "quality" cells are usually not vastly cheaper but are of much lower capacity. Current will fall with time. A very good cell will fall little over 1 to maybe 2 seconds. More used cells will start lower and fall faster. Well used cells may plummet. I place cells in approximate order of current after testing. The top ones can be grouped and wrapped with a rubber band. The excessively keen may mark the current given on the cell with a marker. Absolute current is not the point - it serves as a measure of usefulness. 3) Gentler - but works reasonably well. Set meter to 2V range or next above 2V if no 2V range. Measure battery unloaded voltage. New unused Alkaline are about 1.65V. Most books don't tell you that. Unused but sat on the shelf 1 year + Alkaline will be down slightly. Maybe 1.55 - 1.6V Modestly used cells will be 1.5V+ Used but useful may be 1.3V - 1.5V range After that it's all downhill. A 1V OC cell is dodo dead. A 1.1V -.2V cell will probably load down to 1V if you look at it harshly. Do this a few times and you will get a feel for it. 4) In between. Use a heavyish load and measure voltage. Keep a standard resistor for this. SOLDER the wires on that you use as probes. A twisted connection has too much variability. Resistor should draw a heavy load for battery type used. 100 mA - 500 mA is probably OK. Battery testers usually work this way. 5) Is this worth doing? Yes, it is. As well as returning a few batteries to the fold and making your life more exciting when some fail to perform, it teaches you a new skill that can be helpful in understanding how batteries behave in real life and the possible effect on equipment. The more you know, the more you get to know, and this is one more tool along the path towards knowing everything :-). [The path is rather longer than any can traverse, but learning how to run along it can be fun].
https://api.stackexchange.com
The AIC and BIC are both methods of assessing model fit penalized for the number of estimated parameters. As I understand it, BIC penalizes models more for free parameters than does AIC. Beyond a preference based on the stringency of the criteria, are there any other reasons to prefer AIC over BIC or vice versa?
Your question implies that AIC and BIC try to answer the same question, which is not true. The AIC tries to select the model that most adequately describes an unknown, high dimensional reality. This means that reality is never in the set of candidate models that are being considered. On the contrary, BIC tries to find the TRUE model among the set of candidates. I find it quite odd the assumption that reality is instantiated in one of the models that the researchers built along the way. This is a real issue for BIC. Nevertheless, there are a lot of researchers who say BIC is better than AIC, using model recovery simulations as an argument. These simulations consist of generating data from models A and B, and then fitting both datasets with the two models. Overfitting occurs when the wrong model fits the data better than the generating. The point of these simulations is to see how well AIC and BIC correct these overfits. Usually, the results point to the fact that AIC is too liberal and still frequently prefers a more complex, wrong model over a simpler, true model. At first glance these simulations seem to be really good arguments, but the problem with them is that they are meaningless for AIC. As I said before, AIC does not consider that any of the candidate models being tested is actually true. According to AIC, all models are approximations to reality, and reality should never have a low dimensionality. At least lower than some of the candidate models. My recommendation is to use both AIC and BIC. Most of the times they will agree on the preferred model, when they don't, just report it. If you are unhappy with both AIC and BIC and have free time to invest, look up Minimum Description Length (MDL), a totally different approach that overcomes the limitations of AIC and BIC. There are several measures stemming from MDL, like normalized maximum likelihood or the Fisher Information approximation. The problem with MDL is that its mathematically demanding and/or computationally intensive. Still, if you want to stick to simple solutions, a nice way for assessing model flexibility (especially when the number of parameters are equal, rendering AIC and BIC useless) is doing Parametric Bootstrap, which is quite easy to implement. Here is a link to a paper on it. Some people here advocate for the use of cross-validation. I personally have used it and don't have anything against it, but the issue with it is that the choice among the sample-cutting rule (leave-one-out, K-fold, etc) is an unprincipled one.
https://api.stackexchange.com
TV documentaries invariably show the Big Bang as an exploding ball of fire expanding outwards. Did the Big Bang really explode outwards from a point like this? If not, what did happen?
The simple answer is that no, the Big Bang did not happen at a point. Instead, it happened everywhere in the universe at the same time. Consequences of this include: The universe doesn't have a centre: the Big Bang didn't happen at a point so there is no central point in the universe that it is expanding from. The universe isn't expanding into anything: because the universe isn't expanding like a ball of fire, there is no space outside the universe that it is expanding into. In the next section, I'll sketch out a rough description of how this can be, followed by a more detailed description for the more determined readers. A simplified description of the Big Bang Imagine measuring our current universe by drawing out a grid with a spacing of 1 light year. Although obviously, we can't do this, you can easily imagine putting the Earth at (0, 0), Alpha Centauri at (4.37, 0), and plotting out all the stars on this grid. The key thing is that this grid is infinite$^1$ i.e. there is no point where you can't extend the grid any further. Now wind time back to 7 billion years after the big bang, i.e. about halfway back. Our grid now has a spacing of half a light year, but it's still infinite - there is still no edge to it. The average spacing between objects in the universe has reduced by half and the average density has gone up by a factor of $2^3$. Now wind back to 0.0000000001 seconds after the big bang. There's no special significance to that number; it's just meant to be extremely small. Our grid now has a very small spacing, but it's still infinite. No matter how close we get to the Big Bang we still have an infinite grid filling all of space. You may have heard pop science programs describing the Big Bang as happening everywhere and this is what they mean. The universe didn't shrink down to a point at the Big Bang, it's just that the spacing between any two randomly selected spacetime points shrank down to zero. So at the Big Bang, we have a very odd situation where the spacing between every point in the universe is zero, but the universe is still infinite. The total size of the universe is then $0 \times \infty$, which is undefined. You probably think this doesn't make sense, and actually, most physicists agree with you. The Big Bang is a singularity, and most of us don't think singularities occur in the real universe. We expect that some quantum gravity effect will become important as we approach the Big Bang. However, at the moment we have no working theory of quantum gravity to explain exactly what happens. $^1$ we assume the universe is infinite - more on this in the next section For determined readers only To find out how the universe evolved in the past, and what will happen to it in the future, we have to solve Einstein's equations of general relativity for the whole universe. The solution we get is an object called the metric tensor that describes spacetime for the universe. But Einstein's equations are partial differential equations, and as a result, have a whole family of solutions. To get the solution corresponding to our universe we need to specify some initial conditions. The question is then what initial conditions to use. Well, if we look at the universe around us we note two things: if we average over large scales the universe looks the same in all directions, that is it is isotropic if we average over large scales the universe is the same everywhere, that is it is homogeneous You might reasonably point out that the universe doesn't look very homogeneous since it has galaxies with a high density randomly scattered around in space with a very low density. However, if we average on scales larger than the size of galaxy superclusters we do get a constant average density. Also, if we look back to the time the cosmic microwave background was emitted (380,000 years after the Big Bang and well before galaxies started to form) we find that the universe is homogeneous to about $1$ part in $10^5$, which is pretty homogeneous. So as the initial conditions let's specify that the universe is homogeneous and isotropic, and with these assumptions, Einstein's equation has a (relatively!) simple solution. Indeed this solution was found soon after Einstein formulated general relativity and has been independently discovered by several different people. As a result the solution glories in the name Friedmann–Lemaître–Robertson–Walker metric, though you'll usually see this shortened to FLRW metric or sometimes FRW metric (why Lemaître misses out I'm not sure). Recall the grid I described to measure out the universe in the first section of this answer, and how I described the grid shrinking as we went back in time towards the Big Bang? Well the FLRW metric makes this quantitative. If $(x, y, z)$ is some point on our grid then the current distance to that point is just given by Pythagoras' theorem: $$ d^2 = x^2 + y^2 + z^2 $$ What the FLRW metric tells us is that the distance changes with time according to the equation: $$ d^2(t) = a^2(t)(x^2 + y^2 + z^2) $$ where $a(t)$ is a function called the [scale factor]. We get the function for the scale factor when we solve Einstein's equations. Sadly it doesn't have a simple analytical form, but it's been calculated in answers to the previous questions What was the density of the universe when it was only the size of our solar system? and How does the Hubble parameter change with the age of the universe?. The result is: The value of the scale factor is conventionally taken to be unity at the current time, so if we go back in time and the universe shrinks we have $a(t) < 1$, and conversely in the future as the universe expands we have $a(t) > 1$. The Big bang happens because if we go back to time to $t = 0$ the scale factor $a(0)$ is zero. This gives us the remarkable result that the distance to any point in the universe $(x, y, z)$ is: $$ d^2(t) = 0(x^2 + y^2 + z^2) = 0 $$ so the distance between every point in the universe is zero. The density of matter (the density of radiation behaves differently but let's gloss over that) is given by: $$ \rho(t) = \frac{\rho_0}{a^3(t)} $$ where $\rho_0$ is the density at the current time, so the density at time zero is infinitely large. At the time $t = 0$ the FLRW metric becomes singular. No one I know thinks the universe did become singular at the Big Bang. This isn't a modern opinion: the first person I know to have objected publically was Fred Hoyle, and he suggested Steady State Theory to avoid the singularity. These days it's commonly believed that some quantum gravity effect will prevent the geometry from becoming singular, though since we have no working theory of quantum gravity no one knows how this might work. So to conclude: the Big Bang is the zero time limit of the FLRW metric, and it's a time when the spacing between every point in the universe becomes zero and the density goes to infinity. It should be clear that we can't associate the Big Bang with a single spatial point because the distance between all points was zero so the Big Bang happened at all points in space. This is why it's commonly said that the Big Bang happened everywhere. In the discussion above I've several times casually referred to the universe as infinite, but what I really mean is that it can't have an edge. Remember that our going-in assumption is that the universe is homogeneous i.e. it's the same everywhere. If this is true the universe can't have an edge because points at the edge would be different from points away from the edge. A homogenous universe must either be infinite, or it must be closed i.e. have the spatial topology of a 3-sphere. The recent Planck results show the curvature is zero to within experimental error, so if the universe is closed the scale must be far larger than the observable universe.
https://api.stackexchange.com
I often hear people talking about parallel computing and distributed computing, but I'm under the impression that there is no clear boundary between the 2, and people tend to confuse that pretty easily, while I believe it is very different: Parallel computing is more tightly coupled to multi-threading, or how to make full use of a single CPU. Distributed computing refers to the notion of divide and conquer, executing sub-tasks on different machines and then merging the results. However, since we stepped into the Big Data era, it seems the distinction is indeed melting, and most systems today use a combination of parallel and distributed computing. An example I use in my day-to-day job is Hadoop with the Map/Reduce paradigm, a clearly distributed system with workers executing tasks on different machines, but also taking full advantage of each machine with some parallel computing. I would like to get some advice to understand how exactly to make the distinction in today's world, and if we can still talk about parallel computing or there is no longer a clear distinction. To me it seems distributed computing has grown a lot over the past years, while parallel computing seems to stagnate, which could probably explain why I hear much more talking about distributing computations than parallelizing.
This is partly a matter of terminology, and as such, only requires that you and the person you're talking to clarify it beforehand. However, there are different topics that are more strongly associated with parallelism, concurrency, or distributed systems. Parallelism is generally concerned with accomplishing a particular computation as fast as possible, exploiting multiple processors. The scale of the processors may range from multiple arithmetical units inside a single processor, to multiple processors sharing memory, to distributing the computation on many computers. On the side of models of computation, parallelism is generally about using multiple simultaneous threads of computation internally, in order to compute a final result. Parallelism is also sometimes used for real-time reactive systems, which contain many processors that share a single master clock; such systems are fully deterministic. Concurrency is the study of computations with multiple threads of computation. Concurrency tends to come from the architecture of the software rather than from the architecture of the hardware. Software may be written to use concurrency in order to exploit hardware parallelism, but often the need is inherent in the software's behavior, to react to different asynchronous events (e.g. a computation thread that works independently of a user interface thread, or a program that reacts to hardware interrupts by switching to an interrupt handler thread). Distributed computing studies separate processors connected by communication links. Whereas parallel processing models often (but not always) assume shared memory, distributed systems rely fundamentally on message passing. Distributed systems are inherently concurrent. Like concurrency, distribution is often part of the goal, not solely part of the solution: if resources are in geographically distinct locations, the system is inherently distributed. Systems in which partial failures (of processor nodes or of communication links) are possible fall under this domain.
https://api.stackexchange.com
Searching an array of $N$ elements using binary search takes, in the worst case $\log_2 N$ iterations because, at each step we trim half of our search space. If, instead, we used 'ternary search', we'd cut away two-thirds of our search space at each iteration, so the worst case should take $\log_3 N < \log_2 N$ iterations... It seems that ternary search is faster, so why do we use binary search?
If you apply binary search, you have $$\log_2(n)+O(1)$$ many comparisons. If you apply ternary search, you have $$ 2 \cdot \log_3(n) + O(1)$$ many comparisons, as in each step, you need to perform 2 comparisons to cut the search space into three parts. Now if you do the math, you can observe that: $$ 2 \cdot \log_3(n) + O(1) = 2 \cdot \frac{\log(2)}{\log(3)} \log_2(n)+ O(1) $$ Since we know that $2 \cdot \frac{\log(2)}{\log(3)} > 1$, we actually get more comparisons with ternary search. By the way: $n$-ary search may make a lot of sense in case if comparisons are quite costly and can be parallelized, as then, parallel computers can be applied. Note that argument can be generalized to $n$-ary search quite easily. You just need to show that the function $f(k) = (k-1) \cdot \frac{\log(2)}{\log(k)}$ is strictly monotone increasing for integer values of $k$.
https://api.stackexchange.com
In a galvanic (voltaic) cell, the anode is considered negative and the cathode is considered positive. This seems reasonable as the anode is the source of electrons and cathode is where the electrons flow. However, in an electrolytic cell, the anode is taken to be positive while the cathode is now negative. However, the reaction is still similar, whereby electrons from the anode flow to the positive terminal of the battery, and electrons from the battery flow to the cathode. So why does the sign of the cathode and anode switch when considering an electrolytic cell?
The anode is the electrode where the oxidation reaction \begin{align} \ce{Red -> Ox + e-} \end{align} takes place while the cathode is the electrode where the reduction reaction \begin{align} \ce{Ox + e- -> Red} \end{align} takes place. That's how cathode and anode are defined. Galvanic cell Now, in a galvanic cell the reaction proceeds without an external potential helping it along. Since at the anode you have the oxidation reaction which produces electrons you get a build-up of negative charge in the course of the reaction until electrochemical equilibrium is reached. Thus the anode is negative. At the cathode, on the other hand, you have the reduction reaction which consumes electrons (leaving behind positive (metal) ions at the electrode) and thus leads to a build-up of positive charge in the course of the reaction until electrochemical equilibrium is reached. Thus the cathode is positive. Electrolytic cell In an electrolytic cell, you apply an external potential to enforce the reaction to go in the opposite direction. Now the reasoning is reversed. At the negative electrode where you have produced a high electron potential via an external voltage source electrons are "pushed out" of the electrode, thereby reducing the oxidized species $\ce{Ox}$, because the electron energy level inside the electrode (Fermi Level) is higher than the energy level of the LUMO of $\ce{Ox}$ and the electrons can lower their energy by occupying this orbital - you have very reactive electrons so to speak. So the negative electrode will be the one where the reduction reaction will take place and thus it's the cathode. At the positive electrode where you have produced a low electron potential via an external voltage source electrons are "sucked into" the electrode leaving behind the the reduced species $\ce{Red}$ because the electron energy level inside the electrode (Fermi Level) is lower than the energy level of the HOMO of $\ce{Red}$. So the positive electrode will be the one where the oxidation reaction will take place and thus it's the anode. A tale of electrons and waterfalls Since there is some confusion concerning the principles on which an electrolysis works, I'll try a metaphor to explain it. Electrons flow from a region of high potential to a region of low potential much like water falls down a waterfall or flows down an inclined plane. The reason is the same: water and electrons can lower their energy this way. Now the external voltage source acts like two big rivers connected to waterfalls: one at a high altitude that leads towards a waterfall - that would be the minus pole - and one at a low altitude that leads away from a waterfall - that would be the plus pole. The electrodes would be like the points of the river shortly before or after the waterfalls in this picture: the cathode is like the edge of a waterfall where the water drops down and the anode is like the point where the water drops into. Ok, what happens at the electrolysis reaction? At the cathode, you have the high altitude situation. So the electrons flow to the "edge of their waterfall". They want to "fall down" because behind them the river is pushing towards the edge exerting some kind of "pressure". But where can they fall down to? The other electrode is separated from them by the solution and usually a diaphragm. But there are $\ce{Ox}$ molecules that have empty states that lie energetically below that of the electrode. Those empty states are like small ponds lying at a lower altitude where a little bit of the water from the river can fall into. So every time such an $\ce{Ox}$ molecule comes near the electrode an electron takes the opportunity to jump to it and reduce it to $\ce{Red}$. But that does not mean that the electrode is suddenly missing an electron because the river is replacing the "pushed out" electron immediately. And the voltage source (the source of the river) can't run dry of electrons because it gets its electrons from the power socket. Now the anode: At the anode, you have the low altitude situation. So here the river lies lower than everything else. Now you can imagine the HOMO-states of the $\ce{Red}$ molecules as small barrier lakes lying at a higher altitude than our river. When a $\ce{Red}$ molecule comes close to the electrode it is like someone opening the floodgates of the barrier lake's dam. The electrons flow from the HOMO into the electrode thus creating an $\ce{Ox}$ molecule. But the electrons don't stay in the electrode, so to speak, they are carried away by the river. And since the river is such a vast entity (lots of water) and usually flows into an ocean, the little "water" that is added to it doesn't change the river much. It stays the same, unaltered so that everytime a floodgate gets opened the water from the barrier lake will drop the same distance.
https://api.stackexchange.com
After reading a dataset: dataset <- read.csv("forR.csv") How can I get R to give me the number of cases it contains? Also, will the returned value include of exclude cases omitted with na.omit(dataset)?
dataset will be a data frame. As I don't have forR.csv, I'll make up a small data frame for illustration: set.seed(1) dataset <- data.frame(A = sample(c(NA, 1:100), 1000, rep = TRUE), B = rnorm(1000)) > head(dataset) A B 1 26 0.07730312 2 37 -0.29686864 3 57 -1.18324224 4 91 0.01129269 5 20 0.99160104 6 90 1.59396745 To get the number of cases, count the number of rows using nrow() or NROW(): > nrow(dataset) [1] 1000 > NROW(dataset) [1] 1000 To count the data after omitting the NA, use the same tools, but wrap dataset in na.omit(): > NROW(na.omit(dataset)) [1] 993 The difference between NROW() and NCOL() and their lowercase variants (ncol() and nrow()) is that the lowercase versions will only work for objects that have dimensions (arrays, matrices, data frames). The uppercase versions will work with vectors, which are treated as if they were a 1 column matrix, and are robust if you end up subsetting your data such that R drops an empty dimension. Alternatively, use complete.cases() and sum it (complete.cases() returns a logical vector [TRUE or FALSE] indicating if any observations are NA for any rows. > sum(complete.cases(dataset)) [1] 993
https://api.stackexchange.com
This question is an extension of two discussions that came up recently in the replies to "C++ vs Fortran for HPC". And it is a bit more of a challenge than a question... One of the most often-heard arguments in favor of Fortran is that the compilers are just better. Since most C/Fortran compilers share the same back end, the code generated for semantically equivalent programs in both languages should be identical. One could argue, however, that C/Fortran is more/less easier for the compiler to optimize. So I decided to try a simple test: I got a copy of daxpy.f and daxpy.c and compiled them with gfortran/gcc. Now daxpy.c is just an f2c translation of daxpy.f (automatically generated code, ugly as heck), so I took that code and cleaned it up a bit (meet daxpy_c), which basically meant re-writing the innermost loop as for ( i = 0 ; i < n ; i++ ) dy[i] += da * dx[i]; Finally, I re-wrote it (enter daxpy_cvec) using gcc's vector syntax: #define vector(elcount, type) __attribute__((vector_size((elcount)*sizeof(type)))) type vector(2,double) va = { da , da }, *vx, *vy; vx = (void *)dx; vy = (void *)dy; for ( i = 0 ; i < (n/2 & ~1) ; i += 2 ) { vy[i] += va * vx[i]; vy[i+1] += va * vx[i+1]; } for ( i = n & ~3 ; i < n ; i++ ) dy[i] += da * dx[i]; Note that I use vectors of length 2 (that's all SSE2 allows) and that I process two vectors at a time. This is because on many architectures, we may have more multiplication units than we have vector elements. All codes were compiled using gfortran/gcc version 4.5 with the flags "-O3 -Wall -msse2 -march=native -ffast-math -fomit-frame-pointer -malign-double -fstrict-aliasing". On my laptop (Intel Core i5 CPU, M560, 2.67GHz) I got the following output: pedro@laika:~/work/fvsc$ ./test 1000000 10000 timing 1000000 runs with a vector of length 10000. daxpy_f took 8156.7 ms. daxpy_f2c took 10568.1 ms. daxpy_c took 7912.8 ms. daxpy_cvec took 5670.8 ms. So the original Fortran code takes a bit more than 8.1 seconds, the automatic translation thereof takes 10.5 seconds, the naive C implementation does it in 7.9 and the explicitly vectorized code does it in 5.6, marginally less. That's Fortran being slightly slower than the naive C implementation and 50% slower than the vectorized C implementation. So here's the question: I'm a native C programmer and so I'm quite confident that I did a good job on that code, but the Fortran code was last touched in 1993 and might therefore be a bit out of date. Since I don't feel as comfortable coding in Fortran as others here may, can anyone do a better job, i.e. more competitive compared to any of the two C versions? Also, can anybody try this test with icc/ifort? The vector syntax probably won't work, but I would be curious to see how the naive C version behaves there. Same goes for anybody with xlc/xlf lying around. I've uploaded the sources and a Makefile here. To get accurate timings, set CPU_TPS in test.c to the number of Hz on your CPU. If you find any improvements to any of the versions, please do post them here! Update: I've added stali's test code to the files online and supplemented it with a C version. I modified the programs to do 1'000'000 loops on vectors of length 10'000 to be consistent with the previous test (and because my machine couldn't allocate vectors of length 1'000'000'000, as in stali's original code). Since the numbers are now a bit smaller, I used the option -par-threshold:50 to make the compiler more likely to parallelize. The icc/ifort version used is 12.1.2 20111128 and the results are as follows pedro@laika:~/work/fvsc$ OMP_NUM_THREADS=1 time ./icctest_c 3.27user 0.00system 0:03.27elapsed 99%CPU pedro@laika:~/work/fvsc$ OMP_NUM_THREADS=1 time ./icctest_f 3.29user 0.00system 0:03.29elapsed 99%CPU pedro@laika:~/work/fvsc$ OMP_NUM_THREADS=2 time ./icctest_c 4.89user 0.00system 0:02.60elapsed 188%CPU pedro@laika:~/work/fvsc$ OMP_NUM_THREADS=2 time ./icctest_f 4.91user 0.00system 0:02.60elapsed 188%CPU In summary, the results are, for all practical purposes, identical for both the C and Fortran versions, and both codes parallelize automagically. Note that the fast times compared to the previous test are due to the use of single-precision floating point arithmetic! Update: Although I don't really like where the burden of proof is going here, I've re-coded stali's matrix multiplication example in C and added it to the files on the web. Here are the results of the tripple loop for one and two CPUs: pedro@laika:~/work/fvsc$ OMP_NUM_THREADS=1 time ./mm_test_f 2500 triple do time 3.46421700000000 3.63user 0.06system 0:03.70elapsed 99%CPU pedro@laika:~/work/fvsc$ OMP_NUM_THREADS=1 time ./mm_test_c 2500 triple do time 3.431997791385768 3.58user 0.10system 0:03.69elapsed 99%CPU pedro@laika:~/work/fvsc$ OMP_NUM_THREADS=2 time ./mm_test_f 2500 triple do time 5.09631900000000 5.26user 0.06system 0:02.81elapsed 189%CPU pedro@laika:~/work/fvsc$ OMP_NUM_THREADS=2 time ./mm_test_c 2500 triple do time 2.298916975280899 4.78user 0.08system 0:02.62elapsed 184%CPU Note that cpu_time in Fortran measuers the CPU time and not the wall-clock time, so I wrapped the calls in time to compare them for 2 CPUs. There is no real difference between the results, except that the C version does a bit better on two cores. Now for the matmul command, of course only in Fortran as this intrinsic is not available in C: pedro@laika:~/work/fvsc$ OMP_NUM_THREADS=1 time ./mm_test_f 2500 matmul time 23.6494780000000 23.80user 0.08system 0:23.91elapsed 99%CPU pedro@laika:~/work/fvsc$ OMP_NUM_THREADS=2 time ./mm_test_f 2500 matmul time 26.6176640000000 26.75user 0.10system 0:13.62elapsed 197%CPU Wow. That's absolutely terrible. Can anyone either find out what I'm doing wrong, or explain why this intrinsic is still somehow a good thing? I didn't add the dgemm calls to the benchmark as they are library calls to the same function in the Intel MKL. For future tests, can anyone suggest an example known to be slower in C than in Fortran? Update To verify stali's claim that the matmul intrinsic is "an order of magnitue" faster than the explicit matrix product on smaller matrices, I modified his own code to multiply matrices of size 100x100 using both methods, 10'000 times each. The results, on one and two CPUs, are as follows: pedro@laika:~/work/fvsc$ OMP_NUM_THREADS=1 time ./mm_test_f 10000 100 matmul time 3.61222500000000 triple do time 3.54022200000000 7.15user 0.00system 0:07.16elapsed 99%CPU pedro@laika:~/work/fvsc$ OMP_NUM_THREADS=2 time ./mm_test_f 10000 100 matmul time 4.54428400000000 triple do time 4.31626900000000 8.86user 0.00system 0:04.60elapsed 192%CPU Update Grisu is correct in pointing out that, without optimizations, gcc converts operations on complex numbers to library function calls while gfortran inlines them in a few instructions. The C compiler will generate the same, compact code if the option -fcx-limited-range is set, i.e. the compiler is instructed to ignore potential over/under-flows in the intermediate values. This option is somehow set by default in gfortran and may lead to incorrect results. Forcing -fno-cx-limited-range in gfortran didn't change anything. So this is actually an argument against using gfortran for numerical calculations: Operations on complex values may over/under-flow even if the correct results are within the floating-point range. This is actually a Fortran standard. In gcc, or in C99 in general, the default is to do things strictly (read IEEE-754 compliant) unless otherwise specified. Reminder: Please keep in mind that the main question was whether Fortran compilers produce better code than C compilers. This is not the place for discussions as to the general merits of one language over another. What I would be really interested in is if anybody can find a way of coaxing gfortran to produce a daxpy as efficient as the one in C using explicit vectorization as this exemplifies the problems of having to rely on the compiler exclusively for SIMD optimization, or a case in which a Fortran compiler out-does its C counterpart.
The difference in your timings seems to be due to the manual unrolling of the unit-stride Fortran daxpy. The following timings are on a 2.67 GHz Xeon X5650, using the command ./test 1000000 10000 Intel 11.1 compilers Fortran with manual unrolling: 8.7 sec Fortran w/o manual unrolling: 5.8 sec C w/o manual unrolling: 5.8 sec GNU 4.1.2 compilers Fortran with manual unrolling: 8.3 sec Fortran w/o manual unrolling: 13.5 sec C w/o manual unrolling: 13.6 sec C with vector attributes: 5.8 sec GNU 4.4.5 compilers Fortran with manual unrolling: 8.1 sec Fortran w/o manual unrolling: 7.4 sec C w/o manual unrolling: 8.5 sec C with vector atrributes: 5.8 sec Conclusions Manual unrolling helped the GNU 4.1.2 Fortran compilers on this architecture, but hurts the newer version (4.4.5) and the Intel Fortran compiler. The GNU 4.4.5 C compiler is much more competitive with Fortran than for version 4.2.1. Vector intrinsics allow the GCC performance to match the Intel compilers. Time to test more complicated routines like dgemv and dgemm?
https://api.stackexchange.com
Here is a question for image processing experts. I am working on a difficult computer vision problem. The task is to count the stomata (marked below) in DIC microscopy images. These images are resistant to most superficial image processing techniques like morphological operations and edge detection. It is also different from other cell counting tasks. I am using OpenCV. My plan is to review potentially useful features for stomata discrimination. Texture classifiers DCT (Discrete cosine transform/frequency-domain analysis) LBP (Local binary patterns) HOG (Histogram of oriented gradients) Robust feature detectors (I am skeptical) Harris corners SIFT, SURF, STAR, etc. Haar cascade classifier/Viola-Jones features And possibly design a novel feature descriptor. I am leaving out the selection of a classifier for now. What have I missed? How would you solve this? Solutions for similar object detection problems would be very helpful. Sample images here. After bandpass filter: Canny edge detection is not promising. Some image areas are out of focus:
Sorry I don't know OpenCV, and this is more a pre-processing step than a complete answer: First, you don't want an edge detector. An edge detector converts transitions (like this dark-to-light): into ridges (bright lines on dark) like this: It performs a differentiation, in other words. But in your images, there is a light shining down from one direction, which shows us the relief of the 3D surface. We perceive this as lines and edges, because we're used to seeing things in 3D, but they aren't really, which is why edge detectors aren't working, and template matching won't work easily with rotated images (a perfect match at 0 degrees rotation would actually cancel out completely at 180 degrees, because light and dark would line up with each other). If the height of one of these mazy lines looks like this from the side: then the brightness function when illuminated from one side will look like this: This is what you see in your images. The facing surface becomes brighter and the trailing surface becomes darker. So you don't want to differentiate. You need to integrate the image along the direction of illumination, and it will give you the original height map of the surface (approximately). Then it will be easier to match things, whether through Hough transform or template matching or whatever. I'm not sure how to automate finding the direction of illumination. If it's the same for all your images, great. Otherwise you'd have to find the biggest contrast line and assume the light is perpendicular to it or something. For my example, I rotated the image manually to what I thought was the right direction, with light coming from the left: You also need to remove all the low-frequency changes in the image, though, to highlight only the quickly-changing line-like features. To avoid ringing artifacts, I used 2D Gaussian blur and then subtracted that from the original: The integration (cumulative sum) can runaway easily, which produces horizontal streaks. I removed these with another Gaussian high-pass, but only in the horizontal direction this time: Now the stomata are white ellipses all the way around, instead of white in some places and black in others. Original: Integrated: from pylab import * import Image from scipy.ndimage import gaussian_filter, gaussian_filter1d filename = 'rotated_sample.jpg' I = Image.open(filename).convert('L') I = asarray(I) # Remove DC offset I = I - average(I) close('all') figure() imshow(I) gray() show() title('Original') # Remove slowly-varying features sigma_2d = 2 I = I - gaussian_filter(I, sigma_2d) figure() imshow(I) title('2D filtered with %s' % sigma_2d) # Integrate summed = cumsum(I, 1) # Remove slowly-changing streaks in horizontal direction sigma_1d = 5 output = summed - gaussian_filter1d(summed, sigma_1d, axis=1) figure() imshow(output) title('1D filtered with %s' % sigma_1d) The Hough transform can be used to detect ridge ellipses like this, made of "edge pixels", though it's really expensive in computation and memory, and they are not perfect ellipses so it would have to be a bit of a "sloppy" detector. I've never done it, but there are a lot of Google results for "hough ellipse detection". I'd say if you detect one ellipse inside the other, within a certain size search space, it should be counted as a stoma. Also see: OpenCV: How to detect a ellipse in the binary image Python and OpenCV. How do I detect all (filled)circles/round objects in an image? Detection of coins (and fit ellipses) on an image
https://api.stackexchange.com
I am a bit confused. What is the difference between a linear and affine function? Any suggestions will be appreciated.
A linear function fixes the origin, whereas an affine function need not do so. An affine function is the composition of a linear function with a translation, so while the linear part fixes the origin, the translation can map it somewhere else. Linear functions between vector spaces preserve the vector space structure (so in particular they must fix the origin). While affine functions don't preserve the origin, they do preserve some of the other geometry of the space, such as the collection of straight lines. If you choose bases for vector spaces $V$ and $W$ of dimensions $m$ and $n$ respectively, and consider functions $f\colon V\to W$, then $f$ is linear if $f(v)=Av$ for some $n\times m$ matrix $A$ and $f$ is affine if $f(v)=Av+b$ for some matrix $A$ and vector $b$, where coordinate representations are used with respect to the bases chosen.
https://api.stackexchange.com
Many times, when I've inherited or encountered scientific code written by other people (or occasionally, even my own work), I've noticed that documentation is either sparse or nonexistent. If I'm lucky, I see informative comments. If I'm very lucky, there's even Doxygen comments and a Doxyfile so that I have function interfaces and some formatted HTML to consult. If I'm extremely lucky, there's a PDF manual and examples in addition to the Doxygen and source file comments, and I'm ecstatic, because it makes my life much, much easier. What information and tools are useful in documenting source code? For that matter, what information and tools are useful to document the data and results that accompany that source code, in the case of scientific software?
I think that documentation for scientific software can be divided into three categories, all of which are necessary for full understanding. The easiest and most common is individual method documentation. There are many systems for this. You mention doxygen, Python has pydoc, and in PETSc we have our own package sowing which generates the following. However, for any piece of software which goes beyond a simple utility, you need a manual. This provides a high-level view of the purpose of the package, and how its different functionalities integrate to achieve this purpose. It helps a new user structure their code, often through the use of examples. In PETSc, we just use LaTeX for the manual, but the PyClaw package uses the Sphinx framework which I am very impressed with. One thing that we have implemented in the sowing package that I find very useful is the link between example code and function documentation. For example, this example solves the Bratu equation. Notice how you can follow the links for any custom type or function call and get to the low-level documentation, and how those pages link back to examples using them. This is how I learn about new functionality which other people in the project contribute. A frequently overlooked part of documentation, I think, is developer documentation. It is not uncommon to publish a coding-style document, and instructions for interacting with the repository. However, it is very rare to explain the design decisions made before implementation. These decisions always involve tradeoffs, and the situation with respect to hardware and algorithms will necessarily change over time. Without a discussion of the tradeoffs reviewed and rationale for particular design decisions, later programmers are left to recreate the entire process on their own. I think this is a major impediment to successful maintenance and improvement of old codes when the original developers are no longer in charge.
https://api.stackexchange.com
There have been various explanations posited for the α-effect. The α-effect refers to a phenomenon wherein nucleophiles with lone pairs on atoms adjacent (i.e., in the α- position) to the atom bearing the reacting lone pair sometimes exhibit dramatically higher reactivity than similar nucleophiles without α-electrons. This effect is especially adduced when no associated increase in Brønsted basicity occurs. For example, hydroperoxide ($\ce{HOO-}$) experimental reaction rate constants are orders of magnitude greater[1] those of hydroxide ($\ce{HO-}$) with various electrophilic substrates, despite the former exhibiting lower Brønsted basicity. There is also a thermodynamic α-effect, in which equilibrium constants are enhanced[2]. It is currently on the list of unsolved problems in chemistry on Wikipedia, but, due to a lack of references to that effect, I'm not entirely convinced it really should be listed there. Here's the summary of my research on the topic thus far: I read Ren, Y. & Yamataka, H.[3], "The alpha-effect in gas-phase SN2 reactions revisited". In it, they claim that explanations based on ground-state destabilization (presumably due to repulsion between the electrons of the nucleophilic atom and the α-electrons) are not correct. Their reasoning is that this would result in a difference in the $\Delta G$ between reactants and products, leading to thermodynamic equilibrium effects. They argue that a correct explanation should be one exclusively involving stabilization of the transition state (i.e., minimization of $\Delta G^{\ddagger}$), and go on to offer some explanation for how this may occur (along with experimental data). Intuitively, their conclusion seems reasonable to me, and it also (at least to my naive comprehension) seems eminently testable. I don't know whether equilibrium effects consistent with ground-state destabilization have actually been observed or not; however, if they haven't, shouldn't that put the nail in the coffin of that theory? Or is it simply that the authors are searching for a purely kinetic α-effect, so that a distinction between a thermodynamic one needs to be made? Fleming devotes a section to the effect in his book, Molecular Orbitals and Organic Chemical Reactions. He notes that the presence of the α-lone pair should raise the energy of the HOMO of the nucleophile, but also points that experimental results don't correlate sufficiently well with the HOMO energies of various α-nucleophiles. In particular, certain soft electrophiles (per HSAB theory), such as alkyl halides, apparently show an anomalous low preference for α-nucleophiles. In the context of SET mechanisms, Fleming says that the higher energy of the HOMO and the availability of α-electrons (which can stabilize a radical intermediate) ought to have a highly favorable effect on the rate of reaction, and notes that experimental results have borne this out. My interpretation of this is that, while the picture is perhaps murky for anionic mechanisms, transition-state stabilization clearly seems to be operative in SET mechanisms. I've also read the original 1962 paper by Pearson and Edwards[4], which also largely argued for transition-state stabilization as the primary explanatory mechanism. Overall, from my reading thus far, it seems that transition-state stabilization has been most consistently invoked and has the largest wealth of evidence and the most plausible arguments supporting it. What I'd like to ask is, (a) are there flaws in my reasoning or understanding of the material, and (b) is this truly a fundamentally unsolved problem, or is there actually some emerging consensus among experts? Notes and References Fleming provides a small table with relative rates ($k_\mathrm{rel} = k_{\ce{HOO-}}/k_{\ce{HO-}}$) in his book. For example, he gives $k_\mathrm{rel} \approx 10^5$ for reaction with $\ce{PhCN}$ and $k_\mathrm{rel} \approx 50$ for $\ce{PhCH2Br}$, while $k_\mathrm{rel} \approx 10^{-4}$ for reaction with $\ce{H3O+}$. The rate of reaction correlates in the expected way with Brønsted basicity only in the case of proton transfer. Again, citing Fleming, he gives the example of the reaction of N-acetylimidazole with hydroxylamines, in which both rate and equilibrium constants are positively affected. Qualitatively, he explains this by noting that the α-electrons raise the energy of the lone pair conjugated to the π-system, making overlap of said lone pair with the π* LUMO more effective. Additionally, he claims both ground-state stabilization and transition-state destabilization as being factors in the reduced electrophilicity of oximes and hydrazones relative to (most) other standard imines. Ren, Y.; Yamataka, H. The α-Effect in Gas-Phase SN2 Reactions Revisited. Org. Lett. 2006, 8 (1), 119–121. DOI: 10.1021/ol0526930. Edwards, J. O.; Pearson, R. G. The Factors Determining Nucleophilic Reactivities. J. Am. Chem. Soc. 1962, 84 (1), 16–24. DOI: 10.1021/ja00860a005.
I am not a kineticist, and my quantum chemistry is long, long out of date, but what I was about to say was that I'd guess the reason the "effect" is "unsolved" is that it's not real. That is, it is not a property of a single reactant while disregarding its environment (gas phase, solvent interactions). Then I saw that the two recent articles both were about solvation, so my comment is redundant (and certainly only a partially/inadequately educated guess). I'd also comment that comparing $\ce{HO-}$ with $\ce{HOO-}$ is apples and oranges. You should compare it with a species with an alpha atom which is electronegative but doesn't have a lone pair. If it doesn't really have a published DFT model, then it might be good for an MS student to work on. I suspect answering it is like "curing cancer", it doesn't have just one 'reason', rather the cures depend on the exact nature of the reaction (including solvation).
https://api.stackexchange.com
I recently purchased a Weller WES51 soldering iron as my first temperature controlled iron and I'm looking for recommendations on the best default temperature to use when soldering. I'm using mainly .031 inch 60/40 solder on through-hole components.
What’s the proper soldering iron temperature for standard .031" 60/40 solder? There is no proper soldering iron temperature just for a given type of solder - the iron temperature should be set for both the component and the solder. When soldering surface mount components, a small tip and 600F (315C) should be sufficient to quickly solder the joint well without overheating the component. When soldering through hole components, 700F (370C) is useful to pump more heat into the wire and plated hole to solder it quickly. A negative capacitor lead to a heatsinking solid pour ground plane is going to need a big fat tip at a much higher temperature. However, I don't micromanage my soldering temperature, and simply keep mine at 700F (370C). I'll change the tips according to what I'm soldering, and the tip size really ends up determining how much heat gets into the joint in a given period of contact. I think you'll find that very few soldering jobs will really require you to change your tip temperature. Keep in mind that the ideal situation is that the soldering iron heats up the joint enough that the joint melts the solder - not the iron. So the iron is expected to be hotter than the melting point of the solder so that the entire joint comes up to the melting point of the solder quickly. The more quickly you bring the joint temperature up and solder it, the less time the soldering iron is on the joint, and thus the less heat gets transferred to the component. It's not a big deal for many passive or small components, but it turns out that overall a higher tip temperature results in faster soldering and less likely damage to the component being soldered. So if you do use higher tip temperatures, don't leave them on components any longer than necessary. Apply the iron, apply the solder, and remove both - it should take just a second or maybe two for surface mount, and 1-3 seconds for a through hole part. Please note that I'm talking about prototyping, hobbyist, and one-off projects. If you are planning on doing final assembly with the iron, repair work for critical projects, etc, then you'll need to consider what you're doing more carefully than this general rule of thumb.
https://api.stackexchange.com
I know how to downsample a BAM file to lower coverage. I know I can randomly select lines in SAM, but this procedure can't guarantee two reads in a pair are always sampled the same time. Is there a way to downsample BAM while keeping pairing information intact?
samtools has a subsampling option: -s FLOAT: Integer part is used to seed the random number generator [0]. Part after the decimal point sets the fraction of templates/pairs to subsample [no subsampling] samtools view -bs 42.1 in.bam > subsampled.bam will subsample 10 percent mapped reads with 42 as the seed for the random number generator.
https://api.stackexchange.com
I have become a bit confused about these topics. They've all started looking the same to me. They seem to have the same properties such as linearity, shifting and scaling associated with them. I can't seem to put them separately and identify the purpose of each transform. Also, which one of these is used for frequency analysis? I couldn't find (with Google) a complete answer that addresses this specific issue. I wish to see them compared on the same page so that I can have some clarity.
The Laplace and Fourier transforms are continuous (integral) transforms of continuous functions. The Laplace transform maps a function \$f(t)\$ to a function \$F(s)\$ of the complex variable s, where \$s = \sigma + j\omega\$. Since the derivative \$\dot f(t) = \frac{df(t)}{dt} \$ maps to \$sF(s)\$, the Laplace transform of a linear differential equation is an algebraic equation. Thus, the Laplace transform is useful for, among other things, solving linear differential equations. If we set the real part of the complex variable s to zero, \$ \sigma = 0\$, the result is the Fourier transform \$F(j\omega)\$ which is essentially the frequency domain representation of \$f(t)\$ (note that this is true only if for that value of \$ \sigma\$ the formula to obtain the Laplace transform of \$f(t)\$ exists, i.e., it does not go to infinity). The Z transform is essentially a discrete version of the Laplace transform and, thus, can be useful in solving difference equations, the discrete version of differential equations. The Z transform maps a sequence \$f[n]\$ to a continuous function \$F(z)\$ of the complex variable \$z = re^{j\Omega}\$. If we set the magnitude of z to unity, \$r = 1\$, the result is the Discrete Time Fourier Transform (DTFT) \$ F(j\Omega)\$ which is essentially the frequency domain representation of \$f[n]\$.
https://api.stackexchange.com
Well, we've got favourite statistics quotes. What about statistics jokes?
A guy is flying in a hot air balloon and he's lost. So he lowers himself over a field and shouts to a guy on the ground: "Can you tell me where I am, and which way I'm headed?" "Sure! You're at 43 degrees, 12 minutes, 21.2 seconds north; 123 degrees, 8 minutes, 12.8 seconds west. You're at 212 meters above sea level. Right now, you're hovering, but on your way in here you were at a speed of 1.83 meters per second at 1.929 radians" "Thanks! By the way, are you a statistician?" "I am! But how did you know?" "Everything you've told me is completely accurate; you gave me more detail than I needed, and you told me in such a way that it's no use to me at all!" "Dang! By the way, are you a principal investigator?" "Geeze! How'd you know that????" "You don't know where you are, you don't know where you're going. You got where you are by blowing hot air, you start asking questions after you get into trouble, and you're in exactly the same spot you were a few minutes ago, but now, somehow, it's my fault!
https://api.stackexchange.com
Most books refer to a steep rise in pH when a titration reaches the equivalence point. However, I do not understand why … I mean I am adding the same drops of acid to the alkali but just as I near the correct volume (i.e. the volume required to neutralize the alkali), the pH just suddenly increases quickly.
I've decided to tackle this question in a somewhat different manner. Instead of giving the chemical intuition behind it, I wanted to check for myself if the mathematics actually work out. As far as I understand, this isn't done often, so that's why I wanted to try it, even though it may not make the clearest answer. It turns out to be a bit complicated, and I haven't done much math in a while, so I'm kinda rusty. Hopefully, everything is correct. I would love to have someone check my results. My approach here is to explicitly find the equation of a general titration curve and figure out from that why the pH varies quickly near the equivalence point. For simplicity, I shall consider the titration to be between a monoprotic acid and base. Explicitly, we have the following equilibria in solution $$\ce{HA <=> H^+ + A^-} \ \ \ → \ \ \ K_\text{a} = \ce{\frac{[H^+][A^-]}{[HA]}}$$ $$\ce{BOH <=> B^+ + OH^-} \ \ \ → \ \ \ K_\text{b} = \ce{\frac{[OH^-][B^+]}{[BOH]}}$$ $$\ce{H2O <=> H^+ + OH^-} \ \ \ → \ \ \ K_\text{w} = \ce{[H^+][OH^-]}$$ Let us imagine adding two solutions, one of the acid $\ce{HA}$ with volume $V_\text{A}$ and concentration $C_\text{A}$, and another of the base $\ce{BOH}$ with volume $V_\text{B}$ and concentration $C_\text{B}$. Notice that after mixing the solutions, the number of moles of species containing $\ce{A}$ ($\ce{HA}$ or $\ce{A^-}$) is simply $n_\text{A} = C_\text{A} V_\text{A}$, while the number of moles of species containing $\ce{B}$ ($\ce{BOH}$ or $\ce{B^+}$) is $n_\text{B} = C_\text{B} V_\text{B}$. Notice that at the equivalence point, $n_\text{A} = n_\text{B}$ and therefore $C_\text{A} V_\text{A} = C_\text{B} V_\text{B}$; this will be important later. We will assume that volumes are additive (total volume $V_\text{T} = V_\text{A} + V_\text{B}$), which is close to true for relatively dilute solutions. In search of an equation To solve the problem of finding the final equilibrium after adding the solutions, we write out the charge balance and matter balance equations: Charge balance: $\ce{[H^+] + [B^+] = [A^-] + [OH^-]}$ Matter balance for $\ce{A}$: $\displaystyle \ce{[HA] + [A^-]} = \frac{C_\text{A} V_\text{A}}{V_\text{A} + V_\text{B}}$ Matter balance for $\ce{B}$: $\displaystyle \ce{[BOH] + [B^+]} = \frac{C_\text{B} V_\text{B}} {V_\text{A} + V_\text{B}}$ A titration curve is given by the pH on the $y$-axis and the volume of added acid/base on the $x$-axis. So what we need is to find an equation where the only variables are $\ce{[H^+]}$ and $V_\text{A}$ or $V_\text{B}$. By manipulating the dissociation constant equations and the mass balance equations, we can find the following: $$\ce{[HA]} = \frac{\ce{[H^+][A^-]}}{K_\text{a}}$$ $$\ce{[BOH]} = \frac{\ce{[B^+]}K_\text{w}}{K_\text{b}\ce{[H^+]}}$$ $$\ce{[A^-]} = \frac{C_\text{A} V_\text{A}}{V_\text{A} + V_\text{B}} \left(\frac{K_\text{a}}{K_\text{a} + \ce{[H^+]}}\right)$$ $$\ce{[B^+]} = \frac{C_\text{B} V_\text{B}}{V_\text{A} + V_\text{B}} \left(\frac{K_\text{b}\ce{[H^+]}}{K_\text{b}\ce{[H^+]} + K_\text{w}}\right)$$ Replacing those identities in the charge balance equation, after a decent bit of algebra, yields: $$\ce{[H^+]^4} + \left(K_\text{a} + \frac{K_\text{w}}{K_\text{b}} + \frac{C_\text{B} V_\text{B}}{V_\text{A} + V_\text{B}}\right) \ce{[H^+]^3} + \left(\frac{K_\text{a}}{K_\text{b}}K_\text{w} + \frac{C_\text{B} V_\text{B}}{V_\text{A} + V_\text{B}} K_\text{a} - \frac{C_\text{A} V_\text{A}}{V_\text{A} + V_\text{B}}K_\text{a} - K_\text{w}\right) \ce{[H^+]^2} - \left(K_\text{a} K_\text{w} + \frac{C_\text{A} V_\text{A}}{V_\text{A} + V_\text{B}}\frac{K_\text{a}}{K_\text{b}} K_\text{w} + \frac{K^2_\text{w}}{K_\text{b}}\right) \ce{[H^+]} - \frac{K_\text{a}}{K_\text{b}} K^2_\text{w} = 0$$ Now, this equation sure looks intimidating, but it is very interesting. For one, this single equation will exactly solve any equilibrium problem involving the mixture of any monoprotic acid and any monoprotic base, in any concentration (as long as they're not much higher than about $1~\mathrm{\small M}$) and any volume. Though it doesn't seem to be possible to separate the variables $\ce{[H^+]}$ and $V_\text{A}$ or $V_\text{B}$, the graph of this equation represents any titration curve (as long as it obeys the previous considerations). Though in its full form it is quite daunting, we can obtain some simpler versions. For example, consider that the mixture is of a weak acid and a strong base. This means that $K_\text{b} \gg 1$, and so every term containing $K_\text{b}$ in the denominator is approximately zero and gets cancelled out. The equation then becomes: Weak acid and strong base: $$\ce{[H^+]^3} + \left(K_\text{a} + \frac{C_\text{B} V_\text{B}}{V_\text{A} + V_\text{B}}\right) \ce{[H^+]^2} + \left(\frac{C_\text{B} V_\text{B}}{V_\ce{A} + V_\ce{B}} K_\ce{a} - \frac{C_\ce{A} V_\ce{A}}{V_\ce{A} + V_\ce{B}}K_\ce{a} - K_\ce{w}\right) \ce{[H^+]} - K_\ce{a} K_\ce{w} = 0$$ For a strong acid and weak base ($K_\text{a} \gg 1$), you can divide both sides of the equation by $K_\text{a}$, and now all terms with $K_\text{a}$ in the denominator get cancelled out, leaving: Strong acid and weak base: $$\ce{[H^+]^3} + \left(\frac{K_\ce{w}}{K_\ce{b}}+\frac{C_\ce{B}V_\ce{B}}{V_\ce{A} + V_\ce{B}} - \frac{C_\ce{A} V_\ce{A}}{V_\ce{A} + V_\ce{B}}\right) \ce{[H^+]^2} - \left(K_\ce{w} + \frac{C_\text{A} V_\ce{A}}{V_\ce{A} + V_\ce{B}} \frac{K_\ce{w}}{K_\ce{b}}\right) \ce{[H^+]} - \frac{K^2_\ce{w}}{K_\ce{b}} = 0$$ The simplest case happens when adding a strong acid to a strong base ($K_\ce{a} \gg 1$ and $K_\ce{b} \gg 1$), in which case all terms containing either in the denominator get cancelled out. The result is simply: Strong acid and strong base: $$\ce{[H^+]^2} + \left(\frac{C_\text{B} V_\text{B}}{V_\text{A} + V_\text{B}} - \frac{C_\text{A} V_\text{A}}{V_\text{A} + V_\text{B}}\right) \ce{[H^+]} - K_\ce{w} = 0$$ It would be enlightening to draw some example graphs for each equation, but Wolfram Alpha only seems to be able to handle the last one, as the others require more than the standard computation time to display. Still, considering the titration of $1~\text{L}$ of a $1~\ce{\small M}$ solution of a strong acid with a $1~\ce{\small M}$ solution of a strong base, you get this graph. The $x$-axis is the volume of base added, in litres, while the $y$-axis is the pH. Notice that the graph is exactly as what you'll find in a textbook! Now what? With the equations figured out, let's study how they work. We want to know why the pH changes quickly near the equivalence point, so a good idea is to analyze the derivative of the equation and figure out where they have a very positive or very negative value, indicating a region where $\ce{[H^+]}$ changes quickly with a slight addition of an acid/base. Suppose we want to study the titration of an acid with a base. What we need then is the derivative $\displaystyle \frac{\ce{d[H^+]}}{\ce{d}V_\ce{B}}$. We will obtain this by implicit differentiation of both sides of the equations by $\displaystyle \frac{\ce{d}}{\ce{d}V_\ce{B}}$. Starting with the easiest case, the mixture of a strong acid and strong base, we obtain: $$\frac{\ce{d[H^+]}}{\ce{d} V_\ce{B}}= \frac{K_\ce{w} - C_\ce{B} \ce{[H^+] - [H^+]^2}}{2(V_\ce{A} + V_\ce{B}\left) \ce{[H^+]} + (C_\ce{B} V_\ce{B} - C_\ce{A} V_\ce{A}\right)}$$ Once again a complicated looking fraction, but with very interesting properties. The numerator is not too important, it's the denominator where the magic happens. Notice that we have a sum of two terms ($2(V_\ce{A} + V_\ce{B})\ce{[H^+]}$ and $(C_\ce{B} V_\ce{B} - C_\ce{A} V_\ce{A})$). The lower this sum is, the higher $\displaystyle \frac{\mathrm{d}\ce{[H^+]}}{\mathrm{d} V_\ce{B}}$ is and the quicker the pH will change with a small addition of the base. Notice also that, if the solutions aren't very dilute, then the second term quickly dominates the denominator because while adding base, the value of $[H^+]$ will become quite small compared to $C_\ce{A}$ and $C_\ce{B}$. Now we have a very interesting situation; a fraction where the major component of the denominator has a subtraction. Here's an example of how this sort of function behaves. When the subtraction ends up giving a result close to zero, the function explodes. This means that the speed at which $\ce{[H^+]}$ changes becomes very sensitive to small variations of $V_\ce{B}$ near the critical region. And where does this critical region happen? Well, close to the region where $C_\ce{B} V_\ce{B} - C_\ce{A} V_\ce{A}$ is zero. If you remember the start of the answer, this is the equivalence point!. So there, this proves mathematically that the speed at which the pH changes is maximum at the equivalence point. This was only the simplest case though. Let's try something a little harder. Taking the titration equation for a weak acid with strong base, and implicitly differentiating both sides by $\displaystyle \frac{\ce{d}}{\ce{d} V_\ce{B}}$ again, we get the significantly more fearsome: $$\displaystyle \frac{\ce{d[H^+]}}{\ce{d}V_\ce{B}} = \frac{ -\frac{V_\ce{A}}{(V_\ce{A} + V_\ce{B})^2} \ce{[H^+]} (C_\ce{B}\ce{[H^+]} - C_\ce{B} K_\ce{a} + C_\ce{A} K_\ce{a})}{3\ce{[H^+]^2 + 2[H^+]}\left(K_\ce{a} + \frac{C_\ce{B} V_\ce{B}}{V_\ce{A} + V_\ce{B}}\right) + \frac{K_\ce{a}}{V_\ce{A} + V_\ce{B}} (C_\ce{B} V_\ce{B} - C_\ce{A} V_\ce{A}) -K_\ce{w}}$$ Once again, the term that dominates the behaviour of the complicated denominator is the part containing $C_\ce{B} V_\ce{B} - C_\ce{A} V_\ce{A}$, and once again the derivative explodes at the equivalence point.
https://api.stackexchange.com
For a project I am working on (in hyperbolic PDEs) I would like to get some rough handle on the behavior by looking at some numerics. I am, however, not a very good programmer. Can you recommend some resources for learning how to effectively code finite difference schemes in Scientific Python (other languages with small learning curve also welcome)? To give you an idea of the audience (me) for this recommendation: I am a pure mathematician by training, and am somewhat familiar with the theoretical aspects of finite difference schemes What I need help with is how to make the computer compute what I want it to compute, especially in a way that I don't duplicate too much of the effort already put in by others (so as to not re-invent the wheel when a package is already available). (Another thing I would like to avoid is to stupidly code something by hand when there are established data structures fitting the purpose.) I have had some coding experience; but I have had none in Python (hence I don't mind if there are good resources for learning a different language [say, Octave for example]). Books, documentation would both be useful, as would collections of example code.
Here is a 97-line example of solving a simple multivariate PDE using finite difference methods, contributed by Prof. David Ketcheson, from the py4sci repository I maintain. For more complicated problems where you need to handle shocks or conservation in a finite-volume discretization, I recommend looking at pyclaw, a software package that I help develop. """Pattern formation code Solves the pair of PDEs: u_t = D_1 \nabla^2 u + f(u,v) v_t = D_2 \nabla^2 v + g(u,v) """ import matplotlib matplotlib.use('TkAgg') import numpy as np import matplotlib.pyplot as plt from scipy.sparse import spdiags,linalg,eye from time import sleep #Parameter values Du=0.500; Dv=1; delta=0.0045; tau1=0.02; tau2=0.2; alpha=0.899; beta=-0.91; gamma=-alpha; #delta=0.0045; tau1=0.02; tau2=0.2; alpha=1.9; beta=-0.91; gamma=-alpha; #delta=0.0045; tau1=2.02; tau2=0.; alpha=2.0; beta=-0.91; gamma=-alpha; #delta=0.0021; tau1=3.5; tau2=0; alpha=0.899; beta=-0.91; gamma=-alpha; #delta=0.0045; tau1=0.02; tau2=0.2; alpha=1.9; beta=-0.85; gamma=-alpha; #delta=0.0001; tau1=0.02; tau2=0.2; alpha=0.899; beta=-0.91; gamma=-alpha; #delta=0.0005; tau1=2.02; tau2=0.; alpha=2.0; beta=-0.91; gamma=-alpha; nx=150; #Define the reaction functions def f(u,v): return alpha*u*(1-tau1*v**2) + v*(1-tau2*u); def g(u,v): return beta*v*(1+alpha*tau1/beta*u*v) + u*(gamma+tau2*v); def five_pt_laplacian(m,a,b): """Construct a matrix that applies the 5-point laplacian discretization""" e=np.ones(m**2) e2=([0]+[1]*(m-1))*m h=(b-a)/(m+1) A=np.diag(-4*e,0)+np.diag(e2[1:],-1)+np.diag(e2[1:],1)+np.diag(e[m:],m)+np.diag(e[m:],-m) A/=h**2 return A def five_pt_laplacian_sparse(m,a,b): """Construct a sparse matrix that applies the 5-point laplacian discretization""" e=np.ones(m**2) e2=([1]*(m-1)+[0])*m e3=([0]+[1]*(m-1))*m h=(b-a)/(m+1) A=spdiags([-4*e,e2,e3,e,e],[0,-1,1,-m,m],m**2,m**2) A/=h**2 return A # Set up the grid a=-1.; b=1. m=100; h=(b-a)/m; x = np.linspace(-1,1,m) y = np.linspace(-1,1,m) Y,X = np.meshgrid(y,x) # Initial data u=np.random.randn(m,m)/2.; v=np.random.randn(m,m)/2.; plt.hold(False) plt.pcolormesh(x,y,u) plt.colorbar; plt.axis('image'); plt.draw() u=u.reshape(-1) v=v.reshape(-1) A=five_pt_laplacian_sparse(m,-1.,1.); II=eye(m*m,m*m) t=0. dt=h/delta/5.; plt.ion() #Now step forward in time for k in range(120): #Simple (1st-order) operator splitting: u = linalg.spsolve(II-dt*delta*Du*A,u) v = linalg.spsolve(II-dt*delta*Dv*A,v) unew=u+dt*f(u,v); v =v+dt*g(u,v); u=unew; t=t+dt; #Plot every 3rd frame if k/3==float(k)/3: U=u.reshape((m,m)) plt.pcolormesh(x,y,U) plt.colorbar plt.axis('image') plt.title(str(t)) plt.draw() plt.ioff()
https://api.stackexchange.com
What tradeoffs should I consider when deciding to use an SPI or I2C interface? This accelerometer/gyro breakout board is available in two models, one for each interface. Would either one be easier to integrate into an Arduino project?
Summary SPI is faster. I2C is more complex and not as easy to use if your microcontroller doesn't have an I2C controller. I2C only requires 2 lines. I2C is a bus system with bidirectional data on the SDA line. SPI is a point-to-point connection with data in and data out on separate lines (MOSI and MISO). Essentially SPI consists of a pair of shift registers, where you clock data in to one shift register while you clock data out of the other. Usually data is written in bytes by having each time 8 clock pulses in succession, but that's not an SPI requirement. You can also have word lengths of 16 bit or even 13 bit, if you like. While in I2C synchronization is done by the start sequence in SPI it's done by SS going high (SS is active low). You decide yourself after how many clock pulses this is. If you use 13 bit words the SS will latch the last clocked in bits after 13 clock pulses. Since the bidirectional data is on two separate lines it's easy to interface. SPI in standard mode needs at least four lines: SCLK (serial clock), MOSI (Master Out Slave In), MISO (Master In Slave Out) and SS (Slave Select). In bideroctional mode needs at least three lines: SCLK (serial clock), MIMO (Master In Master Out) which is one of the MOSI or MISO lines and SS (Slave Select). In systems with more than one slave you need a SS line for each slave, so that for \$N\$ slaves you have \$N+3\$ lines in standard mode and \$N+2\$ lines in bidirectional mode. If you don't want that, in standard mode you can daisy-chain the slaves by connecting the MOSI signal of one slave to the MISO of the next. This will slow down communication since you have to cycle through all slaves data. Like tcrosley says SPI can operate at a much higher frequency than I2C. I2C is a bit more complex. Since it's a bus you need a way to address devices. Your communication starts with a unique start sequence: the data line (SDA) is pulled low while the clock (SCL) is high, for the rest of the communication data is only allowed to change when the clock is low. This start sequence synchronizes each communication. Since the communication includes the addressing only two lines are required for any number of devices (up to 127). edit It's obvious that the data line is bidirectional, but it's worth noting that this is also true for the clock line. Slaves may stretch the clock to control bus speed. This makes I2C less convenient for level-shifting or buffering. (SPI lines in standard mode are all unidirectional.) After each byte (address or data) is sent the receiver has to acknowledge the receipt by placing an acknowledge pulse on SDA. If your microcontroller has an I2C interface this will automatically be taken care of. You can still bit-bang it if your microcontroller doesn't support it, but you'll have to switch the I/O pin from output to input for each acknowledge or read data, unless you use an I/O pin for reading and one for writing. At 400kHz standard I2C is much slower than SPI. There are high-speed I2C devices which operate at 1MHz, still much slower than 20MHz SPI.
https://api.stackexchange.com
I would like to select a random record from a large set of n unaligned sequencing reads in log(n) time complexity (big O notation) or less. A record is defined as the equivalent of four lines in FASTQ format. The records do not fit in RAM and would need to be stored on disk. Ideally, I would like to store the reads in a compressed format. I would prefer a solution that does not require any extra files such as for example a reference genome. The title of this question mentions a FASTQ only because FASTQ is a common format for storing unaligned reads on disk. I am happy with answers that require a single limited transformation of the data to another file format in time complexity order n. Update A clarification: I want the random record to be selected with probability 1/n.
Arbitrary record access in constant time To get a random record in constant time, it is sufficient to get an arbitrary record in constant time. I have two solutions here: One with tabix and one with grabix. I think the grabix solution is more elegant, but I am keeping the tabix solution below because tabix is a more mature tool than grabix. Thanks to user172818 for suggesting grabix. Update This answer previously stated that tabix and grabix perform lookups in log(n) time. After taking a closer look at the grabix source code and the tabix paper I am now convinced that lookups are independent of n in complexity. However, both tools use an index that scales in size proportionally to n. So, the loading of the index is order n. However, if we consider the loading of the index as "...a single limited transformation of the data to another file format...", then I think this answer is still a valid one. If more than one record is to be retrieved, then the index needs to be stored in memory, perhaps with a framework such as pysam or htslib. Using grabix Compress with bgzip. Index the file and perform lookups with grabix In bash: gzip -dc input.fastq.gz | bgzip -c > output.fastq.gz grabix index output.fastq.gz # retrieve 5-th record (1-based) in log(n) time # requires some math to convert indices (4*4 + 1, 4*4 + 4) = (17, 20) grabix grab output.fastq.gz 17 20 # Count the number of records for part two of this question export N_LINES=$(gzip -dc output.fastq.gz | wc -l) Using tabix The tabix code is more complicated and relies on the iffy assumption that \t is an acceptable character for replacement of \n in a FASTQ record. If you are happy with a file format that is close to but not exactly FASTQ, then you could do the following: Paste each record into a single line. Add a dummy chromosome and line number as the first and second column. Compress with bgzip. Index the file and perform lookups with tabix Note that we need to remove leading spaces introduced by nl and we need to introduce a dummy chromosome column to keep tabix happy: gzip -dc input.fastq.gz | paste - - - - | nl | sed 's/^ *//' | sed 's/^/dummy\t/' | bgzip -c > output.fastq.gz tabix -s 1 -b 2 -e 2 output.fastq.gz # now retrieve the 5th record (1-based) in log(n) time tabix output.fastq.gz dummy:5-5 # This command will retrieve the 5th record and convert it record back into FASTQ format tabix output.fastq.gz dummy:5-5 | perl -pe 's/^dummy\t\d+\t//' | tr '\t' '\n' # Count the number of records for part two of this question export N_RECORDS=$(gzip -dc output.fastq.gz | wc -l) Random record in constant time Now that we have a way of retrieving an arbitrary record in log(n) time, retrieving a random record is simply a matter of getting a good random number generator and sampling. Here is some example code to do this in python: Using grabix # random_read.py import os import random n_records = int(os.environ["N_LINES"]) // 4 rand_record_start = random.randrange(0, n_records) * 4 + 1 rand_record_end = rand_record_start + 3 os.system("grabix grab output.fastq.gz {0} {1}".format(rand_record_start, rand_record_end)) Using tabix # random_read.py import os import random n_records = int(os.environ["N_RECORDS"]) rand_record_index = random.randrange(0, n_records) + 1 # super ugly, but works... os.system( "tabix output.fastq.gz dummy:{0}-{0} | perl -pe 's/^dummy\t\d+\t//' | tr '\t' '\n'".format( rand_record_index) ) And this works for me: python3.5 random_read.py Disclaimer Please note that os.system calls a system shell and is vulnerable to shell injection vulnerabilities. If you are writing production code, then you probably want to take extra precautions. Thanks to Chris_Rands for raising this issue.
https://api.stackexchange.com
I am looking for fun, interesting mathematics textbooks which would make good studious holiday gifts for advanced mathematics undergraduates or beginning graduate students. They should be serious but also readable. In particular, I am looking for readable books on more obscure topics not covered in a standard undergraduate curriculum which students may not have previously heard of or thought to study. Some examples of suggestions I've liked so far: On Numbers and Games, by John Conway. Groups, Graphs and Trees: An Introduction to the Geometry of Infinite Groups, by John Meier. Ramsey Theory on the Integers, by Bruce Landman. I am not looking for pop math books, Gödel, Escher, Bach, or anything of that nature. I am also not looking for books on 'core' subjects unless the content is restricted to a subdiscipline which is not commonly studied by undergrads (e.g., Finite Group Theory by Isaacs would be good, but Abstract Algebra by Dummit and Foote would not).
Check into Generatingfunctionology by Herbert Wilf. From the linked (author's) site, the second edition is available for downloading as a pdf. There is also a link to the third edition, available for purchase. It's a very helpful, useful, readable, fun, (and short!) book that a student could conceivably cover over winter break. Another promising book by John Conway (et. al.) is The Symmetries of Things, which may very well be of interest to students. One additional suggestion, as it is a classic well worth being placed on any serious student's bookshelf: How to Solve It by George Polya.
https://api.stackexchange.com
My teacher told me about resonance and explained it as different structures which are flipping back and forth and that we only observe a sort of average structure. How does this work? Why do the different structures not exist on their own?
This answer is intended to clear up some misconceptions about resonance which have come up many times on this site. Resonance is a part of valence bond theory which is used to describe delocalised electron systems in terms of contributing structures, each only involving 2-centre-2-electron bonds. It is a concept that is very often taught badly and misinterpreted by students. The usual explanation is that it is as if the molecule is flipping back and forth between different structures very rapidly and that what is observed is an average of these structures. This is wrong! (There are molecules that do this (e.g bullvalene), but the rapidly interconverting structures are not called resonance forms or resonance structures.) Individual resonance structures do not exist on their own. They are not in some sort of rapid equilibrium. There is only a single structure for a molecule such as benzene, which can be described by resonance. The difference between an equilibrium situation and a resonance situation can be seen on a potential energy diagram. This diagram shows two possible structures of the 2-norbornyl cation. Structure (a) shows the single delocalised structure, described by resonance whereas structures (b) show the equilibrium option, with the delocalised structure (a) as a transition state. The key point is that resonance hybrids are a single potential energy minimum, whereas equilibrating structures are two energy minima separated by a barrier. In 2013 an X-ray diffraction structure was finally obtained and the correct structure was shown to be (a). Resonance describes delocalised bonding in terms of contributing structures that give some of their character to the single overall structure. These structures do not have to be equally weighted in their contribution. For example, amides can be described by the following resonance structures: The left structure is the major contributor but the right structure also contributes and so the structure of an amide has some double bond character in the C-N bond (ie. the bond order is >1) and less double bond character in the C-O bond (bond order <2). The alternative to valence bond theory and the resonance description of molecules is molecular orbital theory. This explains delocalised bonding as electrons occupying molecular orbitals which extend over more than two atoms.
https://api.stackexchange.com
I saw in a SO thread a suggestion to use filtfilt which performs backwards/forwards filtering instead of lfilter. What is the motivation for using one against the other technique?
filtfilt is zero-phase filtering, which doesn't shift the signal as it filters. Since the phase is zero at all frequencies, it is also linear-phase. Filtering backwards in time requires you to predict the future, so it can't be used in "online" real-life applications, only for offline processing of recordings of signals. lfilter is causal forward-in-time filtering only, similar to a real-life electronic filter. It can't be zero-phase. It can be linear-phase (symmetrical FIR), but usually isn't. Usually it adds different amounts of delay at different frequencies. An example and image should make it obvious. Although the magnitude of the frequency response of the filters is identical (top left and top right), the zero-phase lowpass lines up with the original signal, just without high frequency content, while the minimum phase filtering delays the signal in a causal way: from __future__ import division, print_function import numpy as np from numpy.random import randn from numpy.fft import rfft from scipy import signal import matplotlib.pyplot as plt b, a = signal.butter(4, 0.03, analog=False) # Show that frequency response is the same impulse = np.zeros(1000) impulse[500] = 1 # Applies filter forward and backward in time imp_ff = signal.filtfilt(b, a, impulse) # Applies filter forward in time twice (for same frequency response) imp_lf = signal.lfilter(b, a, signal.lfilter(b, a, impulse)) plt.subplot(2, 2, 1) plt.semilogx(20*np.log10(np.abs(rfft(imp_lf)))) plt.ylim(-100, 20) plt.grid(True, which='both') plt.title('lfilter') plt.subplot(2, 2, 2) plt.semilogx(20*np.log10(np.abs(rfft(imp_ff)))) plt.ylim(-100, 20) plt.grid(True, which='both') plt.title('filtfilt') sig = np.cumsum(randn(800)) # Brownian noise sig_ff = signal.filtfilt(b, a, sig) sig_lf = signal.lfilter(b, a, signal.lfilter(b, a, sig)) plt.subplot(2, 1, 2) plt.plot(sig, color='silver', label='Original') plt.plot(sig_ff, color='#3465a4', label='filtfilt') plt.plot(sig_lf, color='#cc0000', label='lfilter') plt.grid(True, which='both') plt.legend(loc="best")
https://api.stackexchange.com
I used to work with publicly available genomic references, where basic statistics are usually available and if they are not, you have to compute them only once so there is no reason to worry about performance. Recently I started sequencing project of couple of different species with mid-sized genomes (~Gbp) and during testing of different assembly pipelines I had compute number of unknown nucleotides many times in both raw reads (in fastq) and assembly scaffolds (in fasta), therefore I thought that I would like to optimize the computation. For me it is reasonable to expect 4-line formatted fastq files, but general solution is still prefered It would be nice if solution would work on gzipped files as well Q : What is the fastest way (performance-wise) to compute the number of unknown nucleotides (Ns) in fasta and fastq files?
For FASTQ: seqtk fqchk in.fq | head -2 It gives you percentage of "N" bases, not the exact count, though. For FASTA: seqtk comp in.fa | awk '{x+=$9}END{print x}' This command line also works with FASTQ, but it will be slower as awk is slow. EDIT: ok, based on @BaCH's reminder, here we go (you need kseq.h to compile): // to compile: gcc -O2 -o count-N this-prog.c -lz #include <zlib.h> #include <stdio.h> #include <stdint.h> #include "kseq.h" KSEQ_INIT(gzFile, gzread) unsigned char dna5tbl[256] = { 0, 1, 2, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 4, 1, 4, 4, 4, 2, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 4, 1, 4, 4, 4, 2, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4 }; int main(int argc, char *argv[]) { long i, n_n = 0, n_acgt = 0, n_gap = 0; gzFile fp; kseq_t *seq; if (argc == 1) { fprintf(stderr, "Usage: count-N <in.fa>\n"); return 1; } if ((fp = gzopen(argv[1], "r")) == 0) { fprintf(stderr, "ERROR: fail to open the input file\n"); return 1; } seq = kseq_init(fp); while (kseq_read(seq) >= 0) { for (i = 0; i < seq->seq.l; ++i) { int c = dna5tbl[(unsigned char)seq->seq.s[i]]; if (c < 4) ++n_acgt; else if (c == 4) ++n_n; else ++n_gap; } } kseq_destroy(seq); gzclose(fp); printf("%ld\t%ld\t%ld\n", n_acgt, n_n, n_gap); return 0; } It works for both FASTA/Q and gzip'ed FASTA/Q. The following uses SeqAn: #include <seqan/seq_io.h> using namespace seqan; int main(int argc, char *argv[]) { if (argc == 1) { std::cerr << "Usage: count-N <in.fastq>" << std::endl; return 1; } std::ios::sync_with_stdio(false); CharString id; Dna5String seq; SeqFileIn seqFileIn(argv[1]); long i, n_n = 0, n_acgt = 0; while (!atEnd(seqFileIn)) { readRecord(id, seq, seqFileIn); for (i = beginPosition(seq); i < endPosition(seq); ++i) if (seq[i] < 4) ++n_acgt; else ++n_n; } std::cout << n_acgt << '\t' << n_n << std::endl; return 0; } On a FASTQ with 4-million 150bp reads: The C version: ~0.74 sec The C++ version: ~2.15 sec An older C version without a lookup table (see the previous edit): ~2.65 sec
https://api.stackexchange.com
We've learnt that the electropositive element is written first. Then why is ammonia written as $\ce{NH3}$ ?
According to current nomenclature rules, $\ce{H3N}$ would be correct and acceptable. However some chemical formulas, like $\ce{NH3}$ for ammonia, that were in use long before the rules came out, are still accepted today.
https://api.stackexchange.com
Are there any tools in Python that are like Matlab's parfor? I found this thread, but it's four years old. I thought maybe someone here might have more recent experience. Here's an example of the type of thing I'd like to parallelize: X = np.random.normal(size=(10, 3)) F = np.zeros((10, )) for i in range(10): F[i] = my_function(X[i,:]) where my_function takes an ndarray of size (1,3) and returns a scalar. At the least, I'd like to use multiple cores simultaneously---like parfor. In other words, assume a shared memory system with 8-to-16 cores.
Joblib does what you want. The basic usage pattern is: from joblib import Parallel, delayed def myfun(arg): do_stuff return result results = Parallel(n_jobs=-1, verbose=verbosity_level, backend="threading")( map(delayed(myfun), arg_instances)) where arg_instances is list of values for which myfun is computed in parallel. The main restriction is that myfun must be a toplevel function. The backend parameter can be either "threading" or "multiprocessing". You can pass additional common parameters to the parallelized function. The body of myfun can also refer to initialized global variables, the values which will be available to the children. Args and results can be pretty much anything with the threading backend but results need to be serializable with the multiprocessing backend. Dask also offers similar functionality. It might be preferable if you are working with out of core data or you are trying to parallelize more complex computations.
https://api.stackexchange.com
It seems that everywhere I look, data structures are being implemented using red-black trees (std::set in C++, SortedDictionary in C#, etc.) Having just covered (a,b), red-black & AVL trees in my algorithms class, here's what I got out (also from asking around professors, looking through a few books and googling a bit): AVL trees have smaller average depth than red-black trees, and thus searching for a value in AVL tree is consistently faster. Red-black trees make less structural changes to balance themselves than AVL trees, which could make them potentially faster for insert/delete. I'm saying potentially, because this would depend on the cost of the structural change to the tree, as this will depend a lot on the runtime and implemntation (might also be completely different in a functional language when the tree is immutable?) There are many benchmarks online that compare AVL and Red-black trees, but what struck me is that my professor basically said, that usually you'd do one of two things: Either you don't really care that much about performance, in which case the 10-20% difference of AVL vs Red-black in most cases won't matter at all. Or you really care about performance, in which you case you'd ditch both AVL and Red-black trees, and go with B-trees, which can be tweaked to work much better (or (a,b)-trees, I'm gonna put all of those in one basket.) The reason for that is because a B-tree stores data more compactly in memory (one node contains many values) there will be much fewer cache misses. You could also tweak the implementation based on the use case, and make the order of the B-tree depend on the CPU cache size, etc. The problem is that I can't find almost any source that would analyze real life usage of different implementations of search trees on real modern hardware. I've looked through many books on algorithms and haven't found anything that would compare different tree variants together, other than showing that one has smaller average depth than the other one (which doesn't really say much of how the tree will behave in real programs.) That being said, is there a particular reason why Red-black trees are being used everywhere, when based on what is said above, B-trees should be outperforming them? (as the only benchmark I could find also shows but it might just be a matter of the specific implementation). Or is the reason why everyone uses Red-black trees because they're rather easy to implement, or to put it in different words, hard to implement poorly? Also, how does this change when one moves to the realm of functional languages? It seems that both Clojure and Scala use Hash array mapped tries, where Clojure uses a branching factor of 32.
To quote from the answer to “Traversals from the root in AVL trees and Red Black Trees” question For some kinds of binary search trees, including red-black trees but not AVL trees, the "fixes" to the tree can fairly easily be predicted on the way down and performed during a single top-down pass, making the second pass unnecessary. Such insertion algorithms are typically implemented with a loop rather than recursion, and often run slightly faster in practice than their two-pass counterparts. So a RedBlack tree insert can be implemented without recursion, on some CPUs recursion is very expensive if you overrun the function call cache (e.g SPARC due to is use of Register window) (I have seen software run over 10 times as fast on the Sparc by removing one function call, that resulted in a often called code path being too deep for the register window. As you don't know how deep the register window will be on your customer's system, and you don't know how far down the call stack you are in the "hot code path", not using recursion make like more predictable.) Also not risking running out of stack is a benefit.
https://api.stackexchange.com
I agree that a Turing Machine can do "all possible mathematical problems". But that is because it is just a machine representation of an algorithm: first do this, then do that, finally output that. I mean anything that is solvable can be represented by an algorithm (because that is precisely the definition of 'solvable'). It is just a tautology. I said nothing new here. And by creating a machine representation of an algorithm, that it will also solve all possible problems is also nothing new. This is also mere tautology. So basically when it is said that a Turing Machine is the most powerful machine, what it effectively means is that the most powerful machine is the most powerful machine! Definition of "most powerful": That which can accept any language. Definition of "Algorithm": Process for doing anything. Machine representation of "Algorithm": A machine that can do anything. Therefore it is only logical that the machine representation of an algorithm will be the most powerful machine. What's the new thing Alan Turing gave us?
I agree that a Turing Machine can do "all the possible mathematical problems". Well, you shouldn't, because it's not true. For example, Turing machines cannot determine if polynomials with integer coefficients have integer solutions (Hilbert's tenth problem). Is Turing Machine “by definition” the most powerful machine? No. We can dream up an infinite hierarchy of more powerful machines. However, the Turing machine is the most powerful machine that we know, at least in principle, how to build. That's not a definition, though: it is just that we do not have any clue how to build anything more powerful, or if it is even possible. What's the new thing Alan Turing gave us? A formal definition of algorithm. Without such a definition (e.g., the Turing machine), we have only informal definitions of algorithm, along the lines of "A finitely specified procedure for solving something." OK, great. But what individual steps are these procedures allowed to take? Are basic arithmetic operations steps? Is finding the gradient of a curve a step? Is finding roots of polynomials a step? Is finding integer roots of polynomials a step? Each of those seems about as natural. However, if you allow all of them, your "finitely specified procedures" are more powerful than Turing machines, which means that they can solve things that can't be solved by algorithms. If you allow all but the last one, you're still within the realms of Turing computation. If we didn't have a formal definition of algorithm, we wouldn't even be able to ask these questions. We wouldn't be able to discuss what algorithms can do, because we wouldn't know what an algorithm is.
https://api.stackexchange.com
Standard finite difference formulas are usable to numerically compute a derivative under the expectation that you have function values $f(x_k)$ at evenly spaced points, so that $h \equiv x_{k+1} - x_k$ is a constant. What if I have unevenly spaced points, so that $h$ now varies from one pair of adjacent points to the next? Obviously I can still compute a first derivative as $f'(x) \approx \frac{1}{h_k}[f(x_{k+1}) - f(x_k)]$, but are there numerical differentiation formulas at higher orders and accuracies that can adapt to variation in the grid size?
J.M's comment is right: you can find an interpolating polynomial and differentiate it. There are other ways of deriving such formulas; typically, they all lead to solving a van der Monde system for the coefficients. This approach is problematic when the finite difference stencil includes a large number of points, because the Vandermonde matrices become ill-conditioned. A more numerically stable approach was devised by Fornberg, and is explained more clearly and generally in a second paper of his. Here is a simple MATLAB script that implements Fornberg's method to compute the coefficients of a finite difference approximation for any order derivative with any set of points. For a nice explanation, see Chapter 1 of LeVeque's text on finite difference methods. A bit more on FD formulas: Suppose you have a 1D grid. If you use the whole set of grid points to determine a set of FD formulas, the resulting method is equivalent to finding an interpolating polynomial through the whole grid and differentiating that. This approach is referred to as spectral collocation. Alternatively, for each grid point you could determine a FD formula using just a few neighboring points. This is what is done in traditional finite difference methods. As mentioned in the comments below, using finite differences of very high order can lead to oscillations (the Runge phenomenon) if the points are not chosen carefully.
https://api.stackexchange.com
I think I remember reading somewhere that the Baire Category Theorem is supposedly quite powerful. Whether that is true or not, it's my favourite theorem (so far) and I'd love to see some applications that confirm its neatness and/or power. Here's the theorem (with proof) and two applications: (Baire) A non-empty complete metric space $X$ is not a countable union of nowhere dense sets. Proof: Let $X = \bigcup U_i$ where $\mathring{\overline{U_i}} = \varnothing$. We construct a Cauchy sequence as follows: Let $x_1$ be any point in $(\overline{U_1})^c$. We can find such a point because $(\overline{U_1})^c \subset X$ and $X$ contains at least one non-empty open set (if nothing else, itself) but $\mathring{\overline{U_1}} = \varnothing$ which is the same as saying that $\overline{U_1}$ does not contain any open sets hence the open set contained in $X$ is contained in $\overline{U_1}^c$. Hence we can pick $x_1$ and $\varepsilon_1 > 0$ such that $B(x_1, \varepsilon_1) \subset (\overline{U_1})^c \subset U_1^c$. Next we make a similar observation about $U_2$ so that we can find $x_2$ and $\varepsilon_2 > 0$ such that $B(x_2, \varepsilon_2) \subset \overline{U_2}^c \cap B(x_1, \frac{\varepsilon_1}{2})$. We repeat this process to get a sequence of balls such that $B_{k+1} \subset B_k$ and a sequence $(x_k)$ that is Cauchy. By completeness of $X$, $\lim x_k =: x$ is in $X$. But $x$ is in $B_k$ for every $k$ hence not in any of the $U_i$ and hence not in $\bigcup U_i = X$. Contradiction. $\Box$ Here is one application (taken from here): Claim: $[0,1]$ contains uncountably many elements. Proof: Assume that it contains countably many. Then $[0,1] = \bigcup_{x \in (0,1)} \{x\}$ and since $\{x\}$ are nowhere dense sets, $X$ is a countable union of nowhere dense sets. But $[0,1]$ is complete, so we have a contradiction. Hence $X$ has to be uncountable. And here is another one (taken from here): Claim: The linear space of all polynomials in one variable is not a Banach space in any norm. Proof: "The subspace of polynomials of degree $\leq n$ is closed in any norm because it is finite-dimensional. Hence the space of all polynomials can be written as countable union of closed nowhere dense sets. If there were a complete norm this would contradict the Baire Category Theorem."
If $P$ is an infinitely differentiable function such that for each $x$, there is an $n$ with $P^{(n)}(x)=0$, then $P$ is a polynomial. (Note $n$ depends on $x$.) See the discussion in Math Overflow.
https://api.stackexchange.com
I am a CS undergraduate. I understand how Turing came up with his abstract machine (modeling a person doing a computation), but it seems to me to be an awkward, inelegant abstraction. Why do we consider a "tape", and a machine head writing symbols, changing state, shifting the tape back and forth? What is the underlying significance? A DFA is elegant - it seems to capture precisely what is necessary to recognize the regular languages. But the Turing machine, to my novice judgement, is just a clunky abstract contraption. After thinking about it, I think the most idealized model of computation would be to say that some physical system corresponding to the input string, after being set into motion, would reach a static equilibrium which, upon interpretation equivalent to the the one used to form the system from the original string, would correspond to the correct output string. This captures the notion of "automation", since the system would change deterministically based solely on the original state. Edit: After reading a few responses, I've realized that what confuses me about the Turing machine is that it does not seem minimal. Shouldn't the canonical model of computation obviously convey the essence of computability? Also, in case it wasn't clear I know that DFAs are not complete models of computation. Thank you for the replies.
Well, a DFA is just a Turing machine that's only allowed to move to the right and that must accept or reject as soon as it runs out of input characters. So I'm not sure one can really say that a DFA is natural but a Turing machine isn't. Critique of the question aside, remember that Turing was working before computers existed. As such, he wasn't trying to codify what electronic computers do but, rather, computation in general. My parents have a dictionary from the 1930s that defines computer as "someone who computes" and this is basically where Turing was coming from: for him, at that time, computation was about slide rules, log tables, pencils and pieces of paper. In that mind-set, rewriting symbols on a paper tape doesn't seem like a bad abstraction. OK, fine, you're saying (I hope!) but we're not in the 1930s any more so why do we still use this? Here, I don't think there's any one specific reason. The advantage of Turing machines is that they're reasonably simple and we're decently good at proving things about them. Although formally specifying a Turing machine program to do some particular task is very tedious, once you've done it a few times, you have a reasonable intuition about what they can do and you don't need to write the formal specifications any more. The model is also easily extended to include other natural features, such as random access to the tape. So they're a pretty useful model that we understand well and we also have a pretty good understanding of how they relate to actual computers. One could use other models but one would then have to do a huge amount of translation between results for the new model and the vast body of existing work on what Turing machines can do. Nobody has come up with a replacement for Turing machines that have had big enough advantages to make that look like a good idea.
https://api.stackexchange.com
I am seeking help understanding Floyd's cycle detection algorithm. I have gone through the explanation on wikipedia ( I can see how the algorithm detects cycle in O(n) time. However, I am unable to visualise the fact that once the tortoise and hare pointers meet for the first time, the start of the cycle can be determined by moving tortoise pointer back to start and then moving both tortoise and hare one step at a time. The point where they first meet is the start of the cycle. Can someone help by providing an explanation, hopefully different from the one on wikipedia, as I am unable to understand/visualise it?
You can refer to "Detecting start of a loop in singly linked list", here's an excerpt: Distance travelled by slowPointer before meeting $= x+y$ Distance travelled by fastPointer before meeting $=(x + y + z) + y = x + 2y + z$ Since fastPointer travels with double the speed of slowPointer, and time is constant for both when both pointers reach the meeting point. So by using simple speed, time and distance relation (slowPointer traveled half the distance): \begin{align*} 2*\operatorname{dist}(\text{slowPointer}) &= \operatorname{dist}(\text{fastPointer})\\ 2(x+y) &= x+2y+z\\ 2x+2y &= x+2y+z\\ x &= z \end{align*} Hence by moving slowPointer to start of linked list, and making both slowPointer and fastPointer to move one node at a time, they both have same distance to cover. They will reach at the point where the loop starts in the linked list.
https://api.stackexchange.com
I've always wondered why processors stopped at 32 registers. It's by far the fastest piece of the machine, why not just make bigger processors with more registers? Wouldn't that mean less going to the RAM?
First, not all processor architectures stopped at 32 registers. Almost all the RISC architectures that have 32 registers exposed in the instruction set actually have 32 integer registers and 32 more floating point registers (so 64). (Floating point "add" uses different registers than integer "add".) The SPARC architecture has register windows. On the SPARC you can only access 32 integer registers at a time, but the registers act like a stack and you can push and pop new registers 16 at a time. The Itanium architecture from HP/Intel had 128 integer and 128 floating point registers exposed in the instruction set. Modern GPUs from NVidia, AMD, Intel, ARM and Imagination Technologies, all expose massive numbers of registers in their register files. (I know this to be true of the NVidia and Intel architectures, I am not very familiar with the AMD, ARM and Imagination instruction sets, but I think the register files are large there too.) Second, most modern microprocessors implement register renaming to eliminate unnecessary serialization caused by needing to reuse resources, so the underlying physical register files can be larger (96, 128 or 192 registers on some machines.) This (and dynamic scheduling) eliminates some of the need for the compiler to generate so many unique register names, while still providing a larger register file to the scheduler. There are two reasons why it might be difficult to further increase the number of registers exposed in the instruction set. First, you need to be able to specify the register identifiers in each instruction. 32 registers require a 5 bit register specifier, so 3-address instructions (common on RISC architectures) spend 15 of the 32 instruction bits just to specify the registers. If you increased that to 6 or 7 bits, then you would have less space to specify opcodes and constants. GPUs and Itanium have much larger instructions. Larger instructions come at a cost: you need to use more instruction memory, so your instruction cache behavior is less ideal. The second reason is access time. The larger you make a memory the slower it is to access data from it. (Just in terms of basic physics: the data is stored in 2-dimensional space, so if you are storing $n$ bits, the average distance to a specific bit is $O(\sqrt{n})$.) A register file is just a small multi-ported memory, and one of the constraints on making it larger is that eventually you would need to start clocking your machine slower to accommodate the larger register file. Usually in terms of total performance this is a lose.
https://api.stackexchange.com
I'm training a neural network but the training loss doesn't decrease. How can I fix this? I'm not asking about overfitting or regularization. I'm asking about how to solve the problem where my network's performance doesn't improve on the training set. A specific variant of this problem arises when the loss has a steep initial decrease and then stops improving almost immediately. Often, this happens because the model is fitting some constant to the target (dependent variable, outcome). For a regression task that is minimizing the square error (MSE loss), this constant is usually something close to $\bar y$ the mean of the target (dependent variable, outcome). For a classification task, it's slightly more subtle, but it can happen that the model fits a constant to predict the proportion of each outcome. Consider the binary classification task with cross-entropy loss. An optimal constant to choose is a solution to $c \log c + (1 - c) \log(1-c)=-\bar y$ where $0 < c< 1$. In both cases, we would prefer the network to be more specific in the sense that the prediction varies as some function of the features (input, independent variable); we don't need to use a neural network to compute the mean of the response. This question is intentionally general so that other questions about how to train a neural network can be closed as a duplicate of this one, with the attitude that "if you give a man a fish you feed him for a day, but if you teach a man to fish, you can feed him for the rest of his life." See this Meta thread for a discussion: What's the best way to answer "my neural network doesn't work, please fix" questions? If your neural network does not generalize well, see: What should I do when my neural network doesn't generalize well?
1. Verify that your code is bug free There's a saying among writers that "All writing is re-writing" -- that is, the greater part of writing is revising. For programmers (or at least data scientists) the expression could be re-phrased as "All coding is debugging." Any time you're writing code, you need to verify that it works as intended. The best method I've ever found for verifying correctness is to break your code into small segments, and verify that each segment works. This can be done by comparing the segment output to what you know to be the correct answer. This is called unit testing. Writing good unit tests is a key piece of becoming a good statistician/data scientist/machine learning expert/neural network practitioner. There is simply no substitute. You have to check that your code is free of bugs before you can tune network performance! Otherwise, you might as well be re-arranging deck chairs on the RMS Titanic. There are two features of neural networks that make verification even more important than for other types of machine learning or statistical models. Neural networks are not "off-the-shelf" algorithms in the way that random forest or logistic regression are. Even for simple, feed-forward networks, the onus is largely on the user to make numerous decisions about how the network is configured, connected, initialized and optimized. This means writing code, and writing code means debugging. Even when a neural network code executes without raising an exception, the network can still have bugs! These bugs might even be the insidious kind for which the network will train, but get stuck at a sub-optimal solution, or the resulting network does not have the desired architecture. (This is an example of the difference between a syntactic and semantic error.) This Medium post, "How to unit test machine learning code," by Chase Roberts discusses unit-testing for machine learning models in more detail. I borrowed this example of buggy code from the article: def make_convnet(input_image): net = slim.conv2d(input_image, 32, [11, 11], scope="conv1_11x11") net = slim.conv2d(input_image, 64, [5, 5], scope="conv2_5x5") net = slim.max_pool2d(net, [4, 4], stride=4, scope='pool1') net = slim.conv2d(input_image, 64, [5, 5], scope="conv3_5x5") net = slim.conv2d(input_image, 128, [3, 3], scope="conv4_3x3") net = slim.max_pool2d(net, [2, 2], scope='pool2') net = slim.conv2d(input_image, 128, [3, 3], scope="conv5_3x3") net = slim.max_pool2d(net, [2, 2], scope='pool3') net = slim.conv2d(input_image, 32, [1, 1], scope="conv6_1x1") return net Do you see the error? Many of the different operations are not actually used because previous results are over-written with new variables. Using this block of code in a network will still train and the weights will update and the loss might even decrease -- but the code definitely isn't doing what was intended. (The author is also inconsistent about using single- or double-quotes but that's purely stylistic.) The most common programming errors pertaining to neural networks are Variables are created but never used (usually because of copy-paste errors); Expressions for gradient updates are incorrect; Weight updates are not applied; Loss functions are not measured on the correct scale (for example, cross-entropy loss can be expressed in terms of probability or logits) The loss is not appropriate for the task (for example, using categorical cross-entropy loss for a regression task). Dropout is used during testing, instead of only being used for training. Make sure you're minimizing the loss function $L(x)$, instead of minimizing $-L(x)$. Make sure your loss is computed correctly. Unit testing is not just limited to the neural network itself. You need to test all of the steps that produce or transform data and feed into the network. Some common mistakes here are NA or NaN or Inf values in your data creating NA or NaN or Inf values in the output, and therefore in the loss function. Shuffling the labels independently from the samples (for instance, creating train/test splits for the labels and samples separately); Accidentally assigning the training data as the testing data; When using a train/test split, the model references the original, non-split data instead of the training partition or the testing partition. Forgetting to scale the testing data; Scaling the testing data using the statistics of the test partition instead of the train partition; Forgetting to un-scale the predictions (e.g. pixel values are in [0,1] instead of [0, 255]). Here's an example of a question where the problem appears to be one of model configuration or hyperparameter choice, but actually the problem was a subtle bug in how gradients were computed. Is this drop in training accuracy due to a statistical or programming error? 2. For the love of all that is good, scale your data The scale of the data can make an enormous difference on training. Sometimes, networks simply won't reduce the loss if the data isn't scaled. Other networks will decrease the loss, but only very slowly. Scaling the inputs (and certain times, the targets) can dramatically improve the network's training. Prior to presenting data to a neural network, standardizing the data to have 0 mean and unit variance, or to lie in a small interval like $[-0.5, 0.5]$ can improve training. This amounts to pre-conditioning, and removes the effect that a choice in units has on network weights. For example, length in millimeters and length in kilometers both represent the same concept, but are on different scales. The exact details of how to standardize the data depend on what your data look like. Data normalization and standardization in neural networks Why does $[0,1]$ scaling dramatically increase training time for feed forward ANN (1 hidden layer)? Batch or Layer normalization can improve network training. Both seek to improve the network by keeping a running mean and standard deviation for neurons' activations as the network trains. It is not well-understood why this helps training, and remains an active area of research. "Understanding Batch Normalization" by Johan Bjorck, Carla Gomes, Bart Selman "Towards a Theoretical Understanding of Batch Normalization" by Jonas Kohler, Hadi Daneshmand, Aurelien Lucchi, Ming Zhou, Klaus Neymeyr, Thomas Hofmann "How Does Batch Normalization Help Optimization? (No, It Is Not About Internal Covariate Shift)" by Shibani Santurkar, Dimitris Tsipras, Andrew Ilyas, Aleksander Madry 3. Crawl Before You Walk; Walk Before You Run Wide and deep neural networks, and neural networks with exotic wiring, are the Hot Thing right now in machine learning. But these networks didn't spring fully-formed into existence; their designers built up to them from smaller units. First, build a small network with a single hidden layer and verify that it works correctly. Then incrementally add additional model complexity, and verify that each of those works as well. Too few neurons in a layer can restrict the representation that the network learns, causing under-fitting. Too many neurons can cause over-fitting because the network will "memorize" the training data. Even if you can prove that there is, mathematically, only a small number of neurons necessary to model a problem, it is often the case that having "a few more" neurons makes it easier for the optimizer to find a "good" configuration. (But I don't think anyone fully understands why this is the case.) I provide an example of this in the context of the XOR problem here: Aren't my iterations needed to train NN for XOR with MSE < 0.001 too high?. Choosing the number of hidden layers lets the network learn an abstraction from the raw data. Deep learning is all the rage these days, and networks with a large number of layers have shown impressive results. But adding too many hidden layers can make risk overfitting or make it very hard to optimize the network. Choosing a clever network wiring can do a lot of the work for you. Is your data source amenable to specialized network architectures? Convolutional neural networks can achieve impressive results on "structured" data sources, image or audio data. Recurrent neural networks can do well on sequential data types, such as natural language or time series data. Residual connections can improve deep feed-forward networks. 4. Neural Network Training Is Like Lock Picking To achieve state of the art, or even merely good, results, you have to set up all of the parts configured to work well together. Setting up a neural network configuration that actually learns is a lot like picking a lock: all of the pieces have to be lined up just right. Just as it is not sufficient to have a single tumbler in the right place, neither is it sufficient to have only the architecture, or only the optimizer, set up correctly. Tuning configuration choices is not really as simple as saying that one kind of configuration choice (e.g. learning rate) is more or less important than another (e.g. number of units), since all of these choices interact with all of the other choices, so one choice can do well in combination with another choice made elsewhere. This is a non-exhaustive list of the configuration options which are not also regularization options or numerical optimization options. All of these topics are active areas of research. The network initialization is often overlooked as a source of neural network bugs. Initialization over too-large an interval can set initial weights too large, meaning that single neurons have an outsize influence over the network behavior. The key difference between a neural network and a regression model is that a neural network is a composition of many nonlinear functions, called activation functions. (See: What is the essential difference between neural network and linear regression) Classical neural network results focused on sigmoidal activation functions (logistic or $\tanh$ functions). A recent result has found that ReLU (or similar) units tend to work better because the have steeper gradients, so updates can be applied quickly. (See: Why do we use ReLU in neural networks and how do we use it?) One caution about ReLUs is the "dead neuron" phenomenon, which can stymie learning; leaky relus and similar variants avoid this problem. See Why can't a single ReLU learn a ReLU? My ReLU network fails to launch There are a number of other options. See: Comprehensive list of activation functions in neural networks with pros/cons Residual connections are a neat development that can make it easier to train neural networks. "Deep Residual Learning for Image Recognition" Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun In: CVPR. (2016). Additionally, changing the order of operations within the residual block can further improve the resulting network. "Identity Mappings in Deep Residual Networks" by Kaiming He, Xiangyu Zhang, Shaoqing Ren, and Jian Sun. 5. Non-convex optimization is hard The objective function of a neural network is only convex when there are no hidden units, all activations are linear, and the design matrix is full-rank -- because this configuration is identically an ordinary regression problem. In all other cases, the optimization problem is non-convex, and non-convex optimization is hard. The challenges of training neural networks are well-known (see: Why is it hard to train deep neural networks?). Additionally, neural networks have a very large number of parameters, which restricts us to solely first-order methods (see: Why is Newton's method not widely used in machine learning?). This is a very active area of research. Setting the learning rate too large will cause the optimization to diverge, because you will leap from one side of the "canyon" to the other. Setting this too small will prevent you from making any real progress, and possibly allow the noise inherent in SGD to overwhelm your gradient estimates. See: How can change in cost function be positive? Gradient clipping re-scales the norm of the gradient if it's above some threshold. I used to think that this was a set-and-forget parameter, typically at 1.0, but I found that I could make an LSTM language model dramatically better by setting it to 0.25. I don't know why that is. Learning rate scheduling can decrease the learning rate over the course of training. In my experience, trying to use scheduling is a lot like regex: it replaces one problem ("How do I get learning to continue after a certain epoch?") with two problems ("How do I get learning to continue after a certain epoch?" and "How do I choose a good schedule?"). Other people insist that scheduling is essential. I'll let you decide. Choosing a good minibatch size can influence the learning process indirectly, since a larger mini-batch will tend to have a smaller variance (law-of-large-numbers) than a smaller mini-batch. You want the mini-batch to be large enough to be informative about the direction of the gradient, but small enough that SGD can regularize your network. There are a number of variants on stochastic gradient descent which use momentum, adaptive learning rates, Nesterov updates and so on to improve upon vanilla SGD. Designing a better optimizer is very much an active area of research. Some examples: No change in accuracy using Adam Optimizer when SGD works fine How does the Adam method of stochastic gradient descent work? Why does momentum escape from a saddle point in this famous image? When it first came out, the Adam optimizer generated a lot of interest. But some recent research has found that SGD with momentum can out-perform adaptive gradient methods for neural networks. "The Marginal Value of Adaptive Gradient Methods in Machine Learning" by Ashia C. Wilson, Rebecca Roelofs, Mitchell Stern, Nathan Srebro, Benjamin Recht But on the other hand, this very recent paper proposes a new adaptive learning-rate optimizer which supposedly closes the gap between adaptive-rate methods and SGD with momentum. "Closing the Generalization Gap of Adaptive Gradient Methods in Training Deep Neural Networks" by Jinghui Chen, Quanquan Gu Adaptive gradient methods, which adopt historical gradient information to automatically adjust the learning rate, have been observed to generalize worse than stochastic gradient descent (SGD) with momentum in training deep neural networks. This leaves how to close the generalization gap of adaptive gradient methods an open problem. In this work, we show that adaptive gradient methods such as Adam, Amsgrad, are sometimes "over adapted". We design a new algorithm, called Partially adaptive momentum estimation method (Padam), which unifies the Adam/Amsgrad with SGD to achieve the best from both worlds. Experiments on standard benchmarks show that Padam can maintain fast convergence rate as Adam/Amsgrad while generalizing as well as SGD in training deep neural networks. These results would suggest practitioners pick up adaptive gradient methods once again for faster training of deep neural networks. Specifically for triplet-loss models, there are a number of tricks which can improve training time and generalization. See: In training a triplet network, I first have a solid drop in loss, but eventually the loss slowly but consistently increases. What could cause this? 6. Regularization Choosing and tuning network regularization is a key part of building a model that generalizes well (that is, a model that is not overfit to the training data). However, at the time that your network is struggling to decrease the loss on the training data -- when the network is not learning -- regularization can obscure what the problem is. When my network doesn't learn, I turn off all regularization and verify that the non-regularized network works correctly. Then I add each regularization piece back, and verify that each of those works along the way. This tactic can pinpoint where some regularization might be poorly set. Some examples are $L^2$ regularization (aka weight decay) or $L^1$ regularization is set too large, so the weights can't move. Two parts of regularization are in conflict. For example, it's widely observed that layer normalization and dropout are difficult to use together. Since either on its own is very useful, understanding how to use both is an active area of research. "Understanding the Disharmony between Dropout and Batch Normalization by Variance Shift" by Xiang Li, Shuo Chen, Xiaolin Hu, Jian Yang "Adjusting for Dropout Variance in Batch Normalization and Weight Initialization" by Dan Hendrycks, Kevin Gimpel. "Self-Normalizing Neural Networks" by Günter Klambauer, Thomas Unterthiner, Andreas Mayr and Sepp Hochreiter 7. Keep a Logbook of Experiments When I set up a neural network, I don't hard-code any parameter settings. Instead, I do that in a configuration file (e.g., JSON) that is read and used to populate network configuration details at runtime. I keep all of these configuration files. If I make any parameter modification, I make a new configuration file. Finally, I append as comments all of the per-epoch losses for training and validation. The reason that I'm so obsessive about retaining old results is that this makes it very easy to go back and review previous experiments. It also hedges against mistakenly repeating the same dead-end experiment. Psychologically, it also lets you look back and observe "Well, the project might not be where I want it to be today, but I am making progress compared to where I was $k$ weeks ago." As an example, I wanted to learn about LSTM language models, so I decided to make a Twitter bot that writes new tweets in response to other Twitter users. I worked on this in my free time, between grad school and my job. It took about a year, and I iterated over about 150 different models before getting to a model that did what I wanted: generate new English-language text that (sort of) makes sense. (One key sticking point, and part of the reason that it took so many attempts, is that it was not sufficient to simply get a low out-of-sample loss, since early low-loss models had managed to memorize the training data, so it was just reproducing germane blocks of text verbatim in reply to prompts -- it took some tweaking to make the model more spontaneous and still have low loss.)
https://api.stackexchange.com
I am trying to design a cloth that, from the point of view of a camera, is very difficult to compress with JPG, resulting in big-size files (or leading to low image quality if file size is fixed). It must work even if the cloth is far away from the camera, or rotated (let's say the scale can vary from 1x to 10x). Noise is quite good (hard to compress), but it becomes grey when looking from far, becoming easy to compress. A good pattern would be kind of fractal, looking similar at all scales. Foliage is better (leaves, tiny branches, small branches, big branches), but it uses too few colors. Here is a first try: I am sure there are more optimum patterns. Maybe hexagon or triangle tessellations would perform better. JPG uses the Y′ Cb Cr color space, I think Cb Cr can be generated in a similar way, but I guess it's better to not use uniformly the full scope of Y' (brightness) since camera will saturate the bright or dark areas (lighting is never perfect). QUESTION: What is the optimum cloth pattern for this problem?
Noise is quite good (hard to compress), but it becomes grey when looking from far, becoming easy to compress. A good pattern would be kind of fractal, looking similar at all scales. Well, there is fractal noise. I think Brownian noise is fractal, looking the same as you zoom into it. Wikipedia talks about adding Perlin noise to itself at different scales to produce fractal noise, which is maybe identical, I'm not sure: I don't think this would be hard to compress, though. Noise is hard for lossless compression, but JPEG is lossy, so it's just going to throw away the detail instead of struggling with it. I'm not sure if it's possible to make something "hard for JPEG to compress" since it will just ignore anything that's too hard to compress at that quality level. Something with hard edges at any scale would probably be better, like the infinite checkerboard plane: Also something with lots of colors. Maybe look at actual fractals instead of fractal noise. Maybe a Mondrian fractal? :)
https://api.stackexchange.com
Red-green colorblindness seems to make it harder for a hunter-gatherer to see whether a fruit is ripe and thus worth picking. Is there a reason why selection hasn't completely removed red-green color blindness? Are there circumstances where this trait provides an evolutionary benefit?
Short answer Color-blind subjects are better at detecting color-camouflaged objects. This may give color blinds an advantage in terms of spotting hidden dangers (predators) or finding camouflaged foods. Background There are two types of red-green blindness: protanopia (red-blind) and deuteranopia (green-blind), i.e., these people miss one type of cone, namely the (red L cone or the green M cone). These conditions should be set apart from the condition where there are mutations in the L cones shifting their sensitivity to the green cone spectrum (deuteranomaly) or vice versa (protanomaly). Since you are talking color-"blindness", as opposed to reduced sensitivity to red or green, I reckon you are asking about true dichromats, i.e., protanopes and deuteranopes. It's an excellent question as to why 2% of the men have either one condition, given that: Protanopes are more likely to confuse:- Black with many shades of red Dark brown with dark green, dark orange and dark red Some blues with some reds, purples and dark pinks Mid-greens with some oranges Deuteranopes are more likely to confuse:- Mid-reds with mid-greens Blue-greens with grey and mid-pinks Bright greens with yellows Pale pinks with light grey Mid-reds with mid-brown Light blues with lilac There are reports on the benefits of being red-green color blind under certain specific conditions. For example, Morgan et al. (1992) report that the identification of a target area with a different texture or orientation pattern was performed better by dichromats when the surfaces were painted with irrelevant colors. In other words, when color is simply a distractor and confuses the subject to focus on the task (i.e., texture or orientation discrimination), the lack of red-green color vision can actually be beneficial. This in turn could be interpreted as dichromatic vision being beneficial over trichromatic vision to detect color-camouflaged objects. Reports on improved foraging of dichromats under low-lighting are debated, but cannot be excluded. The better camouflage-breaking performance of dichromats is, however, an established phenomenon (Cain et al., 2010). During the Second World War it was suggested that color-deficient observers could often penetrate camouflage that deceived the normal observer. The idea has been a recurrent one, both with respect to military camouflage and with respect to the camouflage of the natural world (reviewed in Morgan et al. (1992) Outlines, rather than colors, are responsible for pattern recognition. In the military, colorblind snipers and spotters are highly valued for these reasons (source: De Paul University). If you sit back far from your screen, look at the normal full-color picture on the left and compare it to the dichromatic picture on the right; the picture on the right appears at higher contrast in trichromats, but dichromats may not see any difference between the two: Left: full-color image, right: dichromatic image. source: De Paul University However, I think the dichromat trait is simply not selected against strongly and this would explain its existence more easily than finding reasons it would be selected for (Morgan et al., 1992). References - Cain et al., Biol Lett (2010); 6, 3–38 - Morgan et al., Proc R Soc B (1992); 248: 291-5
https://api.stackexchange.com
TL:DR: Is it ever a good idea to train an ML model on all the data available before shipping it to production? Put another way, is it ever ok to train on all data available and not check if the model overfits, or get a final read of the expected performance of the model? Say I have a family of models parametrized by $\alpha$. I can do a search (e.g. a grid search) on $\alpha$ by, for example, running k-fold cross-validation for each candidate. The point of using cross-validation for choosing $\alpha$ is that I can check if a learned model $\beta_i$ for that particular $\alpha_i$ had e.g. overfit, by testing it on the "unseen data" in each CV iteration (a validation set). After iterating through all $\alpha_i$'s, I could then choose a model $\beta_{\alpha^*}$ learned for the parameters $\alpha^*$ that seemed to do best on the grid search, e.g. on average across all folds. Now, say that after model selection I would like to use all the the data that I have available in an attempt to ship the best possible model in production. For this, I could use the parameters $\alpha^*$ that I chose via grid search with cross-validation, and then, after training the model on the full ($F$) dataset, I would a get a single new learned model $\beta^{F}_{\alpha^*}$ The problem is that, if I use my entire dataset for training, I can't reliably check if this new learned model $\beta^{F}_{\alpha^*}$ overfits or how it may perform on unseen data. So is this at all good practice? What is a good way to think about this problem?
The way to think of cross-validation is as estimating the performance obtained using a method for building a model, rather than for estimating the performance of a model. If you use cross-validation to estimate the hyperparameters of a model (the $\alpha$s) and then use those hyper-parameters to fit a model to the whole dataset, then that is fine, provided that you recognise that the cross-validation estimate of performance is likely to be (possibly substantially) optimistically biased. This is because part of the model (the hyper-parameters) have been selected to minimise the cross-validation performance, so if the cross-validation statistic has a non-zero variance (and it will) there is the possibility of over-fitting the model selection criterion. If you want to choose the hyper-parameters and estimate the performance of the resulting model then you need to perform a nested cross-validation, where the outer cross-validation is used to assess the performance of the model, and in each fold cross-validation is used to determine the hyper-parameters separately in each fold. You build the final model by using cross-validation on the whole set to choose the hyper-parameters and then build the classifier on the whole dataset using the optimized hyper-parameters. This is of course computationally expensive, but worth it as the bias introduced by improper performance estimation can be large. See my paper G. C. Cawley and N. L. C. Talbot, Over-fitting in model selection and subsequent selection bias in performance evaluation, Journal of Machine Learning Research, 2010. Research, vol. 11, pp. 2079-2107, July 2010. ( pdf) However, it is still possible to have over-fitting in model selection (nested cross-validation just allows you to test for it). A method I have found useful is to add a regularisation term to the cross-validation error that penalises hyper-parameter values likely to result in overly-complex models, see G. C. Cawley and N. L. C. Talbot, Preventing over-fitting in model selection via Bayesian regularisation of the hyper-parameters, Journal of Machine Learning Research, volume 8, pages 841-861, April 2007. ( So the answers to your question are (i) yes, you should use the full dataset to produce your final model as the more data you use the more likely it is to generalise well but (ii) make sure you obtain an unbiased performance estimate via nested cross-validation and potentially consider penalising the cross-validation statistic to further avoid over-fitting in model selection.
https://api.stackexchange.com
A diode is put in parallel with a relay coil (with opposite polarity) to prevent damage to other components when the relay is turned off. Here's an example schematic I found online: I'm planning on using a relay with a coil voltage of 5V and contact rating of 10A. How do I determine the required specifications for the diode, such as voltage, current, and switching time?
First determine the coil current when the coil is on. This is the current that will flow through the diode when the coil is switched off. In your relay, the coil current is shown as 79.4 mA. Specify a diode for at least 79.4 mA current. In your case, a 1N4001 current rating far exceeds the requirement. The diode reverse voltage rating should be at least the voltage applied to the relay coil. Normally a designer puts in plenty of reserve in the reverse rating. A diode in your application having 50 volts would be more than adequate. Again 1N4001 will do the job. Additionally, the 1N4007 (in single purchase quantities) costs the same but has 1000 volt rating.
https://api.stackexchange.com
Sometimes men wake up with an erection in the morning. Why does this happen?
Sometimes men wake up with an erection in the morning. Why does this happen? Shortly speaking: REM (Rapid Eye Movement) is one phase of sleep. During this phase, we dream and some of our neurotransmitters are shut off. This include norepinephrine, which is involved in controlling erections. Norepinephrine prevents blood from entering the penis (preventing the erection). In absence of norepinephrine—during REM phase norepinephrine is absent—blood enters the penis, leading to an erection. This phenomenon is called nocturnal penile tumescence. Such erections typically occur 3 to 5 times a night. A related question concerning similar erections in women can be found here. High pressure in the bladder may also lead to a "reflex erection". This erection allows for preventing uncontrolled urination. The drawback is that when in the morning one has an erection and can't wait to pee it might get hard to accurately target the toilets! This video is also a nice and easy source of information on the subject. Is it bad? (Reading my "note" below, you have edited your post to get rid of this question, thank you) It is perfectly healthy you don't have to worry about that. These erections are even thought of as contributing to penile health. At the opposite end of the spectrum, the absence of erections during the nights are an index of Erectile Dysfunction (E.D.). Note Be aware that medical questions are often considered off-topic on this site. Asking "is it bad?" turns your question into a medical one. Health-related questions (but not personal health) should be asked on health.SE
https://api.stackexchange.com
Does anyone have recommendations on a usable, fast C++ matrix library? What I mean by usable is the following: Matrix objects have an intuitive interface (ex.: I can use rows and columns while indexing) I can do anything with the matrix class that I can do with LAPACK and BLAS Easy to learn and use API Relatively painless to install in Linux (I use Ubuntu 11.04 right now) To me, usability is more important than speed or memory usage right now, to avoid premature optimization. In writing the code, I could always use 1-D arrays (or STL vectors) and proper index or pointer arithmetic to emulate a matrix, but I'd prefer not to in order to avoid bugs. I'd also like to focus my mental effort on the actual problem I'm trying to solve and program into the problem domain, rather than use part of my finite attention to remember all of the little programming tricks I used to emulate matrices as arrays, and remember LAPACK commands, et cetera. Plus, the less code I have to write, and the more standardized it is, the better. Dense versus sparse doesn't matter yet; some of the matrices I am dealing with will be sparse, but not all of them. However, if a particular package handles dense or sparse matrices well, it is worth mentioning. Templating doesn't matter much to me either, since I'll be working with standard numeric types and don't need to store anything other than doubles, floats, or ints. It's nice, but not necessary for what I'd like to do.
I've gathered the following from online research so far: I've used Armadillo a little bit, and found the interface to be intuitive enough, and it was easy to locate binary packages for Ubuntu (and I'm assuming other Linux distros). I haven't compiled it from source, but my hope is that it wouldn't be too difficult. It meets most of my design criteria, and uses dense linear algebra. It can call LAPACK or MKL routines. There generally is no need to compile Armadillo, it is a purely template-based library: You just include the header and link to BLAS/LAPACK or MKL etc. I've heard good things about Eigen, but haven't used it. It claims to be fast, uses templating, and supports dense linear algebra. It doesn't have LAPACK or BLAS as a dependency, but appears to be able to do everything that LAPACK can do (plus some things LAPACK can't). A lot of projects use Eigen, which is promising. It has a binary package for Ubuntu, but as a header-only library it's trivial to use elsewhere too. The Matrix Template Library version 4 also looks promising, and uses templating. It supports both dense and sparse linear algebra, and can call UMFPACK as a sparse solver. The features are somewhat unclear from their website. It has a binary package for Ubuntu, downloadable from their web site. PETSc, written by a team at Argonne National Laboratory, has access to sparse and dense linear solvers, so I'm presuming that it can function as a matrix library. It's written in C, but has C++ bindings, I think (and even if it didn't, calling C from C++ is no problem). The documentation is incredibly thorough. The package is a bit overkill for what I want to do now (matrix multiplication and indexing to set up mixed-integer linear programs), but could be useful as a matrix format for me in the future, or for other people who have different needs than I do. Trilinos, written by a team at Sandia National Laboratory, provides object-oriented C++ interfaces for dense and sparse matrices through its Epetra component, and templated interfaces for dense and sparse matrices through its Tpetra component. It also has components that provide linear solver and eigensolver functionality. The documentation does not seem to be as polished or prominent as PETSc; Trilinos seems like the Sandia analog of PETSc. PETSc can call some of the Trilinos solvers. Binaries for Trilinos are available for Linux. Blitz is a C++ object-oriented library that has Linux binaries. It doesn't seem to be actively maintained (2012-06-29: a new version has just appeared yesterday!), although the mailing list is active, so there is some community that uses it. It doesn't appear to do much in the way of numerical linear algebra beyond BLAS, and looks like a dense matrix library. It uses templates. Boost::uBLAS is a C++ object-oriented library and part of the Boost project. It supports templating and dense numerical linear algebra. I've heard it's not particularly fast. The Template Numerical Toolkit is a C++ object-oriented library developed by NIST. Its author, Roldan Pozo, seems to contribute patches occasionally, but it doesn't seem to be under active development any longer (last update was 2010). It focuses on dense linear algebra, and provides interfaces for some basic matrix decompositions and an eigenvalue solver. Elemental, developed by Jack Poulson, is a distributed memory (parallel) dense linear algebra software package written in a style similar to FLAME. For a list of features and background on the project, see his documentation. FLAME itself has an associated library for sequential and shared-memory dense linear algebra, called libflame, which appears to be written in object-oriented C. Libflame looks a lot like LAPACK, but with better notation underlying the algorithms to make development of fast numerical linear algebra libraries more of a science and less of a black art. There are other libraries that can be added to the list; if we're counting sparse linear algebra packages as "matrix libraries", the best free one I know of in C is SuiteSparse, which is programmed in object-oriented style. I've used SuiteSparse and found it fairly easy to pick up; it depends on BLAS and LAPACK for some of the algorithms that decompose sparse problems into lots of small, dense linear algebra subproblems. The lead author of the package, Tim Davis, is incredibly helpful and a great all-around guy. The Harwell Subroutine Libraries are famous for their sparse linear algebra routines, and are free for academic users, though you have to go through this process of filling out a form and receiving an e-mail for each file that you want to download. Since the subroutines often have dependencies, using one solver might require downloading five or six files, and the process can get somewhat tedious, especially since the form approval is not instantaneous. There are also other sparse linear algebra solvers, but as far as I can tell, MUMPS and other packages are focused mostly on the solution of linear systems, and solving linear systems is the least of my concerns right now. (Maybe later, I will need that functionality, and it could be useful for others.)
https://api.stackexchange.com
What the difference between TPM and CPM when dealing with RNA seq data? What metrics would you use if you have to perform some down stream analysis other than Differential expression for eg. Clustering analysis using Hclust function and then plotting heat map to find differences in terms of expression levels, correlation and pca Is it wrong to use TPM for such analysis, if yes then when does one use TPM versus CPM.
You can find the various equations in this oft-cited blog post from Harold Pimentel. CPM is basically depth-normalized counts, whereas TPM is length-normalized (and then normalized by the length-normalized values of the other genes). If one has to choose between those two choices one typically chooses TPM for most things, since generally the length normalization is handy. Realistically, you probably want log(TPM) since otherwise noise in your most highly expressed genes dominates over small expression signals.
https://api.stackexchange.com
My textbook mentions that SCUBA tanks often contain a mixture of oxygen and nitrogen along with a little helium which serves as a diluent. Now as I remember it, divers take care not to surface too quickly because it results in 'the Bends', which involves the formation of nitrogen bubbles in the blood and is potentially fatal. If that's the case, why not use pure oxygen gas in SCUBA tanks? It seems like a good idea since it would a) Enable divers to stay underwater for longer periods of time (I keep hearing that ordinary SCUBA tanks only give divers a pathetic hour or so of time underwater. b) Possibly eliminate the chances of developing 'the Bends' upon surfacing. Well, it seems plausible, that is if the diver were to take a 10 minute deep-breathing session with pure oxygen to flush out whatever nitrogen's there in his lungs before hooking up a cylinder of pure oxygen and going for a dive. So if there's no gaseous nitrogen in his lungs and blood, then he wouldn't have to worry about nitrogen bubbles developing in his system. Now those two possible advantages aren't hard to overlook, but since no one fills SCUBA tanks with pure oxygen, there must be some reason that I've overlooked, that discourages divers from filling the tanks with pure oxygen. So what is it? Also, I hear that the oxygen cylinders used in hospitals have very high concentrations of oxygen; heck, there's one method of treatment called the Hyperbaric Oxygen Therapy (HBOT) where they give patients 100% pure oxygen at elevated pressures. Hence I doubt whether the increase in pressure associated with diving is the problem here. So I reiterate: Why is it a bad idea for divers to breathe pure oxygen underwater? I guess most of the recent answers have kinda missed a main point, so I'll rephrase the question: Why is it a bad idea for divers to breathe pure oxygen underwater? If it is indeed due to pressure considerations as most sources claim, then why doesn't it seem to be a problem when patients are given 100% pure oxygen in cases like the HBOT (which is performed at elevated pressures) ?
The other answers here, describing oxygen toxicity are telling what can go wrong if you have too much oxygen, but they are not describing two important concepts that should appear with their descriptions. Also, there is a basic safety issue with handling pressure tanks of high oxygen fraction. An important property of breathed oxygen is its partial pressure. At normal conditions at sea level, the partial pressure of oxygen is about 0.21 atm. This is compatible with the widely known estimate that the atmosphere is about 78% nitrogen, 21% oxygen, and 1% "other". Partial pressures are added to give total pressure; this is Dalton's Law. As long as you don't use toxic gasses, you can replace the nitrogen and "other" with other gasses, like Helium, as long as you keep the partial pressure of oxygen near 0.21, and breathe the resulting mixtures without adverse effects. There are two hazards that can be understood by considering the partial pressure of oxygen. If the partial pressure drops below about 0.16 atm, a normal person experiences hypoxia. This can happen by entering a room where oxygen has been removed. For instance, entering a room which has a constant source of nitrogen constantly displacing the room air, lowering the concentration -- and partial pressure -- of oxygen. Another way is to go to the tops of tall mountains. The total atmospheric pressure is lowered and the partial pressure of oxygen can be as low as 0.07 atm (summit of Mt. Everest) which is why very high altitude climbing requires carrying additional oxygen. Yet a third way is "horsing around" with Helium tanks -- repeatedly inhaling helium to produce very high pitched voices deprives the body of oxygen and the partial pressure of dissolved oxygen in the body falls, perhaps leading to loss of consciousness. Alternatively, if the partial pressure rises above about 1.4 atm, a normal person experiences hyperoxia which can lead to oxygen toxicity (described in the other answers). At 1.6 atm the risk of central nervous system oxygen toxicity is very high. So, don't regulate the pressure that high? There's a problem. If you were to make a 10-foot long snorkel and dive to the bottom of a swimming pool to use it, you would fail to inhale. The pressure of air at your mouth would be about 1 atm, because the 10-foot column of air in the snorkel doesn't weigh very much. The pressure of water trying to squeeze the air out of you (like a tube of toothpaste) is about 1.3 atm. Your diaphragm is not strong enough to overcome the squeezing and fill your lungs with air. Divers overcome this problem by using a regulator (specifically, a demand valve), which allows the gas pressure at the outlet to be very near that of the ambient pressure. The principle job of the regulator is to reduce the very high pressure inside the tank to a much lower pressure at the outlet. The demand valve tries to only supply gas when the diver inhales and tries to supply it at very nearly ambient pressure. Notice that at depth the ambient pressure can be much greater than 1 atm, increasing by about 1 atm per 10 m (or 33 feet). If the regulator were to supply normal air at 2 atm pressure, the partial pressure of oxygen would be 0.42 atm. If at 3 atm, 0.63 atm. So as a diver descends, the partial pressure of oxygen automatically increases as a consequence of having to increase the gas pressure to allow the diver to inflate their lungs. Around 65 m (220 ft), the partial pressure of oxygen in an "air mix" would be high enough to risk hyperoxia and other dangerous consequences. Now imagine a gas cylinder containing 100% oxygen. If we breathe from it at the surface, the partial pressure of oxygen is 1 atm -- high, but not dangerous. At a depth of 10 m, the partial pressure of supplied oxygen is 2 atm -- exceeding acceptable exposure limits. This is a general pattern -- raising the oxygen fraction of diving gasses decreases the maximum diving depth. And you can't lower the partial pressure much because the lower limit, 0.16 atm, isn't that much lower than the 0.21 atm of sea level atmosphere. One general category of solutions is to change gas mixes at various depths. This is complicated, requires a great deal of planning, and is outside the scope of your question. But it is certainly not as straightforward as just simplifying the gas mixtures or just raising the partial pressure of oxygen. Additionally, compressed oxygen is a relatively annoying gas to work with. It is not itself flammable, but it makes every nearby organic thing flammable. For instance using grease or oil on or near an oxygen fitting risks spontaneously igniting the grease or oil. Merely having grease on your hand while handling oxygen refilling gear (with a small leak) can burn your hand.
https://api.stackexchange.com
Does anyone know of a freeware SPICE / circuit simulator? SPICE (Simulation Program with Integrated Circuit Emphasis) is a general-purpose, open source analog electronic circuit simulator. It is a powerful program that is used in integrated circuit and board-level design to check the integrity of circuit designs and to predict circuit behavior. Wikipedia
ngSpice is available for gEDA. gnuCAP is also available for gEDA. LTSpice is free from Linear Technology. I thought that one of the other analog chip makers had a spice too but I can't remember who :( I have been to a few talks on simulation given by physicists and EEs who have done chip design. Each of the talks seems to end like this --- Except for simple circuits you will spend most of your time getting models and determining where the models need to be modified for your application. Unless you are doing work for an IC manufacturer the manufacturer will not give you detailed models. You will not be able to avoid a prototype. You should only simulate subsections of your design. Simulating the entire design is not usually practical. Also most of the free simulators are not distributed with models. Re-distribution of the models is usually a copyright violation. LTspice is distributed with models of the Linear Tech parts. I am not sure the quality of the models. Most manufacturers do not want to reveal too many details about their process.
https://api.stackexchange.com
The sensitive plant (Mimosa pudica) is a remarkable little plant whose characteristic feature is its ability to droop its leaves when disturbed: Apparently, this ability to droop rests on the cells in the leaves of the sensitive plant being able to draw water out of themselves through changes in intracellular ion concentrations, which makes the leaves less turgid. What I'm hazy about is how the plant "senses" vibrations. Plants don't really have a nervous system to speak of; how then does the sensitive plant "know" to droop when disturbed?
In fact, the idea of a plant nervous system is quite serious and constantly developing; of course those are rather local, simple signal pathways rather than an "animalian" centralized global network, but they use similar mechanisms -- depolarisation waves, neurotransmitter-like compounds, specialized cells... Here is a review paper by Brenner et al. In the case of Mimosa, there is a good paper summing up Takao Sibaoka's long research of the topic. In short, it seems that its petioles' phloem has cells which have polarized membranes and can trigger depolarization due to a mechanical stimulation. The signal then propagates to the corresponding pulvinus by a mixture of electrical and Cl- depolarization waves. In the pulvinus, this signal triggers a second depolarization which coordinates the pulvinus' cells to trigger water pumping responsible for the leaf drop. The transmission to the adjacent leaves is most likely mechanical, i.e. the movement of one dropping leaf excites another. References: Brenner ED, Stahlberg R, Mancuso S, Vivanco J, Baluska F, Van Volkenburgh E. 2006. Plant neurobiology: an integrated view of plant signaling. Trends in plant science 11: 413–9. Sibaoka T. 1991. Rapid plant movements triggered by action potentials. The Botanical Magazine Tokyo 104: 73–95.
https://api.stackexchange.com
For a molecule to have a smell it's necessary that the molecule be volatile enough to be in the air. So I think that excludes molecules which are solid at room temperature and atmospheric pressure. Maybe the question then is equivalent to: what is the highest molecular weight organic compound which is liquid at room temperature and atmospheric pressure?
I'll quote from $\ce{[1]}$: The general requirements for an odorant are that it should be volatile, hydrophobic and have a molecular weight less than approximately 300 daltons. Ohloff (1994) has stated that the largest known odorant is a labdane with a molecular weight of 296. The first two requirements make physical sense, for the molecule has to reach the nose and may need to cross membranes. The size requirement appears to be a biological constraint. To be sure, vapor pressure (volatility) falls rapidly with molecular size, but that cannot be the reason why larger molecules have no smell, since some of the strongest odorants (e.g. some steroids) are large molecules. In addition, the cut-off is very sharp indeed: for example, substitution of the slightly larger silicon atom for a carbon in a benzenoid musk causes it to become odorless (Wrobel and Wannagat, 1982d). A further indication that the size limit has something to do with the chemoreception mechanism comes from the fact that specific anosmias become more frequent as molecular size increases. At the “ragged edge” of the size limit, subjects become anosmic to large numbers of molecules. An informal poll among perfumers, for example has elicited the fact that most of them are completely anosmic to one or more musks (e.g. Galaxolide® mw 244.38) or, less commonly, ambergris odorants such as Ambrox®, or the larger esters of salicylic acid. One can probably infer from this that the receptors cannot accommodate molecules larger than a certain size, and that this size is genetically determined (Whissel-Buechy and Amoore, 1973) and varies from individual to individual. N.B.: Labdane's molecular formula is $\ce{C20H38}$, which gives a molecular weight (MW) of $\pu{278.5 Da}$ (Da). $\ce{[5]}$ Thus either the $\pu{296 Da}$ value is a typo, or the authors were quoting the MW of a labdane derivative. Note added in response to answer posted by John Cuthbert (which was a nice find!): While iodoform, at $\pu{394 Da}$, does indeed exceed the $\pu{>300 Da}$ "general requirement" provided above by Turin & Yoshii, a comparison of its estimated density to that of, e.g., labdane, indicates it's a much smaller molecule (iodoform's three iodine atoms add a lot of mass without a lot of size, at least relative to carbon, hydrogen, and oxygen): I couldn't find labdane's density, but I found the density of one of its diols (i.e., labdane with an $\text{–OH}$ substituted for $\text{–H}$ in two places). So if we use its density, along with labane's molecular weight, we obtain: $\pu{MW = 278.5 Da}$, $\pu{\rho = 0.9 g/cm^3}$ $\ce{[6]}$ => estimated molecular volume ≈ $\pu{510 Å^3}$ Iodoform: $\pu{MW = 393.732 Da}$, $\pu{\rho = 4.008 g/cm^3}$ $\ce{[7]}$ => estimated molecular volume ≈ $\pu{160 Å^3}$ Even if the density of labdane were, say, 20% higher than that of the diol, we'd get a molecular volume of ≈ $\pu{430 Å^3}$, which is still far above that of iodoform. This makes it clear that the limiting attribute is physical size rather than molecular weight, and that Turin & Yoshii were using molecular weight as a shorthand surrogate for size. This works reasonably well when comparing oxygenated hydrocarbons, but obviously breaks down when the compounds contain significantly heavier nuclei. As Turin & Yoshii write more precisely at the end of the quoted passage: "One can probably infer from this that the receptors cannot accommodate molecules larger than a certain size." [Emphasis mine.] References $\ce{[1]}$: "Structure-odor relationships: a modern perspective", by Luca Turin (Dept of Physiology, University College London, UK) and Fumiko Yoshii (Graduate School of Science and Technology, Niigata University, Japan), which appears as chapter 13 of: Handbook of Olfaction and Gustation. Richard L. Doty (ed.). 2nd ed., Marcel Dekker, 2003. $\ce{[2]}$: Ohloff, G. Scent and fragrances: the fascination of odors and their chemical perspectives. Berlin, Springer, 1994. $\ce{[3]}$: Wrobel D, Wannagat U. SILA PERFUMES. 2. SILALINALOOL. Chemischer Informationsdienst. 13(30), Jul 27, 1982. $\ce{[4]}$: Whissell-Buechy D, Amoore JE. Letter: Odour-blindness to musk: simple recessive inheritance. Nature, 245(5421):157-8, Sep 21, 1973. $\ce{[5]}$: $\ce{[6]}$: $\ce{[7]}$:
https://api.stackexchange.com
In single-cell RNA-seq data we have an inflated number of 0 (or near-zero) counts due to low mRNA capture rate and other inefficiencies. How can we decide which genes are 0 due to gene dropout (lack of measurement sensitivity), and which are genuinely not expressed in the cell? Deeper sequencing does not solve this problem as shown on the below saturation curve of 10x Chromium data: Also see Hicks et al. (2017) for a discussion of the problem: Zero can arise in two ways: the gene was not expressing any RNA (referred to as structural zeros) or the RNA in the cell was not detected due to limitations of current experimental protocols (referred to as dropouts)
Actually this is one of the main problems you have when analyzing scRNA-seq data, and there is no established method for dealing with this. Different (dedicated) algorithms deal with it in different ways, but mostly you rely on how good the error modelling of your software is (a great read is the review by Wagner, Regev & Yosef, esp. the section on "False negatives and overamplification"). There are a couple of options: You can impute values, i.e. fill in the gaps on technical zeros. CIDR and scImpute do it directly. MAGIC and ZIFA project cells into a lower-dimensional space and use their similarity there to decide how to fill in the blanks. Some people straight up exclude genes that are expressed in very low numbers. I can't give you citations off the top of my head, but many trajectory inference algorithms like monocle2 and SLICER have heuristics to choose informative genes for their analysis. If the method you use for analysis doesn't model gene expression explicitly but uses some other distance method to quantify similarity between cells (like cosine distance, euclidean distance, correlation), then the noise introduced by dropout can be covered by the signal of genes that are highly expressed. Note that this is dangerous, as genes that are highly expressed are not necessarily informative. ERCC spike ins can help you reduce technical noise, but I am not familiar with the Chromium protocol so maybe it doesn't apply there (?) since we are speaking about noise, you might consider using a protocol with unique molecular identifiers. They remove the amplification errors almost completely, at least for the transcripts that you capture... EDIT: Also, I would highly recommend using something more advanced than PCA to do the analysis. Software like the above-mentioned Monocle or destiny is easy to operate and increases the power of your analysis considerably.
https://api.stackexchange.com
I've just finished a Classical Mechanics course, and looking back on it some things are not quite clear. In the first half we covered the Lagrangian formalism, which I thought was pretty cool. I specially appreciated the freedom you have when choosing coordinates, and the fact that you can basically ignore constraint forces. Of course, most simple situations you can solve using good old $F=ma$, but for more complicated stuff the whole formalism comes in pretty handy. Then in the second half we switched to Hamiltonian mechanics, and that's where I began to lose sight of why we were doing things the way we were. I don't have any problem understanding the Hamiltonian, or Hamilton's equations, or the Hamilton-Jacobi equation, or what have you. My issue is that I don't understand why would someone bother developing all this to do the same things you did before but in a different way. In fact, in most cases you need to start with a Lagrangian and get the momenta from $p = \frac{\partial L}{\partial \dot{q}}$, and the Hamiltonian from $H = \sum \dot{q_i}p_i - L$. But if you already have the Lagrangian, why not just solve the Euler-Lagrange equations? I guess maybe there are interesting uses of the Hamiltion formalism and we just didn't do a whole lot of examples (it was the harmonic oscillator the whole way, pretty much). I've also heard that it allows a somewhat smooth transition into quantum mechanics. We did work out a way to get Schrödinger's equation doing stuff with the action. But still something's not clicking. My questions are the following: Why do people use the Hamiltonian formalism? Is it better for theoretical work? Are there problems that are more easily solved using Hamilton's mechanics instead of Lagrange's? What are some examples of that?
There are several reasons for using the Hamiltonian formalism: Statistical physics. The standard thermal states weight of pure states is given according to $$\text{Prob}(\text{state}) \propto e^{-H(\text{state})/k_BT}$$ So you need to understand Hamiltonians to do stat mech in real generality. Geometrical prettiness. Hamilton's equations say that flowing in time is equivalent to flowing along a vector field on phase space. This gives a nice geometrical picture of how time evolution works in such systems. People use this framework a lot in dynamical systems, where they study questions like 'is the time evolution chaotic?'. The generalization to quantum physics. The basic formalism of quantum mechanics (states and observables) is an obvious generalization of the Hamiltonian formalism. It's less obvious how it's connected to the Lagrangian formalism, and way less obvious how it's connected to the Newtonian formalism. [Edit in response to a comment:] This might be too brief, but the basic story goes as follows: In Hamiltonian mechanics, observables are elements of a commutative algebra which carries a Poisson bracket $\{\cdot,\cdot\}$. The algebra of observables has a distinguished element, the Hamiltonian, which defines the time evolution via $d\mathcal{O}/dt = \{\mathcal{O},H\}$. Thermal states are simply linear functions on this algebra. (The observables are realized as functions on the phase space, and the bracket comes from the symplectic structure there. But the algebra of observables is what matters: You can recover the phase space from the algebra of functions.) On the other hand, in quantum physics, we have an algebra of observables which is not commutative. But it still has a bracket $\{\cdot,\cdot\} = -\frac{i}{\hbar}[\cdot,\cdot]$ (the commutator), and it still gets its time evolution from a distinguished element $H$, via $d\mathcal{O}/dt = \{\mathcal{O},H\}$. Likewise, thermal states are still linear functionals on the algebra.
https://api.stackexchange.com
In evaluating the quality of a piece of software you are about to use (whether it's something you wrote or a canned package) in computational work, it is often a good idea to see how well it works on standard data sets or problems. Where might one obtain these tests for verifying computational routines? (One website/book per answer, please.)
If you are interested in conducting an analysis on sparse matrices, I would also consider Davis's University of Florida Sparse Matrix Collection and the Matrix Market.
https://api.stackexchange.com
I haven't yet gotten a good answer to this: If you have two rays of light of the same wavelength and polarization (just to make it simple for now, but it easily generalizes to any range and all polarizations) meet at a point such that they're 180 degrees out of phase (due to path length difference, or whatever), we all know they interfere destructively, and a detector at exactly that point wouldn't read anything. So my question is, since such an insanely huge number of photons are coming out of the sun constantly, why isn't any photon hitting a detector matched up with another photon that happens to be exactly out of phase with it? If you have an enormous number of randomly produced photons traveling random distances (with respect to their wavelength, anyway), that seems like it would happen, similar to the way that the sum of a huge number of randomly selected 1's and -1's would never stray far from 0. Mathematically, it would be: $$\int_0 ^{2\pi} e^{i \phi} d\phi = 0$$ Of course, the same would happen for a given polarization, and any given wavelength. I'm pretty sure I see the sun though, so I suspect something with my assumption that there are effectively an infinite number of photons hitting a given spot is flawed... are they locally in phase or something?
First let's deal with a false assumption: similar to the way that the sum of a huge number of randomly selected 1's and -1's would never stray far from 0. Suppose we have a set of $N$ random variables $X_i$, each independent and with equal probability of being either $+1$ or $-1$. Define $$ S = \sum_{i=1}^N X_i. $$ Then, yes, the expectation of $S$ may be $0$, $$ \langle S \rangle = \sum_{i=1}^N \langle X_i \rangle = \sum_{i=1}^N \left(\frac{1}{2}(+1) + \frac{1}{2}(-1)\right) = 0, $$ but the fluctuations can be significant. Since we can write $$ S^2 = \sum_{i=1}^N X_i^2 + 2 \sum_{i=1}^N \sum_{j=i+1}^N X_i X_j, $$ then more manipulation of expectation values (remember, they always distribute over sums; also the expectation of a product is the product of the expectations if and only if the factors are independent, which is the case for us for $i \neq j$) yields $$ \langle S^2 \rangle = \sum_{i=1}^N \langle X_i^2 \rangle + 2 \sum_{i=1}^N \sum_{j=i+1}^N \langle X_i X_j \rangle = \sum_{i=1}^N \left(\frac{1}{2}(+1)^2 + \frac{1}{2}(-1)^2\right) + 2 \sum_{i=1}^N \sum_{j=i+1}^N (0) (0) = N. $$ The standard deviation will be $$ \sigma_S = \left(\langle S^2 \rangle - \langle S \rangle^2\right)^{1/2} = \sqrt{N}. $$ This can be arbitrarily large. Another way of looking at this is that the more coins you flip, the less likely you are to be within a fixed range of breaking even. Now let's apply this to the slightly more advanced case of independent phases of photons. Suppose we have $N$ independent photons with phases $\phi_i$ uniformly distributed on $(0, 2\pi)$. For simplicity I will assume all the photons have the same amplitude, set to unity. Then the electric field will have strength $$ E = \sum_{i=1}^N \mathrm{e}^{\mathrm{i}\phi_i}. $$ Sure enough, the average electric field will be $0$: $$ \langle E \rangle = \sum_{i=1}^N \langle \mathrm{e}^{\mathrm{i}\phi_i} \rangle = \sum_{i=1}^N \frac{1}{2\pi} \int_0^{2\pi} \mathrm{e}^{\mathrm{i}\phi}\ \mathrm{d}\phi = \sum_{i=1}^N 0 = 0. $$ However, you see images not in electric field strength but in intensity, which is the square-magnitude of this: $$ I = \lvert E \rvert^2 = \sum_{i=1}^N \mathrm{e}^{\mathrm{i}\phi_i} \mathrm{e}^{-\mathrm{i}\phi_i} + \sum_{i=1}^N \sum_{j=i+1}^N \left(\mathrm{e}^{\mathrm{i}\phi_i} \mathrm{e}^{-\mathrm{i}\phi_j} + \mathrm{e}^{-\mathrm{i}\phi_i} \mathrm{e}^{\mathrm{i}\phi_j}\right) = N + 2 \sum_{i=1}^N \sum_{j=i+1}^N \cos(\phi_i-\phi_j). $$ Paralleling the computation above, we have $$ \langle I \rangle = \langle N \rangle + 2 \sum_{i=1}^N \sum_{j=i+1}^N \frac{1}{(2\pi)^2} \int_0^{2\pi}\!\!\int_0^{2\pi} \cos(\phi-\phi')\ \mathrm{d}\phi\ \mathrm{d}\phi' = N + 0 = N. $$ The more photons there are, the greater the intensity, even though there will be more cancellations. So what does this mean physically? The Sun is an incoherent source, meaning the photons coming from its surface really are independent in phase, so the above calculations are appropriate. This is in contrast to a laser, where the phases have a very tight relation to one another (they are all the same). Your eye (or rather each receptor in your eye) has an extended volume over which it is sensitive to light, and it integrates whatever fluctuations occur over an extended time (which you know to be longer than, say, $1/60$ of a second, given that most people don't notice faster refresh rates on monitors). In this volume over this time, there will be some average number of photons. Even if the volume is small enough such that all opposite-phase photons will cancel (obviously two spatially separated photons won't cancel no matter their phases), the intensity of the photon field is expected to be nonzero. In fact, we can put some numbers to this. Take a typical cone in your eye to have a diameter of $2\ \mathrm{µm}$, as per Wikipedia. About $10\%$ of the Sun's $1400\ \mathrm{W/m^2}$ flux is in the $500\text{–}600\ \mathrm{nm}$ range, where the typical photon energy is $3.6\times10^{-19}\ \mathrm{J}$. Neglecting the effects of focusing among other things, the number of photons in play in a single receptor is something like $$ N \approx \frac{\pi (1\ \mathrm{µm})^2 (140\ \mathrm{W/m^2}) (0.02\ \mathrm{s})}{3.6\times10^{-19}\ \mathrm{J}} \approx 2\times10^7. $$ The fractional change in intensity from "frame to frame" or "pixel to pixel" in your vision would be something like $1/\sqrt{N} \approx 0.02\%$. Even give or take a few orders of magnitude, you can see that the Sun should shine steadily and uniformly.
https://api.stackexchange.com
A few years ago, MapReduce was hailed as revolution of distributed programming. There have also been critics but by and large there was an enthusiastic hype. It even got patented! [1] The name is reminiscent of map and reduce in functional programming, but when I read (Wikipedia) Map step: The master node takes the input, divides it into smaller sub-problems, and distributes them to worker nodes. A worker node may do this again in turn, leading to a multi-level tree structure. The worker node processes the smaller problem, and passes the answer back to its master node. Reduce step: The master node then collects the answers to all the sub-problems and combines them in some way to form the output – the answer to the problem it was originally trying to solve. or [2] Internals of MAP: [...] MAP splits up the input value into words. [...] MAP is meant to associate each given key/value pair of the input with potentially many intermediate key/value pairs. Internals of REDUCE: [...] [REDUCE] performs imperative aggregation (say, reduction): take many values, and reduce them to a single value. I can not help but think: this is divide & conquer (in the sense of Mergesort), plain and simple! So, is there (conceptual) novelty in MapReduce somewhere, or is it just a new implementation of old ideas useful in certain scenarios? US Patent 7,650,331: "System and method for efficient large-scale data processing " (2010) Google’s MapReduce programming model — Revisited by R. Lämmel (2007)
I can not help but think: this is divide & conquer, plain and simple! M/R is not divide & conquer. It does not involve the repeated application of an algorithm to a smaller subset of the previous input. It's a pipeline (a function specified as a composition of simpler functions) where pipeline stages are alternating map and reduce operations. Different stages can perform different operations. So, is there (conceptual) novelty in MapReduce somewhere, or is it just a new implementation of old ideas useful in certain scenarios? MapReduce does not break new ground in the theory of computation -- it does not show a new way of decomposing a problem into simpler operations. It does show that particular simpler operations are practical for a particular class of problem. The MapReduce paper's contribution was evaluating a pipeline of two well understood orthogonal operators that can be distributed efficiently and fault-tolerantly on a particular problem: creating a text index of large corpus benchmarking map-reduce on that problem to show how much data is transferred between nodes and how latency differences in stages affect overall latency showing how to make the system fault tolerant so machine failures during computation can be compensated for automatically identifying specific useful implementation choices and optimizations Some of the critiques fall into these classes: "Map/reduce does not break new ground in theory of computation." True. The original paper's contribution was that these well-understood operators with a specific set of optimizations had been successfully used to solve real problems more easily and fault-tolerantly than one-off solutions. "This distributed computation doesn't easily decompose into map & reduce operations". Fair enough, but many do. "A pipeline of n map/reduce stages require latency proportional to the number of reduce steps of the pipeline before any results are produced." Probably true. The reduce operator does have to receive all its input before it can produce a complete output. "Map/reduce is overkill for this use-case." Maybe. When engineers find a shiny new hammer, they tend to go looking for anything that looks like a nail. That doesn't mean that the hammer isn't a well-made tool for a certain niche. "Map/reduce is a poor replacement for a relational DB." True. If a relational DB scales to your data-set then wonderful for you -- you have options.
https://api.stackexchange.com
I've implemented a gaussian blur fragment shader in GLSL. I understand the main concepts behind all of it: convolution, separation of x and y using linearity, multiple passes to increase radius... I still have a few questions though: What's the relationship between sigma and radius? I've read that sigma is equivalent to radius, I don't see how sigma is expressed in pixels. Or is "radius" just a name for sigma, not related to pixels? How do I choose sigma? Considering I use multiple passes to increase sigma, how do I choose a good sigma to obtain the sigma I want at any given pass? If the resulting sigma is equal to the square root of the sum of the squares of the sigmas and sigma is equivalent to radius, what's an easy way to get any desired radius? What's the good size for a kernel, and how does it relate to sigma? I've seen most implementations use a 5x5 kernel. This is probably a good choice for a fast implementation with decent quality, but is there another reason to choose another kernel size? How does sigma relate to the kernel size? Should I find the best sigma so that coefficients outside my kernel are negligible and just normalize?
What's the relationship between sigma and radius? I've read that sigma is equivalent to radius, I don't see how sigma is expressed in pixels. Or is "radius" just a name for sigma, not related to pixels? There are three things at play here. The variance, ($\sigma^2$), the radius, and the number of pixels. Since this is a 2-dimensional gaussian function, it makes sense to talk of the covariance matrix $\boldsymbol{\Sigma}$ instead. Be that as it may however, those three concepts are weakly related. First of all, the 2-D gaussian is given by the equation: $$ g({\bf z}) = \frac{1}{\sqrt{(2 \pi)^2 |\boldsymbol{\Sigma}|}} e^{-\frac{1}{2} ({\bf z}-\boldsymbol{\mu})^T \boldsymbol{\Sigma}^{-1} \ ({\bf z}-\boldsymbol{\mu})} $$ Where ${\bf z}$ is a column vector containing the $x$ and $y$ coordinate in your image. So, ${\bf z} = \begin{bmatrix} x \\ y\end{bmatrix}$, and $\boldsymbol{\mu}$ is a column vector codifying the mean of your gaussian function, in the $x$ and $y$ directions $\boldsymbol{\mu} = \begin{bmatrix} \mu_x \\ \mu_y\end{bmatrix}$. Example: Now, let us say that we set the covariance matrix $\boldsymbol{\Sigma} = \begin{bmatrix} 1 & 0 \\ 0 & 1\end{bmatrix}$, and $\boldsymbol{\mu} = \begin{bmatrix} 0 \\ 0\end{bmatrix}$. I will also set the number of pixels to be $100$ x $100$. Furthermore, my 'grid', where I evaluate this PDF, is going to be going from $-10$ to $10$, in both $x$ and $y$. This means I have a grid resolution of $\frac{10 - (-10)}{100} = 0.2$. But this is completely arbitrary. With those settings, I will get the probability density function image on the left. Now, if I change the 'variance', (really, the covariance), such that $\boldsymbol{\Sigma} = \begin{bmatrix} 9 & 0 \\ 0 & 9\end{bmatrix}$ and keep everything else the same, I get the image on the right. The number of pixels are still the same for both, $100$ x $100$, but we changed the variance. Suppose instead we do the same experiment, but use $20$ x $20$ pixels instead, but I still ran from $-10$ to $10$. Then, my grid has a resolution of $\frac{10-(-10)}{20} = 1$. If I use the same covariances as before, I get this: These are how you must understand the interplay between those variables. If you would like the code, I can post that here as well. How do I choose sigma? The choice of the variance/covariance-matrix of your gaussian filter is extremely application dependent. There is no 'right' answer. That is like asking what bandwidth should one choose for a filter. Again, it depends on your application. Typically, you want to choose a gaussian filter such that you are nulling out a considerable amount of high frequency components in your image. One thing you can do to get a good measure, is compute the 2D DFT of your image, and overlay its co-efficients with your 2D gaussian image. This will tell you what co-efficients are being heavily penalized. For example, if your gaussian image has a covariance so wide that it is encompassing many high frequency coefficients of your image, then you need to make its covariance elements smaller.
https://api.stackexchange.com
I've seen lots of schematics use \$V_{CC}\$ and \$V_{DD}\$ interchangeably. I know \$V_{CC}\$ and \$V_{DD}\$ are for positive voltage, and \$V_{SS}\$ and \$V_{EE}\$ are for ground, but what is the difference between each of the two? Do the \$C\$, \$D\$, \$S\$, and \$E\$ stand for something? For extra credit: Why \$V_{DD}\$ and not simply \$V_D\$?
Back in the pleistoscene (1960s or earlier), logic was implemented with bipolar transistors. Even more specifically, they were NPN because for some reasons I'm not going to get into, NPN were faster. Back then it made sense to someone that the positive supply voltage would be called Vcc where the "c" stands for collector. Sometimes (but less commonly) the negative supply was called Vee where "e" stands for emitter. When FET logic came about, the same kind of naming was used, but now the positive supply was Vdd (drain) and the negative Vss (source). With CMOS this makes no sense, but it persists anyway. Note that the "C" in CMOS stands for "complementary". That means both N and P channel devices are used in about equal numbers. A CMOS inverter is just a P channel and a N channel MOSFET in its simplest form. With roughly equal numbers of N and P channel devices, drains aren't more likely to be positive than sources, and vice versa. However, the Vdd and Vss names have stuck for historical reasons. Technically Vcc/Vee is for bipolar and Vdd/Vss for FETs, but in practise today Vcc and Vdd mean the same, and Vee and Vss mean the same.
https://api.stackexchange.com
The purpose of this question is to ask about the role of mathematical rigor in physics. In order to formulate a question that can be answered, and not just discussed, I divided this large issue into five specific questions. Update February, 12, 2018: Since the question was put yesterday on hold as too board, I ask future to refer only to questions one and two listed below. I will ask a separate questions on item 3 and 4. Any information on question 5 can be added as a remark. What are the most important and the oldest insights (notions, results) from physics that are still lacking rigorous mathematical formulation/proofs. The endeavor of rigorous mathematical explanations, formulations, and proofs for notions and results from physics is mainly taken by mathematicians. What are examples that this endeavor was beneficial to physics itself. What are examples that insisting on rigour delayed progress in physics. What are examples that solid mathematical understanding of certain issues from physics came from further developments in physics itself. (In particular, I am interested in cases where mathematical rigorous understanding of issues from classical mechanics required quantum mechanics, and also in cases where progress in physics was crucial to rigorous mathematical solutions of questions in mathematics not originated in physics.) The role of rigor is intensely discussed in popular books and blogs. Please supply references (or better annotated references) to academic studies of the role of mathematical rigour in modern physics. (Of course, I will be also thankful to answers which elaborate on a single item related to a single question out of these five questions. See update) Related Math Overflow questions: Examples-of-non-rigorous-but-efficient-mathematical-methods-in-physics (related to question 1); Examples-of-using-physical-intuition-to-solve-math-problems; Demonstrating-that-rigour-is-important.
Rigorous arguments are very similar to computer programming--- you need to write a proof which can (in principle) ultimately be carried out in a formal system. This is not easy, and requires defining many data-structures (definitions), and writing many subroutines (lemmas), which you use again and again. Then you prove many results along the way, only some of which are of general usefulness. This activity is extremely illuminating, but it is time consuming, and tedious, and requires a great deal of time and care. Rigorous arguments also introduce a lot of pedantic distinctions which are extremely important for the mathematics, but not so important in the cases one deals with in physics. In physics, you never have enough time, and we must always have a only just precise enough understanding of the mathematics that can be transmitted maximally quickly to the next generation. Often this means that you forsake full rigor, and introduce notational short-cuts and imprecise terminology that makes turning the argument rigorous difficult. Some of the arguments in physics though are pure magic. For me, the replica trick is the best example. If this ever gets a rigorous version, I will be flabbergasted. 1) What are the most important and the oldest insights (notions, results) from physics that are still lacking rigorous mathematical formulation/proofs. Here are old problems which could benefit from rigorous analysis: Mandelstam's double-dispersion relations: The scattering amplitude for 2 particle to 2 particle scattering can be analytically expanded as an integral over the imaginary discontinuity $\rho(s)$ in the s parameter, and then this discontinuity $\rho(s)$ can be written as an integral over the t parameter, giving a double-discontinuity $\rho(s,t)$ If you go the other way, expand the discontinuity in t first then in s, you get the same function. Why is that? It was argued from perturbation theory by Mandelstam, and there was some work in the 1960s and early 1970s, but it was never solved as far as I know. The oldest, dating back centuries: Is the (Newtonian, comet and asteroid free) solar system stable for all time? This is a famous one. Rigorous bounds on where integrability fails will help. The KAM theorem might be the best answer possible, but it doesn't answer the question really, since you don't know whether the planetary perturbations are big enough to lead to instability for 8 planets some big moons, plus sun. continuum statistical mechanics: What is a thermodynamic ensemble for a continum field? What is the continuum limit of a statistical distribution? What are the continuous statistical field theories here? What are the generic topological solitonic solutions to classical nonlinear field equations? Given a classical equation, how do you find the possible topological solitons? Can they all be generated continuously from given initial data? For a specific example, consider the solar-plasma--- are there localized magneto-hydrodynamic solitons? There are a bazillion problems here, but my imagination fails. 2) The endeavor of rigorous mathematical explanations, formulations, and proofs for notions and results from physics is mainly taken by mathematicians. What are examples that this endeavor was beneficial to physics itself. There are a few examples, but I think they are rare: Penrose's rigorous proof of the existence of singularities in a closed trapped surface is the canonical example: it was a rigorous argument, derived from Riemannian geometry ideas, and it was extremely important for clarifying what's going on in black holes. Quasi-periodic tilings, also associated with Penrose, first arose in Hao and Wang's work in pure logic, where they were able to demonstrate that an appropriate tiling with complicated matching edges could do full computation. The number of tiles were reduced until Penrose gave only 2, and finally physicists discovered quasicrystals. This is spectacular, because here you start in the most esoteric non-physics part of pure mathematics, and you end up at the most hands-on of experimental systems. Kac-Moody algebras: These came up in half-mathematics, half early string theory. The results became physical in the 1980s when people started getting interested in group manifold models. The ADE classificiation from Lie group theory (and all of Lie group theory) in mathematics is essential in modern physics. Looking back further, Gell-Mann got SU(3) quark symmetry by generalizing isospin in pure mathematics. Obstruction theory was essential in understanding how to formulate 3d topological field theories (this was the subject of a recent very interesting question), which have application in the fractional quantum hall effect. This is very abstract mathematics connected to laboratory physics, but only certain simpler parts of the general mathematical machinery are used. 3) What are examples that insisting on rigour delayed progress in physics. This has happened several times, unfortunately. Statistical mechanics: The lack of rigorous proof of Boltzmann ergodicity delayed the acceptance of the idea of statistical equilibrium. The rigorous arguments were faulty--- for example, it is easy to prove that there are no phase transitions in finite volume (since the Boltzmann distribution is analytic), so this was considered a strike against Boltzmann theory, since we see phase transitions. You could also prove all sorts of nonsense about mixing entropy (which was fixed by correctly dealing with classical indistinguishability). Since there was no proof that fields would come to thermal equilibrium, some people believed that blackbody light was not thermal. This delayed acceptance of Planck's theory, and Einstein's. Statistical mechanics was not fully accepted until Onsager's Ising model solution in 1941. Path integrals: This is the most notorious example. These were accepted by some physicists immediately in the 1950s, although =the formalism wasn't at all close to complete until Candlin formulated Grassman variables in 1956. Past this point, they could have become standard, but they didn't. The formalism had a bad reputation for giving wrong results, mostly because people were uncomfortable with the lack of rigor, so that they couldn't trust the method. I heard a notable physicist complain in the 1990s that the phase-space path integral (with p and q) couldn't possibly be correct because p and q don't commute, and in the path integral they do because they are classical numbers (no, actually, they don't--- their value in an insertion depends discontinuously on their time order in the proper way). It wasn't until the early 1970s that physicists became completely comfortable with the method, and it took a lot of selling to overcome the resistance. Quantum field theory construction: The rigorous methods of the 1960s built up a toolbox of complicated distributional methods and perturbation series resummation which turns out to be the least useful way of looking at the thing. It's now C* algebras and operator valued distributions. The correct path is through the path integral the Wilsonian way, and this is closer to the original point of view of Feynman and Schwinger. But a school of rigorous physicists in the 1960s erected large barriers to entry in field theory work, and progress in field theory was halted for a decade, until rigor was thrown out again in the 1970s. But a proper rigorous formulation of quantum fields is still missing. In addition to this, there are countless no-go theorems that delayed the discovery of interesting things: Time cannot be an operator (Pauli): this delayed the emergence of the path integral particle formulation due to Feynman and Schwinger. Here, the time variable on the particle-path is path-integrated just like anything else. Von-Neumann's proof of no-hidden variables: This has a modern descendent in the Kochen Sprecher theorem about entangled sets of qubits. This delayed the Bohm theory, which faced massive resistance at first. No charges which transform nontrivially under the Lorentz group(Coleman-Mandula): This theorem had both positive and negative implications. It killed SU(6) theories (good), but it made people miss supersymmetry (bad). Quasicrystal order is impossible: This "no go" theorem is the standard proof that periodic order (the general definition of crystals) is restricted to the standard space-groups. This made quasicrystals bunk. The assumption that is violated is the assumption of strict periodicity. No supergravity compactifications with chiral fermions (Witten): this theorem assumed manifold compactification, and missed orbifolds of 11d SUGRA, which give rise to the heterotic strings (also Witten, with Horava, so Witten solved the problem). 4) What are examples that solid mathematical understanding of certain issues from physics came from further developements in physics itself. (In particular, I am interested in cases where mathematical rigorous understanding of issues from classical mechanics required quantum mechenics, and also in cases where progress in physics was crucial to rigorous mathematical solutions of questions in mathematics not originated in physics.) There are several examples here: Understanding the adiabatic theorem in classical mechanics (that the action is an adiabatic invariant) came from quantum mechanics, since it was clear that it was the action that needed to be quantized, and this wouldn't make sense without it being adiabatic invariant. I am not sure who proved the adiabatic theorem, but this is exactly what you were asking for--- an insightful classical theorem that came from quantum mechanics (although some decades before modern quantum mechanics) The understanding of quantum anomalies came directly from a physical observation (the high rate of neutral pion decay to two photons). Clarifying how this happens through Feynman diagrams, even though a naive argument says it is forbidden led to complete understanding of all anomalous terms in terms of topology. This in turn led to the development of Chern-Simons theory, and the connection with Knot polynomials, discovered by Witten, and earning him a Fields medal. Distribution theory originated in Dirac's work to try to give a good foundation for quantum mechanics. The distributional nature of quantum fields was understood by Bohr and Rosenfeld in the 1930s, and the mathematics theory was essentially taken from physics into mathematics. Dirac already defined distributions using test functions, although I don't think he was pedantic about the test-function space properties. 5) The role of rigor is intensly discussed in popular books and blogs. Please supply references (or better annotated references) to academic studies of the role of mathematical rigour in modern physics. I can't do this, because I don't know any. But for what it's worth, I think it's a bad idea to try to do too much rigor in physics (or even in some parts of mathematics). The basic reason is that rigorous formulations have to be completely standardized in order for the proofs of different authors to fit-together without seams, and this is only possible in very long hindsight, when the best definitions become apparent. In the present, we're always muddling through fog. So there is always a period where different people have slightly different definitions of what they mean, and the proofs don't quite work, and mistakes can happen. This isn't so terrible, so long as the methods are insightful. The real problem is the massive barrier to entry presented by rigorous definitions. The actual arguments are always much less daunting than the superficial impression you get from reading the proof, because most of the proof is setting up machinery to make the main idea go through. Emphasizing the rigor can put undue emphasis on the machinery rather than the idea. In physics, you are trying to describe what a natural system is doing, and there is no time to waste in studying sociology. So you can't learn all the machinery the mathematicians standardize on at any one time, you just learn the ideas. The ideas are sufficient for getting on, but they aren't sufficient to convince mathematicians you know what you're talking about (since you have a hard time following the conventions). This is improved by the internet, since the barriers to entry have fallen down dramatically, and there might be a way to merge rigorous and nonrigorous thinking today in ways that were not possible in earlier times.
https://api.stackexchange.com
I'm a mathematician who recently became very interested in questions related to mathematical physics but somehow, I faced difficulties in penetrating the literature... I'd highly appreciate any help with the following question: My aim is to relate a certain (equivariant) linear sigma model on a disc (with a non-compact target $\mathbb C$) as constructed in the exciting work of Gerasimov, Lebedev and Oblezin in Archimedean L-factors and Topological Field Theories I, to integrable systems (in the sense of Dubrovin, if you like). More precisely, I'd like to know if it's possible to express "the" correlation function of an (equivariant) linear sigma model (with non-compact target) as in the above reference in terms of a $\tau$-function of an associated integrable system? As far as I've understood from the literature, for a large class of related non-linear sigma models (or models like conformal topological field theories) such a translation can be done by translating the field theory (or at least some parts of it) into some Frobenius manifold (as in Dubrovin's approach, e.g., but other approaches are of course also welcome). Unfortunately, so far, I haven't been able to understand how to make things work in the setting of (equivariant) linear sigma models (with non-compact target). Any help or hints would be highly appreciated!
This is a reference resources question, masquerading as an answer, given the constraints of the site. The question hardly belongs here, and has been duplicated in the overflow cousin site . It might well be deleted. There have been schools and proceedings on the subject, Integrability: From Statistical Systems to Gauge TheoryLecture Notes of the Les Houches Summer School: Volume 106, June 2016, Volume 106, Patrick Dorey, Gregory Korchemsky, Nikita Nekrasov, Volker Schomerus, Didina Serban, and Leticia Cugliandolo. Print publication date: 2019, ISBN-13: 9780198828150, Published to Oxford Scholarship Online: September 2019. DOI: 10.1093/oso/9780198828150.001.0001 including, specifically, Integrability in 2D fields theory/sigma-models, Sergei L Lukyanov & Alexander B Zamolodchikov. DOI:10.1093/oso/9780198828150.003.0006 Integrability in sigma-models, K. Zarembo. DOI:10.1093/oso/9780198828150.003.0005 I am particular to Integrable 2d sigma models: Quantum corrections to geometry from RG flow, Ben Hoare, Nat Levine, Arkady Tseytlin, Nucl Phys B949 (2019) 114798 , but that's only by dint of personal connectivity...
https://api.stackexchange.com
Today a friend's six year old sister asked me the question "why don't people on the other side of the earth fall off?". I tried to explain that the Earth is a huge sphere and there's a special force called "gravity" that tries to attract everything to the center of the Earth, but she doesn't seem to understand it. I also made some attempts using a globe, saying that "Up" and "Down" are all local perspective and people on the other side of the Earth feel they're on the top, but she still doesn't get it. How can I explain the concept of gravity to a six year old in a simple and meaningful way?
Having my own 6-year-old and having successfully explained this, here's my advice from experience: Don't try to explain gravity as a mysterious force. It doesn't make sense to most adults (sad, but true! talk to non-physicists about it and you'll see), it won't make sense to a 6yo. The reason this won't work is that it requires inference from general principles to specific applications, plus it requires advanced abstract thinking to even grasp the concept of invisible forces. Those are not skills a 6-year-old has at their fingertips. Most things they're figuring out right now is piecemeal and they won't start fitting their experiences to best-fit conscious models of reality for a few years yet. Do exploit 6-year-old's tendency to take descriptions of actions-that-happen at face value as simple piecemeal facts. Stuff pulls other stuff to itself. When you have a lot of stuff, it pulls other things a lot. The bigger things pull the smaller things to them. Them having previously understood the shape of the solar system and a loose grasp of the fact of orbits (not how they work—that's a different piece—just that planets and moons move in "circular" tracks around heavier things like the Sun and Earth) may be useful before embarking on these parts of the conversation. I'm not sure, but that was a thing my 6yo already had started to grasp at this point. These conversations were also mixed in with our conversations about how Earth formed from debris, and how the pull was involved in making that happen, and how it made the pull more and more. So, I can't really separate out that background; it may also help/be necessary. Don't try to correct a 6-year-old's confusion about up and down being relative, but use it instead. There's a lot of Earth under us, and it pulls us down when we jump. If we jumped off the side, it would pull us back sideways. If we fell off the bottom, it would pull us back up. You can follow this up later with a Socratic dialogue about the relative nature of up and down, but don't muddy the waters with that immediately. That won't have any purchase until they accept the fact that Earth will pull you "back up" if you fall off. Build it up over a series of conversations. They won't get it the first time, or the tenth, but pieces of it will stick. Don't try to instill a grasp of the overall working model. If you can successfully give them some single, disconnected facts that they actually believe, putting them together will happen as they age and mature and get more exposure to this stuff. All this is assuming a decently smart but not prodigious child, of course. (A 6-year-old prodigy can probably grasp a lay adult's model of gravity, but if that's who you're dealing with then you don't need to adjust your teaching.) For some more context, this was also after my child's class started experimenting with magnets at school. I was inspired to attempt to explain gravity when my kid told me that trees didn't float off into space because the Earth was a giant magnet. (True! But not why trees don't float away.) Comparing gravity and magnetism might help, to give them an example of invisible pull that they can feel, but it might just confuse the subject a lot too since I had a lot of work (over multiple conversations) to convince my own that trees aren't sticking to the ground because of magnetism, even if the Earth is a giant magnet. And, a final piece of advice that's incidental, but can help: Once you've had a few of these conversations, play Kerbal Space Program while they watch. (Again, this comes from experience. My kid loves to watch KSP.) Seeing a practical example of gravity at work in it natural environment will go a long way to cementing the previous conversations. It may sound like a sign-off joke, but seeing a system moving and being manipulated makes a huge difference to a young child's comprehension, because it is no longer abstract or requires building mental abstractions to grasp, like showing them a globe does.
https://api.stackexchange.com
I currently find Harvard's RESTful API for ExAC extremely useful and I was hoping that a similar resource is available for Gnomad? Does anyone know of a public access API for Gnomad or possibly any plans to integrate Gnomad into the Harvard API?
As far as I know, no but the vcf.gz files are behind a http server that supports Byte-Range, so you can use tabix or any related API: $ tabix " "22:17265182-17265182" 22 17265182 . A T 762.04 PASS AC=1;AF=4.78057e-06;AN=209180;BaseQRankSum=-4.59400e+00;ClippingRankSum=2.18000e+00;DP=4906893;FS=1.00270e+01;InbreedingCoeff=4.40000e-03;MQ=3.15200e+01;MQRankSum=1.40000e+00;QD=1.31400e+01;ReadPosRankSum=2.23000e-01;SOR=9.90000e-02;VQSLOD=-5.12800e+00;VQSR_culprit=MQ;GQ_HIST_ALT=0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|1;DP_HIST_ALT=0|0|0|0|0|0|0|0|0|0|0|1|0|0|0|0|0|0|0|0;AB_HIST_ALT=0|0|0|0|0|0|0|0|0|0|0|0|1|0|0|0|0|0|0|0;GQ_HIST_ALL=1591|589|120|301|650|589|1854|2745|1815|4297|5061|2921|10164|1008|6489|1560|7017|457|6143|52950;DP_HIST_ALL=2249|1418|6081|11707|16538|9514|28624|23829|7391|853|95|19|1|0|0|1|0|1|0|0;AB_HIST_ALL=0|0|0|0|0|0|0|0|0|0|0|0|1|0|0|0|0|0|0|0;AC_AFR=0;AC_AMR=0;AC_ASJ=0;AC_EAS=0;AC_FIN=1;AC_NFE=0;AC_OTH=0;AC_SAS=0;AC_Male=1;AC_Female=0;AN_AFR=11994;AN_AMR=31324;AN_ASJ=7806;AN_EAS=13112;AN_FIN=20076;AN_NFE=94516;AN_OTH=4656;AN_SAS=25696;AN_Male=114366;AN_Female=94814;AF_AFR=0.00000e+00;AF_AMR=0.00000e+00;AF_ASJ=0.00000e+00;AF_EAS=0.00000e+00;AF_FIN=4.98107e-05;AF_NFE=0.00000e+00;AF_OTH=0.00000e+00;AF_SAS=0.00000e+00;AF_Male=8.74386e-06;AF_Female=0.00000e+00;GC_AFR=5997,0,0;GC_AMR=15662,0,0;GC_ASJ=3903,0,0;GC_EAS=6556,0,0;GC_FIN=10037,1,0;GC_NFE=47258,0,0;GC_OTH=2328,0,0;GC_SAS=12848,0,0;GC_Male=57182,1,0;GC_Female=47407,0,0;AC_raw=1;AN_raw=216642;AF_raw=4.61591e-06;GC_raw=108320,1,0;GC=104589,1,0;Hom_AFR=0;Hom_AMR=0;Hom_ASJ=0;Hom_EAS=0;Hom_FIN=0;Hom_NFE=0;Hom_OTH=0;Hom_SAS=0;Hom_Male=0;Hom_Female=0;Hom_raw=0;Hom=0;POPMAX=FIN;AC_POPMAX=1;AN_POPMAX=20076;AF_POPMAX=4.98107e-05;DP_MEDIAN=58;DREF_MEDIAN=5.01187e-84;GQ_MEDIAN=99;AB_MEDIAN=6.03448e-01;AS_RF=9.18451e-01;AS_FilterStatus=PASS;CSQ=T|missense_variant|MODERATE|XKR3|ENSG00000172967|Transcript|ENST00000331428|protein_coding|4/4||ENST00000331428.5:c.707T>A|ENSP00000331704.5:p.Phe236Tyr|810|707|236|F/Y|tTc/tAc||1||-1||SNV|1|HGNC|28778|YES|||CCDS42975.1|ENSP00000331704|Q5GH77||UPI000013EFAE||deleterious(0)|benign(0.055)|hmmpanther:PTHR14297&hmmpanther:PTHR14297:SF7&Pfam_domain:PF09815||||||||||||||||||||||||||||||,T|regulatory_region_variant|MODIFIER|||RegulatoryFeature|ENSR00000672806|TF_binding_site|||||||||||1||||SNV|1||||||||||||||||||||||||||||||||||||||||||||,T|regulatory_region_variant|MODIFIER|||RegulatoryFeature|ENSR00001729562|CTCF_binding_site|||||||||||1||||SNV|1|||||||||||||||||||||||||||||||||||||||||||| UPDATE: 2019: the current server for gnomad doesn't support Byte-Range requests.
https://api.stackexchange.com
I am trying to understand the benefits of joint genotyping and would be grateful if someone could provide an argument (ideally mathematically) that would clearly demonstrate the benefit of joint vs. single-sample genotyping. This is what I've gathered from other resources (Biostars, GATK forums, etc.) Joint-genotyping helps control FDR because errors from individually genotyped samples are added up, and amplified when merging call-sets (by Heng Li on If someone understands this, can you please clarify what is the difference on the overall FDR rate between the two scenarios (again, with an example ideally) Greater sensitivity for low-frequency variants - By sharing information across all samples, joint calling makes it possible to “rescue” genotype calls at sites where a carrier has low coverage but other samples within the call set have a confident variant at that location. (from I don't understand how the presence of a confidently called variant at the same locus in another individual can affect the genotyping of an individual with low coverage. Is there some valid argument that allows one to consider reads from another person as evidence of a particular variant in a third person? What are the assumptions for such an argument? What if that person is from a different population with entirely different allele frequencies for that variant? Having read several of the papers (or method descriptions) that describe the latest haplotype-aware SNP calling methods (HaplotypeCaller, freebayes, Platypus) the overall framework seems to be: Establish a prior on the allele frequency distribution at a site of interest using one (or combination) of: non-informative prior, population genetics model-based prior like Wright Fisher, prior based on established variation patterns like dbSNP, ExAC, or gnomAD. Build a list of plausible haplotypes in a region around the locus of interest using local assembly. Select haplotype with highest likelihood based on prior and reads data and infer the locus genotype accordingly. At which point(s) in the above procedure can information between samples be shared or pooled? Should one not trust the AFS from a large-scale resource like gnomAD much more than the distribution obtained from other samples that are nominally party of the same "cohort" but may have little to do with each other because of different ancestry, for example? I really want to understand the justifications and benefits offered by multi-sample genotyping and would appreciate your insights.
Say you are sequencing to 2X coverage. Suppose at a site, sample S has one reference base and one alternate base. It is hard to tell if this is a sequencing error or a heterozygote. Now suppose you have 1000 other samples, all at 2X read depth. One of them has two ALT bases; 10 of them have one REF and one ALT. It is usually improbable that all these samples have the same sequencing error. Then you can assert sample S has a het. Multi-sample calling helps to increase the sensitivity of not so rare SNPs. Note that what matters here is the assumption of error independency. Ancestry only has a tiny indirect effect. Multi-sample calling penalizes very rare SNPs, in particular singletons. When you care about variants only, this is for good. Naively combining single-sample calls yields a higher error rate. Multi-sample calling also helps variant filtering at a later stage. For example, for a sample sequenced to 30X coverage, you would not know if a site at 45X depth is caused by a potential CNV/mismapping or by statistical fluctuation. When you see 1000 30X samples at 45X depth, you can easily know you are looking at a CNV/systematic mismapping. Multiple samples enhance most statistical signals. Older methods pool all BAMs when calling variants. This is necessary because a single low-coverage sample does not have enough data to recover hidden INDELs. However, this strategy is not that easy to massively parallelized; adding a new sample triggers re-calling, which is very expensive as well. As we are mostly doing high-coverage sequencing these days, the old problem with INDEL calling does not matter now. GATK has this new single-sample calling pipeline where you combine per-sample gVCFs at a later stage. Such sample combining strategy is perhaps the only sensible solution when you are dealing with 100k samples. The so-called haplotype based variant calling is a separate question. This type of approach helps to call INDELs, but is not of much relevance to multi-sample calling. Also, of the three variant callers in your question, only GATK (and Scalpel which you have not mentioned) use assembly at large. Freebayes does not. Platypus does but only to a limited extent and does not work well in practice. I guess what you really want to talk about is imputation based calling. This approach further improves sensitivity with LD. With enough samples, you can measure the LD between two positions. Suppose at position 1000, you see one REF read and no ALT reads; at position 1500, you see one REF read and two ALT reads. You would not call any SNPs at position 1000 even given multiple samples. However, when you know the two positions are strongly linked and the dominant haplotypes are REF-REF and ALT-ALT, you know the sample under investigation is likely to have a missing ALT allele. LD transfers signals across sites and enhances the power to make correct genotyping calls. Nonetheless, as we are mostly doing high-coverage sequencing nowadays, imputation based methods only have a minor effect and are rarely applied.
https://api.stackexchange.com
I'd be tempted to call nipples in men vestigial, but that suggests they have no modern function. They do have a function, of course, but only in women. So why do men (and all male mammals) have them?
I believe it is for this reason: the female body plan is the default one. Males are a variation upon that, in humans at least. Nipples are part of the basic body plan. For a man to not have them, he would need to actively evolve something that would prevent nipples from developing. There is no selective pressure for the development of such a thing, so it hasn't happened. Keep in mind that the code for the general body plan is shared between males and females. The Y chromosome modifies the development of that body plan so the person becomes male.
https://api.stackexchange.com
A lot of the organometallics are rather... interesting compounds to work with. The most famous (among those who care, anyway) is tert-butyllithium or t-BuLi. It is the textbook example of a pyrophoric substance, demonstrated to pretty much every chemistry major as an air-sensitive chemical requiring special handling (Syringe and cannula transfers, gas-tight septa, argon/nitrogen blankets, that kind of thing). Despite the inherent hazards of the stuff, it's widely used in the industry (hence widespread notoriety) to add butyl groups to an organic molecule (most organometallics are useful for this kind of carbon-carbon bond formation), and you can buy it by the - airtight - gallon canister. There are, surprisingly (except to most organic chemists), even more dangerous compounds in the average organic chemistry lab. Along the pyrophoric line, many of the multi-methyl-metallics are violently pyrophoric (even compared to BuLi), including trimethylaluminum, dimethylzinc, and dimethylmagnesium. All of these are also extremely poisonous (anything these compounds can do to your wonder-drug-in-progress, they can also do to various key structures in your own body), with dubious honors reserved for dimethylmercury. Because many of these, especially the organoalkaline compounds, react violently with water, they also automatically rate at least a 3 on the "reactivity" scale. When leads me to wonder, because I wonder about these things from the safety of my office chair in a completely unrelated field; just how bad can it get? Specifically, is there any compound with an accepted use in laboratory or industrial application that is nasty enough to max out the entire NFPA-704 diamond? The closest I can find is trimethylaluminum, at a 3-4-3 (heath-fire-reactivity). T-BuLi is a 3-3-4. I can't find NFPA data on straight diazomethane (which may be because nobody in their right mind ever works with the stuff in its pure gaseous form; it's always used in a dilute diethyl ether solution, and even then is never sold or shipped that way) but it would probably be a finalist, as the gas is acutely toxic, autoignites at room temperature, and detonates on standing (something for everyone!). I'm thinking that these two inorganic families - light alkyl-metallics and organo-polyazides - would be the most likely candidates to produce a compound so toxic, so flammable, and so readily reactive, yet so interesting to chemistry, that the NFPA would see fit to rate it, and would give it highest honors.
Answering my own question based on the comments, tert-butyl-hydroperoxide is at least one such chemical. As stated on this MSDS from a government website, it's a 4-4-4, with additional special warning of being a strong oxidizer. The only thing that it does not do that could make the 704 diamond any worse is react strongly with water. It is in fact water soluble, though marginally, preferring to float on top (and therefore traditional water-based fire suppression is ineffective, but foam/CO2 will work). If anyone else can find a chemical that, in a form that is used in the lab or industrially, is a 4-4-4 that is a strong oxidizer and reacts strongly with water, that's pretty much "as bad as it gets" and they'll get the check.
https://api.stackexchange.com
We have a random experiment with different outcomes forming the sample space $\Omega,$ on which we look with interest at certain patterns, called events $\mathscr{F}.$ Sigma-algebras (or sigma-fields) are made up of events to which a probability measure $\mathbb{P}$ can be assigned. Certain properties are fulfilled, including the inclusion of the null set $\varnothing$ and the entire sample space, and an algebra that describes unions and intersections with Venn diagrams. Probability is defined as a function between the $\sigma$-algebra and the interval $[0,1]$. Altogether, the triple $(\Omega, \mathscr{F}, \mathbb{P})$ forms a probability space. Could someone explain in plain English why the probability edifice would collapse if we didn't have a $\sigma$-algebra? They are just wedged in the middle with that impossibly calligraphic "F". I trust they are necessary; I see that an event is different from an outcome, but what would go awry without a $\sigma$-algebras? The question is: In what type of probability problems the definition of a probability space including a $\sigma$-algebra becomes a necessity? This online document on the Dartmouth University website provides a plain English accessible explanation. The idea is a spinning pointer rotating counterclockwise on a circle of unit perimeter: We begin by constructing a spinner, which consists of a circle of unit circumference and a pointer as shown in [the] Figure. We pick a point on the circle and label it $0$, and then label every other point on the circle with the distance, say $x$, from $0$ to that point, measured counterclockwise. The experiment consists of spinning the pointer and recording the label of the point at the tip of the pointer. We let the random variable $X$ denote the value of this outcome. The sample space is clearly the interval $[0,1)$. We would like to construct a probability model in which each outcome is equally likely to occur. If we proceed as we did [...] for experiments with a finite number of possible outcomes, then we must assign the probability $0$ to each outcome, since otherwise, the sum of the probabilities, over all of the possible outcomes, would not equal 1. (In fact, summing an uncountable number of real numbers is a tricky business; in particular, in order for such a sum to have any meaning, at most countably many of the summands can be different than $0$.) However, if all of the assigned probabilities are $0$, then the sum is $0$, not $1$, as it should be. So if we assigned to each point any probability, and given that there is an (uncountably) infinity number of points, their sum would add up to $> 1$.
To Xi'an's first point: When you're talking about $\sigma$-algebras, you're asking about measurable sets, so unfortunately any answer must focus on measure theory. I'll try to build up to that gently, though. A theory of probability admitting all subsets of uncountable sets will break mathematics Consider this example. Suppose you have a unit square in $\mathbb{R}^2$, and you're interested in the probability of randomly selecting a point that is a member of a specific set in the unit square. In lots of circumstances, this can be readily answered based on a comparison of areas of the different sets. For example, we can draw some circles, measure their areas, and then take the probability as the fraction of the square falling in the circle. Very simple. But what if the area of the set of interest is not well-defined? If the area is not well-defined, then we can reason to two different but completely valid (in some sense) conclusions about what the area is. So we could have $P(A)=1$ on the one hand and $P(A)=0$ on the other hand, which implies $0=1$. This breaks all of math beyond repair. You can now prove $5<0$ and a number of other preposterous things. Clearly this isn't too useful. $\boldsymbol{\sigma}$-algebras are the patch that fixes math What is a $\sigma$-algebra, precisely? It's actually not that frightening. It's just a definition of which sets may be considered as events. Elements not in $\mathscr{F}$ simply have no defined probability measure. Basically, $\sigma$-algebras are the "patch" that lets us avoid some pathological behaviors of mathematics, namely non-measurable sets. The three requirements of a $\sigma$-field can be considered as consequences of what we would like to do with probability: A $\sigma$-field is a set that has three properties: Closure under countable unions. Closure under countable intersections. Closure under complements. The countable unions and countable intersections components are direct consequences of the non-measurable set issue. Closure under complements is a consequence of the Kolmogorov axioms: if $P(A)=2/3$, $P(A^c)$ ought to be $1/3$. But without (3), it could happen that $P(A^c)$ is undefined. That would be strange. Closure under complements and the Kolmogorov axioms let us to say things like $P(A\cup A^c)=P(A)+1-P(A)=1$. Finally, We are considering events in relation to $\Omega$, so we further require that $\Omega\in\mathscr{F}$ Good news: $\boldsymbol{\sigma}$-algebras are only strictly necessary for uncountable sets But! There's good news here, also. Or, at least, a way to skirt the issue. We only need $\sigma$-algebras if we're working in a set with uncountable cardinality. If we restrict ourselves to countable sets, then we can take $\mathscr{F}=2^\Omega$ the power set of $\Omega$ and we won't have any of these problems because for countable $\Omega$, $2^\Omega$ consists only of measurable sets. (This is alluded to in Xi'an's second comment.) You'll notice that some textbooks will actually commit a subtle sleight-of-hand here, and only consider countable sets when discussing probability spaces. Additionally, in geometric problems in $\mathbb{R}^n$, it's perfectly sufficient to only consider $\sigma$-algebras composed of sets for which the $\mathcal{L}^n$ measure is defined. To ground this somewhat more firmly, $\mathcal{L}^n$ for $n=1,2,3$ corresponds to the usual notions of length, area and volume. So what I'm saying in the previous example is that the set needs to have a well-defined area for it to have a geometric probability assigned to it. And the reason is this: if we admit non-measureable sets, then we can end up in situations where we can assign probability 1 to some event based on some proof, and probability 0 to the same event event based on some other proof. But don't let the connection to uncountable sets confuse you! A common misconception that $\sigma$-algebras are countable sets. In fact, they may be countable or uncountable. Consider this illustration: as before, we have a unit square. Define $$\mathscr{F}=\text{All subsets of the unit square with defined $\mathcal{L}^2$ measure}.$$ You can draw a square $B$ with side length $s$ for all $s \in (0,1)$, and with one corner at $(0,0)$. It should be clear that this square is a subset of the unit square. Moreover, all of these squares have defined area, so these squares are elements of $\mathscr{F}$. But it should also be clear that there are uncountably many squares $B$: the number of such squares is uncountable, and each square has defined Lebesgue measure. So as a practical matter, simply making that observation is often enough to make the observation that you only consider Lebesgue-measurable sets to gain headway against the problem of interest. But wait, what's a non-measurable set? I'm afraid I can only shed a little bit of light on this myself. But the Banach-Tarski paradox (sometimes the "sun and pea" paradox) can help us some: Given a solid ball in 3‑dimensional space, there exists a decomposition of the ball into a finite number of disjoint subsets, which can then be put back together in a different way to yield two identical copies of the original ball. Indeed, the reassembly process involves only moving the pieces around and rotating them, without changing their shape. However, the pieces themselves are not "solids" in the usual sense, but infinite scatterings of points. The reconstruction can work with as few as five pieces. A stronger form of the theorem implies that given any two "reasonable" solid objects (such as a small ball and a huge ball), either one can be reassembled into the other. This is often stated informally as "a pea can be chopped up and reassembled into the Sun" and called the "pea and the Sun paradox".1 So if you're working with probabilities in $\mathbb{R}^3$ and you're using the geometric probability measure (the ratio of volumes), you want to work out the probability of some event. But you'll struggle to define that probability precisely, because you can rearrange the sets of your space to change volumes! If probability depends on volume, and you can change the volume of the set to be the size of the sun or the size of a pea, then the probability will also change. So no event will have a single probability ascribed to it. Even worse, you can rearrange $S\in\Omega$ such that the volume of $S$ has $V(S)>V(\Omega)$, which implies that the geometric probability measure reports a probability $P(S)>1$, in flagrant violation of the Kolmogorov axioms which require that probability has measure 1. To resolve this paradox, one could make one of four concessions: The volume of a set might change when it is rotated. The volume of the union of two disjoint sets might be different from the sum of their volumes. The axioms of Zermelo–Fraenkel set theory with the axiom of Choice (ZFC) might have to be altered. Some sets might be tagged "non-measurable", and one would need to check whether a set is "measurable" before talking about its volume. Option (1) doesn't help use define probabilities, so it's out. Option (2) violates the second Kolmogorov axiom, so it's out. Option (3) seems like a terrible idea because ZFC fixes so many more problems than it creates. But option (4) seems attractive: if we develop a theory of what is and is not measurable, then we will have well-defined probabilities in this problem! This brings us back to measure theory, and our friend the $\sigma$-algebra.
https://api.stackexchange.com
I'm trying to download three WGS datasets from the SRA that are each between 60 and 100GB in size. So far I've tried: Fetching the .sra files directly from NCBI's ftp site Fetching the .sra files directly using the aspera command line (ascp) Using the SRA toolkit's fastqdump and samdump tools It's excruciatingly slow. I've had three fastqdump processes running in parallel now for approximately 18 hours. They're running on a large AWS instance in the US east (Virginia) region, which I figure is about as close to NCBI as I can get. In 18 hours they've downloaded a total of 33GB of data. By my calculation that's ~500kb/s. They do appear to still be running - the fastq files continue to grow and their timestamps continue to update. At this rate it's going to take me days or weeks just to download the datasets. Surely the SRA must be capable of moving data at higher rates that this? I've also looked, and unfortunately the datasets I'm interested have not been mirrored out to ENA or the Japanese archive, so it looks like I'm stuck working with the SRA. Is there a better way to fetch this data that wouldn't take multiple days?
Proximity to NCBI may not necessarily give you the fastest transfer speed. AWS may be deliberately throttling the Internet connection to limit the likelihood that people will use it for undesirable things. There's a chance that a home network might be faster, but you're likely to get the fastest connection to NCBI by using an academic system that is linked to NCBI via a research network. Another possibility is using Aspera for downloads. This is unlikely to help if bandwidth is being throttled, but it might help if there's a bit of congestion through the regular methods: NCBI also has an online book about best practises for downloading data from their servers. On a related note, just in case someone sees this and EBI/ENA is an option, there's a great guide for how to do file transfer using Aspera on the EBI web site: Your command should look similar to this on Unix: ascp -QT -l 300m -i <aspera connect installation directory>/etc/asperaweb_id_dsa.openssh era-fasp@fasp.sra.ebi.ac.uk:<file or files to download> <download location> In my case, I've just started downloading some files from a MinION sequencing run. The estimated completion time via standard FTP was 12 hours for about 32GB of data; ascp has reduced that estimated download time to about an hour. Here's the command I used for downloading: ascp -QT -l 300m -i ~/.aspera/connect/etc/asperaweb_id_dsa.openssh era-fasp@fasp.sra.ebi.ac.uk:/vol1/ERA932/ERA932268/oxfordnanopore_native/20160804_Mock.tar.gz .
https://api.stackexchange.com
I'm interested working with the medication information provided by the UK Biobank. In order to get these into a usable form I would like to map them to ATC codes. Since many of the drugs listed in the data showcase include dosage information, doing an exact string match between drug names is not very effective. I've considered using something like fuzzywuzzy to do string matching between the medications in the data showcase and the ATC drug names but validating the matches could still be a laborious process. Does anyone know of a tool that can match drug names to ATC codes or some other drug ontology? If not, maybe there's a better way to do it that I haven't thought of.
The CART tool let's you upload a set of names and map them (optionally in a fuzzy way) to STITCH 4 identifiers, and then use those to map to ATC codes (using the chemicals sources download file). It's a bit indirect, and I'm not sure what CART will do with the dosage info you mention.
https://api.stackexchange.com
A friend of mine was looking over the definition of pH and was wondering if it is possible to have a negative pH. From the equation below, it certainly seems mathematically possible—if you have a $1.1$ (or something $\gt 1$) molar solution of $\ce{H+}$ ions: $$\text{pH} = -\log([\ce{H+}])$$ (Where $[\ce{X}]$ denotes the concentration of $\ce{X}$ in $\frac{\text{mol}}{\text{L}}$.) If $[\ce{H+}] = 1.1\ \frac{\text{mol}}{\text{L}}$, then $\mathrm{pH} = -\log(1.1) \approx -0.095 $ So, it is theoretically possible to create a substance with a negative pH. But, is it physically possible (e.g. can we create a 1.1 molar acid in the lab that actually still behaves consistently with that equation)?
One publication for you: “Negative pH Does Exist”, K. F. Lim, J. Chem. Educ. 2006, 83, 1465. Quoting the abstract in full: The misconception that pH lies between 0 and 14 has been perpetuated in popular-science books, textbooks, revision guides, and reference books. The article text provides some counterexamples: For example, commercially available concentrated HCl solution (37% by mass) has $\mathrm{pH} \approx -1.1$, while saturated NaOH solution has $\mathrm{pH} \approx 15.0$.
https://api.stackexchange.com
Disclaimer: I'm not a statistician but a software engineer. Most of my knowledge in statistics comes from self-education, thus I still have many gaps in understanding concepts that may seem trivial for other people here. So I would be very thankful if answers included less specific terms and more explanation. Imagine that you are talking to your grandma :) I'm trying to grasp the nature of beta distribution – what it should be used for and how to interpret it in each case. If we were talking about, say, normal distribution, one could describe it as arrival time of a train: most frequently it arrives just in time, a bit less frequently it is 1 minute earlier or 1 minute late and very rarely it arrives with difference of 20 minutes from the mean. Uniform distribution describes, in particular, chance of each ticket in lottery. Binomial distribution may be described with coin flips and so on. But is there such intuitive explanation of beta distribution? Let's say, $\alpha=.99$ and $\beta=.5$. Beta distribution $B(\alpha, \beta)$ in this case looks like this (generated in R): But what does it actually mean? Y-axis is obviously a probability density, but what is on the X-axis? I would highly appreciate any explanation, either with this example or any other.
The short version is that the Beta distribution can be understood as representing a distribution of probabilities, that is, it represents all the possible values of a probability when we don't know what that probability is. Here is my favorite intuitive explanation of this: Anyone who follows baseball is familiar with batting averages—simply the number of times a player gets a base hit divided by the number of times he goes up at bat (so it's just a percentage between 0 and 1). .266 is in general considered an average batting average, while .300 is considered an excellent one. Imagine we have a baseball player, and we want to predict what his season-long batting average will be. You might say we can just use his batting average so far- but this will be a very poor measure at the start of a season! If a player goes up to bat once and gets a single, his batting average is briefly 1.000, while if he strikes out, his batting average is 0.000. It doesn't get much better if you go up to bat five or six times- you could get a lucky streak and get an average of 1.000, or an unlucky streak and get an average of 0, neither of which are a remotely good predictor of how you will bat that season. Why is your batting average in the first few hits not a good predictor of your eventual batting average? When a player's first at-bat is a strikeout, why does no one predict that he'll never get a hit all season? Because we're going in with prior expectations. We know that in history, most batting averages over a season have hovered between something like .215 and .360, with some extremely rare exceptions on either side. We know that if a player gets a few strikeouts in a row at the start, that might indicate he'll end up a bit worse than average, but we know he probably won't deviate from that range. Given our batting average problem, which can be represented with a binomial distribution (a series of successes and failures), the best way to represent these prior expectations (what we in statistics just call a prior) is with the Beta distribution- it's saying, before we've seen the player take his first swing, what we roughly expect his batting average to be. The domain of the Beta distribution is (0, 1), just like a probability, so we already know we're on the right track, but the appropriateness of the Beta for this task goes far beyond that. We expect that the player's season-long batting average will be most likely around .27, but that it could reasonably range from .21 to .35. This can be represented with a Beta distribution with parameters $\alpha=81$ and $\beta=219$: curve(dbeta(x, 81, 219)) I came up with these parameters for two reasons: The mean is $\frac{\alpha}{\alpha+\beta}=\frac{81}{81+219}=.270$ As you can see in the plot, this distribution lies almost entirely within (.2, .35)- the reasonable range for a batting average. You asked what the x axis represents in a beta distribution density plot—here it represents his batting average. Thus notice that in this case, not only is the y-axis a probability (or more precisely a probability density), but the x-axis is as well (batting average is just a probability of a hit, after all)! The Beta distribution is representing a probability distribution of probabilities. But here's why the Beta distribution is so appropriate. Imagine the player gets a single hit. His record for the season is now 1 hit; 1 at bat. We have to then update our probabilities- we want to shift this entire curve over just a bit to reflect our new information. While the math for proving this is a bit involved (it's shown here), the result is very simple. The new Beta distribution will be: $\mbox{Beta}(\alpha_0+\mbox{hits}, \beta_0+\mbox{misses})$ Where $\alpha_0$ and $\beta_0$ are the parameters we started with- that is, 81 and 219. Thus, in this case, $\alpha$ has increased by 1 (his one hit), while $\beta$ has not increased at all (no misses yet). That means our new distribution is $\mbox{Beta}(81+1, 219)$, or: curve(dbeta(x, 82, 219)) Notice that it has barely changed at all- the change is indeed invisible to the naked eye! (That's because one hit doesn't really mean anything). However, the more the player hits over the course of the season, the more the curve will shift to accommodate the new evidence, and furthermore the more it will narrow based on the fact that we have more proof. Let's say halfway through the season he has been up to bat 300 times, hitting 100 out of those times. The new distribution would be $\mbox{Beta}(81+100, 219+200)$, or: curve(dbeta(x, 81+100, 219+200)) Notice the curve is now both thinner and shifted to the right (higher batting average) than it used to be- we have a better sense of what the player's batting average is. One of the most interesting outputs of this formula is the expected value of the resulting Beta distribution, which is basically your new estimate. Recall that the expected value of the Beta distribution is $\frac{\alpha}{\alpha+\beta}$. Thus, after 100 hits of 300 real at-bats, the expected value of the new Beta distribution is $\frac{81+100}{81+100+219+200}=.303$- notice that it is lower than the naive estimate of $\frac{100}{100+200}=.333$, but higher than the estimate you started the season with ($\frac{81}{81+219}=.270$). You might notice that this formula is equivalent to adding a "head start" to the number of hits and non-hits of a player- you're saying "start him off in the season with 81 hits and 219 non hits on his record"). Thus, the Beta distribution is best for representing a probabilistic distribution of probabilities: the case where we don't know what a probability is in advance, but we have some reasonable guesses.
https://api.stackexchange.com
In my computational science PhD program, we are working almost exclusively in C++ and Fortran. It seems like some professors prefer one over the other. I am wondering which one is 'better' or if one is better than the other in a certain circumstance.
As so often, the choice depends on (1) the problem you are trying to solve, (2) the skills you have, and (3) the people you work with (unless it's a solo project). I'll leave (3) aside for the moment because it depends on everyone's individual situation. Problem dependence: Fortran excels at array processing. If your problem can be described in terms of simple data structures and in particular arrays, Fortran is well adapted. Fortran programmers end up using arrays even in non-obvious cases (e.g. for representing graphs). C++ is better suited for complex and highly dynamic data structures. Skill dependence: it takes a lot more programming experience to write good C++ programs than to write good Fortran programs. If you start out with little programming experience and only have so much time to learn that aspect of your job, you probably get a better return on investment learning Fortran than learning C++. Assuming, of course, that your problem is suited to Fortran. However, there's more to programming than just Fortran and C++. I'd recommend to anyone going into computational science to start with a dynamic high-level language such as Python. Always remember that your time is more valuable than CPU time!
https://api.stackexchange.com
What makes dimerization possible in $\ce{AlCl3}$? Are there 3c-2e bonds in $\ce{Al2Cl6}$ as there are in $\ce{B2H6}$?
Introduction The bonding situation in $\ce{(AlCl3)2}$ and $\ce{(BCl3)2}$ is nothing trivial and the reason why aluminium chloride forms dimers, while boron trichloride does not, cannot only be attributed to size. In order to understand this phenomenon we need to look at both, the monomers and the dimers, and compare them to each other. Understanding the respective bonding situation of the monomers, is key to understand which deficiencies lead to dimerisations. Computational details Since I was unable to find any compelling literature on the subject, I ran some calculations of my own. I used the DF-M06L/def2-TZVPP for geometry optimisations. Each structure has been optimised to a local minimum in their respective symmetry restrictions, i.e. $D_\mathrm{3h}$ for the monomers and $C_\mathrm{2v}$ for the dimers. Analyses with the Natural Bond Orbital model (NBO6 program) and the Quantum Theory of Atoms in Molecules (QTAIM, MultiWFN) have been run on single point energy calculations at the M06/def2-QZVPP//DF-M06-L/def2-TZVPP level of theory. A rudimentary energy decomposition analysis has been done on that level, too. Energy decomposition analysis The dissociation energy of the dimers $\ce{(XY3)2}$ to the monomers $\ce{XY3}$ is defined as the difference of the energy of the dimer $E_\mathrm{opt}[\ce{(XY3)2}]$ and double the energy of the monomer $E_\mathrm{opt}[\ce{XY3}]$ at their optimised (relaxed) geometries $\eqref{e-diss-def}$. The interaction energy is defined as the difference of energy of the relaxed dimer and double the energy of the monomers in the geometry of the dimer $E_\mathrm{frag}[\ce{(XY3)^{\neq}}]$ $\eqref{e-int-def}$. That basically means breaking the molecule in two parts, but keeping these fragments in the same geometry. The deformation energy (or preparation energy) is defined as the difference of the energy of the optimised and the non-optimised monomer $\eqref{e-def-def}$. This is the energy required to distort the monomer (in its ground state) to the configuration it will have in the dimer. $$\begin{align} E_\mathrm{diss} &= E_\mathrm{opt}[\ce{(XY3)2}] - 2E_\mathrm{opt}[\ce{XY3}] \tag1\label{e-diss-def}\\ E_\mathrm{int} &= E_\mathrm{opt}[\ce{(XY3)2}] - 2E_\mathrm{frag}[\ce{(XY3)^{\neq}}] %\ddag not implemented \tag2\label{e-int-def}\\ E_\mathrm{def} &= E_\mathrm{frag}[\ce{(XY3)^{\neq}}] - E_\mathrm{opt}[\ce{XY3}] \tag3\label{e-def-def}\\ E_\mathrm{diss} &= E_\mathrm{int} + 2E_\mathrm{def}\tag{1'} \end{align}$$ Results & Discussion The Monomers $\ce{XCl3; X{=}\{B,Al\}}$. Let's just get the obvious out of the way: Boron is (vdW-radius 205 pm) smaller than aluminium (vdW-radius 240 pm). For comparison chlorine has a vdW-radius of 205 pm, too. That is pretty much reflected in the bond lengths and the chlorine-chlorine distance. \begin{array}{llrrr}\hline &\ce{X{=}}& \ce{Al} &\ce{B} &\ce{Cl}\\\hline \mathbf{d}(\ce{X-Cl})&/\pu{pm} & 206.0 &173.6&--\\ \mathbf{d}(\ce{Cl\bond{~}Cl'})&/\pu{pm} & 356.8 & 300.6 & --\\\hline \mathbf{r}_\mathrm{vdW}&/\pu{pm} & 240 & 205 & 205\\ \mathbf{r}_\mathrm{sing}&/\pu{pm} & 126 & 85 & 99\\ \mathbf{r}_\mathrm{doub}&/\pu{pm} & 113 & 78 & 95\\\hline \end{array} From this data we can draw certain conclusions without further looking. The boron monomer is much more compact than the aluminium monomer. When we compare the bond lengths to the covalent radii (Pyykkö and Atsumi) we find that the boron chloride bond is about the length that we would expect from a double bond ($\mathbf{r}_\mathrm{doub}(\ce{B}) + \mathbf{r}_\mathrm{doub}(\ce{Cl}) = 173~\pu{pm}$). While the aluminium chloride bond is still significantly shorter than a single bond ($\mathbf{r}_\mathrm{sing}(\ce{Al}) + \mathbf{r}_\mathrm{sing}(\ce{Cl}) = 225~\pu{pm}$), it is still also much longer than a double bond ($\mathbf{r}_\mathrm{doub}(\ce{Al}) + \mathbf{r}_\mathrm{doub}(\ce{Cl}) = 191~\pu{pm}$). This itself offers compelling evidence, that there is more π-backbonding in $\ce{BCl3}$ than in $\ce{AlCl3}$. Molecular orbital theory offers more evidence for this. In both compounds is a doubly occupied π orbital. The following pictures are for a contour value of 0.05; aluminium (left/top) and boron (right/bottom) In numbers, the main contributions are as follows (this is just a representation, not the actual formula): $$\begin{align} \pi(\ce{BCl3}) &= 21\%~\ce{p_{$z$}-B} + \sum_{i=1}^3 26\%~\ce{p_{$z$}-Cl^{$(i)$}}\\ \pi(\ce{AlCl3}) &= 13\%~\ce{p_{$z$}-Al} + \sum_{i=1}^3 29\%~\ce{p_{$z$}-Cl^{$(i)$}} \end{align}$$ There is still some more evidence. The natural atomic charges (NPA of NBO6) fairly well agree with that assesment; aluminium is far more positive than boron. $$\begin{array}{lrr} & \ce{AlCl3} & \ce{BCl3}\\\hline \mathbf{q}(\ce{X})~\text{[NPA]} & +1.4 & +0.3 \\ \mathbf{q}(\ce{Cl})~\text{[NPA]} & -0.5 & -0.1 \\\hline %\mathbf{q}(\ce{X})~\text{[QTAIM]} & +2.4 & +2.0 \\ %\mathbf{q}(\ce{Cl})~\text{[QTAIM]} & -0.8 & -0.7 \\\hline \end{array}$$ The analysis in terms of QTAIM also shows that the bonds in $\ce{AlCl3}$ they are predominantly ionic (left/top) while in $\ce{BCl3}$ are predominantly covalent (right/bottom). One final thought on the bonding can be supplied with a natural resonance theory analysis (NBO6). I have chosen the following starting configurations and let the program calculate their contribution. The overall structures in terms of resonance are the same for both cases, that is if you force resonance treatment of the aluminium monomer. Structure A does not contribute, while the others contribute to about 31%. However, when not forced into resonance, structure A is the best approximation of the bonding situation for $\ce{AlCl3}$. In the case of $\ce{BCl3}$ the algorithm finds a hyperbond between the chlorine atoms, a strongly delocalised bond between multiple centres. In this case these are 3-centre-4-electron bonds between the chlorine atoms, resulting from the higher lying degenerated π orbitals. This all is quite good evidence that the monomer of boron chloride should be more stable towards dimerisation than the monomer of aluminium. The Dimers $\ce{(XCl3)2; X{=}\{B,Al\}}$. The obvious change is that the co-ordination of the central elements goes from trigonal planar to distorted tertrahedral. A look at the geometries will give us something to talk about. \begin{array}{llrrr}\hline &\ce{X{=}}& \ce{Al} &\ce{B} &\ce{Cl}\\\hline \mathbf{d}(\ce{X-Cl})&/\pu{pm} & 206.7 &175.9&--\\ \mathbf{d}(\ce{X-{\mu}Cl})&/\pu{pm} & 226.1 &198.7&--\\ \mathbf{d}(\ce{Cl\bond{~}{\mu}Cl})&/\pu{pm} & 354.1 & 308.0 & --\\ \mathbf{d}(\ce{{\mu}Cl\bond{~}{\mu}Cl'})&/\pu{pm} & 323.6 & 287.3 & --\\ \mathbf{d}(\ce{B\bond{~}B'})&/\pu{pm} & 315.7 & 274.7 & --\\\hline \mathbf{r}_\mathrm{vdW}&/\pu{pm} & 240 & 205 & 205\\ \mathbf{r}_\mathrm{sing}&/\pu{pm} & 126 & 85 & 99\\ \mathbf{r}_\mathrm{doub}&/\pu{pm} & 113 & 78 & 95\\\hline \end{array} In principle nothing much changes other than the expected elongation of the bonds that are now bridging. In case of aluminium the stretch is just below 10% and for boron it is slightly above 14%, having a bit more impact. In the boron dimer also the terminal bonds are slightly (> +1%) affected, while for aluminium there is almost no change. The charges are not really a reliable tool, especially when they are that close to zero as they are for boron. In both cases one can see that charge density is transferred from the bridging chlorine to the central $\ce{X}$. $$\begin{array}{lrr} & \ce{(AlCl3)2} & \ce{(BCl3)2}\\\hline \mathbf{q}(\ce{X})~\text{[NPA]} & +1.3 & +0.2 \\ \mathbf{q}(\ce{Cl})~\text{[NPA]} & -0.5 & -0.1 \\\hline \mathbf{q}(\ce{{\mu}Cl})~\text{[NPA]} & -0.4 & +0.1 \\\hline \end{array}$$ A look at the central four-membered-ring of in terms of QTAIM offers that the overall bonding does not change. In aluminium they get a little more ionic, while in boron they stay largely covalent. The NBO analysis offers a maybe quite surprising result. There are no hyperbonds in any of the dimers. While a description in these terms is certainly possible, after all it is just an interpretation tool, it is completely unnecessary. So after all we have two kinds of bonds in the dimers four terminal $\ce{X-Cl}$ and four bridging $\ce{X-{\mu}Cl}$ bonds. Therefore the most accurate description is with formal charges (also the simplest). The notation with the arrows is not wrong, but it does not represent the fact that the bonds are equal for symmetry reasons alone. To make this straight: There are no hyperbonds in $\ce{(XCl3)2; X{=}\{B,Al\}}$; this includes three-centre-two-electron bonds, and three-centre-four-electron bonds. And deeper insight to those will be offered on another day. The differentiation between a dative bond and some other for of bond does not make sense, as the bonds are equal and only introduced by a deficiency of the used description model. A natural resonance theory for $\ce{(BCl3)2}$ gives us a overall contribution of the main (all single bonds) structure of 46%; while all other structure do contribute, there are too many and their contribution is too little (> 5%). I did not run this analysis for the aluminium case as I did not expect any more insight and I did not want to waste calculation time. Dimerisation - yes or no The energies offer us a clear trend. Aluminium likes to dimerise, boron not. However, there are still some things to discuss. I am going to argue for the reaction $$\begin{align} \ce{2XCl3 &-> (XCl3)2}& \Delta E-\mathrm{diss}/E_\mathrm{o}/H/G&. \end{align};$$ therefore if reaction energies are negative the dimerisation is favoured. The following table includes all calculated energies, including the energy decomposition analysis mentioned at the beginning. All energies are given in $\pu{kJ mol^-1}$. \begin{array}{lrcrcrcrr} \Delta & E_\mathrm{diss} &(& E_\mathrm{int} &+2\times& E_\mathrm{def}&)& E_\mathrm{o} &H &G\\\hline \ce{Al} & -113.5 &(& -224.2 &+2\times& 55.4&)& -114.7 & -60.4 & -230.4\\ \ce{B} & 76.4 &(& -111.2 &+2\times& 93.8&)& 82.6 & -47.1 & 152.5\\\hline \end{array} The result is fairly obvious at first. The association for aluminium is strongly exergonic, while for boron it is strongly endergonic. While both reactions should be exothermic, stronger for aluminium, the trend for the observed electronic energies ($E_\mathrm{o}$ including the zero-point energy correction) and the (electronic) dissociation energies reflect the overall trend for the Gibbs enthalpies. While it is fairly surprising how strongly entropy favours association of $\ce{AlCl3}$, it is also surprising how it strongly disfavours it for $\ce{BCl3}$. A look at the decomposed electronic energy offers great insight into the reasons why one dimer is stable and the other not (at room temperature). The interaction energy of the fragments is double for aluminium than it is for boron. This can be traced back to the very large difference in the atomic partial charges. One could expect that the electrostatic energy is a lot more attractive for aluminium than it is for boron. The deformation energy on the other hand clearly reflects the changes in the geometry discussed above. For aluminium there is a smaller penalty resulting from the elongation of the $\ce{Al-Cl}$ bond and pyramidalisation. For boron on the other hand this has a 1.5 times larger effect. The distortion also weakens the π-backbonding, which the additional bonding would need to compensate. The four-membered-ring is certainly not an ideal geometry and the bridging chlorine atoms come dangerously close. Conclusion, Summary and TL;DR: The distortion of the geometry of the monomer $\ce{BCl3}$ cannot be compensated by the additional bonding between the two fragments. Therefore the monomers are more stable than the dimer. Additionally entropy considerations at room temperature favour the monomer, too. On the other hand, the distortion of the molecular geometry in $\ce{AlCl3}$ is less severe. The gain in interaction energy of the two fragments well overcompensates for the change. Entropy also favours the dimerisation. While size of the central atom is certainly the distinguishing factor, its impact is only severe on the electronic structure. Steric crowding would not be a problem when the interaction energy would compensate for that. This is quite evident because $\ce{BCl3}$ is still a very good Lewis acid and forms stable compounds with much larger moieties than itself. References The used van der Waals radii were taken from S. S. Batsanov Inorg. Mat. 2001, 37 (9), 871-885. And the covalent radii have been taken from P. Pyykkö and M. Atsumi Chem. Eur. J. 2009, 15, 12770-12779. Computations have been carried out using Gaussian 09 rev D.01 with NBO 6.0. Additional analyses have been performed with MultiWFN 3.3.8. Orbital pictures were generated with the incredible ChemCraft.
https://api.stackexchange.com
My understanding is that light can not escape from within a black hole (within the event horizon). I've also heard that information cannot propagate faster than the speed of light. I assume that the gravitational attraction caused by a black hole carries information about the amount of mass within the black hole. So, how does this information escape? Looking at it from a particle point of view: do the gravitons (should they exist) travel faster than the photons?
There are some good answers here already but I hope this is a nice short summary: Electromagnetic radiation cannot escape a black hole, because it travels at the speed of light. Similarly, gravitational radiation cannot escape a black hole either, because it too travels at the speed of light. If gravitational radiation could escape, you could theoretically use it to send a signal from the inside of the black hole to the outside, which is forbidden. A black hole, however, can have an electric charge, which means there is an electric field around it. This is not a paradox because a static electric field is different from electromagnetic radiation. Similarly, a black hole has a mass, so it has a gravitational field around it. This is not a paradox either because a gravitational field is different from gravitational radiation. You say the gravitational field carries information about the amount of mass (actually energy) inside, but that does not give a way for someone inside to send a signal to the outside, because to do so they would have to create or destroy energy, which is impossible. Thus there is no paradox.
https://api.stackexchange.com
I've heard that the Hilbert transform can be used to calculate the envelope of a signal. How does this work? And how is this "Hilbert envelope" different from the envelope one gets by simply rectifying a signal? I'm interested specifically in finding a way to calculate an envelope for use in dynamic range compression (i.e., "turning down the volume" of the loud parts of an audio signal automatically).
The Hilbert transform is used to calculate the "analytic" signal. See for example If your signal is a sine wave or an modulated sine wave, the magnitude of the analytic signal will indeed look like the envelope. However, the computation of the Hilbert transform is not trivial. Technically it requires a non-causal FIR filter of considerable length so it will require a fair amount of MIPS, memory and latency. For a broad band signal, it really depends on how you define "envelope" for your specific application. For your application of dynamic range compression you want a metric that is well correlated with the the perception of loudness over time. The Hilbert Transform is not the right tool for that. A better option would be to apply an A-weighted filter ( and then do a lossy peak or lossy RMS detector. This will correlate fairly well with perceived loudness over time and is relatively cheap to do.
https://api.stackexchange.com
I know that the cells of mammals at least stop dividing when they are old, and then die a programmed cell death. Then other cells have to replace them. But in a bacterial colony, each cell replicates for itself. Obviously, if a division of a bacterial cell of generation N were to produce two new cells of generation N+1, and all bacteria died of old age at generation M, there would be no bacteria left around. So how is it regulated in bacteria? Are their divisions simply unlimited? Does a cell never die and just divide forever?
This is a interesting question and for a long time it was thought that they do not age. In the meantime there are some new papers which say that bacteria do indeed age. Aging can be defined as the accumulation of non-genetic damages (for example oxidative damage to proteins) over time. If too much of these damages are accumulated, the cell will eventually die. For bacteria there seems to be an interesting way around this. The second paper cited below found that bacteria do not divide symmetrically into two daughter cells, but seem to split into one cell which receives more damage and one which receives less. The latter one can be called rejuvenated and seems to make sure that the bacteria can seemingly divide forever. Using this strategy limits the non-genetic damage to relatively few cells (if you consider the doubling mechanism) which could eventually die to save the others. Have a look at the following publications which go into detail (the first is a summary of the second but worth reading): Do bacteria age? Biologists discover the answer follows simple economics Temporal Dynamics of Bacterial Aging and Rejuvenation Aging and death in an organism that reproduces by morphologically symmetric division.
https://api.stackexchange.com
If I write on the starting page of a notebook, it will write well. But when there are few or no pages below the page where I am writing, the pen will not write well. Why does this happen?
I'd say the culprit is the contact area between the two surfaces relative to the deformation. When there are other pieces of paper below it, all the paper is able to deform when you push down; because the paper is fairly soft and deformable fiber. If there is more soft deformable paper below it, the layers are able to bend and stretch more. (A simplified example of this is Springs in series, where the overall stiffness decreases when you stack up multiple deformable bodies in a row) This deformation creates the little indents on the page (and on pages below it; you can often see on the next page the indents for the words you wrote on the page above). The deeper these indents are, the more of the ballpoint is able to make contact with the surface. If there is barely any deformation, then the flat surface doesn't get to make good contact with the page. This makes it hard for the tip of the pen to actually roll, which is what moves the ink from the cartridge to the tip. It would also make a thinner line due to less contact area. Here is an amazing exaggerated illustration I made on Microsoft Paint: The top one has more pages, the bottom one has fewer. I've exaggerated how much the pages deform obviously; but the idea is that having more pages below with make that indent larger; leading to the increased surface area on the pen tip. Note that this doesn't really apply to other types of pens. Pens that use other ways to get the ink out have less of an issue writing with solid surfaces behind; but ballpoint pens are usually less expensive and more common.
https://api.stackexchange.com
I know how to code for factorials using both iterative and recursive (e.g. n * factorial(n-1) for e.g.). I read in a textbook (without been given any further explanations) that there is an even more efficient way of coding for factorials by dividing them in half recursively. I understand why that may be the case. However I wanted to try coding it on my own, and I don't think I know where to start though. A friend suggested I write base cases first. and I was thinking of using arrays so that I can keep track of the numbers... but I really can't see any way out to designing such a code. What kind of techniques should I be researching?
The best algorithm that is known is to express the factorial as a product of prime powers. One can quickly determine the primes as well as the right power for each prime using a sieve approach. Computing each power can be done efficiently using repeated squaring, and then the factors are multiplied together. This was described by Peter B. Borwein, On the Complexity of Calculating Factorials, Journal of Algorithms 6 376–380, 1985. (PDF) In short, $n!$ can be computed in $O(n(\log n)^3\log \log n)$ time, compared to the $\Omega(n^2 \log n)$ time required when using the definition. What the textbook perhaps meant was the divide-and-conquer method. One can reduce the $n-1$ multiplications by using the regular pattern of the product. Let $n?$ denote $1 \cdot 3 \cdot 5 \dotsm (2n-1)$ as a convenient notation. Rearrange the factors of $(2n)! = 1 \cdot 2 \cdot 3 \dotsm (2n)$ as $$(2n)! = n! \cdot 2^n \cdot 3 \cdot 5 \cdot 7 \dotsm (2n-1).$$ Now suppose $n = 2^k$ for some integer $k>0$. (This is a useful assumption to avoid complications in the following discussion, and the idea can be extended to general $n$.) Then $(2^k)! = (2^{k-1})!2^{2^{k-1}}(2^{k-1})?$ and by expanding this recurrence, $$(2^k)! = \left(2^{2^{k-1}+2^{k-2}+\dots+2^0}\right) \prod_{i=0}^{k-1} (2^i)? = \left(2^{2^k - 1}\right) \prod_{i=1}^{k-1} (2^i)?.$$ Computing $(2^{k-1})?$ and multiplying the partial products at each stage takes $(k-2) + 2^{k-1} - 2$ multiplications. This is an improvement of a factor of nearly $2$ from $2^k-2$ multiplications just using the definition. Some additional operations are required to compute the power of $2$, but in binary arithmetic this can be done cheaply (depending on what precisely is required, it may just require adding a suffix of $2^k-1$ zeroes). The following Ruby code implements a simplified version of this. This does not avoid recomputing $n?$ even where it could do so: def oddprod(l,h) p = 1 ml = (l%2>0) ? l : (l+1) mh = (h%2>0) ? h : (h-1) while ml <= mh do p = p * ml ml = ml + 2 end p end def fact(k) f = 1 for i in 1..k-1 f *= oddprod(3, 2 ** (i + 1) - 1) end 2 ** (2 ** k - 1) * f end print fact(15) Even this first-pass code improves on the trivial f = 1; (1..32768).map{ |i| f *= i }; print f by about 20% in my testing. With a bit of work, this can be improved further, also removing the requirement that $n$ be a power of $2$ (see the extensive discussion).
https://api.stackexchange.com
In my linear algebra class, we just talked about determinants. So far I’ve been understanding the material okay, but now I’m very confused. I get that when the determinant is zero, the matrix doesn’t have an inverse. I can find the determinant of a $2\times 2$ matrix by the formula. Our teacher showed us how to compute the determinant of an $n \times n$ matrix by breaking it up into the determinants of smaller matrices. Apparently there is a way by summing over a bunch of permutations. But the notation is really hard for me and I don’t really know what’s going on with them anymore. Can someone help me figure out what a determinant is, intuitively, and how all those definitions of it are related?
Your trouble with determinants is pretty common. They’re a hard thing to teach well, too, for two main reasons that I can see: the formulas you learn for computing them are messy and complicated, and there’s no “natural” way to interpret the value of the determinant, the way it’s easy to interpret the derivatives you do in calculus at first as the slope of the tangent line. It’s hard to believe things like the invertibility condition you’ve stated when it’s not even clear what the numbers mean and where they come from. Rather than show that the many usual definitions are all the same by comparing them to each other, I’m going to state some general properties of the determinant that I claim are enough to specify uniquely what number you should get when you put in a given matrix. Then it’s not too bad to check that all of the definitions for determinant that you’ve seen satisfy those properties I’ll state. The first thing to think about if you want an “abstract” definition of the determinant to unify all those others is that it’s not an array of numbers with bars on the side. What we’re really looking for is a function that takes N vectors (the N columns of the matrix) and returns a number. Let’s assume we’re working with real numbers for now. Remember how those operations you mentioned change the value of the determinant? Switching two rows or columns changes the sign. Multiplying one row by a constant multiplies the whole determinant by that constant. The general fact that number two draws from: the determinant is linear in each row. That is, if you think of it as a function $\det: \mathbb{R}^{n^2} \rightarrow \mathbb{R}$, then $$ \det(a \vec v_1 +b \vec w_1 , \vec v_2 ,\ldots,\vec v_n ) = a \det(\vec v_1,\vec v_2,\ldots,\vec v_n) + b \det(\vec w_1, \vec v_2, \ldots,\vec v_n),$$ and the corresponding condition in each other slot. The determinant of the identity matrix $I$ is $1$. I claim that these facts are enough to define a unique function that takes in N vectors (each of length N) and returns a real number, the determinant of the matrix given by those vectors. I won’t prove that, but I’ll show you how it helps with some other interpretations of the determinant. In particular, there’s a nice geometric way to think of a determinant. Consider the unit cube in N dimensional space: the set of N vectors of length 1 with coordinates 0 or 1 in each spot. The determinant of the linear transformation (matrix) T is the signed volume of the region gotten by applying T to the unit cube. (Don’t worry too much if you don’t know what the “signed” part means, for now). How does that follow from our abstract definition? Well, if you apply the identity to the unit cube, you get back the unit cube. And the volume of the unit cube is 1. If you stretch the cube by a constant factor in one direction only, the new volume is that constant. And if you stack two blocks together aligned on the same direction, their combined volume is the sum of their volumes: this all shows that the signed volume we have is linear in each coordinate when considered as a function of the input vectors. Finally, when you switch two of the vectors that define the unit cube, you flip the orientation. (Again, this is something to come back to later if you don’t know what that means). So there are ways to think about the determinant that aren’t symbol-pushing. If you’ve studied multivariable calculus, you could think about, with this geometric definition of determinant, why determinants (the Jacobian) pop up when we change coordinates doing integration. Hint: a derivative is a linear approximation of the associated function, and consider a “differential volume element” in your starting coordinate system. It’s not too much work to check that the area of the parallelogram formed by vectors $(a,b)$ and $(c,d)$ is $\Big|{}^{a\;b}_{c\;d}\Big|$ either: you might try that to get a sense for things.
https://api.stackexchange.com
What are the definitions of these three things and how are they related? I've tried looking online but there is no concrete answer online for this question.
Here's a graphic I use to explain the difference in my general chemistry courses: All electrons that have the same value for $n$ (the principle quantum number) are in the same shell Within a shell (same $n$), all electrons that share the same $l$ (the angular momentum quantum number, or orbital shape) are in the same sub-shell When electrons share the same $n$, $l$, and $m_l$, we say they are in the same orbital (they have the same energy level, shape, and orientation) So to summarize: same $n$ - shell same $n$ and $l$ - sub-shell same $n$, $l$, and $m_l$ - orbital Now, in the other answer, there is some discussion about spin-orbitals, meaning that each electron would exist in its own orbital. For practical purposes, you don't need to worry about that - by the time those sorts of distinctions matter to you, there won't be any confusion about what people mean by "shells" and "sub-shells." For you, for now, orbital means "place where up to two electrons can exist," and they will both share the same $n$, $l$, and $m_l$ values, but have opposite spins ($m_s$).
https://api.stackexchange.com
I am used to thinking of finite-differences as a special case of finite-elements, on a very constrained grid. So what are the conditions on how to choose between Finite Difference Method (FDM) and Finite Element Method (FEM) as a numerical method? On the side of Finite Difference Method (FDM), one may count that they are conceptually simpler and easier to implement than Finite Element Method (FEM). FEM have the benefit of being very flexible, e.g., the grids may be very non-uniform and the domains may have arbitrary shape. The only example I know where FDM has turned out superior to FEM is in Celia, Bouloutas, Zarba, where the benefit is due to the FD method using a different discretization of time derivative, which, however, could be fixed for the finite element method.
It is possible to write most specific finite difference methods as Petrov-Galerkin finite element methods with some choice of local reconstruction and quadrature, and most finite element methods can also be shown to be algebraically equivalent to some finite difference method. Therefore, we should choose a method based on which analysis framework we want to use, which terminology we like, which system for extensibility we like, and how we would like to structure software. The following generalizations hold true in the vast majority of variations in practical use, but many points can be circumvented. Finite Difference Pros efficient quadrature-free implementation aspect ratio independence and local conservation for certain schemes (e.g. MAC for incompressible flow) robust nonlinear methods for transport (e.g. ENO/WENO) M-matrix for some problems discrete maximum principle for some problems (e.g. mimetic finite differences) diagonal (usually identity) mass matrix inexpensive nodal residual permits efficient nonlinear multigrid (FAS) cell-wise Vanka smoothers give efficient matrix-free smoothers for incompressible flow Cons more difficult to implement "physics" staggered grids are sometimes quite technical higher than second order on unstructured grids is difficult no Galerkin orthogonality, so convergence may be more difficult to prove not a Galerkin method, so discretization and adjoints do not commute (relevant to optimization and inverse problems) self-adjoint continuum problems often yield non-symmetric matrices solution is only defined pointwise, so reconstruction at arbitrary locations is not uniquely defined boundary conditions tend to be complicated to implement discontinuous coefficients usually make the methods first order stencil grows if physics includes "cross terms" Finite Element Pros Galerkin orthogonality (discrete solution to coercive problems is within a constant of the best solution in the space) simple geometric flexibility discontinuous Galerkin offers robust transport algorithm, arbitrary order on unstructured grids cellwise entropy inequality guaranteeing $L^2$ stability holds independent of mesh, dimension, order of accuracy, and presence of discontinuous solutions, without needing nonlinear limiters easy of implementing boundary conditions can choose conservation statement by choosing test space discretization and adjoints commute (for Galerkin methods) elegant foundation in functional analysis at high order, local kernels can exploit tensor product structure that is missing with FD Lobatto quadrature can make methods energy-conserving (assuming a symplectic time integrator) high order accuracy even with discontinuous coefficients, as long as you can align to boundaries discontinuous coefficients inside elements can be accommodated with XFEM easy to handle multiple inf-sup conditions Cons many elements have trouble at high aspect ratio continuous FEM has trouble with transport (SUPG is diffusive and oscillatory) DG usually has more degrees of freedom for same accuracy (though HDG is much better) continuous FEM does not provide cheap nodal problems, so nonlinear smoothers have much poorer constants usually more nonzeros in assembled matrices have to choose between consistent mass matrix (some nice properties, but has full inverse, thus requiring an implicit solve per time step) and lumped mass matrix.
https://api.stackexchange.com
As part of some blockchain-related research I am currently undertaking, the notion of using blockchains for a variety of real-world applications are thrown about loosely. Therefore, I propose the following questions: What important/crucial real-world applications use blockchain? To add on to the first question, more specifically, what real-world applications actually need blockchain - who may or may not currently use it? From a comment, I further note that this disregards the notion of cryptocurrencies. However, the use of smart contracts can have other potential applications aside from benefits they can pose to the area of cryptocurrencies
Apart from Bitcoin and Ethereum (if we are generous) there are no major and important uses today. It is important to notice that blockchains have some severe limitations. A couple of them being: It only really works for purely digital assets The digital asset under control needs to keep its value even if it's public All transactions need to be public A rather bad confirmation time Smart contracts are scary Purely digital assets If an asset is actually a physical asset with just a digital "twin" that is being traded, we will risk that local jurisdiction (i.e. your law enforcement) can have a different opinion of ownership than what is on the blockchain. To take an example; suppose that we are trading (real and physical) bikes on the blockchain, and that on the blockchain, we put its serial number. Suppose further that I hack your computer and put the ownership of your bike to be me. Now, if you go to the police, you might be able to convince them that the real owner of the bike is you, and thus I have to give it back. However, there is no way of making me give you the digital twin back, thus there is a dissonance: the bike is owned by you, but the blockchain claims it's owned by me. There are many such proposed use cases (trading physical goods on a blockchain) out in the open of trading bikes, diamonds, and even oil. The digital assets keep value even if public There are many examples where people want to put assets on the blockchain, but are somehow under the impression that that gives some kind of control. For instance, musician Imogen Heap is creating a product in which all musicians should put their music on the blockchain and automatically be paid when a radio plays your hit song. They are under the impression that this creates an automatic link between playing the song and paying for the song. The only thing it really does is to create a very large database for music which is probably quite easy to download. There is currently no way around having to put the full asset visible on the chain. Some people are talking about "encryptions", "storing only the hash", etc., but in the end, it all comes down to: publish the asset, or don't participate. Public transactions In business it is often important to keep your cards close to your chest. You don't want real time exposure of your daily operations. Some people try to make solutions where we put all the dairy farmers' production on the blockchain together with all the dairy stores' inventory. In this way we can easily send trucks to the correct places! However, this makes both farmers and traders liable for inflated prices if they are overproducing/under-stocked. Other people want to put energy production (solar panels, wind farms) on the blockchain. However, no serious energy producer will have real time production data out for the public. This has major impact on the stock value and that kind of information is the type you want to keep close to your chest. This also holds for so-called green certificates, where you ensure you only use "green energy". Note: There are theoretical solutions that build on zero-knowledge proofs that would allow transactions to be secret. However, these are nowhere near practical yet, and time will show if this item can be fixed. Confirmation time You can, like Ethereum, make the block time as small as you would like. In Bitcoin, the block time is 10 minutes, and in Ethereum it is less than a minute (I don't remember the specific figure). However, the smaller block time, the higher the chance of long-lived forks. To ensure your transaction is confirmed you still have to wait quite long. There are currently no good solutions here either. Smart contracts are scary Smart contract are difficult to write. They are computer programs that move assets from one account to another (or more complicated). However, we want traders and "normal" people to be able to write these contracts, and not rely on computer science programming experts. You can't undo a transaction. This is a tough nut to crack! If you are doing high value trading, and end up writing a zero too much in the transaction (say \$10M instead of \$1M), you call your bank immediately! That fixes it. If not, let's hope you have insurance. In a blockchain setting, you have neither a bank, nor insurance. Those \$9M are gone and it was due to a typo in a smart contract or in a transaction. Smart contracts is really playing with fire. It's too easy to empty all your assets in a single click. And it has happened, several times. People have lost hundreds of millions of dollars due to smart contract errors. Source: I am working for an energy company doing wind and solar energy production as well as trading oil and gas. Have been working on blockchain solution projects.
https://api.stackexchange.com
I haven't seen the question stated precisely in these terms, and this is why I make a new question. What I am interested in knowing is not the definition of a neural network, but understanding the actual difference with a deep neural network. For more context: I know what a neural network is and how backpropagation works. I know that a DNN must have multiple hidden layers. However, 10 years ago in class I learned that having several layers or one layer (not counting the input and output layers) was equivalent in terms of the functions a neural network is able to represent (see Cybenko's Universal approximation theorem), and that having more layers made it more complex to analyse without gain in performance. Obviously, that is not the case anymore. I suppose, maybe wrongly, that the differences are in terms of training algorithm and properties rather than structure, and therefore I would really appreciate if the answer could underline the reasons that made the move to DNN possible (e.g. mathematical proof or randomly playing with networks?) and desirable (e.g. speed of convergence?)
Let's start with a triviliaty: Deep neural network is simply a feedforward network with many hidden layers. This is more or less all there is to say about the definition. Neural networks can be recurrent or feedforward; feedforward ones do not have any loops in their graph and can be organized in layers. If there are "many" layers, then we say that the network is deep. How many layers does a network have to have in order to qualify as deep? There is no definite answer to this (it's a bit like asking how many grains make a heap), but usually having two or more hidden layers counts as deep. In contrast, a network with only a single hidden layer is conventionally called "shallow". I suspect that there will be some inflation going on here, and in ten years people might think that anything with less than, say, ten layers is shallow and suitable only for kindergarten exercises. Informally, "deep" suggests that the network is tough to handle. Here is an illustration, adapted from here: But the real question you are asking is, of course, Why would having many layers be beneficial? I think that the somewhat astonishing answer is that nobody really knows. There are some common explanations that I will briefly review below, but none of them has been convincingly demonstrated to be true, and one cannot even be sure that having many layers is really beneficial. I say that this is astonishing, because deep learning is massively popular, is breaking all the records (from image recognition, to playing Go, to automatic translation, etc.) every year, is getting used by the industry, etc. etc. And we are still not quite sure why it works so well. I base my discussion on the Deep Learning book by Goodfellow, Bengio, and Courville which went out in 2017 and is widely considered to be the book on deep learning. (It's freely available online.) The relevant section is 6.4.1 Universal Approximation Properties and Depth. You wrote that 10 years ago in class I learned that having several layers or one layer (not counting the input and output layers) was equivalent in terms of the functions a neural network is able to represent [...] You must be referring to the so called Universal approximation theorem, proved by Cybenko in 1989 and generalized by various people in the 1990s. It basically says that a shallow neural network (with 1 hidden layer) can approximate any function, i.e. can in principle learn anything. This is true for various nonlinear activation functions, including rectified linear units that most neural networks are using today (the textbook references Leshno et al. 1993 for this result). If so, then why is everybody using deep nets? Well, a naive answer is that because they work better. Here is a figure from the Deep Learning book showing that it helps to have more layers in one particular task, but the same phenomenon is often observed across various tasks and domains: We know that a shallow network could perform as good as the deeper ones. But it does not; and they usually do not. The question is --- why? Possible answers: Maybe a shallow network would need more neurons then the deep one? Maybe a shallow network is more difficult to train with our current algorithms (e.g. it has more nasty local minima, or the convergence rate is slower, or whatever)? Maybe a shallow architecture does not fit to the kind of problems we are usually trying to solve (e.g. object recognition is a quintessential "deep", hierarchical process)? Something else? The Deep Learning book argues for bullet points #1 and #3. First, it argues that the number of units in a shallow network grows exponentially with task complexity. So in order to be useful a shallow network might need to be very big; possibly much bigger than a deep network. This is based on a number of papers proving that shallow networks would in some cases need exponentially many neurons; but whether e.g. MNIST classification or Go playing are such cases is not really clear. Second, the book says this: Choosing a deep model encodes a very general belief that the function we want to learn should involve composition of several simpler functions. This can be interpreted from a representation learning point of view as saying that we believe the learning problem consists of discovering a set of underlying factors of variation that can in turn be described in terms of other, simpler underlying factors of variation. I think the current "consensus" is that it's a combination of bullet points #1 and #3: for real-world tasks deep architecture are often beneficial and shallow architecture would be inefficient and require a lot more neurons for the same performance. But it's far from proven. Consider e.g. Zagoruyko and Komodakis, 2016, Wide Residual Networks. Residual networks with 150+ layers appeared in 2015 and won various image recognition contests. This was a big success and looked like a compelling argument in favour of deepness; here is one figure from a presentation by the first author on the residual network paper (note that the time confusingly goes to the left here): But the paper linked above shows that a "wide" residual network with "only" 16 layers can outperform "deep" ones with 150+ layers. If this is true, then the whole point of the above figure breaks down. Or consider Ba and Caruana, 2014, Do Deep Nets Really Need to be Deep?: In this paper we provide empirical evidence that shallow nets are capable of learning the same function as deep nets, and in some cases with the same number of parameters as the deep nets. We do this by first training a state-of-the-art deep model, and then training a shallow model to mimic the deep model. The mimic model is trained using the model compression scheme described in the next section. Remarkably, with model compression we are able to train shallow nets to be as accurate as some deep models, even though we are not able to train these shallow nets to be as accurate as the deep nets when the shallow nets are trained directly on the original labeled training data. If a shallow net with the same number of parameters as a deep net can learn to mimic a deep net with high fidelity, then it is clear that the function learned by that deep net does not really have to be deep. If true, this would mean that the correct explanation is rather my bullet #2, and not #1 or #3. As I said --- nobody really knows for sure yet. Concluding remarks The amount of progress achieved in the deep learning over the last ~10 years is truly amazing, but most of this progress was achieved by trial and error, and we still lack very basic understanding about what exactly makes deep nets to work so well. Even the list of things that people consider to be crucial for setting up an effective deep network seems to change every couple of years. The deep learning renaissance started in 2006 when Geoffrey Hinton (who had been working on neural networks for 20+ years without much interest from anybody) published a couple of breakthrough papers offering an effective way to train deep networks (Science paper, Neural computation paper). The trick was to use unsupervised pre-training before starting the gradient descent. These papers revolutionized the field, and for a couple of years people thought that unsupervised pre-training was the key. Then in 2010 Martens showed that deep neural networks can be trained with second-order methods (so called Hessian-free methods) and can outperform networks trained with pre-training: Deep learning via Hessian-free optimization. Then in 2013 Sutskever et al. showed that stochastic gradient descent with some very clever tricks can outperform Hessian-free methods: On the importance of initialization and momentum in deep learning. Also, around 2010 people realized that using rectified linear units instead of sigmoid units makes a huge difference for gradient descent. Dropout appeared in 2014. Residual networks appeared in 2015. People keep coming up with more and more effective ways to train deep networks and what seemed like a key insight 10 years ago is often considered a nuisance today. All of that is largely driven by trial and error and there is little understanding of what makes some things work so well and some other things not. Training deep networks is like a big bag of tricks. Successful tricks are usually rationalized post factum. We don't even know why deep networks reach a performance plateau; just 10 years people used to blame local minima, but the current thinking is that this is not the point (when the perfomance plateaus, the gradients tend to stay large). This is such a basic question about deep networks, and we don't even know this. Update: This is more or less the subject of Ali Rahimi's NIPS 2017 talk on machine learning as alchemy: [This answer was entirely re-written in April 2017, so some of the comments below do not apply anymore.]
https://api.stackexchange.com
If symmetry conditions are met, FIR filters have a linear phase. This is not true for IIR filters. However, for what applications is it bad to apply filters that do not have this property and what would be the negative effect?
Let me add the following graphic to the great answers already given, with the intention of a specific and clear answer to the question posed. The other answers detail what linear phase is, this details why it is important in one graphic: When a filter has linear phase, then all the frequencies within that signal will be delayed the same amount in time (as described mathematically in Fat32's answer). When a filter has non-linear phase, individual frequencies or bands of frequencies within the spectrum of the signal are delayed different amounts in time. Any signal can be decomposed (via Fourier Series) into separate frequency components. When the signal gets delayed through any channel (such as a filter), as long as all of those frequency components get delayed the same amount, the same signal (signal of interest, within the passband of the channel) will be recreated after the delay. Consider a square wave, which through the Fourier Series Expansion is shown to be made up of an infinite number of odd harmonic frequencies. In the graphic above I show the summation of the first three components. If these components are all delayed the same amount, the waveform of interest is intact when these components are summed. However, significant group delay distortion will result if each frequency component gets delayed a different amount in time. The following may help give additional intuitive insight for those with some RF or analog background. Consider an ideal lossless broadband delay line (such as approximated by a length of coaxial cable), which can pass wideband signals without distortion. The transfer function of such a cable is shown in the graphic below, having a magnitude of 1 for all frequencies (given it is lossless) and a phase negatively increasing in direct linear proportion to frequency. The longer the cable, the steeper the slope of the phase, but in all cases "linear phase". This is also consistent with the equation for Group Delay, which is the negative derivative of phase with respect to frequency. This makes sense; the phase delay of 1 Hz signal passing through a cable with a 1 second delay will be 360°, while a 2 Hz signal with the same delay will be 720°, etc... Bringing this back to the digital world, $z^{-1}$ is the z-transform of a 1 sample delay (therefore a delay line), with a similar frequency response to what is shown, just in terms of H(z); a constant magnitude = 1 and a phase that goes linearly from $0$ to $-2\pi$ from f = 0 Hz to f = fs (the sampling rate). The simplest mathematical explanation is that the a phase that is linear with frequency and a constant delay are Fourier Transform pairs. This is the shift property of the Fourier Transform. A constant time delay in time of $\tau$ seconds results in a linear phase in frequency $-\omega \tau$, where $\omega$ is the angular frequency axis in radians/sec: $$\mathscr{F}\{g(t-\tau)\} = \int_{-\infty}^{\infty}g(t-\tau)e^{j\omega t}dt$$ $$u = t - \tau$$ $$\mathscr{F}\{g(u)\} = \int_{-\infty}^{\infty}g(u)e^{-j\omega (u+\tau)}du$$ $$ = e^{-j\omega \tau}\int_{-\infty}^{\infty}g(u)e^{-j\omega u}du$$ $$ = e^{-j\omega \tau}G(j\omega)$$ If this post was helpful, I provide more intuitive details such as this in online courses on DSP that are combined with live workshops. You can find more details on current course offerings here: DSP_coach.com
https://api.stackexchange.com
The situation Some researchers would like to put you to sleep. Depending on the secret toss of a fair coin, they will briefly awaken you either once (Heads) or twice (Tails). After each waking, they will put you back to sleep with a drug that makes you forget that awakening. When you are awakened, to what degree should you believe that the outcome of the coin toss was Heads? (OK, maybe you don’t want to be the subject of this experiment! Suppose instead that Sleeping Beauty (SB) agrees to it (with the full approval of the Magic Kingdom’s Institutional Review Board, of course). She’s about to go to sleep for one hundred years, so what are one or two more days, anyway?) [Detail of a Maxfield Parrish illustration.] Are you a Halfer or a Thirder? The Halfer position. Simple! The coin is fair--and SB knows it--so she should believe there's a one-half chance of heads. The Thirder position. Were this experiment to be repeated many times, then the coin will be heads only one third of the time SB is awakened. Her probability for heads will be one third. Thirders have a problem Most, but not all, people who have written about this are thirders. But: On Sunday evening, just before SB falls asleep, she must believe the chance of heads is one-half: that’s what it means to be a fair coin. Whenever SB awakens, she has learned absolutely nothing she did not know Sunday night. What rational argument can she give, then, for stating that her belief in heads is now one-third and not one-half? Some attempted explanations SB would necessarily lose money if she were to bet on heads with any odds other than 1/3. (Vineberg, inter alios) One-half really is correct: just use the Everettian “many-worlds” interpretation of Quantum Mechanics! (Lewis). SB updates her belief based on self-perception of her “temporal location” in the world. (Elga, i.a.) SB is confused: “[It] seems more plausible to say that her epistemic state upon waking up should not include a definite degree of belief in heads. … The real issue is how one deals with known, unavoidable, cognitive malfunction.” [Arntzenius] The question Accounting for what has already been written on this subject (see the references as well as a previous post), how can this paradox be resolved in a statistically rigorous way? Is this even possible? References Arntzenius, Frank (2002). Reflections on Sleeping Beauty Analysis 62.1 pp 53-62. Bradley, DJ (2010). Confirmation in a Branching World: The Everett Interpretation and Sleeping Beauty. Brit. J. Phil. Sci. 0 (2010), 1–21. Elga, Adam (2000). Self-locating belief and the Sleeping Beauty Problem. Analysis 60 pp 143-7. Franceschi, Paul (2005). Sleeping Beauty and the Problem of World Reduction. Preprint. Groisman, Berry (2007). The end of Sleeping Beauty’s nightmare. Preprint. Lewis, D (2001). Sleeping Beauty: reply to Elga. Analysis 61.3 pp 171-6. Papineau, David and Victor Dura-Vila (2008). A Thirder and an Everettian: a reply to Lewis’s ‘Quantum Sleeping Beauty’. Pust, Joel (2008). Horgan on Sleeping Beauty. Synthese 160 pp 97-101. Vineberg, Susan (undated, perhaps 2003). Beauty’s Cautionary Tale.
Strategy I would like to apply rational decision theory to the analysis, because that is one well-established way to attain rigor in solving a statistical decision problem. In trying to do so, one difficulty emerges as special: the alteration of SB’s consciousness. Rational decision theory has no mechanism to handle altered mental states. In asking SB for her credence in the coin flip, we are simultaneously treating her in a somewhat self-referential manner both as subject (of the SB experiment) and experimenter (concerning the coin flip). Let’s alter the experiment in an inessential way: instead of administering the memory-erasure drug, prepare a stable of Sleeping Beauty clones just before the experiment begins. (This is the key idea, because it helps us resist distracting--but ultimately irrelevant and misleading--philosophical issues.) The clones are like her in all respects, including memory and thought. SB is fully aware this will happen. We can clone, in principle. E. T. Jaynes replaces the question "how can we build a mathematical model of human common sense"--something we need in order to think through the Sleeping Beauty problem--by "How could we build a machine which would carry out useful plausible reasoning, following clearly defined principles expressing an idealized common sense?" Thus, if you like, replace SB by Jaynes' thinking robot, and clone that. (There have been, and still are, controversies about "thinking" machines. "They will never make a machine to replace the human mind—it does many things which no machine could ever do." You insist that there is something a machine cannot do. If you will tell me precisely what it is that a machine cannot do, then I can always make a machine which will do just that!” --J. von Neumann, 1948. Quoted by E. T. Jaynes in Probability Theory: The Logic of Science, p. 4.) --Rube Goldberg The Sleeping Beauty experiment restated Prepare $n \ge 2$ identical copies of SB (including SB herself) on Sunday evening. They all go to sleep at the same time, potentially for 100 years. Whenever you need to awaken SB during the experiment, randomly select a clone who has not yet been awakened. Any awakenings will occur on Monday and, if needed, on Tuesday. I claim that this version of the experiment creates exactly the same set of possible results, right down to SB's mental states and awareness, with exactly the same probabilities. This potentially is one key point where philosophers might choose to attack my solution. I claim it's the last point at which they can attack it, because the remaining analysis is routine and rigorous. Now we apply the usual statistical machinery. Let's begin with the sample space (of possible experimental outcomes). Let $M$ mean "awakens Monday" and $T$ mean "awakens Tuesday." Similarly, let $h$ mean "heads" and $t$ mean "tails". Subscript the clones with integers $1, 2, \ldots, n$. Then the possible experimental outcomes can be written (in what I hope is a transparent, self-evident notation) as the set $$\eqalign{ \{&hM_1, hM_2, \ldots, hM_n, \\ &(tM_1, tT_2), (tM_1, tT_3), \ldots, (tM_1, tT_n), \\ &(tM_2, tT_1), (tM_2, tT_3), \ldots, (tM_2, tT_n), \\ &\cdots, \\ &(tM_n, tT_1), (tM_n, tT_2), \ldots, (tM_n, tT_{n-1}) & \}. }$$ Monday probabilities As one of the SB clones, you figure your chance of being awakened on Monday during a heads-up experiment is ($1/2$ chance of heads) times ($1/n$ chance I’m picked to be the clone who is awakened). In more technical terms: The set of heads outcomes is $h = \{hM_j, j=1,2, \ldots,n\}$. There are $n$ of them. The event where you are awakened with heads is $h(i) = \{hM_i\}$. The chance of any particular SB clone $i$ being awakened with the coin showing heads equals $$\Pr[h(i)] = \Pr[h] \times \Pr[h(i)|h] = \frac{1}{2} \times \frac{1}{n} = \frac{1}{2n}.$$ Tuesday probabilities The set of tails outcomes is $t = \{(tM_j, tT_k): j \ne k\}$. There are $n(n-1)$ of them. All are equally likely, by design. You, clone $i$, are awakened in $(n-1) + (n-1) = 2(n-1)$ of these cases; namely, the $n-1$ ways you can be awakened on Monday (there are $n-1$ remaining clones to be awakened Tuesday) plus the $n-1$ ways you can be awakened on Tuesday (there are $n-1$ possible Monday clones). Call this event $t(i)$. Your chance of being awakened during a tails-up experiment equals $$\Pr[t(i)] = \Pr[t] \times P[t(i)|t] = \frac{1}{2} \times \frac{2(n-1)}{n(n-1)} = \frac{1}{n}.$$ Bayes' Theorem Now that we have come this far, Bayes' Theorem--a mathematical tautology beyond dispute--finishes the work. Any clone's chance of heads is therefore $$\Pr[h | t(i) \cup h(i)] = \frac{\Pr[h]\Pr[h(i)|h]}{\Pr[h]\Pr[h(i)|h] + \Pr[t]\Pr[t(i)|t]} = \frac{1/(2n)}{1/n + 1/(2n)} = \frac{1}{3}.$$ Because SB is indistinguishable from her clones--even to herself!--this is the answer she should give when asked for her degree of belief in heads. Interpretations The question "what is the probability of heads" has two reasonable interpretations for this experiment: it can ask for the chance a fair coin lands heads, which is $\Pr[h] = 1/2$ (the Halfer answer), or it can ask for the chance the coin lands heads, conditioned on the fact that you were the clone awakened. This is $\Pr[h|t(i) \cup h(i)] = 1/3$ (the Thirder answer). In the situation in which SB (or rather any one of a set of identically prepared Jaynes thinking machines) finds herself, this analysis--which many others have performed (but I think less convincingly, because they did not so clearly remove the philosophical distractions in the experimental descriptions)--supports the Thirder answer. The Halfer answer is correct, but uninteresting, because it is not relevant to the situation in which SB finds herself. This resolves the paradox. This solution is developed within the context of a single well-defined experimental setup. Clarifying the experiment clarifies the question. A clear question leads to a clear answer. Comments I guess that, following Elga (2000), you could legitimately characterize our conditional answer as "count[ing] your own temporal location as relevant to the truth of h," but that characterization adds no insight to the problem: it only detracts from the mathematical facts in evidence. To me it appears to be just an obscure way of asserting that the "clones" interpretation of the probability question is the correct one. This analysis suggests that the underlying philosophical issue is one of identity: What happens to the clones who are not awakened? What cognitive and noetic relationships hold among the clones?--but that discussion is not a matter of statistical analysis; it belongs on a different forum.
https://api.stackexchange.com
I found two of these objects near a creek in Missouri. They feel like they are made out of bone but they do not look like any bone I have seen before. They also appear as though the could be some sort of plant part. I am having a very difficult time identifying them and any help would be appreciated.
Those are isolated turtle bones: Specifically, they are part of the carapace, or upper shell. The projections would articulate with the backbone. The "toothlike" structure at the other end projects down toward the margin of the shell. Based on the size, and the fact that you are in Missouri, I'm guessing they are snapping turtle bones. Here's a photo of the inside of a snapping turtle shell: They are a little hard to make out, but you can faintly see the marginal projections.
https://api.stackexchange.com
In computer science, we have often have to solve recurrence relations, that is find a closed form for a recursively defined sequence of numbers. When considering runtimes, we are often interested mainly in the sequence's asymptotic growth. Examples are The runtime of a tail-recursive function stepping downwards to $0$ from $n$ whose body takes time $f(n)$: $\qquad \begin{align} T(0) &= 0 \\ T(n+1) &= T(n) + f(n) \end{align}$ The Fibonacci sequence: $\qquad \begin{align} F_0 &= 0 \\ F_1 &= 1 \\ F_{n+2} &= F_n + F_{n+1} \end{align}$ The number of Dyck words with $n$ parenthesis pairs: $\qquad\begin{align} C_0 &= 1 \\ C_{n+1}&=\sum_{i=0}^{n}C_i\,C_{n-i} \end{align}$ The mergesort runtime recurrence on lists of length $n$: $\qquad \begin{align} T(1) &= T(0) = 0 \\ T(n) &= T(\lfloor n/2\rfloor) + T(\lceil n/2\rceil) + n-1 \end{align}$ What are methods to solve recurrence relations? We are looking for general methods and methods for a significant subclass as well as methods that yield precise solutions and methods that provide (bounds on) asymptotic growth. This is supposed to become a reference question. Please post one answer per method and provide a general description as well as an illustrative example.
Converting Full History to Limited History This is a first step in solving recurrences where the value at any integer depends on the values at all smaller integers. Consider, for example, the recurrence $$ T(n) = n + \frac{1}{n}\sum_{k=1}^n \big(T(k-1) + T(n-k)\big) $$ which arises in the analysis of randomized quicksort. (Here, $k$ is the rank of the randomly chosen pivot.) For any integer $n$, the value of $T(n)$ depends on all $T(k)$ with $k<n$. Recurrences of this form are called full history recurrences. To solve this recurrence, we can transform it into a limited history recurrence, where $T(n)$ depends on only a constant number of previous values. But first, it helps to simplify the recurrence a bit, to collect common terms and eliminate pesky fractions. \begin{align*} n T(n) &= n^2 + 2\sum_{k=1}^{n-1} T(k) \end{align*} Now to convert to a limited-history recurrence, we write down the recurrence for $T(n-1)$, subtract, and regather terms: \begin{align*} (n-1) T(n-1) &= (n-1)^2 + 2\sum_{k=1}^{n-2} T(k) \\ \implies nT(n) - (n-1)T(n-1) &= (2n-1) + 2T(n-1) \\[1ex] \implies n T(n) &= (2n-1) + (n+1) T(n-1) \\[1ex] \implies \frac{T(n)}{n+1} &= \frac{2n-1}{n(n+1)} + \frac{T(n-1)}{n} \end{align*} Now if we define $t(n) = T(n)/(n+1)$ and replace the fraction $\frac{2n-1}{n(n+1)}$ with the simpler asymptotic form $\Theta(1/n)$, we obtain the much simpler recurrence $$ t(n) = \Theta(1/n) + t(n-1). $$ Expanding this recurrence into a summation immediately gives us $t(n) = \Theta(H_n) = \Theta(\log n)$, where $H_n$ is the $n$th harmonic number. We conclude that $\boldsymbol{T(n) = \Theta(n\log n)}$.
https://api.stackexchange.com
Need to understand the working of 'Embedding' layer in Keras library. I execute the following code in Python import numpy as np from keras.models import Sequential from keras.layers import Embedding model = Sequential() model.add(Embedding(5, 2, input_length=5)) input_array = np.random.randint(5, size=(1, 5)) model.compile('rmsprop', 'mse') output_array = model.predict(input_array) which gives the following output input_array = [[4 1 3 3 3]] output_array = [[[ 0.03126476 0.00527241] [-0.02369716 -0.02856163] [ 0.0055749 0.01492429] [ 0.0055749 0.01492429] [ 0.0055749 0.01492429]]] I understand that each value in the input_array is mapped to 2 element vector in the output_array, so a 1 X 4 vector gives 1 X 4 X 2 vectors. But how are the mapped values computed?
In fact, the output vectors are not computed from the input using any mathematical operation. Instead, each input integer is used as the index to access a table that contains all possible vectors. That is the reason why you need to specify the size of the vocabulary as the first argument (so the table can be initialized). The most common application of this layer is for text processing. Let's see a simple example. Our training set consists only of two phrases: Hope to see you soon Nice to see you again So we can encode these phrases by assigning each word a unique integer number (by order of appearance in our training dataset for example). Then our phrases could be rewritten as: [0, 1, 2, 3, 4] [5, 1, 2, 3, 6] Now imagine we want to train a network whose first layer is an embedding layer. In this case, we should initialize it as follows: Embedding(7, 2, input_length=5) The first argument (7) is the number of distinct words in the training set. The second argument (2) indicates the size of the embedding vectors. The input_length argument, of course, determines the size of each input sequence. Once the network has been trained, we can get the weights of the embedding layer, which in this case will be of size (7, 2) and can be thought as the table used to map integers to embedding vectors: +------------+------------+ | index | Embedding | +------------+------------+ | 0 | [1.2, 3.1] | | 1 | [0.1, 4.2] | | 2 | [1.0, 3.1] | | 3 | [0.3, 2.1] | | 4 | [2.2, 1.4] | | 5 | [0.7, 1.7] | | 6 | [4.1, 2.0] | +------------+------------+ So according to these embeddings, our second training phrase will be represented as: [[0.7, 1.7], [0.1, 4.2], [1.0, 3.1], [0.3, 2.1], [4.1, 2.0]] It might seem counterintuitive at first, but the underlying automatic differentiation engines (e.g., Tensorflow or Theano) manage to optimize these vectors associated with each input integer just like any other parameter of your model. For an intuition of how this table lookup is implemented as a mathematical operation which can be handled by the automatic differentiation engines, consider the embeddings table from the example as a (7, 2) matrix. Then, for a given word, you create a one-hot vector based on its index and multiply it by the embeddings matrix, effectively replicating a lookup. For instance, for the word "soon" the index is 4, and the one-hot vector is [0, 0, 0, 0, 1, 0, 0]. If you multiply this (1, 7) matrix by the (7, 2) embeddings matrix you get the desired two-dimensional embedding, which in this case is [2.2, 1.4]. It is also interesting to use the embeddings learned by other methods/people in different domains (see as done in [1]. [1] López-Sánchez, D., Herrero, J. R., Arrieta, A. G., & Corchado, J. M. Hybridizing metric learning and case-based reasoning for adaptable clickbait detection. Applied Intelligence, 1-16.
https://api.stackexchange.com
What is the difference between the three terms below? percentile quantile quartile
0 quartile = 0 quantile = 0 percentile 1 quartile = 0.25 quantile = 25 percentile 2 quartile = .5 quantile = 50 percentile (median) 3 quartile = .75 quantile = 75 percentile 4 quartile = 1 quantile = 100 percentile
https://api.stackexchange.com
I spotted these two in my garden. What is this insect? He had firm control over the wasp and was just hanging on by one leg. He appeared to hold on until the wasp stopped moving and then flew away with it. I live in Ohio (USA). The wasp was a bit less than 2cm long while the other insect was about 2.5cm long.
Given the large eyes, the almost non-existent antennae, the humped back, elongated abdomen and the wings, I'd say it is a robber fly. It is one of many insects known to prey on wasps. Note the description on the linked page: This spindly piece of nastiness is a Robber Fly in the genus Diogmites. It seems that it's members of this particular genus that are adorned with the name Hanging Thief. You may remember that this was to denote their habit of dangling from a leg or two while the other limbs held onto prey, stabbed it to death with venom and then sucked out the insides. [Emphasis mine.]
https://api.stackexchange.com
I have seen it mentioned that dependent type systems are not inferable, but are checkable. I was wondering if there is a simple explanation of why that is so, and whether or not there is there a limit of "dependency" where types can be indexed by values, below which type inference is possible and above which it is not?
For a rather simple version of dependent type theory, Gilles Dowek gave a proof of undecidability of typability in a non-empty context: Gilles Dowek, The undecidability of typability in the $\lambda\Pi$-calculus Which can be found here. First let me clarify what is proven in that paper: he shows that in a dependent calculus without annotations on the abstractions, it is undecidable to show typeability of a term in a non-empty context. Both of those hypotheses are necessary: in the empty context, typability reduces to that of the simply-typed $\lambda$-calculus (decidable by Hindley-Milner) and with the annotations on the abstractions, the usual type-directed algorithm applies. The idea is to encode a Post correspondence problem as a type conversion problem, and then carefully construct a term which is typeable iff the two specific types are convertible. This uses knowledge of the shape of normal forms, which always exist in this calculus. The article is short and well-written, so I won't go into more detail here. Now in polymorphic calculi like system-F, it would be nice to be able to infer the type abstractions and applications, and omit the annotations on $\lambda$s as above. This is also undecidable, but the proof is much harder and the question was open for quite some time. The matter was resolved by Wells: J. B. Wells, Typability and type checking in System F are equivalent and undecidable. This can be found here. All I know about it is that it reduces the problem of semi-unification (which is unification modulo instantiation of universal quantifiers, and is undecidable) to type checking in System F. Finally it is quite easy to show that inhabitation of dependent families is undecidable: simply encode a Post problem into the constructor indices. Here are some slides by Nicolas Oury that sketch the argument. As to whether there is a "limit", it much depends on what you are trying to do with your dependent types, and there are many approximations which try to be either decidable, or at least close enough to be usable. These questions are still very much part of active research though. One possible avenue is the field of "refinement types" where the language of expression of type dependencies is restricted to allow for decidable checking see, e.g. Liquid Types. It's rare that full type inference is decidable even in these systems though.
https://api.stackexchange.com
Are there some good sites or blogs where I can keep myself updated on the latest news and papers about image and signal processing research, or I should just check out "classical" providers like IEEE Transactions, Elsevier, etc?
There are many for different subjects - Efg's algorithm collection : DSP Forum : Data compression - About rendering - For all research papers - Resources on Mp3 and Audio - Steve on Image Processing - Image Processing and Retrieval Accelerated Image Processing - The Digital Signal Processing Blog - Noise & Vibration Measurement Blog - Image Processing with Matlab, Open Blog -
https://api.stackexchange.com
The state of the art of non-linearity is to use rectified linear units (ReLU) instead of sigmoid function in deep neural network. What are the advantages? I know that training a network when ReLU is used would be faster, and it is more biological inspired, what are the other advantages? (That is, any disadvantages of using sigmoid)?
Two additional major benefits of ReLUs are sparsity and a reduced likelihood of vanishing gradient. But first recall the definition of a ReLU is $h = \max(0, a)$ where $a = Wx + b$. One major benefit is the reduced likelihood of the gradient to vanish. This arises when $a > 0$. In this regime the gradient has a constant value. In contrast, the gradient of sigmoids becomes increasingly small as the absolute value of x increases. The constant gradient of ReLUs results in faster learning. The other benefit of ReLUs is sparsity. Sparsity arises when $a \le 0$. The more such units that exist in a layer the more sparse the resulting representation. Sigmoids on the other hand are always likely to generate some non-zero value resulting in dense representations. Sparse representations seem to be more beneficial than dense representations.
https://api.stackexchange.com