anchor stringlengths 0 150 | positive stringlengths 0 96k | source dict |
|---|---|---|
Topography in general sense | Question: What does topography mean in topographical barrier? I can't fully understand the word topography. I have read the pages appearing on googling topography.
Topography is the arrangement of the natural and artificial physical features of an area. Could topographical barrier be any landforms like a mountain range,a plateau or even a forest?
Answer: 'Topography' implies variation in altitude. A flat rain forest, such as most of the Amazon basin has very little variation in altitude, and therefore doesn't constitute a topographic barrier. By contrast, the topography of the Andean mountain chain, further west, has a huge altitude variation, and hence constitutes one of the classic topographic barriers in respect of air flow, rainfall, salt balance, etc.
So any mountain range or plateau may be a topographic barrier. Forests may or may not be topographic barriers, according to whether or not they have significant topographic variation. Hence the forests of Papua New Guinea constitute a t.b., but most lowland forests do not. | {
"domain": "earthscience.stackexchange",
"id": 826,
"tags": "terminology"
} |
Connection between a simple matter wave and Heisenberg's uncertainty relation | Question: When looking at the wave function of a particle, I usually prefer to write
$$
\Psi(x,t) = A \exp(i(kx - \omega t))
$$
since it reminds me of classical waves for which I have an intuition ($k$ tells me how it moves through space ($x$) and $\omega$ tells me how it moves through time ($t$), roughly speaking). However, I noticed that you can translate this from the $(k,\omega)$ into the $(p,E)$ space by extracting $\hbar$:
$$
\Psi(x,t) = A \exp(i(px - Et)/\hbar)
$$
When looking at this representation, I couldn't help but be remembered of the uncertainty relations
$$
\Delta p \Delta x \geq \hbar\\
\Delta E \Delta t \geq \hbar
$$
This cannot be a coincidence, but the derivation of these relations (as described e.g. on Wikipedia) are simply over my head and my textbook merely motivates them with an argument based on wave packets.
What is the connection here? Is there an intuitive explanation for the recurrence of both uncertainty relations in the wave function of a matter particle?
Answer: You are absolutely right. In fact, the uncertainty relations are a direct consequence of this wave nature and the "conjugated" variables being $p \leftrightarrow x$ and $E \leftrightarrow t$.
I will attempt a simple explanation. Remember that the wavefunction gives you a probability amplitude for finding the particle at some location $x$ at some time $t$? The probability to find the particle at some point $x$ at time $t$ is given by $|\Psi(x,t)|^2$.
Now here's the catch: If you put your plane wave into that equation, you'll find that $|\Psi(x,t)|^2 = A$, independent of $x$ and $t$. So for your plane wave, the particle has equal probability to be anywhere. In terms of uncertainty, then, we could say that the uncertainty in position is at a maximum, and so is the uncertainty in time.
What about momentum and energy? Well, your plane wave has a definite momentum of $p = \hbar k$ and a definite energy of $E = \hbar \omega$, so their uncertainty is zero. This is an extreme case of the uncertainty relation: Certainty in one variable means maximum uncertainty in the other variable.
Any other possible form of the wave function can always be written as a sum of plane waves (that's the Fourier theorem):
$$\Psi(x,t) = \int dE \int dk A(k,E) \exp(i(kx-E/\hbar t)$$
You can think of $\Psi(x,t)$ as the wavefunction in position and time domain and $A(k,E)$ as the wavefunction in momentum and frequency domain, and the conversion between those two is achieved via the Fourier transform.
You can now mathematically show how if $\Psi(x,t)$ is "narrow" (i.e. position has low uncertainty) then $A(k,E)$ must be broad and vice versa.
The intuition behind that: You need to add up a lot of plain waves with lots of different momenta to go from the broad plain wave distribution to a narrow wave packet, but this then implies that you have high uncertainty in momentum. | {
"domain": "physics.stackexchange",
"id": 7542,
"tags": "wavefunction, heisenberg-uncertainty-principle"
} |
How are two-qubit states experimentally projected into the Bell basis? | Question: To perform Quantum Teleportation, we need state of two entangle qubits in the Bell basis
$$\left(\frac{|00\rangle + \rangle11\rangle}{\sqrt{2}}, \frac{|00\rangle - |11\rangle}{\sqrt{2}}, \frac{|01\rangle + |10\rangle}{\sqrt{2}},\frac{|01\rangle - |10\rangle}{\sqrt{2}} \right).$$
To project in the product basis ($|00\rangle,|10\rangle,|01\rangle,|11\rangle$, or in the product basis along x or y axis (or any other axis)) we can check whether the individual spins are pointing up or down, but I don't know how the state is experimentally projected over a basis of entangled states like the Bell basis.
Answer: Quantum circuit setup
Since the quantum circuits are all unitary operations, they are reversible too. The circuit that is used to generate Bell basis from the product basis can be used in reverse, just as shown below, to measure in the product basis, for which we already have an understanding.
\begin{align*}
|\Phi^+\rangle &=\frac1{\sqrt2}(|00\rangle+|11\rangle)\rightarrow|00\rangle \\
|\Psi^+\rangle &=\frac1{\sqrt2}(|01\rangle+|10\rangle)\rightarrow|01\rangle \\
|\Phi^-\rangle &=\frac1{\sqrt2}(|00\rangle-|11\rangle)\rightarrow|10\rangle \\
|\Psi^-\rangle &=\frac1{\sqrt2}(|01\rangle-|10\rangle)\rightarrow|11\rangle
\end{align*}
Experimental implemetations
A photonic Bell state measurement setup consists of a beam-splitter followed by detectors. The two outputs of the beam-splitter each include a polarization beam-splitter followed by two single photon detectors and hence allow identifying two orthogonal polarization modes.
Figure taken from R. Valivarthi et. al., Optics express, 22(20):24497–24506, 2014.
The input and output spatial modes are labelled 1,2 and 3,4, respectively. The same output port of the beam-splitter signals projection onto $|\psi^+\rangle$ and a coincidence of photons in modes 0 and 1 in different output ports of the beam-splitter is a signature of $|\psi^-\rangle$. However, the above setup cannot distinguish between states $|\phi+\rangle$ and $|\phi^-\rangle$. So with the above
set-up we can unambiguously distinguish only 2 of the 4 Bell states.
A conceptually simple way to improve the efficiency of the BSM to 100% is to implement a CNOT (short for controlled not) gate using non-linear optics. A proposal for such an implementation to completely distinguish all four Bell states can be seen in this paper by Kim et. al. It must also noted that CNOT gate is not efficeintly acted using photons, but often implemented in atomic or stationary qubit systems. | {
"domain": "physics.stackexchange",
"id": 67584,
"tags": "quantum-mechanics, quantum-information, quantum-entanglement"
} |
Distinguishability a set of permutations | Question: Given integers $d<n$, find the largest $k$ such that there exists a set of $k$ permutations $\sigma_1,\cdots,\sigma_k$ on $[n]$, such that any size-$d$ subset $T\subseteq [n]$ is ``distinguishable'' by the permutations.
Here we say that a set $T$ is NOT distinguishable by two permutation $\sigma,\sigma^*$ if we view both permutations as arrangements of $[n]$ into a sequence, and the restricted orders on $T\subseteq [n]$ in both arrangements are the same, otherwise it is distinguishable by $\sigma$ and $\sigma^*$. We say that a subset $T\subseteq [n]$ is distinguished by a collection of permutations if it is distinguishable by every pair of permutations in the collection.
Probably it is hard to express $k$ in terms of $n$ and $d$, so we shoot for asymptotic lower or upper bounds on $k$. Actually I am more interested in the case where $d$ is small (let's say $d=O(\sqrt{n})$). Any previous results or relevant ideas are appreciated.
Answer: Here are loose lower and upper bounds.
Fix $d \le n$ as in the post. Let $k^*$ denote the largest possible value of $k$ meeting the conditions in the post. We show that $k^* = \exp(\Theta(d\log d)$) for $d\ge 3\sqrt n$, but $k^* \le 2$ for $d\le n^{1/3}$. I suspect the latter bound can be strengthened (e.g. shown for larger $d$).
Lemma 1. $d!/{n\choose d} \le k^* \le d!$
Proof. The upper bound $k^*\le d!$ holds simply because each chosen permutation induces a distinct permutation on the $d$-subset $\{1,\ldots,d\}$. For the lower bound, say that two permutations of $[n]$ conflict if, for some $d$-subset $T$ of $[n]$, they induce the same relative order on $T$. A given permutation $\sigma$ induces a relative order on $n\choose d$ such $d$-subsets. Each $d$-subset $T$ and relative order on $T$ is induced by $n!/d!$ permutations of $[n]$. It follows that any given permutation $\sigma$ conflicts with at most $c = {n\choose d} \times n!/d!$ other permutations. So, any maximal set of pairwise non-conflicting permutations must have size at least $n! / c = d!/{n\choose d}$. $\diamond$
Corollary 1. If $d\ge 3\sqrt n$, then $k^* = \exp(\Theta(d\log d))$.
Proof. By Lemma 1 and calculation from Stirling's approximation,
$$k^* \ge d!/{n\choose d} = \frac{d^{2d+1}\exp(d^2/2n - 2d+O(1))}{n^d} = \exp(\Omega(d\log d))$$ for $d\ge 3\sqrt n$.
For the upper bound, note $k^*\le d!= \exp(O(d\log d))$. $~~~~\diamond$
Lemma 2. If $2\le d\le n^{1/3}$, then $k^* = 2$.
We give two proofs.
Proof 1.
Consider any $d$ with $2\le d\le n^{1/3}$.
To see that $k^*\ge 2$, note that (as Zihan noted in his comment) for $d\ge 2$ every $d$-subset is distinguishable by the identity permutation and its reverse.
To finish we show $k^*\le 2$.
Fix any three permutations $\sigma_1, \sigma_2, \sigma_3$. Assume WLOG that $\sigma_1$ is the identity permutation: $\sigma_1(k) = k$ for $k\in [n]$. We show that some $d$-subset of $[n]$ is not distinguishable by some pair of the three permutations.
If $\sigma_2$ has an increasing subsequence of length $d$, then that subsequence induces the same permutation on its $d$-subset $T$ that $\sigma_1$ does, so $T$ is indistinguishable by $\sigma_1$ and $\sigma_2$, and we are done.
Otherwise, by the Erdős–Szekeres Theorem, $\sigma_2$ has a decreasing subsequence of length $n/d \ge d^2$ on some subset, say $T'$, of $[n]$. On $T'$, $\sigma_1$ is increasing and $\sigma_2$ is decreasing.
Applying the theorem to $\sigma_3$ restricted to $T'$, $\sigma_3$ has either an increasing subsequence of length $\sqrt{d^2} = d$ on some $d$-subset $T''$ within $T'$, or a decreasing subsequence of that length on some $d$-subset $T''$ within $T'$. In the first case, $\sigma_1$ and $\sigma_3$ don't distinguish $T''$. In the second case, $\sigma_2$ and $\sigma_3$ don't distinguish $T''$.$~~\diamond$
Here's an alternate proof of Lemma 2, by adapting the proof of the Erdős–Szekeres Theorem, for those who are interested in the details.
Proof 2. Consider any $d$ with $2\le d\le n^{1/3}$.
To see that $k^*\ge 2$, note that (as Zihan noted in his comment) for $d\ge 2$ every $d$-subset is distinguishable by the identity permutation and its reverse. To finish we show $k^*\le 2$.
Fix any three permutations $\sigma_1, \sigma_2, \sigma_3$. Assume WLOG that $\sigma_1$ is the identity permutation: $\sigma_1(k) = k$ for $k\in [n]$. Assume for contradiction that every $d$-subset $T$ of $[n]$ is distinguishable by each pair of these three permutations.
For each pair $i, j$ with $1\le i < j \le 3$, define $I_{ij}(k)$ to be the maximum size of any subset $T\subseteq [k]$ that contains $k$ such that the order imposed on $T$ by both $\sigma_i$ and $\sigma_j$ is monotonically increasing. Define $D_{ij}(k)$ to be the maximum size of any subset $T\subseteq \{1,\ldots,k\}$ that contains $k$ such that the order imposed on $T$ by both $\sigma_i$ and $\sigma_j$ is monotonically decreasing. Define 3-tuple
$$s(k) = \big(I_{12}(k),\,I_{13}(k),\,D_{23}(k)\big),$$
and $S = \{s(k) : k\in[n]\}.$
Claim 1. For every $k,\ell$ with $1\le k<\ell \le n$, we have $s(k) \ne s(\ell)$.
Before we prove the claim, note that it implies the lemma as follows. The claim implies that $|S| = n$. Each of the three values in any 3-tuple $s(k)$ is in $[d-1]$ (because, for example, there is a subset of $[n]$ of size $I_{12}(k)$ that is not distinguishable by $\sigma_1$ and $\sigma_2$). So $S\subseteq [d-1]^3$, so $n = |S|\le(d-1)^3$, implying that $d>n^{1/3}$, contradicting that $d\le n^{1/3}$ and proving the lemma.
To prove the claim, consider any $k,\ell\in[n]$ with $k<\ell$. Consider the relative order that each of the three permutations induces on the pair $k, \ell$: for each $i\in[3]$, either $\sigma_i(k) < \sigma_i(\ell)$ or $\sigma_i(k) > \sigma_i(\ell)$. Since $\sigma_1$ is the identity, $\sigma_1(k) < \sigma_1(\ell)$.
First consider the case that $\sigma_2(k) < \sigma_2(\ell)$. By definition of $I_{12}$, there is a subset $T$ of $[k]$ that contains $k$ such that $|T| = I_{12}(k)$ and $\sigma_1$ and $\sigma_2$ are monotonically increasing on $T$. So $T' = T\cup\{\ell\}$ is a subset of $[\ell]$ that contains $\ell$ such that $|T'| = I_{12}(k)+1$ and $\sigma_1$ and $\sigma_2$ are monotonically increasing on $T'$. It follows that $I_{12}(\ell) \ge |T'| > I_{12}(k)$. It follows that $s(\ell) \ne s(k)$ in this case.
For the case when $\sigma_3(k) < \sigma_3(\ell)$, by the same argument $I_{13}(\ell) > I_{13}(k)$, so $s(\ell)\ne s(k)$ in that case.
In the remaining case, $\sigma_2(\ell) < \sigma_2(k)$ and $\sigma_3(\ell) < \sigma_3(k)$. By a similar argument $D_{23}(\ell) > D_{23}(k)$. So $s(\ell)\ne s(k)$ in all cases, proving the claim. $\diamond$
EDIT: Comment on the tightness of the proof of Lemma 2. The proof of Lemma 2 shows the existence of a $d$-subset $T$ which is indistinguishable by two of the permutations and that has the following stronger property: the two permutations are both increasing or both decreasing over $T$. Given this, I believe the bound of $\Theta(n^{1/3})$ on $d$ is best possible. That is, I believe that for, say, $d\ge 2n^{1/3}$, choosing appropriate random permutations w.h.p. yields $\exp(\Theta(d\log d))$ permutations such that, for every pair $\sigma$ and $\sigma^*$ of the permutations, there is no $d$-subset $T$ on which $\sigma$ and $\sigma^*$ are both increasing, or both decreasing. (The argument is similar to the proof of Lemma 1 above, with the additional observation that, for a random permutation, w.h.p. there are only about ${n\choose d}/d!$ $d$-subsets on which the permutation is increasing or decreasing.)
So, to strengthen the lemma, the proof would have to somehow consider indistinguishable subsets on which the two permutations are not monotonic. | {
"domain": "cstheory.stackexchange",
"id": 4365,
"tags": "co.combinatorics, permutations"
} |
Do probability wave function moves or it is just sitting there until it interacts? | Question: Imagine an electron is emitted from a source, at this moment the probability wave function of the electron appears... then how come the same electron have to take some time to reach the target such as the screen? I like to neglect the quantum eraser experiment for now since it is disturbing.
Btw Merry Xmas! wishlist for Santa... a XL Hadron Collider ;D
Answer: The wavefunction is the solution of a quantum mechanical equation that is a function, in this case, of (x,y,z,t) for the given boundary conditions. $Ψ^*Ψ$ is the probability of finding the electron at a given (x,y,z,t). It is a solution for all space time, so this answers your:
then how come the same electron have to take some time
the time is within the wavefunction's mathematical form.
If the boundary conditions change by the electron interacting, then a new wavefunction has to be calculated modeling the interaction. | {
"domain": "physics.stackexchange",
"id": 85106,
"tags": "quantum-mechanics, probability, wavefunction-collapse"
} |
Moveit: "Group 'arm' includes joints that have more than 1 DOF | Question:
I have this error message from ROS when loading the model in the C++ ROS node. All joints in the model have only 1 axis of rotation so this message does not make sense. is there any reason why this message might be showing up?
Originally posted by craigc on ROS Answers with karma: 3 on 2017-02-17
Post score: 0
Original comments
Comment by NEngelhard on 2017-02-18:
Could you post your urdf?
Comment by craigc on 2017-02-18:
The code will not post well but the URDF code is hosted at https://github.com/greenpro/sac_description/blob/master/urdf/scorbot_description.xacro
The rest of the description project is at
https://github.com/greenpro/sac_description
Answer:
First: the error message you quote is actually not coming from MoveIt itself, but from the kinematics plugin you have configured for your arm group. MoveIt itself doesn't really care, but plugins like KDL, LMA and others don't support joints with more than a single dof.
As to a possible cause: in greenpro/sac_config/config/andreas_arm.srdf (here) you have:
<group name="arm">
<joint name="virtual_joint" />
...
</group>
...
<virtual_joint name="virtual_joint" type="planar" parent_frame="odom_combined" child_link="world" />
Your arm group includes virtual_joint, which you have configured as a planar joint. Planar joints combine 2 dof, so I think that is where your error message is coming from.
Btw: the virtual joint is typically not included in any group, as it is the joint that connects your robot / cell to the 'world'.
Originally posted by gvdhoorn with karma: 86574 on 2017-02-19
This answer was ACCEPTED on the original site
Post score: 1
Original comments
Comment by gvdhoorn on 2017-02-24:
From greenpro/sac_config@67d1af6463da688cededec1a0def76129ff7209e I have the impression that you've solved the problem by removing the virtual joint frome the arm group?
Comment by craigc on 2017-02-24:
I solved the problem by remaking the project using the setup assistant and changing the joint to a fixed joint. The removal was from a previous attempt to solve the problem. The configuration is now at https://github.com/greenpro/scorbot_config | {
"domain": "robotics.stackexchange",
"id": 27052,
"tags": "ros, moveit, joints"
} |
How to find the projection optimally distinguishing the quantum states $|0\rangle$ and $|+\rangle$? | Question: I have a qubit. The probabality $p$ to find it in either of the two possible states $\{|0\rangle,|+\rangle\}$ is $p = 1/2$. I now want to measure it to maximize the probability that the measurement is correct.
From this presentation (page 5), I know that I can determine the probability as $$\frac{1}{2}+\frac{1}{4}\left\||0\rangle-|+\rangle\right\|_{\rm tr}.$$
But how do I find the associated projection?
Answer: I made a silly mistake in the comments. The measurement you are looking for consists of the two projectors unto the positive and negative subspaces of $|0\rangle\langle 0 | - |+\rangle \langle + |$. In particular, the matrix $|0\rangle\langle 0 | - |+\rangle \langle + |$ can be diagonalised as $\sum_i \lambda_i |\psi_i\rangle \langle \psi_i |$, where the $|\psi_i\rangle
$ form an orthonormal basis and the $\lambda_i$ need not be positive. Let's assume that all the $\lambda_i$ are non-zero, you can check later that this will not really matter.
Now write $$|0\rangle\langle 0 | - |+\rangle \langle + | = \sum_i \lambda_i |\psi_i\rangle \langle \psi_i |\\
= \sum_{\lambda_i>0} \lambda_i |\psi_i\rangle \langle \psi_i | + \sum_{\lambda_i<0} \lambda_i |\psi_i\rangle \langle \psi_i |$$
where I have split up the sum into those where the $\lambda_i$ are positive and negative, respectively.
The projectors unto the so-called positive and negative subspaces are then $\Pi_+ = \sum_{\lambda_i>0} |\psi_i\rangle \langle \psi_i|$ and $\Pi_- = \sum_{\lambda_i<0} |\psi_i\rangle \langle \psi_i|$, and give you the projectors you seek for your measurement.
The above can be generalised to the case where the two states $\rho_1$ and $\rho_2$ are given with unequal probabilities $p_1 \neq p_2$. Then one can repeat the above game, but calculating the positive and negative subspaces of $p_1\rho_1 -p_2\rho_2$ instead. | {
"domain": "physics.stackexchange",
"id": 82707,
"tags": "quantum-mechanics, quantum-information, quantum-measurements"
} |
Why do gases coexist as liquid and vapour? | Question: I have having difficulty in understanding the liquefaction of gases.In the graph
of isotherms of $\ce{CO2}$ I cannot understand how can gas coexist as liquid and vapour under area of $\mathrm{XCEBY}$.
I have read the following statements in my textbook:
At $\pu{21.5 ^\circ C}$, $\ce{CO2}$ remains a gas up to point $\mathrm B$. At point B a liquid of specific volume appears.In fact,the gas and liquid $\ce{CO2}$ coexist along the horizontal line $\mathrm{BC}$. The decrease of volume represents condensation of more and more $\ce{CO2}$ gas till point $\mathrm C$ is reached.
A careful study of isotherms reveal that it is possible to change gas to liquid by following a path in which a single phase is present throughout the process.For example,move vertically from $\mathrm{A}$ to $\mathrm{F}$ by increasing the temperature of the gas.Now move from point $\mathrm{F}$ to point $\mathrm{G}$ by increasing pressure at constant temperature.Move from point $\mathrm{G}$ to point $\mathrm{H}$ by lowering the temperature.As soon as we cross point $\mathrm H$ we get a liquid.
(i)Why $\ce{CO2}$ coexist as liquid and vapour in the area of $\mathrm{XCEBY}$?(instead of converting directly into liquid by condensation of all the molecules simultaneously)
(ii)Why under some range of pressure and temperature $\ce{CO2}$ converts directly into liquid without going through the two-phase region?
Answer:
Vapor-liquid coexistence.
This is possible because changing the system's molar volume $V_\mathrm m$ does not affect the Gibbs free energy of either phase, so equality of the Gibbs free energy (that is, phase coexistence,) can be maintained for a range of $V_\mathrm m$; this is the coexistence region $\mathrm{XCEBY}$.
On the other hand, changing $p$ and $T$ will affect the Gibbs free energy, and if instead we plot this phase diagram on the $p,T$-plane, the entire coexistence region $\mathrm{XCEBY}$ will reduce to a single curve, the liquid-vapor coexistence curve.
In other words: Fix $T$. Only one value of $p$ results in phase coexistence; phase coexistence is a curve on the $p,T$-plane. A range of $V_\mathrm m$ results in phase coexistence; phase coexistence is a region on the $p,V_\mathrm m$-plane.
Phase transitions without coexistence.
This is made possible because the liquid and vapor phases share continuous translational symmetry. In contrast, a phase transition from the liquid phase to a solid, crystalline phase requires breaking this continuous symmetry, resulting instead in the discrete translational symmetry possessed by a crystalline lattice. This shared symmetry permits the possibility of continuously going from one phase to the other without an explicit phase transition.
This possibility is realized past the critical temperature, the temperature represented by the critical point $\mathrm E$. Past the critical isotherm identified by line segment $\mathrm{HE}$ is the supercritical fluid "phase", which shares properties of both liquid and vapor. Isotherms like $\mathrm{GF}$ do not represent a liquid-vapor transition, because the species remains as a supercritical fluid throughout. A liquid-vapor transition that bypasses the coexistence region, like $\mathrm{AFGHD}$, is a continuous transformation from liquid to supercritical fluid to vapor, rather than a discrete phase transition. | {
"domain": "chemistry.stackexchange",
"id": 10742,
"tags": "thermodynamics, gas-laws, kinetic-theory-of-gases"
} |
Data-flow analysis problem adjust to Ullman-Aho's framework? | Question: I am reading the classical book "Compilers. Principles, techniques and tools" by Aho et alii. On chapter 9.3 they talk about a general framework to solve data-flow analysis problems that use a framework which is monotone and of finite height.
The technique is shown to be useful for live variable and reaching definition analysis and I'm wondering if it is applicable to the following problems:
Checking if variables are always initialized.
Do range computations (the idea is to apply it on out of bounds array accesses check).
Eliminate common subexpressions.
My question is if this same framework can be used for this problem or I need more general frameworks such as the constant propagation framework described in chapter 9.4.
If the answer is yes what are the values of the framework defined as $(D,F,V,\land)$, where D is the direction of the analysis, F the family of transfer functions, V is the semilattice domain and $\land$ the semilattice operator? If the answer is no for some of the problems I don't really need this parameters for the more general framework but the reason why it doesn't work would suffice so that I can find a more general framework.
I ask this just in case somebody already know the answer and I can save me some time so don't worry about being too specific.
Answer: Checking initialization: Yes, you can use this framework. You need only a single boolean for each variable. The lattice is $V\to \{\bot,\top\}$, i.e., $2^V$, where $V$ is the set of variables. The height of this lattice is $n+1$ where $n=|V|$ is the number of variables. The transfer functions are monotonic. Consequently, you can use the framework.
Range computation: No. The lattice of ranges has infinite height. Consider, e.g., the sequence of ranges $[0,0]$, $[0,1]$, $[0,2]$, $[0,3]$, and so on: it never ends. Consequently, you need something more, such as widening operators.
Common subexpressions: I don't know of any nice way to express this in that framework (though there could always be something I'm not aware of). | {
"domain": "cs.stackexchange",
"id": 7917,
"tags": "compilers, lattices, data-flow-analysis"
} |
image_compressed problem in rqt_image_view | Question:
Hi,
i'am logging jpeg compressed image in a bag and i can see these images when using rqt_bag. When i try to do live viewing of the image using rqt_image_view (topic played from the bag), the player fails to load the transport image_compressed withe the following error :
Unable to load plugin for transport 'image_compressed', error string:
According to the loaded plugin descriptions the class image_transport/image_compressed_sub with base class type image_transport::SubscriberPlugin does not exist. Declared types are image_transport/compressedDepth_sub image_transport/compressed_sub image_transport/raw_sub image_transport/theora_sub
Any idea on how to fix this ?
Thanks,
Originally posted by jpiat on ROS Answers with karma: 1 on 2016-10-17
Post score: 0
Original comments
Comment by tanasis on 2018-08-01:
I got the same error. For me the fix was to end the topic name with "/compressed", i.e /camera/image_raw/compressed. I had it like: /camera/image_compressed and it was giving me that error.
Comment by Humpelstilzchen on 2018-10-03:
tanasis, please post a new question. You are not supposed to write "compressed", so there is something wrong in your setup, Also check the documentation
Answer:
You are missing compressed_image_transport in your ros installation.
Yes, this question is a little old, but is first hit on google for this error...
Originally posted by Humpelstilzchen with karma: 1504 on 2017-07-29
This answer was ACCEPTED on the original site
Post score: 1
Original comments
Comment by kyubot on 2021-08-17:
This worked for me | {
"domain": "robotics.stackexchange",
"id": 25988,
"tags": "ros, rqt-image-view"
} |
Complexity of DFA intersection in this specific case? | Question: In general, the size of the DFA that recognizes the intersection of $n$ languages is exponential in $n$. However, in my case I am computing the intersection of a very restricted subset of possible languages. I am curious if this weakens the lower complexity bound.
With an alphabet $\Sigma$, for the $i$th language, I have set $A_i \subseteq \Sigma$ and another set $B_i \subseteq \Sigma$. The $i$th language $L_i$ consists of strings containing any number of symbols in $A_i$, followed by one symbol in $B_i$, followed by any number of symbols in $\Sigma$. I would like to find a DFA that recognizes $L = L_1 \cap L_2 \cap ... \cap L_n$.
Do these restrictions on the input languages eliminate the exponential lower bound?
Answer: The precise bound is $2^n$. The lower bound was given in the comments: the state complexity of $A^*a_1A^* \cap \dotsm \cap A^*a_nA^*$ is $2^n$.
For the upper bound, it suffices to observe that if $B$ and $C$ are subsets of the alphabet $A$, then the language $B^*CA^* = (B - C)^*CA^*$ is recognised by a 2-state DFA. It follows that the complexity of the intersection of $n$ such languages is upper bounded by $2^n$. | {
"domain": "cstheory.stackexchange",
"id": 4801,
"tags": "automata-theory, regular-language, dfa"
} |
Travelling in outerspace | Question: Firstly, is it correct that for travel in outer space, the distance that can be travelled with a given amount of fuel is determined by the energy required to overcome the following forces: gravity from nearby objects, drag?
Assuming this is correct, what (roughly) is the difference in the magnitude of these forces, and how does this change for interplanetary, interstellar, and intergalactic space?
I am trying to work out whether the amount of mass being transported is of significance, or is only the amount of drag important.
Answer: The distance you can travel in space is mostly set by the velocity you have and time. It is not like on the surface of Earth, where the distance is largely set by the amount of fuel.
The reason is that friction and drag are almost completely absent in space. If you fire your rocket engine the amount of fuel determines the velocity you get. But in free space that just means you will now coast forever with that velocity, and the distance is set by the amount of time you wait.
An obvious complication is starting from a planet, where a fair bit of the fuel will be spent on overcoming gravity (and some air resistance). If you do not have enough fuel to reach escape velocity from the planet the distance is also going to be limited by the size of your orbit. If you have a moon or other planets within reach you can do clever gravity assist manoeuvres to coast with very little fuel between them, including getting escape velocity from the planetary system. This has less to do with fuel than clever navigation and timing. | {
"domain": "physics.stackexchange",
"id": 65796,
"tags": "rocket-science, propulsion, space-travel, space-mission"
} |
Is it possible for density in pounds per cubic foot, times a volume, to equal a force in pounds? | Question: In the Calculus book "Calculus: Early Transcendentals" by Edwards and Penney, 7th Edition, there is a chapter on Force and Work. In particular, there is a section explaining how to calculate the work done when filling a tank with fluid.
The assumptions of the problem are:
the tank is filled in thin, horizontal layers of fluid, each lifted from its ground position to its final position in the tank
the bottom of the tank is at height $y=a$ and its top at height $y=b>a$.
$A(y)$ is the cross-sectional area of the tank at height $y$
The solution of the problem:
partition $[a,b]$ into n subintervals of length $ \Delta y$
the volume of the i-th horizontal slice is thus $\Delta V_i = \int_{y_{i-1}}^{y_i} A(y)dy = A(y_i^*) \Delta y$ for some $y_i^*$ in $[y_{i-1}, y_i]$ (the last equality follows from the average value theorem for integrals, on the interval $[y_{i-1}, y_i]$
Now here is the part I don't understand, and I think it probably has to do with confusion regarding the system of measurement
suppose $ \rho $ is the density of the fluid (in pounds per cubic
foot, for example), then the force required to lift this slice from the ground to its final position in the tank is simply the (constant) weight of the slice: $$F_i= \rho \Delta V_i = \rho A(y_i^*) \Delta y$$
I see a density times a volume, giving a mass in pounds (which to me is the counterpart to the kilogram unit of mass if we are in a metric system). I googled and found out that indeed there is a unit called a pound of force, which is defined as the force that accelerates 1 pound of mass at 9.80665 meters per second square.
How is the expression above for force a force and not just a mass?
Answer:
How is the expression above for force a force and not just a mass?
It's clearly just a mass, but the author seems to be abusing the fact that the proportionality constant between pounds - as in mass - and pounds of force is $g = 1\,\frac{\mathrm{lbf}}{\mathrm{lb}}$.
So the correct expression for a force would be
$$ F_i= g \, \rho \, \Delta V_i $$
which holds in any unit system, not just the $\mathrm{lb/lbf}$ version. | {
"domain": "physics.stackexchange",
"id": 79516,
"tags": "newtonian-gravity, work"
} |
Tennis serving machine--- How does a spinning ball bounce? | Question: I have an idea of making a tennis serving machine. I will briefly describe what it is:
The machine is configured to serve the ball at a fixed speed to the center of the left (or right) service court
Based on the rotation in 3 directions (X,Y,Z) of the ball, the machine would let the ball land in various positions in the left service court.
How can I determine the relationship between the angular velocity of the ball and the location where it lands?
Answer: If you want to describe the dynamics of the ball, you need to use the SO(3) matrix which describes the ball's orientation. This is a 3 by 3 matrix whose transpose is its inverse. The orientation may be parametrized by Euler angles, and most of the literature on rigid rotating bodies uses this convention. But I think it is best just to use the matrix entries themselves because Euler angles are hard to work with. The orientation matrix itself has a velocity vector which is described by an anti-symmetric matrix.
The center of mass motion of the ball, ignoring air resistance, will be a parabolic arc in the direction of the original motion, and the spin has no effect. The ball will not go off-center just by spinning it unless it collides with some part of the machine going out.
There is asymmetric air drag on the ball when it is rotating, which will lead the ball to arc its trajectory a little bit. This is a small effect. You shouldn't use spin to do this, because the main effect of the spin will be on the bounce when landing, which is going to be impossibly wild given the enormous spin you intend to put on the ball. Human servers can't put too much spin on the ball, because they are limited by the racket design. You are better off just aiming the ball in a different direction for different serves, and if you want to disguise the direction, do it with a reflector plate which the ball bounces off. You should match to experiment, not theory because it will be easier to fit the experimental data with a curve than to predict it from mechanics.
Given your current spin design, you will make inhuman and unanswerable serves.
Reflection of spinning tennis balls
Since you keep asking for this, I worked it out. It is somewhat interesting because there are several issues that one has to keep straight. Most of the answer is determined independent of tennis-ball details, but one quantity, the change in rotation in the plane of reflection, is impossible to predict well.
Consider a tennis ball impacting the z=0 plane, travelling freely with velocity $v_x,v_z$, and with rotation vector $(\omega_x, \omega_y, \omega_z)$. This is the general case
since you choose the z axis perpendicular to the wall, and the x-axis parallel to the velocity in the plane of the wall.
At the moment of impact, the friction force of the ball will quickly and irreversibly enforce the no-slip condition, before any significant deformation of the ball. The reason is that the total impulse (momentum transfer) from the impact is about $2Mv_x$, so that the available friction impulse is of the order of $2\mu Mv_x$, where $\mu$ is the coefficient of friction, which is of order 1, and this is much bigger than the impulse required to enforce no slip or a reasonable range of $\omega$, say 10-500.
No-slip-on-contact means that the friction impulse imparted to the ball in the x-y plane $P_x,P_y$ must satisfy the following:
$$ v_x + {P_x\over M} = R\omega_y - {\alpha P_x\over M}$$
$$ {P_y\over M} = R\omega_x - {\alpha P_y\over M}$$
These conditions enforce that the velocity and the angular velocity after the impulse are those required for no-slip. This gives the impulse. The constant $\alpha$ is the coefficient of the moment of inertia,
$$ I = {2MR^2\over \alpha}$$
For a shell, like a tennis ball, $\alpha=3$.
These conditions determine the outgoing velocity in the x,y directions and the outgoing angular velocity in the x,y directions.
$$\Delta V_x = {R\omega_y - v_x\over 1+\alpha}$$
$$\Delta V_y = {R\omega_x \over 1+\alpha}$$
The z direction is executing a reflection independent of the x and y, because once no-slip is established, the elastic process happens as it would for a non-rotating ball. The final z velocity is $\kappa v_z$ in the opposite direction, so that
$$\Delta v_z = -(1+\kappa)v_z$$
Here $\kappa$ is a phenomenological bounce-loss parameter, for a tennis ball, I would guess about .8 (from bouncing tennis balls, they go back to about 64% of their original height each bounce).
The final values of $\omega_x$ and $\omega_y$ are determined by the no-slip condition :
$$\omega_y^f = {v_x\over R}$$
$$\omega_x^f = {v_y\over R}$$
The undetermined quantity is the final value of $\omega_z$, the rotation in the plane of the impact wall. This rotation is reduced by the friction force as the ball elastically deforms, and bounces off. I will write this as
$$\omega_z^f = q(v_z,\mu) \omega_z$$
Where $q(v_z,\mu)$ is a phenomenological function which you need to parametrize. The friction torque is reduced by the impact area from the friction force, and this is a factor of maybe 1% for a ball at 60 m/s, but the total friction impact available is $2\mu Mv_z$, which is about 100 times the amount needed to stop a reasonable rotation. So these are comparable, and it is not easy to predict how the impact will affect this component of rotation, except that it will reduce it, perhaps by as little as 1%, perhaps as much as 90% per bounce. This needs to be measured for a real tennis ball at real impact speeds. | {
"domain": "physics.stackexchange",
"id": 1578,
"tags": "newtonian-mechanics, projectile, drag, rigid-body-dynamics, angular-velocity"
} |
How does the amount of mass in an atmosphere affect the seasonal changes and dynamics of the planet's climate? | Question: I was thinking about this question, which may turn out to be simple, about climate dynamics: How does the amount of mass in an atmosphere affect the seasonal changes and dynamics of the planet's climate? For example, while I know there are seasons on Mars, there surely isn't as stark of shift between seasons like Earth for example. Perhaps the amount of mass in the atmosphere really isn't a controlling variable? Perhaps composition or even distance to external heat sources is more important?
Answer: Seasons are determined by the degree of tilt of the planet's axis, not the mass of the atmosphere. Mars has an axial tilt slightly larger than Earth, so Mars' seasons are slightly more pronounced than Earth's. For a planet like Venus, which has virtually no rotation and an extreme axial tilt, "seasons" are also affected by the rotation/revolution ratio.
If you are interested in the climate differences between separate planets, mass of the atmosphere does affect overall global temperature (e.g. more atmospheric mass = more heat trapping) but the mass itself is not the main driver of the dynamic changes of climate within an individual atmosphere. Really Mars and Venus don't have as much "short term" climate dynamics like Earth, because they don't have ocean/land dynamics. Though, they definitely have seasons. Earth's "short term" climate dynamics are driven by the heterogeneous distribution of land, ocean, and (to a smaller extent) clouds.
All the planets do share similar long term drivers of climate dynamics, which on Earth are collectively known as the Malenkovitch cycles. The Malenkovich cycles are on the order of 10s of thousands of years and include changes in axial tilt, axial precession, and orbital eccentricity. Some would also argue that long term gravitational changes in orbit parameters due to trojan asteroids and large planets like Jupiter also affect the Malenkovitch cycles. These cycles shift the timing, intensity, and spatial distribution of solar input to the planet. | {
"domain": "earthscience.stackexchange",
"id": 177,
"tags": "meteorology, climate, planetary-science"
} |
How do you get the equation of motion of a spherical pendulum WITHOUT using Lagrange or Hamilton equation? | Question: How do you get the equation of motion of a spherical pendulum WITHOUT using Lagrange or Hamilton equation? I have been searching for a proper explanation but all websites use Lagrangian and I don't know that. Can anyone give me a link or something?
Answer: The idea is very easy (computations are not so easy if you are not familiar with curvilinear coordinates): Write down $\vec{F}=m\vec{a}$ using the basis $\hat{r}, \hat{\theta}, \hat{\varphi}$ associated to spherical coordinates and next project that vectorial equation along the basis of vectors tangent to the sphere, $\hat{\theta}, \hat{\varphi}$. The two equations you find this way do not contain the unknown reaction due to the sphere, as it is normal to it by hypotheses. This pair of equations is the same as the one obtained within the Lagrangian approach.
You have two degrees of freedom and a system of two differential equations which can be proved to satisfy the theorem of existence and uniqueness and thus it determines the motion of the pendulum. As a matter of fact this procedure is nothing but what Lagrangian mechanics automatically does. | {
"domain": "physics.stackexchange",
"id": 78576,
"tags": "homework-and-exercises, newtonian-mechanics"
} |
Remove repetitive region vcf file using repeatmasker bed file | Question: I have a 1000 genomes vcf file for chromosome 14. And I want to remove variants in repetitive regions flagged by repeatMasker. I have a bed file for those repeats. I downloaded that file from UCSC. How can I eliminate/remove those sites in vcf file using repeat masker's bed file? Insights will be appreciated.
Answer: A couple fast alternatives:
$ bedops --chrom chr14 -n 1 <(vcf2bed < variants.vcf) <(sort-bed repeats.bed) > answer.bed
$ bedops --chrom chr14 -n 1 <(vcf2bed < variants.vcf) <(rmsk2bed < repeats.rmsk) > answer.bed
Using --chrom chr14 focuses set operations on that chromosome. | {
"domain": "bioinformatics.stackexchange",
"id": 1832,
"tags": "vcf, snp, bedtools, repeatmasker, variants"
} |
Why does work done for polarization per unit volume contain $1\over 2$as in $\frac{1}{2} \mathbf E\cdot \mathbf P?$ | Question: Work done per unit volume to change the polarization from $0$ to $\bf P$ is given as the integral of $\mathbf E\cdot d\mathbf P'$ as $$u_p= \int_0^{\bf P}\mathbf E\cdot d\mathbf P' \;$$ integrating which it gives \begin{align}u_p&=\mathbf E\int_0^{\bf P} d\mathbf P'\\&= \mathbf E\;( \mathbf P')|_0^{\bf P}\\&= \mathbf E\cdot \mathbf P \end{align}
So, how did $1\over 2$ come in the relation above?
But Feynman did this otherwise; he included $1\over 2$ as is written in this excerpt from his lecture:
[...] the work per unit volume is found to be
$$\boldsymbol{E}⋅d\boldsymbol{P}.$$
Since the magnitude of $\boldsymbol P$ is proportional to $\boldsymbol E,$ the work done per unit volume in bringing the polarization from $0$ to $\boldsymbol P$ is the integral of $\boldsymbol E⋅d\boldsymbol P.$ Calling this work $u_P$, we write
$$u_P=\frac{1}{2}\boldsymbol E⋅\boldsymbol P=\frac{1}{2}\sum_i E_iP_i$$ [...]
Where did $1\over 2$ come from? I'm not getting that.
Answer: Since $\textbf{E}\equiv \textbf{E}(\textbf{P})$ one cannot pull it out of the integral sign.
Using the correct relation $E^i = \alpha^i_{\phantom{i}j}\,P^j$ and replacing the before within the integral sign gives back the $1/2$ after integration. | {
"domain": "physics.stackexchange",
"id": 27203,
"tags": "classical-electrodynamics, polarization"
} |
Interference with a minus sign | Question: In Lectures on Physics, by Richard Feynman, pg 3-11, I found the following:
In case of electrons, the interfering amplitudes for exchange interfere with a negative sign.
I was unable to understand this. On reading further, it seems that electrons have spins unlike alpha particles and that causes them them to interfere in this manner.
I am unable to understand the connection between the statement and the reason given. I would be grateful for any clarity on this matter.
I didn't truly understand the + sign either, but it made more sense when I thought about it like either this or that happens to reach the final state, there are two ways to get there, so I need to add the probability amplitudes of both to get the final amplitude. (We always use + to indicate or in probability.)
Answer: Strictly speaking, Feynman at this point did not give a reason for why the interference is so peculiar for electrons. He just gave a rule. The discussion on pg 3-12 about spins that followed immediately was not to give a reason for the minus sign. There the point was, if you can measure spins, you can distinguish electrons and, therefore, there will be no interference at all (the probabilities and not amplitudes will add up).
Now to your question. My explanation below is not discussing the same experiment as on pg 3-11 of Feynman. But if you think about it carefully, you will see the connection. The interference occurs when we are talking about identical particles. Consider two identical particles. We describe their state by some probability amplitude. E.g., the square of this amplitude gives you probability of finding one electron at point A and another electron at point B. Imagine that you exchanged the two particles. In this process, something can happen to the amplitude, but only in such a way as to keep the square the same (if we exchange two identical particles, the probability of finding these two particles at points A and B will not change). Mathematically, this means that exchange operation can only affect the complex phase of the original probability amplitude (probability amplitude gets multiplied by $e^{i\varphi}$ with some $\varphi$). Now imagine, you exchange the two particles again. The amplitude again changes (by the same factor $e^{i\varphi}$). However, two exchanges is the same thing as not exchanging at all! So after two exchanges, you must have the original probability amplitude. In the end, this means that there could be two possibilities. The exchange operation keeps probability amplitude the same (trivial case) and the exchange operation multiplies the amplitude by a -1 (non-trivial). Now, this thinking will not lead any further, in a sense it cannot explain why electrons behave the way they do. Experimental evidence suggests that Nature realizes both cases, those particles that do not change the sign of amplitude upon exchange (bosons) and those that do change the sign of amplitude (fermions). Electrons belong to the second category. That's it. This is experimental fact, which we have to accept. At least this is the spirit, in which Feynman explains Quantum Mechanics. We cannot always understand all laws of nature, but we can still describe them (at least we hope to).
And yes, there is a connection to spins. Fermions can only have half-integer spins, bosons can only have integer spins. But this is too deep. Later on pg 4-3 Feynman talks about this relation (apologizing for not being able to explain any better) saying that Pauli derived it using quantum field theory and relativity. | {
"domain": "physics.stackexchange",
"id": 32820,
"tags": "quantum-mechanics, probability, identical-particles"
} |
Memory-efficient string collection | Question: My goal is to create a memory-efficient (immutable) collection of strings. The imagined use-case is checking for valid words in a Scrabble-like game.
Wikimedia Commons has a pretty good summary of the data structure (author: Chkno):
(Image license: Creative Commons Attribution-Share Alike 3.0 Unported.)
For an input of { "tap", "taps", "top", "tops" }, StringCollection should construct the figure on the right. The only difference is that instead of an EOW link, states are marked as final.
The algorithm for constructing the data structure is from the paper Incremental construction of minimal acyclic finite-state automata.
namespace Mjolka.Collections
{
using System;
using System.Collections.Generic;
using System.Text;
/// <summary>
/// Represents a memory-efficient collection of strings.
/// </summary>
[Serializable]
public class StringCollection : IEnumerable<string>
{
/// <summary>
/// The initial state of the finite-state automaton.
/// </summary>
private readonly State initialState;
/// <summary>
/// The number of elements in the collection.
/// </summary>
private readonly int count;
/// <summary>
/// Initializes a new instance of the <see cref="StringCollection"/> class that contains
/// the specified strings, where the strings are in lexicographic order.
/// </summary>
/// <param name="strings">
/// The collection of strings that are in the new <see cref="StringCollection"/>, in
/// lexicographic order.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="strings"/> is <c>null</c>.
/// </exception>
/// <exception cref="ArgumentException">
/// An item in <paramref name="strings"/> is <c>null</c>.
/// </exception>
public StringCollection(IEnumerable<string> strings)
{
if (strings == null)
{
throw new ArgumentNullException("strings");
}
var register = new Dictionary<State, State>(new StateComparer());
using (var enumerator = strings.GetEnumerator())
{
if (!enumerator.MoveNext())
{
return;
}
if (enumerator.Current == null)
{
throw new ArgumentException("strings cannot contain null", "strings");
}
if (string.IsNullOrEmpty(enumerator.Current))
{
this.initialState = new FinalState();
}
else
{
this.initialState = new State();
AddSuffix(this.initialState, enumerator.Current.ToCharArray());
}
this.count = 1;
while (enumerator.MoveNext())
{
var word = enumerator.Current;
if (word == null)
{
throw new ArgumentException("strings cannot contain null", "strings");
}
var chars = word.ToCharArray();
int prefix;
var lastState = this.CommonPrefix(chars, out prefix);
if (lastState.HasChildren)
{
ReplaceOrRegister(lastState, register);
}
var suffix = new ArraySegment<char>(chars, prefix, word.Length - prefix);
AddSuffix(lastState, suffix);
this.count++;
}
}
ReplaceOrRegister(this.initialState, register);
register.Clear();
}
/// <summary>
/// Gets the number of strings contained in the <see cref="StringCollection"/>.
/// </summary>
public int Count
{
get { return this.count; }
}
/// <summary>
/// Determines if the <see cref="StringCollection"/> contains the specified value.
/// </summary>
/// <param name="value">
/// The value to locate in the <see cref="StringCollection"/>.
/// </param>
/// <returns>
/// <code>true</code> if the <see cref="StringCollection"/> contains the specified value;
/// otherwise, <code>false</code>.
/// </returns>
public bool Contains(string value)
{
if (value == null)
{
return false;
}
var state = this.initialState;
foreach (var c in value.ToCharArray())
{
var nextState = state.Transition(c);
if (nextState == null)
{
return false;
}
state = nextState;
}
return state.IsFinal;
}
/// <summary>
/// The get enumerator.
/// </summary>
/// <returns>
/// The <see cref="Enumerator"/>.
/// </returns>
public Enumerator GetEnumerator()
{
return new Enumerator(this);
}
/// <summary>
/// The get enumerator.
/// </summary>
/// <returns>
/// The enumerator.
/// </returns>
IEnumerator<string> IEnumerable<string>.GetEnumerator()
{
return new Enumerator(this);
}
/// <summary>
/// The get enumerator.
/// </summary>
/// <returns>
/// The enumerator.
/// </returns>
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return new Enumerator(this);
}
/// <summary>
/// Counts the number of states in the finite-state automaton.
/// </summary>
/// <returns>
/// The number of states in the finite-state automaton.
/// </returns>
internal int CountStates()
{
var seen = new HashSet<State>();
var stack = new Stack<State>();
stack.Push(this.initialState);
while (stack.Count > 0)
{
var state = stack.Pop();
if (!seen.Add(state))
{
continue;
}
foreach (var child in state.Children)
{
stack.Push(child.State);
}
}
return seen.Count;
}
/// <summary>
/// Adds a suffix to a state.
/// </summary>
/// <param name="state">
/// The state to add the suffix to.
/// </param>
/// <param name="suffix">
/// The suffix to add to the state.
/// </param>
private static void AddSuffix(State state, IList<char> suffix)
{
var length = suffix.Count - 1;
for (var i = 0; i < length; i++)
{
var newState = new State();
state.AddEdge(suffix[i], newState);
state = newState;
}
state.AddEdge(suffix[length], new FinalState());
}
/// <summary>
/// Replaces a state or inserts it into the register.
/// </summary>
/// <param name="state">
/// The state to replace or insert into the register.
/// </param>
/// <param name="register">
/// The register.
/// </param>
private static void ReplaceOrRegister(State state, IDictionary<State, State> register)
{
var child = state.LastChild;
if (child == null)
{
return;
}
if (child.HasChildren)
{
ReplaceOrRegister(child, register);
}
State replacement;
if (register.TryGetValue(child, out replacement))
{
state.LastChild = replacement;
}
else
{
register.Add(child, child);
}
}
/// <summary>
/// Gets the common prefix of a word and the finite-state automaton.
/// </summary>
/// <param name="word">
/// The word to find the common prefix of.
/// </param>
/// <param name="prefixLength">
/// The length of the common prefix.
/// </param>
/// <returns>
/// The last <see cref="State"/> in the common prefix.
/// </returns>
private State CommonPrefix(IList<char> word, out int prefixLength)
{
var state = this.initialState;
var length = word.Count;
for (var i = 0; i < length; i++)
{
var next = state.Transition(word[i]);
if (next == null)
{
prefixLength = i;
return state;
}
state = next;
}
prefixLength = length;
return state;
}
/// <summary>
/// Represents a labeled edge from one state to another.
/// </summary>
[Serializable]
private struct Edge
{
/// <summary>
/// The edge label.
/// </summary>
public readonly char Label;
/// <summary>
/// The edge state.
/// </summary>
public readonly State State;
/// <summary>
/// Initializes a new instance of the <see cref="Edge"/> struct.
/// </summary>
/// <param name="label">
/// The edge label.
/// </param>
/// <param name="state">
/// The edge state.
/// </param>
public Edge(char label, State state)
{
this.Label = label;
this.State = state;
}
}
/// <summary>
/// The path segment.
/// </summary>
private struct PathSegment
{
/// <summary>
/// The label.
/// </summary>
public readonly char Label;
/// <summary>
/// The depth.
/// </summary>
public readonly int Depth;
/// <summary>
/// Initializes a new instance of the <see cref="PathSegment"/> struct.
/// </summary>
/// <param name="label">
/// The label.
/// </param>
/// <param name="depth">
/// The depth.
/// </param>
public PathSegment(char label, int depth)
{
this.Label = label;
this.Depth = depth;
}
}
/// <summary>
/// The enumerator.
/// </summary>
public class Enumerator : IEnumerator<string>
{
/// <summary>
/// The initial state.
/// </summary>
private readonly State initialState;
/// <summary>
/// The string builder.
/// </summary>
private readonly StringBuilder stringBuilder;
/// <summary>
/// The states to traverse next.
/// </summary>
private readonly Stack<State> states;
/// <summary>
/// The edges leading to the states on the stack.
/// </summary>
private readonly Stack<PathSegment> edges;
/// <summary>
/// Initializes a new instance of the <see cref="Enumerator"/> class.
/// </summary>
/// <param name="stringCollection">
/// The string collection.
/// </param>
public Enumerator(StringCollection stringCollection)
{
this.initialState = stringCollection.initialState;
this.stringBuilder = new StringBuilder();
this.states = new Stack<State>();
this.states.Push(this.initialState);
this.edges = new Stack<PathSegment>();
}
/// <inheritdoc />
public string Current
{
get { return this.stringBuilder.ToString(); }
}
/// <inheritdoc />
object System.Collections.IEnumerator.Current
{
get { return this.Current; }
}
/// <inheritdoc />
public bool MoveNext()
{
// Move to the next FinalState, adding chars in the
// path to this.stringBuilder.
while (this.states.Count > 0)
{
var state = this.states.Pop();
var depth = -1;
if (this.edges.Count > 0)
{
var edge = this.edges.Pop();
depth = edge.Depth;
if (depth < this.stringBuilder.Length)
{
this.stringBuilder.Remove(depth, this.stringBuilder.Length - depth);
}
var label = edge.Label;
this.stringBuilder.Append(label);
}
var children = state.Children;
if (children != null)
{
depth = depth + 1;
for (var i = children.Length - 1; i >= 0; i--)
{
var child = children[i];
this.edges.Push(new PathSegment(child.Label, depth));
this.states.Push(child.State);
}
}
if (state.IsFinal)
{
return true;
}
}
return false;
}
/// <inheritdoc />
public void Reset()
{
this.stringBuilder.Clear();
this.states.Clear();
this.states.Push(this.initialState);
this.edges.Clear();
}
/// <inheritdoc />
public void Dispose()
{
}
}
/// <summary>
/// Represents a state in the finite-state automaton.
/// </summary>
[Serializable]
private class State
{
/// <summary>
/// The edges out of the state.
/// </summary>
private Edge[] children = new Edge[0];
/// <summary>
/// Gets a value indicating whether the state has children.
/// </summary>
public bool HasChildren
{
get { return this.children.Length > 0; }
}
/// <summary>
/// Gets or sets the last edge out of the state.
/// </summary>
public State LastChild
{
get
{
var length = this.children.Length;
return length > 0
? this.children[length - 1].State
: null;
}
set
{
var lastIndex = this.children.Length - 1;
var lastChild = this.children[lastIndex];
this.children[lastIndex] = new Edge(lastChild.Label, value);
}
}
/// <summary>
/// Gets a value indicating whether the state is final.
/// </summary>
public virtual bool IsFinal
{
get { return false; }
}
/// <summary>
/// Gets the children.
/// </summary>
public Edge[] Children
{
get { return this.children; }
}
/// <summary>
/// Gets the state corresponding to the edge with the specified label out of the state,
/// if it exists.
/// </summary>
/// <param name="label">
/// The label of the edge out of the state.
/// </param>
/// <returns>
/// The <see cref="State"/> corresponding to the edge with the specified label.
/// </returns>
public State Transition(char label)
{
var length = this.children.Length;
for (var i = 0; i < length; i++)
{
var child = this.children[i];
if (child.Label == label)
{
return child.State;
}
}
return null;
}
/// <summary>
/// Adds an edge out of the state.
/// </summary>
/// <param name="label">
/// The label of the edge to the specified state.
/// </param>
/// <param name="state">
/// The state.
/// </param>
public void AddEdge(char label, State state)
{
var length = this.children.Length;
var newChildren = new Edge[length + 1];
Array.Copy(this.children, newChildren, length);
newChildren[length] = new Edge(label, state);
this.children = newChildren;
}
}
/// <summary>
/// Represents a final state in the finite-state automaton.
/// </summary>
[Serializable]
private sealed class FinalState : State
{
/// <inheritdoc />
public override bool IsFinal
{
get { return true; }
}
}
/// <summary>
/// Represents a state comparer.
/// </summary>
private class StateComparer : IEqualityComparer<State>
{
/// <inheritdoc />
public bool Equals(State left, State right)
{
if (left.IsFinal != right.IsFinal)
{
return false;
}
var leftChildren = left.Children;
var rightChildren = right.Children;
if (leftChildren.Length != rightChildren.Length)
{
return false;
}
for (var i = 0; i < leftChildren.Length; i++)
{
var leftChild = leftChildren[i];
var rightChild = rightChildren[i];
if (leftChild.Label != rightChild.Label || leftChild.State != rightChild.State)
{
return false;
}
}
return true;
}
/// <inheritdoc />
public int GetHashCode(State obj)
{
unchecked
{
var result = obj.IsFinal ? 17 : 521;
foreach (var child in obj.Children)
{
result = (31 * result) + child.Label.GetHashCode();
result = (31 * result) + child.State.GetHashCode();
}
return result;
}
}
}
}
}
The code and unit tests are available on GitHub.
All feedback/improvements are welcome. There are some parts I'm not particularly happy with:
The special-casing of the empty string in the constructor
Using an out parameter in CommonPrefix
All of Enumerator.MoveNext
Edit: Subclassing State and using Edge[] instead of List<Edge> were guided by profiling. Here are some stats from dotMemory:
Test input: BritishWords.txt. 79,764 words, 776,045 bytes.
Build: .NET 4.5/x86/Release.
Code as posted here:
Retained Bytes
StringCollection 1,469,008
Using a boolean field for IsFinal instead of subclassing State:
StringCollection 1,612,224
Using List<Edge> (andTrimExcess) instead of Edge[]:
StringCollection 2,360,732
In comparison, using a HashSet<string> (which requires the strings to also be in memory):
Objects Count Bytes
string 79,764 2,509,260
Retained Bytes
HashSet<string> 1 1,448,432
---------
3,957,692
Of course, for many applications, 2.5MB is just a rounding error, but sometimes it matters. I'm just trying to reduce memory usage as a learning exercise.
Answer: For this answer, I'll work on the following assumptions, so tell me if any of them are wrong:
You're most interested in memory efficiency
You're not so interested in time efficiency, especially within the initial construction of the collection
You're happy to use LINQ
Enumerator
The first thing I notice here are the stacks. And the first thing that makes me think: recursion! You're not only worrying about keeping two stacks aligned, but you also have to keep track of how deep you are inside them. Taking advantage of the call stack to take care of that for you makes life a lot easier.
So start with the signature:
private IEnumerable<string> Next(State state, PathSegment? edge, StringBuilder builder)
You know the State and PathSegment? need to be in there because they're the ones in stacks. The way I've done it I've replaced the class with an iterator method, which necessitates the StringBuilder being passed back and forth rather than being kept as a class-level variable.
From there, it's fairly simple to rework what you have currently to a new version:
private IEnumerable<string> Next(State state, PathSegment? edge, StringBuilder builder)
{
if (edge != null)
{
builder.Append(edge.Value.Label);
}
if (state.IsFinal)
yield return builder.ToString();
foreach (var child in state.Children)
{
var nextEdge = new PathSegment(child.Label, 0);
foreach (var result in Next(child.State, nextEdge, builder))
yield return result;
}
if(builder.Length > 0)
builder.Remove(builder.Length - 1, 1);
}
Notice that by taking advantage of the call stack, depth isn't needed at all, we just remove the last character from the builder before exiting the method. This means that we can actually get rid of the PathSegment class altogether and use Edge directly instead!
After applying that, the next thing that stands out is this line:
foreach (var result in Next(child.State, child, builder))
It doesn't seem like we should have to pass both child.State and child. So let's simplify further:
private IEnumerable<string> Next(Edge edge, StringBuilder builder)
{
var state = edge.State;
if (state.IsFinal)
yield return builder.ToString();
foreach (var child in state.Children)
{
builder.Append(child.Label);
foreach (var result in Next(child, builder))
yield return result;
}
if (builder.Length > 0)
builder.Remove(builder.Length - 1, 1);
}
Note that labels are now appended before calling into the method recursively, rather than at the beginning. This is so that we can do:
public IEnumerable<string> StringEnumerator()
{
var entryEdge = new Edge('\0', initialState);
return Next(entryEdge, new StringBuilder());
}
You can plonk this directly in your StringCollection class and use it for your GetEnumerator. | {
"domain": "codereview.stackexchange",
"id": 8573,
"tags": "c#, strings"
} |
gazebo crashes after C-c pr2_teleop | Question:
This happens every time so that I have to open gazebo and rviz (+ re-size those windows as I prefer). Since I'm just reporting the particular phenomenon & reproduction scenario I've been seeing, I don't know if this issue can be generalized. Any idea is appreciated.
Phenom:
Every time I C-c pr2_teleop, gazebo and rviz crash after that.
error msg in the terminal pr2_gazebo was opened in:
[gazebo-*2] process has died [pid 15754, exit code -11].
log files: /home/icg-dell-m6400/.ros/log/030eb44a-c82c-11e0-b04d-0026b9168399/gazebo-2*.log
[base_hokuyo_node-15] process has died [pid 15783, exit code -11].
log files: /home/icg-dell-m6400/.ros/log/030eb44a-c82c-11e0-b04d-0026b9168399/base_hokuyo_node-15*.log
[tilt_hokuyo_node-16] process has died [pid 15785, exit code -11].
log files: /home/icg-dell-m6400/.ros/log/030eb44a-c82c-11e0-b04d-0026b9168399/tilt_hokuyo_node-16*.log
[camera_synchronizer_node-18] process has died [pid 15800, exit code -11].
log files: /home/icg-dell-m6400/.ros/log/030eb44a-c82c-11e0-b04d-0026b9168399/camera_synchronizer_node-18*.log
gazebo-2*.log: see http://pastebin.com/gchDEBSD
Env: Ubuntu 10.10, ros-diamondback-all as of Aug 16, '11. Memory 3.9 GB, Intel Core 2 Duo 2.53 GHz. Dell Precision M6400. nVidia Corporation G94M [Quadro FX 2700M], OpenGL version string: 3.3.0 NVIDIA 260.19.06
Thanks.
(UPDATE; Aug 18, 2011)
Ok I tried 2 patterns of booting order below, and I found Segfault only sometimes occurs while gazebo is running with gdb. For the 1st order below, I couldn't get backtrace. Here's the result backtraced for the 2nd one. http://pastebin.com/hcBcPNpU (however bt returned only 1 line and it seems not much new info). I also updated the environment info since it might be hardware related according to the Segfault error content.
Order-1. gazebo -> teleop -> gdb -> C-c teleop (nothing special occurs) -> teleop -> C-c teleop (gazebo crashes, gdb says "No stack")
Order-2. gazebo -> gdb -> teleop -> C-c teleop (SegFault occurs) -> teleop -> Type "cont" on gdb (gazebo crashes, gdb says "No stack")
Command used to run the programs:
gazebo: roslaunch pr2_gazebo pr2_empty_world.launch
teleop: roslaunch pr2_teleop teleop_keyboard.launch
(Update Aug 22, '11)
This phenom doesn't occur on my another machine that uses NVIDIA driver as well.
Env: Ubuntu 11.04, Kernel 2.6.38-11-generic, GNOME 2.32.1, nVidia Corporation Device 1251
Originally posted by 130s on ROS Answers with karma: 10937 on 2011-08-16
Post score: 0
Original comments
Comment by 130s on 2011-08-18:
@hsu I added commands I used for gazebo & teleop in the question body.
Comment by 130s on 2011-08-18:
@Eric Perko For the log with backtrace, please see the question body that I just updated. Thx
Comment by hsu on 2011-08-18:
in addition to bt output, please also pose the roslaunch commands you use to start things up. thanks.
Comment by Eric Perko on 2011-08-18:
@IsaacS: when you get the SegFault in GDB, type "bt" to get a backtrace and paste that here or to pastebin. The backtrace will be much more helpful than the normal startup output since it should show exactly where the segfault occurs.
Comment by 130s on 2011-08-18:
@hsu Now I can dump with gdb. Here's the result. http://pastebin.com/2Z5aCmxj I see a Segmentation Fault occurs, but not yet figured out what's the root cause.
Comment by 130s on 2011-08-16:
@hsu thanks. All of them are executed on different terminals (am I answering your question?). I've been failing to gdb and posted a new question for that (http://answers.ros.org/question/1886/gdb-says-program-is-not-being-run-upon-gazebo).
Comment by hsu on 2011-08-16:
How are you starting up pr2_teleop/gazebo/rviz? make sure they are not in the same launch script. Can you get a backtrace or coredump of gazebo? (see http://www.ros.org/wiki/pr2_simulator/Tutorials/RunningSimulatorWithGDB for reference)
Answer:
Just a workaround. I changed the version of the driver to the older version as follows:
previously in use) 260.19.06 NVIDIA
accelerated graphics driver (version
current)
new) 173.14.28 NVIDIA
accelerated graphics driver (version
173)
Changed by "System"->"Administration"->"Additional Drivers".
Don't know what unexpected effects might happen though.
Although I'm talking about the workaround in very specific case, I hope it helps others who have similar issue.
Originally posted by 130s with karma: 10937 on 2011-08-22
This answer was ACCEPTED on the original site
Post score: 0 | {
"domain": "robotics.stackexchange",
"id": 6434,
"tags": "gazebo, rviz"
} |
Complement of HAMPATH | Question: Is the complement of the Hamiltonian Path problem known to be in $\mathsf{NP}$? I could not find explanations saying that it is, but then neither were there any claims saying that it is not in $\mathsf{NP}$.
Answer: The HAMPATH complement ("G does not contain an Hamiltonian path from s to t") is in co-NP; to be more precise it is co-NP complete (it is easy to prove that $L$ is NP-complete if and only if its complement $\bar{L}$ is co-NP-complete).
The question if it is in NP is open.
But since HAMPATH is NP-complete, if its complement is in $\mathsf{NP}$ then $\mathsf{NP} = \mathsf{co\mbox{-}NP}$ | {
"domain": "cs.stackexchange",
"id": 562,
"tags": "complexity-theory, decision-problem"
} |
Resistors in parallel - finding total current | Question:
I am given this circuit, where $R_1 = 4.00 \Omega$, $R_2=8.00 \Omega$, and $R_3 =5.00\Omega$. I was given by the problem statement that $I_2$, the current through $R_2$ is $I_2=4\text{A}$. I found the current through $R_1$ to be $I_1 = 8 \text{A}$. I used the relation $\frac{I_1}{I_2} = \frac{R_2}{R_1}$ to solve for $I_1$.
The next part of the problem asks us to find the current $I_3$ through $R_3$. Here is what I tried to do:
I considered the part of $R_1$ and $R_2$ as one combined parallel component to $R_3$. Since $R_1$ and $R_2$ are parallel (WRT each other), I did $\frac{1}{R_{eq}} = \frac{1}{R_1}+\frac{1}{R_2}$. Then I summed their currents, $I_{eq} = I_1 + I_2$.
I am not sure if that last step where I summed their currents is legal.
Is the right idea to treat the $R_1$ and $R_2$ parts as one component parallel to $R_3$? I wanted to use the relation $\frac{I_{eq}}{I_3}=\frac{R_3}{R_{eq}}$, where $I_{eq}$ and $R_{eq}$ denote the whole $R_1$ and $R_2$ component.
Answer: Yes, what you did is correct. You have rediscovered Kirchoff's current law.
Consider the point I've marked with the red circle where the wires from R₁ and R₂ meet. The current flowing into this point has to be the same as the current flowing out of that point, and that means:
$$ I_1 + I_2 = I_3 $$
Analysing a circuit by looking at the nodes, i.e. the points where wires join, is known as nodal analysis and it's an important part of your toolbox. | {
"domain": "physics.stackexchange",
"id": 95847,
"tags": "electric-circuits, electric-current, electrical-resistance"
} |
Write a parabolic equation in kinematics | Question: How might I go about writing a parabolic equation in standard form $ax^2 + bx + c$ given all of the following measurements:
$X_0, X_f, Y_o, Y_f$: the initial and final x and y positions.
$V_{x0}, V_{xf}, V_{y0}, V_{yf}$: the initial and final x and y velocities.
$t_x, t_y$: the time it takes for $x_0$ to transition to $x_f$; same for y. These are equal in parabolic equations.
$a_x, a_y$: acceleration in x and y.
I don't know how I would give the trajectory as a normal parabola from this data because I'm not sure which variables to substitute and where into $ax^2 + bx + c$.
Answer: You may be overthinking it. In general when you need to solve for coefficients you first need to ask what relates the coefficients? In this case it doesn't seem you've written precisely what equation you want. In your post, you've written the parabola in terms of x. Do you mean you want y position as a function of x position? This isn't the standard way to go about it, normally the most useful method is to give x and y in terms of t.
If the parabolic equation gives the height of the ball at time t: $y(t)=a t^2+b t+c$ and a linear equation gives the position of the ball at time t: $x(t)=d t$, and if we assume gravity is directed downwards giving an acceleration of $g$ we can clearly see that $d=V_{x0}=V_{xf}=(X_f-X_0)/(t)$. (gravity does not change the horizontal velocity at all)
Now, gravity dictates the ball's acceleration completely, which tells us $a=-\frac{g}{2}$. That leaves two constants, and so we need to come up with two equations to solve for them. If we are given the initial and final positions and the time taken to go between the states, we don't need velocities at all. The two equations are:
$$Y_0=y(t_0)=a t_0^2+b t_0+c$$
$$Y_f=y(t_f)=a t_f^2+b t_f+c$$
or, written more clearly for our purposes:
$$b t_0+c=Y_0-a t_0^2$$
$$b t_f+c=Y_f-a t_f^2$$
(written in this form because it's a standard format in linear algebra for a system of linear equations and helps isolate the unknowns)
These simultaneous equations can be solved for $b$ and $c$ in terms of the other components. (try subtracting one equation for the other), giving us all the coefficients.
If you wanted to solve for $y$ in terms of $x$, first solve for $t$ in terms of $x$ and then substitute that value of $t$ into the equation for $y$. | {
"domain": "physics.stackexchange",
"id": 10483,
"tags": "kinematics"
} |
What does it mean if a high or low number of my componenets describe a percentage of the cumulative explained variance? | Question: In the following code run after PCA i can see that X number of components explain Y % of cumulative explained variance (CEV).
I would like to know
1- What percentage of the CEV is typically acceptable e.g. 95% or 99%? (Or is it a case by case basis?)
2- If 20 out of 200 components explain 95% of the CEV, what does this say about my data, what about when 200 out of 200 explain 95% ?
pca = PCA().fit(X_train)
plt.plot(np.cumsum(pca.explained_variance_ratio_))
plt.xlabel('Number of components')
plt.ylabel('cumulative explained variance');
Answer: I always think that Principal component analysis is a very interesting tool. Many know its applications, few knows exactly what is going on.
If you care about the math, you need to study eigen values and eigen vectors, but here let me explain pca in a very simple way. Imagine that you have a point in a 2-d space (x, y), this same point can be represented by using another two values, let us say (r, theta), where r is the distance from the origin and theta is the angle with respect to the +v x-axis.
Given any point (x,y), you can find the point (r, theta) corresponding to the point (x,y). You should be able to move between the two coordinates easily. Now let us ask the following question:
If I decide to ignore the theta dimension (for example set it to zero) how many points in the (x,y) you still can recover? All the points across the +ve x-axis can be recovered correctly. Now what about the r dimension, if we set it to zero, we can recover only one point which is the origin point.
Principal component analysis helps find this new coordinate system depending on the data, number of dimensions and variation across each dimension. The higher variation across dimension the more important to reserve this dimension. Very important to know that pca proposes both new coordinates and a measure of how much each dimension is important to recover the points in the original coordinate.
For example, let us take these points,
(1,1)
(2,2)
(3,3)
Both x and y dimensions are important and they experience the same variation.
If we transform, these data points into a new coordinate system (k,m), such that
K=x. And. M=0
Then. K is very important 100% and m is not important at all 0%
You can recover the original points by using, x=k. And y=k. Note that the variation across the m dimension is zero and it is high across the k dimension.
How much you want to reserve depends mainly on the application, usually > 95% is good.
For the second question, it is possible to recover less than 100% when you use less dimensions, but when you use 200 of 200 you should be able to recover 100%. | {
"domain": "datascience.stackexchange",
"id": 3924,
"tags": "machine-learning, pca"
} |
Why is static-single assignment preferred over continuation passing style in many industry-used compilers? | Question: According to the Wikipedia page on static-single assignment (SSA), SSA is used by large and well-known projects such as LLVM, GCC, MSVC, Mono, Dalvik, SpiderMonkey, and V8 while the page on projects using continuation-passing style (CPS) is a bit lacking in comparison.
I have this notion that CPS is preferred by compilers and interpreters that implement primarily functional languages -- particularly, Haskell and Scheme seem to have strong inclinations towards CPS style due to the restrictions on mutation or need for first-class continuation support (I would guess that Smalltalk would possibly need this as well). The major literature that I've encountered that uses CPS seems to be those that are primarily working on Scheme or are related to Scheme in some respect.
Is there any particular reason why SSA is used in industry besides momentum of adoption? SSA and CPS have a close relationship; that means that it would be easy to state either in terms of another, but perhaps the information representation would be less compact or less efficient for CPS.
Answer: I imagine many compiler implementers for typical imperative languages simply weren't that familiar with CPS and CPS-based compilation techniques. In the functional programming community both CPS and CPS-based compilation are very well-known techniques - the latter from Guy Steele's work. Nevertheless, even in the FP community, most compilers don't use CPS-based techniques for compilation unless the language itself supports control operators like call/cc. Something more like Administrative Normal Form (ANF) (sometimes also referred to as Monadic Normal Form which is intimately related for reasons that will become clear) is used which has an even tighter relationship to SSA than CPS does.
If I remember correctly, administrative normal form gets its name from the fact that CPS-based compilation can lead to beta-redexes in the intermediate code that didn't correspond to anything in the source code. These were referred to as "administrative redexes". These could reduced at compile-time, but there was a good amount of research on performing a CPS transform that would output code without the administrative redexes in the first place. The goal then was to produce output in a normal form where all "administrative" redexes were reduced, and this was the origin of Administrative Normal Form. It didn't take long to realize there wasn't a whole lot of benefit to viewing this as a(n optimization of a) two-step process: CPS-transform, reduce administrative redexes. In particular, administrative normal form looks rather like monadic-style as practiced (by hand) most notably in Haskell. The CPS transform can be understood as a conversion to monadic-style where you just happen to be using the CPS monad (so there's really multiple ways to "convert" to monadic-style corresponding to different evaluation orders). In general, though, you could be using a quite different monad, and so conversion to monadic-style and thus administrative normal form isn't really related to CPS in particular.
Nevertheless, there were some benefits to CPS versus ANF. In particular, there were certain optimizations that you could do in CPS with just standard optimizations, such as beta reducing, that required (seemingly) ad-hoc rules for ANF. From the monadic perspective, these rules correspond to commuting conversions. The upshot is now there is a theory that can explain what rules should be added and why. A recent paper gives a (new and) pretty clear description of this (from a logical perspective) and its related work section serves as a brief but decent survey of and references into the literature on the topics I mention.
The problem with CPS is tied to one of its main benefits. CPS transforming allows you to implement control operators like call/cc, but this means every non-local function call in the CPS intermediate code has to be treated as potentially performing control effects. If your language includes control operators, then this is just as it should be (though even then most functions probably aren't doing any control shenanigans). If your language doesn't include control operators, then there are global invariants on the use of continuations that are not evident locally. This means there are optimizations that are unsound to perform on general CPS code that would be sound to perform on this particularly well-behaved use of CPS. One way this manifests is in the change in precision of data and control flow analyses. (CPS transforming helps in some ways, hurts in others, though the ways it helps are mostly due to duplication rather than the CPS aspect itself.)1 You could, of course, add rules and adjust analyses to compensate for this (i.e. to exploit the global invariants), but then you've partially defeated one of the major benefits of CPS-based compilation which is that many (seemingly) special-purpose, ad-hoc optimizations become special-cases of general-purpose optimization (particularly beta reduction).
Ultimately, unless your language has control operators, there is usually not much reason to use a CPS-based compilation scheme. Once you compensate for the issues I mentioned above, you've typically eliminated the benefits of CPS-based compilation and produced something equivalent to not using CPS. At that point, CPS is just making convoluted looking intermediate code for not much benefit. An argument for CPS-based compilation from 2007 addresses some of these issues and presents some other benefits using a different form of CPS conversion. The things that paper brings up are covered in part by the (2017) paper I mentioned before.
1 Doesn't the equivalence between SSA and CPS make this more or less impossible? No. One of the first things the paper introducing this equivalence states is that the equivalence does not work for arbitrary CPS code, but it does work for the output of a CPS transform (which they define) for a language without control operators. | {
"domain": "cs.stackexchange",
"id": 11968,
"tags": "compilers, program-optimization, continuations"
} |
An intuitive explanation of the basis-independency of EPR pair | Question: As usual, we write the EPR pair as
$$
\frac{1}{\sqrt2}(\left|00\right> + \left|11\right>).
$$
A property of the EPR pair is that this definition is basis-independent, which means
$$
\frac{1}{\sqrt2}(\left|00\right> + \left|11\right>) = \frac{1}{\sqrt2}(\left|uu\right> + \left|vv\right>)
$$
as long as $\left|u\right>$ and $\left|v\right>$ are orthogonal in $\mathbb{R}^2$. (As pointed out by @ElioFabri, if we set $\left|u\right>=\left|0\right>$ and $\left|v\right>=i\left|1\right>$ then the equailty no longer holds. Hence we cannot put them in $\mathbb{C}^2$.)
Question: Is there any way to explain this other than an elementary direct computation?
Answer: Here's a neat way to see this.
The main element is vectorization. Vectorization of a matrix $A=\sum A_{i,j}\vert i \rangle\langle j\vert$ is defined by $\vert\text{vec}({A})\rangle = \sum A_{i,j}\vert i \rangle\vert j\rangle$. Essentially, a bra turns into a ket. The cute thing about this is that you've now established a correspondence between matrices and bipartite pure states.
Next, consider what the identity matrix vectorizes to. You have $\sum_i \vert i \rangle\langle i\vert \rightarrow \sum_i \vert i \rangle\vert i\rangle $, which is an unnormalized Bell state. Indeed, if you chose to do it in two dimensions and the computational basis, you have your state $\vert 0\rangle\langle 0\vert + \vert 1\rangle\langle 1\vert \rightarrow \vert\Phi^+\rangle = \vert 00 \rangle + \vert 11\rangle$ upto normalization. You might be interested in the other Pauli matrices and what they do. I leave it to you to work it out but they simply give you the other Bell states.
But wait, you're free to write the identity as $\sum_i\vert i \rangle\langle i\vert$ in any orthonormal basis. So indeed you can have $i = \{0,1\}$ or $i = \{+,-\}$ or as you wanted to write it, $i = \{u,v\}$ for some $\vert u\rangle \perp \vert v\rangle$.
In some sense, the intuition is that because the identity matrix vectorizes to the $\vert\phi^+\rangle$ state, the freedom in representing the identity using any orthonormal basis carries over to the freedom in representing the vectorized state. | {
"domain": "physics.stackexchange",
"id": 56117,
"tags": "quantum-mechanics, hilbert-space"
} |
Why does it require more force to turn a servo if it is electronically connected to another servo? | Question: I have two servo motors that I rigged up to use as a telescope remote focuser. The idea is to turn one servo by hand and use the power generated to turn the other, which is geared to a telescope focuser knob. I noticed that when the two servos are electrically connected, it is noticeably harder to turn a servo compared to turning it by itself. I tried changing the polarity of the connection hoping it would help, but it is still harder to turn the servo when they are connected. Does anyone know why this is?
Answer: The other servo, being an electrical device, has some finite resistance.
When the servos are not electrically connected, the output of the manually turned servo is an open circuit, meaning that there is infinite resistance and no current flows. Because no current is flowing, the electrical output power of manually turned servo is
$P = IV$
where $I = 0$, so
$P = (0)(V) = 0$.
When you connect another servo, there is now a finite resistance connected to the manually turned servo's leads, so now current may flow. Now the current is given by
$V = IR$
$I = V/R$
so the electrical output power of the servo is
$P = IV$
$P = V^2/R$
There are two "types" of voltage in a motor when you operate it normally; the applied voltage and a back-voltage, commonly called "back EMF". This back EMF is a byproduct of motor motion.
The requirements for motor action are:
Current-carrying conductor
Applied magnetic field
Applied voltage differential on the conductor
The output of motor action is relative motion between the current-carrying conductor and the magnetic field.
The requirements for generator action are:
Current-carrying conductor
Applied magnetic field
Relative motion between the conductor and field
The output of generator action is a voltage differential in the conductor.
So you can see that if you meet motor action then you get generator action and both happen simultaneously.
When you back-drive a motor, you can get an output voltage at the motor terminals, if you have an applied magnetic field. In some instances, electric vehicles for instance, the motor is created such that the magnetic field is in the form of an electromagnet, called field windings. In this version, it is possible to vary the strength of the magnetic field by varying the current in the field windings; this varies the output current of the motor during back-driven operations and produces a variable strength braking effect.
In your case, with servo motors, the magnetic field typically comes in the form of permanent magnets in the motor housing. This means that the only way to vary output current (assuming a fixed output resistance) is to vary speed, as this varies the voltage you generate as dictated by the back-EMF constant;
$ V_{\mbox{back EMF}} = K_{\omega} \omega \phi$
where $K_{\omega}$ is the back-EMF constant, $\omega$ is the speed at which you are driving the motor, and $\phi$ is the strength of the magnetic field.
Looking again at the electrical output power of the servo:
$P = V^2/R$
Output power of the servo goes up with voltage squared. Since voltage is proportional to the driving speed of the motor, you can see that output power goes up based on speed squared; if you double the speed at which you drive the servo you quadruple the output power of the servo. This is why the servo gets "very hard" to drive.
There will always be some resistance when you try to drive a servo or motor, even with an open circuit, because they are real devices and thus have mass and inertia. You apply a torque to accelerate the motor:
$ \tau = I\alpha$
where $\tau$ is the torque you apply, $I$ is the effective motor inertia, and $\alpha$ is the rate at which you are accelerating the motor shaft. Output power varies with torque and speed:
$P_\mbox{mechanical} = \tau \omega$
so it requires more power to accelerate an already-moving object than it does to accelerate a stationary object.
Finally, the total power you apply to the servo is given by:
$P = P_{\mbox{mechanical}} + P_{\mbox{backEMF}}$
$P = \tau \omega + V^2/R$
$P = I\alpha \omega + (K_{\omega} \omega \phi)^2/R$
$P = (I \alpha)\omega + \frac{(K_\omega \phi)^2}{R}\omega^2 $
Where again, if the back-driven servo is not electrically connected to anything, then $R$ becomes infinitely large and the second term in the above equation becomes zero. | {
"domain": "robotics.stackexchange",
"id": 869,
"tags": "servomotor"
} |
What are the causes of lower UV radiation at lower elevations? | Question: After recently visiting the Dead Sea in Israel and not getting any skin burns, I was wondering about the reasons for that. Searching the literature, it seems that the UV radiation is indeed lower in the Dead Sea (ca. -400 m) compared to Beer Sheva (a nearby city at ca. +300 m): 1 2 3. Both UVA and UVB rays are lower, but UVB rays are attenuated the most.
These sources give mostly measurements, but hardly discuss the reasons for the lower radiation. I always thought that the ozone layer blocks most of the UV radiation, but here it seems that just a few hundred meters of atmosphere can greatly reduce the amount of incident UV.
What are the reasons for that? Is it simply because there are more air molecules that absorb the radiation?
Answer: You are almost totally correct when you asked:
What are the reasons for that? Is it simply because there are more air molecules that absorb the radiation?
The Ozone Layer blocks most of UVB, but does not affect the amount UVA entering the atmosphere (as seen in the illustration below):
(Image source)
But there is a little more to it than that. From NASA's Earth Observatory's webpage What Determines How Much Ultraviolet Radiation Reaches the Earth’s Surface?, elevation's role in attenuating UVB (and by similar processes, UVA):
high elevations UV-B radiation travels through less atmosphere before it reaches the ground, and so it has fewer chances of encountering radiation-absorbing aerosols or chemical substances (such as ozone and sulfur dioxide) than it does at lower elevations.
The aerosols absorb and scatter incident UV radiation. So nearer to the surface, there is a greater concentration that the light must pass through - and as the altitude decreases, the UV radiation path is therefore increased, so the further 'down' in altitude, the more the air mass and an increased presence of aerosols absorb and scatter solar UV radiation.
In respect to the aerosols in area you have specified (the Dead Sea), according to the first link in your question, The Analysis of the Ultraviolet Radiation in the Dead Sea Basin, Israel (Kudish et al. 1997), they state
the air above the Dead Sea is characterized by a
relatively high aerosol content due to the very high salt content of the Dead Sea
Their results indicate that
The relative attenuation in the ultraviolet range as a function of wavelength, i.e.
site-specific spectral selectivity, decreases with increasing wavelength.
thus, indicating that the attenuation is also wavelength dependent. | {
"domain": "earthscience.stackexchange",
"id": 264,
"tags": "atmosphere, ozone, topography"
} |
Is it possible to remove Staedtler ink from a paper? | Question: I am practicing engineering drafting and sometimes I am near on finishing my work but suddenly I make a mistake. Is it possible to remove the ink? If yes, how? Where can I buy such tools? I am using a Staedtler's Mars Matic 0.5mm.
Answer: To remove such ink it needs to scraped off, usually with a scalpel blade. This works well on thicker and more studier media such as film or vellum, but it will always be obvious where the erasure was made.
Depending on the amount of ink that needs to be removed and the robustness of the media, sometimes an ink erasure can work (such as a Staedtler blue ink eraser, Mars Plastic Combo), but again it will be obvious where the erasure was made. This can work on paper, but only with thicker robust paper.
If you need to present a drawing of professional standard, redraw the entire drawing. | {
"domain": "engineering.stackexchange",
"id": 1018,
"tags": "drafting"
} |
Significance when expectation of a commutator is zero | Question: It is clear to me what it means when the commutator of two operator $[A, B]$ is zero and what it implies. However, is there any significance when the expectation of the commutator $\langle[A, B]\rangle$ is zero?
I know $\langle[H, O]\rangle = 0$, where $H$ is the hamiltonian and $O$ the observable implies $\langle O \rangle$ is stationary but not sure about the general case for two operators.
Answer: I don't think we can conclude anything if $\langle[A,B]\rangle=0$, if not the condition on the uncertainties of previous answer: but even for that, the fact that on a particular state the product of the uncertainties has to be greater or equal to zero, doesn't imply that this particular state will realize the condition with the equal sign.
About the operators or the state, this condition can come from very etherogeneous situations, so unless further details are provided we can't draw many conclusions:
1) $[A,B]=0$: we know what it means, $A$ and $B$ are compatible observables (I assumed they're Hermitian, am I wrong?) and a common eigenbasis can be found;
on the other hand, $|\psi\rangle$ can be whatever;
2) $[A,B]\neq0$, $[A,B]|\psi\rangle=0$: this, for example, might happen in those peculiar cases where $A$ and $B$ don't commute but $|\psi\rangle$ is still a simultaneous eigenstate of both of them;
(example: the eigenstate of $\vec L^2$, $L_z$ for $l=0$, $|l,l_z\rangle=|0,0\rangle$, by the rotational symmetry of the situation, is a simultaneous eigenstate also of $L_x$ and $L_y$ with eigenvalue 0, although obviously $[L_z,L_{x/y}]\neq0$)
3) $[A,B]\neq0$, $[A,B]|\psi\rangle\neq0$: in this case the only possibility to have $\langle[A,B]\rangle=0$ is that the vector $[A,B]|\psi\rangle$ is orthogonal to the vector $|\psi\rangle$.
This in turn means that $|\psi\rangle$ is not eigenstate of $(AB-BA)$, so is not simultaneous eigenstate of $A$ and $B$. | {
"domain": "physics.stackexchange",
"id": 54889,
"tags": "quantum-mechanics, operators, commutator, observables"
} |
FizzBuzz in Python using a class | Question: I recently read the book clean code by Robert C. Martin and I'm trying to apply his style of writing methods to the FizzBuzz programming example.
So far I have two "public" methods called: start and parseNumber, that respectively start the FizzBuzz program or parse a single number according to the FizzBuzz principle.
class FizzBuzz(object):
def start(self, end_number):
return ",".join(self._parse_numbers(end_number))
def _parse_numbers(self, end_number):
number_list = []
for number in range(1, end_number+1):
number_list.append(self.parse_number(number))
return number_list
def parse_number(self, number):
if self._is_number_divisible_by_five_and_three(number):
return "FizzBuzz"
elif self._is_number_divisible_by_three(number):
return "Fizz"
elif self._is_number_divisible_by_five(number):
return "Buzz"
else:
return str(number)
def _is_number_divisible_by_five_and_three(self, number):
return number % 15 == 0
def _is_number_divisible_by_three(self, number):
return number % 3 == 0
def _is_number_divisible_by_five(self, number):
return number % 5 == 0
I'm happy with the last 3 methods that are clearly doing one thing. But the _parse_numbers and parse_number methods can be improved, I just don't know how to do that.
Answer: First of all, you don't need to make a class for this. There's no real reason for FizzBuzz to be an object when all you have is a collection of functions anyway. Likewise, you have a lot of functions that don't really need to be functions. All your test functions could just be plain if statements and that'd make them more readable to Python. I see you've discovered the _ naming convention in Python, where names beginning with that are to be considered private. However you don't need to use these that often. Nothing's ever going to be truly private in Python without a lot of work, so instead allow people to access functions if they want to. Only mark functions private if there's actual problems with them attempting to use the function outside of a specific process.
parse_number is good, though I'd replace the tests with plain tests instead of your functions.
def parse_number(number):
if number % 15 == 0:
return "FizzBuzz"
elif number % 3 == 0:
return "Fizz"
elif number % 5 == 0:
return "Buzz"
else:
return str(number)
You could also add a docstring and maybe a comment, to indicate what the function does and returns as well as noting how number % 15 == 0 is the same as (number % 5 == 0) and (number % 3 == 0).
def parse_number(number):
"""Returns a string Fizzbuzz representation of a number"""
# This is the same as (number % 5 == 0) and (number % 3 == 0)
if number % 15 == 0:
Start seems like a not very worthwhile function and not a great name if you're no longer making a class. But if you want to keep it a name like fizzbuzz_string would be better.
Now, your _parse_numbers isn't a great name because it's too similar to an existing function. There's also little reason to mark it as private. Instead this could be your main method, or at least call it fizzbuzz. You could also build it easier and faster with something called a list comprehension. A list comprehension is basically a for loop like expression that will be evaluated to create a list. Yours is very simple, you just need to run parse_number on each number in your range, so this is how you could write it:
def parse_number(number):
"""Returns a string Fizzbuzz representation of a number"""
# This is the same as (number % 5 == 0) and (number % 3 == 0)
if number % 15 == 0:
return "FizzBuzz"
elif number % 3 == 0:
return "Fizz"
elif number % 5 == 0:
return "Buzz"
else:
return str(number)
def fizzbuzz(end_number):
"""Return a list of Fizzbuzz parsed numbers up to end_number."""
return [parse_number(number) for number in range(1, end_number+1)]
def fizzbuzz_string(end_number):
return ",".join(fizzbuzz(end_number))
Now you can easily just call print fizzbuzz_string(number) and get the full list without needing an object or the other extraneous functions. | {
"domain": "codereview.stackexchange",
"id": 34331,
"tags": "python, fizzbuzz"
} |
getting the weights of intermediate layer in keras | Question: I have an image dataset 376 classes each class has 15 pictures corresponds to a person. I would like to get the feature vector that corresponds to each person.
What I have done is, after I compiled the model I then used this link
as a reference to get the weights of the last convolutional layer. However, when I do this, I get the error:
InvalidArgumentError: You must feed a value for placeholder tensor 'conv_layer' with dtype float and shape [?,19,19,360]
How can I resolve this issue?
Here is the code that I have done so far:
train_data = np.array(train_data, dtype=np.float32)
test_data = np.array(test_data, dtype=np.float32)
train_data = train_data / 180 # to make the array values between 0-1
test_data = test_data / 180
train_label = keras.utils.to_categorical(train_label, 376)
test_label = keras.utils.to_categorical(test_label, 376)
# CNN MODEL
model = Sequential()
model.add(Conv2D(180, (3, 3), padding='same', input_shape=(180, 180, 3),
activation="relu")) #180 is the number of filters
model.add(Conv2D(180, (3, 3), activation="relu"))
model.add(MaxPooling2D(pool_size=(3, 3)))
model.add(Dropout(0.25))
model.add(Conv2D(360, (3, 3), padding='same', activation="relu"))
model.add(Conv2D(360, (3, 3), activation="relu"))
conv_layer = model.add(MaxPooling2D(pool_size=(3, 3)))
model.add(Dropout(0.25))
flatten_layer = model.add(Flatten())
model.add(Dense(496, activation="relu"))
model.add(Dropout(0.5))
dense_layer = model.add(Dense(376, activation="softmax"))
#compiling the model
model.compile(
loss='categorical_crossentropy',
optimizer='adam',
metrics=['accuracy']
)
model.fit(
train_data,
train_label,
batch_size=32,
epochs=40,
verbose = 2 ,
validation_split=0.1,
shuffle=True)
# getting intermediate layer weights
get_layer_output = K.function([model.layers[0].input],
[model.layers[11].output])
layer_output = get_layer_output([conv_layer])[0]
Answer: The easiest way to create a truncated output from a network is create a sub-network of it and apply weights of your trained network. The following example is a modification of what you have shown up there, but it will guide you out
Network you want to train originally
model = Sequential()
model.add(Conv2D(10, (3, 3), padding='same', input_shape=(60, 60, 3),
activation="relu"))
model.add(Conv2D(10, (3, 3), activation="relu"))
model.add(MaxPooling2D(pool_size=(3, 3)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(5, activation="softmax"))
model.compile(
loss='categorical_crossentropy',
optimizer='adam',
metrics=['accuracy'])
model.fit(
train_data,
train_label)
Now create a subnetwork from which you want the outputs, like from above example
model_new = Sequential()
model_new.add(Conv2D(10, (3, 3), padding='same', input_shape=(60, 60, 3),
activation="relu"))
model_new.add(Conv2D(10, (3, 3), activation="relu"))
model_new.add(MaxPooling2D(pool_size=(3, 3)))
model_new.add(Dropout(0.25))
model_new.add(Flatten())
model_new.compile(
loss='categorical_crossentropy',
optimizer='adam',
metrics=['mse'])
# You need to apply fit on random array's created, just so as to initialise
# weights. Anyways you will replacing them with original ones from above.
model_new.fit(train_data, y=np.random.rand(40, 3610))
Now take weights from the first trained network and replace the weights of the second network like
model_new.set_weights(weights=model.get_weights())
You can check whether the weights are changed in the above step by actually adding these check statements like
print("Are arrays equal before fit - ",
any([np.array_equal(a1, a2) for a1, a2 in zip(model_new.get_weights(), model.get_weights()[:4])]))
model_new.set_weights(weights=model.get_weights())
print("Are arrays equal after applying weights - ",
all([np.array_equal(a1, a2) for a1, a2 in zip(model_new.get_weights(), model.get_weights()[:4])]))
This should yeild
Are arrays equal before fit - False
Are arrays equal after applying weights - True
Hope this helps. | {
"domain": "datascience.stackexchange",
"id": 4874,
"tags": "machine-learning, deep-learning, keras, cnn, image-recognition"
} |
Could there be planets that are not rotating around their axis yet are in orbit around a star? | Question: The title really says it all.
I know that there are planets like Earth that rotate around their axis and also around their star. I know that there are tidally locked planets which always have the same side turned towards their star. And, of course, there are rogue planets that don't orbit a star at all.
But what about a scenario where a planet is in a stable orbit around a star, yet does not revolve around its own axis? From the point of view of someone on the planet, all the stars stay almost unmoving in the sky, but the sun seems to slowly orbit the planet. Half a year there is light, and half a year there is darkness.
Is this realistic? Or would such a planet start rotating around its axis anyway due to whatever forces?
Answer: There is nothing specifically preventing it, but there is no mechanism that can create or maintain this situation.
Tidal locking occurs as a transfer of energy between rotation and orbit. This transfer of energy stops when the rotation rate of the planet equals its orbital time. So planets will tend to evolve towards this state of tidal locking.
Now the formation of planets in protoplanetary discs will naturally give them some angular momentum. They will tend to spin the same way. It is possible events (such as collisions) will occur that will change the rotation, even reverse it. It is, I suppose, possible that events will conspire to give a planet very close to zero rotation. Unlike tidal locking, having no rotation is not self-sustaining, so tidal effects will tend to cause a planet having no rotation to evolve towards tidal lock.
I suppose further that a planet that happened to have a slow backwards rotation could, as a result of tidal locking, have it's rotation slowed and eventually reversed. At some point it would not have been rotating at all. And since these changes happen slowly, there might be a period during which the planet was not rotating for much longer than the lifespan of any creatures on it.
There are so many ifs here, which is why although there is nothing to prevent this happening, it would be almost infinitely rare. | {
"domain": "astronomy.stackexchange",
"id": 6014,
"tags": "planet"
} |
alternative gyro for Turtlebot | Question:
As the Sparkfun ADXRS613 breakout gyro for the turtlebot is not available from sparkfun anymore, I was wondering if the Active-Robots Gyro Breakout Board MLX90609-E2 is an interchangeable alternative?
It seems to have the same sensitivities, rate and required voltages.. Only thing different I see is that the standard capacitor sets it to ~36Hz instead of ~361Hz for the adxrs613. Switching out the capacitor should fix this, is it useful though?
Originally posted by Marco on ROS Answers with karma: 77 on 2011-09-14
Post score: 0
Answer:
This is a duplicate question of this one:
http://answers.ros.org/question/2122/gyro-substitute-for-turtlebot
And more info:
http://answers.ros.org/question/1400/using-a-different-gyro-on-a-turtlebot
Originally posted by AHornung with karma: 5904 on 2011-09-14
This answer was ACCEPTED on the original site
Post score: 2 | {
"domain": "robotics.stackexchange",
"id": 6698,
"tags": "ros, hardware, gyro, turtlebot"
} |
How do gluons bind the quarks together within the hadrons and mesons? | Question: I was trying to know about the strong nuclear force within the nucleus and the books and websites told me that it is the gluons which carry the force, and now I am curious how the gluons carry this force
Answer: As in your profile you say you are a ninth class student in India, it means that your physics background is still at understanding the classical physics level.
The strong nuclear force and the strong force of particle physics belong to the quantum mechanical studies, which I doubt it is taught in your year.
In classical physics force can be defined as the change in momentum in time, $F=dp/dt$. At the level of nuclei and particles, this is the only reasonable definition of a force, because any interaction between quantum mechanical entities happens by the exchange of an elementary particle which transfers energy and momentum and quantum numbers ( which you will eventually learn about) between the quantum mechanical entities, be they nuclei or particles.
Think of two boats in a quiet sea. If one boat throws a ball to the other, they interact with the $dp/dt$ the ball carries. That is how forces are to be defined in the micro level of nuclear and particle physics. In this answer here , there is an illustration of the boats with a boomerang thrown, to show an analogy with attractive forces. ( the feynman diagrams are for later in your education, if you still like physics and pursue it)
The elementary particles carrying the force to first order in most interactions are:
the photon, for electromagnetic interactions
the Z and W for weak interactions
the gluon for strong interactions
For nuclei, which are bound states of protons and neutrons, the strong nuclear force, is a spill over force from the strong force which has the gluon as a force carrier . Interaction of nuclei can be modeled by having the composite hadron particle pion as a force carrier.
Protons (and neutrons and other hadrons) are an entity with three valence quarks held together by an innumerable number of gluons as force carriers, because gluons are very attractive to quarks and to each other. ( the word comes from glue)
Here is an illustration of a proton:
The three valence quarks are lost in the plethora of gluons and quark antiquark pairs created by the mechanism of strong interactions.
The strong force is so strong that new quantum mechanical models have been developed to explain the hadrons ( bound states of quarks by gluons), called QCD on the lattice. | {
"domain": "physics.stackexchange",
"id": 63853,
"tags": "particle-physics, quantum-chromodynamics, quarks, strong-force, gluons"
} |
How easy is it to switch the area of research in CS (going from M.Tech to PhD)? | Question: I'm faced with a rather tough dilemma :-
I had completed M.Tech in CS 2 years back, completing my dissertation in the field of VLSI Testing. While I liked my work, I don't wish to go back to pursue my PhD in that - I've been strongly wanting to pursue a theoretical course (in approximation/online algorithms) as means for obtaining my doctoral degree.
However, since I've had no research experience in TCS(Theoretical Computer Science), I'm afraid that would hurt my chances of getting admission to a reasonably good school in the US - whereas, the research experience in VLSI (as well as the LORs from my adviser/committee members, who are well known in the field of VLSI) would have helped me get into a good program (but my enthusiasm in that field has already petered out).
That's why, I wanted to hear from people who have successfully migrated from their initial research field (in UG/MS level) and have been able to embark on a completely different field for their PhD - how did you explain the reason for your shift in the SOP, whether that affected their chances in getting into a top school etc. Also, for any academics browsing the question, what would be your take on it - do you always prefer students who have a background matching your interests only ?
Answer: In some departments, PhD students are only admitted if a faculty member is willing and ready to advise/fund them. You may have a harder time being admitted to these departments to be a theory PhD student if you have not already done some theory research; there's not much incentive for individual faculty members to take risks on students who are less experienced in their fields, especially when they have to spend hard-earned grant money to do it.
Other departments expect their PhD students to float for a year or so, taking a broad swath of classes and maybe working as a teaching assistant, before settling on a particular research area and advisor. These departments may be more willing to admit smart students who are switching areas, or just don't know what area they want to work in, because the risk is amortized across the entire department.
Even for the latter departments, though, you want to cast yourself in the best light. Your statement of purpose should describe your past research experiences in detail (demonstrating the intellectual maturity, independence, stubbornness, etc. required to do research anywhere), before explaining why your current research interests are leaning more toward theory. In other words, what Dana said.
A few points of personal anecdotal evidence:
Over the last ten years, my department has moved away from the second admission model toward the first. Our students get into research faster, but we admit fewer generally smart students who don't already have focused research interests/experience.
David Eppstein may correct me, but the second admission model is how I got into theoretical computer science research. I applied to UC Irvine to study software engineering. (I had been a professional software engineer for a few years, so given my crappy undergrad GPA, that was the only thing I could credibly claim.) By the end of the first year, during which I worked as a TA and did not have a formal advisor, I realized that theory was a much better fit.
Amir Nayyeri, one of my most successful PhD students, started his PhD program at UIUC working on sensor networks, because that's what he did as an undergraduate. But once he was in the door, he decided that he'd rather do theory, took and aced some graduate theory classes, and started doing unpaid theory research while also working as an RA for his sensor-network advisor. So switching fields is possible, even in departments where students are pigeonholed from day one. | {
"domain": "cstheory.stackexchange",
"id": 1108,
"tags": "soft-question, advice-request, career"
} |
The curious case of the time derivative of the expectation value of the position | Question: Having defined the expectation value of position as follows
$$
\langle x \rangle = \int x {\lvert\Psi(x,t)\rvert}^2dx
$$
The time derivative of the expectation value is derived in my literature in the following way:
$$
\frac{d\langle x \rangle }{dt} = \int x\partial_t{\lvert\Psi\rvert}^2dx = \ldots
$$
From here it is straightforward algebra and calculus to the answer.
$$
\frac{d\langle x \rangle }{dt} = \frac{-i\hbar}{2m}\int\overline{\Psi}\partial_x\Psi dx
$$
What strikes me as odd is the fact that the author didn't write
$$
\frac{d\langle x \rangle }{dt} = \int \partial_t\left(x\lvert\Psi\rvert^2dx\right)
$$
Somehow, the position $x$ is treated as a constant. There is no explanation to why this is the case. From above, $x$ is somehow unchanging in time and the only thing that alters the expectation value is the wave function. This might be the case but then what is the interpretation of $x$?
Why doesn't $x$ vary in time?
Answer: Because in QM, the wave function contains all the relevant information, and $x$ is the coordinate parameter.
You are expecting $x$ to be dependent on time because you are used to seeing it as the particle's coordinate, i.e. a function of time that says where the particle is for each time parameter value.
But here, $\psi$ has this information, and $x$ is just the parameter value for which you want to evaluate the odds of finding the particle. So $x$ is not the position of the particle in the sense that is a time function giving the particle's position; its just another parameter on which $\psi$ depends.
This is similar to wave mechanics, in the sense that you use $x$ as a variable on which the function of wave form depends, but is not a particular coordinate of the wave, is just a coordinate of the space where the wave exists. | {
"domain": "physics.stackexchange",
"id": 24340,
"tags": "quantum-mechanics, time-evolution"
} |
A Graph's Density and Sparsity | Question:
A graph is dense when |E| (edges) is closest to $|V|^2$.
A graph is sparse when |E| is closer to $|V|$.
What does it mean to take the magnitude of the vertices? Secondly, I am having a hard time conceptualizing why the above two rules are true.
Also can someone elaborate on why if a graph is sparse, it should be represented with an adj list and why if it is dense, it is best to use an adjacency matrix instead?
Answer: The notation $|V|$ here means the number of vertices in your graph. Likewise, $|E|$ is used to denote the number of edges. We typically say that a graph is sparse whenever $|E| \in O(|V|)$ - i.e there are few enough edges. Similarly, we say that a graph is dense whenever $|E| \in \Theta(|V|^2)$ - i.e there are many edges in your graph. These are not really rules, but rather just the terminology one often uses in textbooks.
An adjacency matrix requires $\Theta(|V|^2)$ space to store, while an adjacency list requires $\Theta(|V| + |E|)$ space to store. So when the graph is sparse, using an adjacency matrix is wasteful in terms of space usage, even though answering queries may be faster. On the other hand, is the graph is dense, then both representations require a quadratic amount of space to store, and so you are better off using the adjacency matrix for $O(1)$ edge queries. There are other trade-offs that one can consider as well depending on the queries you anticipate using often, such as vertex insertion/deletion, neighborhood queries, among others... but this is the general rule of thumb.
It may also make a difference when implementing certain algorithms, like Dijkstra's. Using an adjacency matrix, the algorithm takes $O(|V|^2)$ time, but using an adjacency list, it can be implemented in $O(|V| + |E| \log |E|)$ time. This type of trade-off is common when implementing different graph algorithms. | {
"domain": "cs.stackexchange",
"id": 6319,
"tags": "graphs"
} |
What is the magnitude of acceleration given $v_i$, $v_f$, and $x$? | Question: I'm really struggling with this question that is part of my physics assignment. Any help would be appreciated.
This is the question:
A speed skater moving to the left across frictionless ice at 8.4 m/s hits a 4.5-m-wide patch of rough ice. She slows steadily, then continues on at 5.7 m/s.
What is the magnitude of her acceleration on the rough ice?
Attempted answer:
I used the formula a=(Vf^2-Vi^2)/2x
a=[(5.7^2) - (8.4^2)]/2(4.5)
a=(32.49-70.56)/9
a=-38.07/9
a=-4.23 m/s^2
Masteringphysics tells me the answer is wrong and to "check my signs"
Answer: If you included the negative sign in your answer, then you aren't (quite) answering the question that was asked. Magnitudes are positive by definition; the negative sign on an acceleration (or velocity) is simply there to indicate direction. | {
"domain": "physics.stackexchange",
"id": 49001,
"tags": "homework-and-exercises, kinematics, acceleration, velocity"
} |
Partition Function - Simpler computation by changing ensemble | Question: I have a question regarding a Derivation presented on the web page http://www.pas.rochester.edu/~stte/phy418S05/hw3.html.
The Problem is to calculate the Partition function for a (discrete) elastic string. The transversal displacement at the nodes $i$ is denoted $y_i$, the Hamiltonian reads
$$H[y_i] = \frac{1}{2} \sum_{i=1}^{L} (y_i - y_{i-1})^2 $$
The string is fixed at then ends, $y_0= 0$ and $y_L= Y$, so the average slope equals $Y/L$.
The partition function reads
$$ Z(Y) = (\prod_{i=1}^L \int_{-\infty}^{\infty} \mathrm{d}y_i) \exp{\frac{-H[y_i]}{kT}} $$
and this could be solved exactly.
But the notes show an easier approach.
A new Ensemble is considered, whereby the average slope can fluctuate too
$$ Z'(\eta) = \int _{-\infty}^{\infty}
\mathrm{d}Y Z(Y) \exp{\frac{-\eta Y}{kT}} $$
One is then expected to
1) compute the free energy
$$ F' (\eta) = -kT ln Z' $$
By then showing that
2) the average slope equals
$$ <Y> = \frac{\partial{F'(\eta)}}{\partial{ \eta}} $$
one should then be in the position to
3) compute the Legendre transform
$$F(Y) = F'(\eta) - \eta Y $$
Sounds all very good, but I am unable to compute the free energy, step 1).
The author claims this approach to compute $F$ is easier than the direct Partition function Z calculation: yet it seems I still have to integrate over the $Z(Y)$ in the second partition function, must be missing a point here. Maybe some clever integration by parts, or property of the Laplace Transform?
Ok, I could use the fact that in the first ensemble (strings' ends fixed)
$$ F(Y) = -kT ln Z(Y),$$ but this does not seem that revealing.
Answer: If the string is constrained at $y_L=Y$ then the partition function is
$$Z(Y) = \prod_{i=1}^{L-1} \int_{-\infty}^{\infty}\mathrm{d}y_i \, \exp \left(- \frac{1}{k_{\mathrm{B}}T}\frac{1}{2} \sum_{i=1}^L (y_i - y_{i-1})^2\right) $$
This is a multidimensional Gaussian integral that could be calculated directly, but it is not trivial (one would have to compute the eigenvalues of the coupling matrix). However, if one defines the increments $w_i = y_i - y_{i-1}$ then the integral nearly factorizes:
$$Z(Y) = \prod_{i=1}^{L} \int_{-\infty}^{\infty}\mathrm{d}w_i \, \exp \left(- \frac{1}{k_{\mathrm{B}}T}\frac{1}{2} \sum_{i=1}^L w_i^2\right) \delta \left( \sum_{j=1}^L w_j -Y\right) $$
Here the Dirac delta function is necessary to ensure that all the individual increments add up to $Y$. Here you see the effect of the constraint: it couples all the individual increments together, which makes the evaluation of the partition function difficult (but there is a hint in the problem you linked to).
If the string is not constrained at $y_L$ then the partition function is
$$Z'(\eta) = \prod_{i=1}^{L} \int_{-\infty}^{\infty}\mathrm{d}w_i \, \exp \left(- \frac{1}{k_{\mathrm{B}}T}\frac{1}{2} \sum_{i=1}^L w_i^2\right)
\exp{\left(-\frac{\eta}{k_{\mathrm{B}}T} \sum_{j=1}^L w_j \right)} $$
In this case the final term is an exponential of the sum of the $w_i$, which factorizes and you can do the integration over each $w_i$ separately. This is easier than computing $Z(Y)$ directly. | {
"domain": "physics.stackexchange",
"id": 40079,
"tags": "homework-and-exercises, statistical-mechanics"
} |
Container for Sets of Integers | Question: I implemented an unordered_set like container for storing small sets of unsigned integers. It uses a trivial hash table for lookups and an unordered array for quickly iterating over small sets.
I'm looking for suggestions on best practices and correctness.
#pragma once
#include <array>
#include <random>
#include <bitset>
// T - Type of integer.
// N - Number of integers in the set from 0 to N-1
template<typename T,T N> class integer_set
{
private:
static constexpr T NOT_IN_SET = ~static_cast<T>(0);
static const T MIN_SIZE_TO_SEARCH_INDEX;
public:
class iterator
{
public:
iterator(const iterator& it) = default;
iterator& operator=(const iterator& it) = default;
iterator();
iterator(const T* element);
bool operator==(const iterator& it) const;
bool operator!=(const iterator& it) const;
bool operator<(const iterator& it) const;
bool operator>(const iterator& it) const;
bool operator<=(const iterator& it) const;
bool operator>=(const iterator& it) const;
T operator*() const;
T operator[](T i) const;
iterator& operator++();
iterator operator++(int);
iterator& operator--();
iterator operator--(int);
iterator operator+(T i) const;
iterator operator-(T i) const;
iterator& operator+=(T i);
iterator& operator-=(T i);
private:
const T* m_element;
};
public:
// The following are undefined if the set is empty:
// front()
// back()
// operator[]()
// min()
// max()
// random()
integer_set();
integer_set(const integer_set& set);
integer_set& operator=(const integer_set& set);
bool operator==(const integer_set& set) const;
bool operator!=(const integer_set& set) const;
bool operator<=(const integer_set& set) const;
bool operator>=(const integer_set& set) const;
bool operator<(const integer_set& set) const;
bool operator>(const integer_set& set) const;
T front() const;
T back() const;
iterator begin() const;
iterator end() const;
iterator find(T v) const;
T operator[](T i) const;
T min() const;
T max() const;
template<class URNG> T random(URNG& gen) const;
T size() const;
bool empty() const;
bool contains(T v) const;
void clear();
void insert(T v);
void insert(const integer_set& set);
void erase(T v);
void erase(const integer_set& set);
public:
static integer_set union_(const integer_set& set1,const integer_set& set2);
static integer_set intersection(const integer_set& set1,const integer_set& set2);
static bool union_empty(const integer_set& set1,const integer_set& set2);
static bool intersection_empty(const integer_set& set1,const integer_set& set2);
private:
// Find the smallest size where searching the index has a probability >= 0.5 of requiring fewer operations than searching the list.
static T min_size_to_search_index();
// Probability that we will find at least one element in the set after picking size elements at random.
static double get_probability(T size);
private:
// m_index[element] is the index of that element in m_list or NOT_IN_SET. For checking if element is in set.
std::array<T,N> m_index;
// Unordered list of elements. For iterating over set.
std::array<T,N> m_list;
// Number of elements in set.
T m_size;
};
namespace std
{
template<typename T,T N> struct hash<integer_set<T,N>>
{
typedef integer_set<T,N> argument_type;
typedef std::size_t result_type;
result_type operator()(const argument_type& set) const
{
std::bitset<N> bits;
for(T v : set)
bits.set(v);
return std::hash<std::bitset<N>>()(bits);
}
};
}
template<typename T,T N> constexpr T integer_set<T,N>::NOT_IN_SET;
template<typename T,T N> const T integer_set<T,N>::MIN_SIZE_TO_SEARCH_INDEX = {min_size_to_search_index()};
////////////////////////////////////////////////
// integer_set
template<typename T,T N> integer_set<T,N>::integer_set()
:m_size{0}
{
m_index.fill(NOT_IN_SET);
static_assert(std::numeric_limits<T>::is_integer,"T must be an integer.");
static_assert(std::is_unsigned<T>::value,"T must be unsigned.");
static_assert(N<NOT_IN_SET,"N is too large.");
}
template<typename T,T N> integer_set<T,N>::integer_set(const integer_set& set)
:m_index(set.m_index),m_size{set.m_size}
{
for(T i=0; i<m_size; ++i)
m_list[i] = set.m_list[i];
}
template<typename T,T N> integer_set<T,N>& integer_set<T,N>::operator=(const integer_set& set)
{
m_size = set.m_size;
m_index = set.m_index;
for(T i=0; i<m_size; ++i)
m_list[i] = set.m_list[i];
return *this;
}
template<typename T,T N> bool integer_set<T,N>::operator==(const integer_set& set) const
{
if(m_size != set.m_size)
return false;
for(T v : set)
{
if(!contains(v))
return false;
}
return true;
}
template<typename T,T N> bool integer_set<T,N>::operator!=(const integer_set& set) const
{
return !operator==(set);
}
template<typename T,T N> bool integer_set<T,N>::operator<=(const integer_set& set) const
{
return m_index <= set.m_index;
}
template<typename T,T N> bool integer_set<T,N>::operator>=(const integer_set& set) const
{
return m_index >= set.m_index;
}
template<typename T,T N> bool integer_set<T,N>::operator<(const integer_set& set) const
{
return m_index < set.m_index;
}
template<typename T,T N> bool integer_set<T,N>::operator>(const integer_set& set) const
{
return m_index > set.m_index;
}
template<typename T,T N> T integer_set<T,N>::front() const
{
return m_list[0];
}
template<typename T,T N> T integer_set<T,N>::back() const
{
return m_list[m_size-1];
}
template<typename T,T N> typename integer_set<T,N>::iterator integer_set<T,N>::begin() const
{
return iterator(m_list.data());
}
template<typename T,T N> typename integer_set<T,N>::iterator integer_set<T,N>::end() const
{
return iterator(m_list.data()+m_size);
}
template<typename T,T N> typename integer_set<T,N>::iterator integer_set<T,N>::find(T v) const
{
if(m_index[v] == NOT_IN_SET)
return end();
else
return iterator(m_list.data()+m_index[v]);
}
template<typename T,T N> T integer_set<T,N>::operator[](T i) const
{
return m_list[i];
}
template<typename T,T N> T integer_set<T,N>::min() const
{
if(m_size >= MIN_SIZE_TO_SEARCH_INDEX)
{
for(T i=0; i<N; ++i)
{
if(m_index[i] != NOT_IN_SET)
return i;
}
}
else
{
T min = m_list[0];
for(T i=1; i<m_size; ++i)
{
if(m_list[i] < min)
min = m_list[i];
}
return min;
}
return NOT_IN_SET;
}
template<typename T,T N> T integer_set<T,N>::max() const
{
if(m_size >= MIN_SIZE_TO_SEARCH_INDEX)
{
for(T i=N; i>0; --i)
{
if(m_index[i-1] != NOT_IN_SET)
return i-1;
}
}
else
{
T max = m_list[0];
for(T i=1; i<m_size; ++i)
{
if(m_list[i] > max)
max = m_list[i];
}
return max;
}
return NOT_IN_SET;
}
template<typename T,T N> template<class URNG> T integer_set<T,N>::random(URNG& gen) const
{
return m_list[std::uniform_int_distribution<T>(0,m_size-1)(gen)];
}
template<typename T,T N> T integer_set<T,N>::size() const
{
return m_size;
}
template<typename T,T N> bool integer_set<T,N>::empty() const
{
return m_size == 0;
}
template<typename T,T N> bool integer_set<T,N>::contains(T v) const
{
return m_index[v] != NOT_IN_SET;
}
template<typename T,T N> void integer_set<T,N>::clear()
{
for(T v : *this)
m_index[v] = NOT_IN_SET;
m_size = 0;
}
template<typename T,T N> void integer_set<T,N>::insert(T v)
{
if(contains(v))
return;
m_index[v] = m_size;
m_list[m_size] = v;
++m_size;
}
template<typename T,T N> void integer_set<T,N>::insert(const integer_set& set)
{
for(T v : set)
insert(v);
}
template<typename T,T N> void integer_set<T,N>::erase(T v)
{
if(!contains(v))
return;
--m_size;
// If this element is not the last in the list
// move the last element in the list to the index of v.
if(m_index[v] != m_size)
{
m_list[m_index[v]] = m_list[m_size];
m_index[m_list[m_size]] = m_index[v];
}
m_index[v] = NOT_IN_SET;
}
template<typename T,T N> void integer_set<T,N>::erase(const integer_set& set)
{
for(T v : set)
erase(v);
}
template<typename T,T N> integer_set<T,N> integer_set<T,N>::union_(const integer_set& set1,const integer_set& set2)
{
if(set1.m_size <= set2.m_size)
{
integer_set out(set2);
out.insert(set1);
return out;
}
else
{
integer_set out(set1);
out.insert(set2);
return out;
}
}
template<typename T,T N> integer_set<T,N> integer_set<T,N>::intersection(const integer_set& set1,const integer_set& set2)
{
integer_set out;
if(set1.m_size <= set2.m_size)
{
for(T v : set1)
{
if(set2.contains(v))
out.insert(v);
}
}
else
{
for(T v : set2)
{
if(set1.contains(v))
out.insert(v);
}
}
return out;
}
template<typename T,T N> bool integer_set<T,N>::union_empty(const integer_set& set1,const integer_set& set2)
{
return set1.m_size == 0 && set2.m_size == 0;
}
template<typename T,T N> bool integer_set<T,N>::intersection_empty(const integer_set& set1,const integer_set& set2)
{
if(set1.m_size <= set2.m_size)
{
for(T v : set1)
{
if(set2.contains(v))
return false;
}
}
else
{
for(T v : set2)
{
if(set1.contains(v))
return false;
}
}
return true;
}
template<typename T,T N> T integer_set<T,N>::min_size_to_search_index()
{
// Bisection
T min_size = 1;
T max_size = N;
T mid_size = (min_size+max_size)/2;
do
{
if(get_probability(mid_size) >= 0.5)
max_size = mid_size;
else
min_size = mid_size;
mid_size = (min_size+max_size)/2;
}
while(mid_size != min_size);
return max_size;
}
template<typename T,T N> double integer_set<T,N>::get_probability(T size)
{
// Simplification of the hypergeometric distribution.
// 1-hygepdf(0,N,size,size) =
// (N-size)!*(N-size)!
// 1 - ___________________
// (N-size-size)!*N!
double num = static_cast<double>(N-size);
double den = static_cast<double>(N);
double p = num/den;
for(T i=1; i<size; ++i)
{
--num;
--den;
p *= num/den;
}
return 1.0-p;
}
////////////////////////////////////////////////
// integer_set::iterator
template<typename T,T N> integer_set<T,N>::iterator::iterator()
:m_element{nullptr}
{}
template<typename T,T N> integer_set<T,N>::iterator::iterator(const T* element)
:m_element{element}
{}
template<typename T,T N> bool integer_set<T,N>::iterator::operator==(const iterator& it) const
{
return m_element == it.m_element;
}
template<typename T,T N> bool integer_set<T,N>::iterator::operator!=(const iterator& it) const
{
return m_element != it.m_element;
}
template<typename T,T N> bool integer_set<T,N>::iterator::operator<(const iterator& it) const
{
return m_element < it.m_element;
}
template<typename T,T N> bool integer_set<T,N>::iterator::operator>(const iterator& it) const
{
return m_element > it.m_element;
}
template<typename T,T N> bool integer_set<T,N>::iterator::operator<=(const iterator& it) const
{
return m_element <= it.m_element;
}
template<typename T,T N> bool integer_set<T,N>::iterator::operator>=(const iterator& it) const
{
return m_element >= it.m_element;
}
template<typename T,T N> T integer_set<T,N>::iterator::operator*() const
{
return *m_element;
}
template<typename T,T N> T integer_set<T,N>::iterator::operator[](T i) const
{
return m_element[i];
}
template<typename T,T N> typename integer_set<T,N>::iterator& integer_set<T,N>::iterator::operator++()
{
++m_element;
return *this;
}
template<typename T,T N> typename integer_set<T,N>::iterator integer_set<T,N>::iterator::operator++(int)
{
iterator temp(*this);
operator++();
return temp;
}
template<typename T,T N> typename integer_set<T,N>::iterator& integer_set<T,N>::iterator::operator--()
{
--m_element;
return *this;
}
template<typename T,T N> typename integer_set<T,N>::iterator integer_set<T,N>::iterator::operator--(int)
{
iterator temp(*this);
operator--();
return temp;
}
template<typename T,T N> typename integer_set<T,N>::iterator integer_set<T,N>::iterator::operator+(T i) const
{
return iterator(m_element+i);
}
template<typename T,T N> typename integer_set<T,N>::iterator integer_set<T,N>::iterator::operator-(T i) const
{
return iterator(m_element-i);
}
template<typename T,T N> typename integer_set<T,N>::iterator& integer_set<T,N>::iterator::operator+=(T i)
{
m_element += i;
return *this;
}
template<typename T,T N> typename integer_set<T,N>::iterator& integer_set<T,N>::iterator::operator-=(T i)
{
m_element -= i;
return *this;
}
Edit:
I implemented this container to speed up a program that uses many set operations. This container gives me a speed up of two orders of magnitude compared to std::unordered_set.
These functions are nearly identical to std::set and std::unordered_set. Like std::unordered_set, iterators return the elements in no particular order.
integer_set();
integer_set(const integer_set& set);
integer_set& operator=(const integer_set& set);
bool operator==(const integer_set& set) const;
bool operator!=(const integer_set& set) const;
iterator begin() const;
iterator end() const;
T front() const;
T back() const;
iterator find(T v) const;
void clear();
bool empty() const;
T size() const;
void insert(T v);
void erase(T v);
These are convenience functions not provided by std::set or std::unordered_set:
// Same as insert(set.begin(),set.end())
void insert(const integer_set& set);
// Same as erase(set.begin,set.end())
void erase(const integer_set& set);
// Test if integer v is in set. Same as find(v) != end()
bool contains(T v) const;
// Smallest/largest integer in set.
T min() const;
T max() const;
// Random integer in set given a RNG e.g. std::mersenne_twister_engine
template<class URNG> T random(URNG& gen) const;
// Element of set. Same as *(begin()+i).
T operator[](T i) const;
// Lexicographical comparison
bool operator<=(const integer_set& set) const;
bool operator>=(const integer_set& set) const;
bool operator<(const integer_set& set) const;
bool operator>(const integer_set& set) const;
// Self Explanatory
integer_set union_(const integer_set& set1,const integer_set& set2);
integer_set intersection(const integer_set& set1,const integer_set& set2);
bool union_empty(const integer_set& set1,const integer_set& set2);
bool intersection_empty(const integer_set& set1,const integer_set& set2);
Here is an example:
#include "integer_set.h"
#include <cassert>
int main()
{
typedef integer_set<uint16_t,256> set256;
set256 set1;
set1.insert(144);
set1.insert(255);
set1.insert(0);
assert(set1.find(0) != set1.end());
assert(set1.contains(144));
assert(set1.contains(255));
set1.clear();
assert(set1.begin() == set1.end());
for(uint16_t i=30;i<100;i+=7)
set1.insert(i);
set1.insert(2);
set1.insert(252);
for(uint16_t i=121;i<240;i+=3)
set1.insert(i);
assert(set1.min() == 2);
assert(set1.max() == 252);
set256 set2;
set2.insert(30);
assert( set256::intersection(set1,set2).contains(30) );
set2 = set1;
for(uint16_t member : set2)
set1.erase(member);
assert(set1.empty());
return 0;
}
Answer: The answer given by @galop1n is a good one, but since you asked for review, here is what could actually be improved in your code:
Your class iterator is nothing but a wrapper which does exactly the same thing as std::array<T, N>::iterator. Therefore, you can simply write
using iterator = typename std::array<T, N>::iterator;
...and delete your whole iterator implementation. The only things that are really important are the values passed to it by begin and end.
It's not really important, but I would have kept my includes in alphbetical order so that I know exactly whether I have to look for an included header higher or lower in the list:
#include <array>
#include <bitset>
#include <random>
You obviously have a naming problem with union_. Since you are creating a set class, I would use operator& for intersection and operator| for union. While it is not recommended to overload operators when the meaning is not obvious, these operators are already commonly used for set operations (e.g. set and frozenset in Python's standard library). To improve consistency and usability, you can also implement operator&= and operator|=; users will expect them to be available if you already provide operator& and operator|.
We already tackled the problem for union_ and intersection by making them operators, but I don't really like the fact that union_empty and intersection_empty are static functions. The need not be static since the only private member they access is m_size, and you can get this member by calling the method size. I would have made them free functions instead.
I don't believe that checking for std::numeric_limits<T>::is_integer in the static assertions is useful since is_unsigned is only true for unsigned integer types. It is probably redundant.
In the method random, you pass the random number generator by reference. The idiomatic way to pass a random number generator (e.g. std::shuffle or std::sample) is to pass it by universal reference and to std::forward it to the following function:
template<typename T,T N>
template<class URNG>
T integer_set<T,N>::random(URNG&& gen) const
{
return m_list[std::uniform_int_distribution<T>(0,m_size-1)(std::forward<URNG>(gen))];
}
This line:
template<typename T,T N> constexpr T integer_set<T,N>::NOT_IN_SET;
Since you already initialized NOT_IN_SET directly in the class declaration, this line is useless. You should remove it. | {
"domain": "codereview.stackexchange",
"id": 6851,
"tags": "c++, c++11, set"
} |
How to include files in URDF | Question:
Does URDF support building a larger model from smaller models defined in other URDF files?
I'm trying to model a simple quadruped, and I initially modelled the entire thing in a few hours with modular SDF files, following a Gazebo tutorial, but then I learned ROS doesn't support SDF at all. So now I'm trying to remodel it in URDF and I'm finding it incredibly difficult. It's been days, and I've barely accomplished anything, which only took me a few hours in SDF despite having zero experience with SDF.
I've tried following the URDF tutorial, but it doesn't explicitly mention any include ability, but from the examples, it looks like Xacro might technically accomplish this. Although I'd like to avoid using complicated macro tools to do something so simple. Is using Xacro the only way?
Originally posted by Cerin on ROS Answers with karma: 940 on 2015-04-26
Post score: 0
Answer:
http://wiki.ros.org/xacro#Including_other_xacro_files
Originally posted by DLu with karma: 38 on 2015-04-26
This answer was ACCEPTED on the original site
Post score: 1
Original comments
Comment by Cerin on 2015-04-26:
That's not really what I'm looking for. Xarco:include seems to essentially copy and paste one file into another. If I had a complicated leg model in one file and I wanted to include it four times in different poses and angles, it wouldn't let me do that. It would only make four identical copies.
Comment by DLu on 2015-04-26:
Then you should transform the entire thing into a macro, save it in its own individual file, then instantiate several different instances of the macro. | {
"domain": "robotics.stackexchange",
"id": 21545,
"tags": "urdf, xacro"
} |
How to calculate the phase and group velocity of a superposition of sine waves with different speed and wavelength? | Question: This might seem like a trivial question but it is not for me. So, I was reading on group and phase velocities from A.P. French where he calculates the phase and group velocities for a superposition of sine waves of different speed and wavelength. I will write down a brief analysis:
$$y(x,t)=A\sin(k_1x-\omega_1t) + A\sin(k_2x-\omega_2t) $$ which simplifies to
$$y(x,t)=2A\sin\left(\frac{k_1+k_2}{2}x-\frac{\omega_1+\omega_2}{2}t\right)\cos\left(\frac{k_1-k_2}{2}x-\frac{\omega_1-\omega_2}{2}t\right)$$
Now, what I usually find in literature is that for a general wave,the velocity of a wave is defined as $v=\omega/k$ and here we see that by simplifying the superposition, we get a slow moving and a fast moving term and
(1) For the slow moving wave which represents the group envelope, we call the velocity as group velocity $v_g=\Delta \omega/\Delta k=\partial\omega/\partial k$ (for waves with small differences in $\omega$ and $k$).
(2) For the fast moving wave which represents the ripples, we call the velocity as phase velocity $v_g=\bar \omega/\bar k=\omega/ k$ (if $\omega$ is given as a function of $k$).
What I don't understand in this analysis is
Why this definition of velocity? Why did we just divide the factors of x and t and call that as velocity? For a single sine wave, I understand how we can find the displacement of a maxima or minima and see how much it moves in some time t and define that as velocity (just like mentioned here). But is there any similar treatment possible for this?
How did we identify which one was the group and which one was the phase velocity? Also, it is not very intuitive at first site for a person who didn't know this before that there are actually 2 velocities embodied in such a solution?
I would be very grateful if someone could possibly have an answer to these questions.
Answer: The top two graphs from the MakeaGIF.com website are for waves of one frequency/wavelength travelling at different phase speed as shown by the motion of the red and blue dot sitting on top of a crest.
The term phase is used because you are observing the particle which make up the medium at their maximum upward excursion from the equilibrium position and the speed of that crest is measured as the distance moved by a crest divided by the time taken to move that distance.
You could have equally well chosen to follow a trough or when the particles had zero displacement or the phase $kx-\omega t = \text{constant}$.
Differentiating this expression gives the phase speed as $\left (\dfrac{dx}{dt}\right)_{\rm phase} = \dfrac \omega k$
The bottom graph is the addition of the top two graphs and you will note that a modulating envelope the peak of which as shown by the red dot travels at the group velocity where group refers to the motion of a number (group) of waves added together and $\left (\dfrac{dx}{dt}\right)_{\rm group} = \dfrac {\Delta\omega} {\Delta k}$.
This is derived from French's cosine term where you want the term in the bracket to be a maximum with $\omega = \omega_1-\omega_2$ and $\Delta k = k_1- k_2$ and follow the movement of that maximum.
Hopefully the gif animations below from the Institute of sound and Vibration Research (isvr) will help you to differentiate between group velocity and phase velocity. | {
"domain": "physics.stackexchange",
"id": 65881,
"tags": "waves, velocity, superposition, phase-velocity"
} |
rosbag of extrinsic calibration | Question:
http://www.ros.org/wiki/openni_launch/Tutorials/ExtrinsicCalibration
my system is ubuntu11.10,installed with ROS( electric) and openni_kinect.
Use rosbag to record 10 seconds of RGB data to rgb.bag:
rosbag record --limit=300 -O rgb /camera/rgb/image_rect /camera/rgb/camera_info
terminal display
[ INFO] [1340799943.911159328]: Subscribing to camera/rgb/image_raw
[ INFO] [1340799943.913291068]: Subscribing to camera/rgb/camera_info
terminate called after throwing an instance of 'std::out_of_range'
what(): basic_string::erase
Aborted
I dont know what to do.
Originally posted by rosmaker on ROS Answers with karma: 51 on 2012-06-27
Post score: 0
Answer:
Hi,
Try changing the command line to:
rosbag record --limit=300 -O rgb.bag /camera/rgb/image_rect /camera/rgb/camera_info
Worked for me :)
Cheers,
Tom
Originally posted by Smot with karma: 61 on 2012-07-17
This answer was ACCEPTED on the original site
Post score: 0 | {
"domain": "robotics.stackexchange",
"id": 9961,
"tags": "calibration"
} |
What causes the intensity difference between emission spectrum of different wavelengths for a certain material? | Question: Can it be explained via blackbody radiation? Or is it purely to do with the material itself? For example, why does the line at 589.0 nm has twice the intensity of the line at 589.6 nm for sodium?
Answer: Sodium is not a blackbody. Rather the spectrum is determined by all the possible transitions between energy levels of it's electrons. Some of those levels are degenerate to varying degrees. If there are a lot of possible transitions with the same energy, the spectrum of the material will have a higher intensity for those energies, or wavelengths, respectively. | {
"domain": "physics.stackexchange",
"id": 77745,
"tags": "optics, experimental-physics, physical-chemistry, spectroscopy"
} |
Taylor expansion in derivation of Noether-theorem | Question: In my classical mechanics lecture we derived the Noether-theorem for a coordinate transformation given by:
$$ q_i(t) \rightarrow q^{'}_i(t)=q_i(t) + \delta q_i(t) = q_i(t) + \lambda I_i(q,\dot q,t).$$
Then we calculated the action $S'$ and used a taylor expansion around $\lambda = 0$:
$$S' = \int_{t_1}^{t_2} dt\,L(q^{'}_i,\dot q^{'}_i,t) = \int_{t_1}^{t_2} dt\,[ L(q_i,\dot q_i,t) + \lambda \frac{d}{d\lambda}L(q^{'}_i,\dot q^{'}_i,t)\bigg \vert_{\lambda = 0}\,].$$
My question is why is there a $\lambda$ in the first order term of the expansion?
Answer: It seems that your $\lambda$ should be thought of as a small parameter. For example, you may write a first order Taylor expansion as
$$
f(x + \lambda) = f(x) + \lambda f'(x) + ...
$$
You could also note that
$$
f'(x) = \frac{d}{d \lambda}f(x + \lambda)\vert_{\lambda = 0}
$$
The main thing is that $\lambda$ should be thought of as a tiny infinitesimal constant which parameterizes your symmetry transformation, i.e. $\delta q_i = \lambda I_i$. Therefore, $\lambda$ parameterizes $L'$. In more compact notation,
$$
L' = L(q_i + \delta q_i) = L(q_i + \lambda I_i)
$$
This means that if we want the tiny change due to this transformation, we can just think of $\lambda$ itself as tiny, so
$$
dL = L(q_i + \lambda I_i) - L(q_i) = \lambda \frac{dL}{d \lambda}.
$$
One final thing to mention is that there MUST be a $\lambda$ out front because the change to your action due to an infinitesimal transformation must be infinitesimal itself, and that change must be proportional to the infinitesimal parameter. | {
"domain": "physics.stackexchange",
"id": 58210,
"tags": "classical-mechanics, lagrangian-formalism, differentiation, action, variational-calculus"
} |
Did universe have finite hydrogen | Question: According to this video stars at end of time and many others on fate of universe they all agree on one thing that stars will eventually convert all the hydrogen into heavier elements and eventually there will be no light , i understand the documentaries are over simplified but is it really the case that universe had/has finite amount of hydrogen to start with and there is no known process that recycling hydrogen back into universe
Answer: Are you sure it's true that all hydrogen will eventually be processed? I can see that star formation rate should eventually slow to a point that there would be essentially no more light being created, but that's not the same thing. Right now, most of the hydrogen in the universe is in the space within clusters of galaxies, and some of it falls into galaxies and some gets ejected, so you might imagine that all of that will eventually get processed. But there is also hydrogen in between galaxy clusters, in the "cosmic web", and since the universe is expanding quite rapidly, it seems quite possible to me that much or most of that gas will never fall into a galaxy, but instead just end up stranded in between the expanding clusters.
What's more, our models now include the "cosmological principle" that treats the universe as homogeneous, but that's just the universe we can see. We have good evidence that it extends way beyond what we can see, so we have no way to know (or even to expect) that the homogeneity is a truly global property of the entire universe (i.e., not just the "observable" universe). On scales we cannot probe, the structure might be fractal, meaning that there could be pockets somewhere doing very different things, and there might always be stars forming somewhere. Another possibility is that there could be a "landscape" of universes, which is hard to say if they count as the same universe or completely different ones, but it does mean there could be in existence hydrogen elsewhere in the "landscape" even after our universe has none. So it's a tricky question to answer if "all the hydrogen" will eventually be processed, but I suppose you could look at all the hydrogen in the observable universe-- but you still have to wonder if the gas between the clusters ever gets into a galaxy. | {
"domain": "astronomy.stackexchange",
"id": 3606,
"tags": "astrophysics, universe"
} |
Security of authentication check for a blog | Question: I am currently making a very big blogging system for my Website where I want really neat code! So, I was wondering: is this method safe/does it have any problems with security? Yes, I'll be encrypting the password anyway. I also want to know if there is a better way to achieve the same idea. Also any tips on implementing high security and high performance?
<?php
class Users {
protected $db;
public $id;
public $username;
public $password;
public $lastlogin;
public $email;
public $rank;
public $creationdate;
public $country;
public $status;
public function __construct() {
$this->db = new mysqli('localhost', 'root', 'php123', 'ht');
}
public function login($username, $password) {
$query = $this->db->prepare("SELECT username, password FROM blog_users WHERE username = ? AND password = ? LIMIT 1");
$query->bind_param('ss', $username, $password);
$query->execute();
$query->bind_result($username, $password);
$query->store_result();
if($query->num_rows == 1) {
while($query->fetch()) {
$userData = getData($username);
$this->id = $this->userData['id'];
$this->username = $username;
$this->password = $password;
$this->lastlogin = time();
$this->email = $this->userData['email'];
$this->rank = $this->userData['rank'];
$this->creationdate = $this->userData['creationdate'];
$this->country = $this->userData['country'];
$this->status = $this->userData['status'];
$_SESSION['loggedin'] = 1;
return true;
}
} else {
return false;
}
$query->close();
$query->free_result();
}
public function getData($username) {
$query = $this->db->prepare("SELECT id, email, rank, creationdate, country, status FROM blog_users WHERE username = ?");
$query->bind_param('s', $username);
$query->execute();
$query->bind_result($id, $email, $rank, $creationdate, $country, $status);
$query->store_result();
$userData = array(
'id' => $id,
'email' => $email,
'rank' => $rank,
'creationdate' => $creationdate,
'country' => $country,
'status' => $status
);
return $userData;
$query->close();
$query->free_result;
}
}
?>
Answer: Ok, just a few quick thoughts, will be adding to this answer later today (ie after work):
One class, One task
Chances are, you've already heard of the SOLID principles. Well, here they are again: your code is in violation of the SRP (Single Responsability principle). A class has one task. No more, no less. Your class does 4 things: it stores data (all those public properties), messes with sessions, connects to the DB and performs queries.
The Database connection and queries are all things that should be dealt with in another class, that simply connects to the DB and executes queries.
This other class could then have a method like this:
public function login(User $user)
{
$query = $this->db->prepare("SELECT username, password FROM blog_users WHERE username = ? AND password = ? LIMIT 1");
$query->bind_param('ss', $user->username, $user->password);
$query->execute();
$query->bind_result($user->username, $user->password);
$query->store_result();
if($query->num_rows == 1)
{
$query->fetch();
$query->close();
return $this->getUserData($user);//changed name of method
}
$query->close();
throw new RuntimeException('User can not login');//error
}
Even this isn't close to efficient code, because it still calls a second method to, basically, repeat the same query. Why would you do so, why not simply write:
public function login(User $user)
{
$query = $this->db->prepare(
"SELECT id, email, rank, creationdate,
country, status, username, password
FROM blog_users
WHERE username = ? AND password = ? LIMIT 1"
);
$query->bind_param('ss', $user->username, $user->password);
$query->execute();
$query->bind_result(
$user->id,
$user->email,
$user->rank,
$user->creationdate,
$user->country,
$user->status,
$user->username,
$user->password
);
$query->store_result();
if($query->num_rows == 1)
{
$query->fetch();
$query->free_result();//call free_result...
$query->close();//and close here, too: your code doesn't do this
return $user;
}
$query->free_result();
$query->close();
throw new RuntimeException('User can not login');//error
}
Isn't that a lot shorter, clearer and doesn't this also do exactly what you are doing? K.I.S.S!
Classes with a dependency, should be open to injection
Your current code is hard to test: the constructor connects to the DB, there is no way for me (the user), or you (when testing) to mock the db connection, or use a bogus testing table.
The best way to make your class easier to test it to allow the user to pass a specific connection to the constructor, and then he can use your class/functionality to work on the db of his choice:
public function __construct(mysqli $connection = null)
{//default null means the argument is optional
if ($connection === null)
$connection = new mysqli();//connect to default
$this->db = $connection;//use connection we've created, or the one the user passed through to the constructor
}
And of course: a DB connection that is opened, should be closed: when your class dies (is destructed), the DB connection should die, too:
public function __destruct()
{
$this->db->close();
$this->db = null;
}
That should be added to your code, too. If you don't then the connection will be kept open until your script has terminated, which could be longer than you want. If performance and cleanliness matter to you, then this should be a habit.
Standards, coding style
Yes, I complain/nag a lot about coding style and standards but if you are, like you say, creating a sizeable code-base, then you should know that coding style and standards are insanely important.
The unofficial PHP standards can be found here. Though unofficial, all major players (ie Zend, Symfony, Cake, Doctrine, ...) all subscribe to them.
Other niggles:
Your class has tons of properties, and it's those properties that you are assigning in the methods. Why, then aren't you assigning $username as soon as you can, so you don't have to pass it to the getData method as an argument?
Another remark I have is simply this:
If a script contains only PHP code, then that script should not have a closing ?> tag. Get rid of it. | {
"domain": "codereview.stackexchange",
"id": 7526,
"tags": "php, security, database, authentication"
} |
Is there a webpage that shows the night sky but can filter out dim stars? | Question: This webpage is very good for viewing the night sky and learning the names of the stars
Timeanddate - Astronomy
However, it shows too many stars. Because I live in the city, I can only see about 50 stars. If I could filter out all of the dim stars, that would help me focus on just the top 50 brightest stars. If I want to learn the names of the stars and how to identify them I have to start with the brightest. Yes, you can scroll over the star and it will tell you how bright it is, but that is very time-consuming.
Answer: I think your requirements can be met by Stellarium. It is a freely available open-source planetarium software available for PC, and can be used offline.
There is also a web version, which you can try out here.
You can filter stars out by pollution levels, as illustrated in the stellarium wiki.
Here is an Astronomy Stackexchange answer on matching the magnitude of stars to what is visible from specific cities. | {
"domain": "astronomy.stackexchange",
"id": 5203,
"tags": "observational-astronomy, amateur-observing, night-sky, star-gazing"
} |
How to show that interaction potential depends only on separation of particles in system with position translation symmetry? | Question: System
2 particles with mass moving in one spatial dimension $x$. Positions of particles are $x_1$ and $x_2$ respectively and they are only acted on by a conservative interaction force corresponding to potential energy $U(x_1,x_2)$
Question:
Show that symmetry under spatial translations $x\rightarrow x+a$ requires the potential energy to only depend on the difference in positions $x_1 - x_2$
Working/Thoughts:
Translation symmetry means that shifting both particles by the same amount along the axis doesn't affect the physics of the particles. Therefore, the particles will only have the same interaction potential energy after being shifted if it only depends on their relative separation - in one dimension this is the difference of their coordinates but if it was in $\mathbb{R}^2$ or $\mathbb{R}^3$ then it would be the norm of the difference of the position vectors. I think I understand the intuition behind this, but I don't know how to show it mathematically.
I have tried out different combinations such as: $x_1 + x_2$, $x_1-x_2$, $x_1x_2$, $(x_1)^2 - (x_2)^2$, $c_1x_1+c_2x_2$, $c(x_1-x_2)$, $(x_1-x_2)^2$ and I found only only combinations containing $(x_1-x_2)$ are invariant under $x_1\rightarrow x_1+a$ and $x_2\rightarrow x_2+a$. There is strong evidence for $U(x_1,x_2) = U(x_1-x_2)$ being the only way. However, I cannot be sure that the potential only depends on the difference in position.
My lecturer also showed me a solution that he didn't expect me to know using the method of characteristics that can be used to find this relation. I haven't learned that yet so I couldn't reproduce the same result.
Question to you: Is there a simpler way than the method of characteristics which one can use to show that $U(x_1,x_2) = U(x_1 - x_2)?$
Answer: Change variables to $$y_1 := (x_1+x_2)/2 \quad y_2 = (x_1-x_2)/2\tag{0}\:.$$
Notice that the map is smooth bijective with smooth inverse $x_1 = y_1+ y_2$ and $x_2 = y_1-y_2$ so that you can indifferently use coordinates $x$ or $y$.
Next, define $$V(y_1,y_2) := U(x_1(y_1,y_2), x_2(y_1,y_2))\:,$$
so that $$ U(x_1,x_2) = V(x_1+x_2, x_1-x_2)\:.\tag{1}$$
According to (0) and the very definition of $V$, saying that $$U(x_1+a,x_2+a) = U(x_1,x_2)$$ for every $a$ is the same as saying that
$$V(y_1,y_2) = V(y_1+a, y_2)$$
for every $a$.
In other words, $V(y_1',y_2) = V(y_1,y_2)$ for every $y_1,y'_1$ and $y_2$.
In other words, $V$ is constant in the first entry:
$$V(y_1,y_2)= W(y_2)\:,$$
for some function $W$ of a single variable.
Inserting this result in (1), we have
$$U(x_1,x_2)= W(x_1-x_2)$$
for some function $W$ with a unique entry. | {
"domain": "physics.stackexchange",
"id": 79411,
"tags": "homework-and-exercises, symmetry, potential-energy, noethers-theorem, conservative-field"
} |
Using PointCloud data for object detection | Question:
Hello,
I'm working on a project that uses Kinect as sensor for a robot. I intend to use PointCloud library for ROS. However, I don't know how to resolve or use the PointCloud data in order to detect objects. The object detection will be used in order to avoid obstacles using potential fields principle. So, I need to transform PointCloud data to obtain all possible obstacles (their coordinates, width, height, distance) in order to create forces to be used in the robot navigation. I don't know which tutorial should I follow? I would really appreciate if anybody gives me some guidance. Thanks in advance.
Originally posted by mozcelikors on ROS Answers with karma: 181 on 2013-07-29
Post score: 1
Answer:
I don't know if something like this already exists but I suggest you to use Octomap to have a collisionMap. Maybe with that, you can then isolate obstacles easier. See this link
You will need to have a filter to erase the ground, this octomap server has this too.
EDIT: If you know the object, you can use tabletop_object_detector but I don't believe this is what you are looking for.
Originally posted by jep31 with karma: 411 on 2013-07-29
This answer was ACCEPTED on the original site
Post score: 2 | {
"domain": "robotics.stackexchange",
"id": 15088,
"tags": "gazebo, pointcloud"
} |
Why is there an upthrust? | Question: Why is there $P_2$?
Is it because by Newton's third law of motion, $P_2$ is there due to the pressure of water column of $0.7 ~m$ above the bottom.
Answer: For an immersed object in water, water exerts pressure on it at every point, the magnitude given by $$P=P_{atm}+\rho gh$$
h is the height of water column above that point.
For the top surface, water exerts pressure downwards. For the bottom surface, water exerts pressure upwards. The water also exerts pressure on lateral sides, but is equal from all sides, since it is at same height. Hence no net effect. The pressure is higher at greater depths, so the box would experience a net upward force from below. | {
"domain": "physics.stackexchange",
"id": 60322,
"tags": "pressure, fluid-statics"
} |
Building machine learning model with variable targets and on the run | Question: I want to add Machine learning predictive capabilities to an existing application; the data that will be used to train the model is stored in a database.
My problem is as follows:
in a typical machine learning project, you have a set of features that you use to train the model, and a single column, which is the target. In my case, most columns can be the target; for instance, the user can select "sales." in this case, the "sales" column would be the target, and it won't be used as a feature in training. On the other hand, if the user wants to predict the "Quantity", which is another column, then the "sales" column would be a feature used in training and so on, and once deployed, the user would need to provide the "sales" value to predict the quantity required to achieve this sales amount. How do I approach this, as I have more than 20 columns that can be either a feature or a target?
the machine learning model should be customized for each customer; due to data residency requirements, I won't have access to each user's data, so the training of the models shall be done in the customer's premises dynamically, is there any way to ensure the model's performance?
I thought about training a CAT boost model or any other model with reasonable defaults on the run, storing it somewhere and using it again whenever needed. However, I have no means of ensuring the model's performance. All that I need is some hints on how to approach this problem so that I can read more into it.
Answer: There's at least two ways to approach these requirements.
Pick the 20 columns of greatest interest to customers for prediction.
Train, evaluate, and deploy 20 regression models.
In data science we learn the "shape" of business data.
Computing covariance can help with this.
We find that some combinations of feature values
will be routinely observed, while other combinations
are extremely rare.
Take advantage of this in order to serve your customers.
Choose a distance metric, and use a clustering technique
such as K-means to characterize your training data.
At inference time, given a feature vector of length 19,
use it to identify nearest cluster and to predict the target feature. | {
"domain": "datascience.stackexchange",
"id": 12120,
"tags": "machine-learning, training"
} |
Why do we put factors of zero in a Lagrangian that is to be extremized? | Question: According to the Wikipedia page on Lagrange multipliers under the section - Example 3: Entropy, it is written that:
$$f(p_1,p_2,\ldots,p_n) = -\sum_{j=1}^n p_j\log_2 p_j$$
For this to be a probability distribution the sum of the probabilities
$p_i$ at each point $x_i$ must equal 1, so our constraint is:
$$g(p_1,p_2,\ldots,p_n)=\sum_{j=1}^n p_j = 1\tag{1}$$
We use Lagrange multipliers to find the point of maximum entropy, $\vec{p}^{\,*}$ across all discrete probability distributions $\vec{p}$ on $$\{x_1,x_2, \ldots, x_n\}$$ We require that:
$$\left.\frac{\partial}{\partial \vec{p}}\Big(f+\lambda (g-1)\Big)\right|_{\vec{p}=\vec{p}^{\,*}}=0\tag{2}$$
My question is simple, why is $1$ is subtracted from the constraint $(1)$, in equation $(2)$?
Put another way, I think eqn. $(2)$ should be
$$\left.\frac{\partial}{\partial \vec{p}}\Big(f+\lambda g\Big)\right|_{\vec{p}=\vec{p}^{\,*}}=0,$$
However, I know that equation $(2)$ is correct as I have a similar problem regarding entropy also. In the following expression, (eqn. $(5)$), I must maximize the entropy subject to the constraints $$\mathrm{Tr}\left[\hat \rho\right]=1\tag{3}$$ and the constraint that the expectation value of the Hamiltonian, $$\mathrm{Tr}\left[\hat \rho \hat H\right]\tag{4}$$ is $E$,
$$S'=-\mathrm{Tr}\left[\hat \rho \ln \hat \rho\right]+\lambda\left(\mathrm{Tr}\left[\hat \rho \hat H-E\right]\right)+\mu\left(\mathrm{Tr}\left[\hat \rho\right]-1\right)\tag{5}$$
I just cannot understand why $1$ is being subtracted in the third term and $E$ is subtracted in the second term. This just seems non-sensical as from eqn. $(3)$ $$\mathrm{Tr}\left[\hat \rho\right]-1=0$$ so it is like $0$ is being added in as a constraint which makes no sense whatsoever to me.
Can someone please explain the logic behind putting factors of zero into the Lagrangian?
Update in response to a comment:
Since this post is not being well received I will try to clarify further by showing a 'counter-example', then, hopefully, it will become more clear why I am getting confused:
On this page for the derivation of the Boltzmann distribution it is written (amongst other things) that,
To find the most-likely configuration, we maximize $\ln\Omega_n$ subject to constraints,
$$\sum_j n_j=N,\quad \sum_j \epsilon_j n_j=U\tag{6}.$$
$\fbox{$\text{Where the statistical weight is defined as } $$\Omega_n=\frac{N!}{\prod_j n_j !}$}$
Using Lagrange's method of undetermined multipliers,
$$\frac{\partial}{\partial n_j}\left[\ln \Omega_n-\alpha\sum_jn_j-\beta\sum_j\epsilon_jn_j\right]=0 \,\, \forall \, j\tag{7}$$
But according to @Connor Behan (in one of the comments below this question)
"$g-1$ is the constraint"
So, this logic implies that equation $(7)$ should actually be written as
$$\frac{\partial}{\partial n_j}\left[\ln \Omega_n-\alpha\color{red}{\left(\sum_jn_j-N\right)}-\beta\color{red}{\left(\sum_j\epsilon_jn_j-U\right)}\right]=0 \,\, \forall \, j\tag{8}$$
Which by virtue of the equations in $(6)$, the terms in the parentheses marked in red are zero. Now you may see what I meant when I asked "why do we put factors of zero in the Lagrangian"
To be pedantic, my reasoning for writing what I did in that last paragraph above is because I am simply subtracting $N$ and respectively $U$ from both sides of the respective equations in $(6)$. Hence my reason for suggesting the terms marked red in $(8)$ are zero.
So, either equation $(7)$ is correct or equation $(8)$ is correct. They can't both be correct so which one is it?
Just a side note, I know that the constant terms ($N$ and $U$) in eqn. $(8)$ will differentiate to zero anyway. But what I would like to know here is the reason for the inconsistency between equations $(7)$ and $(8)$.
Answer: The discussion in the comments suggests that the following might help clarify the confusion.
Original problem The original maximization problem is this: Maximize
$$\ln\Omega_n = - \sum_j n_i \ln \frac{n_j}{N}\tag{1}$$
subject to the constraints
$$\sum_j n_j = N,\quad \sum_j E_j = U \tag{2}$$
The constraints impose a relationship between the $n_j$, therefore we cannot simply differentiate $\ln\Omega$ with respect to $n_j$ and set the result eqial to zero because $n_j$ are not independent.
Lagrange's reformulation Construct a new function in which the $n_j$ are independent. This function is
$$
\mathcal L(\{n_j\}, \alpha, \beta)
= \ln\Omega_n
- \alpha\left(\sum_j n_j - N\right)
- \beta\left(\sum_j E_j n_j - U\right)
$$
This is a function of $n_j$, $\alpha$ and $\beta$, and all variables are independent. The solution then is
$$\tag{3}
\frac{\partial \mathcal L }{\partial n_j} = 0,\quad
\frac{\partial \mathcal L }{\partial \alpha} = 0,\quad
\frac{\partial \mathcal L }{\partial \beta} = 0 .
$$
Since the $n_j$ are now independent, we can choose their values arbitrarily (in this problem they must be non negative numbers), therefore they are no longer required to obey the constraints.
Suppose we identify a set $(n^*_j, \alpha^*\neq 0, \beta^*\neq 0)$ that satisfies all equations in (3). Then
$$\tag{4}
\frac{\partial \mathcal L}{\partial \alpha^*} = 0
\Rightarrow
\frac{\partial}{\partial\alpha^*}\alpha^*\left(\sum_j n^*_j - N\right) = 0
\Rightarrow
\boxed{\sum_j n^*_j = N\vphantom{\sum^j}}
$$
We conclude that the solution to (3) also satisfies all constraints.
In Sumamry Lagrange constructs a new function in which all variables are independent. This relaxes the requirement that the $n_j$ must obey the constraints. Even so, the solution that is obtained by minimizing this new function is guaranteed to satisfy these constraints. | {
"domain": "physics.stackexchange",
"id": 94363,
"tags": "lagrangian-formalism, entropy, variational-principle, density-operator, constrained-dynamics"
} |
Cavity resonator modelling and simulation of em fields inside the cavity | Question: I want to model a cylindrical cavity resonator and study the different modes of em fields inside it using MATLAB/COMSOL. Please refer me books/articles or other resources so that I can achieve my goal.
Answer: The idea is that you have to specify the equation to solve, usually it is the Helmholtz equation which is of elliptic type. Then, you have to specify boundary conditions and choose a numerical technique to solve the problem (in a complicated geometry it might be FEM or FDM, sometimes one can use a variational method without a grid). After that, you have to choose a solver or write your own code implementing that numerical (or analytical) method. Depending on the solver, it is better to start with a corresponding manual in order to understand how to use it.
There are plenty of literature. To begin with I would suggest following books
1) Jian-Ming Jin, The Finite Element Method in Electromagnetics, John Wiley & Sons, 2015
2) Umran S. Inan, Robert A. Marshall, Numerical Electromagnetics: The FDTD Method, Cambridge University Press, 2011
3) Matthew N.O. Sadiku, Numerical Techniques in Electromagnetics with MATLAB, CRC Press, 2000
I think the last one suits your needs the best. Again, before using a solver, the most crucial is to understand what kind of equation one has to solve. If your know the equation and boundary conditions, using COMSOL is simple and is well explained in the COMSOL manual by numerous examples. | {
"domain": "physics.stackexchange",
"id": 49648,
"tags": "electromagnetism, resource-recommendations, simulations, resonance, software"
} |
Looper: missing argument error | Question: While trying to run looper I am getting the following error:
Error (missing attribute): 'sandro_rna_seq' requires sample attribute '/scratch/nv4e/sandro_looper/pipeline/jyvo_experiment-metadata.yaml' for option/argument '-E'
Not submitted: Required attribute(s) missing for pipeline arguments string
In my pipeline_interface.yaml file I have the following:
arguments:
"-L": "IU"
"-T": "gencode_mouse_m13"
"-E": "/scratch/nv4e/sandro_looper/pipeline/jyvo_experiment-
metadata.yaml"
The file "/scratch/nv4e/sandro_looper/pipeline/jyvo_experiment-metadata.yaml" is definitely present but it still gives an error...
Any suggestions would be greatly appreciated.
Answer: You are using the argument values incorrectly. Argument values are sample attributes, not full character paths. Hence, "IU" is a sample attribute, "gencode_mouse_m13" is a sample attribute, so why would you think "/scratch..." would be treated any differently?
The pipeline interface maps sample attributes to command-line arguments. It is modulated by sample (different values per sample). What you're trying to do is pass a constant string to an argument.
For this, there is a pipeline_args section of your project config. Please read the docs on project config. | {
"domain": "bioinformatics.stackexchange",
"id": 385,
"tags": "scrnaseq, yaml, looper"
} |
Sort algorithm in c | Question: I wrote this algorithm a while ago, and decided to revisit it and polish it up.
It basically works by comparing each number with all the other numbers once, so comparing the first number to all except itself, the second to all numbers after itself etc, to avoid double comparison. I'm sure it has an official name, but have no idea what that would be as I put it together myself.
#include <stdio.h>
#include<stdlib.h>///only needed for example code
#include<time.h>///only needed for example code
int number,scan,totalnumbers;
int main()
{
totalnumbers=10;///just for the example. functional code would need an input system.
int array[totalnumbers][3];//one for input, second tallying values, third for transfer output.
///for the example choose random numbers :
srand(time(NULL));
for (scan=0;scan<totalnumbers;scan++)
{
array[scan][0]=rand()%200;
}
//fill [2] with zeros, as will be incremented to work out location.
for (scan=0;scan<totalnumbers;scan++)//formatting the whole array
{
array[scan][1]=0;
}
for(number=0;number<totalnumbers;number++)
{
for(scan=number+1;scan<totalnumbers;scan++)///compare to all numbers, excluding itself
{
if(array[number][0]>array[scan][0])
{
array[number][1]++;
}
else
{
array [scan][1]++;///this includes when they are equal, and can be adjusted if you want earlier or later instanses of the same number to be displayed first
}
}
}
///now we put each number into its place in the third 'array'
for(number=0;number<totalnumbers;number++)
{
array[array[number][1]][2]=array[number][0];///the position in array[number] [1] tells us wher the one in array[number][0]should go, and we place it there in [2]
}
printf("Results\n");
for(number=0;number<totalnumbers;number++)
{
printf("%d\n",array[number][2]);
}
}
Answer: Central
In showing the algorithm, it is far better to clearly delineate the test driver code from the core code-under-test. The mixture of the algorithm with test code in main() blurs that boundary. Suggest using a function to set off your algorithm. Something like the following and have main() call it:
void my_sort(int *destination, const int *source, int *tally, int size)
The 3 arrays rolled into a 2D array is disconcerting. Code then uses 0,1,2 to note which array rather than a more meaningful #define SOURCE 1 #define TALLY 2, …. Further, the N*N for() loop accesses array[][], yet has to skip over every third element array[][2]. This needlessly spreads out the data, likely increasing cache misses. Also, the type of array[][0] needs to match type of array[][2], yet not type array[][1]. To rectify all these, suggest making 3 separate arrays, 2 of type data_t and the 3rd (tally array) of type size_t. By clearly using data_T, code can readily be adapted to cope with "number" as stated in the post, be it int, double, etc.
data_T source[totalnumbers];
data_T destination[totalnumbers];
size_t tally[totalnumbers];
A subtle good aspect about this sort is that elements of the same value do not change order. This property is useful in more complicated data types and compares.
An important weakness to this sort in that is in O(n*n) rather than a O(n*log2(n)). Yet it does minimize the movement of elements.
A weakness to this sort, is that the source and destination array cannot be the same array. Not an in-place sort.
I found the description imprecise "It basically works by comparing each number with all the other numbers once" should be "It basically works by comparing each number with all subsequent numbers once"
Minor
Why asymmetric spacing in #include statement?
#include <stdio.h>
// #include<stdlib.h>
// #include<time.h>
#include <stdlib.h> // Add space
#include <time.h>
Why /// versus // ? WET vs DRY.
// #include<stdlib.h>///only needed for example code
#include <stdlib.h> // only needed for example code
Avoid unneeded pluralizing totalnumbers totalnumber
Unclear why the blank line after array[] below.
{
array[number][1]++;
}
With a separate tally array, suggest a memset() call instead
// for (scan=0;scan<totalnumbers;scan++) {
// array[scan][1]=0;
//}
memset(tally, 0, sizeof tally);
Respect the presentation width and check spelling (at least 3 words misspelled). Reeding comments ahtat arent spellled korreclty is mor dificult.
// Too long
// array [scan][1]++;///this includes when they are equal, and can be adjusted if you want earlier or later instanses of the same number to be displayed first
Instead
// This includes when they are equal, and can be adjusted if you want
// earlier or later instances of the same number to be displayed first
array [scan][1]++;
Pedantic
srand() expects unsigned. Cast to indicate possible loss of precision is OK
// srand(time(NULL));
srand((unsigned) time(NULL));
Not a fan of the missing return 0; at the end. Although not needed, it adds pause in the review – was this OP’s intent?
Suggest a name and date in your code
// Orangesandlemons 2016 | {
"domain": "codereview.stackexchange",
"id": 19697,
"tags": "algorithm, c, sorting"
} |
Find the loop invariant of the given while loop | Question: I don't know how to find a loop invariant. I'm not sure where to start. Can anyone find the loop invariant of the given program and explain your method please.
{n ≥ 0 ∧ i = 0}
while i < n − 1 loop
b[i] := a[i + 1];
i:=i + 1
end loop
{∀j.(0 ≤ j < n − 1 → b[j] = a[j + 1])}
Answer: At the end of each iteration you have
$$
\forall j: 0 \leq j < i \implies b[j] = a[j+1]
$$
which you can prove by induction. Thus, when the algorithm terminates, $i$ has reached $n-1$ and you have
$$
\forall j: 0 \leq j < n-1 \implies b[j] = a[j+1]\,.
$$
I figured this out by just asking myself what kind of statement I can make at the end of each iteration. In this case it's that the first $i$ elements have been copied. Then I just turned that into a formal statement. | {
"domain": "cs.stackexchange",
"id": 11035,
"tags": "proof-techniques, loop-invariants, hoare-logic, proof-assistants"
} |
Debye Hückel Theory | Question: In the derivation of the Poisson-Boltzmann equation, my textbook arrives at the expression
$$
\rho_i = c_+ z_+ F + c_-z_-F = c_+^oz_+^oFe^{-z_+e\phi_i/kT} + c_-^oz_-Fe^{-z_-e\phi_i/kT}
$$
where $c_\pm$ is the concentration (of positive or negative ions), $z_\pm$ is the valence of the ions, $F$ is the Faraday constant ($=eN_A$) and $c_\pm^o$ is the concentration in the bulk. The rest is standard notation.
The book now writes that
Because the average electrostatic interaction energy is small compared with $kT$, we may write
$$
\rho_i = (c_+^o z_+ + c_-^oz_-)F - (c_+^oz_+^2 + c_-^oz_-^2)\frac{F^2\phi_i}{kN_AT} + \cdots
$$
How do they know that $ze\phi \ll kT$?
To make an estimate, I find the electric potential of a proton (or an $\text{Na}^+$ ion) in vacuum at 1 nm away.
$$
V^{vac} = \frac{1}{4\pi\epsilon_0}\frac{+1e}{1nm} \approx 1.43 \text{V}.
$$
In water ($\epsilon = \epsilon_0\epsilon_r = \epsilon_078$),
$$
V^{sol} = \frac{1}{4\pi78}\frac{+1e}{1nm} \approx 0.02 \text{V}.
$$
So in solution a $\text{Cl}^-$ ion would have the energy
$$
w=(-1e)V^{sol} \approx -3.2 \cdot 10^{-21}J
$$
while at room temperature $kT \approx 3.9 \cdot 10^{-21}J$.
Is this roughly the idea behind the above assumption?
Answer: I see four reasons to make this assumption:
The first one is simply that we do not know really how to deal with the non linear problem in general cases and therefore we linearize but I agree that it is not a good justification although this is most of the time the hidden reason why people use it
The Poisson-Boltzmann equation is mostly used in aqueaous solutions and therefore you have a factor 80 (owing to the dielectric constant of bulk water) that appears in all your potentials...this more or less ensures that a monovalent ion does not generate a so high potential energy with other monovalent ions. If you have free ions in solution, it means that the thermal energy was enough to begin with to unbind them from the groups there were bound to
It can be rigorously shown that at large distances from an ion at any valency, the generated potential decays exponentially with the distance (or rather like a Yukawa potential) because of the screening owing to the mobile charges in solution (this result holds in the non linear Poisson-Boltzmann case but also beyond the Poisson-Boltzmann theory).
Incindentally, a Yukawa potential is what you can expect from the field generated by an isolated ion in solution within the linearized Poisson-Boltzmann theory. Also, if you are a bit familiar with liquid theory, a particular closure of the Orstein-Zernike equation leads to an infinite summation over tree-like diagrams that leads to a total correlation function between two point ions in solutions that decays as a Yukawa as well which tells you more or less that although you linearize, you still encapsulate important many body effects
Because of the last point, there is a huge litterature on charge renormalization of charged particles in solution as a function of their valency, size and salt concentration. In the context of the Poisson-Boltzmann theory, charge renormalization refers to a mapping from the non linear theory to the linearized one via the use of effective charge paramaters | {
"domain": "physics.stackexchange",
"id": 7481,
"tags": "debye-length"
} |
Use PTZ controls on Axis Camera | Question:
I have an Axis camera (AXIS M5014 PTZ) and I am using axis_camera package to get the video stream. The video stream using axis.py works perfectly fine.
Now I am trying to use axis_ptz.py node to control PTZ parameters of the camera. Firstly, there is barely any documentation on this page explaining how you can actually set the parameters for dynamic configuration. After some research I found that rosrun rqt_reconfigure rqt_reconfigure opens a GUI for you to set parameters on different available variables. Now, only "pan" variable works, and "tilt" doesn't do anything. Are there and examples/tutorials/documentation that can help me out?
Originally posted by ajain on ROS Answers with karma: 281 on 2014-10-27
Post score: 0
Answer:
The teleop.py node subscribes to sensor_msgs/Joy and publishes axis_camera/Axis messages. If you have a joystick, you should be able to control the PTZ using it.
The axis_ptz.py node subscribes to the cmd topic and receives the published axis_camera/Axis in order to control the PTZ unit.
In a nutshell, if you publish axis_camera/Axis messages from your node, you should be able to control the PTZ unit. I based myself on the teleop.py when I wrote my own node.
As for the dynamic reconfigure, I haven't tried that out.
I hope it helps!
Originally posted by Murilo F. M. with karma: 806 on 2014-10-29
This answer was ACCEPTED on the original site
Post score: 2 | {
"domain": "robotics.stackexchange",
"id": 19863,
"tags": "ros, rqt-reconfigure, dynamic-reconfigure"
} |
How does the force between two charges becomes zero? | Question: In case of Coulombs law,
$$
F=k\frac{q_1q_2}{d^2}
$$
So, if $F=0$, then $q_1q_2$ must be 0. Is this true?
Answer: What Jim is talking about in the comments is a limit: for $d$ becoming increasingly large, $F$ becomes increasingly small.
For example, if $q_1 = q_2 = 1\,\text{C}$ and the charges are a distance $d = 1\,\text{m}$ apart, we find that the force is
$$F = k \sim 10^{10}\,\text{N}.$$
If the distance is made 1000 times bigger, the force is
$$F = k/(1000\,\text{m})^2 \sim 10^4\,\text{N},$$
i.e. $10^6$ times smaller. If the distance is increased by another factor 1000, the force is decreased by a factor $10^6$ yet again and becomes $F \sim 10^{-2}\,\text{N}$.$^1$
So even though the distance between $q_1$ and $q_2$ can never actually reach infinity, it's clear that $d$ can become so big that the Coulomb force becomes negligible. At this point you can treat $F$ as being exactly zero without introducing any noticeable errors.
$^1$ Note that the Coulomb is a large unit and so $1\,\text{C}$ is already very extreme. More realistically you'll see values $|q| \sim 1\,\text{mC} = 10^{-3}\,\text{C}$ which would give you a force $F\sim 10^4\,\text{N}$ for charges only one meter apart already. For $d = 1000\,\text{m}$ then, you'd have $F\sim 10^{-2}\,\text{N}$. Since the Newton is a fairly small unit, this value for the force is already immensely small as compared to other forces that might be present.
For example, if the charges are tiny little identical metal cubes of mass $m = 1\,\text{kg}$ (a fairly realistic value for the given charges) lying on a plastic table, the static friction will be large enough to keep the cubes from sliding towards each other for a Coulomb attraction of up to $1$-$10\,\text{N}$. This is 2 to 3 orders of magnitude larger than the actual Coulomb force between the charges so that we can safely neglect the latter. | {
"domain": "physics.stackexchange",
"id": 17741,
"tags": "forces, electrostatics, coulombs-law"
} |
Can I determine magnetic field strength from pull force? | Question: I have some samarium cobalt magnets and I need to estimate the characteristics of the magnetic field they produce. They are spec'd to give 16 lbf of pull against an iron plate. Is it possible to estimate the magnetic field strength as a function of distance from the magnet using that force rating? I also, of course, know the dimensions of the magnets, but not of the plate.
Also, a secondary question: Is there a way to modify the above model to account for placing two magnets in series?
I only need a rough estimate, and I am interested in the variation with respect to the axial(pulling) direction. Any tips would be greatly appreciated.
Answer: There is an approximate force calculator at https://www.kjmagnetics.com/calculator.asp which you could use to get an estimate of the magnet grade.
Alternately you could download a free modelling software package like FEMM at http://www.femm.info/wiki/HomePage which would allow you to fairly accurately model the specific dimensions of your steelplate and magnets.
FEMM would allow you to calculate the force of stacked multiple magnets (but you can probably also do that with the simple calculator if you scale the magnet thickness). | {
"domain": "physics.stackexchange",
"id": 69457,
"tags": "electromagnetism"
} |
Computing pairwise bitwise OR in a list of bit-strings | Question: I am trying to solve this problem using Clojure:
You are given a list of \$N\$ people who are attending ACM-ICPC World
Finals. Each of them are either well versed in a topic or they are
not. Find out the maximum number of topics a 2-person team can know.
And also find out how many teams can know that maximum number of
topics.
Input Format:
The first line contains two integers \$N\$ and \$M\$ separated by a single
space, where \$N\$ represents the number of people, and M represents the
number of topics. \$N\$ lines follow. Each line contains a binary string
of length \$M\$. In this string, 1 indicates that the ith person knows a
particular topic, and 0 indicates that the ith person does not know
the topic.
Output Format:
On the first line, print the maximum number of topics a 2-people team
can know. On the second line, print the number of 2-person teams that
can know the maximum number of topics.
Constraints:
\$2 ≤ N ≤ 500\$
\$1 ≤ M ≤ 500\$
Sample Input:
4 5
10101
11100
11010
00101
Sample Output:
5
2
However, my implementation is too slow to pass all the test cases. What are some suggestions to optimize this implementation? Basically, I have a list of bit-strings, and I am trying to find a faster way to bitwise-OR every pair of strings, and find the maximum number of set bits that could be obtained from ORing a pair.
(let [[N _] (clojure.string/split (read-line) #" ")
N (Integer/parseInt N)
strings (vec (repeatedly N read-line))
known
(for [i (range N) j (range (inc i) N)
:let [s1 (strings i)
s2 (strings j)]]
(apply + (map #(if (or (= %1 \1)
(= %2 \1))
1
0)
s1
s2)))
maximum (apply max known)]
(println maximum)
(println (count (filterv #(= % maximum) known))))
Answer: I was able to get it accepted by optimizing the inner loop by using BitSets instead of plain strings. I then just used the BitSet's or and bit counting method (cardinality) to do the work. Here's the resulting code:
(import [java.util BitSet])
(defn string->bitset [str]
(let [bitset (BitSet. (count str))]
(doall (map-indexed #(when (= \1 %2)
(.set bitset %1)) str))
bitset))
(defn bitset-or [s1 s2]
(let [tmp (.clone s1)]
(.or tmp s2)
tmp))
(let [[N _] (clojure.string/split (read-line) #" ")
N (Integer/parseInt N)
bitsets (mapv #(string->bitset %) (repeatedly N read-line))
known
(for [i (range N) j (range (inc i) N)
:let [s1 (bitsets i)
s2 (bitsets j)]]
(.cardinality (bitset-or s1 s2)))
maximum (apply max known)]
(println maximum)
(println (count (filterv #(= % maximum) known)))) | {
"domain": "codereview.stackexchange",
"id": 10514,
"tags": "performance, programming-challenge, lisp, clojure, bitwise"
} |
Gas being evacuated out at an infinitesimally small rate | Question: I am unable to think about a fact that my textbook used. It said that whenever an ideal gas is evacuated out from a chamber at an infinitesimally small $ volume/time$ rate, the mass inside the chamber in the small interval $dt $ remains constant provided the whole process is done isothermally.
I just can't think about it intuitively. The volume of the gas has decreased by an amount(not matter how much small it is) then how can the mass not lessen by some amount, say $ dm$ because itis the moles of the gas that are actually taking up the volume and if I decrease volume, the number of moles must go down and hence the mass also.
Can anybody please help me in thinking about this problem?
Answer: What sou say is correct.
If we, in an isothermal process, let some moles escape from the chamber, volume decreases by an amount $dV$ and also does mass ($dm$).
But when we are working with ideal gasses, the assumption is that the gas is very dilute so that there is no potential energy because of the particles being near each other. This also means that $dm/dV$ is really small.
So the assumption that the mass will be constant is almost correct and practical. | {
"domain": "physics.stackexchange",
"id": 36282,
"tags": "thermodynamics"
} |
Improving the performace of the Naive Bayes classifier by decorrelating the data | Question: I was wondering if it is possible to improve the performance of the Naïve Bayes classifier by decorrelating the data. The Naïve Bayes assumes conditional independence of the features given some class $P(a_1, a_2 | c_1) = P(a_1 | c_1)P(a_2 | c_1)$ which is not necessarily true.
What if we applied a transformation into the space using decorrelation which will result in $Cov(a_1, a_2) = 0$ for all features. We have that if $a_1$, $a_2$ independent, then $Cov(a_1, a_2) = 0$. Although the converse does not strictly follow (e.g. consider the two dependent random variables $X \sim Norm(0, 1)$, and $X^2$ whose covariance is 0), the new features will be closer to being independent.
Answer: As you pointed out, a null covariance does not guarantee that variables are independent. You can have strongly dependent variables which show a covariance equal to 0. See a famous plot taken from Wikipedia page on Pearson correlation coefficient
A standard way to uncorrelate variables is to perform principal component analysis on the dataset, and use all components which are, by definition, uncorrelated. But please note that the Naive Bayes assumption is conditional independence, so independence for each class. In the general case, PCA projection would not be the same depending on the selected class.
Regarding the performance of Naive Bayes, I see no reason that a simple transformation should improve the model. This is supported by some reasonably well-received answers on similar questions, for instance this one on Stack Overflow, or this other one on Cross Validated.
However, I have read several reports of people getting increased accuracy when performing PCA prior to Naive Bayes. See here for instance, for a few exchanges on the subject, within a community of which trustworthiness is unknown to me; or search "PCA naive bayes" through your web search engine.
So in the end, I have no mathematical evidence to support this, but my feeling would be that the model performance variation before/after transformation could depend on the problem, especially the directions of principal components for each class.
Perhaps, if you perform some tests, you could share the result here. Otherwise, I think you could get answers with more mathematical background on Cross Validated. | {
"domain": "datascience.stackexchange",
"id": 6382,
"tags": "statistics, preprocessing, naive-bayes-classifier"
} |
Feeling low pressure fluid with high velocity | Question: In Bernoulli theorem physics we say that pressure is low when velocity is high but we feel pressure when fluid hits us why?
Answer: This shows a misunderstanding of pressure in the Bernoulli relation as well as a misunderstanding of how feelings work. Completely disregarding Bernoulli for a moment, let's say I touch you and then I punch you. Would you not feel the touch just because the punch is larger? This isn't relevant to Bernoulli, but I just want to point this out to you that relative softness does not mean undetectable.
In any case we don't need to think about the Bernoulli equation here really. If I have a high pressure pushing on the fluid at one place and a lower pressure pushing on the fluid at another place, which way will the fluid accelerate? Well, it will accelerate in the direction of decreasing pressure, so the velocity will increase as the pressure decreases.
This low pressure is not the pressure you would feel if this high-velocity stream were to hit you. The pressure you would feel is called the "stagnation pressure", and you can get an expression for it using the Bernoulli equation. I will leave this as an exercise to you to research/figure out. | {
"domain": "physics.stackexchange",
"id": 56659,
"tags": "fluid-dynamics, pressure, bernoulli-equation"
} |
Understanding zero field inside a conductor? | Question: Imagine a neutral conductor of any shape, the charges are randomly distribuited among the object. No way we can say the electric field inside is zero. If I'm wrong, then what can we say about the electric field at this point?:
Now, it's exposed to an electric field, then electrons will move until the field is 0, otherwise they will keep moving. Everything results in the given arrangement of charges. It's "logical" the field E is canceled by the field between the charges. So, the field inside a neutral conductor affected by the field E is zero. Because the conductor is still neutral, right?
Now, lest's charge the conductor negatively. Since electrons move "freely". the electrons will repel each other in an arrangement as follows:
At this point, according to books and videos, the electric field inside is still zero. The charges arrange so that any point inside experience a 0 electric field. But I don't really see it. The former case is more understandable. Now, there's not an external field arranging the charges so that they cancel the field. The only field I see now is the one created by the conductor itself.
I would like some corrections about my analysis.
Answer: On a local level, when you measure the electric field in matter (conductor or otherwise) there is a rapid variation both in time and space. Semiclassically, the electric field get's very large as you approach the nucleus, then drops off, the electrons are moving around the nucleus at very large speeds. So, yes, you are correct when you say there will be non-zero electric fields in conductors. Experimentally, though, any measurements we make in matter, are really time and space averaged results. These averaged fields are sometimes referred to as the macroscopic fields and it is these fields that are usually made use of. A very good reference if you can get it is a paper by Russakoff, American Journal of Physics Vol 38, Number 10, pp 1188-1195 (1970). | {
"domain": "physics.stackexchange",
"id": 30553,
"tags": "electrostatics, electric-fields, conductors"
} |
Wave function with a delta potential | Question: I have a particle and a potential $$V(x)=\frac{\hbar^2}{2m}k\delta(x),$$
where $\delta (x)$ is the Delta function, and I am interested in the solutions of the stationary Schroedinger equation.
If $\psi_1$ is the solution for $x<0$ and $\psi_2$ for $x>0$, I must have $\psi_1'(0) \neq \psi_2'(0)$, because of the delta function.
Now I read that the condition is $$\psi_2'(0) -\psi_1'(0) = -k\psi_2(0).$$
My question is: why? How do I get to this conclusion?
Answer: With a delta function potential, the particle is free on either side of the barrier:
$$
\psi(x)=\begin{cases}\psi_L(x)=A_re^{ikx}+A_le^{-ikx} \\
\psi_R(x)=B_re^{ikx}+B_le^{-ikx}\end{cases}
$$
where $A_i,\,B_i$ are constants such that $A_r+A_l=B_r+B_l$ (i.e., $\psi(x)$ satisfies the continuous function condition).
But at the barrier we have the issue that $V(0)=\infty$. So to resolve this issue, we use Schroedinger's equation and integrate it over some small region $\left[-\epsilon,\,\epsilon\right]$ and then let $\epsilon\to0$:
$$
-\frac{\hbar^2}{2m}\int_{-\epsilon}^\epsilon\psi''\,dx+\int_{-\epsilon}^\epsilon V\psi\,dx=E\int_{-\epsilon}^\epsilon\psi\,dx
$$
The first term is clearly $d\psi/dx$ evaluated at two points. The last term goes to zero in the limit $\epsilon\to0$ (recall that $E$ is constant and finite, so that as $\epsilon\to0$, the width goes to 0 and so does the whole value).
For the potential term, the delta function has the great property that
$$
\int\delta(x-a)f(x)\,dx=f(a)
$$
Thus, that middle term becomes $\left.\psi(x)\right|_{-\epsilon}^\epsilon$. We then combine these two to get
$$
-\frac{\hbar^2}{2m}\left[\psi'\left(+\epsilon\right)-\psi'(-\epsilon)\right]+\left.\lambda\psi(x)\right|_{-\epsilon}^{\epsilon}=0
$$
As $\epsilon\to0$, we can get the relation you are confused over:
$$
\psi'_R(0)-\psi'_L(0)=+k\psi(0)
$$ | {
"domain": "physics.stackexchange",
"id": 11141,
"tags": "quantum-mechanics, homework-and-exercises, schroedinger-equation, potential, dirac-delta-distributions"
} |
rosdep all packages | Question:
I've recently been working with some experimental packages created for ROS and amd compiling these from source. Quite a few of these packages seem to have dependencies, so naturally I have been using the rosdep install [package] command. However, this seems a bit tedious given the amount of packages in the workspace.
I was wondering if there was a quicker way to do this or is this the standard way? - Something along this lines of install all dependencies for packages within a specific folder or similar.
Originally posted by twix on ROS Answers with karma: 23 on 2015-02-04
Post score: 2
Answer:
Try:
rosdep --help
Quote:
[...]
-a, --all select all packages
[...]
--from-paths Affects the 'check', 'keys', and 'install' verbs. If
specified the arugments to those verbs will be
considered paths to be searched, acting on all catkin
packages found there in.
Originally posted by Martin Günther with karma: 11816 on 2015-02-04
This answer was ACCEPTED on the original site
Post score: 1
Original comments
Comment by twix on 2015-02-04:
Thanks! I was trying to get to this same set of instructions by just typing rosdep but it was giving me the commands instead of the arguments obviously. facepalm
Comment by Martin Günther on 2015-02-04:
Oh, I see. Yeah, it's strange that when run without any arguments, rosdep only prints half the help page. | {
"domain": "robotics.stackexchange",
"id": 20791,
"tags": "ros, rosdep, build, packages, dependencies"
} |
Thermodynamic process in auto-refrigeration | Question: I'm trying to understand why a high-pressure liquid drops in temperature when it's pressure is reduced in a refrigeration cycle. I can't use PV=nRT which only applies to gases, but a lower pressure would mean the liquid would start boiling if it was at a sufficient temperature. From just looking at a phase change diagram, the liquid could change to a gas with a drop in pressure and no temperature change. But according to Wikipedia:
"The saturated liquid refrigerant passes through the expansion valve and undergoes an abrupt decrease of pressure. That process results in the adiabatic flash evaporation and auto-refrigeration of a portion of the liquid (typically, less than half of the liquid flashes)."
If it's an adiabatic process and Q=0 then ΔU=-Q-W and internal energy decreases (Q=0 for the process but the latent heat of vaporization -Q would have to come from the liquid). I don't know how internal energy changes for liquids (which is supposed to be more complicated than gases) but for an ideal monoatomic gas a negative ΔU=(3/2)nRT would result in a decreased temperature. Does something similar happen for liquids and is this why you get a net decrease in temperature of both the liquid and vapor?
Thank you.
Answer: In addition to the $PV = nRT$ which you mentioned, substances have phase diagrams, or imperative states if you will. These are the states that substances must conform to given certain environmental conditions, because of the elements they are made of and the resulting bonding structures. They have been charted from experimental data.
For example, according to the phase diagram for water, water at atmospheric pressure and $110^\circ C \space(383K)$ is a gas. If we start with a few grams of ice at $-20^\circ C$, and at atmospheric pressure, and place it in an oven at $110^\circ C$, at the same pressure, it has to abide by the phase diagram and evaporate.
This is also true for refrigerant fluids going through a restriction valve from the 'condenser' side to the 'evaporator' side. The choice of refrigerant and the choice of refrigerant flow rate resulting in the pressures and temperatures around the restriction valve, is deliberate so as to effect the required refrigeration. As the refrigerant fluid passes through the valve it finds itself at a (lower) pressure, it evaporates to conform to its phase diagram. At a micro level, it is expanding to fill a larger volume. It maintains the same total energy (adiabatic process) but much less energy per unit volume, causing it to cool. If the fluid has to go from liquid to gas, it will need to scavenge energy from itself to allow some of it to evaporate, thereby cooling the fluid. | {
"domain": "physics.stackexchange",
"id": 47418,
"tags": "thermodynamics, adiabatic"
} |
How did the activities of protocells become inheritable? | Question: I have learned that first a protocell came to exist and its characteristics came to be passed on by genetic material. So how come genes for all the activities come to incorporate into genetic material? Did genetic material come first and random sequences made random proteins that were used to make cells ?
Answer: Well.. This is a tough question (Something that has bugged me for years and still doing so). I don't fully agree that replicative potential came first. This is just my opinion based on some reasoning and I dont really have any reference.
If you compare a nucleotide and a protein, the likelihood of formation of protein is much higher because:-
Amino acids are simpler molecules and simplest of them did appear in the famous Urey-Miller experiment. Nucleotides on the other hand are much more complex
Peptide/amide bond formation is a well known phenomenon even in non-biological chemistries whereas Phosporic esters cant be called common compounds.
In my opinion function evolved first and then its codification. Initially the cell division must have been just like a huge drop dividing into two. I would like to differ from mgkrebbs on this. Lipids are simple molecules and they can spontaneously form compartments such as miscelles based on simple principles of thermodynamics. If miscelles get huge they can divide.
I still cannot understand whether it is chemical reproduction that came fist or sustained multispecies chemical reactions. I tend to believe the second with relatively more confidence.
The popular RNA world hypothesis is justified by certain observations and fits nicely in the Darwinian scheme of biology that we are so used to believe in all the time. But it doesn't answer the previously mentioned thermodynamic perspective. Also I fail to understand why an ancient RNA would code a protein. What advantage would it have to code a protein in the first place. So to conclude I don't have a doubt that proteins came first. The initial soup and the basic functionalities were provided by them. Then nucleotides evolved parallely and they became catalysts of protein synthesis. So the reactants came before the catalysts and the better catalyst got selected.
I again iterate that this is just my opinion which you may consider pondering over along with the answers that others have provided. | {
"domain": "biology.stackexchange",
"id": 1291,
"tags": "evolution, genetics"
} |
Amcl particlecloud topic not publishing | Question:
Hi,
I would like to know why rviz is not showing the particle cloud for any of my robots. Below I have provided my navigation stack launch file and my amcl parameters yaml file. Everything works (e.g. navigating from a to b), except the amcl localization.
Thank you very much.
move_base_decentralised.launch:
<launch>
<master auto="start"/>
Run the map server
<node name="map_server" pkg="map_server" type="map_server" args="$(find lasmultigazebo4)/maps/my_map.yaml"/>
<node pkg="lasmulticontrol4" type="fixed_tf_broadcaster.py" name="broadcaster_fixed" />
<group ns="n_1">
<node pkg="amcl" type="amcl" name="amcl">
<rosparam file="$(find lasmultigazebo4)/config/amcl_params.yaml" command="load" />
<remap from="scan" to="/n_1scan"/>
<param name="odom_frame_id" value="n_1/odom" />
<param name="global_frame_id" value="map" />
<param name="base_frame_id" value="n_1base_footprint" />
<param name="use_map_topic" value="true"/>
</node>
<node pkg="move_base" type="move_base" respawn="false" name="move_base" output="screen">
<param name="base_local_planner" value="dwa_local_planner/DWAPlannerROS" />
<rosparam file="$(find lasmultigazebo4)/config/robot1config/costmap_common_params.yaml" command="load" ns="global_costmap" />
<rosparam file="$(find lasmultigazebo4)/config/robot1config/costmap_common_params.yaml" command="load" ns="local_costmap" />
<rosparam file="$(find lasmultigazebo4)/config/robot1config/local_costmap_params.yaml" command="load" />
<rosparam file="$(find lasmultigazebo4)/config/robot1config/global_costmap_params.yaml" command="load" />
<rosparam file="$(find lasmultigazebo4)/config/robot1config/dwa_local_planner_params.yaml" command="load" />
<!--<remap from="odom" to="n_1/odom"/>-->
<remap from="cmd_vel" to="Ug_cmd_vel"/>
</node>
</group>
<group ns="n_2">
<node pkg="amcl" type="amcl" name="amcl">
<rosparam file="$(find lasmultigazebo4)/config/amcl_params.yaml" command="load" />
<remap from="scan" to="/n_2scan"/>
<param name="odom_frame_id" value="n_2/odom" />
<param name="global_frame_id" value="map" />
<param name="base_frame_id" value="n_2base_footprint" />
<param name="use_map_topic" value="true"/>
</node>
<node pkg="move_base" type="move_base" respawn="false" name="move_base" output="screen">
<param name="base_local_planner" value="dwa_local_planner/DWAPlannerROS" />
<rosparam file="$(find lasmultigazebo4)/config/robot2config/costmap_common_params.yaml" command="load" ns="global_costmap" />
<rosparam file="$(find lasmultigazebo4)/config/robot2config/costmap_common_params.yaml" command="load" ns="local_costmap" />
<rosparam file="$(find lasmultigazebo4)/config/robot2config/local_costmap_params.yaml" command="load" />
<rosparam file="$(find lasmultigazebo4)/config/robot2config/global_costmap_params.yaml" command="load" />
<rosparam file="$(find lasmultigazebo4)/config/robot2config/dwa_local_planner_params.yaml" command="load" />
<!--<remap from="odom" to="n_1/odom"/>-->
<remap from="cmd_vel" to="Ug_cmd_vel"/>
</node>
</group>
<group ns="n_3">
<node pkg="amcl" type="amcl" name="amcl">
<rosparam file="$(find lasmultigazebo4)/config/amcl_params.yaml" command="load" />
<remap from="scan" to="/n_3scan"/>
<param name="odom_frame_id" value="n_3/odom" />
<param name="global_frame_id" value="map" />
<param name="base_frame_id" value="n_3base_footprint" />
<param name="use_map_topic" value="true"/>
</node>
<node pkg="move_base" type="move_base" respawn="false" name="move_base" output="screen">
<param name="base_local_planner" value="dwa_local_planner/DWAPlannerROS" />
<rosparam file="$(find lasmultigazebo4)/config/robot3config/costmap_common_params.yaml" command="load" ns="global_costmap" />
<rosparam file="$(find lasmultigazebo4)/config/robot3config/costmap_common_params.yaml" command="load" ns="local_costmap" />
<rosparam file="$(find lasmultigazebo4)/config/robot3config/local_costmap_params.yaml" command="load" />
<rosparam file="$(find lasmultigazebo4)/config/robot3config/global_costmap_params.yaml" command="load" />
<rosparam file="$(find lasmultigazebo4)/config/robot3config/dwa_local_planner_params.yaml" command="load" />
<!--<remap from="odom" to="n_1/odom"/>-->
<remap from="cmd_vel" to="Ug_cmd_vel"/>
</node>
</group>
<group ns="n_4">
<node pkg="amcl" type="amcl" name="amcl">
<rosparam file="$(find lasmultigazebo4)/config/amcl_params.yaml" command="load" />
<remap from="scan" to="/n_4scan"/>
<param name="odom_frame_id" value="n_4/odom" />
<param name="global_frame_id" value="map" />
<param name="base_frame_id" value="n_4base_footprint" />
<param name="use_map_topic" value="true"/>
</node>
<node pkg="move_base" type="move_base" respawn="false" name="move_base" output="screen">
<param name="base_local_planner" value="dwa_local_planner/DWAPlannerROS" />
<rosparam file="$(find lasmultigazebo4)/config/robot4config/costmap_common_params.yaml" command="load" ns="global_costmap" />
<rosparam file="$(find lasmultigazebo4)/config/robot4config/costmap_common_params.yaml" command="load" ns="local_costmap" />
<rosparam file="$(find lasmultigazebo4)/config/robot4config/local_costmap_params.yaml" command="load" />
<rosparam file="$(find lasmultigazebo4)/config/robot4config/global_costmap_params.yaml" command="load" />
<rosparam file="$(find lasmultigazebo4)/config/robot4config/dwa_local_planner_params.yaml" command="load" />
<!--<remap from="odom" to="n_1/odom"/>-->
<remap from="cmd_vel" to="Ug_cmd_vel"/>
</node>
</group>
</launch>
amcl_params.yaml:
odom_model_type: omni
odom_alpha5: 0.2
transform_tolerance: 0.2
gui_publish_rate: 10.0
laser_max_beams: 30
min_particles: 500
max_particles: 5000
kld_err: 0.05
kld_z : 0.99
odom_alpha1: 0.2
odom_alpha2: 0.2
<!-- translation std dev, m -->
odom_alpha3: 0.8
odom_alpha4: 0.2
laser_z_hit: 0.5
laser_z_short: 0.05
laser_z_max: 0.05
laser_z_rand: 0.5
laser_sigma_hit: 0.2
laser_lambda_short: 0.1
laser_lambda_short: 0.1
laser_model_type: likelihood_field
<!-- <param name="laser_model_type" value="beam"/> -->
laser_likelihood_max_dist: 2.0
update_min_d: 0.2
update_min_a: 0.5
resample_interval: 1
transform_tolerance: 0.1
recovery_alpha_slow: 0.0
recovery_alpha_fast: 0.0
Originally posted by Pytrik on ROS Answers with karma: 13 on 2020-03-26
Post score: 1
Answer:
My guess is that AMCL subscribes to (namespace)/map instead of /map. Check rosnode info on your amcl nodes and make sure they subscribe to correct topics.
You can force the amcl nodes to subscribe to the /map topic with:
<remap from="map" to="/map"/>
Originally posted by bob-ROS with karma: 525 on 2020-03-26
This answer was ACCEPTED on the original site
Post score: 1
Original comments
Comment by Pytrik on 2020-03-26:
That seems to be the trick. I had some new errors, namely flickering and jittery control behaviour.
I had to remove my 'odom' frame and my odom frame transform to map, since amcl does the transform from map to n_1/odom, n_2/odom, n_3/odom ... n_n/odom on its own. | {
"domain": "robotics.stackexchange",
"id": 34645,
"tags": "navigation, ros-kinetic, amcl"
} |
custom gazebo plugin | Question:
I've created custom modelplugin for my model in cpp how do i add it correctly in my urdf?
i added it but gazebo is not recognizing it and when i add to my plugin its giving me an error so i removed it i started it with with this its not giving me an error but not gazebo is recognizing this plugin
i added this in my pavkage.xml file
<export>
<gazebo_ros gazebo_model_path="${prefix}/models"/>
<gazebo_ros plugin_path="${prefix}/lib" gazebo_media_path="${prefix}" />
</export>
Originally posted by me_saw on ROS Answers with karma: 31 on 2020-03-20
Post score: 0
Answer:
Hi @me_saw,
A Gazebo plugin is added with this lines in the URDF:
<plugin filename="plugin_name.so" name="some_name" >
plugin args...
</plugin>
However you will need to export the plugins path to advertise Gazebo where to find custom plugins. Take a look at this tutorial, you whould be able to follow it until the end, where you will find how to export and launch the plugin.
Originally posted by Weasfas with karma: 1695 on 2020-03-24
This answer was ACCEPTED on the original site
Post score: 2
Original comments
Comment by me_saw on 2020-03-27:
Hello,
I used the exact format as you have shown but still the gazebo is not loading the plugin
and i followed that tutorial I gave the path but still no use
gazebo is loading my model without any errors and without plugin
Comment by Weasfas on 2020-03-28:
Mmm, Ok. I followed the tutorial exactly as it is in case there was any mistake in the explanation but I managed to generate the pugin and see the box moving on Gazebo. At his point I would recommend you to use the --verbose flag with Gazebo in order to see its log E.g.: Gazebo --verbose my_world.world and ensure you wrote the proper plugin name in the world file (libmodel_push.so), and the plugin has executable permissions (E.g.: sudo chmod +x libmodel_push.so).
Comment by me_saw on 2020-03-28:
I did the tutorial and the plugins that were shown there worked perfectly fine, the box was moving as it has to.The problem arises when i create my own plugin with the exact same method that was shown there but i attached wheels to my robot, it isn't working and I also tried loading the launch file using --verbose but it was clean it's not even showing the plugin part
Comment by Weasfas on 2020-03-29:
Aa, ok. But that is different. In that case the URDF has a set of links and joints. For that to work you need to use the joints not the link. For instance, imagine you have a basic robot with a base_link and two wheel_links the descriptino will be somewhat to:
base_link --> wheel_left_link (joined by left_wheel_joint: continuous)
base_link --> right_wheel_link (joined by right_wheel_joint: continuous)
Then you need to load a plugin that uses that joints setting the velocity to move the model. Take a look at the diff_drive_plugin source code, in line 280 and 281 is doing exactly that to assign wheel velocities.
Comment by me_saw on 2020-03-29:
I used this plugin it's working fine with the sdf but when I try to load it in urdf it isn't showing any plugin loaded I even applied it to joints I am using this plugin formy urdf model
Comment by Weasfas on 2020-03-29:
Ok. I just cloned your repo into my computer and launched Gazebo. When I publish on the two wheel topic 1.00 I can see how the model moves. Maybe a trifle but you are launching Gazebo on pause state: <arg name="paused" value="true" /> Did you remember to click the play button in the bottom right corner of the GUI?
Comment by me_saw on 2020-03-29:
well that is not my repo got that from a tutorial. That model is working fine and it uses sdf model . I want to use that plugin for my own urdf
Comment by Weasfas on 2020-03-29:
Well, if you cannot post the description we will not be able to help you further than this, because if it is not something related to the spurce code of the plugin or your PC/Gazebo environment, It must be something wrong in the robot description.
Comment by me_saw on 2020-03-29:
Thank you so much for your help
I'll try to figure out what the problem is
Comment by me_saw on 2020-03-29:
Hey,
i sorted it out and created a sdf file to load the plugin but when i load sdf file usinggzsever it's giving me an error as Exception occured in the Load function of plugin with name and file name.
Comment by Weasfas on 2020-03-30:
Hi @me_saw,
Glad you sorted the intitial problem. As for the actual problem I say that It would be better to open a new question so the topics are separated and more clear. Yo may provide the link for this new question here.
Comment by me_saw on 2020-04-01:
can you help me with this
Comment by bankai on 2020-06-25:
could uou explain how you added the plugin? Did you still use an urdf file for your model? | {
"domain": "robotics.stackexchange",
"id": 34616,
"tags": "ros, urdf, ros-melodic, plugin, gazebo-ros"
} |
Project Euler #7: 10001st prime | Question: This is my implementation of Project Euler #7. Have I overdone it again? Is there anything else I should or should not do? It runs in 9 milliseconds on my computer.
What is the 10001st prime number?
static int NPrimeGenerator(int nPrime)
{
List<int> primes = new List<int>();
primes.Add(2);
int nPrimeVal = 3;
while (primes.Count != nPrime)
{
int sqrtNPrimeVal = (int) Math.Sqrt(nPrimeVal);
foreach (int i in primes)
{
if (nPrimeVal % i == 0) { break; }
if (i >= sqrtNPrimeVal)
{
primes.Add(nPrimeVal);
break;
}
}
nPrimeVal += 2;
}
return primes[primes.Count - 1];
}
static void Main(string[] args)
{
Stopwatch s = new Stopwatch();
s.Start();
int nPrime = NPrimeGenerator(10001);
s.Stop();
Console.WriteLine(nPrime);
Console.WriteLine(s.ElapsedMilliseconds);
}
Answer:
Have I overdone it again?
I think it's not bad at all. I don't think you overdid anything.
Is there anything else I should or should not do?
Notice that the condition primes.Count != nPrime of the while loop is unnecessary evaluated many times:
when nothing was added to the list,
the re-evaluation is pointless.
You could improve this by changing it to an infinite loop with while (true),
and moving the original condition to the point right after adding a prime to the list. If the target count is reached, break out of both loops.
TOP: while (true)
{
int sqrtNPrimeVal = (int) Math.Sqrt(nPrimeVal);
foreach (int i in primes)
{
if (nPrimeVal % i == 0) { break; }
if (i >= sqrtNPrimeVal)
{
primes.Add(nPrimeVal);
if (primes.Count == nPrime)
{
break TOP;
}
break;
}
}
nPrimeVal += 2;
}
But I think a bigger problem with this code is the poor naming,
especially of variables:
nPrimeVal implies a prime value, possibly the n-th prime. But that's not the case, making it very misleading. possiblePrime would be better.
nPrime implies.... I don't really know what. It's the target count, so I'd name it targetCount
NPrimeGenerator is not a great name. The method returns the n-th prime number, so GetNthPrime would seem more natural
It's good that you skip even numbers when searching for the next time.
What would be even better is to use a sieve,
a popular choice being the Sieve of Eratosthenes.
Lastly,
a little thing,
but note that in the condition i >= sqrtNPrimeVal you can drop the equality (making it i > sqrtNPrimeVal),
as in the case of equality the condition will not be reached,
thanks to the break right before it. | {
"domain": "codereview.stackexchange",
"id": 11600,
"tags": "c#, programming-challenge"
} |
turtlebot_teleop Logitech | Question:
turtlebot_teleop not working with Logitech joystick
Logitech joystick connected
roslaunch turtlebot_teleop logitech.launch
rostopic echo /joy
Does not change when I move the joystick. Any missing step?
Originally posted by pnambiar on ROS Answers with karma: 120 on 2014-06-05
Post score: 0
Original comments
Comment by Ken_in_JAPAN on 2014-06-05:
Hi @pnambiar, I think you need to execute some command like a playstation3 on the web( http://ros.informatik.uni-freiburg.de/roswiki/turtlebot_teleop%282f%29Tutorials%282f%29PS3%2820%29Joystick%2820%29Teleop.html ).
Comment by Ken_in_JAPAN on 2014-06-05:
Is your joystick connected with workstation? I think joystick is used instead of keyboard, because you need kind of like driver to communicate with your turtlebot. I have moved a turtlebot with PS3joystick.
Comment by Ken_in_JAPAN on 2014-06-06:
@pnambiar, Could you tell me more detailed information about your using joystick? I think there is a few information on ROS tutorial too. Does your joystick have either a USB cable or USB wireless? I think it doesn't have a bluetooth.
Comment by Ken_in_JAPAN on 2014-06-09:
@pnambiar, I think you should write your answer. Please inform all of your solution.
Answer:
The Hoystick has a usb cable. The problem is actually solved. I was using it on a windows machine with though a virtual box and I gould not get it to work. But on a linus machine it seems to work work. No additional steps needed.
Originally posted by pnambiar with karma: 120 on 2014-06-09
This answer was ACCEPTED on the original site
Post score: 0 | {
"domain": "robotics.stackexchange",
"id": 18182,
"tags": "ros, joystick, logitech"
} |
Matlab : How to plot the constellation diagram for this method? | Question: I am trying to generate symbols +1,-1 using a function by partitioning the interval of the function into two levels. The function is the Tent Map. This in a way achieves bpsk modulation. I want to see the constellation diagram for bpsk . But I am getting error
Undefined variable "comm" or class "comm.RaisedCosineTransmitFilter".
Error in GenerateData (line 32)
txfilter = comm.RaisedCosineTransmitFilter('Shape','Normal', ...
So, I typed in >>
help comm.RaisedCosineTransmitFilter
and I believe that my Matlab does not have this class because this is the output of the help
comm.RaisedCosineTransmitFilter not found.
How can I view the constellation diagram?
This is the way I generate +1/-1 symbols for bpsk.
%generate bpsk
N = 10000; %number of data points
x(1) = rand(1,1);
for i =2:N
x(i) = 2 * min(x(i-1), 1 - x(i-1)); %Tent map implementation
end
modData = 2*(x>0.5)-1; %generating symbols
% modData holds the modulated symbols
qpsk = comm.QPSKModulator;
Rup = 16;
txfilter = comm.RaisedCosineTransmitFilter('Shape','Normal', ...
'RolloffFactor',0.5, ...
'FilterSpanInSymbols',10, ...
'OutputSamplesPerSymbol',Rup);
constDiagram = comm.ConstellationDiagram('SamplesPerSymbol',Rup, ...
'SymbolsToDisplaySource','Property','SymbolsToDisplay',100);
txSig = txfilter( modData);
constDiagram(txSig)
Could somebody please show the correct way to obtain the constellation diagram. I am using Matlab2011b version on 64 bit i7 processor. Thank you.
Answer: The function you are using is from the Communication Systems Design Toolbox. You might have it not installed/licensed on your PC.
In case you just want to plot a constellation diagram, you can go with this code (Note, that it works for QAM constellations, not BPSK (since BPSK has only one domain)).
values = -7:2:7; % Values in real and complex domain
[X, Y] = meshgrid(values, values);
QAM = X(:) + 1j*Y(:);
plot(QAM, 'x')
Actually, the QAM constellation contains all combinations of possible real and complex values. Hence, you need the cartesian product between real and complex parts. Taking this solution, you can plot the constellation diagram. | {
"domain": "dsp.stackexchange",
"id": 4509,
"tags": "matlab, constellation-diagram"
} |
Does Q# have a bigint type? | Question: Shor's algorithm works with very large integers; larger than 64 bits. So the built-in 64-bit Int type is insufficient for doing the classical processing (e.g. computing the multipliers $b^{2^k} \pmod{N}$). Is there a big int type suitable for those purposes?
Answer: Q# now has a BigInt type included: https://docs.microsoft.com/en-us/quantum/user-guide/language/typesystem/#available-types | {
"domain": "quantumcomputing.stackexchange",
"id": 2239,
"tags": "programming, q#"
} |
PTFE sheet vacuum forming | Question: I need to make PTFE caps on my test tubes. Why PTFE? The test tubes contain industrial solvent mixtures & the rubber caps that came with the test tubes are very, very slowly being dissolved.
I need about a dozen caps. If I were to make it out of solid PTFE, turned on a lathe creating the cap, then it would be expensive. So I'm thinking of having thick cups of PTFE. Then it would be filled by a soft elastomer, creating the cap. Seeing that most PTFE pieces are created by taking PTFE powder & thermoforming it in molds, the production method is expensive even if the cups are lightweight. So I'm thinking "what about vacuum forming?", so I'm here. Can Vacuum forming be used on PTFE?
Answer: Normally no, after all the point of PTFE is that its has not the problems of thermoplastics.
But there exist products like moldflon that enables you to process them in this way. OTOH i would machine them as its cheaper on my time. | {
"domain": "engineering.stackexchange",
"id": 2644,
"tags": "plastic"
} |
Are there any organic compounds with three or more oxygen atoms bonded together in a straight chain? | Question: Recently, there was a question which enquired about some oxygen rich compounds that burn themselves completely and thus not requiring any external atmospheric oxygen. The author came up with the compound $\ce{HC(=O)OOOH}$* which I am not sure if it exists. We already have peracids ($\ce{RC(=O)OOH}$) but I am not sure if there is any acid that has longer oxygen chain than peracid and I am also not sure if it remains acid any longer. Internet does not give me valid result. I know that long oxygen chains are unstable and prone to detonation (as are all oxygen rich compounds) but OP's compound* made me curious.
We have had previous discussions before mainly discussion hydrogen polyoxides, $\ce{HO_nH}$ (which has been detected and produced experimentally), peroxide linkage vs disulfide and bond energy comparison:
Why does sulfur, but not oxygen, catenate?
Are long oxygen molecules possible?
Why is an S-S bond stronger than an O-O bond?
Why are peroxides unstable but disulfide bridges considered stable? Why are esters stable but thiolesters are unstable?
However I am asking if there is any such corresponding organic compound that has been detected spectroscopically and that it exists even for some microseconds?
*the question was later edited to performic acid, thus its existence is already in question.
**When writing the formula, it looks like four oxygen atoms together in straight chain. However, one of the oxygen exist as carbonyl bond, thus compounds with three or more oxygen atoms in straight chain is in question.
Answer: Three oxygen atoms in a row is more common than one might think. In the first stage of the reaction between alkenes and ozone, the ozone is attached to both ends of the double bond to form an intermediate with a five-membered ring (a molozonide). This ring contains the three oxygen atoms still in a row, before it breaks up:
(image source)
In addition, ionic ozonides, $\ce{R^+O_3^-}$, are known with some organic cations $\ce{R^+}$. These are made by metathesis reactions from the ozonides of heavier alkali metals, as described in this answer for $\ce{(CH_3)_4N^+O_3^-}$. | {
"domain": "chemistry.stackexchange",
"id": 16342,
"tags": "organic-chemistry, bond, synthesis, polymers, stability"
} |
[ROS2] Is there a way for a node to subscribe to existing topics? | Question:
It is extremely easy to create a topic, just by publishing a message to a nonexistent topic would cause ROS2 to create that topic for you, as seen in this tutorial
However, is there a way to make an existing node subscribe to an existing topic?
The tutorial above showed a way to create a new node to subscribe to a topic, by simply using the command ros2 topic echo /<TOPIC NAME>. This created a new node, /_ros2cli_25438, which I assume is the command line, subscribing to the topic /barbarians, which is being published to by the existing node /_ros2cli_publisher_std_msgs_String.
However, is there a command to have an existing node subscribe to an existing topic?
Originally posted by wan_da on ROS Answers with karma: 57 on 2019-06-03
Post score: 0
Answer:
However, is there a way to make an existing node subscribe to an existing topic?
A node can subscribe to a topic whether it exists or not. If it doesn't, then after the node subscribes it will effectively exist.
However, is there a command to have an existing node subscribe to an existing topic?
If a node's source is not written so that it subscribes to a topic, then no, you can't make it subscribe to a topic via an external command.
If you want to write a node that can subscribe to a topic on demand, then you can do that with the following steps:
Have the node subscribe to a topic with a message type that is something like the following:
std_msgs/String topic_name
When the node receives a message on the topic, it would subscribe to the specified topic.
Use rostopic pub /blag std_msgs/String 'topic_to_subscribe_to' to tell the node to subscribe to a new topic.
The above makes some assumptions:
The topic will have a type fixed at compile time, or you are using rclpy and have written your callback such that it can handle in some way any message type that arrives.
The node's subscriber callback is reentrant, such that multiple topics receiving messages at once using the same callback is not a problem, or you can guarantee that your node will only ever subscribe to or receive messages on one topic at a time.
Originally posted by Geoff with karma: 4203 on 2019-06-04
This answer was ACCEPTED on the original site
Post score: 1
Original comments
Comment by gvdhoorn on 2019-06-04:
@Geoff: your answer is high-level, so it doesn't really matter, but the OP tagged this with ros2 and you're referring to rospy which is the ROS 1 client library. Should that have been rclpy?
Comment by Geoff on 2019-06-04:
Gah sorry. I need sleep. Yes, it should be rclpy. Although as you say, the answer doesn't change for ROS 1 or ROS 2.
Comment by wan_da on 2019-06-04:
Thank you very much.
Comment by gvdhoorn on 2019-06-04:
As a general comment on this topic btw: @wan_da: you may want to look into remapping. If you're worried about nodes not subscribing to topics that exist -- but perhaps they are subscribing to topics with the same type but a different name -- and still want to connect nodes, you can remap whatever topic they are subscribing to, to something else. I've tried to clarify how this works in ROS 1 in #q303611. That Q&A also links to a ROS 2 article about the subject.
It does have its uses, but using a topic to instruct a node to subscribe to another topic seems like an anti-pattern to me.
Comment by Geoff on 2019-06-04:
I definitely agree it's an anti-pattern and not something I would recommend doing. A node's interface, in terms of the topics, services, actions and parameters it interacts with, needs to be known and well-documented. Creating a node that subscribes to the message type you are interested in and remapping it at launch time is the correct approach. | {
"domain": "robotics.stackexchange",
"id": 33114,
"tags": "ros2"
} |
Do holes have wavefunctions? | Question: Do holes (as in the absence of an electron) have wavefunctions?
In my understanding, when we talk about holes, we are implicitly invoking two multiparticle wavefunctions:
$$\tag{1} \Psi(x_1,...,x_N)= \left|
\begin{matrix}
\psi_1(x_1) & ... & \psi_N(x_1) \\
\vdots & & \vdots \\
\psi_1(x_N) & ... & \psi_N(x_N)
\end{matrix}
\right|$$
and
$$\tag{1} \Phi(x_1,...,x_{N-1})= \left|
\begin{matrix}
\psi_1(x_1) & ... & \psi_{N-1}(x_1) \\
\vdots & & \vdots \\
\psi_1(x_{N-1}) & ... & \psi_{N-1}(x_{N-1})
\end{matrix}
\right|$$
Then we can say that $\Phi$ is $\Psi$ with an additional hole at a single-particle orbital $N$. (I am ignoring the fact that not all multiparticle states can be written as a Slater determinant.)
I think I've heard people talk about "hole wavefunctions." How do we define a hole wavefunction? In fact, can we even define a single particle wavefunction in a multiparticle system? If it exists, does the hole wavefunction need to be antisymmetrized with electron states (i.e., for an exciton, writing a Slater determinant for the hole and the electron)?
As a side note, I could also ask similar questions about positrons.
Answer: You have everything pretty much correct. If you have a piece of semiconductor with $10^{18}$ electrons, a full valence band would be
$$\tag{3} \Psi(x_1,...,x_{10^{18}})= \left|
\begin{matrix}
\psi_1(x_1) & ... & \psi_{10^{18}}(x_1) \\
\vdots & & \vdots \\
\psi_1(x_{10^{18}}) & ... & \psi_{10^{18}}(x_{10^{18}})
\end{matrix}
\right|$$
and then a valence band with five holes in it would be
$$\tag{4} \Phi(x_1,...,x_{10^{18}-5})= \left|
\begin{matrix}
\psi_1(x_1) & ... & \psi_{10^{18}-5}(x_1) \\
\vdots & & \vdots \\
\psi_1(x_{10^{18}-5}) & ... & \psi_{10^{18}-5}(x_{10^{18}-5})
\end{matrix}
\right|$$
Those five holes would have the wavefunctions $\psi_{10^{18}-4}(x)$, $\psi_{10^{18}-3}(x)$, $\psi_{10^{18}-2}(x)$, $\psi_{10^{18}-1}(x)$, $\psi_{10^{18}}(x)$.
So a single-particle wavefunction in a multiparticle system is just one of the entries of the Slater determinant.
Most metals and semiconductors can be described in the "single-particle approximation", i.e. there is at least one way to write the Slater determinant so that to a very good approximation you can treat each entry $\psi_i$ as a separate particle, behaving like you would expect a typical particle to behave, and only weakly interacting with the other particles (described by the other $\psi_j$). That is the situation in which people are usually talking about single-electron or single-hole wavefunctions. | {
"domain": "physics.stackexchange",
"id": 93482,
"tags": "quantum-mechanics, condensed-matter, wavefunction, many-body"
} |
Assigning list index values to String | Question: I am just trying to convert each list of values to String by index one by one. My Code is running fine. But I am thinking that I can write better code than this. I Need your good coding possibilities here to convert from list to String.
I am using the code below to convert:
CarComment[] list = form.getCarDataJaxb().getCarCommentList();
JSONObject obj = new JSONObject();
JSONArray comments = new JSONArray();
for (int i=0;i<list.length;i++){
if (notEmpty(list[i].getText())){
JSONArray commObj = new JSONArray();
String str = list[i].getText();
str = str.replaceAll("<", "<");
commObj.put(str);
comments.put(commObj);
}
}
obj.put("carcomm", comments);
response.setContentType("text/json");
response.getWriter().write(obj.toString());
I am trying to write good coding technique while converting from list to String at line
String str = list[i].getText();
Answer: There actually isn't so much to improve here (at least not that I can think of).
Instead of using an index to iterate by, you can use a Java for-each loop. Since you only used the iterator variable to read the index of the list, it is usually more readable to use a for-each loop.
You were not indenting your code correctly (before the edit of your question), which I also fixed below.
And, below I use the opposite way of checking if the text is empty, by using continue if the if-statement is not true, you can avoid having to indent the code an extra step.
CarComment[] list = form.getCarDataJaxb().getCarCommentList();
JSONObject obj = new JSONObject();
JSONArray comments = new JSONArray();
for (CarComment carComment : list) {
if (!notEmpty(carComment.getText()))
continue;
JSONArray commObj = new JSONArray();
commObj.put(carComment.getText().replaceAll("<", "<"));
comments.put(commObj);
}
obj.put("carcomm", comments);
response.setContentType("text/json");
response.getWriter().write(obj.toString());
Preferably, to avoid double-negation, you should use if (isEmpty(...)) instead of if (!notEmpty(...))
However, there's no way of having to do a method call to getText (or a similar method call) on your line.
String str = list[i].getText();
What I did was to skip the declaration of a local variable and process the string (by calling replaceAll) directly when adding it to it's destination. | {
"domain": "codereview.stackexchange",
"id": 5087,
"tags": "java, strings, collections"
} |
Formally proving no algorithm exists | Question: Are there standard techniques to show that no algorithms exist for given complexity constraints?
For example, consider the following problem. The input is a list of items with exactly one duplicate, and you wish to find the duplicate item.
How do you formally prove that there cannot be an algorithm that does this in constant space and linear time?
Answer: See this lower bound for sorting, for example:
http://planetmath.org/lowerboundforsorting
You typically need to assume something about the algorithm's access to the input data. In this case, the assumption is that the algorithm sorts via pairwise comparisons. Any such algorithm must make at least $\Omega(n\log n)$ such comparisons. This is because the pairwise comparisons effectively induce a binary tree on $n!$ leaves -- one leaf for each possible input ordering. Such a tree must have depth $\Theta(\log(n!))=\Theta(n\log n)$.
Note that in a different data access model, algorithms can achieve linear-time sorting:
https://en.wikipedia.org/wiki/Radix_sort
Obiously, faster than linear time is impossible, since you have to at least read all of the inputs. | {
"domain": "cstheory.stackexchange",
"id": 3961,
"tags": "proofs, complexity"
} |
Rails 5 controller to get information about Steam users | Question: I've done a bit of modifications and finally got it working, and did a lot of reading about @ vs @@ vs just declaring and I came up with.
It goes to Steam's API to return information (JSON Format) based on the endpoint. A list of games they own, a list of games they recently played, profile information, etc.
class SteamController < ApplicationController
def initialize
@steamKey = ENV["steam_api_key"]
@ISteamUrl = "http://api.steampowered.com/ISteamUser/"
@IPlayerUrl = "http://api.steampowered.com/IPlayerService/"
end
def get_steam_summary_per_user #/steam/:id
@steamEndpoint = "GetPlayerSummaries/v0002/?key="+@steamKey+"&steamids="
@steamId = User.find(params[:id]).steamId
@playerUrl = @ISteamUrl + @steamEndpoint + @steamId.to_s
@games = HTTParty.get(@playerUrl).to_json
render json: @games
end
def get_steam_recently_played_per_user #/game/:id
@recPlayedEndpoint = "GetRecentlyPlayedGames/v0001/?key="+@steamKey+"&steamid="
@steamId = User.find(params[:id]).steamId
@playerUrl = @IPlayerUrl + @recPlayedEndpoint + @steamId.to_s
@games = HTTParty.get(@playerUrl).to_json
render json: @games
end
def get_steam_owned_games_per_user #/allGames/:id
@allGamesUrl = "GetOwnedGames/v0001/?key="+@steamKey+"&steamid="
@steamId = User.find(params[:id]).steamId
@playerUrl = @IPlayerUrl + @allGamesUrl + @steamId.to_s
@games = HTTParty.get(@playerUrl).to_json
render json: @games
end
end
Routes
get '/steam/:id', to: 'steam#get_steam_summary_per_user'
get '/games/:id', to: 'steam#get_steam_recently_played_per_user'
get '/allgames/:id', to: 'steam#get_steam_owned_games_per_user'
I originally just has @baseUrl but realized they have multiple services and versions, but even before that I couldn't figure out why doing
@baseUrl = "http://api.steampowered.com/"+@recPlayedEndpoint+"etcetc
wouldn't work - I assumed it was related to initializing the `@recPlayedEndpoint and then re-assigning it later.
Ths code feels very redundant to me and I still have 5-6 more functions to build out.
The routes make sense, and I'm not sure if I can do them better. Please also tell me if my syntax is not proper for Rails - While I have an Angular front-end I'm trying to understand when to use camel case vs snake, vs pascal etc etc.
(All of this outputs to pure JSON and I use my Angular side render it, so if there is an easier way to do this. However, this is NOT set up on an api version of Rails)
Answer: You don't need all those @s. Everything in the action methods can be handled with local variables, and the initlization can be made more Rails-like. For instance:
class SteamController < ApplicationController
BASE_URL = "http://api.steampowered.com".freeze
before_action :load_user
def get_steam_summary_per_user #/steam/:id
endpoint = url_for_path_and_id("/ISteamUser/GetPlayerSummaries/v0002/", @user.steamId)
render json: HTTParty.get(endpoint).to_json
end
def get_steam_recently_played_per_user #/game/:id
endpoint = url_for_path_and_id("/IPlayerService/GetRecentlyPlayedGames/v0001/", @user.steamId)
render json: HTTParty.get(endpoint).to_json
end
def get_steam_owned_games_per_user #/allGames/:id
endpoint = url_for_path_and_id("/IPlayerService/GetOwnedGames/v0001/", @user.steamId)
render json: HTTParty.get(endpoint).to_json
end
private
def url_for_path_and_id(path, id)
"#{BASE_URL}#{path}?key=#{ENV["steam_api_key"]}&steamid=#{id}"
end
def load_user
@user = User.find(params[:id])
end
end
Here I'm using Rails's before_action setup to load the user, since that's common for all actions. The constants have been moved to, well, constants, or their values to where they're used. A method has been added to construct the URLs. I'm using the more Ruby-like approach of string interpolation to build the URLs rather than string concatenation.
Yes, I've hard-coded a few strings into the methods, although they do have some parts in common, but I've based it on the sections of a URL: Base (constant), path (varies from method to method, even if parts of it repeat), and query string (appended at the end).
One thing that stands out is that the User model has a steamId attribute: That should be steam_id - in Ruby you should use snake_case for attribute and method names.
However, a different (and, I think, better) approach would be to make a service object to wrap the Steam API. Basically a plain old Ruby class (you can place it in app/services, for instance).
Your controller actions would simply construct a service object, passing in the user, and then call the relevant method to get what they want. E.g. your controller would be just:
class SteamController < ApplicationController
before_action :create_client
def get_steam_summary_per_user
render json: @steam_client.summary
end
def get_steam_recently_played_per_user
render json: @steam_client.recently_played
end
def get_steam_owned_games_per_user
render json: @steam_client.owned
end
private
def create_client
user = User.find(params[:id])
@steam_client = SteamAPIClient.new(user)
end
end
where SteamAPIClient is your service object. Keep the controller skinny, and put the logic elsewhere.
Another thing that stood out is the way you set up your routes. The Rails Way™ would be to make the API part of the User controller. From your application's standpoint, you're trying to get information about a user - the fact that it comes from Steam's API is an implementation detail.
In other words, I'd rather see URLs like:
/users/:id/summary
/users/:id/owned
/users/:id/recent
than URLs like /steam/:id, or /games/:id. If you follow common RESTful API patterns, those URLs indicate that you have a collection of "steams" and a collection of "games", and the :id is used to pick out a particular one. But that's not your model; you don't have multiple "steams". What you have a users, identified by an id, which in turn have some associated data you can fetch.
Or in route-speak:
resources :users do
member :summary, via: :get
member :owned, via: :get
member :recent, via: :get
end
Doing things this way is another reason to extract the actual Steam API-fethcing code into a service object, so you can just call it from the Users controller.
The give-away in your current code is that all your actions are called ..._per_user. Well, if it's per user, then make it per user by making it member actions on the Users controller.
Basic idea is that you treat the Steam API as you would treat the database: It's a data source. You don't put all the database connection and querying logic in a controller, you just put User.find(x), and the rest happens elsewhere. Same here, in a sense. | {
"domain": "codereview.stackexchange",
"id": 24639,
"tags": "ruby, ruby-on-rails, json, controller"
} |
How to find the tension | Question: A massless rod of length L attached to mass m and with axle to cart of mass M. The cart has a shape of equilateral triangle (edge L). the cart is at rest and its center of mass is above x=0 and a rod is perpendicular to the ground. the cart is free to move without friction. at time t=0 the mass m is released and starts to fall to the left. at time t=τ the rod is parallel to the ground.
Why the tension from the stick at time $t=\tau$ is $T=mv^2/L=2mg$ and not $T=mv^2/L=mg$?
Answer: Ok, the tension will be equal to centrifugal force $T=mv^2/L$. Try to calculate velocity from energy conservation law $mgL=mv^2/2$ and then see what happens. | {
"domain": "physics.stackexchange",
"id": 12192,
"tags": "homework-and-exercises, newtonian-mechanics"
} |
Why doesn't CAS9 cleave the original CRISPR sequence in the bacterial genome? | Question: CAS9 is the RNA-guided endonuclease that cleaves DNA as specified by the RNA sequence and is used to target viruses that infect bacteria. So why doesn't this RNA+endonuclease combo also cleave the original CRISPR spacer sequences (which also have the same DNA?). Is it the same reason that the bacterial genome is methylated (and hence protects from restriction enzymes)? Does methylation also make a difference to CAS9 as it does to restriction enzymes?
This actually was a doubt asked to Eric Lander in this lecture.
Answer: It is not the methylation status. The crRNA is not only complementary to the spacer sequence within the CRISPR array but also to the repeat sequence flanking that spacer. The additional base pairing of the sgRNA with the repeat prevents a nucleolytic cleavage by Cas9. In addition, the arrays typically do not contain PAM sequences.
Here you will find a nice illustration: | {
"domain": "biology.stackexchange",
"id": 6669,
"tags": "molecular-biology, crispr"
} |
Speed of satellite when it falls freely on the surface of the earth | Question: I am a high school student in my final two years before university. I have a question which I do not know how to approach. Any help would be appreciated. Thanks!
"If an artificial satellite is moving in a circular orbit around the earth with a speed equal to half the magnitude of escape velocity from the earth,If the satellite is stopped suddenly in its orbit and allowed to fall freely on to the earth,find the speed with which it hits the surface of earth."
Answer: There are three pieces to this puzzle. First you need to derive an equation for the escape velocity of an object launched from the surface of the earth. Then you need to find the orbital radius of an object orbiting at half the escape velocity. Then you need to determine how long it takes (neglecting air resistance) for the object to fall from that orbital radius to the surface of the earth. Do you know how to do any of these things? | {
"domain": "physics.stackexchange",
"id": 28563,
"tags": "homework-and-exercises, newtonian-mechanics, newtonian-gravity, orbital-motion, satellites"
} |
Is the moon's revolution speed increasing or decreasing | Question: I've come across multiple answers to this question. So, the moon is moving away from the Earth a couple of centimeters per year and the Earth's rotation is slowing down. Here it says the moon's revolution is speeding up, another place it says it is slowing down. So, due to tidal effects, is the moon's revolution slowing down or speeding up?
Answer: The moon's rotation is very slowly decreasing. The page you link to is correct but confusing, and you need to understand one of the weird things about orbits to understand it:
If you speed up in an orbit you go slower
Here is how this apparent paradox works. If you are orbiting the Earth and you fire your rockets to speed up, you will lift yourself to a higher orbit, where you will be moving slower.
The tidal bulge is a large mass and this large mass is in front of the moon. Any large mass has a gravitational effect and there is a gravitational force on the moon by the bulge, and an equal and opposite force on the bulge by the moon. The bulge is in front of the moon, so the gravitational action of the bulge pulls the moon forward.
So the tidal bulge acts to pull the moon forward in its orbit, which makes it slow down, and since the moon is tidally locked it also slows its rotation speed. However the moon is already spinning quite slowly, only one complete rotation per month, so the amount of slow down is very small.
The article writes
The slowing of the speed of rotation of Earth also results in the increase in speed of revolution of moon around the Earth. [...] The increase in speed of revolution of moon around the Earth also results in the increase in radius of orbit of moon.
You should understand that when it says "increase in speed of the moon" it means that the moon is actually slowing down due to the increase in radius. | {
"domain": "astronomy.stackexchange",
"id": 2914,
"tags": "the-moon, tidal-locking"
} |
SLAM from partly occluded LiDAR sensor | Question: I am building my first project which will use 2D LIDAR for SLAM and the robotic platform is a small car. However the LIDAR is hidden inside and it's occluded by 4 cylinders which connect the roof with the floor of the platform. Is it possible to reliably map the environment and the position of the robot when the lidar is occluded like that? I would be very thankful for recommending some of the simplest possible algorithms to handle this problem.
For clarity, I sketched what the robot looks like from 2 sides:
The environment of the robot is not known a priori. The robot only knows the direction and distance to the waypoint and its goal is to navigate to it and plan its motion as it is progressing and discovering new obstacles.
Answer: This is definitely possible and rather normal. You should set the respective measurements to zero or NaN and most algorithms should be able to handle these cases. Laserscans almost always have incomplete data (e.g. due to maximal distance or a object with very high or low reflectivity) | {
"domain": "robotics.stackexchange",
"id": 1894,
"tags": "slam, lidar"
} |
I/O function takes far too long | Question: //parses the text path vector into the engine
void Level::PopulatePathVectors(string pathTable)
{
// Read the file line by line.
ifstream myFile(pathTable);
for (unsigned int i = 0; i < nodes.size(); i++)
{
pathLookupVectors.push_back(vector<vector<int>>());
for (unsigned int j = 0; j < nodes.size(); j++)
{
string line;
if (getline(myFile, line)) //enter if a line is read successfully
{
stringstream ss(line);
istream_iterator<int> begin(ss), end;
pathLookupVectors[i].push_back(vector<int>(begin, end));
}
}
}
myFile.close();
}
This function is taking about 5 minutes to pass in a text file which is 744 * 744 lines long. Each line is a list of integers like this:
1 4 6 24 7 4 8 n
they can be of varying length. I have no idea why it's taking so long, but it needs to run in a matter of seconds, not minutes! The odd thing is that the same function in C# (in fact a very unoptimised version) does in fact only take seconds to run.
Could the problem be a setting?
This is a link to the path table it is parsing http://dl.dropbox.com/u/13519335/WepTestLevelPathTable.txt
Answer: I setup nodes.size() to return 744.
This then forces all 553536 to be read from the file.
When I run your code it completes in 3.8 seconds (with -O3 it takes 2.5 seconds).
If I update the code to reserve the appropriate amount of space in each vector we can reduce the time it takes to: 3.3 seconds (with -O3 2.2 seconds).
So for the 5 minute figure you are quoting there must be some other error in your code.
Comments on your code:
Pass no-mutable parameters by cost reference (to avoid the copy).
void Level::PopulatePathVectors(string pathTable)
Add lines to reserve the appropriate space in each vector. This will prevent multiple re-allocations of the vector while you read. This is important when you have a triply nested vector.
pathLookupVectors.push_back(vector<vector<int> >());
pathLookupVectors.reserve(nodes.size()); // Add this line
for (unsigned int i = 0; i < nodes.size(); i++)
{
pathLookupVectors.push_back(vector<vector<int>>());
pathLookupVectors.back().reserve(nodes.size()) // Add this line
No Need to manually close the file.
see https://stackoverflow.com/q/748014/14065
Implementation using fstream failed evaluation
myFile.close(); | {
"domain": "codereview.stackexchange",
"id": 831,
"tags": "c++, c++11"
} |
Calculating smoothed derivative of a signal by using difference with larger step=convolving with rectangular window | Question: I have a signal sampled at $\Delta t: fi(ti=i\Delta t)$ where i = 0..n-1. I want to find the first derivative of the signal: f'(t).
My first thought was to estimate this by a central difference:
$f'(t_i) =\frac{f(t_{i+1})−f(t_{i−1})}{2\Delta t}$
However the signal may have a lot of high frequency noise that may cause quick fluctuations in f'.
I guess the proper thing might be to smooth the signal by convolving with a window function e.g., Hann and then find the derivative from the differences.
A colleague suggested a faster way of finding a smoothed estimate of the derivative:
use a central difference over 2n samples, where n >> 1:
$f'(t_i) =\frac{f(t_{i+n})−f(t_{i−n})}{2n\Delta t}$
This would of course be computationally faster than first convolving with a window function but is it a good solution?
If we form the sum:
$S=2\Delta t[f'(t_{i-n+1})+f'(t_{i-n+2})+..+f'(t_{i+n-1})]$
and expand each derivative by the central difference with step $\Delta t$:
$S=f(t_{i-n+2})-f(t_{i-n})+f(t_{i-n+3})-f(t_{i-n+2})+..+f(t_{i+n})-f(t_{i+n-2})$
all terms except two cancels out:
$S=f(t_{i+n})-f(t_{i-n})=2n\Delta tf'(t_i)$
Therefore:
$f'(t_i)=\frac{1}{n}[f'(t_{i-n+1})+f'(t_{i-n+2})+..+f'(t_{i+n-1})]$
So taking the central difference over 2n samples is equivalent with first convolving by a rectangular window of size 2n - 2 and then taking a central difference over +/- 1 sample.
How "bad" is it to smooth with a rectangular window?
If we take the FFT this will cause "ringing", but we do not need to take the FFT.
Thanks in advance for any answers!
Answer: This is a hard question to handle generally. Smoothing with a rectangular window is used all the time (often called a "moving average"), so that's not necessarily a problem. I'm not sure what ringing you're referring to, perhaps the sidelobes of the rectangular window's frequency response.
Differentiation is inherently a highpass operation; the ideal continuous-time differentiator has a transfer function of:
$$
H(s) = s
$$
So that its magnitude response is:
$$
|H(j\omega)| = \omega
$$
The gain of a differentiator therefore increases monotonically with frequency. If your signal contains high-frequency noise, then it could be amplified by applying a differentiator. To combat this, two approaches are apparent:
Design a more sophisticated differentiator filter that has the desired linear magnitude response over the portion of the band that covers your signal of interest, then sharply attenuates higher frequencies. You could design such a filter using least-squares methods or the frequency-sampling method, for example.
Use a cascaded approach where you first suppress all of the high-frequency noise that you can using a lowpass filter, then follow with the differentiator. The frequency coverage of the differentiator need not be as tight since the lowpass filter will eliminate the out-of-band noise.
The methods should be roughly equivalent if you're using linear filters; you could think of the first single-filter approach as just a cascade of a differentiator and a lowpass filter. As you noted, the central-difference approach can be modeled in this way. It's hard for anyone to say that it's "bad" without any knowledge of your application. My main thought would be that it is "bad" if the smoothing operation tangibly attenuates your signal of interest, such that the derivative estimate is no longer useful. However, if the parameters of the signal are such that you can smooth the noise without noticeably distorting the signal (i.e. if the signal is well-oversampled), then it could be a win. | {
"domain": "dsp.stackexchange",
"id": 109,
"tags": "fourier-transform, smoothing"
} |
Questions regarding the 'adjoint of $SO(N)$' section in Zee's group theory | Question: I am reading A. Zee's book about group theory and I am confused about several parts of his discussion in chapter 4.1 about the adjoint of $SO(n)$.
First question:
The first thing mentioned is that an antisymmetric tensor $T^{ij}$ in $SO(N)$ furnished (still don't fully understand how that word is used in this book) a $\frac{1}{2}N(N-1)$-dimensional representation. He also says there are $\frac{1}{2}N(N-1)$ generators of $SO(N)$ which are the $N$-dimensional matrices
$$\mathcal{J}_{(m n)}^{i j}=\left(\delta^{m i} \delta^{n j}-\delta^{m j} \delta^{n i}\right)$$
He then renames the $(mn)$ index $ 1 \leq a \leq \frac{1}{2}N(N-1)$. But from this part he immediately states:
Then we have $\frac{1}{2}N(N-1)$ matrices $\mathcal{J}_{a}^{i j}$, each of which is a $\frac{1}{2}N(N-1)$-by-$\frac{1}{2}N(N-1)$ dimensional matrix.
How does this happen? $\mathcal{J}_{(m n)}^{i j}$ was $N$-dimensional, but $\mathcal{J}_{a}^{i j}$ is $\frac{1}{2}N(N-1)$-dimensional just from reindexing?
Second question
This follows immediately from the first question.
Zee then states
We can also regard the antisymmetric tensor $T^{ij}$ as an $N$-by-$N$ matrix, and hence write it as a linear combination of the $\mathcal{J}_a$'s, with coefficients denoted by $A_a$: $$T^{ij} = A_a \mathcal{J}^{ij}_a$$
(where summation over $a$'s is implied and $i=1,2,...,N$ and $a=1,2,...,\frac{1}{2}N(N-1)$
This is just another question of dimensionality. How can we switch between $T^{ij}$ being $\frac{1}{2}N(N-1)$-dimensional to $N$-dimensional?
Answer: I don't have that text, but your question is standard stuff. I suspect what you are missing is the fast interplay of D-dimensional vectors and the D×D matrices acting on them, sometimes regarded as vector elements themselves, of a larger vector!
The dimension D of the representation is the dimensionality of the "vectors" on which the D×D representation matrices act. But all kinds of objects "furnish" D-dimensional vectors on which the suitable representation matrices act to transform them. "Furnish" means provide components of a large D-dimensional vector specifying a possibly new representation.
Antisymmetric tensors $T^{ij}$ in $SO(N)$ with indices $j=1,...,N$ comprise a set of $\frac{1}{2}N(N-1)$ independent antisymmetric matrices, so they furnish vectors of an irreducible D-dimensional representation, with $D=\frac{1}{2}N(N-1)$: they define the relevant vector space. Each such matrix is a component of the D-vector.
It is also true that there are $\frac{1}{2}N(N-1)$ generators of $SO(N)$, indexed by the (mn) pairs,
$$\mathcal{J}_{(m n)}^{i j}=\left(\delta^{m i} \delta^{n j}-\delta^{m j} \delta^{n i}\right)$$
which act on the space of N-dimensional js to rotate them to such is.
However, these N×N antisymmetric matrices may also be regarded as the $D=\frac{1}{2}N(N-1)$ components of a new vector, acted upon by some larger $\frac{1}{2}N(N-1) \times \frac{1}{2}N(N-1)$ matrices, (actually $\frac{1}{2}N(N-1)$ independent such, indexed by (mn). This is the adjoint representation.)
So the D=N generators became the $D=\frac{1}{2}N(N-1)$-vector elements of the adjoint (which they furnished). Fortuitously, these two dimensions are the same for N=3, so the fundamental of SO(3) happens to also be its adjoint!
Now
We can also regard the antisymmetric tensor $T^{ij}$ as an $N$-by-$N$ matrix, and hence write it as a linear combination of the $\mathcal{J}_a$'s, with coefficients denoted by $A_a$: $$T^{ij} = A_a \mathcal{J}^{ij}_a.$$
This object is an N×N antisymmetric matrix, but also an $\frac{1}{2}N(N-1)$-dimensional vector in the adjoint representation vector space, introduced above, itching to be rotated by the suitable
$\frac{1}{2}N(N-1)\times\frac{1}{2}N(N-1)$ adjoint representation matrices. (These matrices are gotten/furnished by the structure constants of the Lie algebra you'd get from your $\cal J$s in the D=N irrep., but don't worry about them.)
The dimension of the adjoint representation is also the dimension of the corresponding Lie algebra (regarded as a vector space as you saw). | {
"domain": "physics.stackexchange",
"id": 89183,
"tags": "quantum-mechanics, group-theory"
} |
Configuration Manager | Question: The idea here is to implement a configuration system using INI files for a pathfinding library nammed Kraken. This library is in java and I am helping implementing it in C++. The goal is to make it cross platform and to specificaly aim embedded systems. For now the INI parser uses inih for simplicity, but should be able to run without file system in the end (with an INI parser that can parse an INI formated string without loading it from a file). We also want to avoid using streams in the release build.
The parameters are stored in modules. Each module can have its parameters changed at runtime to adapt the pathfinding to the situation. This is done by changing the INI section for the desired module. For each module, the user can register function pointers that are called when its section changes.
The parameters have hard coded default values and the INI file should have a defaut section containing all parameter values. The code should follow ROS style guidelines.
A few inelegant things bother me:
The enum to string conversion
Finding the module related with a specific ConfigKey
The use of the ConfigurationParameter struct and the hardcoded default values (a lot of code is here only for this part to work)
Thank you for your time and your advices on this, I really appreciate it.
ConfigurationHandler.h
#ifndef CONFIGURATION_HANDLER_H
#define CONFIGURATION_HANDLER_H
#include <string>
#include <functional>
#include <optional>
#include "configuration_module.h"
#include "iniReader/INIReader.h"
/*
* The order of this enum is important as it gives an easy way
* to get the relation between a parameter and its module using
* the first key of each group.
* If you have to modify this enum, keep the groups in the same
* order and let the first key of each group at the first place.
*/
namespace ConfigKeys
{
enum class ConfigKeys
{
//Navmesh parameters
NavmeshObstaclesDilatation = 0,
LargestTriangleAreaInNavmesh,
LongestEdgeInNavmesh,
NavmeshFilename,
//Auto replanning
NecessaryMargin,
PreferedMargin,
MarginBeforeCollision,
InitialMargin,
//Research and mechanical parameters
MaxCurvatureDerivative,
MaxLateralAcceleration,
MaxLinearAcceleration,
DefaultMaxSpeed,
MinimalSpeed,
MaxCurvature,
StopDuration,
SearchTimeout,
ThreadNumber,
EnableDebug,
FastAndDirty,
CheckNewObstacles,
AllowBackwardMotion,
//Memory management parameters
NodeMemoryPoolSize,
ObstaclesMemoryPoolSize,
//Tentacle parameters
PrecisionTrace,
NbPoints
};
}
using ConfigKey = ConfigKeys::ConfigKeys ;
namespace ConfigModules
{
enum class ConfigModules
{
Navmesh = 0, //Require to regenerate the navmesh
Autoreplanning, //Can be modified on-the-fly
ResearchMechanical, //Can be modified on-the-fly
Memory, //Require to recreate the pools
Tentacle,
Unknown
};
}
using ConfigModule = ConfigModules::ConfigModules ;
class ConfigurationHandler
{
private:
//Structure holding all possible types of parameter value.
//It should be an union, but it will require a bit more work because of the std::string
struct ConfigurationParameter
{
double numeric_value;
bool boolean_value;
std::string string_value;
ConfigurationParameter() = default;
ConfigurationParameter(double value) { numeric_value = value; }
ConfigurationParameter(int value) { numeric_value = value; }
ConfigurationParameter(bool value) { boolean_value = value; }
ConfigurationParameter(std::string value) { string_value = value; }
};
public:
ConfigurationHandler(const std::string& filename);
void registerCallback(ConfigModule module_enum, ConfigurationCallback callback);
void changeModuleSection(ConfigModule module_enum, std::string new_section);
void changeModuleSection(std::vector<ConfigModule>&& modules, std::string new_section);
long getInt(ConfigKey key, ConfigModule module = ConfigModule::Unknown);
double getDouble(ConfigKey key, ConfigModule module = ConfigModule::Unknown);
bool getBool(ConfigKey key, ConfigModule module = ConfigModule::Unknown);
std::string getString(ConfigKey key, ConfigModule module = ConfigModule::Unknown);
private:
ConfigModule getModuleEnumFromKeyEnum(ConfigKey key) const noexcept;
std::string findSectionName(ConfigKey key, ConfigModule module_key);
void setDefaultValues();
inline std::string getKeyName(ConfigKey key);
std::optional<ConfigurationModule> getModule(ConfigModule module);
//Helper function for default values initialization
template<typename T>
void doAddDefaultValue(ConfigKey key, T value)
{
default_values_[(int)key] = ConfigurationParameter{value};
}
INIReader ini_reader_;
std::vector<ConfigurationModule> modules_;
std::vector<ConfigurationParameter> default_values_;
static constexpr int configuration_key_count = (int)ConfigKey::NbPoints + 1;
static constexpr int module_count = (int)ConfigModule::Tentacle + 1;
//The array that keeps the string values of the ConfigKeys
const std::string configuration_key_string_values[configuration_key_count] = {
"NavmeshObstaclesDilatation", "LargestTriangleAreaInNavmesh", "LongestEdgeInNavmesh", "NavmeshFilename",
"NecessaryMargin", "PreferedMargin", "MarginBeforeCollision", "InitialMargin", "MaxCurvatureDerivative",
"MaxLateralAcceleration", "MaxLinearAcceleration", "DefaultMaxSpeed", "MinimalSpeed", "MaxCurvature",
"StopDuration", "SearchTimeout", "ThreadNumber", "EnableDebug", "FastAndDirty", "CheckNewObstacles",
"AllowBackwardMotion", "NodeMemoryPoolSize", "ObstaclesMemoryPoolSize", "PrecisionTrace", "NbPoints"
};
};
#endif //CONFIGURATION_HANDLER_H
ConfigurationHandler.cpp
#include "configuration_handler.h"
ConfigurationHandler::ConfigurationHandler(const std::string& filename) :
ini_reader_{filename},
modules_(module_count),
default_values_(configuration_key_count)
{
setDefaultValues();
}
long ConfigurationHandler::getInt(ConfigKey key, ConfigModule module)
{
auto defaultValue = static_cast<int>(default_values_[static_cast<int>(key)].numeric_value);
auto sectionName = findSectionName(key, module);
return ini_reader_.GetInteger(sectionName, getKeyName(key), defaultValue);
}
double ConfigurationHandler::getDouble(ConfigKey key, ConfigModule module)
{
auto defaultValue = default_values_[static_cast<int>(key)].numeric_value;
auto sectionName = findSectionName(key, module);
return ini_reader_.GetReal(sectionName, getKeyName(key), defaultValue);
}
bool ConfigurationHandler::getBool(ConfigKey key, ConfigModule module)
{
auto defaultValue = default_values_[static_cast<int>(key)].boolean_value;
auto sectionName = findSectionName(key, module);
return ini_reader_.GetBoolean(sectionName, getKeyName(key), defaultValue);
}
std::string ConfigurationHandler::getString(ConfigKey key, ConfigModule module)
{
auto defaultValue = default_values_[static_cast<int>(key)].string_value;
auto sectionName = findSectionName(key, module);
return ini_reader_.Get(sectionName, getKeyName(key), defaultValue);
}
void ConfigurationHandler::registerCallback(ConfigModule module_enum, ConfigurationCallback callback)
{
auto module = getModule(module_enum);
if(module)
{
module->registerCallback(callback);
}
}
void ConfigurationHandler::changeModuleSection(ConfigModule module_enum, std::string new_section)
{
auto module = getModule(module_enum);
if(module)
{
module->changeSection(*this, new_section);
}
}
void ConfigurationHandler::changeModuleSection(std::vector<ConfigModule>&& modules, std::string new_section)
{
for(auto module : modules)
{
changeModuleSection(module, new_section);
}
}
std::string ConfigurationHandler::findSectionName(ConfigKey key, ConfigModule module_key)
{
if(module_key == ConfigModule::Unknown)
{
module_key = getModuleEnumFromKeyEnum(key);
}
return modules_[static_cast<int>(module_key)].getCurrentSection();
}
std::string ConfigurationHandler::getKeyName(ConfigKey key)
{
return configuration_key_string_values[static_cast<int>(key)];
}
ConfigModule ConfigurationHandler::getModuleEnumFromKeyEnum(ConfigKey key) const noexcept
{
//I'm not proud of this function, but I could'nt find a better solution yet.
if(key < ConfigKey::NecessaryMargin)
{
return ConfigModule::Navmesh;
}
else if(key < ConfigKey::MaxCurvatureDerivative)
{
return ConfigModule::Autoreplanning;
}
else if(key < ConfigKey::NodeMemoryPoolSize)
{
return ConfigModule::ResearchMechanical;
}
else if(key < ConfigKey::PrecisionTrace)
{
return ConfigModule::Memory;
}
else
{
return ConfigModule::Tentacle;
}
}
std::optional<ConfigurationModule> ConfigurationHandler::getModule(ConfigModule module)
{
auto moduleId = static_cast<int>(module);
if(moduleId < module_count)
{
return modules_[moduleId];
}
else
{
return std::nullopt;
}
}
void ConfigurationHandler::setDefaultValues()
{
doAddDefaultValue<int>(ConfigKey::NavmeshObstaclesDilatation, 100);
doAddDefaultValue<int>(ConfigKey::LargestTriangleAreaInNavmesh, 20000);
doAddDefaultValue<int>(ConfigKey::LongestEdgeInNavmesh, 200);
doAddDefaultValue<std::string>(ConfigKey::NavmeshFilename, "navmesh.krk");
doAddDefaultValue<int>(ConfigKey::NecessaryMargin, 40);
doAddDefaultValue<int>(ConfigKey::PreferedMargin, 60);
doAddDefaultValue<int>(ConfigKey::MarginBeforeCollision, 100);
doAddDefaultValue<int>(ConfigKey::InitialMargin, 100);
doAddDefaultValue<int>(ConfigKey::MaxCurvatureDerivative, 5);
doAddDefaultValue<int>(ConfigKey::MaxLateralAcceleration, 3);
doAddDefaultValue<int>(ConfigKey::MaxLinearAcceleration, 2);
doAddDefaultValue<int>(ConfigKey::DefaultMaxSpeed, 1);
doAddDefaultValue<int>(ConfigKey::MinimalSpeed, 0);
doAddDefaultValue<int>(ConfigKey::MaxCurvature, 5);
doAddDefaultValue<int>(ConfigKey::StopDuration, 800);
doAddDefaultValue<int>(ConfigKey::SearchTimeout, 10000);
doAddDefaultValue<int>(ConfigKey::ThreadNumber, 1);
doAddDefaultValue<bool>(ConfigKey::EnableDebug, true);
doAddDefaultValue<bool>(ConfigKey::FastAndDirty, false);
doAddDefaultValue<bool>(ConfigKey::CheckNewObstacles, false);
doAddDefaultValue<int>(ConfigKey::NodeMemoryPoolSize, 20000);
doAddDefaultValue<int>(ConfigKey::ObstaclesMemoryPoolSize, 50000);
doAddDefaultValue<bool>(ConfigKey::AllowBackwardMotion, true);
doAddDefaultValue<int>(ConfigKey::NbPoints, 5);
doAddDefaultValue<float>(ConfigKey::PrecisionTrace, 0.02f);
}
ConfigurationModule.h
#ifndef CONFIGURATION_MODULE_H
#define CONFIGURATION_MODULE_H
#include <string>
#include "configuration_callback_holder.h"
class ConfigurationHandler;
class ConfigurationModule
{
public:
void registerCallback(ConfigurationCallback callback);
void changeSection(ConfigurationHandler& configuration_handler, std::string new_section);
std::string getCurrentSection();
private:
ConfigurationCallbackHolder callbacks_holder_;
std::string current_section_ = {"default"};
};
#endif //CONFIGURATION_MODULE_H
ConfigurationModule.cpp
#include "configuration_module.h"
void ConfigurationModule::registerCallback(ConfigurationCallback callback)
{
callbacks_holder_ += callback;
}
void ConfigurationModule::changeSection(ConfigurationHandler& configuration_handler, std::string new_section)
{
if(new_section != current_section_)
{
current_section_ = new_section;
callbacks_holder_(configuration_handler);
}
}
std::string ConfigurationModule::getCurrentSection()
{
return current_section_;
}
ConfigurationCallbackHolder.h
#ifndef CONFIGURATION_CALLBACK_HOLDER_H
#define CONFIGURATION_CALLBACK_HOLDER_H
#include <vector>
#include <string>
#include <functional>
class ConfigurationHandler;
using ConfigurationCallback = std::function<void(ConfigurationHandler&)>;
class ConfigurationCallbackHolder
{
public:
void operator+=(const ConfigurationCallback callback);
void operator()(ConfigurationHandler& configuration_handler) const;
private:
std::vector<ConfigurationCallback> callbacks_;
};
#endif //CONFIGURATION_CALLBACK_HOLDER_H
ConfigurationCallbackHolder.cpp
#include "configuration_callback_holder.h"
void ConfigurationCallbackHolder::operator+=(const ConfigurationCallback callback)
{
callbacks_.push_back(callback);
}
void ConfigurationCallbackHolder::operator()(ConfigurationHandler& configuration_handler) const
{
auto iterator = callbacks_.cbegin();
for(; iterator != callbacks_.cend(); ++iterator)
{
(*iterator)(configuration_handler);
}
}
Answer: //The array that keeps the string values of the ConfigKeys
const std::string configuration_key_string_values[configuration_key_count] = {
"NavmeshObstaclesDilatation", "LargestTriangleAreaInNavmesh", "LongestEdgeInNavmesh", "NavmeshFilename", ⋯
When I have an array like this for names or other purpose, where the actual enumeration values are significant, I will use at least an explicit initializer on the first one (as did you) but also comments there explaining that. Furthermore, all places that must be updated as well when you change the enumeration will be marked with some unique word that can be grepped for (and that is part of the commentary).
You might be interested in the short video “Enums 4 Ways” at CppCon (née BoostCon) 2018, posted to YouTube last week.
Do the enumeration values need to be a contiguous range of small integers (e.g. used in switch statements, stored in small words) or just serve as compile-time unique values?
Because another thing you can do is define named constants rather than enumerators. If the C++ symbol is itself a lex string, you automatically have the correspondence at least in one direction!
struct my_enum_thing {
static const char* const NavmeshObstaclesDilatation = "NavmeshObstaclesDilatation";
// etc.
The actual value of the symbol is a pointer, and unique. But, they are the full word size, and not consecutive numbers.
You might use an “X Macro” approach to define everything from one supplied list of names.
const std::string configuration_key_string_values[configuration_key_count] =
You don’t need to give the array size (and have those previous lines to figure it out), as it will simply match the initializer count.
You are creating all the string objects at run-time, which will duplicate the bytes of the string. So you will have the original lex strings still in your read-only data, and the std::strings with pointers to heap memory containing the same contents. And all that copying has to happen at program-start.
Make the array a constexpr itself, and use std::string_view values. You can construct the string view wrapper at compile time, and it points back to the lex string, without duplication.
using namespace std::literals::string_view_literals;
constexpr std::string_view config_values[]= {
"NavmeshObstaclesDilatation"sv, "LargestTriangleAreaInNavmesh"sv, ⋯
Note the sv on following the closing quote.
The advantage of making the array of string view, rather than plain lex strings, is that code does not have to call strlen when using them.
long ConfigurationHandler::getInt(ConfigKey key, ConfigModule module)
{
auto defaultValue = static_cast<int>(default_values_[static_cast<int>(key)].numeric_value);
auto sectionName = findSectionName(key, module);
return ini_reader_.GetInteger(sectionName, getKeyName(key), defaultValue);
}
double ConfigurationHandler::getDouble(ConfigKey key, ConfigModule module)
{
auto defaultValue = default_values_[static_cast<int>(key)].numeric_value;
auto sectionName = findSectionName(key, module);
return ini_reader_.GetReal(sectionName, getKeyName(key), defaultValue);
}
bool ConfigurationHandler::getBool(ConfigKey key, ConfigModule module)
{
auto defaultValue = default_values_[static_cast<int>(key)].boolean_value;
auto sectionName = findSectionName(key, module);
return ini_reader_.GetBoolean(sectionName, getKeyName(key), defaultValue);
⋯ etc. ⋯
I’m seeing a lot of repetition here, as well as conceptually a single operation that should be parameterized on type. You should make it a template, so most of the code is naturally shared. If ini_reader is a 3rd party library and not template friendly in this same way, you just have to supply one-line wrappers, not duplicate the whole body.
x = config.get<long>(key, module);
y = config.get<double> (key2, module);
z - config.get<bool> (key3, module);
Oh, and my syntax highlighting is reminding me that module is reserved as a new reserved word. So don’t use it as a variable name!
auto module = getModule(module_enum);
if(module)
{
module->registerCallback(callback);
}
The idiom is to initialize and test at the same time. The advantage is that the variable is only in scope if it is correct to use!
if (auto module = getModule(module_enum))
{
module->registerCallback(callback);
}
ConfigModule ConfigurationHandler::getModuleEnumFromKeyEnum(ConfigKey key) const noexcept
{
//I'm not proud of this function, but I could'nt find a better solution yet.
if(key < ConfigKey::NecessaryMargin)
{
return ConfigModule::Navmesh;
}
else if(key < ConfigKey::MaxCurvatureDerivative)
{
return ConfigModule::Autoreplanning;
}
else if(key < ConfigKey::NodeMemoryPoolSize)
{
return ConfigModule::ResearchMechanical;
}
else if(key < ConfigKey::PrecisionTrace)
{
return ConfigModule::Memory;
}
else
{
return ConfigModule::Tentacle;
}
}
Put the pairs of values in an array. So
{ ConfigKey::NecessaryMargin, ConfigModule::Navmesh },
{ ConfigKey::MaxCurvatureDerivative, ConfigModule::Autoreplanning },
⋮
Then you can write the logic once, iterating over the tuples of parameters.
for (auto [ck, cm] : the_list) {
if (key < ck) return cm;
}
// none of the above
return ConfigModule::Temtacle;
This is a general concept and working through it here will probably help you in more places.
Another idea, if you can be flexible about the assignment of code numbers, is to code the bunch in the high-order bits. So something like
enum ⋯ { NecessaryMargin= 0, ⋯
MaxCurvatureDerivative = 0x1'0000,
MaxLateralAcceleration, // continue auto-numbering
Now you can examine the high bits of the enumeration’s value to recover the module that goes with it.
if(moduleId < module_count)
{
return modules_[moduleId];
}
else
{
return std::nullopt;
}
Look at the code generated when you call this!
Writing it to allow NVRO is much cleaner.
std::optional<ConfigurationModule> retval;
if (moduleId < module_count)
retval.emplace(modules_[moduleId]);
return retval;
The default values could be built at compile time, not copied into a vector at run time. Try setting them up in sorted order in an array, and then find it using std::lower_bound etc. BTW, std::map uses a lot of (dynamic) memory and is slow; a sorted vector is faster for lookups!
Good luck with that project — it looks interesting! | {
"domain": "codereview.stackexchange",
"id": 30930,
"tags": "c++, c++17"
} |
What processes cause the collapse of a wavefunction and break entanglement? | Question: This question states that measuring the spin of an entangled particle causes the collapse of the wavefunction and thus the entanglement is broken.
Then this question states that we don't know what exactly is the cause for the collapse of wavefunctions.
However, what processes are known to collapse the wavefunction, and specifically break entanglement?
So measuring the spin collapses the wavefunction. What else does?
Chemical processes?
Presence in magnetic field without a screen (similar to Stern-Gerlach experiment)?
Irradiation of some form?
Heating?
EDIT
Given comments that the collapse of the wavefunction is still not understood, I'd like to emphasize experimental observations.
Also, given that the collapse of a wavefunction may or may not be an artificial construct, can we focus on what processes have been observed to destroy entanglement?
(From what I understand of current theory, entanglement is only broken by the resolution/collapse of the wavefunction, thus asking "what has been observed to collapse the wavefunction" and "what has been observed to break entanglement" should be questions with the same answers.)
Answer: Since you already talk about Stern-Gerlach, I suspect that the focus of your question is more about at which point in existing experimental techniques the collapse occurs, and not about learning existing techniques. In Stern-Gerlach that would be the deflection, not the screen, because this is where the spin value gets to be determined. If I got the question right, then the general answer is "at the point in the experiment where the studied property gets a specific value and superposition ends".
Also: Measuring is interacting with the system under study. There is nothing special putting measurement apart from any other physical process. This means that any interaction of the original system with anything else in the universe will break the wavefunction, preparing a new state.
I think the most concise (and entertaining) answer was the first comment (source) in the first of your links:
Basically, for observations to happen, there has to be an interaction
between particles, or as the post put it less/more(?) eloquently,
whenever a physicist says "observe", mentally replace it with "hit
with sh*t. | {
"domain": "physics.stackexchange",
"id": 39210,
"tags": "quantum-mechanics, wavefunction, quantum-entanglement, measurement-problem, wavefunction-collapse"
} |
Extracting specific data from unstructured text - NER | Question: I have a reasonably simple problem to solve. I need to extract reservations numbers from unstructured text. Based on my research, it seems to be an NER problem. Based on a visual analysis of the dataset, I could notice that the reservation number is frequently near specific keywords, such as 'confirmation', 'reservation', 'confirmation number', 'reservations number', etc.
First, I decided to try a Regex rule to extract the data, but some minimum variations might render this solution inefficient. The reservation number can have very different variations, such as:
ZXC51657856,
EA5FFD4,
45615177413515,
QT454545EF,
At this moment, I don't have a dataset available to train a classifier to solve this issue.
I would like to receive some ideas from the community to guide me towards an elegant solution to this problem, as I'm pretty new to ML in general and time is limited.
Answer: From your question, I too feel it's a NER problem. And about the dataset, unless there is a data set which tags the reservation numbers and is similar to your application, you WILL have to create your own data set.
I worked on a similar problem before and my dataset looked something like this:
<TEAM>Northern</TEAM> NNP
<TEAM>Ireland</TEAM> NNP
man NN
<PLAYER>James</PLAYER> NNP
<PLAYER>McIlroy</PLAYER> NNP
is VBZ
confident JJ
he PRP
can MD
win VB
his PRP$
first JJ
major JJ
title NN
at IN
this DT
weekend NN
's POS
<COMPETITION>Spar</COMPETITION> JJ
<COMPETITION>European</COMPETITION> JJ
<COMPETITION>Indoor</COMPETITION> NNP
<COMPETITION>Championships</COMPETITION> NNP
in IN
<LOCATION>Madrid</LOCATION> NNP
You can see that that I have the entity tag and the part of speech tag in the word. When I parse this dataset for training, I also add the IOB tags (Inside, Outside, and Beginning)
[(('Claxton', 'NNP\n'), 'B-PLAYER'),
(('hunting', 'VBG\n'), 'O'),
(('first', 'RB\n'), 'O'),
(('major', 'JJ\n'), 'O'),
(('medal', 'NNS\n'), 'O'),
(('.', '.\n'), 'O'),
(('British', 'JJ\n'), 'O'),
(('hurdler', 'NN\n'), 'O'),
(('Sarah', 'NNP\n'), 'B-PLAYER'),
(('Claxton', 'NNP\n'), 'I-PLAYER')......]
Then I just used the ClassifierBasedTagger(There are other taggers too). I can't find the source but I used this code:
class NamedEntityChunker(ChunkParserI):
def __init__(self, train_sents, **kwargs):
assert isinstance(train_sents, Iterable), 'The training set should be an Iterable'
self.feature_detector = features
self.tagger = ClassifierBasedTagger(
train = train_sents,
feature_detector = features,
**kwargs)
def parse(self, tagged_sents):
chunks = self.tagger.tag(tagged_sents)
iob_triplets = [(w, t, c) for ((w, t), c) in chunks]
return conlltags2tree(iob_triplets)
Here features is a function which returns a dictionary of the features to be used such as the previous word, previous word's pos tag etc. Just features to train the model on.
{
'word' : word,
'lemma' : stemmer.stem(word),
'pos' : pos,
'allascii' : allascii,
'next-word' : nextword,
'next-lemma' : stemmer.stem(nextword),
'next-pos' : nextpos,
'prev-word' : prevword,
'prev-lemma': stemmer.stem(prevword),
'prev-pos' : prevpos
}
You can find useful theory here
I hope this helps. | {
"domain": "datascience.stackexchange",
"id": 3720,
"tags": "nlp, named-entity-recognition"
} |
What does it mean for equations to have not advanced to the point where one could plug them into a computer? | Question: In this article about the EMC effect (in no way relevant to my question), the statement is made:
The problem is that the complete QCD equations describing all the quarks in a nucleus are too difficult to solve, Cloët and Hen both said. Modern supercomputers are about 100 years away from being fast enough for the task, Cloët estimated. And even if supercomputers were fast enough today, the equations haven't advanced to the point where you could plug them into a computer, he said.
I want the simplest possible example of equations that can't be plugged into a computer (This really should go without saying, but I want an example that typifies the reason the QCD equations specifically can't be plugged into a computer. So I guess in some sense it is relevant to my question contrary to what I said above. Also if you want to talk about QCD or EMC that's fine; I wouldn't have read the article if I wasn't interested in those things, and maybe it's helpful in the context of the question as well?).
Answer: This refers to a technical problem with lattice QCD simulations known as the "fermion sign problem", see also the previous post here. The sign problem implies that we can efficiently simulate the QCD equation of state at finite temperature, but not at finite net baryon density. We can compute the masses and properties of mesons and glueballs, but baryonic states with mass number $A>1$ are exponentially hard in $A$. The EMC problem refers to certain matrix elements in heavy nuclei (such as Calcium, $A=40$, or lead, $A=208$), which cannot be computed using available algorithms and computers architectures. It is conceivable that new classical algorithms, or new kinds of computers (quanutum) could help. | {
"domain": "physics.stackexchange",
"id": 88794,
"tags": "computational-physics"
} |
Does sulfuric acid formed in a previous step dehydrate a secondary alcohol? | Question: In the following reaction won't the sulphuric acid dehydrate the secondary alcohol after it's formed?
Answer: It could, but the addition of water would push equilibrium toward the hydrated product, and the $\ce{H2SO4}$ would likely transfer into the water layer that you made by adding $\ce{H2O}$.
Plus, you would only make stoichiometric sulfuric acid. Depending on the amount of water, the pH of the solution formed could be fairly neutral. Also, usually, the acid (despite being a catalyst) is used in large excess for dehydration reactions.
Therefore, it is possible (given the right conditions) but unlikely. | {
"domain": "chemistry.stackexchange",
"id": 5377,
"tags": "organic-chemistry, reaction-mechanism, alcohols"
} |
Nitronate anion reduction with TiCl3. Nef reaction | Question: We can do the Nef reaction, by treatment of nitronate anion with $\ce{TiCl3}$. Here is the mechanism from article:
And I can’t understand what is exactly happening in $35\to38$ or $36\to37$. Can you please show precisely with arrows what is going on? Precise mechanism
Answer: When we go from 35 to 38 or from 36 to 37, the Ti(IV) species $\ce{TiOCl2}$ is leaving. Since the titanium entered as $\ce{Ti^{III}Cl3}$, this represents a net one-electron reduction.
But wait, there's more. The 36$\to$37 step requires adding another electron to neutralize the positive charge on 36, and if we treat the hydroxyl hydrogen on 38 as protic then that molecule also needs an additional electron. In either case a second $\ce{TiCl3}$ must be introduced at the 36$\to$37 or 35$\to$38 step as the source of this electron, so we have a two-electron reduction of the organic molecule using two $\ce{TiCl3}$ molecules in all. The charge on titanium from the second $\ce{TiCl3}$ molecule is balanced by accepting the chloride ion that the first $\ce{TiCl3}$ molecule surrendered to add to the oxygen earlier in the mechanism.
Below, I add the additional $\ce{TiCl3}$ molecule indicating where the electron from that molecule goes.
Thus we render the overall reaction:
$\ce{(CH3)2C^0H–N^{III}O2 +2Ti^{III}Cl3 -> (CH3)2C^{II}=O + Ti^{IV}OCl2 + Ti^{IV}Cl4 + N^{-I}H2OH}$
where oxidation states (based on expected bond polarities) on the atoms that are oxidized or reduced are indicated. Note that even though the substrate was reduced by two electrons, the nitrogen atom in the nitro group took four leaving the carbon in a higher oxidation state. | {
"domain": "chemistry.stackexchange",
"id": 17907,
"tags": "organic-chemistry"
} |
Would a generator in vacuum/space provide electricity endlessly? | Question: At it's simplest, electricity generation is achieved by induced voltage due to a changing magnetic field. In a vacuum in the absence of friction, would the initial spin imparted to the rotor of a generator ever come to a halt?
i.e. Would a traditional generator in space generate electricity perpetually (notwithstanding component failure etc)?
Answer: No, because the process of transferring the voltage into a useable form or device will reduce it. In other words, under perfectly idealized conditions (which are impossible), yes it might spin forever, but as soon as you try to use your generator to power a device, you'll slow it down. | {
"domain": "physics.stackexchange",
"id": 1629,
"tags": "electricity, vacuum, perpetual-motion"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.