anchor
stringlengths
0
150
positive
stringlengths
0
96k
source
dict
Physical interpretation of density of states
Question: The following pictures shows some typical examples of density of states: and for superconductor: Here is my interpretation: Energy level zero represents Fermi energy level. Positive energy represents energy levels for holes. Negative energy level represents energy levels for electrons. Density of states (DOS) on positive axis represents probability of electrons/holes to be found if we multiply DOS with Fermi function. For superconductor example, we have two curves separated by gap of aproximately +/- 1meV. It is a superconducting gap. Within that gap we have superconducting state. My question is for insulator DOS example. Top unshaded peak represents electron bands and and shaded one represents hole bands. What is the physical interpretation if unshaded peak is on negative axis instead positive and shaded peak is still positive? Is there such thing as negative energy levels? (antiparticle?) Answer: The hole and electron bands in your example are, in other words, occupied and unoccupied (virtual) energy bands. If you flipped that, it means all the electrons have been exited into the conduction bands, leaving behind unoccupied states in what used to be the valence bands. Such a scenario could be realized, for instance, with powerful laser pulses, where the excitation density is high enough to momentarily excite everything from the valence bands. The energy of some states is negative only because of the chosen reference value, which is generally the Fermi level. There is no need to invoke the antiparticle concept here.
{ "domain": "physics.stackexchange", "id": 42506, "tags": "quantum-mechanics, condensed-matter, solid-state-physics, density-of-states" }
Using the curse of dimensionality for encoding non-ordered (nominal) categorical variables of high cardinality
Question: When the dimension is high, all data are approximately at the same distance away from each other. This makes distance-based methods such as k-nearest neighbors less useful if the data are more or less uniformly distributed. This is also referred to as the curse of dimensionality. However, why not to make lemonade out of this dimensionality lemon? Why not to encode nominal categorical variables of high cardinality with randomly distributed points in some high-dimensional space but such that the number of dimensions is much less than we would get with the one-hot encoding? As the distance between any two points is almost the same, no artificial ordering will be introduced. The encoding is very fast. No need to calculate embedding with some neural network. Will this encoding work? Will it be meaningless or introduce any bias? Is anybody using it? Do you know any references? Answer: When the dimension is high, all data are approximately at the same distance away from each other. Yes, but this is the worst case scenario of the curse of dimensionality: This happens only if the data is extremely sparse. In real cases it's not really "all data", because some data points are less sparse than others, and it's not really "the same distance", because there can be small but meaningful differences in the distance between points. There are known mitigation measures which can prevent this worst case scenario to happen, in particular various feature selection/extraction methods. So in real cases it's simply a mistake to work with some very high dimensionality data left "untreated". Why not to encode nominal categorical variables of high cardinality with randomly distributed points in some high-dimensional space but such that the number of dimensions is much less than we would get with the one-hot encoding? This would correspond to a random feature extraction method: instead of trying to group similar features together when reducing the dimensions, features are just randomly projected into a low-dimension space. The disadvantage is clear: instead of simplifying the data while preserving the patterns, the patterns in the data are just ignored. It's likely that the data would become pretty much useless after that. The goal is not just to reduce dimensionality for the sake of it, it's to reduce dimensionality in a way which leaves the most important characteristics of the data as intact as possible, or even emphasize them by removing the noise. This method would be equivalent to randomly selecting features instead of selecting the most informative ones. For example, in the case of text data there is often high dimensionality due to the high number of distinct words. A basic but very effective method consists in discarding words which appear rarely: this reduces the dimensions a lot (due to the Zipf distribution of words in a text), prevents noise due to words which happen by chance, and preserves most of the patterns which happen with moderately frequent words.
{ "domain": "datascience.stackexchange", "id": 9210, "tags": "machine-learning, preprocessing, categorical-data, dimensionality-reduction, categorical-encoding" }
Update OpenCV version in ROS
Question: Hello, I checked my OpenCV version discovering that is 2.4.8. I want to update it to 2.4.13 (at least 2.4.9) but I don't want to stop to use it in ROS Indigo too. Since OpenCV is not a system dependencies anymore for Indigo, can I simply remove the old version of OpenCV and install a new one without "break" ROS Indigo? Anyone knows if other actions are required? Originally posted by marcoresk on ROS Answers with karma: 76 on 2016-11-19 Post score: 0 Answer: You can locally upgrade any package. But you will potentially have to rebuild all packages built against that package if the ABI has changed. Otherwise it will be fine. Originally posted by tfoote with karma: 58457 on 2018-04-29 This answer was ACCEPTED on the original site Post score: 0 Original comments Comment by gvdhoorn on 2018-04-30: Related: #q289264. I've also described how to update a system dependency and then rebuild packages that depend on it.
{ "domain": "robotics.stackexchange", "id": 26284, "tags": "ros, opencv" }
What units of distance should I use for square potential well?
Question: I make some calculations for double square potential well and I want the values to make sense for a real physical system. The energy is in eV. What would be a convenient unit of distance? On wikipedia one can find the unit $\hbar c/{\rm eV}=1.97\cdot10^{-7}\rm m$. However with this unit everything seems to get nonsensical. For demonstration I calculate ground state of an electron in an infinite potential well: $$E_n=\frac{n^2 h^2}{8mL^2}$$ $$E_1=\frac{h^2}{8mL^2}$$ SI units: Planck constant $$h_{SI}=6.626\cdot10^{-34}\,\rm Js$$ electron mass $$m_{SI}=9.109\cdot10^{-31}\rm kg$$ I choose: $$L_{SI}=0.390\,\rm nm$$ After pluging into the formula above we obtain $$E_1=3.96\cdot10^{-19}\rm J=2.47\rm eV$$ Which corresponds to example. Electron volts $$h_{e}=4.136\cdot10^{-15}\,\rm eV\cdot s$$ $$m_{e}=511000\,\frac{\rm eV}{c^2}$$ $$L_e=\frac{0.39\cdot10^{-9}}{1.97\cdot10^{-7}}\frac{\rm \hbar c}{\rm eV}=0.198\cdot10^{-2}\frac{\rm \hbar c}{\rm eV}$$ If I plug it in this time I get: $$E_1=\frac{(4.136\cdot10^{-15})^2}{8\cdot 511000\cdot(0.198\cdot10^{-2})^2}{\rm eV}=1.07\cdot10^{-30}{\rm eV}$$ which is absolute nonsense. I figured that I need $L_e$ to be: $$L_e=\frac{0.39\cdot10^{-9}}{3\cdot10^8}$$ So it should be just divided by the speed of light $c$ but I need the dimension to be correct. Edit1: Flipped $\frac{\hbar c}{eV}$ (there used to be $\frac{eV}{\hbar c}$ instead), corrected numerical value of $L_e$ Answer: This is a good example of why it's never a good idea to ignore the constants and hope that they work out correctly. Here's how you avoid doing that kind of mistake. Your values for $L=0.198\times10^{-2}\:\hbar c/\mathrm{eV}=0.39\:\mathrm{nm}$, $h=4.136\times 10^{-15}\:\mathrm{eV\:s}$, and $m=5.11\times 10^5\:\mathrm{eV}/c^2$ are all correct. Now let's put them into your formula for $E_1$ without forgetting the constants: \begin{align} E_1 & = \frac{h^2}{4mL^2} \\& =\frac{(4.136\times 10^{-15}\:\mathrm{eV\:s})^2}{8(5.11\times 10^5\:\mathrm{eV}/c^2)(0.198\times10^{-2}\:\hbar c/\mathrm{eV})^2} \\& =\frac{(4.136\times 10^{-15})^2}{8\times 5.11\times 10^5\times(0.198\times10^{-2})^2} \times \frac{(\mathrm{eV\:s})^2}{ \mathrm{eV}/c^2(\hbar c/\mathrm{eV})^2} \\& =1.07\times 10^{-30} \frac{(\mathrm{eV\:s})^2}{ \mathrm{eV}/c^2(\hbar c/\mathrm{eV})^2} . \end{align} As you can see, the numerical factor comes out about correct, but the rest of the units come out as one jangled soup. A few cancellations are easy, starting with $c$, but to take this apart you need to go deeper: \begin{align} E_1 & = 1.07\times 10^{-30} \frac{(\mathrm{eV\:s})^2}{ \mathrm{eV}/c^2(\hbar c/\mathrm{eV})^2} \\ & = 1.07\times 10^{-30} \frac{\mathrm{eV\:s^2}}{ (\hbar /\mathrm{eV})^2} \\ & = 1.07\times 10^{-30} \frac{\mathrm{eV^3\:s^2}}{ \hbar^2} \\ & = 1.07\times 10^{-30} \times(2\pi)^2\left(\frac{\mathrm{eV\:s}}{ h}\right)^2\mathrm{eV} \\ & = 1.07\times 10^{-30} \times\left(\frac{2\pi}{4.136\times 10^{-15}}\right)^2\mathrm{eV} \\ & = 2.46\:\mathrm{eV} \end{align} There's no contradiction - just missing numerical factors. Leaving out the units in intermediate steps is OK if all your calculation is in SI units (and if you're OK with forgoing one of the easiest sanity checks that can raise flags immediately if you've e.g. forgotten to put in some factor) but with anything fancier than that, it leaves you exposed to this kind of thing. Work out the unit cancellations explicitly - it's good for a number of reasons.
{ "domain": "physics.stackexchange", "id": 39816, "tags": "quantum-mechanics, units" }
How does Golgi's neural histological stain work?
Question: What is known about the targets of Golgi staining of neurons? Are larger neurons more likely to be stained? Are specific cell types more susceptible than others? The current wikipedia article says the mechanism is still not fully understood. What is preventing us from using the advanced molecular biology techniques to understand the process? Answer: Some background information. First of all one should notice, that Golgi staining belongs to so-called morphological types of stainings in neuroscience, where the actual anatomy of different neurons is revealed (compared to other techniques, like Ca-imaging or potential imaging). Second, Golgi staining is a type of silver staining, there the sedimentation of silver or its salts (here: silver chromate) reveals the morphological traits of the cels. And, third, Golgi staining is applied to fixed preparation. This means that the tissue (normally a brain slice) is pre-treated (here: with formol) to kill all cells and arrest every biological process. What is known about the targets. The common description of the target is quoted as "a limited number of cells at random in their entirety". This is the essence of Golgi staining: Only single cells are stained, therefore there is no impediment from adjacent cell staining while deriving the morphological structure of the cells (very important for light microscopy where you have integrated input from different depths). The cells are stained randomly, there is no known preference among neuronal cells for Golgi staining and I haven't seen any other types of cells in CNS stained with Golgi, therefore it is quite specific for neuronal cells (and leaving macro- and microglia, astrocytes etc. intact). The cells are stained in their entirety, meaning that the complete cell is stained very nicely, showing detailed arborisation of dendritic tree, that was very important in studying of Purkinje cells in cerebellum. Are larger neurons more likely to be stained? Are specific cell types more susceptible than others? Golgi staining is used mostly for brain slices (I have never seen or heard its application for other tissues). Traditionally one of the biggest cells here are pyramid neurons (NA, ACh-ergic) and one of the smallest are interneurons (often GABA-ergic) -- both are amenable to Golgi staining (reference) and there is no seemingly clusterization of stained cells by their size or transmitter type. What is preventing us from using the advanced molecular biology techniques to understand the process? I can name several reasons for this: Since Golgi staining is applied to fixed preparation the tissue is already "damaged" (formol leads to dessication of cells and shrumping), therefore it is difficult to use some fine mollecular biology methods to investigate these tissues. There is no way to tell which cells get stained beforehand. And as long as the microcrystallisation of silver chromate is started it can't be (easily) stopped and reversed. Therefore it is difficult to look at what caused the staining afterwards, then the whole cell is impregnated with silver. I think there were no real attempts to crack the mistery of this staining: how intersting it might be, this seems to be an interdisciplinary question on the brink between biology and chemistry. So, maybe one day somebody will look into it and explain everything.
{ "domain": "biology.stackexchange", "id": 184, "tags": "neuroscience" }
Did some senses evolve from other senses or are they considered independent?
Question: Are there evolutionary connections between different senses, in such a way that one sense is evolved from the other or from a common root, e.g. the possibility that hearing and touch are derived from a common root? If there are such evolutionary paths, are there any attempts to draw a map between different senses? Answer: Hearing and touch are both examples of mechanosensation, i.e. touch receptors are activated by pressure changes and sensory hair cells (hearing) are activated by fluid motion initiated by sound waves. Therefore, I think it makes sense that they evolved from similar origins. Vision on the other hand is due to photosensation, which has a very different physiology, so I don't think there's any evidence of a similar evolutionary link, but there may be (almost certainly are) similarities in the way our brains have evolved to respond to the different senses.
{ "domain": "biology.stackexchange", "id": 7132, "tags": "evolution, senses" }
Why is it called back-propagation?
Question: While looking at the mathematics of the back-propagation algorithm for a multi-layer perceptron, I noticed that in order to find the partial derivative of the cost function with respect to a weight (say $w$) from any of the hidden layers, we're just writing the error function from the final outputs in terms of the inputs and hidden layer weights and then canceling all the terms without $w$ in it as differentiating those terms with respect to $w$ would give zero. Where is the back-propagation of error while doing this? This way, I can find the partial derivatives of the first hidden layer first and then go towards the other ones if I wanted to. Is there some other method of going about it so that the Back Propagation concept comes into play? Also, I'm looking for a general method/algorithm, not just for 1-2 hidden layers. I'm fairly new to this and I'm just following what's being taught in class. Nothing I found on the internet seems to have proper notation so I can't understand what they're saying. Answer: Have a look at the following article Principles of training multi-layer neural network using backpropagation. It was very useful to me. You can also see here an example of backpropagation in Matlab. It effectively solves the XOR problem. You can also play around with the cost function or the learning rate. You may get surprising results! Does this answer your question?
{ "domain": "ai.stackexchange", "id": 1834, "tags": "terminology, backpropagation, history, multilayer-perceptrons" }
Gas Station problem : Fixed path variation
Question: Given a set of cities where you need a certain amount of fuel to travel from one city to another, each city has a different fuel price and you can only load K amount of fuel to the vehicle. The path is fixed (ie) you have to go from C1 to Cn through C2, C3,.. and so on. The objective is to fill fuel in these cities in such a way the spendings on fuel is minimized. I thought about storing the minimum prices within a window whose requirements add up to K and then find the minimum cost required to traverse. I'm not sure how it holds up or is it even right in the first place. What if being greedy and filling up fuel to reach the city empty till you reach the closest city with cheaper fuel, not the optimal solution? How do i prove that it is? Answer: The greedy strategy works in this case (fill up as much as you need to reach the next cheaper city, or fill up to K if no cheaper city is reachable with a full tank). The proof is pretty much the same as most standard proofs for greedy algorithms: Among all optimal solutions, take the one that "agrees with the greedy strategy the longest" and show that this solution is in fact identical to the greedy one (to understand why this almost always works, you can read up on matroids and see how the standard proof is done in this case). Informally, in this case : Call GS your greedy strategy and let OPTS be an optimal strategy which agrees with GS for the longest time, starting from the beginning. Suppose GS and OPTS differ in strategy for the first time in city C: If OPTS fuels up more than GS at this point, then that means that GS fueled up just enough to reach the next cheapest city C'. It is clear that OPTS will arrive in C' with more fuel than GS (more than 0). But GS can then fill its tank up to as much as OPTS (for cheaper than OPTS could have at any point between C and C'). We can thus construct an optimal strategy OPTS' which does what GS does up to C' and then copies OPTS. But OPTS' is optimal and "agrees with GS" for longer than OPTS, which is impossible by definition of OPTS. So it is impossible that OPTS fuels up more than GS in C. If OPTS fuels up less than GS in C, then let C' be the next city where OPTS is gonna fuel up. C' can not be cheaper than C, otherwise GS would have filled up just enough to get there and OPTS would have had to fuel up at some point between C and C'. So C' is as least as expensive as C, and filling up in C would not have been worse for OPTS. We can once again construct a new strategy OPTS' which contradicts the definition of OPTS. So it is impossible that OPTS fuels up less than GS in C. Putting both together, we see that there can not be a "first disagreement point" between GS and OPTS. Thus, GS = OPTS, and GS is an optimal strategy.
{ "domain": "cs.stackexchange", "id": 14424, "tags": "algorithms, dynamic-programming, greedy-algorithms" }
Why is casting float to double applicable?
Question: This is indeed a Computer Science Question. As far as I am concerned casting down (up) does not require any mathematical operation. It is just shrinking down (leveraging) the significant bits. e.g Long: 0x00000000ffffffff casts down to Int: 0xffffffff However, this does not work with the representation of double and float: Double: b = 0xa000 0001 1000 0001 should cast down to Float: c = 0x1000 1001 which is not the same, even if the double is in the boundaries of float. So how is Casting from any type to another defined? Answer: This is really not a computer science question... First, you failed to distinguish between "casting" and "conversion". In many computer languages, "casting" is an explicit instruction to convert a value from some type to another type. For example in C, double d = 3.7; float f = d; // Automatic conversion, no casting double d = 3.7; float f = (float) d; // Casting as requested by programmer double e = (float) d; // Casting to float, followed by conversion to double So what you were really talking about was value conversion, not casting. (Being precise in what you write is arguably part of computer science). The effect of any conversion is defined by the computer language in question. "Shrinking down (leveraging) the significant bits" is something that doesn't make any sense at all. Bits don't have a size, you can't shrink them. And the word "leveraging" doesn't mean what you think it means. I assume you meant "removing the significant bits". But that's not how value conversion is defined. In C and C++, it is defined in terms of values. A conversion between scalar types results in the exact same value if the old value can be represented in the new type. If the value cannot be represented, then there are rules for conversions between integer types; in some cases the value is modified according to rules in the language, sometimes the value is modified according to implementation defined rules (and "implementation defined" has a very specific meaning in C and C++ that you need to learn), or it is undefined behaviour. Converting non-integral floating point values to integer values first rounds the value towards zero, and then other rules apply. Conversion between floating-point values will produce the original value if possible, rounds according to rounding rules in the language if that is not possible, with additional rules if the value is too large to represent. Do you notice how nothing at all here is talking about bits? Swift distinguishes between conversions that cannot fail and conversion that can fail. Conversions that can fail produce an optional value. Which is a totally different thing. For example, you cannot convert UInt to Int, only to an optional Int. You cannot convert Int64 to Int32, only to an optional Int32. But you can convert Int32 to Int64, because it is a conversion that cannot fail.
{ "domain": "cs.stackexchange", "id": 16336, "tags": "formal-languages, compilers" }
How to define new topic in UWSIM?
Question: Hello, I want to add a topic through which two vehicles can communicate with each other. Currently, the vehicles communicate to ROS and vice-versa. I want the vehicles to communicate with each other. I tried to create my own example code and put it along other examples present, but I was not able to compile it. I just want to pass timestamp from one vehicle to another. Can someone please tell me where should I start? I saw timestamp information is already included in standard message header. But I don’t know where to define my topic. Should it be in RosInterface.cpp? And how do I add my own cpp code for testing? Originally posted by User_810 on ROS Answers with karma: 5 on 2015-04-13 Post score: 0 Answer: ROS is designed so that communication between nodes, regardless of where they are running, happens through the ROS master. I'm not familiar with UWSIM, but if it's a sim that just has ROS plugins the following architecture is pretty standard: You can write your nodes so that each robot has a publisher and subscriber. When you initialize a publisher or subscriber with a topic: ros::Publisher chatter_pub = n.advertise<std_msgs::String>("chatter", 1000); That topic is created and the ROS master handles all communication to it. In this case the topic is called chatter. Aside from writing the publisher/subscriber nodes there are no additional steps to take when you want a topic created. So, for each simulated robot you would have a node that handles outbound communication through a publisher and inbound through a subscriber. If your robots are called rob_one and rob_two, then their publishers can publish on topics: rob_one_timestamp and rob_two_timestamp, respectively. Then rob_one's subscriber can subscribe to rob_two_timestamp and vice versa. It's a bit tough without seeing some of your code, and your CMakeLists.txt to understand why it isn't compiling. Originally posted by aak2166 with karma: 593 on 2015-04-13 This answer was ACCEPTED on the original site Post score: 2
{ "domain": "robotics.stackexchange", "id": 21423, "tags": "ros, uwsim" }
Finding car's average acceleration?
Question: I am trying to calculate the car's average acceleration in (m/s^2) between 0 and 2.1 s. I need to express this answer using two significant figures, I have been trying the following to get it and it keeps telling me my answer is wrong, what am I doing wrong? a = (delta v)/(delta time) a = (60 - 0) / (2.1) a = 28.57 Answer: What is wrong is the units. You are doing $$ \frac{(60 \mbox{ miles/hr})}{(2.1 \mbox{ sec})} = 28.57 \mbox{ mph/s } $$ What you need to do is convert the speed into $\mbox{m/s}$ $$ (60 \mbox{ miles/hr}) = ( \frac{1}{3600}60 \mbox{ miles/sec} ) = ( 1610 \frac{1}{3600} 60 \mbox{ meter/sec}) = 26.833 \mbox{ m/s} $$ Now do the acceleration as $$ \frac{(26.833 \mbox{ meter/sec})}{(2.1 \mbox{ sec})} = ... \mbox{m/s}^2 $$
{ "domain": "physics.stackexchange", "id": 33776, "tags": "homework-and-exercises, kinematics, time, acceleration, velocity" }
How to measure a correlated operator $Z_1Z_2$?
Question: I was reading this articl and I am stuck trying to understand equation $(60)$, which reads $$\langle\psi|\Lambda_{1,2}(X)Z_1\Lambda_{1,2}(X)|\psi\rangle=\langle\psi|Z_1Z_2|\psi\rangle$$ where $\Lambda(X)=|0\rangle\langle0|\otimes I+|1\rangle\langle1|\otimes X$ defines the CNOT gate. How do we obtain this equation? Also, I do not understand what does $Z_i$ mean for $i=1,2$ and what the subscripts $_{1,2}$ in $\Lambda_{1,2}$ are. Answer: Subscripts The meaning of the subscripts is explained in the preceding sentence Still the expectation value of the single qubit operator $Z_k$ on the $k$th qubit is [...] i.e. the subscript refers to the qubit on which the operator acts. Also, even though this does not appear to be stated explicitly, one would usually read the subscripts on $\Lambda_{1,2}$ as referring to the control and target qubits, respectively. This is suggested by the expression $$\Lambda(X)=|0\rangle\langle0|\otimes I+|1\rangle\langle1|\otimes X$$ which flips the second qubit if the first qubit is $|1\rangle$. Measuring $Z_1Z_2$ Under this interpretation of $\Lambda_{1,2}$, the equation $(60)$ is wrong, because $$ \begin{align} \Lambda_{1,2}(X)Z_1\Lambda_{1,2}(X) &= \Lambda_{1,2}(X)Z_1(|0\rangle\langle0|\otimes I+|1\rangle\langle1|\otimes X) \\ &= \Lambda_{1,2}(X)(Z_1|0\rangle\langle0|\otimes I+Z_1|1\rangle\langle1|\otimes X) \\ &= \Lambda_{1,2}(X)(|0\rangle\langle0|\otimes I-|1\rangle\langle1|\otimes X) \\ &= \Lambda_{1,2}(X)(|0\rangle\langle0|Z_1\otimes I+|1\rangle\langle1|Z_1\otimes X) \\ &= \Lambda_{1,2}(X)(|0\rangle\langle0|\otimes I+|1\rangle\langle1|\otimes X)Z_1 \\ &= \Lambda_{1,2}(X)\Lambda_{1,2}(X)Z_1 \\ &= Z_1. \end{align} $$ On the other hand, $$ \begin{align} \Lambda_{1,2}(X)Z_2\Lambda_{1,2}(X) &= \Lambda_{1,2}(X)Z_2(|0\rangle\langle0|\otimes I+|1\rangle\langle1|\otimes X) \\ &= \Lambda_{1,2}(X)(|0\rangle\langle0|\otimes Z_2+|1\rangle\langle1|\otimes Z_2X) \\ &= \Lambda_{1,2}(X)(|0\rangle\langle0|\otimes Z_2-|1\rangle\langle1|\otimes XZ_2) \\ &= \Lambda_{1,2}(X)(|0\rangle\langle0|Z_1\otimes Z_2+|1\rangle\langle1|Z_1\otimes XZ_2) \\ &= \Lambda_{1,2}(X)(|0\rangle\langle0|\otimes I+|1\rangle\langle1|\otimes X)(Z_1\otimes Z_2) \\ &= \Lambda_{1,2}(X)\Lambda_{1,2}(X)Z_1Z_2 \\ &= Z_1Z_2. \end{align} $$ There are two ways to interpret the above. Either there is a mistake in the paper and the equation $(60)$ should read $$ \langle\psi|\Lambda_{1,2}(X)Z_\color{red}{2}\Lambda_{1,2}(X)|\psi\rangle = \langle\psi|Z_1Z_2|\psi\rangle $$ or $\Lambda_{1,2}$ actually refers to the CNOT gate with qubit $1$ as the target and qubit $2$ as the control. Personally, I find the former much more likely. In any case, the error is very minor and has no effect on any claims in the paper. In particular, it is true that entangling operations like $\Lambda_{1,2}(X)$ enable one to measure correlated operators like $Z_1Z_2$.
{ "domain": "quantumcomputing.stackexchange", "id": 3326, "tags": "quantum-state, entanglement, measurement, linear-algebra" }
How do the electric or magnetic fields contain momentum?
Question: I have recently come to know that the electric and magnetic field contain both linear and angular momenta, which are known functions of the electric and magnetic fields at any given point in space and time. I don't understand how this is the case; could you explain how this works? Is it related to photons being emitted by the accelerating charges, or with the Abraham-Lorentz force? Answer: In terms of a photon picture, this is not really mysterious at all. The electromagnetic force is mediated, in its quantum mechanical description, by the exchange of photons. These can be real - i.e. represent real light beams - or virtual, which means that the energy for the photon's existence has been 'borrowed' for a small amount of time as allowed by the Heisenberg uncertainty principle. Electrostatic and magnetostatic fields consist, in the quantum picture, of a huge number of virtual photons flying back and forth. Now, each of these photons carries a certain amount of momentum. They must, because they will impart a force on the charged particles that absorb or emit them. Since each photon carries momentum, it is no surprise that the field as a whole can contain some net amount of momentum! Sometimes this will be zero - the contributions from the different photons will cancel out either locally at each point or globally once all points are considered - but this need not be the case. Thus, the electromagnetic field can carry momentum. Now, this is a nice and intuitive picture, but it draws on a very exotic concept, so I'd understand if it weirds you out a little. More than that, since the existence of electromagnetic field momentum is required within classical electrodynamics, one would also want an answer which does not require quantum mechanics to explain it. (Think about this last bit carefully - it's not a trivial argument.) In the end, whether the field "has" momentum or not is a matter of the definition of the word "have", which is a human construct. Strictly speaking, what is true is that it is possible to arrange situations where charged particles interact in a way in which their total mechanical momentum is not conserved, but once all the particles are separated again then their final total momentum equals the initial one. This is augmented by the fact that there exists a quantity, with units of momentum, and which can be calculated from the electric and magnetic fields at each point, which will give a conserved quantity if it is added to the particles' total mechanical momentum. It is important to note that the conservation of momentum is not a given; it is a property of physical theories which any particular theory may or may not have. (As it happens, all physical theories which we observe in the real world do observe it in some form, but that is not guaranteed a priori.) One example of this is newtonian mechanics with forces which obey Newton's third law. In this case, it is a theorem of the theory that the total mechanical moementum is conserved. Another example is Noether's theorem, which guarantees a momentum conservation law in dynamical systems of a certain class, whose laws are translationally invariant. For certain systems this invariance exists and hence momentum is conserved; for others it is not and momentum is not conserved. For charged mechanical particles interacting electromagnetically, Newton's third law does not hold, so our old theorem is not applicable (and in fact its conclusion is false, as the mechanical momentum is not conserved). However, this does not mean that we cannot find a smarter, more sophisticated theorem which does imply a conservation law. One therefore needs to sit for a bit and jiggle at the maths, but the theorem is indeed provable. In essence, what you do is write down the total force on the mechanical particles, express it in terms of electromagnetic fields, charges and currents, use Maxwell's equations to transform the charges and currents into electric and magnetic fields, and thus derive an expression for the total mechanical force on the system in terms of the integral of a certain function of the electric and magnetic fields at each point. One then needs to transform this quantity into the total time derivative of a simpler expression, which will be interpreted as the electromagnetic field momentum. This is possible but it leaves a remainder which depends on what volume you're integrating over. One can then prove that, for localized systems, this remainder vanishes. When it does, the total dynamical momentum - mechanical plus electromagnetic - is conserved. In general, I would discourage you from attempting this calculation until you have taken solid courses in electromagnetism and vector calculus at university level, or you will just bruise yourself up against it. Focus, instead, on the physics, on a qualitative level. If you have more specific questions I'm happy to try and reply, but if you want details on the mathematics you do need to specify what your background is so that we can give answers you will understand.
{ "domain": "physics.stackexchange", "id": 73603, "tags": "electromagnetism, momentum, conservation-laws, classical-electrodynamics" }
Can we model gravitation as a repulsive force?
Question: This question is actually related to my earlier question ("what is motion"). The fact that objects move a lot in the universe and that the universe is expanding, can imply that gravity is a repulsive force that increases with distance.. so the farthest objects repel us more. This can still explain several existing observations, e.g., why does the apple fall? Motion is the result of such repulsion. Two objects unlucky enough not to be moving relative to each other get squished due to the repulsion of the rest of the universe around them. The earth repels the apple less than the stars so it is pushed towards the earth. Furthermore, it can explain the expanding universe without the need for dark energy. This could be demonstrated in a thought experiment. If we take a lot of same-charge particles (with small mass) such as electrons and lock them in a large box at a low enough temperature. The mutual repulsion of the particles may cause similar motion as if due to gravitational attraction. Another experiment would be to measure the slight changes in our weight during day and night when the sun and earth align (if their masses are large enough to detect the feeble change in repulsion). [EDIT: the question in the original form may not have been clear. It is "can we model".. with a yes/no answer and why (not). If downvoting, please justify. Answer: Show me a distribution of remote mass that would provide the behavior we see for both Jupiter in orbit around the sun the many moons in orbit around Jupiter which both appear to be $1/r^2$ forces. Now try to generalize to support all the moons and planets in the solar system. You can't do it because the system is highly over-constrained.
{ "domain": "physics.stackexchange", "id": 6007, "tags": "gravity" }
Improve this function that compares jQuery versions
Question: Please help me improve this function that compares the jQuery version currently available (or not) with the one required. function(need) { if (typeof(jQuery) != 'undefined') { if (!need) return true; var re = /(\d+)\.(\d+)\.(\d+)/, cur = re.exec(jQuery.fn.jquery), need = re.exec(need); return (need[1] <= cur[1] && need[2] <= cur[2] && need[3] <= cur[3]); } else return false; } Answer: I'm sorry, but that code is completely broken. It doesn't work if either version contains only two numbers such as the current "1.6". It uses string comparison instead of integer comparison, so that it will return true if you "need" (theoretical) version "1.4.10" but only "1.4.2" is included, because "10" < "2" is true. It doesn't stop comparing minor version numbers, if the major number is already bigger. For example it will return false if "1.4.2" is "needed", but "1.5.1" is included, because "2" > "1" And finally you should keep in mind that "newer" isn't necessarily better. For example, the new 1.6 version changes how .attr() works, and scripts that rely on the old functionality of .attr() may break.
{ "domain": "codereview.stackexchange", "id": 1684, "tags": "javascript, jquery" }
How to assess the strength of the acid?
Question: Which is the stronger acid in the given pairs? $\ce{HClO3}$ and $\ce{HBrO3}$ $\ce{HClO2}$ and $\ce{HClO}$ $\ce{H2Se}$ and $\ce{H2S}$ given that the number of oxygen atoms is the same, the most electronegative atom should result in a stronger acid, thus $\ce{HClO3}$ is stronger. $\ce{HClO2}$ is stronger since it has more oxygen atoms. Here's where my logic fails, since the structure is the same (both have $\ce{2H+}$) then it boils down to 2 things to account for: electronegativity and the size of the atom. Going with electronegativity, sulfur is more electronegative thus stronger acid which was my original answer. But, the correct answer is $\ce{H2Se}$ is the stronger acid which implies in this case atomic size ($\ce{Se}$ is larger than $\ce{S}$) outweighs electronegativity. I do not understand why in this case $\ce{H2Se}$ is stronger than $\ce{H2S}$ given sulfur is more electronegative, and most importantly why the same logic used in 1. can't be applied here and how do I discern where to account for atomic size specifically or when to account for electronegativity? Any detailed-dumbed down explanations on the logic are highly appreciated. Answer: Let's start with $\ce{HXO_3}$. In $\ce{HXO_3}$, after removal of proton, an $\ce{XO_3-}$ ion is formed which is resonance stabilised. For example, if X was $\ce{Cl}$, Now, this shows that the $X$ needs to have a tendency to pull the electrons towards itself which decreases in the order :$\ce{Cl>Br>I}$. So more resonance is present in $\ce{ClO_3^-}$ than in $\ce{BrO_3^-}$ making the conjugate base of $\ce{HClO_3}$ more stable. Hence it is more acidic. So acidic strength decreases as: $\ce{HClO_3>HBrO_3>HIO_3}$ Now let's compare $\ce{HXO_3}$ and $\ce{HXO_2}$. You should now know that the acidic nature depends on the stability of the resulting conjugate base. Here, the number of resonance structure for $\ce{HXO_3}$ is more. Hence, the acid strength decreases in the order: $\ce{HClO_3>HClO_2>HClO}$. So its actually the number of resonance structures that affects the acidic strength. Finally, let's come to hydrides of 16th group. Let me represent any 16th group element as $Y$. Now, as size of $Y$ increases, the $\ce{H-Y}$ bond length increases. This means, the $\ce{H-Y}$ bond becomes weaker and removal of $\ce{H+}$ ion becomes easier. The size of atom decreases in the order :$\ce{O>S>SE>Te}$. Hence, the acidic strength decreases as : $\ce{H_2Te>H_2Se>H_2S>H_2O}$ This shows that electronegative is not the only reason. For example, if you considered $\ce{HF}$ and $\ce{HCl}$, then you may think that $\ce{HF}$ is more acidic because $\ce{F}$ is more electronegative and hence will be happy to get a negative charge. But, charge on a small atom is unfavourable. As atomic size increases, the charge can spread over a larger area. Hence, $\ce{Cl-}$ is more stable. The same trend is seen in case of hydrides of 16th group. The charge in $\ce{Se-}$ is spread over a larger area. Hence, its more stable.
{ "domain": "chemistry.stackexchange", "id": 4383, "tags": "inorganic-chemistry, acid-base" }
Aren't the ROS and catkin tutorials mixed?
Question: I've been looking at the ROS tutorial page (http://wiki.ros.org/ROS/Tutorials), and it appears to be mixed with he catkin tutorial page (http://wiki.ros.org/catkin/Tutorials). For example, there's twice the tutorial 'Creating a ROS package', and the 'Overlaying with catkin workspaces' is shown at the ROS tutorial page, while that is a very specific catkin tutorial. I'm unsure whether I can change the page myself, but I feel as if it should be changed. The current setup is confusing for new users. Originally posted by RafBerkvens on ROS Answers with karma: 386 on 2013-09-24 Post score: 3 Answer: I think I fixed what @RafBerkvens is talking about. Basically there were catkin tutorials which were interleaved into the ROS tutorials, but only in the listing. Something like this: ROS Tutorial 1 ROS Tutorial 2 Catkin Tutorial 1 ROS Tutorial 3 Catkin Tutorial 2 ... Someone added a fork in the tutorial chain which wasn't natural. @RafBerkvens, does the new setup help? Edit: This change is responsible, it also previously wiped out the later Tutorials, which I caught and fixed at the time, but I missed this subtle change before: http://wiki.ros.org/ROS/Tutorials/NavigatingTheFilesystem?action=diff&rev1=105&rev2=106 Originally posted by William with karma: 17335 on 2013-09-25 This answer was ACCEPTED on the original site Post score: 3 Original comments Comment by RafBerkvens on 2013-09-25: Yes, this solves the issue I was reporting. Thanks for the update.
{ "domain": "robotics.stackexchange", "id": 15643, "tags": "ros, catkin, tutorial" }
Training Objective of language model for GPT3
Question: On page 34 of OpenAI's GPT-3, there is a sentence demonstrating the limitation of objective function: Our current objective weights every token equally and lacks a notion of what is most important to predict and what is less important. I am not sure if I understand this correctly. In my understanding, the objective function is to maximize the log-likelihood of the token to predict given the current context, i.e., $\max L \sim \sum_{i} \log P(x_{i} | x_{<i})$. Although we aim to predict every token that appears in the training sentence, the tokens have a certain distribution based on the appearance in human litterature, and therefore we do not actually assign equal weight to every token in loss optimization. And what should be an example for a model to get the notion of "what is important and what is not". What is the importance refer to in here? For example, does it mean that "the" is less important compared to a less common noun, or does it mean that "the current task we are interested in is more important than the scenario we are not interested in ?" Any idea how to understand the sentence by OpenAI? Answer: This may be best understood with a bit more of context from the article: A more fundamental limitation of the general approach described in this paper – scaling up any LM-like model, whether autoregressive or bidirectional – is that it may eventually run into (or could already be running into) the limits of the pretraining objective. Our current objective weights every token equally and lacks a notion of what is most important to predict and what is less important. [RRS20] demonstrate benefits of customizing prediction to entities of interest. I think that the relevant part of the reference [RRS20] is this paragraph: Recently, Guu et al.(2020) found that a “salient span masking” (SSM) pre-training objective produced substantially better results in open-domain question answering. This approach first uses BERT (Devlin et al., 2018) to mine sentences that contain salient spans (named entities and dates) from Wikipedia. The question answering model is then pre-trained to reconstruct masked-out spans from these sentences, which Guu et al. (2020) hypothesize helps the model “focus on problems that require world knowledge”. We experimented with using the same SSM data and objective to continue pretraining the T5 checkpoints for 100,000 additional steps before fine-tuning for question answering. With that context in mind, I understand that the sentence in the GPT-3 papers means that in normal language models, the predictions of every token has the same importance weight toward the computation of the loss, as the individual token losses are added together in an unweighted manner. This as opposed to the salient span masking approach, which finds tokens that are important to predict by means of a BERT-based preprocessing.
{ "domain": "datascience.stackexchange", "id": 9407, "tags": "nlp, language-model, gpt" }
Is multiprocessing possible on a Turing Machine?
Question: I recently created a parallel implementation of the Merge Sort, in which the sorting of several groups was accomplished by different processes, and was wondering if this was theoretically possible on Turing Machine? Answer: This is a subtle question. TMs are very much a sequential model of computation. So in some sense, TMs cannot (directly) model multiprocessing. However, TMs can do step-by-step simulations of the reductions a multiprocessor is carrying out. So TMs can do a sequential simulation of a parallel computation. Whether this a genuine model of parallel computation is debatable. See also the discussion Applicability of Church-Turing thesis to interactive models of computation.
{ "domain": "cstheory.stackexchange", "id": 3242, "tags": "turing-machines, dc.parallel-comp" }
Cannot calibrate “upgraded starpointer finderscope” for Celestron AstroMaster 114EQ
Question: My wife just bought me an AstroMaster 114EQ which came with an "upgraded starpointer finderscope" -- it looks different than the one depicted in that link. I have tried following the instructions in their documentation to calibrate the finderscope with the primary telescope image and, unfortunately, the small red dot in the finderscope simply will not align with the main image of the telescope. In attempting to calibrate it, I pointed the scope at a building about a mile and a half away and got it clearly focused in the main scope. I then looked through the starpointer finderscope and tried to adjust it but the range of adjustment would not allow me to line up the red dot with this building -- the dot was high and to the right and the adjustment knobs simply would not turn any more -- they were at the end of their adjustable range. The supplementary documentation for the starpointer finderscope that came with the scope doesn't tell you which end points toward your target and which toward your face. I cannot really tell from the images in their website which orientation is correct. The mount doesn't seem to enforce any particular orientation. I assumed that the lense should be at the far end of the scope toward your objective and the power/brightness knob and the up/down adjustment knob, should be close to your face. Can anyone suggest how I might remedy this? I did search here first and this other post did not seem to have the information I was after. I'm supposed to go camping the day after tomorrow and would love to be able to locate Jupiter. I'm concerned that the scope may have been incorrectly assembled...i.e., the mount is off or something. Answer: I do not have one of these scopes, so my answer reflects general knowledge of astronomical telescopes. Yes, the lens should be at the far end, away from your eye. As for the alignment question, you can probably get a bit more movement in "left/right" direction by loosening the screws that hold the base of the finder to the scope, and twisting the mount and then re-tighten it. For the up/down adjustment, you may need to use a shim (a thin bit of metal) to adjust the angle, but the adjustment built into the finder is normally adequate. I doubt if there is a problem with the scope - if you can get a good focus, that's fine.
{ "domain": "astronomy.stackexchange", "id": 2248, "tags": "telescope, amateur-observing, newtonian-telescope" }
What are the high field strength and large ion lithophile (HFS or HFSE & LIL or LILE) elements?
Question: There are two groups of elements that are frequently mentioned when discussing incompatible trace elements. They are the high field strength elements (HFS or HFSE) and the large ion lithophile elements (LIL or LILE). What are these groups? How are they used in geochemistry and petrology? Answer: First, a short introduction to incompatible elements The Earth's mantle is mostly composed of the minerals olivine, pyroxene, anorthite, spinel and garnet. These minerals are made from the elements Si, Al, Fe, Mg and Ca. In the figure below I've put them in the MRFE field (Mantle Rock Forming Elements). The trace elements, the elements that occur in very low concentrations, do not form their own minerals and instead are incorporated into the crystal lattice of the common minerals. This is easy in the case elements that share the radius and charge with the major elements because they can easily fit into the crystal lattice (for example Ni in olivine, Cr in clinopyroxene). Most elements, however, plot out of the MRFE field in the figure and are considered incompatible elements. That is, in the case of mantle melting, these incompatible elements are partitioned to the magma and eventually migrate with it when it goes to form new rocks (for example basalts). Because different processes and conditions of mantle melting result in different patterns and contents of incompatible elements in the new rocks, we can learn about the mantle melting process by studying these elements in more accessible rocks (such as basalts in volcanoes). Note that I am referring to incompatible elements as incompatible with respect to mantle minerals. In some crustal rocks K, Na and Ti become major elements. In that case the MRFE should be renamed CRFE (Crustal Rock Forming Elements) and expanded to include these elements as well. HFSE and LILE The incompatible elements are then subdivided into two groups: the high field strength elements (HFS or HFSE) and the large ion lithophile elements (LIL or LILE). The LIL name partly gives away why they are called like that: the LIL are indeed larger than other cations. They are lithophile in the sense that they are incompatible and usually end up enriched in the crust (also lithosphere). The HFS are also enriched in the crust (eventually) but their name derives from their small radius compared to their high cationic charge: the z/r ratio. As a result, their bonding to nearby anions is very strong, that is - they have a high electrical field strength. The subdivision between the two groups has been defined at z/r = 2.0, but as this is a continuous value, no strict theoretical definition of where the boundary lies can be given. Historically, the REE have been considered as LIL. In more modern times, the REE may be excluded when discussing HFS. Why do we need the two groups? Even though both the LILE and HFSE behave in an incompatible way during mantle melting, their response to post-magmatic processes differ. The HFSE are usually immobile: that is, they are mostly resistant to metamorphism and hydrothermal alteration. On the other hand, the LILE are fluid-mobile and hydrothermal alteration may change their contents in the studied rock. Fresh rocks are a scarce luxury and many rocks that we study have experienced some kind of alteration. Because HFSE are resistant to these processes, their contents are likely to be representative of the original rock. This is extremely important: it is possible to look at a rock beyond the altered mineral composition and the modified major element contents. The LIL can teach us the opposite - we can learn about the alteration processes. If we do find fresh rocks and we find anomalies in the LIL systematics, we can learn about hydrothermal processes that occurred in the mantle that would otherwise not be able to see. What about hexavalent cations? One would think that hexavalent cations such as Mo6+, Cr6+, V6+ and U6+ should also appear in the figure as cations with an even more HFS character. However, when in the hexavalent state they form anionic complexes and do not behave like the cations in the figure. Further reading MIT OpenCourseWare - Trace-Element Geochemistry The Use of Trace Elements in Igneous Petrology About the figure Inspired by figure 2.2 from Ore Deposit Geology / Scott. Data for figure from An Earth Scientist's Periodic Table of the Elements and Their Ions (also doi)
{ "domain": "earthscience.stackexchange", "id": 312, "tags": "geology, volcanology, geochemistry, mineralogy, petrology" }
How to calculate sensor_msgs/LaserScan data?
Question: I have made a bag: 2021-02-15-11-32-28.bag and converted it in the: rplidarA1.csv File. So I have 2 Mb data and the following fields: %time field.header.seq field.header.stamp field.header.frame_id field.angle_min field.angle_max field.angle_increment field.time_increment field.scan_time field.range_min field.range_max field.ranges0 bis field.ranges719 field.intensity My question: With which of these fields, I can calculate the distance to a object ? I real appreciate your comments :-) Originally posted by Tricia279 on ROS Answers with karma: 15 on 2021-02-23 Post score: 0 Answer: The Lidar's laserscan/ranges work in this way: It detects and record in terms of an array in a string of Float32. So in the lets say the object is 2 meters between the Lidar 0 degree to 3 degree: Range: [2.0 2.0 2.0 0.0 0.0 0.0 ....] More on: http://docs.ros.org/en/api/sensor_msgs/html/msg/LaserScan.html Hope it helps. Originally posted by loguna with karma: 98 on 2021-02-25 This answer was ACCEPTED on the original site Post score: 0 Original comments Comment by drtritm on 2021-02-26: As @loguna have mentioned, but you should notice that the angle increment play a role in it. In @loguna example, the angle_increment is 1 degree, assumed that the measure unit of angle_increment is degree(but it's rad) Comment by Tricia279 on 2021-03-02: @loguna: I have 3 additional questions: The "range" in your example is it the field_range ? range_min or range_max ? I use RViz: How I can set the angle in rad there ? and How I can get these Range: [2.0 2.0 2.0 0.0 0.0 0.0 ....] ? Comment by loguna on 2021-03-03: Its in Field range. So the lidar spins 360 degree, it collects signals and place them into an array in meters. So lets say the Lidar collect a signal per degree (Check with your Lidar manufacturer), your array should contain [360] meters values. To obtain the signal, import the LaserScan from sensor_msgs.msg. Than try printing "LaserScan.ranges". If you wish to detect obstacle at a specific direction: The way i usually do is place an object in front of the Lidar. Next I set a random value like LaserScan.range[180] to see if the lidar did pick up the object. If it didnt, i change the "value" of LaserScan.range[value] until i get a hit. N usually 360 degree Lidar is use more towards mapping and not really to detect obstacles at a specific direction. Hence in RVIZ, it will show all the points in 360 degree.
{ "domain": "robotics.stackexchange", "id": 36123, "tags": "ros, ros-melodic, sensor-msgs, 2dlaserscan" }
Implement `Penultimate` in Shapeless
Question: I attempted to define Penultimate, i.e. a type class for shapeless.HList's that have a second to last element. import shapeless.{HList, HNil, ::} object Penultimate { type Aux[L <: HList, O] = Penultimate[L] { type Out = O } def apply[H <: HList](implicit ev: Penultimate[H]) = ev implicit def secondToLast[H, G]: Aux[H :: G :: HNil, H] = new Penultimate[H :: G :: HNil] { override type Out = H override def apply(in: H :: G :: HNil): Out = in.head } implicit def inductive[H, T <: HList, OutT]( implicit penult: Aux[T, OutT] ): Penultimate[H :: T] = new Penultimate[::[H, T]] { override type Out = OutT override def apply(in: H :: T): Out = penult.apply(in.tail) } } trait Penultimate[H <: HList] { type Out def apply(in: H): Out } It appears to work: scala> Penultimate[Int :: Int :: HNil] res1: net.Penultimate[shapeless.::[Int,shapeless.::[Int,shapeless.HNil]]] = net.Penultimate$$anon$1@3c37902d scala> Penultimate[Int :: HNil] <console>:16: error: could not find implicit value for parameter ev: net.Penultimate[shapeless.::[Int,shapeless.HNil]] Penultimate[Int :: HNil] ^ scala> Penultimate[HNil] <console>:16: error: could not find implicit value for parameter ev: net.Penultimate[shapeless.HNil] Penultimate[HNil] ^ But, is it a valid implementation of Penultimate? If not, what flaws does it have? Answer: More static types One big improvement you could make would be to have the Penultimate.apply method provide the output type in its signature. For example, with your current code you can write this: scala> val instance = Penultimate[Int :: String :: HNil] instance: Penultimate[shapeless.::[Int,shapeless.::[String,shapeless.HNil]]] = Penultimate$$anon$1@2819ef2f scala> instance(1 :: "" :: HNil) res0: instance.Out = 1 But not this: scala> val x: Int = instance(1 :: "" :: HNil) <console>:14: error: type mismatch; found : instance.Out required: Int val x: Int = instance(1 :: "" :: HNil) ^ If you want to keep track of the output type statically, you have to do it by hand: val instance = implicitly[Penultimate.Aux[Int :: String :: HNil, Int]] val x: Int = instance(1 :: "" :: HNil) Which works, but ugh. It's a lot easier to change your implementation of apply: def apply[H <: HList](implicit ev: Penultimate[H]): Aux[H, ev.Out] = ev Now this works just fine: scala> Penultimate[Int :: String :: HNil].apply(1 :: "" :: HNil): Int res1: Int = 1 …well, at least it works for hlists with two elements. When we add more things get weird: scala> val instance = Penultimate[Char :: Int :: String :: HNil] warning: there was one feature warning; re-run with -feature for details instance: Penultimate[shapeless.::[Char,shapeless.::[Int,shapeless.::[String,shapeless.HNil]]]]{type Out = ev.Out} forSome { val ev: Penultimate[shapeless.::[Char,shapeless.::[Int,shapeless.::[String,shapeless.HNil]]]] } = Penultimate$$anon$2@49393eeb scala> val x: Int = instance('a' :: 1 :: "" :: HNil) <console>:18: error: type mismatch; found : instance.Out (which expands to) ev.Out required: Int val x: Int = instance('a' :: 1 :: "" :: HNil) ^ This time apply is fine, but the method that provides inductive instances isn't. You can fix it by giving its result type the same kind of treatment: implicit def inductive[H, T <: HList, OutT]( implicit penult: Aux[T, OutT] ): Aux[H :: T, OutT] = new Penultimate[H :: T] { override type Out = OutT override def apply(in: H :: T): Out = penult.apply(in.tail) } Now the following will work just fine: val instance = Penultimate[Char :: Int :: String :: HNil] val x: Int = instance('a' :: 1 :: "" :: HNil) Now we have useful result types for instances (i.e. result types that track the output type statically), and an improved apply that lets us make use of them. Point of style 1: DepFn1 This is a relatively minor point, but you could define your type class like this: import shapeless.DepFn1 trait Penultimate[H <: HList] extends DepFn1[H] This is essentially exactly the same (the Out and apply are still there—you're just getting them from DepFn1), but it's less verbose and clearer about the intent. Point of style 2: infix vs. not infix I'd personally avoid writing ::[H, T] in one place and H :: T in others—for a type with a symbolic name like :: I'd always use the infix version. If you prefer the non-infix version, that's also fine, I guess. Mixing them isn't fine, though. :) Point of style 3: don't just stick the override keyword everywhere This is again a matter of personal preference, but I'd drop the override keyword from both the type member and the apply implementations in the anonymous new Penultimate class definitions, since your implementations aren't actually overriding anything. Point of style 4: consistent type parameter names In several places you use H as a type parameter name for a head type parameter, but in the Penultimate trait definition itself you use it apparently to stand just for "hlist". I'd use L, which also has the benefit of being consistent with the L in the Aux type member. Point of style 5: explicit apply Now we're getting into super-nitpick territory, but in general if writing out x.apply(y) isn't necessary to avoid y looking like an explicit implicit parameter, etc., I'd just use x(y). Point of style 6: import order More nitpickery: : precedes H, so it's likely that if you're using something like Scalastyle it's going to complain about the import. Point of style 7: trait vs. abstract class For a type class like this that will almost certainly never need to be mixed in with another trait, I'd prefer to make it an abstract class, for the reasons given here. Point of style 8: unique instance names I'm not sure how strongly I'd be willing to stand by this one if pressed, but I've developed a distaste for type class instance names that I can't reasonably expect to be globally unique. It's very unlikely anyone will be importing the contents of the Penultimate type class here, but if they did, having something called inductive in scope is kind of unhelpful. At the very least I'd probably tack a Penultimate suffix on each method name. Maybe that's unreasonable. I don't know—it probably doesn't matter much either way. Other than that it looks pretty good to me!
{ "domain": "codereview.stackexchange", "id": 23936, "tags": "scala" }
Can phosphoric acid be used to substitute sulfuric acid in the synthesis of thymolphthalein?
Question: I am planning to synthesize thymolphthalein, a pH indicator. I am wondering if phosphoric acid can be used to substitute sulfuric acid in the preparation. I know it can catalyze Friedel-Crafts reactions, which are a part of the synthesis. Any advice would be appreciated. Answer: I used polyphosphoric acid and it worked.
{ "domain": "chemistry.stackexchange", "id": 16204, "tags": "organic-chemistry" }
JSON Lexer code
Question: How does the following look for a json lexer? Are there any things that can be improved upon? Does the pattern look general-purpose enough to be able to generalize it to make it into a useful program, beyond just my personal tokenization of json? import re TOKENS = [ # (name, regex) ('OPEN_BRACE', r'{'), ('CLOSE_BRACE', r'}'), ('OPEN_BRACKET', r'\['), ('CLOSE_BRACKET', r'\]'), ('COMMA', r','), ('SPACE', r'\s'), ('COLON', r':'), ('NULL', r'null'), ('TRUE', r'true'), ('FALSE', r'false'), ('NUMBER', r'-?(?:0|[1-9]\d*)(?:\.\d+)?(?:e[-+]\d+)?'), ('STRING', r'"[^"\\]*(\\"[^"\\]*)*"'), ('EOF', r'^$') ] class Token: def __init__(self, type, value): self.type=type self.value=value def __eq__(self, other): return other == self.value def __str__(self): return '<%s -- %s>' % (self.type, self.value) class Lexer: def __init__(self, input): self.input = input self.idx = 0 self.tokens = [] def pprint(self): print [str(token) for token in self.tokens] def getNextToken(self): substring = self.input[self.idx:] if self.idx < len(self.input) else '' for token in TOKENS: s = re.match(token[1], substring) if s: self.idx += s.end() token = Token(token[0], s.group()) self.tokens.append(token) return token raise RuntimeError("Unrecognized token at position %d -- '%s'" % (self.idx, substring[:5])) def parse(self): tok = True while tok: tok = self.getNextToken() if tok == '':break return self.tokens l = Lexer('{"name": "david"}') l.parse() l.pprint() Answer: Some basic advice. Use Python 3. Put some blank lines between your methods and functions to make the code easier to read and edit. Your Token class is a perfect candidate for a dataclass. It has a tiny number of attributes and is also well-suited to be immutable. It is handy for a Token to know where it came from. This is not required for lexing, but I would typically include a pos attribute in a Token class. That allows to to trace a token back to its origin during a debugging scenario. A Token should not have a sneaky definition of equality for no good reason. Your Token.__eq__() method says a string equals a token if their text values are the same. That's non-intuitive and the benefit it provides your program is tiny (it allows you to terminate the lexing loop with if tok == ''). Much better is to play by the book and stop lexing when you hit EOF. The code is just as easy to write and a lot more straightforward for the reader. Unless you have a reason for it, don't tokenize whitespace one space at a time. It spawns lots of unhelpful tokens that can be condensed to one. I converted your SPACE token definition to the following: ('WHITESPACE', r'\s+'), Pay careful attention to naming. A couple examples. (1) Your TOKENS are not actually tokens (ie, instances of the Token class). They are token definitions, or something along those lines. (2) A lexer does not parse; it tokenizes. Give its primary method a proper name like lex() or tokenize(). Speaking of lexing and parsing. A now-deleted comment implied that your lexer is ill-conceived because it fails to enforce the syntax rules of JSON. That is both incorrect and a common error when first trying build a lexer: we let our brains get ahead of ourselves and start smuggling higher-level concepts (like the syntax for JSON) into a low-level task (writing a lexer that converts text to narrowly-valid tokens). Your lexer should accept a sequences of valid tokens even if they are JSON gibberish. Token-defintion order matters. When lexing you have to take special care to attempt to match the token definitions in an order that will avoid confusion, which can occur if one definition embraces a simpler definition (for example, a quoted string can contain lots of other stuff). One strategy to avoid such problems it to attempt the "bigger" entities first. Even though I found no specific problems along these lines in your lexer, on general principle I rearranged the ordering of the token definitions. Your lexer generates a lot of substrings. Each time the next token is requested, you first have to create a string representing the rest-of-the-text (everything after self.idx). That's not necessary if you take advantage of the fact that compiled regular expression objects take an optional pos parameter telling them where to start matching. In the illustration below, I pre-compiled all of the regexes when defining TOKEN_DEFINITIONS. When to return information and where to accumulate it. Since the lexer is accumulating the tokens, it's not clear to me that Lexer.lex() should return anything (I opted for no). Another question is which method should accumulate the tokens? At least to my eye, that seems more appropriate for lex() than get_next_token(). Your quoted-string regex doesn't work correctly. What you want to match is easy to describe in words: " Initial double-quote. .*? Stuff, non-greedy (otherwise we'll go to the last double-quote). " Closing double-quote (details to follow). The tricky part is that closing double-quote. It cannot be preceded by a backslash. That calls for a negative-lookbehind. So the components of the necessary regex look like this: " .*? (?<!\\)" It can be confusing to test stuff like this because you have to correctly navigate the string processing happening at the level of your Python syntax. One strategy is to create a variety of quoted strings in Python, put them into a dict, use the json library to created valid JSON text, and then make sure that your lexer can handle it. Speaking of testing, set your programs up to facilitate testing. In a real project of my own, I would use proper unit tests, but even in a code review context I typically start by rearranging the author's code into a form that I can subject to experimentation and testing. As shown below, I created a top-level main() function and an easy way to add examples as I checked and edited your code. import re import json import sys from dataclasses import dataclass def json_simple(): # A simple chunk of JSON with various data types. d = dict( msg = "hello world", n = 99.34, status = True, other = None, ) return json.dumps(d, indent = 4) def good_tokens_bad_json(): # The lexer should accept this. Let the parser reject it. return ''' true null "hi" } 123 { ''' def json_quoting_example(): # Some strings with internal double-quotes and backslashes. examples = ( # Just quotes. r'__"foo"__', r'__"foo__', r'__foo"__', # Quotes with leading backslashes. r'__\"foo\"__', r'__\"foo__', r'__foo\"__', # Quotes with 2 leading backslashes. r'__\\"foo\\"__', r'__\\"foo__', r'__foo\\"__', ) # Convert those examples into a dict and then JSON text. d = { f'ex{i}' : ex for i, ex in enumerate(examples) } return json.dumps(d, indent = 4) def invalid_text(): return '''{"a": 123, blort: 99}''' EXAMPLES = dict( quoting = json_quoting_example(), goodbad = good_tokens_bad_json(), simple = json_simple(), invalid = invalid_text(), ) def main(): args = sys.argv[1:] + ['simple'] k = args[0] text = EXAMPLES[k] lex = Lexer(text) lex.lex() for tok in lex.tokens: print(tok) EOF = 'EOF' TOKEN_DEFINITIONS = [ # Try to match these bigger concepts first. ('QUOTED_STRING', r'".*?(?<!\\)"'), ('NUMBER', r'-?(?:0|[1-9]\d*)(?:\.\d+)?(?:e[-+]\d+)?'), # Everything else is atomic and simple, so no confusion to worry about. ('OPEN_BRACE', r'{'), ('CLOSE_BRACE', r'}'), ('OPEN_BRACKET', r'\['), ('CLOSE_BRACKET', r'\]'), ('COMMA', r','), ('WHITESPACE', r'\s+'), ('COLON', r':'), ('NULL', r'null'), ('TRUE', r'true'), ('FALSE', r'false'), (EOF, r'$') ] TOKEN_DEFINITIONS = [ (type, re.compile(pattern)) for type, pattern in TOKEN_DEFINITIONS ] @dataclass(frozen = True) class Token: pos: int type: str value: str class Lexer: def __init__(self, text): self.text = text self.pos = 0 self.tokens = [] def lex(self): while True: tok = self.get_next_token() self.tokens.append(tok) if tok.type == EOF: break def get_next_token(self): for tok_type, rgx in TOKEN_DEFINITIONS: m = rgx.match(self.text, pos = self.pos) if m: value = m.group() self.pos += len(value) return Token(self.pos, tok_type, value) chunk = self.text[self.pos : self.pos + 20] msg = f'Unrecognized token: position={self.pos} content={chunk!r}' raise ValueError(msg) if __name__ == '__main__': main() Postscript: my regular expression for quoted strings is also bad. It fails when the string actually ends with a backslash. I believe that this answer shows how to do it correctly (but I did not test it extensively, which one really must do this these sorts of things). Here are the components of the regular expression broken down and applied to your situation (double-quoted strings only): " # Opening quote. ( (\\{2})* # Just an even N of backslashes. | # OR ... ( .*? # Stuff, non-greedy. [^\\] # Non backslash. (\\{2})* # Even N of backslashes. ) ) " # Closing quote.
{ "domain": "codereview.stackexchange", "id": 44255, "tags": "python, python-2.x" }
Does reduction from an NP-complete problem to some problem $X$ imply that $X\in NP$?
Question: I am having problems resolving the following question: Given some problem $X$. If there exists a polynomial time reduction from (for example) $\mbox{SAT}$ to $X$, $(\mbox{SAT} \leq_{p} X)$ and since we know that $\mbox{SAT}$ is $\mbox{NP-complete}$, to show that $X$ is $\mbox{NP-complete}$ is it necessary to show that $X\in \mbox{NP}$ via some third party algorithm? If yes, then why? Answer: the reduction only shows that X is at least as hard as SAT (NP-HARD). This could mean that X is in a class suspected to be harder than NP such as PSPACE or EXPTIME. To show that X is NP-complete you must show that it is also in NP. If you try it out you will see that you can easily reduce SAT to problems in EXPTIME that are not suspected to be in NP. The idea being that your reduction shows that X is at least as hard as SAT, but there are classes of problems harder than NP problems which X could fall into.
{ "domain": "cs.stackexchange", "id": 996, "tags": "complexity-theory, terminology, reductions, np" }
Orbital pendulum (librating moon dumbell model)
Question: Consider a moon orbiting its planet on a circular orbit. The moon is tidal locked to its planet, and has two permanent bulges, not exactly aligned with the planet. According to Newton's theory of gravitation, the moon should oscillates around its equilibrium alignment with the planet. I'm considering a simple moon represented by two small parts, with gravitationnal force acting on each part. The line joining both parts is confined in the orbital plane only, for simplicity. The moon should behaves like a pendulum. For very small angular displacements $\vartheta$, I've found this differential equation : \begin{equation}\tag{1} \ddot{\vartheta} + \frac{3 G M}{r_{\text{cm}}^3} \, \vartheta = 0, \end{equation} where $M$ is the planet's mass, and $r_{\text{cm}}$ is the distance from the planet to the center of mass of the moon. This is the equation of harmonic oscillations, and the oscillations angular frequency is thus \begin{equation}\tag{2} \Omega = \sqrt{\frac{3 G M}{r_{\text{cm}}^3}}. \end{equation} For our Moon, this gives a period of 15.8 days. On the surface of the Earth, holding a long rod by its center of mass, gives a period of 48.7 minutes (this is too long to be measurable, because of the friction that will stabilize the rod in its equilibrium vertical position. Also, the imprecision in the support would tilt the rod much faster in a direction or another). Now, I never saw this anywhere, and I need a confirmation that it is right. Searching with Google about moon's oscillations gives me nothing. I'm very surprised that the moment of inertia doesn't show in the angular frequency formula (2). EDIT : Here are some details. The moon and its bulges are modeled as a light rod with a spherical mass on each end (dumbell-like moon). The spin angular momentum is defined relative to the center of mass of the moon : \begin{equation}\tag{3} \vec{S} = m_1 \, \vec{\tilde{r}}_1 \times \vec{\tilde{v}}_1 + m_2 \, \vec{\tilde{r}}_2 \times \vec{\tilde{v}}_2, \end{equation} where $m_1 = m_2 = \tfrac{1}{2} \, m_{\text{moon}}$, and vectors with a tilde are defined relative to the center of mass frame. We have $\vec{\tilde{r}}_2 = -\, \vec{\tilde{r}}_1$ (see the picture below). Using the right hand rule for the cross product, I find this : \begin{equation}\tag{4} S = (m_1 \, \tilde{r}_1^2 + m_2 \, \tilde{r}_2^2) (\omega_{\text{rev}} - \dot{\vartheta}) \equiv I \, \omega_{\text{rot}}. \end{equation} The time derivative of the spin vector is equal to the torque applied on the moon : \begin{align} \frac{d\vec{S}}{dt} &= \vec{\tilde{r}}_1 \times \vec{F}_1 + \vec{\tilde{r}}_2 \times \vec{F}_2 \\[12pt] &= -\, \vec{\tilde{r}}_1 \times \frac{G M m_1}{r_1^3} \, \vec{r}_1 - \vec{\tilde{r}}_2 \times \frac{G M m_2}{r_2^3} \, \vec{r}_2 \\[12pt] &= -\, \frac{G M m}{2} \Big( \frac{1}{r_1^3} \, \vec{\tilde{r}}_1 \times (\vec{r}_{\text{cm}} + \vec{\tilde{r}}_1) + \frac{1}{r_2^3} \, \vec{\tilde{r}}_2 \times (\vec{r}_{\text{cm}} + \vec{\tilde{r}}_2) \Big) \\[12pt] &= -\, \frac{G M m}{2} \Big( \frac{1}{r_1^3} - \frac{1}{r_2^3} \Big) \, \vec{\tilde{r}}_1 \times \vec{r}_{\text{cm}} \tag{5} \end{align} Expanding the last parenthesis to lowest order gives \begin{equation} \frac{1}{r_1^3} - \frac{1}{r_2^3} \approx \frac{6 \, \tilde{r}_1}{r_{\text{cm}}^4} \, \cos{\vartheta}. \end{equation} Substituting this and (4) into equ. (5), using the small angle approximation : $2 \sin{\vartheta} \, \cos{\vartheta} \equiv \sin{2\vartheta} \approx 2 \vartheta$, and simplifying, gives equ. (1). Answer: Now, I never saw this anywhere, and I need a confirmation that it is right. Searching with Google about moon's oscillations gives me nothing. I'm very surprised that the moment of inertia doesn't show in the angular frequency formula (2). While your model is correct for your simple dumbbell model, it does not describe the Moon's librations. The Moon's librations are the result of the Moon's elliptical orbit rather than gravity gradient torque. The reason moments of inertia don't show up in your simple model is that they cancel in that simple model. As is well-known (well-known in the artificial satellite community), the gravity gradient torque on an orbiting body expressed in the body-fixed frame of the orbiting object is approximately $$\tau_{gg} = 3\frac{GM}{r^3}\hat r \times (\mathrm I \hat r)\tag{1}$$ where $\tau$ is the gravity gradient torque, $GM$ is the gravitational parameter of the central body, $r$ is the magnitude of the distance between the central body and orbiting body, $\hat r$ is the unit vector from the central body to the orbiting body (or from the orbiting body to the central body; changing the sign has no effect), expressed in the body-fixed coordinates of the orbiting body, and $\mathrm I$ is the orbiting body's moment of inertia tensor. Suppose the orbiting body is rotating about the orbital angular momentum axis, that this rotation axis is a principal axis, that its rotation rate is, on average, equal to the orbital rate, and that the principal axis with the smaller of the remaining two principal moments of inertia is nearly co-aligned with the displacement vector connecting the two bodies. Denoting $\hat x$ and $\hat y$ as the in-plane principal axes, with the $\hat x$ axis pointing more or less toward the central body, the unit vector $\hat r$ is $\cos\theta\,\hat x - \sin\theta\,\hat y$, where $\theta$ is small by assumption. The orbiting body's moment of inertia tensor is $I = \begin{bmatrix} A&0&0 \\ 0&B&0 \\ 0&0&C \end{bmatrix}$ where $A<B$, by assumption. Applying equation (1) yields a gravity gradient torque of $$\tau_{gg} = -3 \frac{GM}{r^3} (B-A)\sin\theta\cos\theta \hat z = -3 \frac{GM}{r^3} (B-A)\frac12\sin(2\theta) \hat z$$ Premultiplying the above by the inverse of the inertia tensor yields the angular acceleration: $$\ddot\theta = \mathrm I^{-1}\tau_{gg} = -3\frac{GM}{r^3} \frac{B-A}C\frac12\sin(2\theta) \approx -3\frac{GM}{r^3} \frac{B-A}C \theta$$ This is a simple harmonic oscillator with angular frequency $$\Omega = \sqrt{\frac{3GM}{r^3} \frac{B-A}C}$$ In the special case $A=0, B=C$ (which is the case for your dumbbell model, or for a slender rod), this simplifies to $$\Omega = \sqrt{\frac{3GM}{r^3}}$$ In the case of the Moon, the principal moments of inertia are very close to one another, making the term $\sqrt{(B-A)/C}$ very small, which in turn makes the oscillation period much larger than the Moon's orbital period. This does not explain the Moon's libration.
{ "domain": "physics.stackexchange", "id": 41220, "tags": "newtonian-mechanics, newtonian-gravity, harmonic-oscillator, moon, tidal-effect" }
Difference between delayed down-converted signal and a down-converted delayed signal
Question: I am having trouble understand what I think should be a pretty simple concept. Conceptually I can understand that a signal that has been down-converted, and then delayed in time is different than a signal that has been delayed in time and then down-converted. I am trying to compensate for this difference on an FPGA (I am down-converting the signal, delaying in time, and then up-converting) The way I see it, the delayed (and attenuated signal) looks like: $A e^{i(\omega_{\text{c}}-\omega_{\text{lo}})(t-\tau_1)} m(t-\tau_1)$ That is different from a down-converted delayed signal, so I need a phase correction constant: $\phi = e^{i\omega_{\text{lo}}\tau_1}$ Which gives: $A e^{i(\omega_{\text{c}}-\omega_{\text{lo}})t - i\omega_{\text{c}}\tau_1} m(t-\tau_1)$ So the correction is a function of the LO and the delay itself, right? I have my sampled signal in I and Q, but I need to multiply it by the correction before up-converting, and that is where I am lost. Answer: Let your original signal be (leaving out any constant multiplicative factor): $$s(t)=e^{i\omega_ct}m(t)$$ Then the down-converted signal is $$\tilde{s}(t)=e^{i(\omega_c-\omega_{lo})t}m(t)$$ and its delayed version is $$\tilde{s}(t-\tau)=e^{i(\omega_c-\omega_{lo})(t-\tau)}m(t-\tau)$$ whereas the delayed and down-converted signal is $$s(t-\tau)e^{-i\omega_{lo}t}=e^{i\omega_c(t-\tau)}e^{-i\omega_{lo}t}m(t-\tau)= \tilde{s}(t-\tau)e^{-i\omega_{lo}\tau}$$ So the correction factor $e^{-i\omega_{lo}\tau}$ indeed depends on both $\omega_{lo}$ and the delay $\tau$.
{ "domain": "dsp.stackexchange", "id": 1936, "tags": "filters, digital-communications, conversion" }
If you suspended your DNA like a rope in its 6ft full length, could you detect it if you waved your hand through it?
Question: I asked this question on biology.stackexchange.com (https://biology.stackexchange.com/questions/58151/if-you-suspended-your-dna-like-a-rope-in-its-6ft-full-length-could-you-feel-it/), and it was suggested to ask it here. Maybe a silly question but I was wondering about this. Trying to understand how small things are. I have read that the DNA in a single cell if stretched out, would be about 6 feet long. If you actually stretched it out and had something hold it - so that it was in a vertical line from about 6 ft to the floor, then: would it cast a visible shadow? if you waved your hand through it, would you be able to feel it? Answer: For the first question, the answer is no, unless you specifically design an experimental system to measure such a thing, which is going to be very hard and very costly. You have much larger objects you can't see with the naked eye. Your entire field of vision is covered by a whole zoo of microorganisms, much larger and much thicker than then DNA molecules that are inside each of them. But you don't see any of them. Stretching a DNA molecule to its full (and truly outstanding) length won't help what-so-ever. On the contrary, I think you can intuitively realize that by stretching you actually lose visibility rather than increasing it: what happens when you take a piece of paper, which is clearly a visible object, and then slice it very carefully to super thin slices and place them linearly? As the slices get thinner they are more difficult to spot, and so is their shadow. As for the second one, you're basically asking how strong the bonds that hold the constituents of the DNA strand are. The typical force required to break covalent bonds is in the order of nano-newtons. That's a billionth of the force required to press a key on your keyboard (oh mighty Wolfram Alpha...), which is very very small. To be able to feel the strand, the human touch sensitivity must be in this order of magnitude, otherwise you'd tear it before noticing it's there. But this is now once more a biological question, which I'd very much like to know the answer to myself! Human senses are actually pretty impressive, but I don't know if they are awesome enough for this task. EDIT: as for the answer hamilthj gave in Biology.SE, the difference there is that these reasearches are about "resolution", i.e. the ability to notice the existence of very small wrinkles on a surface. But there participants were allowed to touch the surfaces freely and exert as much force as they desired. Here you don't care much for the "resolution", i.e. you don't care about being able to tell exactly where the DNA strand touches your finger, but whether you can feel it or not. Obviously, if the DNA strand were supernaturally strong it could cut your finger off, but still you wouldn't be able to tell just by toucing were exactly does it contact your hand, and this is probably due to the finite nerve density or something of this sort.
{ "domain": "physics.stackexchange", "id": 39419, "tags": "biology" }
Implementation of glass filter for images
Question: This is exercise 3.1.39. from the book Computer Science An Interdisciplinary Approach by Sedgewick & Wayne: Write a program that takes the name of an image file as a command-line argument and applies a glass filter: set each pixel p to the color of a random neighboring pixel (whose pixel coordinates both differ from p’s coordinates by at most 5). Here is my program: import java.awt.Color; public class test { public static int[] chooseRandomNeighbor(int i, int j) { int[] chosenNeighbor = new int[2]; double r = Math.random(); if (r < 1.0/8.0) { chosenNeighbor[0] = i-1; chosenNeighbor[1] = j-1; } else if (r < 2.0/8.0) { chosenNeighbor[0] = i-1; chosenNeighbor[1] = j; } else if (r < 3.0/8.0) { chosenNeighbor[0] = i-1; chosenNeighbor[1] = j+1; } else if (r < 4.0/8.0) { chosenNeighbor[0] = i; chosenNeighbor[1] = j+1; } else if (r < 5.0/8.0) { chosenNeighbor[0] = i+1; chosenNeighbor[1] = j+1; } else if (r < 6.0/8.0) { chosenNeighbor[0] = i+1; chosenNeighbor[1] = j; } else if (r < 7.0/8.0) { chosenNeighbor[0] = i+1; chosenNeighbor[1] = j-1; } else if (r < 8.0/8.0) { chosenNeighbor[0] = i; chosenNeighbor[1] = j-1; } return chosenNeighbor; } public static Picture filter(Picture picture) { int width = picture.width(); int height = picture.height(); Picture filteredPicture = new Picture(width,height); // the following four for-loops make the dead frame for (int row = 0; row < height; row++) { Color color = picture.get(0,row); filteredPicture.set(0,row,color); } for (int row = 0; row < height; row++) { Color color = picture.get(width-1,row); filteredPicture.set(width-1,row,color); } for (int col = 0; col < width; col++) { Color color = picture.get(col,0); filteredPicture.set(col,0,color); } for (int col = 0; col < width; col++) { Color color = picture.get(col,height-1); filteredPicture.set(col,height-1,color); } // the real filtering takes place here for (int col = 1; col < width-1; col++) { for (int row = 1; row < height-1; row++) { int[] chosenNeighbor = chooseRandomNeighbor(row,col); Color color = picture.get(chosenNeighbor[1],chosenNeighbor[0]); filteredPicture.set(col,row,color); } } return filteredPicture; } public static void main(String[] args) { Picture picture = new Picture(args[0]); Picture filteredPicture = filter(filter(filter(filter(picture)))); filteredPicture.show(); } } Picture is a simple API written by the authors of the book. I checked my program and it works. Here is one instance of it: Input (picture of James McAvoy taken from Wikipedia who played in the movie Glass): Output: Is there any way that I can improve my program? Thanks for your attention. Answer: Interesting exercise and nice implementation, few suggestions on my side: The method chooseRandomNeighbor is only used by filter, so it can be set to private The name filter is too general for a method, a better name might be applyGlassFilter In Java the name of a class starts with a capital letter Optimization random neighboring pixel (whose pixel coordinates both differ from p’s coordinates by at most 5). The method chooseRandomNeighbor picks an adjacent random neighbor (which differ by at most 1) and then gets called 4 times. That implies creating 4 full images in memory. Wouldn't be better to directly pick a neighbor with maximum distance 5? To do that the method chooseRandomNeighbor needs to accept the width or height: int neighborColIndex = chooseRandomNeighbor(col,width); int neighborRowIndex = chooseRandomNeighbor(row,height); And this is chooseRandomNeighbor refactored: private static int chooseRandomNeighbor(int index, int max) { // Random delta between -5 and +5 int randomDelta = (int) ((Math.random() * (10)) - 5); // Add delta to index without overflowing the limit int neighborIndex = (index + randomDelta) % max; // If index is negative return 0 return neighborIndex < 0 ? 0 : neighborIndex; } Now the method filter can be called only once and only the new image will be created in memory. Side note: you are getting better and better, keep up the good work! Code Refactored public class Test { public static Picture applyGlassFilter(Picture inputPicture) { int width = inputPicture.width(); int height = inputPicture.height(); Picture outputPicture = new Picture(width, height); for (int col = 0; col < width; col++) { for (int row = 0; row < height; row++) { int neighborColIndex = chooseRandomNeighbor(col,width); int neighborRowIndex = chooseRandomNeighbor(row,height); Color c = inputPicture.get(neighborColIndex,neighborRowIndex); outputPicture.set(col, row, c); } } return outputPicture; } private static int chooseRandomNeighbor(int index, int max) { // Random delta between -5 and +5 int randomDelta = (int) ((Math.random() * (10)) - 5); // Add delta to index without overflowing the limit int neighborIndex = (index + randomDelta) % max; // If index is negative return 0 return neighborIndex < 0 ? 0 : neighborIndex; } public static void main(String[] args) { Picture inputPicture = new Picture(args[0]); Picture outputPicture = applyGlassFilter(inputPicture); outputPicture.show(); } }
{ "domain": "codereview.stackexchange", "id": 39345, "tags": "java, beginner" }
How to locally identify a cold front passage?
Question: I know that the passage of a cold front affects local conditions by decreasing the temperature and shifting the winds. Some precipitation could happen as well. How do software that analyze weather station data identify a cold front passage? Is there a certain change in temperature, wind, pressure, or other variable that allows the software to identify a front? Answer: A cold front lies in a trough of low pressure and separates air masses. As you mention in your question there are differences in temperature and the winds on either side of the front, though these can be subtle depending on latitude and season. A "classic" (mid-latitude NH) cold frontal passage might be recorded as southerly or southwesterly winds, increasing in in strength, temperatures rising and pressure falling. As FROPA occurs the pressure will bottom out and start to rise, winds shift to northwesterly or northerly, temperatures start to fall and skies clear. A "classic" (mid-latitude NH) warm frontal passage might be seen as temperatures stable, calm or weak southerly or easterly winds, high clouds with bases lowering over time and pressure falling. The FROPA will see pressure at its minimum and starting to rise, winds shifting to southerly and temperature warming. The common factors the changes in pressure, wind and temperature and can be used to determine frontal passage. Look for a pressure minimum, a change in temperature trend and a shift in wind. A cold frontal will also generally bring drier air, and a warm front humid air, so this can also be used. Here is a meteogram from SLC: In this plot, cold frontal passage occurs around 7Z, marked by a minimum pressure trending upward, dropping temperatures and dew points, winds shifting to northerly and skies starting to clear once the precipitation ends. Individual frontal passages will be different in exact details, but these general set of trends should help you out.
{ "domain": "earthscience.stackexchange", "id": 879, "tags": "meteorology, atmosphere, earth-observation" }
Calculating lens parameters
Question: I have a very bright LED light and I'd like to make this light focus so it forms around 5mm thick strong line (height can be arbitrary) on on an object about 150 mm away. I used a cylindrical lens for this purpose which has a focal length of 150mm and it seemed to achieve what I want, but it had to be held away from the light at about a distance of about 150 mm, which does not work for my experiment. I'm trying to understand how I can calculate the lens parameters needed so that I can get a front focal length of about 150mm but a back focal length of around 20mm or less. I'm not sure whether I'm using the terminology right, but I want the lens to be 20mm (or less) from the light and the focus distance to be 150mm away from the light. Answer: Suppose the object (the LED) is distance o from the lens and we want the image to be distance i from the lens: To get that to work, the focal length f of the lens must satisfy: $$ \frac{1}{f} = \frac{1}{o} + \frac{1}{i}$$ In your case, you want $o=20$ and $i=150-o=130 \text{ mm}$. To achieve that, you need a lens with focal length: $$ f = \frac{1}{\frac{1}{o} + \frac{1}{i}}$$ Substituting in the numbers: $$ f = \frac{1}{\frac{1}{20} + \frac{1}{130}}$$ which yields: $$ f = 17.3 \text{ mm}$$
{ "domain": "physics.stackexchange", "id": 26353, "tags": "optics, lenses" }
Java xPath: simple expression evaluation
Question: This code is using XPath to expose a library function that can check whether an XML file contains a string or an expression: private XPath xPath = XPathFactory.newInstance().newXPath(); public boolean applyFilter(String xml, String xPathExpression) { String result = xPath.evaluate(xPathExpression, new InputSource(new StringReader(xml))); return !(StringUtils.isEmpty(result) || "false".equals(result)); } Is there a better way to do that? I'd prefer to not use external libraries here. Answer: Like the other said in the comments, it's a bit hard to do a code review without context; I have a suggestion for you based on the current code. Since you seem to use the Apache Commons - lang3 library, you can use the org.apache.commons.lang3.BooleanUtils#toBoolean method to convert the string boolean. This method will return false when empty or null. Before public boolean applyFilter(String xml, String xPathExpression) throws XPathExpressionException { //[...] return !(StringUtils.isEmpty(result) || "false".equals(result)); } After public boolean applyFilter(String xml, String xPathExpression) throws XPathExpressionException { //[...] return !BooleanUtils.toBoolean(result); }
{ "domain": "codereview.stackexchange", "id": 38572, "tags": "java, xpath" }
Static in limbs
Question: I have noticed that while sitting in the Sukhasan posture(picture below) for a long time, my feet suddenly become all stiff and i am unable to move it. What I deduce from the experience is that it is static, though I fail to understand how it accumulated at my feet.Does anyone have an explanation for this? Answer: I have no idea how "static" comes into this, do you mean static electricity? Why would that be related? Anyway, what you are probably experiencing is simple numbness caused by your posture applying pressure to a nerve: In the image above, the right leg is likely to be pressing the the left which can cause paresthesia, more commonly known as "pins and needles". As explained in the NIH's paresthesia information page: Most people have experienced temporary paresthesia -- a feeling of "pins and needles" -- at some time in their lives when they have sat with legs crossed for too long, or fallen asleep with an arm crooked under their head. It happens when sustained pressure is placed on a nerve. The feeling quickly goes away once the pressure is relieved.
{ "domain": "biology.stackexchange", "id": 1604, "tags": "human-biology" }
If pressure in fluids is caused by the elastic collision of fluid molecules then why does the pressure increase with depth?
Question: We know that pressure in fluids increases with depth but why does it happen, if pressure is caused by the collision of particles? Answer: Pressure also has to do with the amount of fluid which is pushing onto the surface you are talking about. In a container, for example, a surface which is at a greater depth has a larger column of fluid above it (i.e. a greater weight pushing down on it.). The pressure on a surface at some depth $h$ is calculated as: $$P=P_o +\rho gh$$ (where $g$ is the gravitational field/acceleration in that region and $P_o$ is the atmospheric pressure.) If you mess around with this formula a bit you will realize that this quantifies pressure in terms of the weight of the fluid column above the surface you choose.
{ "domain": "physics.stackexchange", "id": 65281, "tags": "fluid-dynamics, pressure" }
Formal math notation of masked vector
Question: I'm struggling to write my algorithm in a concise and correct way. The following is an explanation for an optimizer's update step of part of a vector of weights (not a matrix in my case). I have a vector $\alpha \in \mathbb{R}^d$, and a set $S$ that includes some indices $1\leq i \leq d$ ($S \subseteq \{1,\dots, d\}$). Now, I want to denote that $\alpha$ is 0 for every index $i\in S$, and otherwise it's the value as in $\alpha_i$. At first I denoted it $\alpha_S$, but I'm not sure it is properly defined or understandable. I could use the following notation: $\alpha_S = \begin{cases} \alpha_j & j \in S\\ 0 & j \notin S \end{cases}$ But its line height is twice the size, and I want to avoid that. Is there any other formal, simplistic way to notate this correctly? Maybe some kind of a masking vector to be multiplied with $\alpha$? Thanks! Answer: Check out the indicator function $1_S(\cdot)$. In your case it would be fined as $$1_S: \{1, \ldots, d\} \rightarrow \{0, 1\}, j \mapsto \begin{cases} 1 & j \in S \\ 0 & \, \text{else} \end{cases}.$$ Multiplying this function with the respective values should give you what you are looking for. Edit: If I understand your comment correctly, the vector you are looking for is $$ \alpha_s = \sum\limits_{i = 1}^{d} \alpha_i e_i 1_{S^C}(i). $$ Here $e_i$ denotes the i-th unit vector of $\mathbb{R}^d$, $S^C$ is the complement $\{1, \ldots, d\} \setminus S$ in $\{1, \ldots, d\}$ and $1_{S^C}$ is the indicator function that is $1$ for $i \notin S$ and $0$ for $i \in S$.
{ "domain": "datascience.stackexchange", "id": 7595, "tags": "optimization, mathematics, notation" }
How does a vacuum oven work?
Question: I am doing some research on vacuum oven, but I cannot find out any website/book to tell me the theory. To my knowledge, it works better than regular oven. However, I have no idea why it is. Please help Answer: Vacuum Ovens works better than regular ovens because: It removes the source of contamination. For example, heating metals to high temperature causes rapid oxidation in regular ovens which is undesirable. It reduces the heat loss which is caused by convection. It allows quick cooling of the product as there are no air to hold heat around product. It allows precise control of uniform temperature in a certain area of oven. There's no air to screw it up.
{ "domain": "physics.stackexchange", "id": 5766, "tags": "temperature" }
Is the current same everywhere in a series circuit?
Question: When we say that the current flowing in a series circuit is the same, do we mean that the current is same in the entire circuit i.e, charge per unit time is the same in the entire circuit at any point of time, or do we mean that at each point in the circuit, the charge per unit time is the same? While explaining, please bear in mind that I'm a student of the tenth grade, who has just been introduced to charge, emf,etc.. I would really appreciate if there are easy explanations with no complex equations and diagrams. Answer: charge per unit time is the same in the entire circuit at any point of time, or do we mean that at each point in the circuit, the charge per unit time is the same? If the circuit has only one loop, then at any point in time, the current is the same at all points in that loop.
{ "domain": "physics.stackexchange", "id": 80083, "tags": "electric-circuits, electric-current, electrical-resistance" }
Merge Sort algorithm
Question: I just read and experimented with C++ implementation of the merge sort algorithm from the Wikipedia page. During the experiments I have slightly modified the source code and would like to know how much the algorithm is improved (if it is). //! \brief Performs a recursive merge sort on the given vector //! \param vec The vector to be sorted using the merge sort //! \return The sorted resultant vector after merge sort is //! complete. vector<int> merge_sort(vector<int>& vec) { // Termination condition: List is completely sorted if it // only contains a single element. if(vec.size() == 1) { return vec; } // Determine the location of the middle element in the vector std::vector<int>::iterator middle = vec.begin() + (vec.size() / 2); vector<int> left(vec.begin(), middle); vector<int> right(middle, vec.end()); // Perform a merge sort on the two smaller vectors left = merge_sort(left); right = merge_sort(right); return merge(vec,left, right); } //! \brief Merges two sorted vectors into one sorted vector //! \param left A sorted vector of integers //! \param right A sorted vector of integers //! \return A sorted vector that is the result of merging two sorted //! vectors. vector<int> merge(vector<int> &vec,const vector<int>& left, const vector<int>& right) { // Fill the resultant vector with sorted results from both vectors vector<int> result; unsigned left_it = 0, right_it = 0; while(left_it < left.size() && right_it < right.size()) { // If the left value is smaller than the right it goes next // into the resultant vector if(left[left_it] < right[right_it]) { result.push_back(left[left_it]); left_it++; } else { result.push_back(right[right_it]); right_it++; } } // Push the remaining data from both vectors onto the resultant while(left_it < left.size()) { result.push_back(left[left_it]); left_it++; } while(right_it < right.size()) { result.push_back(right[right_it]); right_it++; } //show merge process.. int i; for(i=0;i<result.size();i++) { cout<<result[i]<<" "; } // break each line for display purposes.. cout<<"***********"<<endl; //take a source vector and parse the result to it. then return it. vec = result; return vec; } The following is my code: typedef std::vector<int> int_v; int_v Merge(int_v& vec, int_v& l, int_v& r) { int_v res; res.reserve(l.size() + r.size()); unsigned int li = 0; unsigned int ri = 0; if (l.size() > 1 && (l[l.size()-1] < r[0])) { res.insert(res.end(), l.begin(), l.end()); res.insert(res.end(), r.begin(), r.end()); return res; } while (li < l.size() && ri < r.size()) { if (l[li] < r[ri]) { res.push_back(l[li++]); } else { res.push_back(r[ri++]); } } while (li < l.size()) { res.push_back(l[li++]); } while (ri < r.size()) { res.push_back(r[ri++]); } vec = res; return vec; } int_v MergeSort(int_v& v) { if (1 == v.size()) { return v; } int_v::iterator m = v.begin() + v.size()/2; int_v l(v.begin(), m); int_v r(m, v.end()); l = MergeSort(l); r = MergeSort(r); return Merge(v, l, r); } The modifications are: res.reserve(l.size() + r.size()); This will help to avoid relocation of the vector each time when there will need to double the size to be able to store the next element. if (l.size() > 1 && (l[l.size()-1] < r[0])) { res.insert(res.end(), l.begin(), l.end()); res.insert(res.end(), r.begin(), r.end()); return res; } I think this will help to avoid the 'while' loops when just concatenation of two sides is enough. Running both versions Wikipedia's one and mine for five million randomly generated integers produces the following differences: Wikipedia's example: time ./a.out real 0m26.278s user 0m26.205s sys 0m0.064s Mine: time ./a.out real 0m22.129s user 0m22.026s sys 0m0.092s Answer: Overall comment. It would have been better if you had used iterators to implement the sort. It's a lot more versatile than using a specific container. Memory Allocation Your implementation requires a lot of dynamic memory allocation. int_v::iterator m = v.begin() + v.size()/2; int_v l(v.begin(), m); int_v r(m, v.end()); Each recursive call makes a copy of the data to be merged. So we get this progression: n + n/2 + n/4 + n/8 + n/16 .... => n(1 + 1/2 + 1/4 + 1/8 + 1/16.....) => 2n So you are using \$2n\$ size of data just through calling MergeSort and it is being allocated and deallocated as the std::vector is being used then destroyed on return. In Addition you are doing another memory allocation in Merge(): int_v res; res.reserve(l.size() + r.size()); Note By using iterators rather than containers, it becomes easy to avoid some of this copying. You just pass the ranges of the containers and do it in-place. Prefer to move rather than to copy vec = res; Here you are copying the contents of the array. Arrays can be moved (this means it swaps a couple of pointers rather than copying all the data). Since you are not using res after this point you should move it. vec = std::move(res); User defined types usually start with a capital typedef std::vector<int> int_v; To distinguish user defined types and objects. Proceed types with an initial capital letter. My Interface would have been: template<typename I> void mergeSort(I begin, I end) { auto size = std::distance(begin, end); auto mid = begin; std::advance(mid, size/2); mergeSort(begin, mid); mergeSort(mid, end); merge(begin, mid, end); } template<typename C> void mergeSort(C& cont) { mergeSort(std::begin(cont), std::end(cont)); }
{ "domain": "codereview.stackexchange", "id": 13537, "tags": "c++, algorithm, sorting, mergesort" }
Changing from tf::Transform to tf::StampedTransform
Question: Could someone try to change any part of my code in order to use tf::StampedTransform. I've been trying to just replace it in place of tf::Transform directly, it doesn't work. I should have been missing something I think. This is needed because I cannot see the base_link movement with respect to the world. I think the tf is not correctly published with the below code. sensor_msgs::PointCloud2 cloud; //Class variable // In a callback function { sensor_msgs::PointCloud2 c_tmp; static tf::TransformBroadcaster tfb; tf::Transform xform; xform.setOrigin(tf::Vector3(pose3D_LDD.pose.position.x, pose3D_LDD.pose.position.y, pose3D_LDD.pose.position.z)); xform.setRotation(tf::Quaternion(pose3D_LDD.pose.orientation.x, pose3D_LDD.pose.orientation.y, pose3D_LDD.pose.orientation.z, pose3D_LDD.pose.orientation.w)); tfb.sendTransform(tf::StampedTransform(xform, ros::Time(pose3D_LDD.header.stamp), "world", "base_link")); tfListener_.waitForTransform("world", "base_link", previous_scan_.header.stamp, ros::Duration(1.0)); try { projector_.transformLaserScanToPointCloud("laser", previous_scan_, c_tmp, tfListener_); if (!initialized_cloud_) { cloud = c_tmp; initialized_cloud_ = true; } else { pcl::concatenatePointCloud(cloud, c_tmp, cloud); ROS_INFO("From c_tmp: Got cloud with %u of width and %u of height", c_tmp.width, c_tmp.height); ROS_INFO("From cloud: Got cloud with %u of width and %u of height", cloud.width, cloud.height); } } Thanks in advance. Originally posted by alfa_80 on ROS Answers with karma: 1053 on 2012-02-02 Post score: 0 Answer: I do exactly the same thing, and it works for me. The only difference is that I put a "/" in front of all my frame_id's (so "world" becomes "/world"). That, and instead of ros::Time(pose3D_LDD.header.stamp), I just use pose3D_LDD.header.stamp directly. Originally posted by DimitriProsser with karma: 11163 on 2012-02-02 This answer was ACCEPTED on the original site Post score: 2 Original comments Comment by DimitriProsser on 2012-02-03: As long as the distance between /world and /base_link is not large, I'd set both target and fixed frames to /world Comment by alfa_80 on 2012-02-02: What frame did you check/tick each for Fixed Frame and Target Frame in your rviz? or in the above case supposedly?
{ "domain": "robotics.stackexchange", "id": 8091, "tags": "transform" }
Writing a better deploy script
Question: This is a script I've written to deploy the Elastic Stack. Can you help me improve it? Especially the parts called out with *** markings. deploy.sh: #!/usr/bin/env bash sudo sysctl -w vm.max_map_count=262144 #use the elastic utility to gen certs docker-compose -f create-certs.yml run --rm create_certs # Start the stack initially per Elastic documentation docker-compose up -d #run a password gen script to make some passwords docker exec elasticsearch /bin/bash -c "bin/elasticsearch-setup-passwords \ auto --batch \ --url https://elasticsearch:9200" | tee es_passes.txt #sub generated kibana and es passes into .env -> *** This could be better *** cat es_passes.txt | grep 'PASSWORD kibana' | awk '{print $4}' | xargs -I {} sed -r -i 's/(KIBANA_PASS=)\w/\1{}/gip' .env cat es_passes.txt | grep 'PASSWORD elastic' | awk '{print $4}' | xargs -I {} sed -r -i 's/(ES_PASS=)\w/\1{}/gip' .env #eliminate duplicate lines -> *** How can I do this better *** awk '!seen[$0]++' .env > .env_dedup mv .env_dedup .env #show the contents of .env cat .env #restart the stack after setting the passwords docker-compose stop docker-compose up -d .env: KIBANA_PASS=some_supersecure_kibana_pass ES_PASS=some_supersecure_elasticsearch_pass other files: docker-compose.yml create-certs.yml update: I have fixed the substitution lines. They now read: cat es_passes.txt | grep 'PASSWORD kibana' | awk '{print $4}' | xargs -I {} sed -r -i 's/^KIBANA_PASS=.*$/KIBANA_PASS={}/' .env cat es_passes.txt | grep 'PASSWORD elastic' | awk '{print $4}' | xargs -I {} sed -r -i 's/^ES_PASS=.*$/ES_PASS={}/' .env Answer: Shots from the hip, three decades since I seriously programmed shell notwithstanding: document your code - in the code. The comments presented are a good start - in the middle, irritatingly. What is the whole script useful for, how shall it be used? You can even have executable comments: if called incorrectly or with -h, --help (or even -?), print a Usage: to "standard error output"/file descriptor 2 Then there are things left open: Why tee to es_passes.txt instead of redirect, have sed print the pattern space? (I read Spanish_passes at first - the reason why in the following comment es may be as appropriate as elastic needed horizontal scrolling) with security related artefacts, assess security implications choose the right tool this does not just depend on task at hand and tools available, but on "craftsperson", too (Here, I might have chosen perl in the 90ies and Python in the current millenium century) the options and commands to sed speak of GNU sed • mention such in your question • consider using --posix don't use cat | command where command allows specifying input file(s) prefer using awks patterns over separate filtering (e.g.,grep) (unless input is massive): awk '/PASSWORD kibana|elastic/{print $4}' es_passes.txt … (not convinced piping to xargs -I is the way to proceed.) the conventional "unix" way to eliminate duplicate lines is uniq, preceded with a sort where global uniqueness is necessary and altering line sequence admissible.
{ "domain": "codereview.stackexchange", "id": 37779, "tags": "bash" }
How likely are caverns inside the mantle?
Question: Almost everyone wrongly assumes that the Earth's mantle is liquid, but it isn't (only the outer core is). Is it possible then that there are hollow spaces within the mantle, similar to caves in the crust? What could they look like and up to how much of the mantle could be hollow? What might be inside mantle caverns? Would they be filled with gas or rather vacuum? Answer: It is extremely unlikely that any hollow volumes exist in the mantle. The mantle is a convecting solid which can deform over long timescales. Let's assume that such a cavern did somehow form. Whatever it is filled it, would be of lower density than the surrounding rock. It would slowly rise upwards through the solid-yet-deformable mantle until it reaches a place where the rocks are brittle, not ductile. That place is the crust. And as you know, the crust is full of caverns and there is no problem with that.
{ "domain": "earthscience.stackexchange", "id": 2408, "tags": "plate-tectonics, crust, mantle, cavern" }
Relativity of simultaneity - An example
Question: I am trying to understand the relativity of simultaneity in different frames, and I am trying to work out an example. Suppose along the x-axis there are two points 2000m apart. Event A happens at t=0 and event B happens at $t=2\cdot10^{-6}s$ after event A happens in the rest frame. If there is an observer moving along the positive x-axis, how fast must he move in order to see the two events happen simultaneously? So a diagram might look like this: A------------------------------B Observer -> My understanding is that the observer should "see" the two events simultaneously if the information reaches him at the same time. Thus, if he stands somewhere between A and B such that after A happens, the information of A and B happening reach him at the same time, then he would think that A and B are simultaneous events. If my logic is correct, then he should stand somewhere to the right of the middle point between A and B. But the example is asking for the velocity of the observer. I am not sure how to do this since I think the initial position of the observer should matter as well (if it does matter, can we assume he starts at the left point?). Answer: Your logic is correct but for one misunderstanding right at the beginning. The observer is smart enough to know that just because the photons are received simultaneously doesn't mean they were emitted at the same time. The emitting of a photon and the receiving at a different time and different place are two distinct events, as explored further in this post, among others. Basically, you need to find a position and a velocity such that the observer infers that the photons were emitted simultaneously. The observer makes this inference by saying the travel time for a photon is the distance between his current position and the source, as measured in his moving frame, divided by $c$. In fact, you don't even need to solve for the position to get the velocity, but I'll let you crank through the appropriate Lorentz transformations.
{ "domain": "physics.stackexchange", "id": 56194, "tags": "special-relativity, reference-frames, observers" }
ffmpeg batch script for video resizing
Question: I have a few hundred mp4 files (thanks android =/) that I need to convert. I only want to convert videos that are too large (>= 1080p) and I do want to keep the exif Information so the timeline is not broken. I hope someone can look over the script to point me to some grave mistakes or give some improvement. Anything I am missing? Thanks in advance. resize() { echo "Filename $1" filename=$(basename -- "$1") extension="${filename##*.}" filename="${filename%.*}" new_filename=${filename}.${timestamp}.${extension} ffmpeg -v quiet -stats -i $1 -map_metadata 0 \ -vf scale=-1:720 -c:v libx264 -crf 23 \ -c:a copy $new_filename < /dev/null exiftool -TagsFromFile $1 "-all:all>all:all" -overwrite_original $new_filename } if [[ -d $1 ]]; then timestamp=$(date +%s) echo "Finding Video Files ..." exiftool $1/*.mp4 -if '$ImageHeight >= 1080' -p '$Filename' > /tmp/fl_$timestamp echo "Processing Video Files ..." while IFS= read -r line; do resize $line done < /tmp/fl_$timestamp rm /tmp/fl_$timestamp elif [[ -f $1 ]]; then resize $1 else echo "Argument missing" exit 1 fi Answer: Consider portable shell The only Bash feature we're using is [[ ]] for testing file properties. It's easy to replace [[ -d $1 ]] with [ -d "$1" ] and that allows us to stick with standard shell, which is more portable and lower overhead: #!/bin/sh Careful with quoting Most of shellcheck's output is due to failure to quote parameter expansions: 236052.sh:9:31: note: Double quote to prevent globbing and word splitting. [SC2086] 236052.sh:9:50: error: Delete trailing spaces after \ to break line (or use quotes for literal space). [SC1101] 236052.sh:10:5: warning: This flag is used as a command name. Bad line break or missing [ .. ]? [SC2215] 236052.sh:11:15: note: Double quote to prevent globbing and word splitting. [SC2086] 236052.sh:12:28: note: Double quote to prevent globbing and word splitting. [SC2086] 236052.sh:12:74: note: Double quote to prevent globbing and word splitting. [SC2086] 236052.sh:18:14: note: Double quote to prevent globbing and word splitting. [SC2086] 236052.sh:18:27: note: Expressions don't expand in single quotes, use double quotes for that. [SC2016] 236052.sh:18:53: note: Expressions don't expand in single quotes, use double quotes for that. [SC2016] 236052.sh:18:75: note: Double quote to prevent globbing and word splitting. [SC2086] 236052.sh:22:16: note: Double quote to prevent globbing and word splitting. [SC2086] 236052.sh:23:20: note: Double quote to prevent globbing and word splitting. [SC2086] 236052.sh:24:16: note: Double quote to prevent globbing and word splitting. [SC2086] 236052.sh:26:12: note: Double quote to prevent globbing and word splitting. [SC2086] Ironically, you do have quotes in some places they aren't strictly necessary, so it's unclear why you missed all these. Errors go to standard output echo "Argument missing" exit 1 That should be: echo >&2 "Argument missing" exit 1 The test here is slightly wrong: the argument may be present, but not the name of a plain file or directory. So I'd replace that with: elif [ -e "$1" ] echo "$1: not a plain file or directory" >&2 exit 1 elif [ "$1" ] echo "$1: file not found" >&2 exit 1 else echo "Argument missing" >&2 exit 1 fi It may be worthwhile to move that testing into the resize function, because at present we assume that the contents found in directory arguments are plain files (that said, we're covering a tiny corner case with that, so I wouldn't sweat it - just let the commands there fail). Don't assume previous commands succeeded In resize, if ffmpeg fails, there's little point running exiftool, so connect them with &&. Also consider removing the file if it was created with errors (so we're not fooled by a partly-written output into thinking this file doesn't need conversion). Avoid temporary files There's no need for the file /tmp/fl_$timestamp: we could simply use a pipeline there. Consider accepting more arguments Instead of only allowing a single argument (and ignoring all but the first), let the user specify as many files as needed; it's easy to loop over them using for. Handle directories using recursion Instead of the while loop, we could invoke our script recursively using xargs. I'll make it a separate function for clarity: resize_dir() { exiftool "$1"/*.mp4 -if '$ImageHeight >= 1080' -p '$Filename' | xargs -r -d '\n' -- "$0" || status=false } (xargs -r is a GNU extension to avoid running the command with no arguments. If this option isn't available, we'll need to modify the script so that passing no arguments isn't an error.) Modified code This is Shellcheck-clean, but I'm not able to test it (lacking the requisite directory of MPEG files). #!/bin/sh set -eu status=true fail() { echo "$@" >&2 status=false } # Resize a single file resize() { echo "Filename $1" filename=$(basename -- "$1") extension=${filename##*.} filename=${filename%.*} new_filename=${filename}.${timestamp}.${extension} if ffmpeg -v quiet -stats -i "$1" -map_metadata 0 \ -vf scale=-1:720 -c:v libx264 -crf 23 \ -c:a copy "$new_filename" < /dev/null && exiftool -TagsFromFile "$1" '-all:all>all:all' \ -overwrite_original "$new_filename" then # success true else # failed; destroy the evidence rm -f "$new_filename" 2>/dev/null fail "Failed to convert $1" fi } # Resize all *.mp4 files in a single directory # N.B. only immediate contents; not recursive resize_dir() { # shellcheck disable=SC2016 exiftool "$1"/*.mp4 -if '$ImageHeight >= 1080' -p '$Filename' | xargs -r -d '\n' -- "$0" || status=false } [ $# -gt 0 ] || fail "Usage: $0 FILE FILE..." timestamp=$(date +%s) for arg do if [ -d "$arg" ] then resize_dir "$arg" elif [ -f "$arg" ] then resize "$arg" elif [ -e "$arg" ] then fail "$arg: not a plain file or directory" else fail "$arg: file not found" fi done exec $status # true or false
{ "domain": "codereview.stackexchange", "id": 37209, "tags": "bash" }
Safe new/delete
Question: A student was having problems with memory management so I put together an overload of global operator new and global operator delete to explicitly check for memory leaks and freeing invalid memory. This uses boost/stacktrace.hpp to point out exactly where you messed up. It is just for educational and possibly debugging purposes: #include <boost/stacktrace.hpp> // boost::stacktrace #include <cstdio> // fprintf #include <type_traits> // decay_t #include <unordered_map> // unordered_map #include <utility> // move // An allocator that uses malloc as its memory source #include "MallocAllocator.h" // Hash map that uses malloc to avoid infinite recursion in operator new template<typename Key, typename T> using MallocHashMap = std::unordered_map<Key, T, std::hash<Key>, std::equal_to<Key>, MallocAllocator<std::pair<const Key, T>>>; // Stack trace that uses malloc to avoid infinite recursion in operator new using MallocStackTrace = boost::stacktrace::basic_stacktrace< MallocAllocator<boost::stacktrace::frame>>; // Memory allocation info with, address, size, stackTrace struct MemoryAllocation { // the constructor is so that we can use emplace in unordered_map MemoryAllocation(void const* const address_, std::size_t const size_, MallocStackTrace trace_) noexcept : address{ address_ } , size{ size_ } , stackTrace{ std::move(trace_) } {} void const* address; std::size_t size; MallocStackTrace stackTrace; }; // new/delete -> Object vs new[]/delete[] -> Array enum class AllocationType { Object, Array, }; // returns AllocationType::Object for AllocationType::Array and // AllocationType::Array for AllocationType::Object static constexpr AllocationType otherAllocType(AllocationType const at) noexcept { switch (at) { case AllocationType::Object: return AllocationType::Array; case AllocationType::Array: return AllocationType::Object; } } // Keeps track of the memory allocated and freed. template<AllocationType at> static MallocHashMap<void*, MemoryAllocation>& get_mem_map() { struct Mem // wrapper around std::unordered_map to check for memory leaks in // destructor { std::decay_t<decltype(get_mem_map<at>())> map; // return type ~Mem() noexcept { if (!map.empty()) { // If map isn't empty, we've leaked memory. for (auto const& p : map) { auto const& memAlloc = p.second; std::fprintf(stderr, "-------------------------------------------------------" "----------\n" "Memory leak! %zu bytes. Memory was allocated in\n%s" "-------------------------------------------------------" "----------\n\n", memAlloc.size, to_string(memAlloc.stackTrace).c_str()); } } } }; static Mem mem; return mem.map; } // test if the memory was allocated with new or new[] template<AllocationType at> static bool allocatedAs(void* const ptr) { auto& memmap = get_mem_map<at>(); auto const it = memmap.find(ptr); return it != memmap.end(); } template<AllocationType at> static void* // template for new and new[] new_base(std::size_t const count) { void* p = std::malloc(count); if (!p) throw std::bad_alloc{}; auto& mem_map = get_mem_map<at>(); mem_map.emplace(std::piecewise_construct, std::forward_as_tuple(p), std::forward_as_tuple(p, count, MallocStackTrace{ 3, 100 })); return p; } template<AllocationType at> static void // template for delete and delete[] delete_base(void* const ptr) noexcept { if (ptr) { // it's fine to delete nullptr if (!allocatedAs<at>(ptr)) { // check for invalid memory free std::fprintf( stderr, "-----------------------------------------------------------------\n" "Invalid memory freed memory at %p\n", ptr); if (allocatedAs<otherAllocType(at)>(ptr)) { auto constexpr myNew = at == AllocationType::Object ? "" : "[]"; auto constexpr otherNew = at == AllocationType::Array ? "" : "[]"; std::fprintf( stderr, "\tNote: this memory was allocated with `new%s` but deleted with " "`delete%s` instead of `delete%s`\n", otherNew, myNew, otherNew); } std::fprintf( stderr, "%s\n---------------------------------------------------------" "--------\n\n", to_string(MallocStackTrace{ 3, 100 }).c_str()); std::_Exit(-1); // If we've messed up, exit } std::free(ptr); // free the pointer get_mem_map<at>().erase(ptr); // remove from the map } } void* operator new(std::size_t const count) { return new_base<AllocationType::Object>(count); } void* operator new[](std::size_t const count) { return new_base<AllocationType::Array>(count); } void operator delete(void* const ptr) noexcept { delete_base<AllocationType::Object>(ptr); } void operator delete[](void* const ptr) noexcept { delete_base<AllocationType::Array>(ptr); } MallocAllocator is a simple allocator that uses malloc to avoid operator new calling itself recursively for it's own bookkeeping purposes. Here's MallocAllocator.h: #ifndef MALLOC_ALLOCATOR_H #define MALLOC_ALLOCATOR_H #pragma once // Won't hurt #include <cstdlib> // malloc/free #include <stdexcept> // bad_alloc template<class T> struct MallocAllocator { using size_type = std::size_t; using difference_type = std::ptrdiff_t; using value_type = T; MallocAllocator() noexcept = default; MallocAllocator(const MallocAllocator&) noexcept = default; template<class U> MallocAllocator(const MallocAllocator<U>&) noexcept {} ~MallocAllocator() noexcept = default; T* allocate(size_type const s, void const* = nullptr) const { if (s == 0) return nullptr; T* temp = static_cast<T*>(std::malloc(s * sizeof(T))); if (!temp) throw std::bad_alloc(); return temp; } void deallocate(T* p, size_type) const noexcept { std::free(p); } }; #endif // !MALLOC_ALLOCATOR_H I am well aware that this is not thread-safe because of the static map. This should be enough for simple debugging and educational purposes, but I'd be happy to hear if you have comments about improving thread-safety. Answer: MallocAllocator(const MallocAllocator&) noexcept = default; //... ~MallocAllocator() noexcept = default; These two will be defined implicitly anyway. I suggest following the rule-of-zero and not declaring them at all. It will not make a difference here, but as general rule this is relevant, because e.g. the declared destructor inhibits declaration of the implicit move operations. The Allocator requirements require that MallocAllocator<T> and MallocAllocator<U> be comparable with == and != and that the comparison indicates whether the two instances can be used to deallocate the other's allocations. So you should add: template<class T, class U> bool operator==(MallocAllocator<T> const&, MallocAllocator<U> const&) noexcept { return true; } template<class T, class U> bool operator!=(MallocAllocator<T> const&, MallocAllocator<U> const&) noexcept { return false; } (or similar) You probably should add using propagate_on_container_move_assignment = std::true_type; to MallocAllocator. Otherwise containers cannot generally statically assert that moving a container with this allocator does not require reallocation. static constexpr AllocationType otherAllocType(AllocationType const at) noexcept { switch (at) { case AllocationType::Object: return AllocationType::Array; case AllocationType::Array: return AllocationType::Object; } } This function is ill-formed in C++11, because control flow statements like switch were not allowed in constexpr functions. You would need to rewrite it as single return statement using the conditional operator. std::decay_t<decltype(get_mem_map<at>())> map; This is also ill-formed in C++11, because the _t helpers for type traits were only introduced in C++14. So use typename std::decay<decltype(get_mem_map<at>())>::type map; instead. In either case this looks very awkward to me and I would probably rather alias the type and type it twice, or if you decide to drop the C++11 support in favor of C++14, you might want to consider making the return type auto& and spelling out the type for map instead. if (!map.empty()) { // If map isn't empty, we've leaked memory. The test is redundant. I don't think it really improves readability either. MallocStackTrace{ 3, 100 } These are magic constants that should be defined as named variables instead. Probably it would also be a good idea to wrap this construction into a function that doesn't take any parameters or has defaulted parameters, given that it is used twice. Your approach using a local static to construct and destruct the allocation map is not always safe when other static storage duration objects are used. Consider for example the test program: std::vector x; int main() { x.push_back(1); } The initialization of x will (dependent on the implementation) probably not call operator new, because no allocation is needed yet. Then push_back requires allocation and calls operator new for the first time, constructing the corresponding static Mem mem;. Now x's construction has completed before mem's and so mem will be destroyed before x will. This causes the allocation done by x to be reported as memory leak and it also causes undefined behavior when the destructor of x is called, because it will access mem when its lifetime has already ended. I am not sure whether there is any way to completely avoid this though. The best I can think of is to mimic #include<iostream>'s behavior and require that all translation units include a header file at the beginning which contains dummy global static objects that call get_mem_map for both allocation types in their initializer, but even then there may be static storage duration objects with unordered dynamic initialization, e.g. in class template specializations, which may execute before those. For thread-safety, assuming performance isn't really important, I would suggest simply to use a single global mutex and to scope-lock it in both delete_base and new_base.
{ "domain": "codereview.stackexchange", "id": 37629, "tags": "c++, c++11, memory-management" }
Official page of Weka for SVM java code
Question: I am using Weka to train a model from few days. I know Weka use Java code to implement a classifier. I also heard that Weka has some github pages to describe the java code for the classifiers. I like to know the SVM java code which is used in WEKA. I found few webpages describing Java code for SVM classifiers for WEKA. I can not understand which one is there official page. Providing me the link to SVM GitHub page would be very helpful. Thank you. Answer: The official Weka source code is stored in a local Gitlab git repository (not on Github). Note that there are two versions of SVM commonly used with Weka: The SMO classifier, source code here. The LibSVM wrapper: an external library that can be used in Weka (i.e. the source code is not part of Weka).
{ "domain": "datascience.stackexchange", "id": 11209, "tags": "classification, svm, weka" }
Hamiltonian invariant under time reversal symmetry
Question: I have an hamiltonian operator $$\hat{H}=-\frac{\hbar^2}{2m}\nabla^2+V(\hat{r})$$ for which there exists an antiunitary operator $\hat{O}$ such as $$OH^*O^{-1}=H$$ If $\psi(r,t)$ is a solution of the time dependent Schrödinger equation I have to show that the function $$\tilde{\psi}(r,t)=O \psi^{*}(r,-t)$$ is also a solution of that equation. My attempt was this: I start from $$i\hbar\frac{\partial}{\partial t}\psi(r,t)=H\psi(r,t)$$ and I firstly change the variable $t\rightarrow -t=t'$ then I took the complex conjugate of both sides of the equation so as to obtain $$i\hbar \frac{\partial}{\partial t'}\psi^*(r,-t')=H^{*}\psi^*(r,-t')$$ Then I apply the operator $O$ to both sides from the left: $$ O \left(i\hbar \frac{\partial}{\partial t'}\psi^*(r,-t')\right)=OH^{*}\psi^*(r,-t')=HO\psi^*(r,-t')$$ Now I don't understand how to proceed because in my opinion the antiunitarity property and the other requirement for $O$ are not sufficient to prove the assertion. My question arises reading a paragraph of the following book: Quantum Mechanics: A New Introduction, Konishi,Paffuti, pag 121, in which the authors state that the property $OH^*O^{-1}=H$ and the antiunitarity of O are sufficient to claim that $\tilde{\psi}$ is a solution, without giving other details. Is this procedure correct? If so is there a way to express the symmetry property (time reversal) of the Hamiltonian with a commutator? I know for example that if the symmetry is expressed by an unitary operator $S$ then $H$ is invariant under the symmetry if $[S,H]=O$, and I wonder if there is a similar property for the antiunitary operator $\hat{O}$ alternative to $OH^{*}=HO$. Update: if I assume instead that $[O,H]=O$ then maybe I can exploit the antilinearity of O and the fact that O anticommute with the time derivative operator(Does the time inversion operator commute or anticommute with the total time derivative) to say that: $$O\left(i\hbar \frac{\partial}{\partial t'}\right)=-i\hbar O\left( \frac{\partial}{\partial t'}\right)=i\hbar \left( \frac{\partial}{\partial t'}\right)O$$ But anyway I don't understand why it appears H* in the book. Answer: I think that you are confusing the unitary matrix $O$ that appears in the first quantized formula $$ OH^*O^{-1} =H $$ with the antilinear operator $T$ that acts as on the second quantised field operator $\psi$ as $$ T\psi T^{-1}= O^\dagger\psi $$ See, for example, appendix C2 in https://arxiv.org/abs/2009.00518.
{ "domain": "physics.stackexchange", "id": 87464, "tags": "quantum-mechanics, homework-and-exercises, operators, schroedinger-equation, time-reversal-symmetry" }
Black Bodies and appearing black
Question: I know a black body is an object that absorbs all wavelengths of light, and also emits all wavelength of light too back out, but if it emits all wavelengths of light, why does it appear black, as all wavelengths combined appear white? Also, with stars, I know they are assumed to be black bodies, but do they appear a certain colour just because they emit more of one wavelength than any other. Edit: Looking at the link in the comments, I kind of understand why black bodies don't have to be black, but what does,it mean for something to be the colour black, like a black radiator? is black paint a black body? Answer: A black body need not be of black color. Black body means a body which ABSORBS all wavelengths completely. This gives rise to two conclusions: A black body doesn't reflect any light. A mirror can't be a black body because when you shine a light beam on a mirror, it doesn't absorb it completely, because it reflects some wavelengths. A black body can't be a transparent object. Because when you shine a beam of light on a transparent object, it doesn't absorb it, instead it allows some wavelengths to go through it. Now, consider a situation where you have a black body in the sunshine. According to our definition, it will absorb all the wavelengths coming from the sun onto it. Saying that it absorbs those wavelengths, it means that it is absorbing their energy. According to Kirchhoff's law, a body having some finite temperature will emit ALL wavelengths of radiation, but the wavelengths themselves can be of different intensities like red is being emitted more intensely than the blue one. The wavelength which is emitted most intensely will be the color that body and I will call that wavelength "max intense wavelength". Our black body lying in the sunshine will also emit radiation of all kinds of wavelengths with different intensities and there would be a wavelength which would be emitted most intensely and that will determine the color of the black-body. If that max intense wavelength lies in the visible region then the black-body will have some visible color like blue or red. But when the max intense wavelength doesn't lie in the visible region, because we see only the visible range of the Electromagnetic spectrum, we will see only that wavelength which has maximum intensity in the visible region, though the overall maximum of intensity is out of range of visible light. When the max intense wavelength is far far away from the visible region then the visible wavelengths will have very low intensities and hence no color is visible and black-body looks black. For a black-body to look white, it will have to emit wavelengths corresponding to the visible region with nearly equal intensities because white light is composed of visible colors but with EQUAL intensities of all the colors. Our sun has its max intense wavelength lying in the visible region and human eyes are evolved to see the most intense wavelength which is visible light. In our situation of black-body absorbing radiation from the sun, it is radiating some energy on its own because of its finite temperature. So it is receiving some power from the sun and emitting some power on its own. When the temperature of black-body becomes constant then it means that power incoming will be equal to power outgoing. If your black paint absorbs all wavelengths completely then only it is a black-body.
{ "domain": "physics.stackexchange", "id": 41294, "tags": "visible-light, radiation, thermal-radiation" }
What is the purpose of the filtering the image data in the PNG file format
Question: I am reading the W3C description of the PNG file format, in particular section $9$ on filtering. The filter functions: None(x) : the identity filter Sub(x) : subtract the pixel value of $x$ by the pixel value in the position immediately before x Up(x): subtract the pixel value of $x$ by the pixel value in the scanline before the scanline containing $x$ Average(x): Subtract the pixel value of $x$ by the mean of the subtracted values described in Su and Up Paeth(x) : Substract the pixel value of $x$ by the result of the Paeth Predicator at three values, see the specification. are applied to different scanlines of an image; the filter function is applied to each pixel in a line. It is stated without justification that: Filtering transforms the PNG image with the goal of improving compression My question is why does applying these filters improve compression? Answer: The usage of a word filtering here is somewhat of a misnomer. The filtering operation is typically associated with waveform processing for various applications, as pulse shaping in the transmitter or noise suppression in the receiver. Image filters are also used, but primarily not for better compressibility of image files. In the context of your reference of PNG file format standard, it is possible that this operation would be more aptly named data preprocessing. A Wikipedia article on PNG file format is more explicit on the compressibility of filtered PNG image data: An image line filtered in this way is often more compressible than the raw image line would be, especially if it is similar to the line above, since the differences from prediction will generally be clustered around 0, rather than spread over all possible image values. To further clarify the effect of PNG data filtering on data compressibility, I cite the LZ77 algorithm article: LZ77 algorithms achieve compression by replacing repeated occurrences of data with references to a single copy of that data existing earlier in the uncompressed data stream. The less variability of "the differences from prediction" that are "clustered around 0", the more "repeated occurrences of data" exist "in the uncompressed data stream". Therefore, the more effective is the LZ77 algorithm's work. The LZ77 is an algorithm the PNG standard uses for compression. Notice also the statement from W3C description of the PNG file format: Filters are applied to bytes, not to pixels, regardless of the bit depth or colour type of the image. Again, the Wikipedia article is helpful to better understand this statement w.r.t. compressibility: An image line filtered in this way is often more compressible than the raw image line would be, especially if it is similar to the line above, since the differences from prediction will generally be clustered around 0, rather than spread over all possible image values. This is particularly important in relating separate rows, since DEFLATE has no understanding that an image is a 2D entity, and instead just sees the image data as a stream of bytes.
{ "domain": "dsp.stackexchange", "id": 9291, "tags": "image-processing" }
C function delimiates strings using a single character array
Question: I am a complete noob to C and I've shied away from using such a powerful language due to it's large learning curve and other complicated mechanisms. For my first minor project I plan to create a small HTTP client that requests for a webpage. Before I start, I need to create a function that can correctly parse a URL using the URI scheme. I devised this function to help me separate http from a host name like www.google.com by recognizing ://. Space and clock efficiency is are priorities of mine. I'm looking for any tips that would help someone who is new to C. int delimiateString(const char *string, const char *delimiator) { const char *buffer; int x, len = strlen(delimiator); for (buffer = string; *buffer != '\0'; buffer++) { if (*delimiator == *buffer) { for (x = 1; x <= len; x++) { if (*(delimiator+x) == *(buffer+x)) { if (x+1 == len) { return (buffer - string); } } else { break; } } } } return strlen(string); } Answer: Your function seems to do this: Find the first occurrence of "delimiator" (delimiter?) in some string. For example find the first occurrence of :// in http://example.com. If found, return the position where it was found If not found, return the length of the input string To find if a string is part of another string, you can use the strstr function. This is equivalent to your code but simpler: int delimiateString(const char *string, const char *delimiator) { char * found = strstr(string, delimiator); return found != NULL ? found - string : strlen(string); } For the record, your original code can be simplified, by eliminating an if around the inner for loop, and rearranging the nested ifs at the deepest level: for (buffer = string; *buffer != '\0'; buffer++) { for (x = 0; x < len; x++) { if (*(delimiator+x) != *(buffer+x)) { break; } if (x+1 == len) { return buffer - string; } } }
{ "domain": "codereview.stackexchange", "id": 12516, "tags": "c, strings" }
Anti-symmetry in Doppler Effect
Question: I know the formula $\nu = \nu_{0}\frac{v + v_{o}}{v - v_{s}}$ for the Doppler Effect and saw that it gives different results in the cases where: 1- The source is stationary and the observer moves towards the source with speed $v$, and 2- The observer is stationary and the source moves towards the observer with speed $v$ I also saw a couple of questions about this issue and all answers seem to point out that this asymmetry is a result of velocities being relative to the medium in which the wave propagates. I've even seen an answer that claims there is a formula that also accounts for the motion of the medium itself and it solves this "paradox". But I could not find the formula nor I could derive it myself; I found the same formula because velocities cancel and the same expression is left. Can anyone write the formula - the mighty formula that preserves symmetry - and the derivation? Thanks in advance! Answer: There is indeed an asymmetry (not anti symmetry) in the Doppler effect through a medium under exchange of the wave source and wave observer. What does stationary mean? With respect to whom? Those are questions that you will find yourself asking as you go deeper and deeper into physics. This asymmetry comes from the fact that one usually considers either the emitter or the observer stationary with respect to the medium. The equation for the (non-relativistic) Doppler effect reads: $$ \nu = \nu_0 \frac{v \pm v_r}{v \mp v_s} .$$ with $v$ the speed of sound in the medium, $v_r$ the speed of the receiver and $v_s$ the speed of the source. Let us say for the sake of simplicity, $v = 1$, and that the source is getting closer to an receiver with speed $v_s = 0.5$, so $$ \nu = \nu_0 \frac{1}{1 - 0.5} = 2\nu_0 .$$ If we swap receiver and source $v_s \to -v_r$, $v_r \to -v_s$, one would expect the Doppler effect to remain unchanged. It is however, not $$\nu = \nu_0 \frac{1+0.5}{1} = \frac{3}{2} \nu_0$$ The problem here came from the fact that the speed of sound through the medium changed when changing the frame of reference. When swapping the source and receiver, we changed who is stationary with respect to the medium. This is all an artifact consequence of Galilean relativity. After the Michelson-Morley experiment, Einstein arrived to a weird conclusion: The speed of light must be the same to any observer. This poses a change in perspective in how we see physics. Galilean relativity assumes (as anyone would, really) that after a change in the frame of reference space and time are left the same, and therefore the speed of propagation through the medium is allowed to change. If you force the speed through 'the medium' to stay the same (this is to paint a picture, there is no 'medium'. Light does not need a medium to propagate), you must allow space and time to change. The way these quantities change is given by Lorentz transformations$$ t' = \gamma(t - vx) \\ x' = \gamma(x - vt),$$ with $\gamma = \frac{1}{1 - v^2/c^2}$ the Lorentz factor. The way this reads is: You are an observer in your own reference frame. You observe a certain event happening at some time t, at some position x. Another observer, who moves in your reference frame at speed $v$, will observe that same event to have happened at some time $t'$, at some position $x'$. Ok. Going the Doppler effect now. The Doppler effect talks about waves and the easiest wave we can think about is the harmonic wave. A harmonic wave propagating at $c$, with angular frequency $\omega = 2\pi \nu$ and wave number $k = \frac{2\pi}{\lambda} = \frac{\omega}{c}$ is of the form $$\psi(t, x) = sin(\omega t - kx + \phi_0).$$ If we want this wave to change correctly under change of frame of reference, we need to impose something like $$\omega t - k x + \phi_0 = \omega' t' - k' x' + \phi_0'.$$ Since we know the relation between space and time for the different frames of reference from the Lorentz transformation, we can use that in our equation $$\omega t - k x + \phi_0 = \omega' \gamma(t - vx) - k' \gamma(x - vt) + \phi_0'\\ = \gamma(\omega' + k'v) t - \gamma(\omega' v + k')x.$$ By comparison, we need (recalling that $k = \frac{\omega}{c}$) $$\omega = \gamma(\omega' + k'v) = \gamma \omega' (1 + v/c) $$ Solving for $\omega'$ $$\omega' = \frac{\omega}{\gamma (1 + \frac{v}{c})} = \omega\frac{\sqrt{1 - \frac{v^2}{c^2}}}{1 + v/c} = \omega \frac{\sqrt{(1-\frac{v}{c})(1 + \frac{v}{c})}}{\sqrt{(1-\frac{v}{c})^2}}=\omega \sqrt{\frac{1 + \frac{v}{c}}{1 - \frac{v}{c}}} = \omega \sqrt{\frac{c + v}{c - v}}$$ Or equivalently, $$\nu = \nu_0 \sqrt{\frac{c + v}{c - v}}.$$ This is your symmetric Doppler effect. Or better put, the relativistic Doppler effect. By the way, if you are interested, under the assumption of what should and should not change under frame of reference, one can talk about many types of Doppler shifts. The most famous are (the just calculated) relativistic Doppler effect, the gravitational redshift, and cosmological redshift. These are all consequences of something called 'covariance', or 'the fact that physics is unimpressed by your choice of coordinates'.
{ "domain": "physics.stackexchange", "id": 99701, "tags": "doppler-effect" }
Is the annihilator appearing in linear algebra books the same as the one of second quantization?
Question: I have seen in some linear algebra textbooks such as Hoffman & Kunze, Friedberg & Insel & Spence, or Advanced Linear algebra by Roman the definition of annihilator. Here I take the definition from Friedberg for a vector*: Let $T$ be a linear operator on a finite-dimensional vector space $V$, and let $x$ be a nonzero vector in $V$. The polynomial $p(t)$ is called a $T$-annihilator of $x$ if $p(t)$ is a monic polynomial of least degree for which $p(T)(x) = 0$. It is quite abstract so I am wondering if it corresponds, or has anything to do, with the annihilator used in second quantization. Wether the annihilator of second quantization is an extension when going to infinite dimensions or not. If the response is negative I would like to know wether there is a formal mathematical object behind it or it is a new construct that did not exist before in mathematics. * There is also a definition for sets. Answer: Well, yes, if we identity $T \leftrightarrow a$ with an annihilation operator; the vector space $V$ with an infinite-dimensional Fock space; $x \leftrightarrow |\Omega \rangle$ with the vacuum state; and the polynomial $p\leftrightarrow {\rm Id}$ with the identity $t\mapsto t$.
{ "domain": "physics.stackexchange", "id": 51402, "tags": "linear-algebra, second-quantization" }
Can you charge a capacitor with only voltage (without current)? If No, then how does a capacitor correct power factor?
Question: Let me explain you why I am asking this question. The other day I was studying about power factor correction of a (step up or any) transformer. It said that on the output side of transformer's secondary, when the voltage is higher, there's no current flowing because of highest impedance, and when voltage starts to reverse, the impedance starts going down and when voltage is zero, the current becomes highest. So voltage and current are out of phase, when voltage exists, current doesn't exist, and when current exists, voltage doesn't exist. So what my understanding of PF correction with caps is that, when load is connected to the output of a transformer's secondary along with cap in parallel, the capacitor gets charged when the voltage is higher and current is lower or zero, and when the voltage in secondary drops, the current from secondary goes directly to load because cap in parallel is already fully or 63% charged, at that time when voltage in secondary is zero, the charged capacitor delivers the voltage to the load (and why not back to secondary?) and this way the load receives the voltage and current at the same time and it consumes most of the available power. So by my study, what I understand is for PF correction, the capacitor gets charged only wiht voltage and no current. However what I also studied is that there has to be current flowing in order to charge a capacitor. That's why I am confused and hereby asking whether capacitor gets charged without current and only with voltage, if they do, then how does actually capacitor corrects power factor? Answer: It said that on the output side of transformer's secondary, when the voltage is higher, there's no current flowing because of highest impedance, and when voltage starts to reverse, the impedance starts going down and when voltage is zero, the current becomes highest. It would be good to see the exact wording, because it sounds like you might be misunderstanding what was said. One way to visualize voltage, current, and charge in AC is to imagine a wheel whose axis is the origin of the Cartesian plane, and a red dot is marked on one point on the edge of the wheel. Now imagine the wheel rotating counter-clockwise. The y-coordinate of the red dot represent charge, and the x-coordinate represents current. Now imagine putting a blue dot on the wheel whose x-coordinate represents voltage. The angle between these two dots represents the phase between current and voltage. If the dots are on the same point, then they are completely in phase, and power will flow from the source to the destination. If they're on opposite sides of the wheel, then they're completely out of phase, and the power will flow in the opposite direction. If they're ninety degrees from each other, then they are orthogonal to each other, and the direction of the flow of power will alternate back and forth, and no net power will be delivered in either direction. What you are describing with "when voltage is zero, the current becomes highest" is this orthogonal case; when the blue dot is at the point (1,0), the voltage is zero, and the red dot is at the point (0,1), and so the current is maximum. It's theoretically possible for a circuit to have current and voltage be perfectly orthogonal, but it generally doesn't happen unless it's being deliberately sought. What I suspect is being described is a situation where they are slightly out of phase, so that when the voltage is zero, the current is non-zero, but not entirely maximal. The average power delivered is zero in the orthogonal case, maximum in the perfectly in phase case, and in between when the voltage and current are partially out of phase. So the purpose of PFC is to bring the phase between the two to as close to zero as practical. So voltage and current are out of phase, when voltage exists, current doesn't exist, and when current exists, voltage doesn't exist. This implies that whenever voltage exists, current doesn't exist. But that's impossible. What is possible is that some of the times (rather than all of the times) that voltage exists, current doesn't exist. So what my understanding of PF correction with caps is that, when load is connected to the output of a transformer's secondary along with cap in parallel, the capacitor gets charged when the voltage is higher and current is lower or zero, and when the voltage in secondary drops, the current from secondary goes directly to load because cap in parallel is already fully or 63% charged, at that time when voltage in secondary is zero, the charged capacitor delivers the voltage to the load (and why not back to secondary?) and this way the load receives the voltage and current at the same time and it consumes most of the available power. So by my study, what I understand is for PF correction, the capacitor gets charged only wiht voltage and no current. However what I also studied is that there has to be current flowing in order to charge a capacitor. First, as I explained before, there's generally going to be some current. You can't have a circuit where voltage and current and mutually exclusive. Second, there are different types of current. Any time a capacitor is charging, there is displacement current, which may correspond to an overall current, but it is different. If PFC is needed in the first place, then presumably the circuit has some inductance, and that inductance causes a displacement current. Ultimately, the purpose of the capacitor is to create a displacement current that cancels out the inductive displacement current.
{ "domain": "physics.stackexchange", "id": 94535, "tags": "electromagnetism, electric-current, voltage, capacitance, power" }
Binding energy for a uniform sphere bound by a Yukawa potential rather than an inverse-square-law potential?
Question: The binding energy of a uniform sphere that interacts through a force that follows the inverse square law is proportional to $a\frac{C^2}{R}$, where $C$ is whatever charge determines the strength of the force on the particle, such as mass or electric charge, $R$ is the radius, and $a$. For gravity, this looks like $\frac{3GM^2}{5R}$. What would the equation be for a Yukawa potential though? I thought the equation might be $a\frac{C^2e^{-bR}}R$, where $a$ and $b$ are constants, but when I predicted the binding energy by using an integral to calculate potential for a given radius and plotting the results, I couldn't get $a\frac{C^2e^{-bR}}R$ to fit the data. The equation I used to predict the binding energy of the sphere for a given radius was this: $$\frac{\int_0^R4\pi r^2\left(\int_{-R}^R\left(\int_0^\sqrt{1-x^2}\left(2\pi y \frac{e^{-\sqrt{(x-r)^2+y^2}}}{\sqrt{(x-r)^2+y^2}}\right)dy\right)dx\right)dr}{\left(\frac43\pi R^3\right)^2}$$ The outermost integral variable, $r$, represents a radius from the center of the sphere that is less than the radius $R$. The $4\pi r^2$ bit is because each radius $r$ also represents an equipotential shell. The rest of the equation treats $r$ like a distance to a certain point, and determines the potential at that point. $\int_{-R}^R\int_0^\sqrt{1-x^2}2\pi y...dydx$ maps each point in the sphere and calculates each point's "contribution" to the potential at point $r$. I divide the whole thing by the volume squared because I want the total "charge" to remain constant. Answer: Per this Math.SE post, given a Yukawa potential with range $1/a$, a spherical shell of mass $m$ with radius $r$ behaves like a point mass potential at the origin, except with mass $m~\sinh(ar)/(ar).$ If we nest these then the binding energy can be found as follows: bring a small mass from infinity to the origin for free, forming a little ball of density $\rho$ and radius $\delta r$, bring another small mass from infinity to the radius $\delta r$ to grow the sphere a little more, paying some energy, and so on. To keep a constant density the mass we have to move each time is $\mathrm dm=\rho~4\pi r^2\mathrm dr,$ while the mass already moved is $m(r)=\frac43\pi r^3~\rho$. So we need to know two things: First, what is the effective mass of a uniform ball, instead of a spherical shell? That's a straightforward integration by parts:$$m_{\text{eff}}(R)=\int_0^R\mathrm dr ~4\pi r^2\rho~\frac{\sinh(ar)}{ar} = \frac{4\pi\rho}{a^3}~\big(aR\cosh(aR)-\sinh(aR)\big) $$ Then assuming your potential looks like $$U(r)=-G\frac{m_1m_2}{r}~e^{-ar}$$ the binding energy is some integral $$E= G\int_0^R\mathrm dr~4\pi r^2\rho~m_{\text{eff}}(r)\frac{e^{-ar}}{r}$$ Calling $4\pi\rho/a^3=\mu$ this gives $$E= G\mu^2~a\int_0^{aR}\mathrm dx~x~e^{-x}(x \cosh x-\sinh x)$$This is technically not a hard integral, it is just a couple more integrations by parts and the integrand actually simplifies when you substitute in the definition of cosh/sinh... But it is a rather big expression so I trust Wolfram Alpha more than I trust my pen and paper, and Wolfram Alpha says it is $$E= {G\mu^2a \over 12}\left( 2 (aR)^3 - 3 (aR)^2 - 3 e^{-2 aR} (aR + 1)^2 + 3 \right)$$ Wolfram Alpha is also kind enough to give us a check on this expression via the Taylor series, which it says is$$E=G\mu^2a\left(\frac{(aR)^5}{15} -\frac{(aR)^6}{18}+\frac{(aR)^7}{35}-\dots\right)$$ which indeed limits in the infinite range $a=0$ case to $(3/5) GM^2/R$ (remember that $\mu\sim1/a^3$). So yeah, I am not surprised that you could not model it that easily, it has a rather complicated form!
{ "domain": "physics.stackexchange", "id": 84724, "tags": "homework-and-exercises, potential-energy, binding-energy" }
Wing as cantilever beam (beam-rod) model for aeroelasticity fluttering analysis
Question: I recently bumbped into a rather basic but interesting question on aeroelasticity. I've learned to derive the fluttering critical speed from Pines's theory but it involves some spring stiffness like for normal spring $K_h$ and torsion spring $K_t$. However, I want to see if I can derive the same thing if the wing is now treated as a continuous beam-rod model (i.e. torsion and bending). The equations of motion are: $ \frac{\partial^2}{\partial y^2} \left( EI \frac{\partial^2 h}{\partial y^2} \right) + m \frac{\partial^2 h}{\partial t^2} + m x_\alpha \frac{\partial^2 \alpha}{\partial t^2}+L=0$ $ -\frac{\partial}{\partial y} \left( GJ \frac{\partial \alpha}{\partial y} \right) + I_\alpha \frac{\partial^2 \alpha}{\partial t^2} + mx_\alpha \frac{\partial^2 h}{\partial t^2} - M = 0$ For simplicity, let $h(y,t)=0$ and $\alpha=s(y)e^{pt}$ so we can focus entirely on the torsion dynamic response. Let $L=qca_0(\alpha+\alpha_0)$ and $M=qcea_0(\alpha+\alpha_0)$. But now things get out of my control as I don't know how to solve for $p$ (to let its real part positive), given $s(y)$ unsolved too. Answer: By writing $\alpha=s(y) e^{pt}$, you've assumed that the solution is separable, i.e. that it can be separated into a part that depends only on y and another part that depends only on t. This is pretty common for this type of equation and it should work. The typical next step here would be to separate the variables in the equation. i.e. move everything that depends on s(y) (and its derivatives) to one side, and everything that depends on $e^{pt}$ (and its derivatives) to the other side. Then, since the left depends only on y, and the right only on t, the only way this can work if is both sides are equal to the same constant. You then just need to find that constant. Typically you'll proceed by assuming something like $s(y) = A \cos(kpy)+B \sin(kpy)$, where A and B are unknown constants and k is the wavenumber. Then just plug in and solve. There will be an infinite number of solutions to the equation. Each solution is a combination of k, A, B that solve the equation (and the boundary conditions), and represents an eigenmode of vibration. Typically, you'll keep only the first few (or maybe only first one) eigenmodes, and then find the time response of the modes. This page might help, http://www1.aucegypt.edu/faculty/mharafa/MENG%20475/Continuous%20Systems%20Fall%202010.pdf , or pick up any textbook on "vibrations of continuous systems".
{ "domain": "engineering.stackexchange", "id": 1536, "tags": "beam, mathematics, aerodynamics" }
invisible mesh in gazebo
Question: Hello, I build up an .urdf-file which can be correctly loaded in rviz. The Geometry is defined by meshes. When I load it in Gazebo the Robot is invisible. The Terminal shows no failure-messages except the warning that urdf will not be any longer supported (this was discussed in a different threat and seems to be unimportant). I simplified my .urdf file to one link to exclude possible problems: <robot name="TX60L"> <link name="base_link" > <inertial> <origin xyz="2 0 0" /> <mass value="1.0" /> <inertia ixx="1.0" ixy="0.0" ixz="0.0" iyy="100.0" iyz="0.0" izz="1.0" /> </inertial> <visual> <origin xyz="0 0 0" rpy="0 0 0" /> <geometry> <mesh filename="package://learning_urdf/meshes/tx60l/bt.stl" scale="0.001 0.001 0.001"/> </geometry> </visual> <collision> <origin xyz="2 0 0"/> <geometry> <box size="1 1 2" /> </geometry> </collision> </link> <gazebo reference="my_box"> <material>Gazebo/Blue</material> </gazebo> </robot> The box-example from the gazebo-tutorial can be displayed correctly. Any Suggestions how to get my model visible? Have I to deliver additional Informations? Many Thanks in advance Dominik Originally posted by viovio on ROS Answers with karma: 117 on 2012-10-26 Post score: 0 Answer: Some shots in the dark: Do you by any chance have an Intel GMA integrated graphics chipset? I know that RViz has problems displaying STL meshes on Intel chipsets, maybe Gazebo does too. Things to try: test your URDF on a computer with a dedicated graphics card (NVidia works well usually) convert your STL file to DAE using meshlab try if RViz can display your model (run gazebo and RViz, then enable "Robot model" visualization in RViz) I'm not sure whether Gazebo displays the "visual" or the "collision" model. Try also putting the mesh into the "collision" tag. This should be a no-brainer, but still: can Gazebo find your mesh file at the specified location? There should be an error message on the console if it can't. Edit: I've just tested your URDF file, and it looks like your minimal example was a little too minimal :-). You need at least one extra link for Gazebo to display anything. The following works for me: <robot name="TX60L"> <link name="base_link" > <inertial> <origin xyz="0 0 0" /> <mass value="1.0" /> <inertia ixx="0.001" ixy="0.0" ixz="0.0" iyy="0.001" iyz="0.0" izz="0.001" /> </inertial> <visual> <origin xyz="0 0 0" rpy="0 0 0" /> <geometry> <mesh filename="package://learning_urdf/meshes/tx60l/bt.stl" /> </geometry> </visual> <collision> <origin xyz="0 0 0" rpy="0 0 0" /> <geometry> <mesh filename="package://learning_urdf/meshes/tx60l/bt.stl" /> </geometry> </collision> </link> <joint name="dummy_joint" type="fixed"> <parent link="base_link" /> <child link="dummy_link" /> <origin xyz="2.0 0 0" rpy="0 0 0" /> </joint> <link name="dummy_link" > <inertial> <origin xyz="2 0 0" /> <mass value="1.0" /> <inertia ixx="0.001" ixy="0.0" ixz="0.0" iyy="0.001" iyz="0.0" izz="0.001" /> </inertial> <visual> <origin xyz="0 0 0"/> <geometry> <box size="0.4 0.4 0.4" /> </geometry> </visual> <collision> <origin xyz="0 0 0"/> <geometry> <box size="0.4 0.4 0.4" /> </geometry> </collision> </link> </robot> If you need more help, please also upload your STL file somewhere (I tested with one of my own STL meshes). Originally posted by Martin Günther with karma: 11816 on 2012-10-27 This answer was ACCEPTED on the original site Post score: 0
{ "domain": "robotics.stackexchange", "id": 11528, "tags": "ros" }
Is it possible for heat to flow from body having less heat energy to a body having more heat energy?
Question: Is it possible for heat to flow from a body having less heat energy to a body having more heat energy? Answer: tl;dr: Yes. Specific heat and temperature are different measurements. The specific heat of a material is a function of temperature that describes how much heat it takes to change the temperature of a material by a specific amount $\frac{dU}{dT}$. Statistical mechanics concerns itself with questions like this. If we integrate the specific heat function from $0K$ to the temperature in question, we find a measure of an object's 'heat energy'. Temperature, on the other hand, describes the tendency for an object to give up energy. In differential form, $\frac{dU}{dS}$, it's the change in internal energy with respect to entropy. A warmer object with less heat (tungsten, for example) may absolutely be more likely to give up heat than colder object with more heat (water, for example). As far as the heat pump explanations, I'd encourage you to pull the refrigerator off the wall and touch the radiation coils on the back - they are in fact warm.
{ "domain": "physics.stackexchange", "id": 16532, "tags": "thermodynamics" }
What are the conditions ensuring a two-qubit density matrix is positive semidefinite?
Question: I've seen some papers writing $$\rho=\frac{1}{4}\left(\mathbb{I} \otimes \mathbb{I}+\sum_{k=1}^{3} a_{k} \sigma_{k} \otimes \mathbb{I}+\sum_{l=1}^{3} b_{l} \mathbb{I} \otimes \sigma_{l}+\sum_{k, l=1}^{3} E_{k l} \sigma_{k} \otimes \sigma_{l}\right).$$ I wonder what condition should the matrix $E$ obey? For a one-qubit state, the density matrix satisfies $\newcommand{\tr}{{\operatorname{tr}}} \tr(\rho)=1$ and is positive semidefinite. And the general form is $$1/2\begin{pmatrix}1+z & x-iy\\x+iy & 1-z\end{pmatrix},$$ satisfying trace condition. As for positive semidefinite conditions, there's a theorem stated that a hermitian matrix is positive semidefinite iff its eigenvalue is not negative. So I calculate the eigenvalues of it and get the restriction that $x^2+y^2+z^2 \le 1$, which can be seen as exactly the Bloch sphere. Then I want to see the same thing happens in two qubits case. But I can only mimic the same reasoning and get the general form $$\rho=\frac{1}{4}\left(\mathbb{I} \otimes \mathbb{I}+\sum_{k=1}^{3} a_{k} \sigma_{k} \otimes \mathbb{I}+\sum_{l=1}^{3} b_{l} \mathbb{I} \otimes \sigma_{l}+\sum_{k, l=1}^{3} E_{k l} \sigma_{k} \otimes \sigma_{l}\right).$$ And when I try to calculate the eigenvalues of this matrix, even Mathematica showed a complex result. But if we think the separable case, easy to see that the vector $a$ and vector $b$ should have length less than 1. But I can't find the restriction on matrix $E$. To summarize, in general, the two qubits state can be stated as: $$\rho=\frac{1}{4}\left(\mathbb{I} \otimes \mathbb{I}+\sum_{k=1}^{3} a_{k} \sigma_{k} \otimes \mathbb{I}+\sum_{l=1}^{3} b_{l} \mathbb{I} \otimes \sigma_{l}+\sum_{k, l=1}^{3} E_{k l} \sigma_{k} \otimes \sigma_{l}\right).$$ What's the restriction on its parameters to make it a legal density matrix, i.e., trace condition and positive semidefinite condition? Answer: (General framework) The general form of this problem is the following. Take a generic Hermitian, unit-trace operator, $X\in\operatorname{Herm}(\mathcal X), \operatorname{Tr}(X)=1$, acting on some $N$-dimensional complex vector space $\mathcal X$. The set of such operators is an affine space of dimension $N^2-1$, embedded in the $N^2$-dimensional real vector space $\operatorname{Herm}(\mathcal X)$ of Hermitian operators. Any operator can be decomposed linearly with an operatorial basis. In particular, any unit-trace Hermitian operator can be decomposed linearly in an orthonormal basis of Hermitian traceless operators. This is the "generalised Bloch representation", which we can write as $$X = \frac{1}{N}\left(I + \sum_{k=1}^{N^2-1} c_k\sigma_k\right).$$ More precisely, we should write $c_k=c_k(X)$. These coefficients $c_k$ implement a (linear) isomorphism between the set of unit-trace Hermitian operators and the vector space $\mathbb R^{N^2-1}$. (Positivity constraint) If we want a positive semidefinite unit-trace Hermitian operator, write it $\rho$, we need to impose further restrictions on the coefficients $c_k$. More specifically, rather than these spanning a full linear space, they will now only cover a convex subset of $\mathbb R^{N^2-1}$. This means, in particular, that you can describe the corresponding set of states via its boundary. (Boundary ain't nice for $N>2$) This boundary is, in general, not very nice. For a single qubit you get a sphere, but as soon as you increase the dimensions, things get messier. For example, this boundary contains non-pure states (which doesn't happen for $N=2$). Similarly, even though all pure states still lie on a hypersphere (assuming a suitable parametrisation), they only cover some subsets of it. (Radial characterisation is doable) Nonetheless, as shown here, it is possible to get a decent characterisation of this boundary, by using "radial" coordinates. This requires computing the eigenvalues corresponding to a given direction, that is, the eigenvalues corresponding to a given linear combination of basis operators. This is numerically trivial to do for any given direction (assuming $N$ is not too big, of course), but finding an analytical expression working for all directions would be very complicated. It is worth noting that this amounts to describing the (convex) set of states via its support function. The conversion between this description and a more standard analytical characterisation is quite complicated, if doable at all. (So... what are the constraints?) Getting back to the question at hand: what does it really mean to find "restrictions for the coefficients $E_{jk}$"? Generally speaking, the boundary of the set of coefficients $c_k(\rho)$ corresponding to valid states $\rho$ is the solution set of $$f(c_1,...,c_{N^2-1})=0$$ for some function $f$. E.g. for $N=2$, we have $f(c_1,c_2,c_3)=c_1^2+c_2^2+c_3^2$. In higher dimensions, this $f$ is more complicated. For the case at hand, the coefficients are related to each other by some implicit relation $$f(a_1,a_2,a_3,b_1,b_2,b_3,E_{11},...,E_{33})=0.$$ This means that the viable range of any $E_{jk}$ depends on the value of all the other parameters. What you can do easily is find things like max and min of any parameter. This amounts to asking, e.g. what is the largest value of $E_{ij}$ that corresponds to any quantum state. Using the radial characterisation above, this can be seen to equal $1/|\lambda_{\rm min}(\sigma_i\otimes\sigma_j)|=1$. In fact, by similar reasoning, you can see that, using your operatorial basis built with products of Pauli matrices, every parameter lies in the interval $[-1,1]$. Note that this might seem to contradict the simple condition you get imposing $\operatorname{Tr}(\rho^2)\le1$, given in the other answer. That this is not a contradiction, is an interesting point per se. In fact, $\operatorname{Tr}(\rho^2)=1$ traces a spherical boundary that (1) surrounds the full set of states, and (2) is only touched by pure states. In other words, the answer $\max_\rho |E_{jk}|=1$ does't contradict the boundary given in the other answer, because the former is achieved by non-pure states (which is also easy to verify directly).
{ "domain": "quantumcomputing.stackexchange", "id": 2951, "tags": "quantum-state, mathematics, density-matrix" }
How to publish array of velocities?
Question: Hello guys, so I am very new to ROS and python. Now I understand the following: to publish on a topic, for example Twist() you write something like this and you publish one value for a couple of seconds (4 seconds in this case): 1 #!/usr/bin/env python 2 import rospy 3 from geometry_msgs.msg import Twist 4 5 def move(): 6 # Starts a new node 7 rospy.init_node('robot_cleaner', anonymous=True) 8 velocity_publisher = rospy.Publisher('/turtle1/cmd_vel', Twist, queue_size=10) 9 vel_msg = Twist() 10 11 vel_msg.linear.x = 0.5 12 vel_msg.linear.y = 0 13 vel_msg.linear.z = 0 14 vel_msg.angular.x = 0 15 vel_msg.angular.y = 0 16 vel_msg.angular.z = 0 17 18 now = rospy.Time.now() 19 20 while rospy.Time.now() < now + rospy.Duration.from_sec(4): 21 pub.publish(vel_msg) 22 23 move() But so instead of publishing one velocity for a couple of seconds I want now to publish like an array of velocities. For example vel_msg.linear.x = [0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9]. So every timestep there will be another velocity published until the last value is reached. How can you do this? And maybe another question: how do you know the timestep that ROS is using between the values of the array? Thanks in advance! Originally posted by logimaker on ROS Answers with karma: 3 on 2020-12-03 Post score: 0 Answer: Hi, you can create a python code that iterates through the array of velocities you want to send, and you can define a rospy.rate to ensure the velocities are sent at the rate you want them to. If you need help how to do that, I made this video that might help: https://www.youtube.com/watch?v=rqA7h37k9gw&ab_channel=TheConstruct Originally posted by rodrigo55 with karma: 156 on 2020-12-09 This answer was ACCEPTED on the original site Post score: 0 Original comments Comment by logimaker on 2020-12-11: Hi, this worked indeed. Thanks a lot! Comment by logimaker on 2020-12-11: I still do have another problem: So the python code iterates through the array of velocities but now at the same time I also want to subscribe to a topic ( for example /pose ) and save this in a text file until the code has iterated over all the velocities. Because now I am doing this manually in a new terminal with "rostopic echo -p /pose > data.txt" which is not very practical... Do you know how to do this? Thanks in advance! Comment by jayess on 2021-03-11: Can you please update your answer with main points from the video? If your video goes down or isn't available for certain regions then your answer/solution isn't as useful. Also, some prefer text to 14+ minute video
{ "domain": "robotics.stackexchange", "id": 35828, "tags": "ros, timestamp, ros-kinetic" }
Why is lead soft?
Question: As most of us know, lead, at room temperature, is quite soft. You can easily bend a lead rod. You can easily scrape a small piece off it with your nail, and you can even pull a thin long piece apart. This can't easily be done with iron. In both cases, a metallic bonding holds the atoms in place. Is lead soft because the metallic bonding in lead is weaker (which I can't imagine because metallic bindings are the same for every metal, I assume)? Sodium is soft too at room temperature, while mercury is even fluid. Does this mean that the metallic bindings in mercury and sodium are weaker too (than in hard metals)? Solid mercury is soft too. So what makes lead soft? Answer: Broadly, lead isn't very well bonded (we know this because of its relatively low melting temperature of 327°C), and its bonding in the solid state is face-centered cubic (FCC), which offers a large number of slip systems—12—with close spacing. (Notably ductile gold and copper, for example, are also FCC metals). Consequently, dislocations move easily through lead, resulting in a low yield stress.
{ "domain": "physics.stackexchange", "id": 79426, "tags": "solid-state-physics, material-science, physical-chemistry, crystals, metals" }
MoveIt moveit::core::RobotModel::RobotModel
Question: Hey there, I can not create a RobotModelConstPtr. I need this to create a RobotState (http://docs.ros.org/jade/api/moveit_core/html/classmoveit_1_1core_1_1RobotState.html#ac5944765b49ee074030c01010af36c07). A part of my Code: // Construct a kinematic model const RobotModelConstPtr kinematic_model; //need it later for RobotState robot_model::RobotModel kinematic_model = (RDFLoader.getURDF(), RDFLoader.getSRDF()); The error is " 'RobotModelConstPtr' does not name a type". This is a link to my hole code (https://www.dropbox.com/s/rko84pkkiigug9j/inv_node_end.cpp?dl=0). It would be perfect if someone can help me out. Thanks The whole code: #include <ros/ros.h> #include <fstream> #include <sstream> #include <urdf/model.h> // MoveIt! #include <moveit/robot_model/robot_model.h> #include <moveit/robot_state/robot_state.h> #include <moveit/rdf_loader/rdf_loader.h> int main(int argc, char **argv) { ros::init(argc, argv, "inv_node"); ros::AsyncSpinner spinner(1); spinner.start(); ros::NodeHandle nh; // Convert urdf file in a string std::ifstream u("youbot_arm.urdf"); std::stringstream su; su << u.rdbuf(); // upload the urdf to the parameter server nh.setParam("robot_description", su.str()); // Convert srdf file in a string std::ifstream s("youbot.srdf"); std::stringstream ss; ss << s.rdbuf(); // upload the srdf to the parameter server nh.setParam("robot_description_semantic", ss.str()); // Initialize the robot model rdf_loader::RDFLoader RDFLoader(su.str(), ss.str()); // Construct a kinematic model const RobotModelConstPtr kinematic_model; //need it later for RobotState robot_model::RobotModel kinematic_model = (RDFLoader.getURDF(), RDFLoader.getSRDF()); ROS_INFO("Model frame: %s", kinematic_model->getModelFrame().c_str()); // RobotStat that maintains the configuration robot_state::RobotStatePtr kinematic_state(new robot_state::RobotState(RobotModel); kinemati_state->setToDefaultValues(); // choose JointGroup const robot_state::JointModelGroup* joint_model_group = RobotModel.getJointModelGroup("arm_1"); // Forward Kinematics kinematic_state->setToRandomPositions(joint_model_group); const Eigen::Affine3d &end_effector_state = kinematic_state->getGlobalLinkTransform("arm_link_0"); /* Print end-effector pose. Remember that this is in the model frame */ ROS_INFO_STREAM("Translation: " << end_effector_state.translation()); ROS_INFO_STREAM("Rotation: " << end_effector_state.rotation()); ros::shutdown(); return 0; } Originally posted by JonasG on ROS Answers with karma: 1 on 2018-05-23 Post score: 0 Original comments Comment by jayess on 2018-05-23: Can you please update your question with a copy and paste of your code? That way the question is self-contained. Comment by JonasG on 2018-05-23: I have updated my question. I hope the formatation is good enough. Answer: It looks like RobotModelConstPrt is declared in http://docs.ros.org/jade/api/moveit_core/html/robot__model_8h_source.html by MOVEIT_CLASS_FORWARD(RobotModel); . This is in the moveit::core namespace, so the fully qualified type name would be moveit::core::RobotModelConstPtr Instead of: const RobotModelConstPtr kinematic_model; //need it later for RobotState Try: const moveit::core::RobotModelConstPtr kinematic_model; //need it later for RobotState Originally posted by ahendrix with karma: 47576 on 2018-05-23 This answer was ACCEPTED on the original site Post score: 2 Original comments Comment by JonasG on 2018-06-06: @ahendrix Do you have experience by using KDL PLugins for computing inverse kinematics? Comment by ahendrix on 2018-06-06: Nope. I don't know anything about MoveIt, I'm just good at reading and interpreting software documentation. Comment by saztyga on 2020-08-31: @ahendrix Sir can you suggest me any tutorial where i can learn how to interpreter c++ documantation
{ "domain": "robotics.stackexchange", "id": 30889, "tags": "ros, moveit, ros-hydro" }
Symmetries of a differential equation, its solutions and hydrogen atom
Question: A symmetry of a differential equation need not be shared by its solutions. However, under that symmetry, the one solution goes to another. For example, consider the time-independent Schrodinger equation (TISE) $H\phi=E\phi$ of an one-dimensional SHO. The TISE is invariant under reflections i.e. $x\to -x$ but the solutions $\phi(x)$ under reflections behave as $$\phi(x)\to\phi(x)~~~~~~~~ {\rm or}~~~~~~~ \phi(x)\to -\phi(x).$$ If the above statements are generically true, then the rotational symmetry of the TISE of the hydrogen atom must also exhibit the same feature. For instance, the wavefunction of the $2p_x$ (or $2p_y$) orbital, under some rotation, must be be transformable to $2p_z$ orbital. However, I don't think that is possible or is it? If possible, what is that operator which takes, for example, $\psi_{2p_x}\to\psi_{2p_z}$? Answer: The hydrogen hamiltonian can be written as $$ H = \frac{p_r^2}{2m} + \frac{L^2}{2mr^2} - \frac{e^2}{r} $$ where $p_r$ is the radial component of the momentum. Since $H$ depends on $L^2$, $p_r$ and $r$, the hamiltonian commutes with every component of $\mathbf L$: $$ [H, \mathbf L] = 0, $$ which in turn means we can simulteneously diagonalize $H$, $L^2$ and one component of $\mathbf L$ (say, $L_z$). We can now introduce the rotation operator: $$ D(\phi, \mathbf n) = \exp \left (- \frac{i \mathbf L \cdot \mathbf n \phi}{\hbar} \right ), $$ which rotates the states by an angle $\phi$ around the unit vector $\mathbf n$. We can transform the hamiltonian under a rotation in the following manner: $$ H \to H' = D(\phi, \mathbf n)^\dagger H D(\phi, \mathbf n). $$ But $H$ commutes with $\mathbf L$, so $H$ also commutes with $D$, and thus $H' = D^\dagger D H = H$. We proved the hamiltonian is invariant under rotations. This means that some degeneracies will occur, i.e., some states will share the same energy. Note however that unlike I said previously (which was a mistake) you cannot rotate one state $|nlm\rangle$ to create one with different $m$ around the $z$-axis. Since the eigenstates of the hamiltonian are also eigenstates of $L_z$, the rotation operator will only introduce a phase factor on the state: $$ D(\phi, \mathbf{\hat z})|nlm\rangle = \exp\left (-\frac{iL_z \phi}{\hbar} \right ) |nlm\rangle = e^{-im\phi}|nlm\rangle $$ But states with different $m$ are orthogonal (their inner product is zero), which is clearly not the case for the rotated state above: $$ \langle nlm | \big(D |nlm\rangle\big) = e^{-im\phi} \neq 0. $$ Now, rotations around the $x$ or $y$-axis will change the value of $m$ since $|nlm\rangle$ is not an eigenstate of $L_x$ or $L_y$. Indeed, you can write $L_x$ and $L_y$ in terms of the ladder operators $L_\pm = L_x \pm i L_y$ which increase/decrease the value of $m$ to calculate the action of the rotation operator. The only thing I can guarantee you is in the end you will arrive at least in a linear combination of states with the same $n$ and $l$ but with different $m$'s.
{ "domain": "physics.stackexchange", "id": 55852, "tags": "quantum-mechanics, symmetry, schroedinger-equation, hydrogen, differential-equations" }
transformations in ros / rviz?
Question: hi, i'm quite new to ros and am using rviz to display my point cloud which i have manipulated a little bit using pcl. by manipulated i only applied a voxel grid thereby reducing the number of points. but my question is, how can i apply a transformation when using rviz? i was able to do it when using only pcl but now that i'm using ros and visualizing it all in rviz, i'm getting compiler errors for just #include pcl/common/transforms.h which is of course, stopping my transformation and translation from working. or maybe transformations and translations are not necessary in ros? but there must be a way right? thanks! Originally posted by liquidmonkey on ROS Answers with karma: 37 on 2012-02-16 Post score: 2 Answer: The pcl_ros package provides transforms for PCL point clouds. Typically, you would add a <depend package="pcl_ros"/> to your manifest.xml, then: #include <pcl_ros/transforms.h> Originally posted by joq with karma: 25443 on 2012-02-16 This answer was ACCEPTED on the original site Post score: 2 Original comments Comment by liquidmonkey on 2012-02-19: thanks very much, worked great!
{ "domain": "robotics.stackexchange", "id": 8261, "tags": "rviz, transform" }
Flipping the labels in a binary classification gives different model and results
Question: I have an imbalanced dataset and I want to train a binary classifier to model the dataset. Here was my approach which resulted into (relatively) acceptable performance: 1- I made a random split to get train/test sets. 2- In the training set, I down-sampled the majority class to make my training set balanced. To do that, I used the resample method from sklearn.utils module. 3- I trained the model, and then evaluated the performance of the model on the test set (which is unseen and still imbalanced). I got fairly acceptable results including precision, recall, f1 score and AUC. Afterwards, I wanted to try out something. Therefore, I flipped the labels in both training set and testing set (i.e. converting 1 to 0 and 0 to 1). Then I repeated the step 3 and trained the model again with flipped labels. This time, the performance of model dropped and I got much lower precision and f1 score on test set. Additional details: The model was trained with GridSearchCV using a LogisticRegression estimator. I have then two question: is there anything wrong with my approach (i.e. downsampling)? and how come flipping the label led into worse results? I have a feeling that it could be due to the fact that my test set is still imbalanced. But more insight will be appreciated. Answer: First I'd like to say that you're asking the right questions, and doing an experiment like this is good way to understand how things work. Your approach is not wrong by itself and the performance difference is not due to downsampling. Actually resampling rarely works well, it's a very simplistic approach to handle class imbalance, but that's a different topic. The second question is more important, and it's about what precision and recall mean: these measures rely on which class is defined as the positive class, thus it is expected that flipping the label would change their value. For example, let's assume a confusion matrix: A B <- predicted as class A 9 1 B 10 70 ^ true class Precision is the proportion of correct predictions (true positive, TP) among instances predicted as positive (TP+FP): if A = positive: 9/(9+10) = 0.47 if B = positive: 70/(10+70) = 0.87 Recall would also be different. The logic of these measures is that the task is defined with a specific class as "main target", usually the minority class (A in this example). So flipping the labels is like changing the definition of the task, there's no reason that the performance has to be the same. Note: accuracy would have the same value no matter the positive class, and this is why it's not recommended with an imbalanced dataset (it gives too much weigth to the majority class).
{ "domain": "datascience.stackexchange", "id": 11268, "tags": "python, classification, scikit-learn, class-imbalance, imbalanced-data" }
Why it is difficult to drink tea with a straw?
Question: It is easy to drink cold drinks, soft drinks with straw but when I tried to drink tea with straw then that was very unpleasant and even for time I lost the sense from my tongue. My question is why it is difficult to drink hot liquids with straw?(Drinking cold liquids is very pleasant!!!) Answer: I think user689's answer is basically correct, so you should regard this as just an extension/clarification of their answer. If you place a small volume of hot tea in contact with your tongue then the large thermal capacity of your tongue will cool the tea a lot and your tongue will heat up a little. This is essentially what happens when you sip tea. You pull in a certain volume of tea, this tea is spread out over the tongue and stays in contact with it for a second or so. In this time the tea cools and your tongue heats. However the heating of the tongue is relatively small because the heat from the tea is spread over a large area. If you suck the same volume of tea through a straw, then because the cross sectional area of the straw is small the velocity of the tea in the straw is high (as user689 points out) so the whole volume of the tea rapidly hits, and heats, a small area on the tongue. This causes much greater heating of that small area and scalds the tongue. Exactly what the sensory effects of the scald are I will leave to our medical/biological colleagues. This also suggests a reason why drinking cool fluids through a straw is pleasant. The same effect means that when drunk through a straw a cold drink causes more intense local cooling than if it was drunk without a straw.
{ "domain": "physics.stackexchange", "id": 14790, "tags": "thermodynamics, everyday-life" }
How the simulator work?
Question: Recently I focused on how to simulate in classical computer, and I found Qiskit offers qasmsimulator and statevector simulator. And others such as project Q also can simulate on classical computer. So is there a general way to simulate on classical computer? And what are differences among simulators? I mean actually it seems like we just need to multiply gate operation as matrixes. Answer: There are three major levels of simulation difficulty (broadly, there are a bunch of others, but these are the main levels.) Clifford simulators can simulate circuits composed of only Clifford elements on stabilizer states. This is classically efficient, since it is classically efficient to calculate the propagation of a Pauli operator through a Clifford gate. As a result, the simulator takes the stabilizers of the input state, propagates them through the circuit, and the resulting stabilizer group represents the final state. The idea that a quantum algorithm needs non-Clifford gates to be better than a classical one comes from the fact that a fully Clifford quantum algorithm could be simulated classically in polynomial time. The second level of simulation is State Vector simulation. In this case, we are basically doing what you mentioned in your question. We take an input state (of size $2^n$, where n is the number of qubits) and then apply gates to it through matrix multiplication. Due to the exponential size of the state, this requires resources exponential in the system size to be simulated, and as a result is not considered classically efficient. The only restriction on these simulations is that the gates must all be unitary and all states must be pure. The last level is Density Matrix simulation. Here, we store the full $2^n \times 2^n$ density matrix of the state. As a result we can simulate any quantum channel, and mixed states are permissible. However we now have an even bigger object to work with. These simulations are often necessary for doing work on simulating physical noise or other non-unitary processes, but are extremely limited in size due to their exponential resource requirements.
{ "domain": "quantumcomputing.stackexchange", "id": 1740, "tags": "quantum-gate, quantum-state, qiskit, programming, simulation" }
What is the difference between FASTA, FASTQ, and SAM file formats?
Question: I'd like to learn the differences between 3 common formats such as FASTA, FASTQ and SAM. How they are different? Are there any benefits of using one over another? Based on Wikipedia pages, I can't tell the differences between them. Answer: Let’s start with what they have in common: All three formats store sequence data, and sequence metadata. Furthermore, all three formats are text-based. However, beyond that all three formats are different and serve different purposes. Let’s start with the simplest format: FASTA FASTA stores a variable number of sequence records, and for each record it stores the sequence itself, and a sequence ID. Each record starts with a header line whose first character is >, followed by the sequence ID. The next lines of a record contain the actual sequence. The Wikipedia artice gives several examples for peptide sequences, but since FASTQ and SAM are used exclusively (?) for nucleotide sequences, here’s a nucleotide example: >Mus_musculus_tRNA-Ala-AGC-1-1 (chr13.trna34-AlaAGC) GGGGGTGTAGCTCAGTGGTAGAGCGCGTGCTTAGCATGCACGAGGcCCTGGGTTCGATCC CCAGCACCTCCA >Mus_musculus_tRNA-Ala-AGC-10-1 (chr13.trna457-AlaAGC) GGGGGATTAGCTCAAATGGTAGAGCGCTCGCTTAGCATGCAAGAGGtAGTGGGATCGATG CCCACATCCTCCA The ID can be in any arbitrary format, although several conventions exist. In the context of nucleotide sequences, FASTA is mostly used to store reference data; that is, data extracted from a curated database; the above is adapted from GtRNAdb (a database of tRNA sequences). FASTQ FASTQ was conceived to solve a specific problem arising during sequencing: Due to how different sequencing technologies work, the confidence in each base call (that is, the estimated probability of having correctly identified a given nucleotide) varies. This is expressed in the Phred quality score. FASTA had no standardised way of encoding this. By contrast, a FASTQ record contains a sequence of quality scores for each nucleotide. A FASTQ record has the following format: A line starting with @, containing the sequence ID. One or more lines that contain the sequence. A new line starting with the character +, and being either empty or repeating the sequence ID. One or more lines that contain the quality scores. Here’s an example of a FASTQ file with two records: @071112_SLXA-EAS1_s_7:5:1:817:345 GGGTGATGGCCGCTGCCGATGGCGTC AAATCCCACC + IIIIIIIIIIIIIIIIIIIIIIIIII IIII9IG9IC @071112_SLXA-EAS1_s_7:5:1:801:338 GTTCAGGGATACGACGTTTGTATTTTAAGAATCTGA + IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII6IBI FASTQ files are mostly used to store short-read data from high-throughput sequencing experiments. The sequence and quality scores are usually put into a single line each, and indeed many tools assume that each record in a FASTQ file is exactly four lines long, even though this isn’t guaranteed. As with FASTA, the format of the sequence ID isn’t standardised, but different producers of FASTQ use fixed notations that follow strict conventions. SAM SAM files are so complex that a complete description [PDF] takes 15 pages. So here’s the short version. The original purpose of SAM files is to store mapping information for sequences from high-throughput sequencing. As a consequence, a SAM record needs to store more than just the sequence and its quality, it also needs to store information about where and how a sequence maps into the reference. Unlike the previous formats, SAM is tab-based, and each record, consisting of either 11 or 12 fields, fills exactly one line. Here’s an example (tabs replaced by fixed-width spacing): r001 99 chr1 7 30 17M = 37 39 TTAGATAAAGGATACTG IIIIIIIIIIIIIIIII r002 0 chrX 9 30 3S6M1P1I4M * 0 0 AAAAGATAAGGATA IIIIIIIIII6IBI NM:i:1 For a description of the individual fields, refer to the documentation. The relevant bit is this: SAM can express exactly the same information as FASTQ, plus, as mentioned, the mapping information. However, SAM is also used to store read data without mapping information. In addition to sequence records, SAM files can also contain a header, which stores information about the reference that the sequences were mapped to, and the tool used to create the SAM file. Header information precede the sequence records, and consist of lines starting with @. SAM itself is almost never used as a storage format; instead, files are stored in BAM format, which is a compact, gzipped, binary representation of SAM. It stores the same information, just more efficiently. And, in conjunction with a search index, allows fast retrieval of individual records from the middle of the file (= fast random access). BAM files are also much more compact than compressed FASTQ or FASTA files. The above implies a hierarchy in what the formats can store: FASTA ⊂ FASTQ ⊂ SAM. In a typical high-throughput analysis workflow, you will encounter all three file types: FASTA to store the reference genome/transcriptome that the sequence fragments will be mapped to. FASTQ to store the sequence fragments before mapping. SAM/BAM to store the sequence fragments after mapping.
{ "domain": "bioinformatics.stackexchange", "id": 47, "tags": "fasta, fastq, file-formats, sam" }
rosjava_android WIFI set up in a windows based virtual box
Question: I have modified the the android_tutorial_pubsub package to let it connect a roscore on PC and write a talker on PC to send message to the android phone. It works OK, but when I move to virtual box in windows 7, I hava no idea how to set up the ip for it to work. Does anybody know how to do this? Thanks. BTW, I found that the connection between the android phone and the PC can only be established when they are connected to the internet. I have tried to connect the PC and the Phone to the same router without connecting the router to the internet, the connection is not established. It only works when I connect the router to the internet. Is there a method to let it work without the internet? Thanks. Originally posted by alexbeta20 on ROS Answers with karma: 5 on 2012-04-12 Post score: 0 Answer: Hi! I'm guessing that in the first test that you did, you were using Ubuntu, and then "moved" that Ubuntu into a VM, running on Windows as a host os? In that setup, the Ubuntu box is most probably being NATed, so it's not in the same network as the Windows box. You would need to check de networking configuration of your virtual machine software. Regarding the Internet connectivity requirements, there are no such requirements. It must be some other problem in your network configuration. Originally posted by tulku with karma: 51 on 2014-09-19 This answer was ACCEPTED on the original site Post score: 1
{ "domain": "robotics.stackexchange", "id": 8953, "tags": "ros, rosjava, virtualbox, android" }
Can viruses infect adipose cells?
Question: Can viruses infect adipose cells or tissue? Answer: Research demonstrated that viruses including HIV virus can find sanctuary in adipose tissue cells. Earlier studies showed that interactions between immune cells and adipocytes, specifically perinodal adipocytes, promote immune activation and adipose inflammation,suggesting adipocyte regulation of HIV replication and pathogenesis. Adipose tissue is categorized as mainly subcutaneous or visceral depots, with other minor depots uniquely associated with critical tissues and organs such as lymph nodes (perinodal fat) and the heart (pericardial and epicardial fat). Adipose tissue contains mature adipocytes and stromal-vascular-fraction cells (AT-SVF cells) which includes preadipocytes, mesenchymal stem cells, and immune cells, and this cellular composition changes significantly during disease and metabolic disorders, most notably obesity. Murine models demonstrated migration of immune cells into adipose tissue to become major regulators of adipocyte function and metabolism, and studies of healthy and diseased humans further showed significant accumulation of immune cells. Additionally, virion-free circulating HIV proteins such as vpr, nef, and tat were shown to mediate detrimental effects on adipose tissue health and systemic metabolism. So yes, the viruses can "live" and "reside" inside adipose tissue and regulate that environment to their own benefit.
{ "domain": "biology.stackexchange", "id": 11774, "tags": "virology" }
An Integral involving solid angle in Peskin and Schroeder
Question: I cannot figure out an integral in the textbook Quantum Field Theory by Peskin and Schroeder. On P.201 the integral above Eq.(6.70), the relevant part in question reads $$\int\frac{\mathrm d\Omega_k}{4\pi}\frac{1}{[\xi\hat{k}\cdot p'+(1-\xi)\hat{k}\cdot p]^2}=\frac{1}{[\xi p'+(1-\xi)p]^2}$$ I tried by writing $\mathrm d\Omega_k=\sin\theta_k ~\mathrm d\theta_k~\mathrm d\phi_k$, as well as assuming $p'$ in the $\hat{z}$ direction, and $p$ in the $x-z$ plane, the resulting integral becomes complicated and involves $$\int \sin\theta~\mathrm d\theta~\mathrm d\phi \frac{1}{\xi\cos\theta p'+(1-\xi)[\cos\theta p_z+\sin\theta\cos\phi p_x]}$$ Then one has to integral with respect to $\phi$ and $\theta$, neither of them is straightforward. Since the resulting expression in the textbook looks rather simple, I am wondering whether there is a straightforward way to obtain the result in the textbook? Any comment is really appreciated. Answer: I advise you to factor out $ \hat{k} $ and align your $z$ axis with the vector $\xi p' + (1-\xi)p$.
{ "domain": "physics.stackexchange", "id": 32140, "tags": "quantum-field-theory" }
Why are there only odd harmonics at High Harmonic Generation?
Question: I'm trying to understand why in High Harmonic Generation (HHG) the spectrum only consist out of odd multiples of the driving frequency. Many sources state "because of symmetry" but they do not clearly explain why this symmetry is needed or symmetry in what? Wikipedia seems to claim it has to do with a symmetry of a monatomic gas where the HHG is generated: In monatomic gases it is only possible to produce odd numbered harmonics for reasons of symmetry - High Harmonic Generation Wikipedia Another source states that the spectrum of a HHG pulse train can be described accordingly: $g(\omega) = \Big[2\omega_d\sum_{n=0}^{\infty}f(n2\omega_d)\delta(\omega-n2\omega_d)\Big]*f_{env}(\omega)$ With $\omega_d$ being the driving frequency of the pump laser, $f(\omega)$ a single HHG pulse in frequency space, $f_{env}(\omega)$ the envelope of the driving pulse in frequency space. In the document it claims that because of this equation it is "clearly visible" we only have odd harmonics. But I would say: we only have even harmonics due to the $2n$ part. Also, if only odd harmonics are possible then what is Second Harmonic Generation? Is this a different mechanic compared to HHG? EDIT: The source I mentioned before, does state that there should be symmetry in the polarisation of a monatomic atom. Meaning that the electron cloud displacement is independent of the direction of the electric field (up to a sign change). This means that the even-orders of $\chi$ should be zero and thus no even harmonics. This part I can understand why atom symmetry leads to the odd harmonics and added it as an answer. Now the only thing which remains is the equation mentioned above which "clearly" shows odd harmonics. Answer: Actually, the source mentioned in my question does answer partially the question. Consider a monatomic gas with an electron cloud. Its response to an electric field is typically given in terms of an expansion. $P(t) = \varepsilon_0\Big[\chi^{(1)}E(t)+\chi^{(2)}E^2(t)+\chi^{(3)}E^3(t)+..\Big]$ When there is spherical symmetry, for a monatomic case, we can expect the reaction of the media (polarisation) for opposite electric fields to be symmetric, i.e. $P(E) = -P(-E)$. This can only be true for odd orders and thus the even $\chi$'s need to be zero. When you plug in a plane wave into the equation, with zero for the even $\chi$, it does create only odd harmonics.
{ "domain": "physics.stackexchange", "id": 69072, "tags": "non-linear-optics" }
Conditionally set strings if files exist
Question: How can I reduce the lines I use with this code block? if ((test.contains("1.jpg") || test.contains("1.png")) && (maxP == false)){ page++; add = 1; if (QFile().exists(basepath + spage + ".jpg")){ p_left = basepath + spage + ".jpg"; } else if(QFile().exists(basepath + spage+ ".png")){ p_left = basepath + spage + ".png"; } if (QFile().exists(basepath + QString::number(page + 1) + ".jpg")){ p_right = basepath + inc + ".jpg"; } else if(QFile().exists(basepath + QString::number(page + 1) + ".png")){ p_right = basepath + inc + ".png"; } } else if ((test.contains("1.jpg") || test.contains("1.png")) && (maxP == true)){ gpage = max; add = 1; if (QFile().exists(basepath + smax + ".jpg")){ p_left = basepath + smax + ".jpg"; } else if(QFile().exists(basepath + smax + ".png")){ p_left = basepath + smax + ".png"; } if (QFile().exists(basepath + QString::number(page + 1) + ".jpg")){ p_right = basepath + sinc + ".jpg"; } else if(QFile().exists(basepath + QString::number(page + 1) + ".png")){ p_right = basepath + sinc + ".png"; } } Answer: I see a number of things that may help you improve your code. Use named constants There are a number of constant strings which are used repeatedly. If they're used more than once, it's probably a sign that you should use named constants instead. constexpr static char[] JPG_EXT{".jpg"}; constexpr static char[] PNG_EXT{".png"}; Consolidate tests in compound if statements Right now the code is basically this: if ((test.contains("1.jpg") || test.contains("1.png")) && (maxP == false)){ // do things } else if ((test.contains("1.jpg") || test.contains("1.png")) && (maxP == true)){ // do other things } This can be simplified like this: if ((test.contains("1.jpg") || test.contains("1.png")) { if (maxP) { // do other things } else { // maxP must be false // do things } } Consolidate code where only the data changes The code currently has repeated patterns like this: if (QFile().exists(basepath + smax + ".jpg")){ p_left = basepath + smax + ".jpg"; } It then repeats, but with slightly different data. That suggests further consolidation: if ((test.contains("1.jpg") || test.contains("1.png")) { QString leftbase, rightbase; if (maxP) { gpage = max; leftbase = basepath + smax; rightbase = basepath + sinc; } else { page++; leftbase = basepath + spage; rightbase = basepath + inc; } add = 1; if (QFile(leftbase + JPG_EXT).exists()) { p_left = leftbase + JPG_EXT; } else if (QFile(leftbase + PNG_EXT).exists()) { p_left = leftbase + PNG_EXT; } if(QFile(basepath + QString::number(page + 1) + JPG_EXT).exists()){ p_right = rightbase + JPG_EXT; } else if(QFile(basepath + QString::number(page + 1) + PNG_EXT).exists(){ p_right = rightbase + PNG_EXT; } } Use a function for repeated actions If you find yourself writing similar code multiple times, it might be a sign that you could use a function. In this code, I'd write this: void setIfJpgOrPngExists(const QString& querybase, const QString& answerbase, QString &target) { if (QFile(querybase + JPG_EXT).exists()) { target = answerbase + JPG_EXT; } else if (QFile(querybase + PNG_EXT).exists()) { target = answerbase + PNG_EXT; } } if ((test.contains("1.jpg") || test.contains("1.png")) { QString leftbase, rightbase; if (maxP) { gpage = max; leftbase = basepath + smax; rightbase = basepath + sinc; } else { page++; leftbase = basepath + spage; rightbase = basepath + inc; } add = 1; setIfJpgOrPngExists(leftbase, leftbase, p_left); setIfJpgOrPngExists(basepath + QString::number(page + 1), rightbase, p_right); }
{ "domain": "codereview.stackexchange", "id": 18863, "tags": "c++, qt" }
ASCII art generator in C
Question: I have written an ASCII art generator library. I was practicing data abstraction and code abstraction and I wanted to know if there is something that can be improved. File tree: | |--Makefile |--fonts--|--StarStrips.c | |--whimsy.c | | |--core.h ---|--include--|--StarStrips.h | |--whimsy.h | |--Makefile /fonts/Makefile sharedlib: whimsy.o StarStrips.o @echo Building the Shared Library; \ gcc -shared -fPIC -o ascii-arts.so whimsy.o StarStrips.o; StarStrips.o : StarStrips.c @echo building StarStrips; \ gcc -c -fPIC StarStrips.c -o StarStrips.o -std=c99 -I../include whimsy.o : whimsy.c @echo building whimsy; \ gcc -c -fPIC whimsy.c -o whimsy.o -std=c99 -I../include /font/whimsy.c #include <whimsy.h> #include <stdlib.h> #include <stdio.h> #include <ctype.h> #include <string.h> int whimsy_allowed(int c) { return islower(c) || c == ' '; } int whimsy_index (int c) { return islower(c)? c -'a'+1 :0; } int whimsy_init(void){ font_alloc(whimsy,10,27); d_alloc(whimsy,space,' ',5,ARRAY({ " ", " ", " ", " ", " ", " ", " ", " ", " ", " " })); d_alloc(whimsy,a,'a',11,ARRAY({ " ", " ", " ", " d888b8b ", "d8P' ?88 ", "88b ,88b ", "`?88P'`88b", " ", " ", " " })); d_alloc(whimsy,b,'b',11,ARRAY({ " d8b ", " ?88 ", " 88b ", " 888888b ", " 88P `?8b", " d88, d88", "d88'`?88P'", " ", " ", " " })); d_alloc(whimsy,c,'c',8,ARRAY({ " ", " ", " ", " d8888b", "d8P' `P", "88b ", "`?888P'", " ", " ", " " })); d_alloc(whimsy,d,'d',11,ARRAY({ " d8b ", " 88P ", " d88 ", " d888888 ", "d8P' ?88 ", "88b ,88b ", "`?88P'`88b", " ", " ", " " })); d_alloc(whimsy,e,'e',8,ARRAY({ " ", " ", " ", " d8888b", "d8b_,dP", "88b ", "`?888P'", " ", " ", " " })); d_alloc(whimsy,f,'f',11,ARRAY({ " ,d8888b", " 88P' ", "d888888P ", " ?88' ", " 88P ", " d88 ", "d88' ", " ", " ", " " })); d_alloc(whimsy,g,'g',11,ARRAY({ " ", " ", " ", " d888b8b ", "d8P' ?88 ", "88b ,88b ", "`?88P'`88b", " )88", " ,88P", " `?8888P " })); d_alloc(whimsy,h,'h',11,ARRAY({ " d8b ", " ?88 ", " 88b ", " 888888b ", " 88P `?8b", " d88 88P", "d88' 88b", " ", " ", " " })); d_alloc(whimsy,i,'i',6,ARRAY({ " d8,", " `8P ", " ", " 88b", " 88P", " d88 ", "d88' ", " ", " ", " " })); d_alloc(whimsy,j,'j',8,ARRAY({ " d8, ", " `8P ", " ", " d88 ", " ?88 ", " 88b ", " `88b", " )88", " ,88P", "`?888P " })); d_alloc(whimsy,k,'k',12,ARRAY({ " d8b ", " ?88 ", " 88b ", " 888 d88'", " 888bd8P' ", " d88888b ", "d88' `?88b,", " ", " ", " " })); d_alloc(whimsy,l,'l',6,ARRAY({ " d8b ", " 88P ", "d88 ", "888 ", "?88 ", " 88b ", " 88b", " ", " ", " " })); d_alloc(whimsy,m,'m',15,ARRAY({ " ", " ", " ", " 88bd8b,d88b ", " 88P'`?8P'?8b", " d88 d88 88P", "d88' d88' 88b", " ", " ", " " })); d_alloc(whimsy,n,'n',11,ARRAY({ " ", " ", " ", " 88bd88b ", " 88P' ?8b", " d88 88P", "d88' 88b", " ", " ", " " })); d_alloc(whimsy,o,'o',9,ARRAY({ " ", " ", " ", " d8888b ", "d8P' ?88", "88b d88", "`?8888P'", " ", " ", " " })); d_alloc(whimsy,p,'p',11,ARRAY({ " ", " ", " ", "?88,.d88b,", "`?88' ?88", " 88b d8P", " 888888P'", " 88P' ", " d88 ", " ?8P " })); d_alloc(whimsy,q,'q',11,ARRAY({ " ", " ", " ", ".d88b,.88P", "88P `88P'", "?8b d88 ", "`?888888 ", " `?88 ", " 88b ", " ?8P " })); d_alloc(whimsy,r,'r',10,ARRAY({ " ", " ", " ", " 88bd88b", " 88P' `", " d88 ", "d88' ", " ", " ", " " })); d_alloc(whimsy,s,'s',9,ARRAY({ " ", " ", " ", " .d888b,", " ?8b, ", " `?8b ", "`?888P' ", " ", " ", " " })); d_alloc(whimsy,t,'t',9,ARRAY({ " ", " d8P ", "d888888P", " ?88' ", " 88P ", " 88b ", " `?8b ", " ", " ", " " })); d_alloc(whimsy,u,'u',10,ARRAY({ " ", " ", " ", "?88 d8P", "d88 88 ", "?8( d88 ", "`?88P'?8b", " ", " ", " " })); d_alloc(whimsy,v,'v',10,ARRAY({ " ", " ", " ", "?88 d8P", "d88 d8P'", "?8b ,88' ", "`?888P' ", " ", " ", " " })); d_alloc(whimsy,w,'w',16,ARRAY({ " ", " ", " ", " ?88 d8P d8P", " d88 d8P' d8P'", " ?8b ,88b ,88' ", " `?888P'888P' ", " ", " ", " " })); d_alloc(whimsy,x,'x',10,ARRAY({ " ", " ", " ", "?88, 88P", " `?8bd8P'", " d8P?8b, ", "d8P' `?8b", " ", " ", " " })); d_alloc(whimsy,y,'y',11,ARRAY({ " ", " ", " ", "?88 d8P ", "d88 88 ", "?8( d88 ", "`?88P'?8b ", " )88", " ,d8P", " `?888P'" })); d_alloc(whimsy,z,'z',9,ARRAY({ " ", " ", " ", "d88888P ", " d8P' ", " d8P' ", "d88888P'", " ", " ", " " })); return 0; } int whimsy_exit(void){ for(int i=0;i<whimsy.d_n;i++) for(int j=0;j<whimsy.c;j++) free(whimsy.d[i][j]); for(int i=0;i<whimsy.d_n;i++) free(whimsy.d[i]); free(whimsy.d); free(whimsy.r); } int whimsy_print(const char* s){ int n = strlen(s); for(int i=0;i<n;i++) if(whimsy.allowed(s[i]) != 1) return -1; for (int i=0;i<whimsy.c;i++) { for(int j=0;j<n;j++) fputs(whimsy.d[whimsy.index(s[j])][i],stdout); putchar('\n'); } } I won't show you /font/StarStrips.c because it's similar lengthy code and the goal of reviewing the code is not giving opinions about the fonts self. /include/core.h #ifndef _ascii_arts_core_ #define _ascii_arts_core_ /* r rows c columns d design char_n number of characters */ struct font{ unsigned int c; unsigned int *r; unsigned int d_n; int (*allowed)(int); int (*index)(int); int (*init)(void); int (*exit)(void); int (*print)(const char*); char ***d; }; #define XX(a,b,c) a##b##c #define font_alloc(font,column,nofdesigns) \ do{ \ font.d_n = nofdesigns; \ font.c = column; \ font.r = malloc(sizeof(int)*font.d_n); \ font.d = malloc(sizeof(char***)*font.d_n); \ for(int i=0;i<font.d_n;i++) \ font.d[i] =malloc(sizeof(char**)*font.c); \ }while(0) #define ARRAY(...) __VA_ARGS__ #define d_alloc(font,__tok,_char,row,design) \ do{ \ font.r[font.index(_char)] = row; \ for(int j=0;j<font.c;j++) \ font.d[font.index(_char)][j] = \ malloc(sizeof(char*)*font.r[font.index(_char)]);\ char * temp[] = design; \ for(int i=0;i<font.c;i++) \ strcpy(font.d[font.index(_char)][i],temp[i]); \ }while(0) #endif /include/whimsy.h #ifndef _whimsy_font_ #define _whimsy_font_ #include <core.h> int whimsy_allowed(int c); int whimsy_index(int c); int whimsy_init(void); int whimsy_exit(void); int whimsy_print(const char* s); struct font whimsy = { .allowed = whimsy_allowed, .index = whimsy_index, .init = whimsy_init, .exit = whimsy_exit, .print = whimsy_print }; #endif /Makefile uninstall: @echo Uninstalling library; \ rm /usr/lib/libaarts.so -f; \ cd /usr/include \ rm whimsy.h core.h StarStrips.h -f install: lib @echo Installing library; \ cp include/*.h /usr/include/; \ cp libaarts.so /usr/lib/ lib: @cd fonts; \ make sharedlib; \ mv ascii-arts.so ../libaarts.so clean: @rm *.so -f; \ cd fonts; \ rm *.o -f; \ cd ../demo; \ rm *.d -f; demos: @cd demo; \ make whimsy Little notes First of all, the main goal of this library was to provide a data structure to hold fonts for ASCII art characters and maybe ASCII art drawings (i.e. converting a PNG image to ASCII arts (not yet done)). in the d_alloc macro the __tok parameter is useless and it is there just for backwards comptiability with previous versions of the same library. Answer: fonts/Makefile Each object depends only on the corresponding source. It means that header modifications wouldn't trigger recompilation. You may fix it by explicitly spelling out dependencies: whimsy.o: whimsy.c whimsy.h core.h In general it is a good habit to have dependencies auto generated: even in your not very complicated case it is easy to miss the core.h dependency. Take a look at -M family of gcc options. include/whimsy.h Do not define objects (like struct font whimsy) in the header file. You never know how many times the client would happen to #include "whimsy.h" in different places of their project. Better practice is to have the definition in the .c file, and declare it in the header as extern struct font whimsy; DRY? Unfortunately, you didn't show your font file. Also, I'm 95% sure the init and print files are identical modulo font name. If I'm correct, you need to unify them, and have the unified version in core.c. Allocation Allocating glyphs dynamically and copying them from a static area looks like a waste for me (it would make sense should you read glyphs from the text file instead). I would have a struct glyph { int width; char * appearance; }; (strictly speaking, glyph.width is redundant: given a font height and appearance length you may calculate width at runtime); an array of glyphs as a part of struct font: struct font { .... struct glyph typeface[128]; .... } and a static initialization of each font like static struct font whimsy = { .... .typeface = { .... ['a'] = (struct glyph) { .width = 10, .appearance = " " " " " " " d888b8b " "d8P' ?88 " "88b ,88b " "`?88P'`88b" " " " " " "; }, .... }, .... }; Beware that such partial array initialization is a gcc extension. More abstraction Now you may take advantage of appearance being default initialized to an NULL, and conclude that such glyph is not implemented. An allowed method becomes a trivial test, and is easily abstracted out of the font specifics.
{ "domain": "codereview.stackexchange", "id": 15881, "tags": "c, library, ascii-art, dynamic-loading" }
Increase maximum shots on IBM Hardware when running Quantum Variational Algorithms
Question: I am interested to know whether there is a quick and elegant way of increasing the number of shots (more than 8192 shots) on IBM hardware when running variational algorithms like VQE or QAOA. I know that within Qiskit, I can specify: backend._configuration.max_shots= shots to change the number of max_shots but this only works for simulator. I can't increase the shots parameter to go over 8192 shots when I set my backend as one of the real hardware. That is, if I specify the following: hardware_backend = provider.get_backend('ibmq_valencia ') maxshots = 20000 hardware_backend._configuration.max_shots= maxshots quantum_instance = QuantumInstance(hardware_backend, shots = maxshots, initial_layout = None, optimization_level = 3) then upon executing the circuit, I will have an error message: Error is : The number of shots in the Qobj (20000) is higher than the number of shots supported by the device (8192). Is there a quick and elegant way to overcome this issue within Qiskit? Thank you! Answer: According to my knowledge, 8192 is a maximum of shots. I think that the reason is fair timesharing as nowadays there are many users of IBM Q. To get better results from VQE, I can only recommend to run your task several times and then pick up the best solution, i.e. the one wiht the lowest (highest) value of the optimized function.
{ "domain": "quantumcomputing.stackexchange", "id": 2260, "tags": "programming, qiskit, ibm-q-experience, vqe" }
How have a static map to understand its GPS coordinates?
Question: I am using rviz, gazebo, and a Clearpath Husky with GPS, IMU, encoders, and LIDAR to simulate autonomous navigation in an outdoor environment. Using robot localization I have an ekf_odom and ekf_map node combined with a navsat_transform working like a charm to localize me in the GPS world. These setup outputs the transforms from map->odom->baselink nicely. The problem I have been running into over the past couple days is how do I properly specify a static map/map_server so that it overlays my gazebo 3D world and so that each time a spawn the robot it is properly localized within the static map in rviz. This is not well documented in and tutorial and has been quite frustrating. I think it has something to do with the datum, or a static transform for the map from the UTM frame but I cannot be sure, and messing around with the launch files for a week has not gotten me any closer to the answer. If you need to see any launch files let me know and I'll update the post ASAP. Originally posted by JackB on ROS Answers with karma: 977 on 2019-06-27 Post score: 2 Answer: Below is the launch file, which I call hybrid_localization because it allows you to have pose in two different map referenced frames fused into a single ekf. I know that is bad practice to have to absolute position's fused together because it causes jitter. This however is predicated on the fact that where you have GPS you will not be able to use AMCL and where you have AMCL you will not have GPS. In my experience on a university campus this holds true, and I have found this setup very useful. I would like to pretend that the launch and config files "explain themselves", but I understand they probably do not, and therefore will be happy to field questions, or provide more information to anyone who is interested. hybrid_localization.launch <launch> <arg name="amcl_map_frame" default="map_amcl"/> <arg name="map_file" default="/home/administrator/philbart_config/maps/pma_23_09_2020_8_15.yaml"/> <arg name="ekf_localization_map_file" default="/home/administrator/philbart_config/ekf_localization_map.yaml"/> <arg name="navsat_transform_file" default="/home/administrator/philbart_config/navsat_transform.yaml"/> <!---Static Transform world-to-map_amcl --> <node pkg="tf2_ros" type="static_transform_publisher" name="world_to_map_amcl_broadcaster" args="-13.62 19.02 0 -0.121 0 0 world $(arg amcl_map_frame)" /> <!---Static Transform world-to-map --> <node pkg="tf2_ros" type="static_transform_publisher" name="world_to_map_broadcaster" args="0 0 0 0 0 0 world map" /> <!---AMCL Map --> <node name="map_server_amcl" pkg="map_server" type="map_server" args="$(arg map_file)"> <param name="frame_id" value="$(arg amcl_map_frame)" /> <remap from="map" to="$(arg amcl_map_frame)"/> <remap from="map_metadata" to="$(arg amcl_map_frame)_metadata"/> </node> <!---AMCL Node --> <include file="$(find husky_navigation)/launch/amcl.launch"> <arg name="global_frame_id" default="$(arg amcl_map_frame)"/> <arg name="map_topic" default="$(arg amcl_map_frame)"/> <arg name="tf_broadcast" default="false"/> </include> <!--- Global EKF --> <node pkg="robot_localization" type="ekf_localization_node" name="ekf_localization_map" output="screen"> <rosparam command="load" file="$(arg ekf_localization_map_file)" /> <remap from="/odometry/filtered" to="/odometry/filtered_map"/> </node> <!--- Navsat Transform Node--> <node pkg="robot_localization" type="navsat_transform_node" name="navsat_transform" output="screen"> <rosparam command="load" file="$(arg navsat_transform_file)" /> <remap from="odometry/filtered" to="odometry/filtered_map"/> <remap from="gps/fix" to="/piksi_reference/piksi/navsatfix_best_fix"/> </node> </launch> Where ekf_localization_map.yaml is: map_frame: map odom_frame: odom base_link_frame: base_link world_frame: map imu0: /gx5/imu/data imu0_config: [false, false, false, true, true, false, false, false, false, true, true, true, true, true, true] imu0_nodelay: true imu0_differential: false imu0_relative: false imu0_queue_size: 10 imu0_remove_gravitational_acceleration: true odom0: /husky_velocity_controller/odom odom0_config: [false, false, false, false, false, false, true, true, true, false, false, true, false, false, false] odom0_queue_size: 10 odom0_nodelay: true odom0_differential: false odom0_relative: false odom1: odometry/gps odom1_config: [true, true, false, false, false, false, false, false, false, false, false, false, false, false, false] odom1_queue_size: 10 odom1_nodelay: true odom1_differential: false odom1_relative: false odom1_rejection_threshold: 2.0 pose0: /amcl_pose pose0_config: [true, true, false, false, false, true, false, false, false, false, false, false, false, false, false] pose0_queue_size: 10 pose0_nodelay: true pose0_differential: false pose0_relative: false pose0_rejection_threshold: 2.0 use_control: false Originally posted by JackB with karma: 977 on 2020-10-02 This answer was ACCEPTED on the original site Post score: 1
{ "domain": "robotics.stackexchange", "id": 33281, "tags": "gazebo, gps, rviz, ros-kinetic" }
Kepler's second law implies angular momentum is constant?
Question: My textbook says that we can infer from Kepler's second law that angular momentum is conserved for a planet, and therefore gravity is a central force. Now I understand how constant angular momentum implies that gravity is a central force. However, I don't see how we know that angular momentum is conserved, based on Kepler's second law. My textbook describes Kepler's second law as follows: $$ \int_{t_1}^{t^2}rv_\phi\,\mathrm dt=C\int_{t_1}^{t_2}\mathrm dt=C(t_2-t_1), $$ where $C$ is a constant. We see that $rv_\phi=r^2\dot\phi=C$. We also know that $|\vec{L}|=|\vec{r}\times\vec{p}|=rmv\sin\theta=mr^2\omega\sin\theta.$ Right, so we can assume $m$ is constant, and $r^2\omega$ as well, by Kepler's second law. What about $\theta$ though? How do we know $\theta$ is constant? For circular orbits, I can see that $\theta=\frac{1}{2}\pi$, but how about elliptical orbits? EDIT Okay, I think I got it. We're considering a solid object (planet) rotating about a fixed axis of rotation, so technically, we should be using $\vec L=I\vec\omega$. But I guess we can approximate the moment of inertia for a planet as $mr^2$, considering the spatial dimensions we're working with. And therefore we get $|\vec L|=I|\vec \omega|=mr^2\omega=$ constant. Given that a planet doesn't 'turn' suddenly, we can also assume the direction of $\vec \omega$ being constant. Answer: My textbook describes Kepler's second law as follows: $$ \int_{t_1}^{t^2}rv_\phi\,\mathrm dt=C\int_{t_1}^{t_2}\mathrm dt=C(t_2-t_1), $$ where $C$ is a constant. That alone says that the magnitude of angular momentum is constant. Your textbook's $v_\phi$ is the component of the velocity vector that is normal to the radial vector: $\vec v = v_r \hat r + v_\phi \hat \phi$. Thus $\vec L = m \vec r \times \vec v = m r v_\phi\,\hat r \times \hat \phi$. Since since $||\hat r \times \hat \phi|| \equiv 1$, the magnitude of a planet's angular momentum vector is $||\vec L|| = m r v_\phi$. Since mass is constant and since $\int_{t_1}^{t_2} r v_\phi dt = C(t_2-t_1)$, the magnitude of the angular momentum vector is constant. To arrive at the angular momentum vector being constant, we need to know that it's direction is constant as well. This is a consequence of orbits being planar, which is part of Kepler's first law.
{ "domain": "physics.stackexchange", "id": 37825, "tags": "newtonian-mechanics, newtonian-gravity, angular-momentum, conservation-laws, orbital-motion" }
Lawn mower robot (type of cutter)
Question: If not all, but major types of lawn mower robots are rotary mowers. I presume1 that reel mower is more efficient, and is said to leave a better lawn health and cut. So, why industry go to the other option? 1 - I'm assuming the efficiency, as electrical rotary mowers have at least 900W universal-motors or induction motors, and a manual reel mower is capable nearly the same cutting speed. Answer: Rotary mowers are mechanically simpler, so cheaper to make. The rotary mower is more tolerant of getting dull, and if you run over something like small trees or rocks, the blades take less damage, and the motor is harder to jam and stall. The blades are also easier to sharpen. For this simplicity, you get a poorer cut, and more grass damage. I do agree, though, that the reel mower would be more efficient. You'd probably need more sensors though, to watch for jamming.
{ "domain": "robotics.stackexchange", "id": 277, "tags": "motor, mechanism" }
Interactions in nonlinear chiral theories
Question: When discussing nonlinear realizations of $SU(3)_L \times S(3)_R$ in Chiral theories, it is usual to introduce the interactions between the baryon octet ($B$) and some meson matrix $M$ as \begin{equation} \mathcal{L}_{int} = g_8^M \left\{ \alpha [\bar B O B M]_F + (1-\alpha) [\bar B O B M]_D \right\} + g_1^M \mathrm{Tr} \left( \bar B O B \right) \mathrm{Tr}\left( M \right) \end{equation} where the anti-symmetric (F) and symmetric (D) terms are defined as: \begin{equation} [\bar B O B M]_F = \mathrm{Tr} \left( \bar B O [B,M]]\right) \end{equation} \begin{equation} [\bar B O B M]_D = \mathrm{Tr} \left( \bar B O \{B,M\} \right) -\frac{2}{3} \mathrm{Tr} \left( \bar B O B \right) \mathrm{Tr}\left( M \right) \end{equation} Here the term $g_1^M$ is related to the singlet interaction and $O$ is some Dirac structure depending on the meson $M$, for example, $O=\gamma_\mu$ for vector mesons $M=V_\mu$ and $O=1$ for the scalar meson $O=X$. If the interaction occurs with a meson octet, then $\mathrm{Tr} M = 0$ and the symmetric term reduces to\begin{equation} [\bar B O B M]_D = \mathrm{Tr} \left( \bar B O \{B,M\} \right) \end{equation} My question is: Why is the symmetric part of the interaction defined with the $2/3$ term? It looks intuitive to me to define it only with the anti-commutator (which is the case when we have a matrix octet). Is this really a definition? Does it have anything to do with the mixing of singlet and octet matrices? Answer: Yes, it is there to ensure that there is no mixing between the singlet, displayed separately, and the octet, so you do not double count. The coefficient of $g_8^M$ contains no singlet. The 3×3 matrix M may, in principle, contain an octet part, and an arbitrary, tracefull!, singlet part proportional to the identity. This singlet part cannot contribute to the F piece, but can contribute to the anticommutator, $$ \mathrm{Tr} \left( \bar B O \{B,M\} \right)=2\mathrm{Tr} \left( \bar B O B~M \right)= 2 \mathrm{Tr} \left( \bar B O B \right) \frac{\mathrm{Tr} M}{3}, $$ since you trace over the 3×3 identity matrix. Now that the octet term has the singlet projected out, you reintroduce the singlet separately, but there is no reason to keep the silly 2/3 factor: it is absorbed in the singlet coefficient.
{ "domain": "physics.stackexchange", "id": 97033, "tags": "lagrangian-formalism, interactions, non-linear-systems, chirality" }
Is voltage just the energy created from the separation of charges?
Question: Recently learnt some physics, and I just want to check my understanding Answer: Yes indeed. Electric potential energy $U_e$ is the potential energy stored when charges are out of equilibrium (like gravitational potential energy when an object is lifted above the ground). Electric potential is the same, but per charge, $\frac{U_e}q$. (Useful when comparing different points.) An electric potential difference between two points is called voltage, $V=\frac{U_{e2} }q-\frac{U_{e1}} q$. Voltage is a measure of the tendency of charges to move. If a charge is alone, then it has no tendency to move at all (there is no electric force pushing or pulling). If two charges are together, then their electric forces create a potential energy that depends on separation distance (just like the gravitational potential energy between a vase and the ground depends on how high up it has been placed).
{ "domain": "physics.stackexchange", "id": 73044, "tags": "electrostatics, charge, potential, potential-energy, voltage" }
Can gravity be measured by proximity?
Question: Can the topography of a terrain be measured by a gravimeter to give a clear image of the surface or sub-surface of a planet or does gravity scatter like light? In other words can the changes in gravity create a 3 dimensional picture of an object if close enough. The picture is speculation of how distance using gravimeters may be used to map the ground and possibly caves. Answer: Scattering like light is not relevant, because we're looking at the non-radiative near-field solution (also: it's static). The GRACE mission and its follow on (https://www.nasa.gov/mission_pages/Grace/index.html) used/uses precision metrology between two satellites flying in formation to reconstruct mass distributions on Earth, with phenomenal resolution. Submarine-borne precision graviometers have been used for both bathymetry and navigation. In your drawing, if the satellite track is supposed to represent the equipotential surface, then the deviations shown are inverted. The theoretical mean-sea-level equipotential surface of the Earth is known as "The Geoid". EGM96 is a full multipole expansion out to $l=360$, and the most recent unclassified version, EGM08 (https://earth-info.nga.mil/GandG/wgs84/gravitymod/egm2008/) goes to an order of a few thousand, but doesn't use all the $m$-values. If look at the geoid over a mass void, such as the Mariana Trench, it dips down, while a mass excess, such as the island of Hawaii, brings sea level (and the geoid) up. It may be counter intuitive that lesser gravity pulls you down further, but the potential is defined as negative energy relative to zero at infinite distance, hence you need to travel to smaller radii to get to the same potential. That's a bit abstract. It turns out, the vertical deflection of local $g$ is also a thing that is measured and made available to scientists (https://geodesy.noaa.gov/GEOID/DEFLEC96/readme.txt). If you imagine surfaces that are orthogonal to the deflection around mass deficits/excesses, it is pretty obvious which way the geoid goes. Finally, there is also the Mars equipotential surface, called the Aeroid, which is computed from satellite tracking and LIDAR elevation measurements. Since Mars was clobbered by a huge impactor, it has an enormous quadruple moment. It really is pear shaped, with the norther hemisphere being low and flat, and the southern hemisphere being at much higher elevation (hence early landers went to the north, where there's enough atmosphere to apply the brakes). Venus also has a known geoid, derived primarily from the Magellan orbit and synthetic aperture radar imaging of the surface.
{ "domain": "physics.stackexchange", "id": 69814, "tags": "newtonian-gravity, orbital-motion, geophysics" }
Are Hermitian operators Hermitian in any basis?
Question: Given a Hilbert space and a Hermitian operator defined on it, will the operator exhibit Hermiticity in any basis used to span the space? My thought on this is that this must be the case, after all, if an operator is Hermitian then it represent an observable. Surely, whether or not an operator is an observable cannot depend on the basis you expand it with? However, I know that there are non-Hermitian operators that have real eigenvalues, so perhaps, it is the case that Hermiticity merely guarantees that an operator is an observable, so that it is possible that an operator might be non-Hermitian in a given basis and yet still represent an observable? Thank you for your time and consideration. Answer: A linear operator on a Hilbert space $A:\mathcal H\to\mathcal H$ is Hermitian if for all $v,w\in\mathcal H$, $$\langle Av, w\rangle = \langle v,Aw\rangle$$ This definition makes no reference to any particular basis, since both the inner product and the linear operators on the Hilbert space are defined independently of any basis. Therefore Hermiticity is a property of the operator and not what basis it is represented in.
{ "domain": "physics.stackexchange", "id": 100182, "tags": "quantum-mechanics, operators, hilbert-space, definition" }
Effective Force in a spinning bucket
Question: If we consider a bucket of water spinning about it's symmetric axis with angular velocity $\boldsymbol{\omega}$, and define a rotating polar coordinate system with origin at the bottom and center of the bucket, we should see that there are two contributing components to the effective force. A gravitational force in the $\hat{\textbf{z}}$ direction and a centrifugal force in the $\hat{\textbf{r}}$ direction. $$\boldsymbol{F}_\text{eff} = mg\hat{\boldsymbol{z}} + m\omega^2r\hat{\boldsymbol{r}}$$ However, when I compute the centrifugal force for an arbitrary vector $\boldsymbol{r} = \langle r, \theta, z \rangle$, I find it has a $\hat{\boldsymbol{z}}$ component (using $\boldsymbol{\omega} =\langle 0, \omega, 0 \rangle$) : $$\boldsymbol{F}_\text{cf} = -m\boldsymbol{\omega} \times (\boldsymbol{\omega}\times\boldsymbol{r}) = \langle m\omega^2r, 0, m\omega^2z\rangle $$ So what's gone wrong here? There should not be a $\hat{\boldsymbol{z}}$ component of centrifugal force in this case as I understand it. Answer: $\mathbf{\omega}=\langle 0,0,\omega \rangle$ is oriented along the $z$ axis, not the $\theta$ axis.
{ "domain": "physics.stackexchange", "id": 73692, "tags": "rotation, centrifugal-force" }
How is compression ratio related to number of dct coefficients
Question: Lets say we have a picture with 6bits/pixel and we use discrete cosine transform with 8x8 blocks of pixels and each coefficient is 8 bits. We can use 2 8x8 masks, a zonal mask A and a zonal bit allocation mask B. A = [1 1 1 1 1 0 0 0 1 1 1 1 0 0 0 0 1 1 1 0 0 0 0 0 1 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ...... ] B = [8 7 6 4 3 2 1 0 7 6 5 4 3 2 1 0 6 5 4 3 3 1 1 0 4 4 3 3 2 1 0 0 3 3 3 2 1 1 0 0 2 2 1 1 1 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 ] Is it correct to say that for A we have 64 : 15 compression namely 4.2 : 1 cause we keep 15 coefficients out of 64? does the same apply for B ? Answer: Compression ratio is defined as the amount of bits in the original image divided by the amount of bits in the compressed image. In the original image the number of coefficients is 64, while you choose 15 coefficients after DCT in the compressed image with mask A. The ratio is 64*6/15*8. With mask B it is 64*6/41*8
{ "domain": "dsp.stackexchange", "id": 1588, "tags": "image-processing, dct, compression" }
On equivalence of NLBA and DLBA
Question: Where I can find reference and documents on the work made for proving whether DLBA are equal NLBA nr not? What is the underlying problem? Why it is still an open question in TCS? Answer: The 1998 chapter about the second LBA Problem, from Schöning and Pruim Gems of TCS mentions the first LBA problem. The chapter does not say much more than the wikipedia article though, apart from mentioning the related Savitch's theorem, whose optimality is a notorious open question. Perhaps by looking at papers quoting the Kuroda or Savitch paper you could get a picture of recent results in the field?
{ "domain": "cstheory.stackexchange", "id": 2507, "tags": "automata-theory" }
Can this be considered wide sense stationary?
Question: I was discussing this problem with one of my classmates. The picture shows a recording of the heart rate during before and after sleep. Can the whole process be considered wide sense stationary? (I say yes because the mean is approximately constant, but how can I estimate the autocorrelation?) Can the whole process be considered ergodic in autocorrelation and mean? (I'm not sure at all about this) Answer: for 1, a random process is WSS if its autocovariance and mean ensemble average don't vary as a function of specific time instance, just lag. As mentioned before, it's hard to conclude this from simply one realization of the process about the ensemble average. However for 2, you can at least estimate what the autocovariance and mean are if the process is ergodic (which, unfortunately, you can't conclude with just a single realization). If the process is indeed ergodic, the ensemble average is equal to the time average in the limit as your interval of average approaches infinity, which is kind of nice with regards to computability.
{ "domain": "dsp.stackexchange", "id": 5886, "tags": "autocorrelation, ergodic" }
How to reflect quantum uncertainty in statistical mechanics?
Question: How does the superposition principle of the quantum mechanics reconcile with the statistical mechanics? Because in deriving canonical distribution, I don't see anything related to superposition principle, but canonical distribution can be used to describe quantum systems, for example, a single quantum oscillator in thermal contact with a heat reservoir.So how to derive canonical distribution not from the eigenstates of the Hamiltonian but from the superposition states? More generally speaking, how to reflect quantum uncertainty in statistical mechanics? Answer: The answer to your question "how to put quantum uncertainty into statistical mechanics" is: with the density matrix. Full description is in textbooks etc,(Feynman's Lectures on Statistical Mechanics, and von Neumann's Mathematical Foundations of Quantum Mechanics are good) but briefly you have a standard ensemble (canonical, microcanonical, or whatever) of $N$ systems with system $i$ in state $|\phi_i>$ (not necessarily eigenstates). Introduce the density operator, $\hat \rho={1 \over N} \sum_{i=1}^N |\phi_i> <\phi_i|$. That's the statistical mechanics bit. Now the quantum. Introduce a basis set of states $|\psi_j>$ which are eigenstates of some operator you're interested in (you have a choice), and the density matrix is defined using these states. $\rho_{jk}=<\psi_j| \hat \rho|\psi_k>={1 \over N} \sum_{i=1}^N<\psi_j |\phi_i> <\phi_i|\psi_k>$. The diagonal elements $\rho_{kk}$ then give the probability that if you measure a random member of the ensemble it will turn our to be in the $k$ eigenstate, and that includes the statistical probability, from the ${ 1\over N } \sum$, and the quantum probability from the $|<\psi|\phi>|^2$. It can also be used to give expectation values for operators. The off-diagonal elements contain information about the nature of the uncertainty. A classic example is an ensemble of electrons which are half spin up and half spin down, compared to an ensemble which are all spin sideways (aligned along, say, the x axis). In both cases, both diagonal elements are just $1 \over 2$, whereas the off diagonals are zero in the first case but not the second. Incidentally, the whole 'collapse of the wave function' business is equivalent to setting all off diagonal elements of the density matrix to zero.
{ "domain": "physics.stackexchange", "id": 65384, "tags": "quantum-mechanics, statistical-mechanics" }
Making a basic sprung mechanism that can withstand moderate percussive force
Question: I'm making a game where you have to hit targets, kind of like whack-a-mole except the targets aren't actively actuated. I'd still like an element of mechanical "feel" to it, so I'm aiming to put the targets on a rod with a spring, so that when you whack it, it goes down, triggers a limit switch so the game knows you've hit it, and it springs back up. See below for a rough model. The intention is to use an off-the-shelf shaft, spring and shaft collar. In terms of scale, the target is going to be somewhere in the range of cue ball to grapefruit, and made from a light material (e.g. plastic, resin, etc), so the spring doesn't have to be particularly strong. (I realize this is slightly vague, but it's TBD and I'm only tasked with making the mechanism.) It needs to withstand a few hundred whacks per day for a couple of months. The mallet will be coated in thick foam but wielded by members of the public. Would using linear bearings in the brackets or a linear bearing pillow block as the whole bracket be overkill? Is there an off-the-shelf component I could use for the bracket otherwise, or would I be better to have a metal bracket fabricated? I've hunted around for a while, but I don't know what to call that kind of bracket. I've also considered 3D-printing a bracket, but I'm not sure if it will be strong enough to put up with repeated whacks. Might I get away with it if I designed enough bracing into the bracket? The limit of the travel can be set by a fixed surface (e.g. the cabinet) so theoretically the bracket primarily needs to withstand the force applied to it by the spring under compression, but if the target is whacked diagonally, the bracket must withstand the lateral force too. Another option I have considered is laser cutting 1/2" ply to make a box-jointed housing, but not sure if the wood against the metal will make a kind of jittery movement. I'm imagining kind of like below, but with box joints and probably an extra sort of lintel under the horizontal pieces. I have time and resources to try a couple of simple prototypes, but I can't feasibly whack it thousands of times to see if it gives. Answer: I'd probably make the brackets out of a low-friction plastic like nylon. You could 3D print them, but they are (or at least can be) simple enough that there may not be much point. Assuming you're only making a relatively small number, I'd probably just get rectangular nylon bar stock, drill a suitable-size hole and cut it to length (and probably a couple screw holes to mount it). No need for the L-shaped mounting base--just use thick enough material to mount as rectangle. Something along this general order: That'll use a little more material than the L-shaped bracket you've drawn, but the savings in fabrication time will more than compensate. Given the application, it doesn't seem as if the slight increase in friction from a larger bearing surface is at all likely to matter. At the opposite extreme, if you were going to be making millions of these, it would probably make sense to get molds made, and have essentially the entire mount injection molded. This has much higher initial cost (molds are pretty expensive) but reduced unit cost. As far as dealing with lateral forces, I'd mostly try to design it to minimize the ability to exert lateral force in the first place. If you look at a typical whack-a-mole kind of game, the button that sticks up won't be a hemisphere. It'll have a much larger radius, so the user has no way to hit it that produces significant lateral force. The "button" that sticks up is also a tight enough fit in the hole that you can't really move it very far laterally in any case. You could also use a shaft that's flexible enough (e.g., probably also plastic) that most lateral force would simply flex the shaft rather than being transmitted to the brackets.
{ "domain": "engineering.stackexchange", "id": 5290, "tags": "mechanical-engineering, mechanisms, metalwork" }
Atomic mass ratios - Is the problem providing enough info?
Question: One gram of Hydrogen reacts with exactly (almost) 8 grams of oxygen to produce $\ce{H2O}$. Another single gram of Hydrogen reacts with 16 grams of Oxygen to produce $\ce{H2O2}$. Can the ratio $\frac{m_O}{m_H}$ be determined from this information? If not, what else do chemists need to know to find this ratio? Answer: Are you asking whether we can figure out the ratio of the mass of an oxygen atom to a hydrogen atom from this information? If so, then the answer is yes, assuming that you know that $\ce{H2O}$ and $\ce{H2O2}$ are the formulas for each compound, and that atoms exist and are indivisible in chemical reactions. $$2n\space \rm{atoms \space H} = 1 \space g \space H$$ $$1n \space \rm{atoms \space O} = 8 \space g \space O$$ Divide the second equation by the first: $$\frac{1n \space \rm{atoms \space O}}{2n\space \rm{atoms \space H}} = \frac{8 \space g \space O}{1 \space g \space H}$$ Cross multiply to get a 16:1 mass ratio. You can confirm this by looking at $\ce{H2O2}$, where the ratio of atoms is 1:1 and mass is again 16:1. If you didn't know the formulae, then you could assume that the ratio was some integer multiple of 8:1, but without more data you wouldn't know which. This is because you would not know whether water had a 1:1 atom (or mole) ratio of $\ce{H}$ to $\ce{O}$, or if it was something else. Incidentally, what you are describing is the law of multiple proportions, and it is one of the key findings that led to the development of atomic theory.
{ "domain": "chemistry.stackexchange", "id": 2787, "tags": "stoichiometry" }
Measure code/node running time
Question: I'm running amcl package for offline data and I want measure its running time, Is there something like MATLAB's tic and toc command? Originally posted by maysamsh on ROS Answers with karma: 139 on 2014-05-17 Post score: 0 Answer: I'm not sure this is what you're looking for but Tic Toc in C++. You could add in your amcl node. EDIT : I had to use something similar myself and realize the link in made for windows. Here is what you're suppose to use on linux : Clock Originally posted by Maya with karma: 1172 on 2014-05-17 This answer was ACCEPTED on the original site Post score: 2
{ "domain": "robotics.stackexchange", "id": 17989, "tags": "ros, package" }
Convert length of time to appropriate unit
Question: I have a time, in seconds, which has the possibility to be very large. I wish to convert said time into the "appropriate" rounded, readable format. I already have code which achieves this, however it's not very efficient (and contains a whole bunch of magic numbers): String readable = decayTime + " minutes"; if(decayTime > 60) { decayTime /= 60; readable = decayTime + " hours"; if(decayTime > 24) { decayTime /= 24; readable = decayTime + " days"; if(decayTime > 365) { decayTime /= 365; readable = decayTime + " years"; if(decayTime > 1000000) { decayTime /= 1000000; readable = decayTime + "mn years"; if(decayTime > 1000) { decayTime /= 1000; readable = decayTime + "bn years"; } } } } Apart from switching out the magic numbers, I can't personally think how to make it better. What would be a better approach to this, or is there something in-built which could help? Answer: Here's one approach, using TreeMap. It looks up your number of milliseconds in a pre-populated map, finds the appropriate entry and does the division. Just create one of these objects, and call the format method as many times as you need to. Note that it's not quite right for negative arguments to format - but you might want to put your own logic in around that, for example, to throw some kind of exception. import java.util.Map; import java.util.NavigableMap; import java.util.TreeMap; public class TimeFormatter { private NavigableMap<Long,String> timeUnits = new TreeMap<>(); public TimeFormatter() { timeUnits.put(Long.MIN_VALUE, " is not a valid argument"); timeUnits.put(1L, " milliseconds"); timeUnits.put(1000L, " seconds"); timeUnits.put(60 * 1000L, " minutes"); timeUnits.put(60 * 60 * 1000L, " hours"); timeUnits.put(24 * 60 * 60 * 1000L, " days"); timeUnits.put(365 * 24 * 60 * 60 * 1000L, " years"); timeUnits.put(1000000L * 365 * 24 * 60 * 60 * 1000L, " million years"); timeUnits.put(1000000000L * 365 * 24 * 60 * 60 * 1000L, " billion years"); } public String format(long milliseconds) { Map.Entry<Long,String> unitBelow = timeUnits.floorEntry(milliseconds); return milliseconds / unitBelow.getKey() + unitBelow.getValue(); } }
{ "domain": "codereview.stackexchange", "id": 21757, "tags": "java, datetime, formatting, unit-conversion" }
Household Melting Point Standards
Question: I'd like to accurately calibrate a digital thermometer I'm building in the range of $50^\circ$ to $120^\circ$ Celsius. I'm aware that one can buy various chemicals that have melting points in this range, but are there any readily available household / pharmaceutical items I could use instead? From what I have read, it looks like the two easiest candidates would be vanillin or Sodium acetate (Thanks Curt F.), but I'm not sure how one would go about creating a pure enough calibration standard at home. Answer: According to this cooking site, Crisco brand vegetable shortening melts between $\mathrm{47^oC-48^oC}$ (yes, I know $\mathrm{48^oC}$ is less than $\mathrm{50^oC}$, but it seems pretty close to me). The best way to use such a non-certified melting point "standard" like this is to use your thermometer side-by-side with a properly calibrated thermometer. Vanillin may be your best bet (melting point of $\mathrm{81^oC - 83^oC}$). Again, using a calibrated thermometer to check the actual melting point would be the ideal situation. Although your question asks about calibrating based on melting point measurements of household items, household items just aren't usually of the purity required for accurate melting point based thermometer calibration. In the absence of a calibrated thermometer as discussed above, the best way to calibrate your thermometer is probably to use the freezing and boiling points of water (don't forget to adjust boiling point for altitude if you don't live at sea level), then check the melting points of Crisco and vanillin if you want. Good agreement with these stated melting points would be a good indicator of proper thermometer calibration, while poor agreement could either be due to improper thermometer calibration or impure material.
{ "domain": "chemistry.stackexchange", "id": 7656, "tags": "physical-chemistry, melting-point, equipment" }
Where is the second face in a graph with 3 nodes?
Question: I understand that to work out the number of faces of a connected planar graph, you use Euler's formula F = A - N + 2, where A is the number of arcs and N is the number of nodes. For a triangle node (3 arcs and 3 nodes), the number of faces would therefore be 3 - 3 + 2 = 2. But I can't count two faces, only one (the triangle itself). Where is the second face, or where have I misunderstood? Answer: You probably smack your head against the wall for this but: One face "inside" the triangle, the other one is "outside".
{ "domain": "cs.stackexchange", "id": 11157, "tags": "graphs, planar-graphs" }
Let G be a graph directed without circles. Suggest a method to find a minimum set of vertices So that all the vertices in the graph can be reached
Question: Let G be a graph directed without circles. Suggest a method to find a minimum set of vertices So that all the vertices in the graph can be reached. I thought to run an SCC algorithm to find binding components and then return them. This is true? Or is there a better algorithm? Answer: Considering the strongly connected component is a good start if graph $G$ may have cycles. However, as implied by Pål GD, every vertex is a strongly connected component of a graph without cycles. We need to do more work to find the minimum set of vertices from which all vertices can be reached. Here is the outline of an algorithm that does the job. Find one root $r$ of $G$ by repeatedly going to the ancestor of a node. Mark $r$ as an wanted vertex. Remove all vertices reachable from $r$. Go to step 1 unless there is no more vertex. return all vertices that are marked as wanted. Exercise. Given a directed graph (that may have cycles), describe an algorithm that finds a minimum set of vertices from which all vertices can be reached. (Hint, strongly connected components are useful now. Try reducing the problem to the current question.)
{ "domain": "cs.stackexchange", "id": 13098, "tags": "algorithms, graphs, optimization, dag" }
How do we know what the biggest star is?
Question: Kurzgesagt claims that the largest (observable) star in the universe would be Stephenson 2-18 which is in line with Wikipedia: It is among the largest known stars, if not the largest, and one of the most luminous red supergiants, with an estimated radius around 2,150 times that of the Sun, which corresponds to a volume nearly 10 billion times bigger than the Sun. Furthermore, Wikipedia says The open cluster Stephenson 2 was discovered by American astronomer Charles Bruce Stephenson in 1990 in the data obtained by a deep infrared survey. I stumbled upon that statement for two reasons: The survey was made in 2010, so if we again would make a survey with newer, higher resolution data (which I assume we might have in the mean time), would we find other objects even bigger? How are we sure that St2-18 was indeed the largest object within the given survey? Technically speaking, one would have to calculate at least the distance or lumnosity for each object of the survey? In a nutshell: How sure are we (in percent) that St2-18 is right now, in 2020, still the largest observed star? Related What is the largest hydrogen-burning star? Is there a theoretical maximum size limit for a star? Answer: As @uhoh stated, there is a crucial distinction between what is in principle "observable" and what we have to-date "observed." Also, you have to specify whether you're talking about biggest in radius or biggest in mass. For stars with very large radii, like the St2-18 system you've referenced, they often can't even constrain the mass! And when they are able to, they end up having pretty small masses, i.e. UY Scuti. Stars, especially high-mass stars, generally increase in radius as they age, but they lose mass as they age. So it's not surprising to find red supergiants with very large radii (because they're at a late stage in their stellar evolution) and with small masses. But the theory behind supergiant stars is very complicated and uncertain still, making mass measurements very very difficult (And thus are not usually attempted) since mass measurements require some kind of binary interaction or a well-understood model of the stellar atmosphere (which is lacking for supergiants as I understand). Regarding what's "observable," keep in mind that this is a fast-changing landscape: for example, gravitational wave detections of intermediate-mass black holes suggest that they possibly form from core-collapse of super-massive stars (among other possibilities). And the link to the question "what is the size limit theoretically of a star" that you provided has many answers which explain how uncertain such a theoretical limit is for mass and for radius. Regarding "observed" systems, you must take into consideration the error bars on mass measurements of stars. The largest observed star with a known mass that has respectable error bars is the Wolf-Rayet star R136a1. See here for a comprehensive list. With that said, you asked, How sure are we (in percent) that St2-18 is right now, in 2020, still the largest observed star? Of course there is always the possibility that with a new survey with better resolution, larger field of view, etc... even larger stars may be in the universe. It's a zoo! We were surprised to find stars as big as St2-18, so why would the universe stop there, eh? There COULD BE SOME reason in principle that disallows larger stars, but the universe keeps providing bigger and bigger stars for us to ponder, so there's no reason a priori to assume so. Regarding the survey you're asking about in particular, the wiki article has a nice discussion explaining the great uncertainty in determining the radius of St2-18, i.e. do we rightly consider it as part of the cluster or not in order to make assumptions about its distance, etc...: A calculation for finding the bolometric luminosity by fitting the Spectral Energy Distribution (SED) gives the star a luminosity of nearly 440,000 L☉, with an effective temperature of 3,200 K, which corresponds to a very large radius of 2,150 R☉ (1.50×109 km; 10.0 au; 930,000,000 mi),[a] which would be considerably larger and more luminous than theoretical models of the largest, and most luminous red supergiants possible (roughly 1,500 R☉ and 320,000 L☉ respectively).[11][6] An alternate but older calculation from 2010, still assuming membership of the Stephenson 2 cluster at 5.5 kpc but based on 12 and 25 μm fluxes, gives a much lower and relatively modest luminosity of 90,000 L☉.[7] A newer calculation, based on SED integration and assuming a distance of 5.8 kpc, gives a bolometric luminosity of 630,000 L☉ although the authors are doubtful that the star is actually a member of the cluster and at that distance. Lastly, you asked How are we sure that St2-18 was indeed the largest object within the given survey? Technically speaking, one would have to calculate at least the distance or lumnosity for each object of the survey? I quickly looked at the survey report paper, and it seems that this is actually unclear. Keep in mind that they were surveying a few different clusters, the Stephenson#2 being only one of them. The tables at the end of their paper make that clear. However, they only list the technical properties, and do not even attempt to constrain the radii for all of these stars. So I'd take it with a grain of salt.
{ "domain": "astronomy.stackexchange", "id": 5099, "tags": "star, size" }
Books describing first-hand experience of astrophysicists finding planets without skipping actual maths
Question: Are there good references of astronomical texts where we get a first-hand experience of astronomers uncovering astronomical gems using maths alone and not using observation. Observation may have been used later to validate the result. In this book, there are several examples of astronomical jewels that were uncovered by the professionals. However the book shies away from describing the actual maths that aided the astrophysicists to make their conclusions and predictions that were later confirmed by experimenters. However, how does a professional astronomer come to conclusions that there must be one more planet at so and so location? Are there books that uncover the exact line of thinking and maths that is involved behind the works of the professionals? I am not looking for a book which solves a toy problem rigorously using Newton's laws and then concludes that the 21st century astronomers use similar techniques at grander scales in their works. Though this is what is happening, i am looking for a more transparent description of how the pioneer discoverers make astronomical predictions with surety. The ideal place to look would be the research papers of these pioneers but is there a book that does that for many such achievements? Answer: The discovery and recapture of Ceres, and the brilliant discovery and use by Gauss of the Normal distribution, the method of least squares, and a method that would now be thought of as a type of fast fourier transform to predict the position of the planet to within 0.5 degrees, based on just 6 observations is one of the great achievements of "pen and paper astronomy". Gauss, though we now think of him as a pure mathematician, held the post of Professor of Astronomy in Göttingen. Discovery of the First Asteroid, Ceres: Historical Studies in Asteroid Research by Clifford Cunningham, ISBN 978-3-319-21777-2 tells this story in some detail, but ouch its not cheap! nearly £100 on dead trees.
{ "domain": "astronomy.stackexchange", "id": 1623, "tags": "astrophysics, fundamental-astronomy, resource-request" }
Choice of lower bound of curve for PV work
Question: I am told that the area under the PV curve gives the magnitude of work done by a gas. Let $V_i$ be the initial volume, $V_f$ be the final volume, and the pressure as a function of volume be given by $P=f(V)$. To my understanding, the work done is given by the area bounded by $x=V_i$, $x=V_f$, $P=F(v)$ and $y=0$. Proceeding in the above stated manner, the work done comes out to be the sum of the areas of green and yellow region, but the answer stated neglects the yellow region. Origin of Question : JEE MAIN Here's the answer according to the official answer key released by the testing agency: Answer: The error comes from reading the graph: the crossing of the axes corresponds to the point (2,2) and not (0,0)
{ "domain": "chemistry.stackexchange", "id": 15135, "tags": "thermodynamics" }
How to reduce Untyped λ-Calculus to Normal Form?
Question: I have an assignment to do which involves reducing an Untyped λ-Calculus expression to Normal Form. I am struggling to come to terms with Lambda Calculus though. For example, one small part of the expression is: ((λ n f x . n f (f x)) (λ f x . x)) Does this mean that we substitute (λ f x . x) in for every n, f and x? Giving us the following: ((λ n f x . (λ f x . x) (λ f x . x) ((λ f x . x) (λ f x . x)))) If so, can this be reduced further? I know I am probably way off with this, but I just do not understand it; any help would be appreciated. Answer: EDIT: Thanks to @ljedrz Comment. Before doing the reduction is worth noting that: $$ (\lambda n f x . n ~ f (f ~ x)) = (\lambda n f x .((n f) (f ~ x))) $$ This is a convention, the parenthesis always associate to the left It can be reduced further, but I advise you to change the second expression to an $\alpha$-equivalent one. $$ \Big(\big(\lambda n f x . (n ~ f) (f ~ x) \big) ~ (\lambda h y . y) \Big) $$ This might not be necessary in this specific problem, but might also save you some headache later trying to keep track if some free variables got captured. \begin{align*} \Big(\big(\lambda \color{red}{n} f x . \color{red}{n} ~ f (f ~ x)\big) ~ \color{red}{(\lambda h y . y)} \Big) &\rightarrow_\beta \big[n ~ / ~(\lambda h y . y)\big] \big(\lambda f x . n ~ f (f ~ x)\big)\\ &\rightarrow_{\alpha} \big( \lambda f x. (\lambda h y. y) ~ f ~ (f~x) \big)\\ \Big( \lambda f x. \big((\lambda \color{red}{h} y. y) ~ \color{red}{f}\big) ~ (f~x) \Big) &\rightarrow_{\beta} \Big(\lambda f x.\big[h ~ / ~ f \big]\big(\lambda y.y\big) ~ (f ~ x) \Big)\\ \Big( \lambda f x. ((\lambda y. y)) ~ (f~x) \Big) &\rightarrow_{\beta} \Big(\lambda f x.\big[y ~ / ~ (f ~ x)\big]y\Big)\\ &\rightarrow_{\alpha} \Big(\lambda f x. (f ~ x) \Big) \end{align*} Which cannot be reduced further.
{ "domain": "cs.stackexchange", "id": 10569, "tags": "lambda-calculus" }
Write a message to a log
Question: I have started to read Robert C. Martin Clean Code book. To learn and gain more expreiences I wrote a single Log class. So I want some suggestions to improve this code.. This is a part of the Log class: public class FileLogger : ILog { private string directoryPath = string.Empty; private string fileName = string.Empty; public FileLogger(string logDirectoryPath, string logFileName) { if (string.IsNullOrEmpty(logDirectoryPath)) { throw new ArgumentException(nameof(logDirectoryPath), "Write some error message..."); } if (string.IsNullOrEmpty(logFileName)) { throw new ArgumentException(nameof(logFileName), "Write some error message..."); } this.directoryPath = logDirectoryPath; this.fileName = logFileName; } public void LogMessage(string message) { try { if (!string.IsNullOrEmpty(message)) { if (!LogDirectoryExists(directoryPath)) { CreateLogDirectory(directoryPath); } WriteToLogFile(message); } } catch (Exception ex) { //Catch exception, do something... } } private bool LogDirectoryExists(string logDirectoryPath) { return Directory.Exists(logDirectoryPath); } private void CreateLogDirectory(string logDirectoryPath) { Directory.CreateDirectory(logDirectoryPath); } private void WriteToLogFile(string message) { using (var logFile = new FileStream(Path.Combine(directoryPath,fileName), FileMode.Append, FileAccess.Write)) { using (var logFileWriter = new StreamWriter(logFile)) { logFileWriter.Write(message); } } } } I wrote 3 different function to write a message to a log. I try to use SRP and Command Query Separation, but I don't sure this is a good in this way. Maybe there are another problems with this code, example naming or variable declarations. Answer: After discussion in comments your code became much better. Also if directoryPath and fileName will not be changed after initialization in constructor you can define these fields as readonly: private readonly string directoryPath = string.Empty; private readonly string fileName = string.Empty; This code using (var logFile = new FileStream(Path.Combine(directoryPath,fileName), FileMode.Append, FileAccess.Write)) { using (var logFileWriter = new StreamWriter(logFile)) { logFileWriter.Write(message); } } can be replaced with File.AppendAllText(Path.Combine(directoryPath, fileName), message); Also ArgumentException's constructor takes message as first argument and paramName as second, so you need to call it like this: throw new ArgumentException("Write some error message...", nameof(logDirectoryPath));
{ "domain": "codereview.stackexchange", "id": 26509, "tags": "c#, beginner, file, logging" }
What does "AC0 many-one reduction" mean?
Question: What does $\mathsf{AC^0}$ many-one reduction mean? I know about polynomial time reductions, but I'm not familiar with $\mathsf{AC^0}$ reductions. Answer: An AC0 many-one reduction is a many-one reduction that can be implemented by an AC0 circuit. It's just like a polynomial-time many-one reduction, except that instead of requiring that the mapping takes polynomial time, we require that the mapping is in AC0. David Richerby further explains: "AC0 is a very low-complexity class so it can be used, for example, to study reductions between logspace problems, which doesn't make sense with polytime reductions since, then, the reduction would be more powerful than the problem class being studied." For instance, if problems A,B can be reduced to each other with polynomial-time reductions, then you learn that their complexity can't be exponentially different (if one is polynomial, the other must be too), but it's possible that they still might be fairly different (polynomially different). If they can be reduced to each other with AC0 reductions, then this has stronger implications about their complexity (it has to be pretty similar).
{ "domain": "cs.stackexchange", "id": 11575, "tags": "reductions, circuits" }
Installation problems
Question: Hi, i have ubuntu 12.04 installed few day ago. when i try to install ROS, my terminal give me this: $ sudo apt-get install ros-indigo-desktop-full Reading package lists... Done Building dependency tree Reading state information... Done Some packages could not be installed. This may mean that you have requested an impossible situation or if you are using the unstable distribution that some required packages have not yet been created or been moved out of Incoming. The following information may help to resolve the situation: The following packages have unmet dependencies: ros-indigo-desktop-full : Depends: ros-indigo-desktop but it is not going to be installed Depends: ros-indigo-perception but it is not going to be installed Depends: ros-indigo-simulators but it is not going to be installed E: Unable to correct problems, you have held broken packages. i'm not so good using ubuntu, but what can i do for solve the problem?? thank you very much! Jacopo Originally posted by JacoPisa on ROS Answers with karma: 110 on 2014-10-21 Post score: 0 Answer: You should install indigo in Ubuntu 14.04 (Trusty) as stated here. Originally posted by Andromeda with karma: 893 on 2014-10-21 This answer was ACCEPTED on the original site Post score: 0
{ "domain": "robotics.stackexchange", "id": 19793, "tags": "ros, installation, ros-indigo" }