anchor
stringlengths
0
150
positive
stringlengths
0
96k
source
dict
Swift HackerRank Balanced Brackets
Question: I solved this stack problem in Swift. Looking for any feedback on my code: import Foundation /// Returns an integer read from one line of standard input. func readInteger() -> Int { guard let line = readLine() else { fatalError("Unexpected end of input") } guard let i = Int(line) else { fatalError("Invalid integer in input") } return i } /// Returns an array of Characters func readStrings() -> [Character] { guard let line = readLine() else { fatalError("Unexpected end of input") } return line.characters.map{ $0 } } // checks if all brackets are balanced func balancedBrackets() { let sequences = readInteger() // outloop loops through each sequence line outerLoop: for _ in 0..<sequences { // create a stack (array in this case) var stack = [Character]() // each line of sequence let sequence = readStrings() // edgeCase is when there are only opening brackets in stack and didn't reach case } ] ) var edgeCase = false // inner loop loops through each bracket character innerLoop: for bracket in sequence { switch bracket { // if opening brackets, append and set edgeCase case "{", "[", "(": stack.append(bracket) // case closing brackets case "}", "]", ")": // checks for empty stack or if the bracket pairs arent matching if stack.isEmpty || (bracket == "}" && stack.last != "{") || (bracket == "]" && stack.last != "[") || (bracket == ")" && stack.last != "(") { edgeCase = true print("NO") // append closing bracket so YES doesn't print when breaking stack.append(bracket) // break out of checking anymore brackets break innerLoop } stack.removeLast() default: fatalError("unknown bracket found") } } // if empty if stack.isEmpty { print("YES") } else if !edgeCase { // stack has opening brackets and hasn't reach if statement in case } ] ) print("NO") } } } balancedBrackets() Answer: readStrings() is better named readCharacters() because that is what it does. I prefer Array(...) instead of .map { $0 } to convert a sequence into an array, but that is a matter of taste: /// Reads one line from standard input and returns the result /// as an array of characters. func readCharacters() -> [Character] { guard let line = readLine() else { fatalError("Unexpected end of input") } return Array(line.characters) } My main point of criticism is that the logic in your main function is far too complicated. The outerLoop: label is not used. The inner loop is confusing, and comments like // append closing bracket so YES doesn't print when breaking // stack has opening brackets and hasn't reach if statement in case } ] ) clearly indicate a code smell. The problem is that you have one single function doing all the work. It immediately becomes simpler if you separate the I/O from the actual computations (which is generally a good idea): func isBalanced(sequence: [Character]) -> Bool { // ... return `true` or `false` ... } func balancedBrackets() { let numSequences = readInteger() for _ in 0..<numSequences { let sequence = readCharacters() let balanced = isBalanced(sequence) print(balanced ? "YES" : "NO") } } balancedBrackets() This makes the code more modular, better readable, and allows you to add test cases easily. The isBalanced() function can "early return" if a non-match is found, making the labels and the special edgeCase variable obsolete: func isBalanced(sequence: [Character]) -> Bool { var stack = [Character]() for bracket in sequence { switch bracket { case "{", "[", "(": stack.append(bracket) case "}", "]", ")": if stack.isEmpty || (bracket == "}" && stack.last != "{") || (bracket == "]" && stack.last != "[") || (bracket == ")" && stack.last != "(") { return false } stack.removeLast() default: fatalError("unknown bracket found") } } return stack.isEmpty } But the repeated usage of character literals is still error-prone. Better define an enumeration: enum Bracket: Character { case Left = "(" case Right = ")" case LeftCurly = "{" case RightCurly = "}" case LeftSquare = "[" case RightSquare = "]" } Determining the matching open bracket for a given closing bracket can be made a computed property of this enumeration: enum Bracket: Character { case Left = "(" case Right = ")" case LeftCurly = "{" case RightCurly = "}" case LeftSquare = "[" case RightSquare = "]" /// For a closing bracket, the corresponding opening bracket is returned. /// For an opening bracket, `nil` is returned. var matchingOpen: Bracket? { switch self { case .Right: return .Left case .RightCurly: return .LeftCurly case .RightSquare: return .LeftSquare default: return nil } } } Now the isBalanced() function does not use any explicit bracket values anymore: func isBalanced(sequence: [Character]) -> Bool { var stack = [Bracket]() for char in sequence { if let bracket = Bracket(rawValue: char) { if let open = bracket.matchingOpen { // `bracket` is a closing bracket and `open` the corresponding opening bracket: guard let last = stack.last where last == open else { return false } stack.removeLast() } else { // `bracket` is an opening bracket: stack.append(bracket) } } else { fatalError("unknown bracket found") } } return stack.isEmpty } If you decide to add another type of brackets later (e.g. «») then only the enumeration needs to be extended, but not the isBalanced() function.
{ "domain": "codereview.stackexchange", "id": 21301, "tags": "programming-challenge, swift, balanced-delimiters" }
Is it possible to set quantum volume in IBM Quantum simulator?
Question: A quantum volume serves as a metric of a quantum processor quality. So far, IBM Quantum provides processors with quantum volume up to 128. Freely accessbile processors have QV up to 32. A user using free access can employ fake processors (see details here) to simulate behavior of her/his circuits on processor with QV higher than 32. However what about simulation of processors with QV above 128? Is it possible to somehow set qasm_simulator to behave like a processor with given quantum volume? Answer: Bear in mind that if you operate on a subset of $n$ qubits, then your QV is at most $2^n$. Hence the answer below assumes that you'd like to experiment with a simulator that has $n$ qubits but some $QV = 2^m$ where $m < n$. I am not aware of a solution out of the box, but you could: specify noise models and coupling map for your simulator compute such setup's QV iterate on noise parameters until you reach your desired QV. By definition your simulator has QV essentially equal to 2 to the power of number of qubits, so you are essentially trying to force some limitations onto it.
{ "domain": "quantumcomputing.stackexchange", "id": 3353, "tags": "qiskit, ibm-q-experience, simulation, quantum-volume" }
The Dual Nature of Matter
Question: I can't seem to understand the dual nature of matter completely. If electrons have a wave nature, then if two electrons were to collide, wouldn't they undergo interference and form an electron wave of larger or smaller amplitude? Does that mean the electrons merge and turn into a "bigger" electron? Then again, this would mean that the electrons would have a phase difference, so what determines the phase of matter? Also, if we were to consider two photons colliding, would they also undergo interference and form a "bigger" photon? Why don't normal everyday objects undergo interference? Just because the wavelength (according to the de Broglie equation) of something is small doesn't mean that it doesn't undergo interference (take for example gamma rays which have a very small wavelength but are the most powerful form of radiation). Answer: First one needs to understand that electrons, and nature in general, are what they are - neither waves nor particles. Whether they exhibit wave like or particle like behaviour depends on the experiments we do. An electron microscope, for instance, uses interference between many electrons to create an image of the object. For a long time people doubted the ability of matter to change properties depending on what WE, the observer, did, but Alain Aspect and others showed that the result of an interference experiment does depend on our choice to measure interference, even of we set things up so that the choice is made after all the photons have travelled past the mirrors/slits in question. For quantum mechanical waves, except in interesting topological circumstances, phases are usually unobservable. The amplitudes may be multiplied by any phase without affecting the outcome of the experiment, which is determined by the (real) squares of the amplitudes. The phases are certainly necessary for the description of waves, but it is not right to say 'the phase of matter'. There is also nothing 'bigger', because as a state/ensemble evolves the total of all amplitudes squared is conserved - this is the law that probabilities always sum to 1. If you want to think of intensity, as in the number density of photons in a beam, this might be changed by various means, but remember that you are then talking about many photons. If you integrate the interference pattern, the expected total intensity does not change from what it was. Everyday objects do undergo interference, but on such large scales that we cannot separate the effects from the complex world around us, the quantum state of which defies description. Some people doubt this, but all evidence indicates that the world really is a quantum one.
{ "domain": "physics.stackexchange", "id": 6735, "tags": "electrons, wave-particle-duality" }
Encryption Algorithm in C#
Question: I'm coding a "encryption" algorithm for learning and and don't know how good is it or how could I make it better: private static byte[] encrypt(byte[] data, int session_id, byte[] password) { int session_key = (session_id & 0xFF); if (session_key == 0) session_key = (session_id << 4); byte[] output = new byte[data.Length]; for (int i = 0; i < output.Length; i++) { int index = getIndex(i, password.Length); int num001 = session_key << 2; int num002 = (session_id | i) >> (i+1); int num003 = function(i, session_key, password[index]); byte encrypted = XorByte(data[i], password); output[i] = (byte)((encrypted ^ num003) + (num002 % num001) ); } return output; } private static byte[] decrypt(byte[] data, int session_id, int length, byte[] password) { int session_key = (session_id & 0xFF); if (session_key == 0) session_key = (session_id << 4); byte[] output = new byte[data.Length]; for (int i = 0; i < output.Length; i++) { int index = getIndex(i, password.Length); int num001 = session_key << 2; int num002 = (session_id | i) >> (i + 1); int num003 = function(i, session_key, password[index]); byte decrypted = (byte)(data[i] - (num002 % num001) ^ num003); output[i] = XorByte(decrypted, password); } return output; } private static int function(int index, int a, int b) { if (a > b) if ((b + index) < a) return a - b - index; else return a - b + index; else if ((a + index) < b) return b - a - index; else return b - a + index; } public static int getIndex(int a, int b) => (a + b) >> 2; private static byte XorByte(byte input, byte[] password) { byte output = input; for (int i = 0; i < password.Length; i++) output ^= password[i]; return output; } Basically, this code takes a byte[] (data) which will be encrypted. The session_id is a randomly-generated number (this is supposed to be used in a client-server app, and every client is assigned an ID), and a password, which is a random generated byte[]. The main functions are encrypt and decrypt, and they call another 3: function(int index, int a, int b) - this creates a number based on another 3 that is used to XOR each byte the input of the encryption and decryption functions. getIndex(int a, int b) - this returns the "middle" number (I don't know how to say it in English) of 2 numbers, that are the number of iterations and the password length. This is used to get a byte within the password. XorByte(byte input, byte[] password) - this applies XOR to a byte recursively for each byte of the password, so the longer the password the harder to break. Outputs: Using a 32 byte random password, a random ID between 1000 and 10000, and the input data: "testing string": UTF-8 bytes: 116 101 115 116 105 110 103 32 115 116 114 105 110 103 encrypted result: ?`R?o1?zqnrjb UTF-8 bytes: 160 96 82 15 237 111 49 205 122 113 110 114 106 98 Time: 112 ticks, less than 1 ms (encryption and decryption) With the same inputs done 100.000 times: Time: 0,08009ms each encryption/decryption, 8009ms overall Answer: Your algorithm effectively combines two simple ciphers: a byte substitution cipher performed by XorByte(), and something that is similar in spirit to xoring with a poor-quality pseudo-random key stream (except for the minor difference due to the use of additive operators instead of xor for the combining step). Calling XorByte() for each byte is wasteful; you get the same effect by calling XorByte(0, password) once, caching the result and xoring every byte with that. There's a lot more random stumblings in the dark like that. E.g. int num002 = (session_id | i) >> (i + 1); There's no need for oring i into the first operand since it will get shifted out completely anyway (unless operator >> implicitly performs a modulo op on its right operand, they way shift instructions do on Intel CPUs). int index = getIndex(i, password.Length); ... int num003 = function(i, session_key, password[index]); This will crash if the input size approaches or exceeds three times the password size, because getIndex() returns half the arithmetic mean. You tried to make your key stream generator look complex but it is actually very poor. As a result you have one simple cipher (byte substitution, indirectly defined by the password) on top of a complicated but still poor one. This algorithm will be very safe as long as it doesn't protect anything of interest. As soon as it does, it will get torn to shreds. Don't forget that your adversaries won't necessarily hobble themselves by using an application-glue language like C#; they could use C++, effectively load all cores of their processors, and process multiple streams on each core via vector instructions (MMX/SSE). Or they could get even more performance by offloading the stuff into their graphics cards (CUDA, OpenCL). IOW, cracking performance could exceed the performance of your own code by five to ten orders of magnitude, especially when combined with a bit of math fu. Summary: if you randomly throw stuff in a pot then what you get is a right hash. Post scriptum: Since there weren't any other takers for reviewing this code, a few more considerations and a bit more detail. It is rarely a good idea to feed passwords and session ids directly into cryptographic computations, because their individual bits are usually not very random (regardless of whether they contain sufficient entropy or not). The standard way of dealing with this is to distill the entropy from password and session id by running them through a hash function (or, more precisely, to apply a password-based key derivation function like PBKDF2). This effectively spreads the entropy over all bits of the resulting hash, which makes it easier to use in further processing. As a first approximation - for testing and experiments - any good hash function will do, even the trusty old MD5 (still my favourite as a general hash function, even though it can't be used for strong crypto anymore). As was said earlier, one part of the algorithm works pretty much like a stream cipher except for the use of additive operators for the combining step instead of xor. In the following I'll gloss over the resulting differences since they are insignificant, and using xor makes epxlanations easier. An important consideration for stream ciphers is that key streams must never be reused. If two messages are encrypted with the same key stream then a simple xor of the two cipher texts yields the xor of the two plain texts. I.e. P ^ S = C P' ^ S = C' C ^ C' = (P ^ S) ^ (P' ^ S) = P ^ P' A cryptanalyst (attacker) can glean lots of invaluable information from something like that, just like when unhashed passwords are fed directly into crypto algorithms. Consequently, stream cipher keys must never be reused. That is usually accomplished by adding a salt or nonce when hashing the password to produce the session key; the nonce - which could be a simple counter, or a unique timestamp (i.e. a timestamp plus unique identifying information like machine, process id, thread id and so on), or both. The salt/nonce must be stored with the encryption header, since it is necessary for decryption. Also, I strongly recommend encapsulating the whole key stream generation in its own class, so that it becomes easier to use and - most importantly - easier to put through rigorous testing independent of other parts. Such a class would yield the key stream byte for byte, and perhaps also in other convenient ways. Using 'Soopr' as placeholder for the name of the as yet anonymous algorithm, a typical use for en/decipherment might look like this: var session_key = SooprKDF(password, session_id, nonce); var key_stream = new SooprKeyStream(session_key); byte xor_byte = XorByte(0, session_key); foreach (byte b in input) output = b ^ xor_byte ^ key_stream.next_byte(); An important quality indicator for cryptographic algorithms is diffusion. As a simple rule of thumb, flipping a single bit in the key material should affect every output bit with probability 50%. This applies not only to the algorithm as a whole, but most specifically to your key stream generator. Put in a different way: the output of your key stream generator should pass all standard quality tests for pseudo-randomness (most famous: Georgio Marsaglia's Diehard suite). Passing such tests is not sufficient for a good crypto algorithm, but it is necessary. If you have your key stream generator as a separate class then you easily run some tests to get an impression of its diffusion capability. E.g. create a random session key, generate a number of key stream bytes, flip a bit in the session key, and generate the same number of key stream bytes again. Then you can count the bits that have flipped between the two stream samples. Let your computer run a whole bunch of such random tests (with varying key stream sample lengths) - perhaps over night - and then look at how often each bit did flip for each key bit, separate per sample length. Every stream bit should have flipped about 50% of the time, for every sample length and every key bit. Tests like this make it easy to find unintended regularities that bleed through, like certain bits that never flip, or not often enough, or too often (which means they are correlated to certain parts of the key - something that shouldn't happen).
{ "domain": "codereview.stackexchange", "id": 18237, "tags": "c#, security, cryptography" }
Do photons interact or not directly?
Question: All I am asking about is photon (EM wavepacket) photon (EM wavepacket) interaction. I have read this question: If photon-photon interactions are impossible, how are higher harmonics generated? where Danielshank says: As far as we know photons do not directly interact with each other. Yet another way to say this is that if a photon is moving along, the existence of a second photon has absolutely no influence over the first photon's path. Photon-Photon Interactions where JEB says: Regarding the photons zinging around in front of you: as particles, they do interact in photon-photon scattering with a negligible cross section in the visible. As electromagnetic waves, their field strengths add linearly, which is the mechanism for con/de-structive interference; however, that only occurs when the waves are coherent. These waves are incoherent and "pass though" one-and-other. Why do two-photon interactions only occur at extremely high energies? So one of them says they do not directly interact, the other one says they do interact. This is a contradiction. What I do not understand mostly, is that photons do not interact directly, two crossing photons will not scatter off (only on the second order). Question: Do photons interact or not directly? Answer: At "tree level," the photon interacts with particles that have electric charge. Since photons don't themselves carry electric charge, there aren't first-order photon-photon interactions. At higher energies, or in more precise measurements, higher-order corrections make this simple statement less accurate. Some fraction of the wavefunction for a free photon includes virtual particle-antiparticle pairs (a phenomenon known as vacuum polarization), and those virtual charged particles may interact with other photons in the electromagnetic field. This is the lowest-order contribution to photon-photon scattering.
{ "domain": "physics.stackexchange", "id": 59450, "tags": "quantum-mechanics, electromagnetism, photons, speed-of-light" }
Can I write the seperation principle for LQG controllers in this state space form?
Question: Look at this picture. This is the seperation principle diagram. It is an LQG controller which going to control the real life process. What I want to do, is to create a state space model for this seperation principle system, including the real life process. A LQG controller is a LQR controller together with the Kalmanfilter. Kalmanfilter is also called an observer. The LQR controler is a feedback gain matrix L and the kalmanfilter is just a mathematical description of the real life system with a gain matrix K. r(t) is the reference signal vector which describe how the system's states should hold e.g. temperature or pressure. y(t) is the output from the real life process. $\hat{y}$ is the estimated output from the kalmanfilter. d(t) is the disturbance vector for the input. That's a bad thing, but the Kalman filter are going to reduce the disturbance and noise. u(t) is the in signal vector to the real life system and the kalmanfilter. n(t) is the noise vector from the measurement tools. x(t) is the state vector for the system. $\dot{x}$ is the state vector derivative for the system. $\hat{x}$ is the estimated state vector for the system. $\dot{\hat{x}}$ is the estimated state vector derivative for the system. A is the system matrix. B is the in signal matrix. C is the output matrix. L is the LQR controler gain matrix. K is the kalmanfilter gain matrix. So....a lot of people create the state space system as this: $$ $$ For the real life system: $$ \dot{x} = Ax + Bu + d$$ For the kalmanfilter: $$\dot{\hat{x}} = A\hat{x} + Bu + Ke$$ But $u(t)$ is: $$u = r - L\hat{x}$$ And $e(t)$ is: $$e = y + n - \hat{y} = Cx + n - C\hat{x} $$ And then...for some reason, people says that the state space model should be model by the state estimation error: $$\dot{\tilde{x}} = \dot{x} - \dot{\hat{x}} = (Ax + Bu + d) - (A\hat{x} + Bu + Ke) $$ $$ \dot{\tilde{x}} = (Ax + Bu + d) - (A\hat{x} + Bu + K(Cx + n - C\hat{x})$$ $$ \dot{\tilde{x}} = Ax - A\hat{x} + d - KCx - Kn + KC\hat{x} $$ And we can say that: $$\tilde{x} = x - \hat{x} $$ Beacuse: $$\dot{\tilde{x}} = \dot{x} - \dot{\hat{x}}$$ The kalmanfilter will be: $$ \dot{\tilde{x}} = (A - KC)\tilde{x} + Kn$$ The real life process will be: $$ \dot{x} = Ax + Bu + d = Ax + B(r - L\hat{x}) + d = Ax + Br - BL\hat{x} + d$$ But: $$\tilde{x} = x - \hat{x} \Leftrightarrow \hat{x} = x - \tilde{x}$$ So this will result for the real life process: $$ \dot{x} = Ax + Br - BL(x - \tilde{x}) + d = Ax + Br - BLx + BL\tilde{x} + d$$ So the whole state space model will then be: $$ \ \begin{bmatrix} \dot{x} \\ \\\dot{\tilde{x}} \end{bmatrix} =\begin{bmatrix} A - BL& BL \\ 0 & A-KC \end{bmatrix} \begin{bmatrix} x\\ \tilde{x} \end{bmatrix}+\begin{bmatrix} B & I & 0\\ 0 & 0 & K \end{bmatrix}\begin{bmatrix} r\\ d\\ n \end{bmatrix}\ $$ Youtube example: https://youtu.be/H4_hFazBGxU?t=2m13s $I$ is the identity matrix. But doesn't need to be only ones on digonal form. $0$ is the zero matrix. The Question: $$ $$ If I write the systems on this forms: $$ \dot{x} = Ax + Bu + d = Ax + B(r - L\hat{x}) + d$$ For the kalmanfilter: $$\dot{\hat{x}} = A\hat{x} + Bu + Ke = A\hat{x} + B(r - L\hat{x}) + K(y + n - \hat{y})$$ Beacuse $u(t)$ and $e(t)$ is: $$u = r - L\hat{x}$$ $$e = y + n - \hat{y} = Cx + n - C\hat{x} $$ I get this: $$\dot{x} = Ax + Br - BL\hat{x} + d$$ $$\dot{\hat{x}} = A\hat{x} + Br - BL\hat{x} + KCx + Kn - KC\hat{x}$$ Why not this state space form: $$ \begin{bmatrix} \dot{x} \\ \\\dot{\hat{x}} \end{bmatrix} =\begin{bmatrix} A & -BL \\ KC & [A-BL-KC] \end{bmatrix} \begin{bmatrix} x\\ \hat{x} \end{bmatrix}+\begin{bmatrix} B & I & 0\\ B & 0 & K \end{bmatrix}\begin{bmatrix} r\\ d\\ n \end{bmatrix}\ $$ Youtube example: https://youtu.be/t_0RmeSnXxY?t=1m44s Who is best? Does them both works as the LQG diagram shows? Which should I use? Answer: This is really a lot to look at, but the most glaring issue I noticed off the bat is your definition of the control signal $u(t)$. What is the input to your controller? What should be the input to your controller? What is the output of the controller? State feedback controllers (and LQR controllers) attempt to drive the system states to zero. The control law for these controllers is: $$ u = -Lx \\ $$ or, in the case of a state estimator (Kalman filter, EKF, etc.), is: $$ u = -L\hat{x} \\ $$ You are attempting to implement reference tracking by passing an input $r(t)$ to the controller. With a state feedback controller, this is generally done with integral control by adding a state to the state matrix such that: $$ \dot{e_I} = r(t) - x(n) \\ $$ where $x(n)$ is the state you're trying to control. Consider, for instance, an oscillating system (spring/mass/damper, etc.) where you're trying to control position. The states would all be the same (position/speed/acceleration), so how would your controller "know" that you're attempting to control position and not speed if you're using a control signal of $u(t) = r(t) - Kx$? So again, for an oscillator, your system might look like: $$ \left[\begin{array}{c} \dot{x} \\ \ddot{x} \\ \end{array}\right] = \left[\begin{array}{cc} 0 & 1 \\ -\omega_n^2 & 0 \\ \end{array}\right]\left[\begin{array}{c} x \\ \dot{x} \\ \end{array}\right] $$ Your integral controller then appends a state. Now, if you're trying to control position, you get: $$ \left[\begin{array}{c} \dot{x} \\ \ddot{x} \\ \dot{e_I} \\ \end{array}\right] = \left[\begin{array}{ccc} 0 & 1 & 0 \\ -\omega_n^2 & 0 & 0\\ -1 & 0 & 0 \\ \end{array}\right]\left[\begin{array}{c} x \\ \dot{x} \\ e_I \\ \end{array}\right] $$ Note the $\dot{e_I}$ state - the derivative of an integral error is just the control error. The integral error term $e_I$ doesn't impact either the $x$ or $\dot{x}$ states, but it gives you a new state for control purposes, $u(t) = -Kx$. Now you get a third gain to tune (third pole to place). Again, this is all specific for state feedback controllers, but the method works the same for integral control of an LQR system - this is referred to as linear-quadratic-integral control. Now you can also clearly change which states you're trying to control by altering how the $\dot{e_I}$ term is defined. You can "pick" the position state with $[1,0]$, or the speed state with $[0,1]$, or the acceleration state by recognizing the definition from the state space form: $\ddot{x} = [-w_n^2,0][_{\dot{x}}^{x}]$. In re-reading your question, it looks like there may be some confusion too on observer setup/design. Observer design is commonly referred to as the "dual" of the controller design because they take similar forms and you can generally do the same steps to get the answer. A state feedback controller attempts to drive the states to zero. With an observer, you commented: And then...for some reason, people says that the state space model should be model by the state estimation error Correct. The observer "states" are the errors between the modeled states and the actual system states. This is where duality comes in. A state feedback controller and an observer BOTH attempt to drive their states to zero. In a controller, the states are the actual system states. In an observer, the states are the differences between actual and modeled system states. When the observer has done its job, the modeled states should be exactly equal to the actual system states. In order for the observer to have a meaningful use for the controller, the observer should converge faster than the controller such that the controller has the actual system states (or very close to) by the time the controller begins to respond. This is the basis for the thumb rule that the observer poles should be "faster" than the control poles (I've read and generally use 5-10 times faster). The observer will cause the modeled states to fluctuate while it converges (hunts) to the correct state measurement, so it's important for that fluctuation to happen faster than the system is able to respond so it doesn't ripple through the controller output. SO, that's the reasoning for observer design - it's basically a second controller that exists to drive state error to zero. :EDIT: - I removed the previous last section here because I mis-read $\tilde{x}$ in the first set of equations as $\hat{x}$ and then confused myself comparing the two. That said, I think the second form is still a little incorrect (assuming the first form is correct) because of how the exogenous inputs are incorporated. Working entirely from the first form, it starts as: $$ \ \begin{bmatrix} \dot{x} \\ \\\dot{\tilde{x}} \end{bmatrix} =\begin{bmatrix} A - BL& BL \\ 0 & A-KC \end{bmatrix} \begin{bmatrix} x\\ \tilde{x} \end{bmatrix}+\begin{bmatrix} B & I & 0\\ 0 & 0 & K \end{bmatrix}\begin{bmatrix} r\\ d\\ n \end{bmatrix}\ $$ First, recognize that the state error $\tilde{x} = x-\hat{x}$, and then look just at the first row: $$ \dot{x} = \left[A-BL\right]x + \left[BL\right]\tilde{x} + Br + Id \\ $$ For the purposes of the rest of this, I'm just going to refer to $Id$ as $d$. So, substitute in the definition of $\tilde{x}$: $$ \dot{x} = \left[A-BL\right]x + \left[BL\right]\left(x-\hat{x}\right) + Br + d \\ $$ $$ \dot{x} = \left[A-BL\right]x + \left[BL\right]\left(x\right) + \left[BL\right]\left(-\hat{x}\right) + Br + d \\ $$ $$ \dot{x} = \left[A-BL+BL\right]x + \left[-BL\right]\hat{x} + Br + d \\ $$ $$ \boxed{\dot{x} = \left[A\right]x + \left[-BL\right]\hat{x} + Br + d} \\ $$ Great! This is the same first row as the second form. Now, to the second row of the first form: $$ \dot{\tilde{x}} = [A-KC]\tilde{x} + Kn \\ $$ Again, make the substitutions of $\tilde{x} = x-\hat{x}$ and now also $\dot{\tilde{x}} = \dot{x} - \dot{\hat{x}}$: $$ \dot{x} - \dot{\hat{x}}= [A-KC]\left(x-\hat{x}\right) + Kn \\ $$ Expand the $x-\hat{x}$ term: $$ \dot{x} - \dot{\hat{x}}= [A-KC]x - [A-KC]\hat{x} + Kn \\ $$ To get rid of the $\dot{x}$ on the left hand side, just use the definition of $\dot{x}$ from the result of the first row! $$ \dot{x} = \left[A\right]x + \left[-BL\right]\hat{x} + Br + d $$ $$ \left[A\right]x + \left[-BL\right]\hat{x} + Br + d - \dot{\hat{x}}= [A-KC]x - [A-KC]\hat{x} + Kn \\ $$ Rearrange: $$ \left[A\right]x + \left[-BL\right]\hat{x} + Br + d - \left([A-KC]x - [A-KC]\hat{x} + Kn\right) = \dot{\hat{x}}\\ $$ $$ \dot{\hat{x}} = \left[A\right]x + \left[-BL\right]\hat{x} + Br + d - \left([A-KC]x - [A-KC]\hat{x} + Kn\right)\\ $$ Distribute the negative: $$ \dot{\hat{x}} = \left[A\right]x + \left[-BL\right]\hat{x} + Br + d + \left(-[A-KC]x + [A-KC]\hat{x} - Kn\right)\\ $$ $$ \dot{\hat{x}} = \left[A\right]x + \left[-BL\right]\hat{x} + Br + d - [A-KC]x + [A-KC]\hat{x} - Kn\\ $$ Rearrange again: $$ \dot{\hat{x}} = \left[A\right]x - [A-KC]x + [A-KC]\hat{x} + \left[-BL\right]\hat{x} + Br + d - Kn\\ $$ Simplify one last time: $$ \boxed{\dot{\hat{x}} = [KC]x + [A-BL-KC]\hat{x} + Br + d - Kn}\\ $$ This is almost, but not quite what is given as the second row of the second form. This equation has the term $d$ (really $Id$) included and also has $-Kn$ instead of $Kn$.
{ "domain": "robotics.stackexchange", "id": 1414, "tags": "control, robotic-arm, kalman-filter, matlab, noise" }
How can you find all unbalanced parens in a string in linear time with constant memory?
Question: I was given the following problem during an interview: Gives a string which contains some mixture of parens (not brackets or braces-- only parens) with other alphanumeric characters, identify all parens that have no matching paren. For example, in the string ")(ab))", indices 0 and 5 contain parens that have no matching paren. I put forward a working O(n) solution using O(n) memory, using a stack and going through the string once adding parens to the stack and removing them from the stack whenever I encountered a closing paren and the top of the stack contained an opening paren. Afterwards, the interviewer noted that the problem could be solved in linear time with constant memory (as in, no additional memory usage besides what's taken up by the input.) I asked how and she said something about going through the string once from the left identifying all open parens, and then a second time from the right identifying all close parens....or maybe it was the other way around. I didn't really understand and didn't want to ask her to hand-hold me through it. Can anyone clarify the solution she suggested? Answer: Since this comes from a programming background and not a theoretical computer science exercise, I assume that it takes $O(1)$ memory to store an index into the string. In theoretical computer science, this would mean using the RAM model; with Turing machines you couldn't do this and you'd need $\Theta(\log(n))$ memory to store an index into a string of length $n$. You can keep the basic principle of the algorithm that you used. You missed an opportunity for a memory optimization. using a stack and going through the string once adding parens to the stack and removing them from the stack whenever I encountered a closing paren and the top of the stack contained an opening paren So what does this stack contain? It's never going to contain () (an opening parenthesis followed by a closing parenthesis), since whenever the ) appear you pop the ( instead of pushing the ). So the stack is always of the form )…)(…( — a bunch of closing parentheses followed by a bunch of opening parentheses. You don't need a stack to represent this. Just remember the number of closing parentheses and the number of opening parentheses. If you process the string from left to right, using these two counters, what you have at the end is the number of mismatched closing parentheses and the number of mismatched opening parentheses. If you want to report the positions of the mismatched parentheses at the end, you'll need to remember the position of each parenthesis. That would require $\Theta(n)$ memory in the worst case. But you don't need to wait until the end to produce output. As soon as you find a mismatched closing parenthesis, you know that it's mismatched, so output it now. And then you aren't going to use the number of mismatched closing parentheses for anything, so just keep a counter of unmatched opening parentheses. In summary: process the string from left to right. Maintain a counter of unmatched opening parentheses. If you see an opening parenthesis, increment the counter. If you see a closing parenthesis and the counter is nonzero, decrement the counter. If you see a closing parenthesis and the counter is zero, output the current index as a mismatched closing parenthesis. The final value of the counter is the number of mismatched opening parentheses, but this doesn't give you their position. Notice that the problem is symmetric. To list the positions of mismatched opening parentheses, just run the algorithm in the opposite direction. Exercise 1: write this down in a formal notation (math, pseudocode or your favorite programming language). Exercise 2: convince yourself that this is the same algorithm as Apass.Jack, just explained differently.
{ "domain": "cs.stackexchange", "id": 13073, "tags": "algorithms" }
Am I accidentaly creating dangerous silver nitride?
Question: I am doing some experiments with alternative film chemistry and I am starting to get concerned about safety. One experiment involves converting a small amount of metallic silver to silver chloride and then soaking the film in an weak ammonia solution (< 10% ammonia hydroxide), to dissolve the silver chloride, additionally there may be small amounts of silver oxide and silver metal left on the film. I read somewhere that in experiments involving ammonia and silver compounds that the dangerous explosive silver nitride could be produced. Should I be worried about it? would I be producing it in dangerous quantities? or at all? There is probably only a few grams of silver on the entire film strip. What are some sensible precautions I could take here? Answer: Wikipedia states specifically that silver nitride is slowly formed from solutions of silver oxide or silver nitrate in aqueous ammonia; it does not mention other silver salts as potential precursors. In case the nitride does form, you can look for it, and if you suspect anything you can easily dissolve it in dilute ammonia solution. From the WP article: Silver nitride may appear as black crystals, grains, crusts, or mirrorlike deposits on container walls. Suspected deposits may be dissolved by adding dilute ammonia or concentrated ammonium carbonate solution, removing the explosion hazard.[1][2] Cited References 1. John L. Ennis and Edward S. Shanley (1991). "On Hazardous Silver Compounds". J. Chem. Educ. 68 (1): A6. doi:10.1021/ed068pA6. 2. Salt Lake Metals Inc., "Silver oxide". Retrieved February 11, 2010.
{ "domain": "chemistry.stackexchange", "id": 15719, "tags": "safety, silver" }
Does decay rate change with time?
Question: In a fire alarm, if we start with americium-241 which emits radiation at 370 kBq (as an example) what will have happened to the decay rate after 470 years (half life is 470 years). The amount of americium will be half, but does this mean that the radiation will also half, thus being 185 kBq? In other words, does the rate at which radioactive particles are emitted also change with time? Answer: In other words, does the rate at which radioactive particles are emitted also change with time? The founding principle of the half-life Law is that: $$\frac{\text{d}N(t)}{\text{d}t}=-kN(t)$$ where $k$ is a constant. In plain English: The decay rate of a radioactive substance is proportional to the amount of radioactive substance. In the case of $^{241}\text{Am}$, indeed after 470 years radioactivity will have dropped to half the initial value.
{ "domain": "physics.stackexchange", "id": 61012, "tags": "particle-physics, radioactivity" }
Combination of lens
Question: In the above diagram, let the refractive index of concave lens be $n_1$ and of convex be $n_2$.So in order to apply lens maker formulae for it, will I have to assume air separation between the lens? What happens if there is another medium between the lens? Will that medium act like another lens because light rays will refract from it like that of a lens? Answer: No.You don't need to consider air separation between them unless it is specified. If there happens to be a different medium between them then that medium will act refract the rays.
{ "domain": "physics.stackexchange", "id": 44205, "tags": "optics, refraction, geometric-optics, lenses" }
Rust program to print citations in Chicago author-date style
Question: I have written a Rust program that lets you input a citation's metadata in a Bibtex-like format and generates a bibliography entry formatted in Markdown that conforms (more or less) to the Chicago Author-Date style described here. Currently, it supports citations for Books, JournalArticles, and NewspaperArticles with any number (>0) of authors. One of my goals was to write the code in a way that makes it easy to add a new resource type, say AcademicThesis, by creating a struct AcademicThesis containing the necessary fields and adding impl AcademicThesis { citation(&self) -> String { ... }} that generates the citation. A secondary goal was to make it expandable to other citation styles, but of course this would require first renaming the citation() method to something more specific. My motivation for writing this program is that almost all of the coding I do involves numerical schemes like this, and I almost never work with strings at all, but it seems like strings have a lot to teach us about how the Rust language works. The following are non-features that I decided against implementing until I have a firmer grasp of the Rust language: Page ranges such as (455, 468) are rendered naively as 455–468 instead of 455–68 Generates citations only, not a full bibliography (e.g. with line breaks, alphabetization, hanging indents...) I would appreciate a general code review. Here is the program: const MONTHS: [&str; 12] = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; pub struct Date { year: u16, month: usize, day: u16 } impl Date { // Return a string such as "May 23" representing the date fn to_month_day(&self) -> String { format!( "{} {}", MONTHS[self.month], self.day ) } } pub struct Name { first: String, last: String } /// Convert a vector of author names into a string listing them in Chicago style fn list_authors(authors: &Vec<Name>) -> String { match authors.len() { 0 => panic!("No author given!"), 1 => format!("{}, {}", authors.first().unwrap().last, authors.first().unwrap().first), 2 => format!( "{}, {} and {} {}", authors.first().unwrap().last, authors.first().unwrap().first, authors.last().unwrap().first, authors.last().unwrap().last, ), _ => { let mut s = format!( "{}, {}, ", authors.first().unwrap().last, authors.first().unwrap().first ); for i in 1..authors.len()-1 { s.push_str(&format!( "{} {}, ", authors[i].first, authors[i].last )) }; s.push_str(&format!( "and {} {}", authors.last().unwrap().first, authors.last().unwrap().last )); s } } } /// Convert "str" to "[str](https://str)", which renders as a link in markdown fn link_to_clickable(url: &String) -> String { return format!("[{}](https://{})", url, url); } pub struct JournalArticle { authors: Vec<Name>, year: u16, title: String, journal: String, volume: u16, issue: u16, pages: (u16, u16), url: String } impl JournalArticle{ /// Generate a citation in Chicago style fn citation(&self) -> String { let author_string = list_authors(&self.authors); return format!( "{}. {}. &ldquo;{}.&rdquo; *{}* {} ({}): {}&ndash;{}. {}.", author_string, self.year, self.title, self.journal, self.volume, self.issue, self.pages.0, self.pages.1, link_to_clickable(&self.url) ); } } pub struct NewspaperArticle { authors: Vec<Name>, date: Date, title: String, newspaper: String, url: String } impl NewspaperArticle { /// Generate a citation in Chicago style fn citation(&self) -> String { let author_string = list_authors(&self.authors); let date_string = self.date.to_month_day(); return format!( "{}. {}. &ldquo;{}.&rdquo; *{},* {}. {}.", author_string, self.date.year, self.title, self.newspaper, date_string, link_to_clickable(&self.url) ); } } pub struct Book { authors: Vec<Name>, year: u16, title: String, publisher: String, location: String } impl Book { /// Generate a citation in Chicago style fn citation(&self) -> String { let author_string = list_authors(&self.authors); return format!( "{}. {}. *{}.* {}: {}.", author_string, self.year, self.title, self.location, self.publisher, ); } } fn main() { // Journal article with one author let source = JournalArticle{ authors: Vec::<Name>::from([Name{ first: String::from("Aaron"), last: String::from("Bodoh&ndash;Creed") }]), year: 2020, title: String::from("Optimizing for Distributional Goals in School Choice Problems"), journal: String::from("Management Science"), volume: 66, issue: 8, pages: (3657, 3676), url: String::from("doi.org/10.1287/mnsc.2019.3376") }; println!("{}\n", source.citation()); // Journal article with two authors let source = JournalArticle{ authors: Vec::<Name>::from([Name{ first: String::from("Paul"), last: String::from("Milgrom") }, Name{ first: String::from("John"), last: String::from("Roberts") }]), year: 1990, title: String::from("The Economics of Modern Manufacturing: Technology, Strategy, and Organization"), journal: String::from("The American Economic Review"), volume: 80, issue: 3, pages: (511, 528), url: String::from("jstor.org/stable/2006681") }; println!("{}\n", source.citation()); // Journal article with three authors let source = JournalArticle{ authors: Vec::<Name>::from([Name{ first: String::from("Chandra"), last: String::from("Chekuri") }, Name{ first: String::from("Jan"), last: String::from("Vondrák") }, Name{ first: String::from("Rico"), last: String::from("Zenklusen") }]), year: 2014, title: String::from("Submodular Function Maximization via the Multilinear Relaxation and Contention Resolution Schemes"), journal: String::from("SIAM Journal on Computing"), volume: 43, issue: 6, pages: (3657, 3676), url: String::from("doi.org/10.1137/110839655") }; println!("{}\n", source.citation()); // Newspaper article let source = NewspaperArticle{ authors: Vec::<Name>::from([Name{ first: String::from("Kathy Johnson"), // Middle names can be treated as an extension of first names last: String::from("Bowles") }]), date: Date{day: 24, month: 5, year: 2022}, title: String::from("Campus Landscapes: So Much More Than Marketing"), newspaper: String::from("Inside Higher Ed"), url: String::from("insidehighered.com/blogs/just-explain-it-me/campus-landscapes-so-much-more-marketing") }; println!("{}\n", source.citation()); // Book let source = Book{ authors: Vec::<Name>::from([Name{ first: String::from("Thomas"), last: String::from("Cormen") }, Name{ first: String::from("Charles"), last: String::from("Leiserson") }, Name{ first: String::from("Ronald"), last: String::from("Rivest") }]), year: 1996, title: String::from("Introduction to Algorithms"), publisher: String::from("The MIT Press"), location: String::from("Cambridge, Massachusetts") }; println!("{}\n", source.citation()); } It outputs Bodoh&ndash;Creed, Aaron. 2020. &ldquo;Optimizing for Distributional Goals in School Choice Problems.&rdquo; *Management Science* 66 (8): 3657&ndash;3676. [doi.org/10.1287/mnsc.2019.3376](https://doi.org/10.1287/mnsc.2019.3376). Milgrom, Paul and John Roberts. 1990. &ldquo;The Economics of Modern Manufacturing: Technology, Strategy, and Organization.&rdquo; *The American Economic Review* 80 (3): 511&ndash;528. [jstor.org/stable/2006681](https://jstor.org/stable/2006681). Chekuri, Chandra, Jan Vondrák, and Rico Zenklusen. 2014. &ldquo;Submodular Function Maximization via the Multilinear Relaxation and Contention Resolution Schemes.&rdquo; *SIAM Journal on Computing* 43 (6): 3657&ndash;3676. [doi.org/10.1137/110839655](https://doi.org/10.1137/110839655). Bowles, Kathy Johnson. 2022. &ldquo;Campus Landscapes: So Much More Than Marketing.&rdquo; *Inside Higher Ed,* June 24. [insidehighered.com/blogs/just-explain-it-me/campus-landscapes-so-much-more-marketing](https://insidehighered.com/blogs/just-explain-it-me/campus-landscapes-so-much-more-marketing). Cormen, Thomas, Charles Leiserson, and Ronald Rivest. 1996. *Introduction to Algorithms.* Cambridge, Massachusetts: The MIT Press. Which renders in Markdown as: Bodoh–Creed, Aaron. 2020. “Optimizing for Distributional Goals in School Choice Problems.” Management Science 66 (8): 3657–3676. doi.org/10.1287/mnsc.2019.3376. Milgrom, Paul and John Roberts. 1990. “The Economics of Modern Manufacturing: Technology, Strategy, and Organization.” The American Economic Review 80 (3): 511–528. jstor.org/stable/2006681. Chekuri, Chandra, Jan Vondrák, and Rico Zenklusen. 2014. “Submodular Function Maximization via the Multilinear Relaxation and Contention Resolution Schemes.” SIAM Journal on Computing 43 (6): 3657–3676. doi.org/10.1137/110839655. Bowles, Kathy Johnson. 2022. “Campus Landscapes: So Much More Than Marketing.” Inside Higher Ed, June 24. insidehighered.com/blogs/just-explain-it-me/campus-landscapes-so-much-more-marketing. Cormen, Thomas, Charles Leiserson, and Ronald Rivest. 1996. Introduction to Algorithms. Cambridge, Massachusetts: The MIT Press. Answer: Nice project! From previous experience writing citation formatting in Rust (just a small side project) I would advise you to not try to follow the standards to the letter, that is just a extreme pile of work that is not worth it. Otherwise really nice work. I attached the code with inline comments below, I prefixed the comments with Note: to make it easy to find them back. If you have questions about any of the comments feel free to reach out. // Note: I always use clippy to warn me when code can be written in a nicer way. // See: https://github.com/rust-lang/rust-clippy #![warn(clippy::all, clippy::pedantic, clippy::nursery)] const MONTHS: [&str; 12] = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December", ]; pub struct Date { year: u16, month: usize, day: u16, } impl Date { /// Return a string such as "May 23" representing the date fn to_month_day(&self) -> String { format!("{} {}", MONTHS[self.month], self.day) } } pub struct Name { first: String, // Note: some cultures have a slightly different scheme with middle parts, this is commonly added to the last name so it will likely not be a problem, eg Dutch/Flemish: Erik van Huffelen (mind the casing!). last: String, } impl Name { // Note: I personally really like this pattern where you have a function/constructor that // takes a `impl into<String>` and calls `.into()`. In this way I very rarely have to think // about the exact string type any more as it will automatically do all the stuff. And // because it is Rust this will be just as fast as doing it 'by hand' (I assume, I have no // reason to believe otherwise). // This can of course be done just as easily for the Citation types. And `Into` is a very // prevalent trait that can be used in very many places. pub fn new(first: impl Into<String>, last: impl Into<String>) -> Self { Self { first: first.into(), last: last.into(), } } } /// Convert a vector of author names into a string listing them in Chicago style fn list_authors(authors: &[Name]) -> String { // Note: I followed clippy here and replaced `&Vec<Name>` with `&[Name]` same explanation as `link_to_clickable` (line 80). match authors.len() { 0 => panic!("No author given!"), 1 => format!("{}, {}", authors[0].last, authors[0].first), // Note; I used direct indexing here into the array as the index is known and it takes less space visually, it is definitely not wrong to use `first` or `last`. I just want to show you some other ways ;-). 2 => format!( "{}, {} and {} {}", authors[0].last, authors[0].first, authors[1].first, authors[1].last, ), _ => { let mut output = format!("{}, {}, ", authors[0].last, authors[0].first); for author in authors.iter().take(authors.len() - 1).skip(1) { // Note: clippy advised this, but I am not sure if I agree, make your own choice here. output.push_str(&format!("{} {}, ", author.first, author.last)); } output.push_str(&format!( "and {} {}", authors.last().unwrap().first, authors.last().unwrap().last )); output } } } /// Convert "str" to "[str](https://str)", which renders as a link in markdown fn link_to_clickable(url: &str) -> String { // Note: this way it is more general, any `&String` can automatically be dereferenced into `&str`. // Using `&String` is essentially the same from the borrow standpoint, it gives you read access to // a piece of text. Specifying `&String` makes it so that you cannot use this functions with a // `&'static str` or a slice/simple operation of a string, eg [`String::trim`] returns a `&str`. return format!("[{url}](https://{url})"); // Note: You can directly include variables in format strings. } // Note: As you a creating a shared behaviour for a couple of structs introducing a `trait` seems to me // like a logical choice. You could also create a single `enum` with all options, but that gives a slightly // different code architecture you might not like in certain cases. (Like not having the option for downstream // users to implement the trait on their own structs.) pub trait Citation { /// Generate a citation in Chicago style fn citation(&self) -> String; // Note: You could write an extra method which prepares the citation output for markdown. fn md_citation(&self) -> String { // Note: this is an example of course you would add more cases for the other special chars. Each // call to `replace` copies the whole string, if this is a problem you could look into a loop over // all chars concatenating everything with the special encoding in one round. self.citation().replace('-', "&ndash"); // Note: here is an example of the single copy replacement. let citation = self.citation(); let mut output = String::with_capacity(citation.len()); for c in citation.chars() { match c { '-' => output += "&ndash;", n => output.push(n), } } output } } pub struct JournalArticle { authors: Vec<Name>, year: u16, title: String, journal: String, volume: u16, issue: u16, pages: (u16, u16), url: String, } impl Citation for JournalArticle { fn citation(&self) -> String { // Note: I tend to like 'one-liners' above introduced variables that are used only once. If needed the name of the variable being used as documentation can be replaced by a real comment ;-). format!( "{}. {}. &ldquo;{}.&rdquo; *{}* {} ({}): {}&ndash;{}. {}.", list_authors(&self.authors), self.year, self.title, self.journal, self.volume, self.issue, self.pages.0, self.pages.1, link_to_clickable(&self.url) ) // Note: here the return is not necessary } } pub struct NewspaperArticle { authors: Vec<Name>, date: Date, title: String, newspaper: String, url: String, } impl Citation for NewspaperArticle { fn citation(&self) -> String { format!( "{}. {}. &ldquo;{}.&rdquo; *{},* {}. {}.", list_authors(&self.authors), self.date.year, self.title, self.newspaper, self.date.to_month_day(), link_to_clickable(&self.url) ) } } pub struct Book { authors: Vec<Name>, year: u16, title: String, publisher: String, location: String, } impl Book { pub fn new( authors: impl Into<Vec<Name>>, year: u16, title: impl Into<String>, publisher: impl Into<String>, location: impl Into<String>, ) -> Self { Self { authors: authors.into(), year, title: title.into(), publisher: publisher.into(), location: location.into(), } } } impl Citation for Book { fn citation(&self) -> String { format!( "{}. {}. *{}.* {}: {}.", list_authors(&self.authors), self.year, self.title, self.location, self.publisher, ) } } fn main() { // Note: it is best to write these tests as unit tests so that reviewers (and you!) can be certain about // their refactorings. See below for how this is done with the book example. // Journal article with one author let source = JournalArticle { // Note: here you can see the impact of the `new` function with `impl Into<String>`. Additionally I // have an IDE which shows the names of parameters in-line once the definition becomes large, this // makes it so that the explicit names of the fields are not really necessary any more. authors: vec![Name::new("Aaron", "Bodoh&ndash;Creed")], year: 2020, title: String::from("Optimizing for Distributional Goals in School Choice Problems"), journal: String::from("Management Science"), volume: 66, issue: 8, pages: (3657, 3676), url: String::from("doi.org/10.1287/mnsc.2019.3376"), }; println!("{}\n", source.citation()); // Journal article with two authors let source = JournalArticle { authors: vec![ Name { first: String::from("Paul"), last: String::from("Milgrom"), }, Name { first: String::from("John"), last: String::from("Roberts"), }, ], year: 1990, title: String::from( "The Economics of Modern Manufacturing: Technology, Strategy, and Organization", ), journal: String::from("The American Economic Review"), volume: 80, issue: 3, pages: (511, 528), url: String::from("jstor.org/stable/2006681"), }; println!("{}\n", source.citation()); // Journal article with three authors let source = JournalArticle{ authors: vec![Name{ first: String::from("Chandra"), last: String::from("Chekuri") }, Name{ first: String::from("Jan"), last: String::from("Vondrák") }, Name{ first: String::from("Rico"), last: String::from("Zenklusen") }], year: 2014, title: String::from("Submodular Function Maximization via the Multilinear Relaxation and Contention Resolution Schemes"), journal: String::from("SIAM Journal on Computing"), volume: 43, issue: 6, pages: (3657, 3676), url: String::from("doi.org/10.1137/110839655") }; println!("{}\n", source.citation()); // Newspaper article let source = NewspaperArticle { authors: vec![Name { first: String::from("Kathy Johnson"), // Middle names can be treated as an extension of first names last: String::from("Bowles"), }], date: Date { day: 24, month: 5, year: 2022, }, title: String::from("Campus Landscapes: So Much More Than Marketing"), newspaper: String::from("Inside Higher Ed"), url: String::from( "insidehighered.com/blogs/just-explain-it-me/campus-landscapes-so-much-more-marketing", ), }; println!("{}\n", source.citation()); } #[cfg(test)] // Note: cfg is conditional compilation, so the compiler will not even look at the code in // this module when compiling in a normal mode, this improves the compiling performance somewhat. mod tests { use super::*; // Note: this imports everything of the outer module (the one you are testing). #[test] fn book() { // Book // Note: arrays can be cast `Into` vecs! let source = Book::new( [ Name::new("Thomas", "Cormen"), Name::new("Charles", "Leiserson"), Name::new("Ronald", "Rivest"), ], 1996, "Introduction to Algorithms", "The MIT Press", "Cambridge, Massachusetts", ); assert_eq!( source.citation(), "Cormen, Thomas, Charles Leiserson, and Ronald Rivest. 1996. *Introduction to Algorithms.* Cambridge, Massachusetts: The MIT Press." ); } } ```
{ "domain": "codereview.stackexchange", "id": 43395, "tags": "strings, rust, formatting" }
Does electricity flow on the surface of a wire or in the interior?
Question: I was having a conversation with my father and father-in-law, both of whom are in electric related work, and we came to a point where none of us knew how to proceed. I was under the impression that electricity travels on the surface while they thought it traveled through the interior. I said that traveling over the surface would make the fact that they regularly use stranded wire instead of a single large wire to transport electricity make sense. If anyone could please explain this for some non-physics but electricly incline people, I would be very appreciated. Answer: It depends on the frequency. DC electricity travels through the bulk cross section of the wire. A changing electrical current (AC) experiences the skin-effect where the electricity flows more easily in the surface layers. The higher the frequency the thinner the surface layer that is usable in a wire. At normal household AC (50/60hz) the skin depth is about 8-10mm but at microwave frequencies the depth of the metal that the current flows in is about the same as a wavelength of visible light edit: Interesting point from Navin - the individual strands have to be insulated from each other for the skin effect to apply to each individually. That is the reason for the widely separated pairs of wires in this question What are all the lines on a double circuit tower?
{ "domain": "physics.stackexchange", "id": 46621, "tags": "electromagnetism, electricity, conductors" }
Why does mechanical equilibrium depend only on potential energy?
Question: As far as I understand, for a system to be considered in equilibrium, the sum of the forces that is applied to it must be $0$: $\vec F = 0$ which is $\partial \frac{E_p}{\partial x}\bigg\rvert _{x=x_0} = 0 $ But it only depends on the potential energy, what about kinetic energy? Answer: Equilibrium here just means that if a particle is placed at the location $x_0 = 0$ with $0$ kinetic energy, it will stay at that location. Imagine another location, say $x_1$, such that $\nabla V(x_1)\not = 0$, if a particle is placed there, it will start moving, if the kinetic energy is zero initially. A simple example of this is a pendulum. Imagine a bar with ends points labeled $A$ and $B$ suspended from one of its end-points ($A$). If the bar is placed vertically with $B$ lower than $A$, the bar will stay at that configuration forever, unless you add kinetic energy. This is also the case if you place $B$ vertically above $A$. The difference between these two configurations is the type of equilibrium (stable vs unstable), but both of them are equilibrium points.
{ "domain": "physics.stackexchange", "id": 41000, "tags": "classical-mechanics, lagrangian-formalism, potential-energy, equilibrium" }
Is the PID just an outdated control method and state-space is superior?
Question: So I've been wondering this for a while; is PID just a simple but slightly outdated control method / isn't state-space (SS) a far superior method in pretty much every way? SS allows for MIMO, PID just SISO. SS allows for non-linear models, PID does not do non-linear models. SS allows you to see and control the states of your system, this is kind of lost in the laplace transform of PID... So given this; why do I encounter PID everywhere? Is it simpler and cheaper and good enough if it works? I've asked this question to my mechatronic systems design professor, but I did not really find his answer all that satisfying: "State space is not going to do magic if loopshaping way of designing PID reaches its edge. State-space is time domain to design linear control while loopshaping is frequency domain. With both you can design PID." His research group is focused on the high-tech side of things, and has made a 'fractional order' PID controller toolbox (FLOreS - Fractional order loop shaping MATLAB toolbox, essentially you place a bunch of zeros and poles close to each other to mimic something which is between e.g. s^1 and s^2). In any event, I think he might be biased so I wish to get some perspective. Answer: I do not think so. Instead of looking directly at PID, lets look at Frequency domain loop shaping in general compared to State-space control (eg, Lead-Lag filters, Notch filters and PID). On top of the fact that in the current industry over 90% of all controllers are PID's or controllers I just mentioned isnt just because they are much easier to learn, but also for a few more reasons: The bodeplot gives an amazing insight in how the controlled system is going to respond. The bandwidth, gain margin and phase margin show instant bounds in robustness and operating range. On top of that, the sensitivity bode-plot gives direct margins on how well the controlled system functions when influenced by noise. While there are some methods to assess controller robustness in State-space, these are incredibly complex to use and to analyze. Controller elements directly "shape" the bode plot (hence the name loop-shaping). eg: do you want a larger phase-margin? add a lead filter, do you want to reduce or remove the resonance peak? add a notch filter and so on. Tuning these filters use frequency values you can read directly from the current bode plot. In state-space, you have no clue whether your designed LQR-filter did remove the resonance peak other than doing a frequency analysis. If it didnt, you have no clue what to change to ensure it does. In a practical environment, the model of the system is often obtained using system-identification. Using frequency response identification, you obtain in essence the bode plot of the system, so even without an actual Laplace model of the system, you can already design a controller for it. On top of that, the nyquist plot can be used to assess stability, so really no model is required. State-space domain identification requires first of all the estimation of the number of states. On top of that, the only thing known from the returning model is that the output responds the same to the input as the actual system, what happens to the states on the other hand, is not known. While I agree that controlling MIMO systems using State Space is indeed much easier, it is in fact possible to create frequency domain controllers of a MIMO system by either decoupling or sequential loop shaping. These methods are however a tad more complex to understand and properly apply. Of course, there are many application to which a state-space controller would outperform a frequency domain controller, but then again, there are many applications to which implementing a simple frequency domain controller that just does the job is much cheaper and faster.
{ "domain": "engineering.stackexchange", "id": 3822, "tags": "control-engineering, pid-control" }
Linear response function for a system with derivative: $U=L \frac{d I}{dt}$, expressing $U=f(I)$
Question: I have a super basic questions. I am a not really into signal processing (more about physics), but I would like to understand an aspect of linear response function (I think the question fits for this forum). From my basic understanding, any linear, time invariant, causal system can relate the output $S(t)$ to the input $E(t)$ under the following relations: $$\begin{equation}S(t)=S(-\infty) + \int_{-\infty}^{+\infty} \chi(t-t') E(t') dt'\label{eq_1} \end{equation}$$ The causality holds when imposing $\chi(u<0)=0$. Let's consider a very simple case: voltage around an inductance. I have the law: $U=L \frac{d I}{d t}$ If I express $I$ as a function of $U$, I can write down: $$I(t)=I(-\infty) + \int_{-\infty}^{+\infty} \frac{U(t')}{L} dt'$$ My response function will simply be $\chi(u)=\frac{\Theta(u)}{L}$ (where the heaviside is for causality). But the system in which $I$ is the input and $U$ the output is also linear. Thus I would expect to be able to express: $$U(t)=U(-\infty) + \int_{-\infty}^{+\infty} f(t-t') I(t')$$ However because of the derivative on $I$ in the law, I don't find how it is possible. Am I wrong in my initial statement and \ref{eq_1} ? Answer: Let's start with the simple system $$y(t)=x(t)\tag{1}$$ where $y(t)$ denotes the output and $x(t)$ denotes the input. It is linear and time-invariant, and, consequently, it must be possible to represent it by the convolution integral $$y(t)=\int_{-\infty}^{\infty}x(\tau)h(t-\tau)d\tau\tag{2}$$ where $h(t)$ is the system's impulse response. In this case, it turns out that $h(t)=\delta(t)$, i.e., the impulse response is a Dirac delta impulse. Now, for a differentiator $$y(t)=x'(t)\tag{3}$$ we "simply" (conceptually, at least) have $h(t)=\delta'(t)$, where $\delta'(t)$ is the (generalized) derivative of $\delta(t)$. So, using the concept of a generalized derivative of a distribution, we can write the input-output relationship of an ideal differentiator as the following convolution integral: $$y(t)=\int_{-\infty}^{\infty}x(\tau)\delta'(t-\tau)d\tau\tag{4}$$
{ "domain": "dsp.stackexchange", "id": 8848, "tags": "linear-systems, causality" }
Logic for Computer Science - How to define msort, merge and split functions inductively?
Question: In "Modelling Computing Systems: Mathematics for Computer Science", I came across a logic exercise to inductively define a merge sort function 'mergeSort', with a hint to first define auxillary functions 'split' and 'merge'. The style of the logic so far looks like this for inductively defined sets Odd and Even, and some other functions that manipulate lists (isort, insert, length, append): 1 ∈ Odd; if n ∈ Odd then (n+2) ∈ Odd; 0 ∈ Even; if n ∈ Even then (n+2) ∈ Even; isort([]) = []; isort(a:L) = (insert a)(isort(L)); (insert a)[] = [a]; (insert a)(b:L) = if a < b then a:(b:L) else b:((insert a)L); length([]) = 0; length(n:L) = 1 + length(L); L1 ++ [] = L1; (a:L1) ++ L2 = a:(L1 ++ L2); I have tried, but I can't figure out how to define the first auxillary function 'split', which should split a list in roughly the same size. So far, I've defined the base cases for empty list and list with single element, but I don't know how to define the inductive case. I am not sure about the logic, the notation and also not about how I could make sure that the function doesn't use the same tail of the list L? split([]) = ([],[]); split(a:[]) = ([a],[]); split(a : b : L) = if length(a : b : L) ∈ Even (a : (split(L)), b : (split(L))); else (a : (split(L)), b : (split(b : L))); How can I inductively call the split function again, without repeating the same split? I have defined the merge function like this, and am pretty sure that should work: merge(L1,[]) = L1; merge([],L2) = L2; merge(a:L1, b:L2) = if a < b (a:(merge(L1, b:L2))); else (b:(merge(a:L1, L2))); As for the final function mergeSort, I've gotten this far: mergeSort([]) = []; mergeSort(a:[]) = [a]; mergeSort(L) = merge("firstResultOf"(split(L)), "secondResultOf"(split(L))); I don't know how to make it clear in the function that merge should use the first and second output lists of split. And I am unsure how to call mergeSort inductively.. How would you do it, using this type of notation? Answer: You can avoid odd and even by considering one more case in split. Any you need recursive calls in mergeSort. Here's a working Haskell solution. split :: [a] -> ([a], [a]) split [] = ([], []) split [x] = ([x], []) split [x,y] = ([x], [y]) split (x : y : l) = (x:xs, y:ys) where (xs,ys) = split l merge :: Ord a => ([a], [a]) -> [a] merge (xs, []) = xs merge ([], ys) = ys merge (x:xs, y:ys) | x <= y = x : merge (xs, y:ys) | otherwise = y : merge (x:xs, ys) mergeSort :: Ord a => [a] -> [a] mergeSort [] = [] mergeSort [x] = [x] mergeSort xs = merge (mergeSort ys, mergeSort zs) where (ys, zs) = split xs
{ "domain": "cs.stackexchange", "id": 20901, "tags": "logic, induction, lists" }
Proof: Sum of weights of paths in a network
Question: I was given problem 6.7 out of the book "Networks: An Introduction" as a question. The problem is defined as follows: Consider the set of all paths from node $s$ to node $t$ on an undirected network with adjacency matrix A. Let us give each path a weight equal to $\alpha^r$, where $r$ is the length of the path. a) Show that the sum of the weights of all the paths from $s$ to $t$ is given by $Z_{st}$ which is the $st$ element of the matrix $Z = (I - \alpha A)^ {-1}$, where $I$ is the identity matrix b) What condition must $\alpha$ satisfy for the sum to converge? Where do I even start on this problem? Since the graph is undirected, I know that A must be a symmetric matrix. Other than that I don't quite know what more information there is to go on. Answer: A few hints: Find out what the entries of $A^2$ mean. How about $A^k$? (Start by a very small adjacency matrix, multiply it with itself and try to think what each entry means). Lookup and understand the Taylor expansion of $f(x) = 1/(1-x)$. Realize that the sum of weights of all paths from $s$ to $t$ is the sum of weights of paths of length 0, 1, 2, ...
{ "domain": "cs.stackexchange", "id": 7545, "tags": "graphs, matrices" }
Is it possible for a person to become "reinfected" with the same strain of a virus?
Question: If a person contracts a virus, viral conjunctivitis for example, is it possible for the individual to become "reinfected" with the exact same strain of the virus once the person has it treated and the symptoms have gone away? I am a nursing student and am fascinated with virology, but my basic microbiology class did not go very in-depth on the subject. Answer: The nature of infectious agents is that they transmit between organisms. This means that they have reservoirs outside a single host, and hence of course encountering the exact same strain twice is possible if this strain leaves the body and at a later stage is carried back to it. This could typically happen for example with influenza or common cold viruses, spreading from one child to other children at school and later being carried back to the original child through them. The reason why the child will not develop another illness when being exposed to the same virus again is the adaptive immune response: After the first infection, immune cells specific to a pathogen will proliferate and differentiate both into effector cells to destroy the pathogen, and into memory cells. These can mount a much stronger immune response much faster when they come in contact with the same (or a structurally very similar) pathogen, meaning that a secondary exposure usually does not result in a proper infection and illness. Of course, this mechanism doesn't work properly for anyone with a compromised immune system. In most cases where a viral disease develops repeatedly, this is due to evasion mechanisms. For example in some viruses, those antigens which tend to be targeted by immune systems have high mutation rates. In this case the "same" virus is actually a mutated strain which causes the same illness, but "looks" different to the immune system, and so the memory cells don't respond. Again, influenza is a great example. The reason why we get flu again winter after winter, is because this virus tends to mutate over the year with relatively low infection prevalence. Then during the winter, when the conditions are favourable for flu infections, typically only a small number of strains cause epidemics - because we were maybe immune to last year's influenza, but this year's has mutated antigens which our immune systems do not recognise yet.
{ "domain": "biology.stackexchange", "id": 9206, "tags": "microbiology, virology" }
Is brute force the accepted best practice for handling Excel COM 'busy' exceptions?
Question: Following on from a question about handling-com-exceptions-busy-codes I would like to know if the following model is the accepted best practice of handling Excel COM busy messages when accessing the Excel COM object model: private void AskExcelToDoSomething() { bool retry = true; do { try { // Call Excel OM retry = false; } catch (COMException e) {} } while (retry); } Assuming that IMessageFilter has been implemented and catches the errors for which it is intended and retries, is the above model the 'accepted' way of handling these busy exceptions? If so, is it not vulnerable to hanging if for some reason it keeps being rejected? Is there no better way of doing this that guarantees success? Answer: You're missing the Thread.Sleep(500); call from the linked post's solution, which is much, much better than what you've posted here: private void TryUntilSuccess(Action action) { bool success = false; while (!success) { try { action(); success = true; } catch (System.Runtime.InteropServices.COMException e) { if ((e.ErrorCode & 0xFFFF) == 0xC472) { // Excel is busy Thread.Sleep(500); // Wait, and... success = false; // ...try again } else { // Re-throw! throw e; } } } } (above code from sepp2k's answer here) is it not vulnerable to hanging if for some reason it keeps being rejected? Given that this code is meant to address a COM exception thrown when Excel is busy, it remaining in the loop would mean, well, that Excel is still busy - and possibly hung... in which case, the user will probably lose their patience and kill the application anyway. The difference between sepp2k's code and the code you're having here, is that you're swallowing all COM exceptions - which is bad. I really don't see a reason not to use the code provided in the post you're following-up on, which filters the error code (if ((e.ErrorCode & 0xFFFF) == 0xC472)) and re-throws all other exceptions, leaving you with a way to exit the loop if you get a COM exception that's saying anything other than Excel is busy.
{ "domain": "codereview.stackexchange", "id": 5015, "tags": "c#, exception-handling, excel, com" }
Motivation for definition of work
Question: Why do we take the dot product in the work energy theorem? Consider the integral $$\int\vert\vec F\vert\vert d\vec r\vert$$ Why don't we define this to be work done for example, instead of $\int\vec F\cdot d\vec r$? I conjecture that this integral gives one unuseful results, thus there is no point to consider it. For example, let $\vec F=( F,0,0)$ and $d\vec r=(0,d y,0)$. Thus above integral becomes $$F\Delta y$$ Assume for simplicity that the object moves with uniform velocity in the $y$ direction. The above equation then becomes $$Fv\Delta t$$ where $v$ is speed and $t$ is time. Thus even a particle with no forces in the $y$ direction gives a non-zero result. This, to me, seems to be a problem from a practical point of view to make predictions. Is my view correct and can it be generalized? Answer: This is somewhat opinion-based, but in my view the definition of work as $W = \int \mathbf F \cdot \mathrm d\mathbf r$ is motivated by the work-energy theorem, which says that $$\Delta \left(\frac{1}{2} mv^2\right) = \int \mathbf F \cdot\mathrm d\mathbf r$$ which follows directly from Newton's 2nd law by integrating both sides: $$\mathbf F = m\mathbf a $$ $$\implies \int\mathbf F \cdot \mathrm d\mathbf r = \int m \mathbf a \cdot \mathbf v \ \mathrm dt = \int \frac{d}{dt}\left(\frac{1}{2}m|\mathbf v|^2\right) \mathrm dt $$ $$\implies \int \mathbf F \cdot \mathrm d\mathbf r = \Delta \left(\frac{1}{2}m |\mathbf v|^2\right)$$ This is a very common way to manipulate 2nd order ODE's of the form $\ddot{\mathbf y} = \mathbf Q$; first one "dots" both sides with $\dot{\mathbf y}$ and then integrates with respect to time to obtain $\Delta\left(\frac{1}{2}|\dot{\mathbf y}|^2\right) = \int \mathbf Q \cdot \dot{\mathbf y} \ \mathrm dt = \int \mathbf Q \cdot \mathrm d \mathbf y$. The impulse-momentum theorem similarly follows from Newton's 2nd law via integrating with respect to $t$ instead of $\mathbf r$: $$\mathbf F = m \mathbf a$$ $$\implies \int \mathbf F \ \mathrm dt = \int m \mathbf a \ \mathrm dt = \int \frac{d}{dt}(m\mathbf v) \mathrm dt$$ $$\implies \int \mathbf F \ \mathrm dt = \Delta(m\mathbf v)$$ There are other reason why work, kinetic energy, impulse, and momentum are useful quantities, but their definitions most naturally arise (again, in my opinion) from the formal manipulation of Newton's 2nd law.
{ "domain": "physics.stackexchange", "id": 92640, "tags": "newtonian-mechanics, forces, work, definition, displacement" }
Is it decidable whether a Turing machine modifies the tape, on a particular input?
Question: Is $L=\{\langle M,w \rangle|M\text{ does not modify the tape on input w}\}$ decidable? We could tell if a TM does not modify the tape on any input by checking if there are no transitions in $M$ that write on the tape, but can it be decided for a given $w$? Answer: Yes, this is decidable. Here are two different proofs of that fact. A counting proof Define a configuration to be the state of the tape, the location of $M$'s head, the state that $M$'s finite control is in, and whether or not $M$ has written to the tape yet. Note that for a fixed $w$, if $M$ does not modify the tape on input $w$, there are only finitely many possible configurations, let's say $N$ of them. $N$ can be easily computed; it is about $2 \times (\text{len}(w) + 2|M|) \times |M|$ where $|M|$ is the number of states in $M$'s finite control. (See footnote *.) So, run $M$ on input $w$ and keep track of all the configurations it enters. One of three things must happen: After at most $N$ steps, $M$ modifies the tape. In that case you know $\langle M,w \rangle \notin L$ and there's no need to keep simulating $M$. After at most $N$ steps, $M$ halts without ever modifying the tape. In that case you know $\langle M,w \rangle \in L$ and there's no need to keep simulating $M$. After at most $N$ steps, $M$ repeats some prior configuration without ever modifying the tape and thus enters a cycle. In that case you know $M$ will loop forever on input $w$, without modifying the tape, so $\langle M,w \rangle \in L$ and there's no need to keep simulating $M$. Thus, after simulating $M$ for $N$ steps, we learn whether $M$ will ever modify the tape on input $w$. Footnote *: In this proof I will consider as equivalent all configurations where the head is more than $|M|$ cells to the right of the input and that differ only in the location of $M$'s head, and I consider as equivalent all configurations where the head is more than $|M|$ cells to the left of the input and that differ only in the location of $M$'s head. Why? If it ever reaches one of those configurations without modifying the tape, then it will loop forever without modifying the tape. This follows by a pigeonhole argument; the finite control can't count higher than $|M|$, i.e., if it reaches one of those configurations, then some state of the finite control must have repeated during the time when it's wholly to the right/left of the input, so it has entered a loop. A conceptual proof For a given $w$, if $M$ doesn't write to the tape, it is equivalent to a two-way deterministic finite automaton (2DFA). So, you can write down a 2DFA with the following three properties: The DFA has a single accepting state $q_a$, with a self-loop (once it accepts, it stays accepting forever). All other states are non-accepting. If $M$ never writes to the tape on input $w$, the behavior of the 2DFA on input $w$ is equivalent to the behavior of $M$, and the 2DFA never transitions to the special accept state $q_a$ and never accepts. If $M$ does write to the tape on input $w$ at some point, the behavior of the 2DFA is equivalent up until the point $M$ first writes to the tape; thereafter the 2DFA follows a transition to the special accept state $q_a$ and thus accepts. How do we build such a 2DFA? The 2DFA is just a copy of the finite control of $M$ (which is a finite automaton), except that it moves to $q_a$ whenever $M$'s finite control would modify the tape: If $M$'s finite control has a transition $q_i \to q_j$ when symbol $i$ is under the head $i$ and this transition doesn't write anything, then the 2DFA has the same transition. If $M$'s finite control has a transition $q_i \to q_j$ when symbol $i$ is under the head $i$ and this transition does write to the tape, the 2DFA has a transition $q_i \to q_a$ on symbol $i$. Now the question just becomes: given a 2DFA, does it accept on input $w$? This is decidable, as every 2DFA is equivalent to a (possibly exponentially larger) ordinary DFA. Comparison of proofs Either proof suffices to show that $L$ is decidable. The counting proof has the advantage of not requiring fancy machinery like 2DFA. The conceptual proof shows both that $L$ is decidable and something stronger: if we restrict attention to a single fixed $M$, then the set of $w$ such that $\langle M,w \rangle \in L$ is in fact a regular language (since 2DFA are equivalent in power to DFAs). Pretty nifty!
{ "domain": "cs.stackexchange", "id": 7885, "tags": "computability, turing-machines, reductions, undecidability" }
How does Bifunctor in Haskell work?
Question: I was reading 'Category Theory for Programmers' by Bartosz Milewski and got really confused by the implementation of bimap in Bifunctor typeclass. class Bifunctor f where bimap :: (a -> c) -> (b -> d) -> f a b -> f c d bimap g h = first g . second h first :: (a -> c) -> f a b -> f c b first g = bimap g id second :: (b -> d) -> f a b -> f a d second = bimap id This is the definition of the Bifunctor typeclass taken directly from the library Control. If bimap evaluates to first and second, which in turn evaluates to bimap itself, how is this supposed to end? Could you please explain how the evaluation of bimap works? Thank you! Answer: A Haskell type class defines a set of functions (sometimes called methods) that belong to the type class. In most cases, specific instances must supply specific implementations of one or more of these. An instance can implement all methods, or just enough to make the instance work. If an instance doesn't implement all methods, the default implementations are used. Type classes are typically documented with the minimal implementation required. This is also true for Bifunctors: Minimal complete definition bimap | first, second This means that an instance must implement either bimap, or both first and second. An instance can also implement all three, but that's not required. The tuple instance, for example, is implemented using bimap: instance Bifunctor (,) where bimap f g ~(a, b) = (f a, g b) This means that the first and second implementations are the default implementations you quoted above. They call the instance's bimap implementation.
{ "domain": "cs.stackexchange", "id": 15231, "tags": "haskell" }
I cant get move_base source files
Question: I tried following this answer, but with apt-get source I always get this on any package Reading package lists... Done E: Unable to find a source package for ros-kinetic-move-base I found source files on github but I want to get them in package folder. How can I get move_base source files so I can edit them, or any files source files? EDIT: ok so i get the files with apt-get source, but how do i put them in move_base directory so i can edit them there and it gets saved and compiled?? Originally posted by topkek on ROS Answers with karma: 27 on 2018-08-26 Post score: 0 Original comments Comment by gvdhoorn on 2018-08-26: Did you follow the instructions in #q12478 to setup the apt source repositories? Comment by topkek on 2018-08-26: yes, still getting the same error EDIT: ok, i did it, thank you :) Comment by gvdhoorn on 2018-08-26: So what did you do in the end? If you made a mistake, but then got things to work please post what you did as an answer so others can learn. Comment by topkek on 2018-08-28: i followed answers from that question and after sudo apt-get update it worked Answer: You will need to clone and build the move_base package into your workspace. So: Go to your workspace src space: cd /path/to/your/catkin_ws/src Put/clone here the package from the kinetic-devel branch: git clone https://github.com/ros-planning/navigation/tree/kinetic-devel Once you do this you can compile the workspace. It should compile successful although there might be some dependencies missing that you will need to install.In that case navigate to your workspace: cd /path/to/your/catkin_ws and to install missing dependencies run: rosdep install --from-paths src -ryi --rosdistro=kinetic Next thing to do is source your setup.bash. Once again navigate to your workspace: cd /path/to/your/catkin_ws and run there: source devel/setup.bash and you should be able to use and edit the package. Originally posted by pavel92 with karma: 1655 on 2018-08-27 This answer was ACCEPTED on the original site Post score: 0 Original comments Comment by topkek on 2018-08-28: ok, i did it but now i get this error when running movebase node without editing anything in the package. ERROR: cannot launch node of type [move_base/move_base]: can't locate node [move_base] in package [move_base] Comment by pavel92 on 2018-08-29: actually, you want only the move_base, not the whole navigation stack so just clone the move_base package. You should still have the navigation stacked already installed via: sudo apt-get install ros-kinetic-navigation Comment by pavel92 on 2018-08-29: regarding the new error message, maybe this question can help. Comment by topkek on 2018-08-29: I just reinstalled ROS and git cloned navigation files. Now everything is working
{ "domain": "robotics.stackexchange", "id": 31644, "tags": "navigation, move-base, ros-kinetic" }
How to make the two-photon process occur in ionization?
Question: In my previous questions I ask about ionizing air molecules such as nitrogen which requires 15.58 eV or oxygen which requires 12.07 eV. If you do the equation wavelength = 1240 eV nm / (photon energy) required for ionization to occur. In this case if I wanted to ionize nitrogen I would need a laser with a wavelength of ~80 nm. This is the single-photon process, but based on what I have heard I see that if you do a two-photon process you can increase your wavelength to more readily available laser and still output the same photon energy. If what I'm saying is true then how do I make this happen? What wavelength at what pulse rate would I need to output 15.58 eV? I just don't understand how you make it a two photon process that is all. I know even a two photon process is probably going to be low, but maybe I can apply the same feedback I receive into a eight-photon process and so on and so forth. Any help would be much appreciated! Answer: The repetition rate of the pulses is completely irrelevant to the probability of getting multiphoton processes: once a given pulse is over, then its ionization events are done with, and it doesn't matter how soon the next pulse comes, it will be an independent event. The probability of multiphoton processes (at a given wavelength) is governed by the intensity of the light: that is, the total energy flux at a given point, which you get by dividing the pulse energy (that's the average beam power divided by the repetition rate) over the pulse duration and the area of the focal spot, at least as an order-of-magnitude estimate. Note, moreover, that for an $n$-photon process, the rate of ionization scales as the $n^\rm{th}$ power of the intensity, which means that a small decrease in the intensity will take a much higher dent in the rate: if you make 95% of the intensity you wanted, for a 6-photon process, the rate will go down by 30%. Moreover, for the avalanche-driven aspects of laser-induced optical breakdown, the dependence on intensity can be a good deal sharper. If you don't have the intensity to drive the positive feedback loop, it just won't happen. If you just want to produce laser-induced optical breakdown of air to see pretty sparks, then RP photonics puts the threshold for breakdown in the neighbourhood of $≈ 2 × 10^{13} \:\mathrm{ W/cm^2}$ for pulse durations of the order of one picosecond.
{ "domain": "physics.stackexchange", "id": 44389, "tags": "photons, laser, ionization-energy" }
How to satisfy bounded waiting in case of deadlock?
Question: I have a doubt regarding bounded waiting. Deadlock implies no Progress because the processes take indefinite time to decide who will enter the critical section . But, Does deadlock implies no bounded waiting ? I think No because bounded waiting is per process and deadlock is for the system. Moreover, In a deadlock, bounded waiting conditon is not violated and bounded waiting is not with respect to time, but with respect to the number of times the processes enter the critical section before intended process enters the critical system . Would anyone at least care to correct me or suggest what is right and not right? Answer: You are correct. Consider the simple synchronization algorithm which denies entry to all processes. In this case we have both deadlock and bounded waiting, since any process $p$ is not bypassed by some process $p'$ before entering the critical section, so you could say bounded waiting is satisfied with the constant function $f=0$.
{ "domain": "cs.stackexchange", "id": 7350, "tags": "operating-systems, deadlocks" }
down sample camera image on driver or image_proc level
Question: In addition to producing higher resolution images than the wge100 cameras, the PR2's Prosilica also puts out images with much better color quality. In the perfect world, I would have a camera on the PR2 that can spew out images at the same frame rate of the wge100 cameras but with the image quality of the Prosilica. I was wondering if there is a way to down sample the images from the Prosilica camera on the driver level or at least have it done by the image_proc node. We obviously down sample the received images in code but we are getting them at 2fps and would like to get them at a faster frame rate and at a lower resolution. If the images were to be down sampled by the driver or by the image_proc node, maybe the travel time would be shorter and we would get a faster frame rate? I don't actually know how fast the camera can spit out images. Just to be clear, I know that you can crop the images using dynamic_reconfigure but I'm wondering whether it can down sample the entire image somehow. I'm a vision noob so I think this is probably feasible - I just don't know how to do it. Originally posted by ben on ROS Answers with karma: 674 on 2011-09-20 Post score: 2 Answer: Limit Your Exposure Time Your most immediate problem is likely that you're exposure-limited. At full resolution, the PR2's Prosilica can stream at 15fps. Since you're only getting 2fps, I'm guessing the environment is dark and auto-exposure is ballooning to ~0.5s to achieve an acceptably bright image. Try playing with the exposure and gain settings - you can access these through dynamic_reconfigure (look for the /prosilica_driver group). Turn off auto_exposure and set the exposure time to 0.066 or less (for 15fps). Then adjust the gain level to get a sufficiently bright image, or let auto_gain do it for you. Gain is digital amplification; it gets you a brighter image at the cost of increased noise. The downsampling can be done either in hardware or software. Hardware Downsampling This is called binning. When you use MxN binning, the camera combines each MxN block of pixels into one super-pixel. You can enable binning with the binning_x and binning_y parameters. Besides reducing the image size, binning can increase frame rate in a couple of ways: For each frame there's less data going over the wire. At full resolution, the frame rate is bandwidth limited, so your max FPS goes up. For the PR2's Prosilica, with 2x2 binning you can achieve 25fps, and at 4x4 binning (612x512 image) you can get ~39fps. A pixel is basically an electron bucket, and by pooling adjacent buckets in hardware you get better sensitivity. So you can reduce exposure time and/or gain in low-light conditions. There is one big drawback to hardware binning: you lose color. Color cameras generally work by tesselating a 2x2 color filter called a Bayer pattern over the sensor. Each pixel only detects one RGB channel. One of image_proc's duties is to interpolate (debayer) the raw image to get a full RGB image. But when you apply binning, each 2x2 Bayer element gets averaged into one monochrome super-pixel. Software Downsampling Downsampling in software gives you none of the frame rate and sensitivity advantages of hardware binning. You should only bother if you need a smaller image and at least one of the following is true: Your camera doesn't support hardware binning. You require color. In ROS Electric, the image_proc package contains a new crop_decimate nodelet that applies software binning/ROI. It is not loaded as part of the standard image_proc node. You can try it out by doing: rosrun nodelet nodelet standalone image_proc/crop_decimate camera:=prosilica camera_out:=prosilica_downsampled rosrun image_view image_view image:=/prosilica_downsampled/image_raw Then open /image_proc_crop_decimate in reconfigure_gui and set decimation_x and decimation_y to 2. Conclusion You may not be able to get everything you want from the PR2 Prosilica. If you don't need color, use hardware binning. If you need color but can live with 15fps, use software downsampling. If you absolutely need color at 30fps, the GC2450C is simply the wrong camera. Prosilica does have cheaper cameras at VGA resolution. Originally posted by Patrick Mihelich with karma: 4336 on 2011-09-21 This answer was ACCEPTED on the original site Post score: 5 Original comments Comment by ben on 2011-09-22: Thanks a lot Patrick! I really appreciate the detailed response. I do need color because I'm doing color blob detection so I'll try the software downsampling.
{ "domain": "robotics.stackexchange", "id": 6731, "tags": "ros, dynamic-reconfigure, image-pipeline, prosilica-camera" }
Are fixed points of RG evolution really scale-invariant?
Question: It is often stated that points in the space of quantum field theories for which all parameters are invariant under renormalisation – that is to say, fixed points of the RG evolution – are scale-invariant field theories. Certainly this should be a necessary condition, since the theory must look the same at all scales. However, I have doubts whether this is sufficient. In the classical theory, there is no notion of renormalisation, but nevertheless we can talk about scale-invariant theories; these theories possess a global dilatation symmetry. Theories with inherent mass scales, such as $\phi^4$ theory with a non-zero quadratic term, are not classically conformal because they lack such a symmetry. It seems to me that the vanishing (or perhaps blowing up?) of such dimensionful couplings must also be a condition to impose on a quantum field theory, if we wish for it to be scale-invariant. My question is then: are the dimensionful couplings of all fixed points in RG flow necessarily trivial? Is it impossible for an RG fixed point to have some mass scale $M \neq 0$ in its Lagrangian? As I see it, either the answer is yes, in which case being at a fixed point is enough to guarantee scale invariance, or the answer is no, in which case we also need to make an additional requirement of our theories if we wish for them to be conformal, beyond the vanishing of all beta functions Answer: No, dimensionful couplings do not have to be all set to zero at an RG fixed point. An RG fixed point is one where all of the beta functions vanish, and beta functions generally have the form $$\beta(g_i) = (d_i - d) g_i + \hbar A_{ij} g_j + \ldots$$ where $d_i$ is the dimension of the corresponding operator. If one truncates the series at $O(\hbar^0)$ then the only possible solution is to have $g_i = 0$ if $d_i \neq 0$, so in classical field theory the only fixed points are the massless free theory and massless $\phi^4$ theory. In a quantum field theory we must account for loop diagrams, which give terms that are higher order in $\hbar$. Then the zeroes of the beta functions are completely different; the massless free theory remains a fixed point, called the Gaussian fixed point, but massless $\phi^4$ theory acquires a mass scale by dimensional transmutation. But this process can also work in reverse. In this case there's a new fixed point, the Wilson-Fisher fixed point, where the classical mass term is nonzero. This is dimensional transmutation running in reverse; the mass renormalizes to exactly zero.
{ "domain": "physics.stackexchange", "id": 47218, "tags": "quantum-field-theory, renormalization, conformal-field-theory, classical-field-theory, scale-invariance" }
pound force and pound mass
Question: I have a question about work measured in foot-pound. Let's say we have a 10 pound-mass ($10$ $\text{lb}_m$) object. Then since that 10 pound-mass ($10$ $\text{lb}_m$) object gives 10 pound-force ($10$ $\text{lb}_f$) due to gravity, if we raise that object 2 feet, the work is 20 foot-pound ($20$ $\text{ft}\cdot\text{lb}_f$). I was wondering if I am right. Answer: You are correct. $F = \left( \text{mass} \right) \cdot \left( \text{acceleration} \right)$, therefore, $\text{weight} = \left( \text{mass} \right) \cdot \left( \text{acceleration} \right)$ due to gravity Weight of a $10 \text{ lb}_m$ object = $\left( 10 \text{ lb}_m \right) \cdot \left( 32.2 \frac{\text{ft}}{\text{s}^2} \right)$ (approximate acceleration due to gravity on Earth) Weight of a $10 \text{ lb}_m$ object = $322 \frac{\text{lb}_m \cdot \text{ft}}{\text{s}^2}$. Since $1 \text{ lb}_{\text{f}}$ = $32.2 \frac{\text{lb}_m \cdot \text{ft}}{\text{s}^2}$, you are correct that its weight is $10 \text{ lb}_{\text{f}}$ ${Work} = \left( \text{force} \right) \cdot \left( \text{distance} \right) = \left( 10 \text{ lb}_{\text{f}} \right) \cdot \left( 2 \text{ feet} \right) = 20 \text{ ft} \cdot \text{lb}_f$
{ "domain": "engineering.stackexchange", "id": 3852, "tags": "mechanical-engineering" }
How to use the generated 3D point cloud in RGBDSLAM package for localization?
Question: Hello, I have generated RGBD map using " RGBDSLAMv2" package and wanted to perform localization in 3D environment.How can this be achieved? has anyone done it?. Can i use the package "humanoid_ navigation" package with " RGBDSLAMv2" package to achieve the same?Please guide me i am novice in this. Thank you. Originally posted by kaygudo on ROS Answers with karma: 11 on 2016-01-21 Post score: 1 Original comments Comment by kaygudo on 2016-01-22: So is there any other way you know? Comment by Felix Endres on 2016-02-09: No, sorry. Answer: For rgbdslam_v2 localization with an existing map is not possible. I do not know whether the humanoid navigation package can do this. Originally posted by Felix Endres with karma: 6468 on 2016-01-22 This answer was ACCEPTED on the original site Post score: 0
{ "domain": "robotics.stackexchange", "id": 23507, "tags": "ros, rgbdslamv2" }
Model's loss weights
Question: I've model with two output layers, age and gender prediction layers. I want to assign different weight values for each output layer's loss. I've the following line of code to do so. model.compile(loss=[losses.mean_squared_error,losses.categorical_crossentropy], optimizer='sgd',loss_weights=[1,10]) My question is what is the effect of loss weights on performance of a model? How can I configure the loss weights so that the model can perform better on age prediction? Answer: This will affect how the backpropagation for each of these outputs will cause the intermediate nodes within the network to be updated. If the output nodes' error were equal then the gradient descent process of the intermediate nodes will favor the resulting error of each of these outputs equally. By more heavily weighting an output node it means that the gradient descent will favor a set of parameters that perform better on that output node.
{ "domain": "datascience.stackexchange", "id": 3186, "tags": "machine-learning, keras, tensorflow" }
Black hole "no hair" theorem
Question: The "no hair" theorem (or conjecture), suggests that black holes can be entirely described by their mass, angular momentum and charge. All other details of the BH formation are lost. Is there a simple way of understanding why you would be able to tell the difference between a BH made from protons and one made from electrons, but not between one made from matter rather than anti-matter? i.e. What is special about charge, and why aren't lepton number, baryon number, strangeness etc, also black hole properties? Answer: The simplest answer lies in a combination of Gauss's law and Birkhoff's theorem. These say, alternately, that the electric field and gravitational field of a spherically symmetric charge distrubtion only depends on the charge and mass-energy enclosed in the spherical shell${}^{1}$. Therefore, if I have a spherically symmetric distribution of charged mass, and I'm out at some radius $R$ outside of it, I can't tell whether it collapsed to a black hole or not just by making local measurements of the fields. This means that the information about the charge and mass of the black hole must live outside of the horizon. There is no similar set of theorems that tells you about whether the distribution was made out of electrons or antiprotons, or lepton number, or the like. So, you lose the information about that stuff, but not the mass and charge. ${}^{1}$Note that the mass energy in a shell depends on the enclosed electromagnetic field, so it's natural that the Nordstrom metric differs from the Schwarzschild metric.
{ "domain": "physics.stackexchange", "id": 17151, "tags": "particle-physics, black-holes, no-hair-theorem" }
Why do cutoff frequencies of a high-pass digital filter differ from the ones i used to transform it from a low-pass analog filter in MATLAB?
Question: I need to transform an elliptic analog low-pass filter to a digital high-pass filter but i'm having a problem because the resulting filter has lower cutoff frequencies than the ones i set. Here is the code sample from MATLAB: Fs = 44100; %Sampling rate Rp = 0.05; Rs = 60; Wp = 2*pi*10000; %Cutoff frequencies of my high-pass filter Ws = 2*pi*9700; WsE= Wp/Ws; %LP->HP transformation for the analog stopband frequency WpE=1 k=sqrt(1-(WpE/WsE)^2); %Elliptic filter calculation of N D=(10^(0.1*Rs)-1)/(10^(0.1*Rp)-1); q0=(1/2)*((1-sqrt(k))/(1+sqrt(k))); q=q0+2*q0^5+15*q0^9+150*q0^13; N=ceil(log10(16*D)/(log10(1/q))); [z,p,k]=ellipap(N,Rp,Rs); %Making the analog prototype bE=k*poly(z);aE=poly(p); [bE,aE]=lp2hp(bE,aE,Wp); %Transforming the low-pass into a high-pass [bd,ad]=bilinear(bE,aE,Fs); Ndigital = 20000; [h,w]=freqz(bd,ad,Ndigital); H=abs(h); f = w/(2*pi)*Fs; % Ploting the filter figure(1); plot(f,20*log10(H), 'LineWidth', 2); xlabel('Hz'); ylabel('|H(z)|'); pause and i am expecting a filter with my desired frequencies but get this: I can't pin-point the problem in the code. Why am i getting these results and how do i fix them? Answer: The bilinear transform warps the frequency axis, that's why cut-off frequencies of the analog filter are not necessarily mapped to the correct frequencies in the digital domain. You can use the prewarping option by providing an optional parameter to bilinear.m. Check the corresponding mathworks documentation.
{ "domain": "dsp.stackexchange", "id": 7111, "tags": "matlab, filters, lowpass-filter, digital-filters, highpass-filter" }
Count frequency of words and print them in sorted order
Question: Objective: Write a program to count the frequencies of unique words from standard input, then print them out with their frequencies, ordered most frequent first. For example, given this input: The foo the foo the defenestration the The program should print the following: the 4 foo 2 defenestration 1 The test input file will be the text of the King James Bible, concatenated 10 times. Code: I used the public-domain stb library stb_ds.h for the hash table. #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdint.h> #include <stdbool.h> #include <limits.h> #include <ctype.h> #define STB_DS_IMPLEMENTATION #include "stb_ds.h" /* pneumonoultramicroscopicsilicovolcanoconiosis - a lung disease caused by * inhaling silica dust. */ #define LONGEST_WORD 45 #define CHUNK_SIZE (8 * 1024) typedef struct count { char *key; size_t value; } count; static int cmp_func(const void *a, const void *b) { const count *const p = *(const count * const *) a; const count *const q = *(const count * const *) b; return (p->value < q->value) - (p->value > q->value); } static void replace_punctuation(size_t len, char s[static len]) { // ".,;:!?\"()[]{}-" static const char table[UCHAR_MAX + 1] = { ['.'] = '.' ^ ' ',[','] = ',' ^ ' ',[';'] = ';' ^ ' ',[':'] = ':' ^ ' ', ['!'] = '!' ^ ' ',['?'] = '?' ^ ' ',['"'] = '"' ^ ' ',['('] = '(' ^ ' ', [')'] = ')' ^ ' ',['['] = '[' ^ ' ',[']'] = ']' ^ ' ',['{'] = '{' ^ ' ', ['}'] = '}' ^ ' ',['-'] = '-' ^ ' ' }; for (size_t i = 0; i < len; ++i) { s[i] ^= table[((unsigned char *) s)[i]]; } } static count *load_ht(FILE * stream) { count *ht = NULL; /* Store the string keys in an arena private to this hash table. */ sh_new_arena(ht); char chunk[CHUNK_SIZE]; size_t offset = 0; while (true) { const size_t nread = fread(chunk + offset, 1, CHUNK_SIZE - offset, stream); if (ferror(stream)) { shfree(ht); return NULL; } if (nread + offset == 0) { break; } /* Search for last white-space character in chunk and process up to there. */ /* Can we replace this with a library function? */ size_t curr_chunk_end; for (curr_chunk_end = nread + offset - 1; curr_chunk_end != SIZE_MAX; --curr_chunk_end) { const unsigned char c = (unsigned char) chunk[curr_chunk_end]; if (isspace(c)) { break; } } /* How can we iterate the chunk just once? */ const size_t curr_chunk_size = curr_chunk_end != SIZE_MAX ? curr_chunk_end : nread + offset; replace_punctuation(curr_chunk_size, &chunk[0]); size_t i = 0; while (true) { /* Malformed input? Perhaps add a check and make the program slower, * or give the user what it deserves. */ char word[LONGEST_WORD]; size_t word_len = 0; while (isspace((unsigned char) chunk[i])) { ++i; } const size_t start = i; /* Profiling showed that much of the time is spent in this loop. */ for (; i < curr_chunk_size && !isspace((unsigned char) chunk[i]); ++i) { word[word_len++] = (char) tolower((unsigned char) chunk[i]); } if (i == start) { break; } word[word_len] = '\0'; /* Skip words beginning with a digit. */ if (!isdigit((unsigned char) word[0])) { /* Strip possessive nouns. */ if (word_len >= 2 && word[word_len - 1] == 's' && word[word_len - 2] == '\'') { word[word_len - 2] = '\0'; } else if (word[word_len - 1] == '\'') { word[word_len - 1] = '\0'; } const size_t new_count = shget(ht, word); shput(ht, word, new_count + 1U); } } /* Move down remaining partial word. */ if (curr_chunk_end != SIZE_MAX) { offset = (nread + offset - 1) - curr_chunk_end; memmove(chunk, chunk + curr_chunk_end + 1, offset); } else { offset = 0; } } return ht; } int main(void) { count *ht = load_ht(stdin); if (!ht) { perror("fread()"); return EXIT_FAILURE; } size_t ht_len = shlenu(ht); /* Profiling the code didn't show malloc()/mmap()/brk()/sbrk() to be a * bottleneck. */ count **const ordered = malloc(sizeof *ordered * ht_len); int rv = EXIT_FAILURE; if (!ordered) { goto cleanup; } for (size_t i = 0; i < ht_len; ++i) { ordered[i] = malloc(sizeof **ordered); if (!ordered[i]) { while (i) { free(ordered[i--]); } goto cleanup; } ordered[i]->key = ht[i].key; ordered[i]->value = ht[i].value; } qsort(ordered, ht_len, sizeof *ordered, cmp_func); for (size_t i = 0; i < ht_len; ++i) { printf("%-*s\t%zu\n", LONGEST_WORD, ordered[i]->key, ordered[i]->value); free(ordered[i]); } rv = EXIT_SUCCESS; cleanup: free(ordered); shfree(ht); return rv; } The program has 127 LOC (excluding stb_ds.h), and the final executable (stripped) sizes around 19 KB. And this is how it performed: » time ./wordfreq < kjvbible_10.txt 1> /dev/null ./wordfreq < kjvbible_10.txt > /dev/null 2.39s user 0.10s system 99% cpu 2.507 total ----------------------------------------------------------------------------------- » time wc kjvbible_10.txt 998170 8211330 43325060 kjvbible_10.txt wc kjvbible_10.txt 1.12s user 0.02s system 98% cpu 1.156 total Review Goals: How can the total running time be reduced? What's a better algorithm for processing the file? Does any part of my code invokes undefined behavior? Have I missed any edge-cases? General coding comments, style, et cetera. Answer: Some subtle concerns. Same but different This is an advanced concern that involves portability. Consider an output where multiple words have the same frequency as with input "the the the foo defenestration foo defenestration foo defenestration". A result of the 3 foo 3 defenestration 3 would be just as valid as: defenestration 3 foo 3 the 3 Recall that the specification details of qsort() do not specify the sub-order when the compare returns 0. Not all qsort() sort these equal cases in the same order. Within a given compiler this is not a issue, yet consider that you are tasked with maintaining code across 10 platforms/compilers and the results were different, yet compliant, as above. This situation occurred in my career and became a nightmare for our test engineer whose job was to verify equivalent functionality across the multiple platforms/compilers. It was not sufficient to simply compare for identical output, but manual analyses was done. For OP, cmp_func() could be augmented to differentiate when a, b point to the same .value. static int cmp_func_alt(const void *a, const void *b) { const count *const p = *(const count * const *) a; const count *const q = *(const count * const *) b; // return (p->value < q->value) - (p->value > q->value); int cmp = (p->value < q->value) - (p->value > q->value); if (cmp == 0) { cmp = (p < q) - (p > q); // Compare pointers } return cmp; } Similar problems occurred with stricmp() and rand(). stricmp() would convert to upper case and compare on some systems and convert to lower case then compare on others. This made _ before A on some systems and after Z on others, thus affecting the sorted order of strings. This was solved with rolling our own portable stricmp() code which outperformed some systems' stricmp() due to a little "trick". rand() (this function varied a great deal per systems) was replaced with a superior yet consistent PRNG routine. Pedantic: Access char data consistently With C2X, this will not likely be a concern. OP's code uses 2 ways to access char data. Best to use the same. With char * s, is the following always true? *((unsigned char *) s) == (unsigned char) *s It differs when char is signed and negative values are not encoded with 2's compliment. <string.h> functions access char via unsigned char * and so I recommend this model. For all functions in this subclause, each character shall be interpreted as if it had the type unsigned char (and therefore every possible object representation is valid and has a different value). C23dr § 7.26.1 4
{ "domain": "codereview.stackexchange", "id": 45480, "tags": "performance, c, programming-challenge" }
What happens when you put (pour) water on water with the same density? (Archimedes)
Question: Suppose you have a glass of water, and you pour on it a volume V of water of the same density; if we consider the archimedes principle, what happens to the water that is poured? Does it float, sink, not move? Answer: Archimedes Principle will not cause the poured water (at the same density) to float or sink. Generally however, the incoming water will sink due to its downward momentum, in proportion to the pouring height above the water surface, easily overcoming the surface tension of the incumbent water. Any air bubbles trapped in the incoming water will then rise to the surface, along with some water surrounding it. See the picture below. If you would like to view the interaction of the two bodies of water, you could colour one of them with a dye that insignificantly varies the water density, and then conduct the pour testing. Alternating which one (dyed or not) you pour should allow you to draw a confident conclusion. Photo courtesy of https://www.dreamstime.com/royalty-free-stock-photos-pouring-water-image1790388
{ "domain": "physics.stackexchange", "id": 64427, "tags": "water, fluid-statics, density, buoyancy" }
How can we estimate the likelihood field for a particular scan in probabilistic terms?
Question: I am trying to implement a scan matcher using Scan based sensor model but I cant figure out how to estimate likelihood for a particular scan. Is there any implementation available ? Would be thankful for help Answer: It looks like ROS has a few packages (in rough order of apparent usefulness): Scan matcher laser scan matcher Local map crsm-slam mrpt-localization amcl
{ "domain": "robotics.stackexchange", "id": 1474, "tags": "slam, probability" }
Expressing CNOT in the eigenbasis of $X$ (Preskill lecture notes eq. 7.6)
Question: In chapter 7, equation 7.6 says CNOT works as follows: CNOT: $\frac{1}{\sqrt{2}} (|0\rangle + |1\rangle )\otimes |x\rangle \rightarrow \frac{1}{\sqrt{2}} (|0\rangle + (-1)^x |1\rangle ) \otimes |x\rangle$, where it acts trivially if the target is $x=0$ state, and it flips the control if the target is the $x=1$ state. I've looked at a few other resources about CNOT and this is the first time I encountered the $(-1)^x$ term. Could someone explain to me where that term comes from? Given that the matrix representation of CNOT is $$ \begin{pmatrix} 1 & 0 &0 &0 \\ 0 & 1 & 0 & 0\\ 0 & 0 & 0 & 1\\ 0 & 0 & 1 & 0 \end{pmatrix}$$ I don't see how that $(-1)^x$ came about. Answer: Expanding on Jalex Look at what happens on the possible terms. \begin{eqnarray*} \mid 0 \rangle \otimes \mid + \rangle &\to& \mid 0 \rangle \otimes \mid + \rangle\\ \mid 0 \rangle \otimes \mid - \rangle &\to& \mid 0 \rangle \otimes \mid - \rangle\\ \mid 1 \rangle \otimes \mid + \rangle &\to& \mid 1 \rangle \otimes \mid + \rangle\\ \mid 1 \rangle \otimes \mid - \rangle &\to& (-1) \mid 1 \rangle \otimes \mid - \rangle\\ \end{eqnarray*} where the first 2 are unchanged because the control is $0$ so nothing happens. The third is unchanged because NOT applied to $\mid + \rangle$ just gives back $\mid + \rangle$. The last is the only one with change because NOT applied to $\mid - \rangle$ gives $(-1) \mid - \rangle$. We can summarize these possibilities by knowing that $\mid + \rangle$ goes with $x=0$ and $\mid - \rangle$ with $x=1$ as: \begin{eqnarray*} \mid 0 \rangle \otimes \mid x \rangle &\to& \mid 0 \rangle \otimes \mid x \rangle\\ \mid 1 \rangle \otimes \mid x \rangle &\to& (-1)^x \mid 1 \rangle \otimes \mid x \rangle\\ \end{eqnarray*} The first two become the first one above. And third and fourth, the second above. Now add the two together along with a $\frac{1}{\sqrt{2}}$ prefactor to give $$ \frac{1}{\sqrt{2}} ( \mid 0 \rangle + \mid 1 \rangle ) \otimes \mid x \rangle \to \frac{1}{\sqrt{2}} ( \mid 0 \rangle + (-1)^x \mid 1 \rangle ) \otimes \mid x \rangle $$
{ "domain": "quantumcomputing.stackexchange", "id": 786, "tags": "quantum-gate, pauli-gates" }
Time travel future (with calculations)
Question: First, I have seen a few similar questions, but none involved the formulas and calculations I want to find. This is why I do not consider this as a duplicate. I know time travel to the future is possible, but I also know that I cannot use the special relativity formulas if there is a change of speed. I need G.R. but I do not know any. This is my question: At time $t=0$ (for me and the fixed referential), I start to travel on a straight line away from the origin ($x=0$). Let's assume that, in the fixed referential of the origin (time=t), my travel lasts 1 unit (I come back at $t=1$ unit of time) my position is given by $x(t)=(3c\sqrt3)t^2(1-t)^2$. The letter $c$ stands for the speed of light in vacuum in the appropriate unit. (If the units are a problem, let's consider I divide this whole thing with $t_0^3$ where $t_0=1$ unit). What is the time difference between my watch and a fixed watch that was resting at the origin when I come back? I do not expect anyone to derive this for me (but I you feel like it, I would be happy), but can you indicate to me which formula I should use? Or, if it is too complicated, maybe try to give me an order of magnitude and how you got it? I would really appreciate it. PS: The reason why I took that function is because I wanted to have a speed of 0 at the start and at the end, and wanted a max speed close to 3/4 of $c$. PPS: I originally wanted to use the Lorentz transform, but I was told those cannot be used because of the u-turn in my example. Answer: This calculation is easy if we do it from the perspective of the stationary observer. Suppose I'm sitting on Earth watching you zooming about on your rocket. In my rest frame I identify spacetime points using my coordinates $(t,x,y,z)$ i.e. the time as measured by my clock and the distances measured with my ruler. Let's suppose you're moving along my $x$ axis i.e. directly towards or away from me, as this makes the algebra simpler. Now suppose I observe you to move a distance $dx$ in a time $dt$, then the corresponding elapsed time on your clock, $d\tau$ is given by this equation: $$ c^2d\tau^2 = c^2dt^2 - dx^2 \tag{1} $$ This equation is called the Minkowski metric and it is the equation describing the geometry of flat spacetime. Anyhow, to calculate your elapsed time I note that $dx/dt$ is just your velocity $v$ as measured in my coordinates, so that means $dx=vdt$. If I substitute for $dx$ in equation (1) I get: $$ c^2d\tau^2 = c^2dt^2 - v^2dt^2 $$ And a bit of rearranging gives: $$ d\tau = \sqrt{1 - \frac{v^2}{c^2}}\,dt $$ Your velocity is a function of time, $v(t)$, because you start next to me, accelerate away then stop and head back. And if I know the form of this function $v(t)$ all I have to do is calculate the integral: $$ \tau = \int_0^t \sqrt{1 - \frac{v^2(t)}{c^2}}\,dt \tag{2} $$ And the value $\tau$ is your elapsed time. Note that for any $v \ne 0$ the quantity $1-v^2(t)/c^2 \lt 1$ so when we integrate this we will inevitably find that $\tau \lt t$ i.e. less time has passed for you than for me so you have experienced time dilation. You say in your question that your equation of motion is: $$ x(t)=(3c\sqrt3)t^2(1-t)^2 $$ And I assume the $x$ and $t$ are distance in time in my coordinates since in your rest frame obviously you aren't moving. So just differentiate this equation to get $v(t)$ then substitute it into equation (2) and do the integral. That will tell you how far into the future you have travelled.
{ "domain": "physics.stackexchange", "id": 33585, "tags": "homework-and-exercises, special-relativity, reference-frames, time, time-dilation" }
Dijkstra's Algorithm Same Node Added Multiple Times to Priority Queue
Question: In the this discussion of Dijkstra's Algorithm appear the following comments: # Nodes can get added to the priority queue multiple times. We only # process a vertex the first time we remove it from the priority queue. I'm curious as to under which circumstances a node would be added to the priority queue multiple times. My understanding was that once a node had been processed, it's min-distance was determined and we could forget about it. Here's the full code for reference: import heapq def calculate_distances(graph, starting_vertex): distances = {vertex: float('infinity') for vertex in graph} distances[starting_vertex] = 0 pq = [(0, starting_vertex)] while len(pq) > 0: current_distance, current_vertex = heapq.heappop(pq) # Nodes can get added to the priority queue multiple times. We only # process a vertex the first time we remove it from the priority queue. if current_distance > distances[current_vertex]: continue for neighbor, weight in graph[current_vertex].items(): distance = current_distance + weight # Only consider this new path if it's better than any path we've # already found. if distance < distances[neighbor]: distances[neighbor] = distance heapq.heappush(pq, (distance, neighbor)) return distances example_graph = { 'U': {'V': 2, 'W': 5, 'X': 1}, 'V': {'U': 2, 'X': 2, 'W': 3}, 'W': {'V': 3, 'U': 5, 'X': 3, 'Y': 1, 'Z': 5}, 'X': {'U': 1, 'V': 2, 'W': 3, 'Y': 1}, 'Y': {'X': 1, 'W': 1, 'Z': 1}, 'Z': {'W': 5, 'Y': 1}, } print(calculate_distances(example_graph, 'X')) # => {'U': 1, 'W': 2, 'V': 2, 'Y': 1, 'X': 0, 'Z': 2} Answer: Consider what will happen for the following graph. counterexample_graph = { 'U': {'V': 6, 'W': 7}, 'V': {'X': 10}, 'W': {'X': 1}, } Suppose U is the starting vertex. You can check that vertex X is added to the priority queue by route U -> V -> X, yielding a distance of 16, then by route U -> W -> X, yielding a shorter distance of 8.
{ "domain": "cs.stackexchange", "id": 19071, "tags": "priority-queues, dijkstras-algorithm" }
MO diagram for pentaamminechlorocobalt(III)?
Question: I was considering the MO diagram for [Co(NH3)5Cl]2+, and figured it’d be as follows: 5 sigma interactions from the NH3 ligands; by reducing a reducible representation one obtains 2A1 + B1 + E 2 pi interactions (pi donation from Cl- px and pz orbitals), which have symmetry E And the cation atomic orbitals, which we just read off the character table. Unfortunately this results in a lot of confusing interactions in the MO diagram. What would the MO diagram look like, and are my group orbitals correct? Thanks! Answer: Let's start at the bottom. There will be three a1 bonding orbitals. First, we can have the metal $4s$ orbital interact with all six ligands in phase. Let's call this $1a_1$. Next, the metal $d_{z^2}$ can interact with all six ligands as well, but the axial ligands are now opposite phase from the equatorial. Let's call that $2a_1$. Both will of course have antibonding counterparts. The third $a_1$ orbital is an interaction of the metal $p_z$ with out of phase axial ligand orbitals. The equatorial ligands do not contribute to this orbital because they are on the nodal plane. Let's call this $3a_1$. Mixed in with these a1 orbitals will be the $b_1$ orbital comprised of the equatorial ligand orbitals interacting with $d_{x^2-y^2}$. That will be $1b_1$. It is lower in energy than $3a_1$ but likely higher than $1a_1$ and $2a_1$. (This $1b_1$ and the $2a_1$ correspond to the $1e_g$ orbitals of an $O_h$ complex.) Near $3a_1$ we have the two $e$ orbitals comprised of the metal $p_x$ and $p_y$, each interacting with a pair of equatorial ligands. Let's call these $1e$. (These along with $3a_1$ correspond to the $1t_{1u}$ orbitals of an $O_h$ complex). If we are only considering sigma interactions, we next have the $e$ and $b_1$ orbitals representing metal $d_{xy}$, $d_{xz}$, and $d_{yz}$, all of which are nonbonding for sigma. However, the pi interactions with Cl mean that the $e$ orbitals are stabilized and have antibonding destabilized counterparts. Let's call those $2e$. The $b_1$ orbital ($d_{xy}$) remains nonbonding. Getting the ordering exactly correct is tough in this sort of qualitative analysis, but that should get you a pretty good start.
{ "domain": "chemistry.stackexchange", "id": 11430, "tags": "molecular-orbital-theory" }
Why is the DNA helix anti-parallel?
Question: Why is it that DNA strands are running in anti-parallel fashion? Given the chemical base-pairing, they could have been parallel just as well. Answer: Parallel nucleic acid double strand is possible but it is not as stable as the antiparallel form (Szabat and Kierzek, 2017). This is because the nucleobases are not aligned in a way that is conducive for the Watson-Crick (WC) type base pairing. In parallel conformation, the bases can form Hoogsteen (HS) and reverse Watson-Crick (RWC) type base pairing (see below). You can see that these base pairs are not as strong as that in WC base pairing: No triple bond between G and C in RWC base pairing GC pair occurs in HS base pairing only when C is protonated at low pH Formation of parallel helices, therefore depends on the sequence. In general, the formation of duplexes with parallel strand orientation is determined mostly by the sequence context and pH conditions. Fragments of RNA or DNA capable of forming a parallel duplex are often rich in A and C, which is related to their ability to become protonated, in middle acidic conditions. However, it is not as simple as RNA/DNA base pairing with its complement. Parallel helices would not follow the WC base pairing rules and therefore predicting whether they will form is not that straightforward. However, parallel helices can form in vivo (see references 23–25 of Szabat and Kierzek, 2017). You can also check out this article by Leontis et al. (2002) for hydrogen bond patterns in parallel and antiparallel helices.
{ "domain": "biology.stackexchange", "id": 4401, "tags": "biochemistry, molecular-biology, dna, structural-biology" }
How can I dynamically get the coordinate of a model from gazebo?
Question: I'm using Gazebo/ROS with TurtleBot. My robot needs to find the distance from itself to all the obstacles that exist in the environment. I believe Laserscan has this information, but I am not sure how can I get the position of the models from Gazebo and reuse them in ROS with rospy. Can someone help me with some examples/tutorials? Originally posted by Turtle on ROS Answers with karma: 41 on 2017-03-27 Post score: 2 Answer: The Gazebo ROS interface is designed to simulate the interface that the robot would see in the real world as closely as possible. The generic goal is that the robot software should not know the difference between the real world and the simulated world. Because of that the position of all obstacles is not made available from the simulator. You can use tools like laser scanners to make estimates of the observable obstacles. This is one of the fundamental elements of robotics to build a model of the world around the robot to allow it to operate. There are many different approaches for different application areas. Some are more mature like 2D navigation or plain object recognition If you really want all the obstacles with ground trute from the simulator you need to write a plugin and give it a ROS interface. To make that happen please read through some of the Gazebo Tutorials on that topic. Originally posted by tfoote with karma: 58457 on 2017-03-27 This answer was ACCEPTED on the original site Post score: 0 Original comments Comment by Turtle on 2017-03-28: Thank you for the answer! You say I can "use tools like laser scanners to make estimates of the observable obstacles". I have searched about this but have not found a good solution yet. Do you have any code examples about how I can use laser scanner for this problem?
{ "domain": "robotics.stackexchange", "id": 27439, "tags": "ros, gazebo, pose, turtlebot, rospy" }
Solve this mole fraction calculation with incomplete information
Question: I am currently trying to solve a problem that seems quite simple at the beginning but the complexity reveals itself soon thereafter. The problem is the following: You mix a known mass of water with a known mass of ethanol. Then you fill up the flask to the 50 mL mark with water, but cannot weigh the contents when you're done. What is the molar fraction of ethanol in this mixture? My attempt at solving this problem is to basically calculate the initial molar fraction, and then stepwise add small virtual amounts of water. Then the new molar fraction is calculated, and somehow the excess volume (which is negative for the water-ethanol mixture) would also be included somewhere here. This is repeated until the final volume is reached. An other attempt would be to simply neglect the excess volume. While this might be fine at the edges of the molar fractions, it would introduce a grave error towards the middle. Or is the error still negligible? Are these reasonable attempts or am I completely missing something here? Answer: I don't think you can solve that unless you know additional information like mass of water added or volume of water added, or the density of the final solution. You could approximate by dividing mass of ethanol by density of ethanol to get volume of ethanol, and saying volume of water added is 50mL-(volume ethanol), but this is only an approximation because volumes are not additive when the two solutions are different. The error could be estimated from this graph: source: http://en.wikipedia.org/wiki/Partial_molar_property or the data from the graph could be used to improve the accuracy of the answer or use this density table: http://www.handymath.com/cgi-bin/ethanolwater3.cgi?submit=Entry
{ "domain": "chemistry.stackexchange", "id": 2814, "tags": "experimental-chemistry, solutions" }
Is colour the conserved charge of global $SU(3)$ color symmetry?
Question: Consider the Lagrangian consisting of three Dirac fields $$ \mathcal{L} = \sum_{a=1}^3 \bar{\psi}_a ( i \gamma^\mu \partial_\mu - m ) \psi_a$$ where $a$ is an internal index labelling the colour degree of freedom. This is symmetric under global $SU(3)$ transformations $$ \psi(x) \rightarrow U \psi(x)$$ where $U \in SU(3)$ is a unitary matrix that acts only on the colour indices. Applying Noether's theorem to this will give me a set of eight conserved charges. However, the Cartan subalgebra is two-dimensional so I can label my eigenstates with only two charges. My question Now I would expect that this means that an $SU(3)$ invariant system has two conserved charges. However, I have come across quite a few contradicting answers here: I have read here that I can also combine this symmetry with the $U(1)$ symmetry to get a set of three conserved charges that commute. Under a change of basis, these three charges can be interpreted as the three colours. On the other hand, this answer says that there are no conserved charges for $SU(3)$! Finally, this answer suggests says that there are two charges (which I would expect) but within the 2D charge space, we can define three colours. I am quite confused by these contradicting answers. Why do some people state that $SU(3)$ charges are colour (or at least related to colour), whilst others say there is no conserved charge? Answer: There is no contradiction in the three answers you are citing, just loose language. Only the third answer deals with your spare globally symmetric Lagrangian. The other two deal with QCD, its gauged (local) extension, involving gluons, which most texts write down: it involves an extra fermion bilinear/ gluon linear term, and a kinetic term for the gluons. It too is also globally, beyond being locally invariant, but the first two answers fuss the analog Noether's theorem for gauge theories which the preamble to your question excludes. Noether's (first) theorem deals with the eight Lie-algebraic generators $F^\alpha, ~~~~\alpha=1,2,...,8$, which you may think of as eight linearly independent 3×3 matrices acting on the three a labels of the states you wrote down. (I assume you are not interested in the specific basis thereof, etc.), $$ \psi_a\to \Bigl (\exp (i\theta^\alpha F_\alpha)\Bigr )_{ab} \psi_b . $$ Summation over repeated indices is implied. There is one "color rotation angle" parameter $\theta^\alpha$ for each of the eight generators written. For infinitesimally small such, the generic increment of the 3-spinors your wrote down is $$ \delta \psi_a = i\theta^\alpha (F_\alpha)_{ab} \psi_b. $$ These yield eight "color charges" through Noether's (first) theorem, $$ Q^\alpha =i\int\!\! dx~~ \bar \psi_a (F^\alpha)_{ab} \gamma_0\psi_b, $$ which you evidently checked are on-shell (~through the application of the equations of motion) time-conserved. Commuting these eight charges with the 3-spinors yields the above $\delta \psi$ increments. Indeed, the two charges corresponding to the two Cartan generators, together with the Baryon charge, $\propto i\int\!\! dx~~ \bar \psi_a \gamma_0\psi_a$, also commuting with those, suffice to uniquely specify the independent components of each triplet $\psi_a$, some people call r,g,b for convenience. So: three colors, eight independent rotations thereof (conserved charges). If/when you add gluon gauge fields, which transform among themselves through 8×8 (not 3×3) matrices, the expanded Lagrangian (QCD) is also globally SU(3) invariant, but through the magic of the gauge construction, it is, in addition, locally (gauge) invariant an issue outside the ambit of your question, if not your confusion. The way the 8 Lie algebra generators and corresponding color charges compose among themselves (commutation) is best described through two roots, corresponding to two Cartan generators; you may think about them as commutator motions among these 8 charges. So, in a way, your three questions harmonize, after all: it's just that they describe three different aspects of the elephant to the three blind men touching three different parts of her... Clarification for comment question: Yes it does, only up to language. Algebraically, flavor SU(3) and color SU(3) are identical, so one uses labels and matrices of the two interchangeably, trusting the reader cannot be confused. Since the same generators are involved, one automatically maps the three diagonal matrices' $\lambda_8; \lambda_3; {\mathbb I}$ diagonals, suitably normalized, to the state vectors $r=(1,0,0); g=(0,1,0); b=(0,0,1)$, virtually a change of basis. The idea is people learn their SU(3) from flavor (the eightfold way), and then instantly translate to color. As generators, they are conserved charges (the baryon number is the identity in that space of triplets), but not all conserved color charges.
{ "domain": "physics.stackexchange", "id": 97431, "tags": "conservation-laws, quantum-chromodynamics, noethers-theorem, confinement, color-charge" }
What is the mathematical relationship between parent and child frame in tf?
Question: I am very confused by the coordinate frame in this tutorial. In this command line syntax rosrun tf static_transform_publisher x y z yaw pitch roll frame_id child_frame_id period_in_ms Does the value x y z yaw pitch roll represents the transform from child_frame_id to frame_id? Or the other way around? And what is the relationship between frame_id and child_frame_id? What is the order of the yaw pitch row in the transformation? Which one is the correct relationship? Extrinsic rotation (occurs about the axes of the fixed coordinate system): child_frame_id = R(yaw) * R(pitch) * R(roll) * frame_id + [x,y,z] child_frame_id = R(roll) * R(pitch) * R(yaw) * frame_id + [x,y,z] Intrinsic rotation (occurs about the axes of a coordinate system XYZ attached to a moving body): child_frame_id = frame_id * R(yaw) * R(pitch) * R(roll) + [x,y,z] child_frame_id = frame_id * R(roll) * R(pitch) * R(yaw) + [x,y,z] Originally posted by ignite on ROS Answers with karma: 77 on 2019-12-02 Post score: 4 Answer: I think the documentation makes this pretty clear, see below. http://wiki.ros.org/tf/Overview/Transformations http://wiki.ros.org/Papers/TePRA2013_Foote?action=AttachFile&do=view&target=TePRA2013_Foote.pdf Originally posted by stevemacenski with karma: 8272 on 2019-12-02 This answer was ACCEPTED on the original site Post score: -1 Original comments Comment by ignite on 2019-12-02: Thanks for pointing to the document. But could you please (in question 2) let me know which one is the correct mathematical formula? I don't think the document is very clear on what is child. I mean, the tf is the transform from child_frame_id to frame_if? Or the other way around? Comment by ignite on 2019-12-02: Also, is the roll, pitch, yaw in this syntax intrinsic rotation or extrinsic rotation? Comment by stevemacenski on 2019-12-02: I believe you can do the leg work yourself to find out :-) its all there for you Comment by ignite on 2019-12-02: @stevemacenski I am trying to do it myself right now. But I was just hoping that someone who is an expert like you can point it out; that is the reason I ask to ROS community here. Also, I don't think the document is very clear, especially about rotation (Euler & quaternion) conventions. (I'm quite sure I will ramp up once I'm familar with ROS convention.) But to newcomers like me, perhaps, in my humble opinion, it would be much easier if we write down the mathematical equations in the document; because the math would say it all.
{ "domain": "robotics.stackexchange", "id": 34080, "tags": "ros, transform, ros-kinetic, tf2" }
Culling strings from a list that are substrings of other list elements
Question: I'm bothered by my answer to this SO question. I'm pretty sure it's more efficient than the sort-and-cull implementations, but I'm having trouble expressing that in a way that I trust. Also, it's rather convoluted by python standards. Is there a way to express the same process more clearly, without pages of comments? The problem statement: Given a subject list of strings, make a list containing every element of the subject that isn't a substring of a different element of the subject. Original Current solution: from itertools import groupby from operator import itemgetter from typing import Dict, Generator, Iterable, List, Union # Exploded is a recursive data type representing a culled list of strings as a tree of character-by-character common prefixes. The leaves are the non-common suffixes. Exploded = None Exploded = Dict[str, Union[Exploded, str]] def explode(subject:typing.Iterable[str])->Exploded: heads_to_tails = dict() for s in subject: if s: head = s[0] tail = s[1:] if head in heads_to_tails: heads_to_tails[head].append(tail) else: heads_to_tails[head] = [tail] return { h: prune_or_follow(t) for (h, t) in heads_to_tails.items() } def prune_or_follow(tails: List[str]) -> Union[Exploded, str]: if 1 < len(tails): return explode(tails) else: #we just assume it's not empty. return tails[0] def implode(e: Exploded) -> Generator[str, None, None]: for (head, continued) in e.items(): if isinstance(continued, str): yield head + continued else: for tail in implode(continued): yield head + tail def cull(subject: List[str]) -> List[str]: return list(implode(explode(subject))) print(cull(['a','ab','ac','add'])) print(cull([ 'a boy ran' , 'green apples are worse' , 'a boy ran towards the mill' , ' this is another sentence ' , 'a boy ran towards the mill and fell'])) print(cull(['a', 'ab', 'ac', 'b', 'add'])) I know that it works for the two three test cases. Answer: All in all this looks good already. A few tips: continue If you change the test in explode from if s: to if not s: continue You can save a level of indentation for the rest of the loop collections.defaultdict checking whether a key is in a dict, and adding it if it isn't is why there is collections.defaultdict which can simplify explode a lot: def explode(subject: Iterable[str]) -> Exploded: heads_to_tails = defaultdict(list) for s in subject: if not s: continue heads_to_tails[s[0]].append(s[1:]) return {h: prune_or_follow(t) for (h, t) in heads_to_tails.items()} tuple unpacking A matter of style, but in most situations where you use my_list[0] and my_list[1:], you can use tuple unpacking. You can use this in prune_or_follow def prune_or_follow(tails: List[str]) -> Union[Exploded, str]: start, *rest = tails if rest: return explode(tails) else: return start Whether this is more clear is a matter of taste. This tuple unpacking does not work as clean in explode because it converts the string into a list of 1-character strings. Exploded You can use a string in typing so you can do: Exploded = Dict[str, Union["Exploded", str]] without the Exploded = None cull typing cull can accept any iterable. For the result, I don't think the order of strings is important, so there is no need to limit you to a list. The signature can then be def cull(subject: Iterable[str]) -> Collection[str]:. Whether you return a list or a set is a matter of implementation. If the result is just used for iteration, you can even forgo the list call, and just return the implode generator, and let the caller decide whether he needs in in a list, set or whatever data structure he wants. implode now you use e as argument name. One-letter variable names are unclear in general, and to be avoided most of the time*. Since it is a kind of a tree, I would change this variable. A slightly different take in implode which doesn't use string concatenation but tuple unpacking: def implode(tree: Exploded, previous=()) -> Generator[str, None, None]: for root, branches in tree.items(): if isinstance(branches, str): yield "".join((*previous, root, *branches)) else: yield from implode(branches, *previous, root) or equivalently: def implode(tree: Exploded, previous=()) -> Generator[str, None, None]: for root, branches in tree.items(): if isinstance(branches, str): yield "".join((*previous, root, *branches)) else: yield from implode(branches, (*previous, root)) The choice between your version and this is a matter of taste, but I wanted to present the different possibilities. Another variation, is using try-except ArgumentError instead of the isinstance: def implode_except(tree: Exploded, previous=()) -> Generator[str, None, None]: for root, branches in tree.items(): try: yield from implode(branches, (*previous, root)) except AttributeError: yield "".join((*previous, root, *branches)) '* I find i, j etc acceptable for a counter or index, and x and y for coordinates, but in general I try not to use one-letter variable names.
{ "domain": "codereview.stackexchange", "id": 35073, "tags": "python, algorithm, python-3.x, strings, cyclomatic-complexity" }
Where is the exomoon? (Possible discovery of a companion to Kepler-1625b)
Question: The new paper in Science Advances Evidence for a large exomoon orbiting Kepler-1625b (open access!) uses a sophisticated combination of occultation light curve simulation, signal processing and statistical analysis to show that there is a significant chance that they have identified an exomoon, a moon orbiting an exoplanet. But it's too sophisticated for me to understand how this Hubble data indicates a potential moon. Terms like "detrending", "Markov chain Monte Carlo", and "Bayesian evidences" are beyond me. Is it possible to choose one of those plots and add an arrow to say "this blip here, this is Kepler-1625b potential moon"? If not, is it possible to at least explain in a simple way what it is from this analysis that has led them to believe there may be a moon there? Abstract: Exomoons are the natural satellites of planets orbiting stars outside our solar system, of which there are currently no confirmed examples. We present new observations of a candidate exomoon associated with Kepler-1625b using the Hubble Space Telescope to validate or refute the moon’s presence. We find evidence in favor of the moon hypothesis, based on timing deviations and a flux decrement from the star consistent with a large transiting exomoon. Self-consistent photodynamical modeling suggests that the planet is likely several Jupiter masses, while the exomoon has a mass and radius similar to Neptune. Since our inference is dominated by a single but highly precise Hubble epoch, we advocate for future monitoring of the system to check model predictions and confirm repetition of the moon-like signal. Answer: "Detrending" refers to removing systematic effects that are caused by the spacecraft, detector or the environment and which are not part of the particular star. The systematic trends can be caused by a large variety of things; the main ones affecting Kepler are drifts in position and focus, thruster firings to compensate for angular momentum build up in the reaction wheels and the roll of the spacecraft every quarter. Because these trends are systematic and affect all the stars that Kepler sees in a similar way, the effects can be modeled and the trends removed - detrending. There are some examples in slide 15 and 16 of this Kepler workshop presentation which shows the "raw" brightness measurements (labeled 'SAP') and the detrended data on the right (labeled 'PDC'). You can see examples of this in the Supplementary Materials. On page 47 in Figure S2, you can see the data before detrending and you can see the dips caused by the transiting exoplanet (Kepler-1625b) but these are superimposed on long-term upwards or downwards slopes or curves. Detrending removes these effects (which will be common to all the stars, not just to Kepler-1625b's star) allowing you to get corrected flat light curves, enabling the search for the much smaller exomoon signal. The evidence for the exomoon is in two parts. The timing of the planet transit that was observed by HST in October 2017 was 77.8 minutes early compared to the predicted time from the Kepler transits. This is shown (but not very well) in Figure S12 in the Supplementary Materials. If there was no exomoon or anything else tugging on Kepler-1625b, we would have expected the HST transit (the data point at transit epoch 7) to be on the extended black prediction line at an O-C value (y axis) of +77.8 minutes, ( off the top of their plot as it scaled). The second piece of evidence is that is if the transit is early, then they should expect to see the shallower/smaller transit of the exomoon after the transit as it would be on the other side of the orbit with the exoplanet. This is what they show in the bottom half of Figure 4; no matter which detrending method they use for the HST data, they see a small shallow dip after the main transit is over, centered around a time (x value) of 3056.25. This gives more confidence that the exomoon interpretation is real and not an artifact of the detrending process. What they are saying after Table 1 is that the Δχ2 (the measure of the change in the goodness of fit of the model as you add extra things to the model) is better with the moon models (models Z and M) over one that just accounts for the transit timing variations (model T). This is because the presence of the exomoon is predicted to cause changes in the length and depth of the exoplanet transit but these are harder to measure than the change in timing.
{ "domain": "astronomy.stackexchange", "id": 3217, "tags": "exoplanet, hubble-telescope" }
Go Quiz exercise, part of Gophercises
Question: This is the first exercise from https://gophercises.com/. Basically the idea is to parse a CSV file in a form of 'question:answer' and count the number of correct answers. Also you have a time out range in which you must finish it. I would appreciate any comments, good or bad :) Thanks a lot ! package main import ( "encoding/csv" "os" "fmt" "flag" "time" ) const Ready = "yes" var correctAnswers int func getFileContent(filename string) (records[][] string, err error) { fd, err := os.Open(filename) if err != nil { exit("Problem with opening the file") } reader := csv.NewReader(fd) return reader.ReadAll() } func outputResult(totalQuestions, correctAnswers int) { fmt.Println("Number of total questions:", totalQuestions) fmt.Println("Number of corrected answers:", correctAnswers) } func exit(message string) { fmt.Println(message) os.Exit(3) } func provideQuestions(questions[][] string, done chan bool) { for index, value := range questions { question, answer := value[0], value[1] fmt.Println("Question N:=", index+1, "=>", question) var userAnswer string fmt.Scanf("%s", &userAnswer) if userAnswer == answer { correctAnswers ++ } } done <- true } func main() { fileName := flag.String("name of csv file", "problems.csv", "The name of the csv file - default to 'problems.csv'") allowedTime := flag.Int("allowed time", 10, "The duration in seconds for which the quizz must be finished.") flag.Parse() var readyToStart string fmt.Println("Type 'yes' if you are ready to start") fmt.Scanf("%s", &readyToStart) if readyToStart != Ready { fmt.Println("Come back later if you are ready") os.Exit(0) } records, err := getFileContent(*fileName) if err != nil { exit("Reader problem.") } done := make(chan bool) timer := time.NewTimer(time.Duration(*allowedTime) * time.Second) go provideQuestions(records, done) select { case <- done: fmt.Println("Great job") fmt.Println("You finished with all questions.") case <- timer.C: fmt.Println("Time expired") } outputResult(len(records), correctAnswers) } Answer: Your function returns error, but actually you don't return it and exit in the function body when opening the file: func getFileContent(filename string) (records[][] string, err error) { fd, err := os.Open(filename) if err != nil { exit("Problem with opening the file") } reader := csv.NewReader(fd) return reader.ReadAll() } From the point of error handling it will be more consistent to return error: fd, err := os.Open(filename) if err != nil { return nil, err } The file was open, but not closed: defer fd.Close(). I don't remember flag package, but if it is not ensure the presence of parameter you need to check filename != nil: records, err := getFileContent(*fileName) Here you have created new goroutine, but returns the result via global variable correctAnswers: done := make(chan bool) go provideQuestions(records, done) It stops working if you decide to improve your game and allow more than one person to play on the same time. You will have race condition on this variable. Much better return the value from goroutine using channel. You already have such channel - done, just change its type to channel of int and return the number of correct answers using it.
{ "domain": "codereview.stackexchange", "id": 39344, "tags": "csv, go" }
NNDSVD to initialize Convex-NMF
Question: I'm working with the Convex Nonnegative Matrix Factorization Algorithm described in Ding, Li, Jordan 2008 ("Convex and Semi-Nonnegative Matrix Factorizations"). Good initialization strategies make all the difference and using the described k-means clustering to get started works very well. But there is a paper describing NNDSVD (Boutsidis, Gallopoulos, 2007) to initialize "traditional" NMF Algos. I wanted to test this, to see if it improves my results. The nonnegativity constraints for Convex-NMF are relaxed. X can have mixed sign data, where X ~ XWG', with factors W and G having only positive data. I've implemented NNDSVD just like in the paper (in C++ w/ OpenCV), but since X has mixed sign data, the resulting W contains negative values as well. Has anyone tried to adapt this initialization strategy? Are there any other recommended initialization strategies for Convex-NMF, aside from the ones mentioned in the Ding et al Paper (and random init)? Answer: I've played before with a library for ("classic") NMF from University of Vienna: libNMF While it wasn't useful for me at first, since they don't implement Convex-NMF, I had a look at their NNDSVD implementation. They simply replace all negative values and values smaller than the machine epsilon with zero. I tried that, but it fails, since the update rules for Convex-NMF are such that I get a division by zero. Since they add 0.2 to all values in their proposed initialization scheme (for "smoothing"), I just did the same here. It works, the precision is worse than expected (a bit worse than k-means, which is my best approach for now), but I'll tweak it a bit more.
{ "domain": "datascience.stackexchange", "id": 832, "tags": "machine-learning, clustering" }
Frequency and amplitude for the three gravitational wave events at LIGO
Question: I was reading LIGO/VIRGO's article Binary Black Hole Mergers in the First Advanced LIGO Observing Run, and have two questions concerning the frequencies and the amplitudes of the three gravitational wave events. The question arises from figure 1 in the article: As far as I understand, the y-axis shows the strain (which corresponds to the amplitude of the GW). The x-axis left is the frequency of the modulation, and right it is the time. On the right image (and explained in the GW articles), one sees that the gravitational wave increases both in frequency and amplitude before the merger. Therefore I would expect in the left image, that the indicated amplitude-frequency bands for the three events increase with increasing frequency. However, it shows that the strain of the bands decreases with increasing frequency. Why is that so? All three events seem to be significantly above noise even below 30Hz, as one can see from the left plot. In my naive picture, for GW150914 that could lead to a much longer signal. Why do they analyse the waves only above 30Hz (right)? Answer: Good question, had me wondering also. But it's relatively straightforward. On your question 1 the left graph is total power (or really square root of that to simply plot amplitude, and on a strain scale) at each frequency. It includes all the power of the signal at that frequency, even if it was at different times. The waveforms spent more time (more cycles), at lower frequencies, that's why it looks that way -- the power at the lower energies integrated power for a longer period of time. It That's the problem with freq/ampl graphs, a freq may include longer periods of time. For instance, in the last detection for GW 151226 the lower frequencies around 30 Hz went on (yes, slowly increasing) for about a second or so. They explain it, in the quote below from the pdf of the paper, in the next paragraph after Fig. 1 (bold italization is mine for the relevant sentence). You really would like to see a 3D plot, with freq and time in two axis, and amplitude the z axis, you could then see the chirp as a ridge int he time freq plane as in the figure below from Matlab at https://www.mathworks.com/help/signal/examples/practical-introduction-to-time-frequency-analysis.html?requestedDomain=www.mathworks.com From the pdf you referred us to, at http://journals.aps.org/prx/pdf/10.1103/PhysRevX.6.041015 "The amplitude of the signal is maximum at the merger, after which it decays rapidly as the final black hole rings down to equilibrium. In the frequency domain, the amplitude decreases with frequency during inspiral, as the signal spends a greater number of cycles at lower frequencies. This is followed by a slower falloff during merger and then a steep decrease during the ringdown. On your second question, no GW150914 has about an SNR of 0 dB at 20 Hz, and better at 30 Hz (at 30 it looks like about 3x$10^{-22}$ at 30, just sort of reading off the graph), so SNR of about $3^2$ or about 10 dB, so just detectable. At 20 Hz it was too low. They will extend the lower limit in later runs I understand.
{ "domain": "physics.stackexchange", "id": 36843, "tags": "gravity, gravitational-waves, ligo" }
What is the pressure difference between capillaries and the outside air?
Question: Why exactly do we bleed? There is a pressure gradient that causes the blood to flow from the capillaries to the outside of the skin. What is this pressure difference? The pressure inside the capillaries is at most 35 torr. The atmospheric pressure is 760 torr, which seems strange;how are we able to bleed at all. Is the gas compressible whereas blood is not and is this contributing to this phenomenon? Are my numbers wrong? How do I work with these two values? I'm working on a simulation where I need the pressure of the capillaries which are underneath the skin and the pressure outside the skin. Answer: Your value of $35$ torr (which is sometimes called the gauge pressure) is the excess pressure over atmospheric pressure i.e. The absolute blood pressure is $760+35= 795$ torr.
{ "domain": "physics.stackexchange", "id": 38152, "tags": "fluid-dynamics, pressure, computational-physics, rheology" }
Will a pulsating electron beam passing through a copper pipe induce eddy currents within the copper pipe?
Question: If a pulsating electron beam is beamed down the center of a copper pipe, so as to not make any physical contact with the pipe, the beam should create a pulsating magnetic field that will not change in direction yet will change in strength. This pulsating magnetic field should thus create eddy currents in the pipe that are equivalent in terms of eddy currents to a field that changes direction. Therefore, the induced eddy currents in the copper pipe should oppose/resist the flow of the electrons as they travel through the copper pipe and induction heating will occur. If so, then I believe that a pulsating electron beam can be used to melt and weld two copper pipes together in perhaps a very short time especially if it is a high powered electron beam. Answer: The efficiency of the process would be important in any practical application. An induction forge can be used to weld steel bars together, but it uses rapidly changing current in a coil to induce eddy currents in the steel bars. A pulsating electron beam would produce an RF magnetic field, which would not penetrate deeply into, e.g., copper. Much more efficient, I suspect, is direct electron beam welding, in which the electron beam directly impinges on the workpiece, thereby delivering almost all of its energy to a small spot. Note that for any metal like copper that oxidizes easily, it's important to use flux, inert gas, or a vacuum to exclude oxygen from the site of the weld.
{ "domain": "physics.stackexchange", "id": 51035, "tags": "electromagnetism, magnetic-fields, electromagnetic-induction, induction" }
How to name the following compound?
Question: I know that when both carboxylic acid and ester group are present then the carboxylic acid takes priority and ester is treated as side chain . It is denoted by prefix alkoxy carbonyl. But the arrangement is different in the given figure. The ester group is attached with single bonded oxygen connected to main chain .Please explain how to name such compounds. Answer to given problem is option d. The IUPAC name of the following compound is: (a) 1-Acetoxy acetic acid (b) 2-Acetoxy acetic acid (c) 2-Ethanoyloxy acetic acid (d) 2-Ethanoyloxyacetic acid Answer: You have already found out that the carboxylic acid group is the principal characteristic group. Therefore, the ester group has to be expressed as a prefix. The corresponding rule in Nomenclature of Organic Chemistry – IUPAC Recommendations and Preferred Names 2013 (Blue Book)) reads as follows. P-65.6.3.2.3 Esters cited as prefixes When, in an ester with the general structure $\ce{R-CO-O-R'}$ or $\ce{R-S(O)_x-O-R'}$, another group is present that has priority for citation as the principal group or when all ester groups cannot be described by the methods prescribed for naming esters, an ester group is indicated by prefixes as ‘acyloxy’ for the group $\ce{R-CO-O-{}}$, and ‘alkyloxy(alkanyl)…oxo’ or ‘alkyl(alkanyl)oxycarbonyl’ for the group $\ce{-CO-OR'}$. In this case, the ester group has the form $\ce{R-CO-O-{}}$, which is expressed as a prefix of the form ‘acyloxy’. Note that some acyl groups that are derived from carboxylic acids have retained names used as preferred IUPAC names. In this case, the preferred prefix for the acyl group $\ce{CH3-CO-{}}$ is the retained name acetyl rather than the systematic name ethanoyl. The preferred name for the corresponding acyloxy group $\ce{CH3-CO-O-{}}$ is acetyloxy. Also note that the name acetyloxy is preferred to the contracted name acetoxy that may be used in general nomenclature. The prefix acetyloxy is a compound substituent group. It consists of a simple substituent group (oxy) to which is attached one more simple substituent group (acetyl). Parentheses are used around such compound prefixes. Therefore, the complete name for the compound that is given in the question is (acetyloxy)acetic acid. Note that locants are omitted for parent compounds when all substitutable hydrogen atoms have the same locant. Therefore, the preferred IUPAC name is (acetyloxy)acetic acid and not 2-(acetyloxy)acetic acid.
{ "domain": "chemistry.stackexchange", "id": 13214, "tags": "nomenclature" }
Reference frame for the Cosmic Neutrino Background
Question: It is well known that there exists a reference frame where the total momentum of the Cosmic Microwave Background is zero (a basic fact of special relativity applied to a collection of massless particles) and the radiation is homogeneous and isotropic. This can be observed in the dipole anisotropy. Neutrinos also decoupled from matter shortly after the Big Bang, and therefore relic neutrinos must form a Cosmic Neutrino Background ($\mathrm{C}\nu\mathrm{B}$). These neutrinos are extremely hard, if not impossible, to detect with current technology. The $\mathrm{C}\nu\mathrm{B}$ also defines a reference frame of zero total momentum. Is it expected that this reference frame is coincident with that of CMB? Answer: As is discussed in this answer, the "rest frame" of the cosmic neutrino background would be very similar to that defined by the cosmic microwave background if neutrinos were very light (say $<0.1$ eV). The Sun would be moving with respect to this frame at around 370 km/s. But if neutrinos were more massive(say getting on for 1-2 eV) then they are expected to be very non-relativistic with speeds comparable to the escape speed of the Milky Way. In those circumstances they will cluster around the Milky Way and would have a rest frame that was more similar to that of the Milky Way galaxy itself - i.e. they would be orbiting around the Galaxy and the Sun would move on average at about 220 km/s with respect to the average neutrino. At present neutrino rest masses are probably somewhere between these extremes and so the cosmic neutrino background is thought to have a small dipole anisotropy that will be somewhat offset with respect to that of the cosmic microwave background. By that I mean that if you subtracted off the dipole anisotropy implied by the CMB you would still be left with an anisotropy in the C$\nu$B.
{ "domain": "physics.stackexchange", "id": 32377, "tags": "cosmology, reference-frames, neutrinos, cosmic-microwave-background" }
Transparent cubes in RViz
Question: Hello. I would like to visualize a cube in order to make visible only the edges of the cube the inner area to not be filled with any color. Thank you. Originally posted by szokei on ROS Answers with karma: 80 on 2011-08-22 Post score: 0 Answer: I don't know how/if the rviz cube markers can be displayed as wireframe, but you can use rviz line markers and add the 12 lines/cube. If it's not too many it shouldn't be a performance problem. Originally posted by dornhege with karma: 31395 on 2011-08-23 This answer was ACCEPTED on the original site Post score: 3
{ "domain": "robotics.stackexchange", "id": 6489, "tags": "rviz" }
When a spring is held from one end and some mass is put on the other end and it's rotated then why does it get stretched?
Question: While going through a question I found that if we hold a spring from one end and rotate it then it gets stretched. One explanation may be that centrifugal force is acting on it...but if I want to analyse it, taking ground as reference frame then What can be the explanation of it getting stretched. I mean what force is acting on it? Answer: Suppose you are watching a mass move in the ground frame and that mass is not attached to a spring. Then the mass is going to move in a straight line at constant speed in accordance with Newton's first law. To make the mass move in a curve you have to apply a force to it to deflect it away from the straight line, and that force has to be exerted by the spring because the spring is the only thing interacting with the mass. That means the spring has to be extended because it only exerts a force when it is extended. This applies to any shape of curve, including the complicated trajectories described in Motion of a mass attached to a rotating spring. Circular motion is a special case because here the force that you need to apply to the mass to deflect it is constant and is always normal to the velocity vector.
{ "domain": "physics.stackexchange", "id": 90383, "tags": "newtonian-mechanics, forces, reference-frames, free-body-diagram, spring" }
Connect sensors to beaglebone/arduino in a complex robot
Question: I'm building the biggest robot I've ever done. The hardware I have so far is as follows: HCR-Platform from DFRobot as a base x2 12V 146Rpm DC motor with two phase hall encoder x7 Sharp 2Y0A21 IR sensors x6 URM37 ultrasonic sensor x4 IR ground sensor Microsoft Kinect Right now I'm only using a RoMeo board (arduino 328 compatible) to drive the motors and process the PIDs for the wheels + steering and also access to all the sensors (except for the kinect). I have a BeagleBone Black running linux that is intended to be the main brain connected to the RoMeo using the RS232 port and do the processing of the Kinect + wifi access. I started thinking about connecting the sensors to the Beagle board directly so I don't need to waste time sending commands to the arduino board to read the sensors and that yielded the first issue, beagle board works on 3.3V instead of 5V used on the sensors. After this I thought to create a board with voltage divisors to connect the sensors there and then using a ribbon cable to connect this new board to the beaglebone. I couldn't find any 2x23 IDC male connector to create the "interface cable" between the two boards so the beaglebone option is out as I don't want to have tons of jumper cables all over the place. This morning I thought about all this again and I researched about GPIO boards over USB and found three from Numato, only one works on TTL 5V and has 8 pins so I would need a few of them to use all the sensors so unless I design my own board this option is out too. At this point I'm quite confused in terms of what's the best hardware I could use to drive this beast. Right now I think I should use a Intel NUC with linux for the Kinect, wifi and usb link to a custom made sensor board. This custom made board will work on TTL 5V, provide a power bus for the sensors and will interface all the "low level" sensors using USB as link. I also thought about an FPGA for the custom board but I'm not sure if this would help me or if it's worth the effort of learning how to use it. What are your thoughts on this? Any idea on how this issues are solved on "complex" robots? Answer: You're right to see this as a problem of complexity. Whatever setup you decide to use, keep in mind that you will inevitably have to troubleshoot it. It's already going to be complex -- but make it work in your favor. In other words, let's say that you choose to make a subassembly for your sensors (like arduino + sensors, or GPIO board + sensors). Make sure that this subassembly is completely self-contained: it can read all the sensor values, and without being connected to the beaglebone it can tell you whether all sensors are being reported properly. What you don't want to do is make it so that the entire system has to be connected in order to check the low-level sensors. As you compare options, figure out which options will support a modular system design and which options won't.
{ "domain": "robotics.stackexchange", "id": 369, "tags": "arduino, mobile-robot, sensors, computer-vision, beagle-bone" }
About pressure formula
Question: Pressure is defined as the force per unit area applied to an object in a direction perpendicular to the surface. Why doesn't pressure depend on the properties of the material exposed to the force ? So pressure depends on the area of the material but why not also on the properties of that material? Assuming we had the same area but for different materials , then the strength of pressure will be definitely different for both. So the formula of pressure should contain a parameter concerning other properties of a material , for example its density ? Answer: The way that objects respond to external pressure is dependent on material properties. The pressure you apply does not.
{ "domain": "physics.stackexchange", "id": 47196, "tags": "pressure, material-science" }
Elastic scattering of x rays in 3D: the principle for XRD analysis
Question: I have some trouble visualising scattering of x-rays in 3D, since all textbooks and examples present it in 2D. Under I will share some reflections (no pun intended) about the elastic scattering of x rays, and the diffraction effects observed, which is the basis of XRD analysis. Here you see a figure of two crystal planes, separated by the distance d. Two parallel and in-phase x-rays hit an atom in the planes. The scattering cones are drawn. The darker area represents those scattering directions going into the crystal itself, and thus not detectable and uninteresting for XRD analysis. The light area are those scattered rays exiting the crystal. Thinking in three dimensions is different from thinking in one dimension. To achieve constructive interference, the rays must travel in the same direction and also be superimposed on each other. Even though the scattered rays ' angle is, say, 45 degrees, they may not travel in the same direction. However, if Bragg's law is valid for 45 degrees, all rays of 45 degrees scattering angle will interfere constructively. So we would get a diffraction cone of increased intensity. However, we cannot detect the whole diffraction cone, partly because some of the rays travel into the crystal, and partly because the detector surface area only covers parts of the diffraction cone; we would measure a curved segment of the diffraction cone. This is called the Debye-Scherrer ring, yes? Though we get constructive interference in all directions of 45 degrees scattering angle, the scattering angle itself is random. This means there are scattered rays which do not undergo constructive interference in all directions, regardless of angle (though smaller angles are more probable). So, in an ocean of random scattering, we have diffraction cones of much greater intensity, since Bragg's law is fulfilled. Is this a correct assessment of the XRD situation? Answer: In 3D you will see spots not cones from a single crystal. If you Google for "XRD spot pattern" images, you will probably find yourself enlightened about how many different shapes, and forms diffraction patterns can take. Debye-Scherrer rings are one special case which occurs when you have a diffraction pattern from a very fine powder. In such a powder you are summing the diffraction patterns from thousands to millions of individual crystallites. In this case, you can imagine a large number of spot patterns rotated randomly around the beam axis so each spot projects into a cone. Each individual crystallite, however will produce a spot pattern, and there is never anything but a spot pattern from a single crystallite. (Sometimes spots can be smeared when there is strain in the crystal, or when the crystal is too small to produce high quality diffraction, but these are really cases of imperfect crystals.) You can see diffractions from rays transmitted through the crystal. However, X-rays tend to be absorbed within a few microns to millimeters in most materials so that limits the size of crystal you can use for transmission X-ray diffraction. Finally, I noticed you said "Two parallel and in-phase x-rays..." I just want to note that diffraction occurs with a single photon. A single photon can scatter, and produce constructive/destructive interference with ITSELF. You need to do this with many photons to see a full interference pattern, however, and this is usually the case in experimental situations. If this is new to you, then take a look at Young's double slit experiment. Hopefully this clarifies things a bit.
{ "domain": "chemistry.stackexchange", "id": 2674, "tags": "physical-chemistry, theoretical-chemistry, x-ray-diffraction" }
Requirements for ability to reproduce
Question: In my (albeit basic) biology classes in the past, we've learned about how, to reproduce, two organisms must have the same number of chromosomes. This has been verified by a few other websites I found. So- I've heard about various genetic disorders in which people can have fewer or more chromosomes than usual. For example, if a person had tetrasomy, they would have two extra chromosomes (48 in total). Chimpanzees also have 48. Therefore: If, hypothetically, a person with tetrasomy and a chimp's sex cells were combined, would it create anything? If not, what are the other requirements for creating a baby organism besides the parents having the same number of chromosomes? Answer: The ability to produce offspring has more to do with the compatibility of the chromosomes than the number. This is why hybrid species (such as mules) are able to survive (but are infertile). If you want to learn about why hybrids are infertile here is stackexchange question about. Although, this would all be dependent on weather gametogenesis could occur with the tetrasomy. But as seen here with Down syndrome, it can be successful.
{ "domain": "biology.stackexchange", "id": 8559, "tags": "reproduction" }
How is the most basic display driven?
Question: I am curious how taking the most basic display such as this OLED one that works with the ardunio is driven: i.e. We are using just a clock and data line to drive a 128x64 pixel display. The pixels containing the OLEDs with TFTs are arranged in a cross-hatch design, but what is the link between them? There are probably shift-registers to cut down on the number of pins, correct? Any guidance is helpful, thanks. Answer: Pretty much every display is multiplexed. Typically each column is turned on (pulled to positive supply, for example) in turn and the rows for the pixels to be turned on in that column are switched to the opposite polarity (pulled to negative supply in this example). Usually the sequence happens at high speed so that there is no noticeable flicker. For very small displays the rows and columns can be driven by the microcontroller. For larger displays this would require too many pins on the controller so the data to be displayed is somehow shifted in serially and shift-registers and latches hold the data within the display. This can have an advantage for displays that change relatively infrequently because the microcontroller can send the data to the display and then forget about it while it gets on with more important stuff. Meanwhile the display can continuously refresh based on the last data it received. We are using just a clock and data line to drive a 128 × 64 pixel display. The simplest implementation of this display would require 128 + 64 pins to drive it. Obviously this is not possible on an Arduino. The pixels containing the OLEDs with TFTs are arranged in a cross-hatch design, but what is the link between them? There are probably shift-registers to cut down on the number of pins, correct? Correct.
{ "domain": "engineering.stackexchange", "id": 3174, "tags": "electrical-engineering, computer-engineering" }
What advantages do birds gain when they mimic other bird species calls in the wild?
Question: I've read that birds such as crows and blue jays often mimic other bird species calls. There seems to be evidence that birds do learn and react to other bird species calls, specifically when they relate to danger. What I'm curious about is what advantages do birds gain when they imitate other species calls? Answer: There are a number of reasons birds will mimic other birds mostly for deception, but not always. Impressing a mate: Songs are a large part of bird courtship behavior, and a more varied song that includes different mimicked tones can help attract a better mate. Because mimicked tones are learned, a bird with more vocal variety is demonstrating its intelligence, ability to survive, and other characteristics a mate would find desirable. Safeguarding Food: Using a hawk or owl call, or the sound of a cat, dog, or other predator, is an effective way for a bird mimic to claim a food source. When it utters such a call, birds monopolizing feeders or nearby bushes, trees, or other feeding spots may scatter, letting the mimic take advantage of a less crowded food source. Defending Territory: Songs are crucial for many birds to claim territory, and adding mimicked tones into the song can demonstrate the resident bird's strength. Extra sounds may also trick other interested birds into believing that there are far more birds in the region than there actually are. The newcomers may then simply move along rather than challenge the resident mimic bird. Social Acceptance: Baby birds learn many songs from their families and other birds of their species, and if mimicked sounds are included, young birds will learn them as part of their initial repertoire. This helps birds fit in with their flocks, which will also help them eventually defend their own territories and attract mates. Many pet birds that mimic speech are doing so for social acceptance, as they consider humans to be their flock.Bird to bird mimicry I have personal experience with one of these where a Blue Jay would come to our feeder imitating the screech of a hawk and all the other birds would scatter so he/her had the feeder to themselves.
{ "domain": "biology.stackexchange", "id": 8718, "tags": "ornithology, behaviour, zoology" }
Is there any work done on topic agnostic binary topic classification?
Question: In the recent preprint paper Tree-based Focused Web Crawling with Reinforcement Learning a new model is introduced to classify web pages called KwBiLSTM. The input to this model is a featurized webpage which, later in the forward pass, is concatenated with a featurized version of a list of keywords. Together, these features are passed to the classification layer, which determines whether the webpage and the keywords correspond to the same topic (label 1 or 0). From literature research I could not find any other work using this novel approach, namely that the topic being classified is supplied as an argument, rather than learned explicitly by providing a set of webpages labeled for a certain topic. My question is: Are there other works using a similar topic-agnostic binary topic classifier? Answer: I realized the problem can be solved as such: Given a target text and a list of keywords, embed both using a sentence embedding model (such as MiniLM-L6-v2 from HuggingFace). The embeddings can then be compared using a similarity measure and classification can be done using a threshold value. This approach is topic agnostic, since the list of key terms can be changed for any topic that needs to be found.
{ "domain": "ai.stackexchange", "id": 3488, "tags": "reference-request, papers, model-request" }
Making list of errors from file
Question: So I have a file of errors, there default meanings and also it's hierarchy in terms of indentation BaseException General for all errors of any and every kind. SystemExit Called for when the system wants to exit. KeyboardInterrupt Called when an operator interrupts an action. GeneratorExit Called when the system requests a generator exit. Exception General for all non-exit errors. StopIteration Called when an iterator ended unexpectedly. StopAsyncIteration Called when an asynchronous iterator ended unexpectedly. ArithmeticError General for arithmetic errors. FloatingPointError Called when interpreting a float failed. OverflowError Called when the result was too large to be represented. ZeroDivisionError Called when dividing by zero. Contrary to belief, it does not blow up the entire system. Atleast- not all the time. AssertionError Called when an assertion fails. And I have then converted it all into a list of tuples, with a searcher function along with it such that error("ArithmeticError"), error("007") and error(7) all return [ 1, "007", "ArithmeticError", "General for arithmetic errors.", [ 0, "004", "Exception", "General for all non-exit errors.", [ 0, "000", "BaseException", "General for all errors of any and every kind." ], ] ] Which is the data from before in the format [ indentation (number of spaces before words), code (line it is on), name (first word), default reason (all words but the first), [ parents indentation parents code parents name parents default reason parents parent (if it exists) [ ] All errors will have a parent apart from BaseException (000) This is the code I have done for it, but I feel like there is a more effecient method. import os,builtlins def r(p,b="default"): #r("cache/errors.log") returns path_to_project_root_folder/cache/errors.logs b,p=b.replace("\\","/"),p.replace("\\","/");p=p if p.startswith("/") else f"/{p}" return ((resourcepath if b=="default" else (b[:len(b)-1] if p.startswith("/") and b.endswith("/") else b))+(p[:len(p)-1] if p.endswith("/") else p)).replace("/","\\").replace("\\\\","\\") resourcepath=os.getcwd()[:os.getcwd().find("Ancilla Project")+len("Ancilla Project")] errors=[[r[0],r[1],r[2][:r[2].find(" ")],r[2][r[2].find(" ")+1:]] for r in[(len(e[:len(e)-len(e.lstrip())]),f"{'0'*(3-len(str(i)))}{i}",e[len(e)-len(e.lstrip()):],) for i,e in enumerate(open(r("cache/errors.log")).read().split("\n"))]] def error(q,obj=False): a=[e for e in errors if (f"{'0'*(3-len(str(q)))}{q}" if isinstance(q,int) else q)==e[1 if isinstance(q,int) else 2]];return ((a[0] if a else None) if not obj else ({**globals(),**vars(builtins)}[a[0][2]] if a else None)) for i,e in enumerate(errors): errors[i]=([(*e,(*errors[int(e[1])-x-1],int(e[1])-x-1)) for x in range(0,int(e[1])) if errors[int(e[1])-x-1][0]<e[0]] if e[0]!=0 else [(*e,(*error("BaseException"),)),] if e[2]!="BaseException" else [(*e,),])[0];e=errors[i] If any more information or clarity is needed I will try my best to give them. And yeah, i know that the amount of PEP violation (whichever one is for python 3.8.6) is so high that it'd collapse under its own gravity and become a blackhole- so some help on that would be appreciated Answer: Small Things Spelling error, builtlins -> builtins. Removed commented out code you don't use, adds unnecessary clutter. Spaces before and after operators (+-*/=). PEP-8 Stuff Line length should not exceed 79 characters. Imports should usually be on separate lines. Whitespace in Expressions and Statements. Use Meaningful Names Almost all of your variables are one character long. As someone looking at your code for the first time, it was very hard to determine what types of variables these are. p and b as parameters? What types are passed? These should be named accordingly to what you assign to them. Space Out Your Code It's nearly impossible, at least for me, to read your code the way you posted it. As you pointed out in a comment, "I hate having to scroll down on the python interpreter...", I edited your code using my editor and it could still fit on the entire page without scrolling. Now you may be using a smaller screen, so I'll give you the benefit of the doubt. However, I write my code enveloped around one principle: Write code that others can understand. Having a huge clump of code, while it still does what you want, will be extremely messy. It will be difficult to debug this program should something not work while you test it.
{ "domain": "codereview.stackexchange", "id": 42312, "tags": "python, python-3.x" }
efficiently minimizing quasiconvex function
Question: The problem is as follows: given black box access to a strictly quasiconvex (or unimodal) function $f$ on an interval, say [0, 1], query $f$ repeatedly at various points to find a subinterval containing the minimum. After $n$ queries to $f$, if the interval's length is reduced by a factor of $t$, the algorithm's score is $\sqrt[n]{t}$, which is the amortized factor by which each query to $f$ reduces the length of the interval. For example, standard ternary search starts with $f(0)$ and $f(1)$, additionally queries $f(\frac{1}{3})$ and $f(\frac{2}{3})$, and obtains a subinterval with size $\frac{2}{3}$. It then iterates and each subsequent iteration starts with $f$ evaluated at the endpoints of the subinterval and reduces the subinterval's length by a factor of $\frac{2}{3}$. Thus the score is $\sqrt{\frac{2}{3}}$. A better ternary search instead queries at $\frac{1}{2}-\varepsilon$ and $\frac{1}{2}+\varepsilon$ and iterates for a score of $\sqrt{\frac{1}{2}+\varepsilon}$. An even better algorithm is "pentanary search", starting with $f(0)$, $f(\frac{1}{2})$, and $f(1)$ and querying $f(\frac{1}{4})$ and $f(\frac{3}{4})$ to obtain a subinterval that is the first, middle, or last half of $[0, 1]$. It then iterates. The key is that 3 points from each iteration can be used in the next. Thus the score is $\sqrt{\frac{1}{2}}$. The best I know of, "golden search", starts with $f(0)$, $f(1)$, and either $f(1-\frac{1}{\phi})$ or $f(\frac{1}{\phi})$, querying for the other of those two, where $\phi$ is the golden ratio. The subinterval is either $[0, \frac{1}{\phi}]$ or $[1-\frac{1}{\phi}, 1]$ and 3 values from the previous iteration can be reused, achieving a score of $\frac{1}{\phi}$. Can we do better than "golden search"? Do we know the optimal score for this problem? Answer: Avriel and Wilde, in their article Optimality proof for the symmetric Fibonacci search technique, showed that Fibonacci search is optimal in the following sense: if you want to bracket the minimum in an interval of length $\delta$ using at most $k$ evaluations, then Fibonacci search maximizes the length of your initial interval.
{ "domain": "cs.stackexchange", "id": 14563, "tags": "algorithms, search-algorithms" }
Project Euler # 15 Lattice paths in Python
Question: Starting in the top left corner of a 2×2 grid, and only being able to move to the right and down, there are exactly 6 routes to the bottom right corner. How many such routes are there through a 20×20 grid? from time import time from functools import lru_cache def make_grid(grid_size): """Return a list of lists containing grid.""" grid = tuple((0,) * (grid_size + 1) for _ in range(grid_size + 1)) return grid @lru_cache(None) def count_lattice_paths(matrix, row, column): """Return number of all possible paths from top left to bottom right of n * n grid.""" if row == 0 or column == 0: return 1 return count_lattice_paths(matrix, row - 1, column) + count_lattice_paths(matrix, row, column - 1) if __name__ == '__main__': start_time = time() g = make_grid(20) length = len(g) - 1 print(count_lattice_paths(g, length, length)) print(f'Time: {time() - start_time} seconds.') Answer: Performance Counter When you use time.time(), you are getting the number of seconds since January 1, 1970, 00:00:00 UTC. This value is (as I'm writing this) around 1565401846.889736 ... so has about microsecond resolution. When you use time.perf_counter(), you are getting "a clock with the highest available resolution to measure a short duration". As I was writing this, I retrieved the value 53.149949335 ... so it has approximately nanosecond resolution. For profiling code, you want the highest resolution timer at your disposal ... so eschew time.time() in favour of time.perf_counter(). Timed Decorator Since you are doing a lot of performance measurements in your exploration of Project Euler, you should package up the performance measurement code in a neat little package that can be easily reused. You were given a decorator for this in an answer to your "Time & Space of Python Containers" question. But here it is again, slightly modified for just doing timing: from time import perf_counter from functools import wraps def timed(func): @wraps(func) def wrapper(*args, **kwargs): start = perf_counter() result = func(*args, **kwargs) end = perf_counter() print(f"{func.__name__}: {end-start:.6f} seconds") return result return wrapper You can decorate a function with @timed, and it will report how long that function takes. You can even decorate multiple functions! And it moves the timing code out of your if __name__ == '__main__': block. Use Test Cases Project Euler 15 gives you the answer to a 2x2 lattice grid. You should run that test case in your code, to give yourself confidence you are getting the correct answer. Eg) @timed def count_lattice_paths(rows, cols): # ... def pe15(rows, cols): paths = count_lattice_paths(rows, cols) print(f"{rows} x {cols} = {paths} paths") if __name__ == '__main__': pe15(2, 2) pe15(20, 20) A few import points. The if __name__ == '__main__': block clearly runs two cases a 2x2 lattice, and a 20x20 lattice. The pe15(rows, cols) calls count_lattice_paths(rows, cols) to get the result, and then prints out the result with a description of the case. The count_lattice_paths(rows, cols) is the @timed function, so the time spent printing the result report in not counted in the timing. The count_lattice_paths() method can be generalized to work with an NxM lattice; it doesn't need to be square, even though the problem asked for the result for a square lattice and gives a square lattice test case. Count Lattice Paths (without a cache) As you noticed, a 2x2 lattice is better represented by a 3x3 grid of nodes. It should be obvious there is only 1 way to reach every node along the top edge. It should be obvious there is only 1 way to reach every node along the left edge. So, our initial array of counts would look like: 1 1 1 1 . . 1 . . At each node (other than the top edge and left edge), the number of paths is equal to the sum of the paths to the node above it and the paths to the node to the left of it. So, there are 1+1 = 2 paths to the node at 1,1: 1 1 1 1 2 . 1 . . Since the value at each point is defined entirely by the values above and left of it, we can directly loop over each node, and compute the required values, and finally return the value at the lower right corner of the grid. We don't even need to store the entire grid; we can compute the next row from the current row. @timed def count_lattice_paths(rows, cols): steps = [1] * (cols + 1) for _ in range(rows): for i in range(cols): steps[i+1] += steps[i] return steps[-1]
{ "domain": "codereview.stackexchange", "id": 35659, "tags": "python, performance, beginner, python-3.x, programming-challenge" }
How does increase in volume change the speed of reaction in production of NO2?
Question: $$\ce{2 NO + O2 <=> 2 NO2}$$ I understand that increasing the volume $×2$ means lower pressure so production of $\ce{NO2}$ is slowed down, but when asked how to express this mathematicaly I can't get to the correct value, which is either $4$ or $8.$ I don't see how inserting $1/2$ in $v = Δc/(2×Δt)$ can give anything close to the offered solutions. Answer: I'm not an expert but this is how I would do it. Determine the reaction rate formula from the reaction equation $$r = K[\ce{NO}]^2[\ce{O2}]$$ Changing the volume by a factor $2$ means the concentration of $\ce{NO}$ and $\ce{O2}$ will become half $$r' = K\cdot\frac{[\ce{NO}]}{2}^2\cdot\frac{[\ce{O2}]}{2}$$ Compare the reaction rates $$r' = K[\ce{NO}]^2\cdot\frac{1}{4}\cdot [\ce{O2}]\cdot\frac{1}{2}$$ $$\frac{r}{r'} = \frac{K[\ce{NO}]^2[\ce{O2}]}{K[\ce{NO}]^2[\ce{O2}]\cdot\frac{1}{8}} = 8$$ Conclusion: increasing the volume by $2$ will decrease the concentration (or pressure) of $\ce{NO}$ and $\ce{O2}.$ This causes the reaction rate to decrease by a factor of $8$.
{ "domain": "chemistry.stackexchange", "id": 12082, "tags": "physical-chemistry, thermodynamics, equilibrium" }
Why does the low entropy at the big bang require an explanation? (cosmological arrow of time)
Question: I have read Sean Carrol's book. I have listened to Roger Penrose talk on "Before the Big Bang". Both are offering to explain the mystery of low entropy, highly ordered state, at the Big Bang. Since the second law of thermodynamics is considered a fundamental law of nature, and since it states that in a closed system entropy either must stay the same or increase, the entropy at the time of the Big Bang must have been much lower than it is now. Also, the thermodynamic arrow was explained by Boltzmann in 1896 embodied in $S = k\ln W$ which was inscribed on his tombstone. $W$ is the number of distinct microstates of the system. It seems to me that trivially this number will be less in the past than in the future since entropy obeys the 2nd law. This determines the thermodynamic arrow of time. Why do we need more explanation of a "fundamental law"? Answer: This is somewhat controversial issue. But let me present the reasons, as far as I understood, why people like Sir Penrose thinks so. Their arguments are roughly as follows: The basic microscopic laws of physics are perfectly time symmetric. They are not biased in any time direction past or future. Second law follows from the fact that that given an initial condition of a system which is not in the most probable state will tend to go towards the most probable state by the same microscopic laws. Since number of disordered states are much higher the system will become more and more disordered with time. Accordingly its entropy will increase until a maximum value when the system comes to the thermal equilibrium. Since the microscopic laws are time symmetric the same argument can be made towards the past time direction as well. Given an an initial condition of a system which is not in the most probable state should go towards more disordered (high entropy) states towards past as well. That's what the mathematics of the laws tells us. This is against our experience. Either all the parts of the universe we are observing (including our memories of past) has just undergone a HUGE fluctuation right now to give the impression that there was a more ordered past (which is crazy) OR the system was already even more ordered (low entropy) and more special in the past. But that means even more huge a fluctuation. This reasoning will lead us to conclude that at the moment of big bang the universe was extra ordinarily ordered and most special. It should be so special that it requires explanation. Critics often point out that prediction and retrodiction is not the same thing forgetting that when one talks about the very "arrow of time" no one can say with justification which is prediction and which is retrodiction. Other than that it is also questionable whether second law can be applied this way to the whole universe or not.
{ "domain": "physics.stackexchange", "id": 370, "tags": "thermodynamics, cosmology, entropy, big-bang, arrow-of-time" }
Momentum in time independent schrodinger equation
Question: In the time independent Schrödinger equation I have read that the wave function is $$\psi(x)=\mathrm e^{-iEt/\hbar}$$ This means that $$\rho(x,t)=|\psi(x,t)|^2=|\psi(x)|^2=ρ(x)$$, that is, $\rho$ is not a function of $t$. That's why it is called stationary state. Therefore, $$\left<x\right>=\int \psi^*x\,\psi \mathrm{d}x=\int \psi(x)^*x\,\psi(x) \mathrm{d}x=\text{constant}$$ and hence $$\left<p\right>=0$$ , the average value of momentum is zero. What does this mean? Does this mean particle is in rest? I think this is something like probability of going in one direction is equal to the probability of going in opposite direction, like $MV-MV =0$. Is this sense right? Or something else is happening? Answer: Your reasoning in the OP is correct, except when you say that the particle is at rest. Recall that in QM the exact position of a particle, and its state of motion, are not well defined. This means that it doesn't make sense to say that a particle is at rest. You could only say that a particle is at rest if $$ \Delta p\equiv 0 $$ but, because of the Heisenberg uncertainty principle, $\Delta p$ is always positive. On the other hand, the correct statement is that it has an equal probability to be moving to the right and to be moving to the left, and thus, on average, its mean velocity is zero. You observed this in the OP, and this is the correct interpretation of $\langle p\rangle=0$.
{ "domain": "physics.stackexchange", "id": 36727, "tags": "quantum-mechanics, momentum, wavefunction, schroedinger-equation" }
What's the difference between a stream and a queue?
Question: What's the difference between a stream and a queue? They both have the concept of an ordered set of elements, but tend to have different implementations and a different vocabulary of 'insert'/'extract' (streams) vs. 'enqueue'/'dequeue' (queue). Are these interchangable? Do they suggest different concepts or patterns? If so, what are the differences? Concrete example of 'stream insertion': https://www.cplusplus.com/reference/ostream/ostream/operator%3C%3C/ Potentially useful conceptual pieces? Stream as sequence of time-function data: https://web.archive.org/web/20160603162316/https://mitpress.mit.edu/sicp/full-text/sicp/book/node69.html Stream as IO channel: https://en.wikipedia.org/wiki/Standard_streams Answer: A queue is an abstract data type with two operations: enqueue() and dequeue() (or sometimes push() and pop()) that have first-in-first-out semantics. A C stream is hard (for me) to describe abstractly. My best cut at it is that it is an abstraction representing a buffered file (where "file" is understood in the Unix sense of the word as something that is usually (but not always) a sequence of bytes and a current file position.) At it's most general a stream is like a sequence of bytes numbered from 0, that can be arbitrarily extended at the end, but that has some additional state (the current position). There are some basic operations (fread() and fwrite()) that read or write an arbitrary number of bytes starting at the current position, and then reset the current position to point just after the most recently read or written byte. The current position can also be changed with fseek() and queried with ftell(). Now here's where it gets "icky." At the time a stream is opened a variety of factors determine which of the above operations are enabled or disabled. If you open your stream only for read then calling fwrite() will cause an error. If you open your stream only for write then calling fread() will cause an error. If your stream is actually a pipe or a socket, or is opened in mode append then you are not allowed to fseek(). You are only allowed to read or write from the current file position. stdin, stdout, and stderr are pipes so you can't fseek() them. You can't fwrite() stdin and you can't fread() stdout or stderr. C++ fixed most of that mess by giving us a hierarchy of types (for example: http://www.cplusplus.com/reference/istream/basic_iostream/), so that we can do error recovery with RAII and can also tell whether the file is readable or writable by looking at the type (although I don't know offhand whether they fixed the seeking mess.) But then there's the whole other question of formatted output. C has fprintf() which formats some stuff and puts some bytes into a writable stream (starting at the current file position). C++ replaced fprintf() with the (IMHO) really-much-too-cute operator<<(). operator<<() has the advantage of being strongly typed, but the extreme disadvantage of requiring the use of manipulators. So operator<<() puts some bytes to the output stream starting at the current file position, but formatted based on a whole bunch of state that is mutated by manipulators. So a C++ stream actually has a bunch of extra state that you need to know about. (Whether integers are going to get formatted hex or decimal from now on, how much precision floats are printed with, etc.) So: a queue inserts and removes individual items of a well defined type from its front or its back. A stream is random access extendable array of bytes where you can read and write arbitrary numbers of bytes from the current file position (except when it isn't random access and except when you either can't read or can't write).
{ "domain": "cs.stackexchange", "id": 17783, "tags": "terminology, data-structures" }
A Generic Approach To Doubly Linked Lists
Question: I've written a small implementation for doubly linked lists. While actually intended to be only used by me in subsequent projects, I wrote it as generically as possible. Maybe this'll be advantageous. I tested the implementation and resolved as many bugs as possible but maybe there are more lurking somewhere in the code. Also, the implementation is supposed to be usable for different lists at the same time but operations cannot be performed on one list simultaneously. I'll have to add a spinlock to the list and alter the code a bit for that. The list works as follows: the first (head) node has the prev field set to NULL, the last (tail) node has the next field set to NULL. A size field counts the number of nodes in the list. If size == 1, prev and next of this lonely node contain NULL and head == tail == node. If size == 0, head and tail are indeterminate. Code Header (dll.h): #ifndef DOUBLY_LINKED_LIST_H #define DOUBLY_LINKED_LIST_H /* When reading through this code, you may encounter functions not being * strictly const-correct. This is because I wanted to make const-correctness * to depict the CONCEPTUAL const-ness, not const-ness due to some random * implementation-detail. */ /* From this implementation's perspective, this is not a pointer to the data * but really the data itsself. */ typedef void* data_t; /* I second that the name "dll" for "doubly-linked list" is ambiguous * with the Windows DLL (Dynamic Link Library) but I don't think this'll * lead to any serious confusion. */ typedef struct dll_node { struct dll_node* prev; struct dll_node* next; data_t data; } dll_node_t; typedef int (*cleanup_op_t)(dll_node_t* node); typedef struct dll { dll_node_t* head; dll_node_t* tail; cleanup_op_t cleanup_op; size_t size; } dll_t; /* Initializes a list with zero nodes. * `list' - The list to initialize * `cleanup_op' - The operation to apply to every datum when it is * removed from the list. This includes the destruction of * the list using `dll_destroy'. */ void dll_init(dll_t* list, cleanup_op_t cleanup_op); /* Data definition with macros - Linux kernel style. C ain't got no * constructors - we use ugly macros to make up for that. AFAIK, GCC does * offer aping constructors using the attribute "constructor" but that's * compiler-specific and therefore not eligible for usage. * Use it if you find it useful. The big fat drawback is that the actually * hidden stuff going on in this macro needs to be exposed for further * operations. Or, when assigning dll_t*'s, you need to know the type too. * That completely defeats the purpose of this macro. * NOTE: LACK OF DO-WHILE LOOP IS ON PURPOSE TO MAKE THE VARIABLE VISIBLE * IN THE OUTER SCOPE! */ #define DEFINE_DLL(identifier, cleanup_op) \ dll_t identifier; \ dll_init(&identifier, (cleanup_op)); /* Destructs the list, that is, all its nodes and the data they contain. * Complexity: O(n) * `list' - The list to destruct */ void dll_destroy(dll_t* list); /* The return value indicates whether the traversing function should continue * or if the required condition has been met. This enables searching for * items in the list and other, crazy stuff the user of this API can think of. */ typedef int (*dll_traverse_op_t)(dll_node_t* node); /* Traverses through a list, starting at the head and going forward to the next * nodes, and performs an operation on every node. * Complexity: O(n) * `list' - The list to traverse through * `op' - The operation to perform */ void dll_traverse(dll_t* list, dll_traverse_op_t op); /* Traverses through a list, starting at the tail and going backward to the * previous nodes, and performs an operation on every node. * Complexity: O(n) * `list' - The list to traverse through * `op' - The operation to perform */ void dll_traverse_rev(dll_t* list, const dll_traverse_op_t op); /* TODO: is it reasonable to return the created node from the dll_add_* and * dll_insert_* functions? Think about that! */ /* TODO: THE BELOW COMMENT SERVES AS A TEMPLATE FOR ALL DOCUMENTING COMMENTS * IN THIS IMPLEMENTATION. FORM THE OTHER ONES WITH THIS ONE HERE IN MIND! */ /* Inserts a node right before another one. * Complexity: O(1) * `list' - The list to insert into * `node' - The node before which to insert the new node * `data' - The data stored by the new node * Notes: * If the list doesn't contain any nodes, a new node is created and added to * the list, INDEPENDENT OF THE VALUE OF `node'. */ dll_node_t* dll_insert_before(dll_t* list, dll_node_t* node, data_t data); /* TODO: THE BELOW COMMENT SERVES AS A TEMPLATE FOR ALL DOCUMENTING COMMENTS * IN THIS IMPLEMENTATION. FORM THE OTHER ONES WITH THIS ONE HERE IN MIND! */ /* Inserts a node right after another one. * Complexity: O(1) * `list' - The list to insert into * `node' - The node after which to insert the new node * `data' - The data stored by the new node * Notes: * If the list doesn't contain any nodes, a new node is created and added to * the list, INDEPENDENT OF THE VALUE OF `node'. */ dll_node_t* dll_insert_after(dll_t* list, dll_node_t* node, data_t data); /* The dll_add_* and dll_insert_* functions are very similar, so I wrote the * actual, generic implementation in the dll_insert_* functions and built * the dll_add_* ones on top of them. * Similarly done with the dll_rm and dll_rm_* functions. */ /* Add a node to the head of the list. * Complexity: O(1) * `list' - The list to prepend the node to * `data' - The data to be stored in the new node */ dll_node_t* dll_add_front(dll_t* list, data_t data); /* Add a node to the tail of the list. * Complexity: O(1) * `list' - The list to append the node to * `data' - The data to be stored in the new node */ dll_node_t* dll_add_back(dll_t* list, data_t data); /* Removes a node. * Complexity: O(1) * `list' - The list to remove the node from * `node' - The node to remove */ void dll_rm(dll_t* list, const dll_node_t* node); /* Remove the node at the head of the list. * Complexity: O(1) * `list' - The list to remove the node from */ void dll_rm_front(dll_t* list); /* Remove the node at the tail of the list. * Complexity: O(1) * `list' - The list to remove the node from */ void dll_rm_back(dll_t* list); #endif Source (dll.c): #include <dll.h> #include <stdlib.h> #include <assert.h> void dll_init(dll_t* list, cleanup_op_t cleanup_op) { assert(list); list->cleanup_op = cleanup_op; list->size = 0; } void dll_destroy(dll_t* list) { assert(list); if (list->size == 0) return; dll_node_t* it = list->head; while (it) { if (list->cleanup_op) /* fare well, branch predictor */ list->cleanup_op(it->data); dll_node_t* tmp = it; it = it->next; free(tmp); } } void dll_traverse(dll_t* list, dll_traverse_op_t op) { assert(list); if (list->size == 0) return; dll_node_t* it = list->head; while (it) { op(it); it = it->next; } } void dll_traverse_rev(dll_t* list, const dll_traverse_op_t op) { if (list->size == 0) return; dll_node_t* it = list->tail; while (it) { op(it); it = it->prev; } } dll_node_t* dll_insert_before(dll_t* list, dll_node_t* node, data_t data) { assert(list); if (list->size == 0) assert(node); dll_node_t* prev_node = list->size == 0 ? NULL : node->prev; dll_node_t* new_node = malloc(sizeof(dll_node_t)); assert(new_node); new_node->data = data; new_node->next = list->size == 0 ? NULL : node; new_node->prev = prev_node; if (list->size == 0) list->head = list->tail = new_node; else { if (node->prev) prev_node->next = new_node; else { assert(node == list->head); list->head = new_node; } node->prev = new_node; } ++(list->size); return new_node; } dll_node_t* dll_insert_after(dll_t* list, dll_node_t* node, data_t data) { assert(list); if (list->size != 0) assert(node); dll_node_t* next_node = list->size == 0 ? NULL : node->next; dll_node_t* new_node = malloc(sizeof(dll_node_t)); assert(new_node); new_node->data = data; new_node->next = next_node; new_node->prev = list->size == 0 ? NULL : node; if (list->size == 0) list->head = list->tail = new_node; else { if (node->next) next_node->prev = new_node; else { assert(node == list->tail); list->tail = new_node; } node->next = new_node; } ++(list->size); return new_node; } dll_node_t* dll_add_front(dll_t* list, data_t data) { return dll_insert_before(list, list->head, data); } dll_node_t* dll_add_back(dll_t* list, data_t data) { return dll_insert_after(list, list->tail, data); } void dll_rm(dll_t* list, const dll_node_t* node) { assert(list); assert(node); assert(list->size != 0); if (list->cleanup_op) list->cleanup_op(node->data); if (node->prev) node->prev->next = node->next; else { assert(node == list->head); list->head = node->next; } if (node->next) node->next->prev = node->prev; else { assert(node == list->tail); list->tail = node->prev; } /* Casting away const-ness is bad but it's just a necessary * implementation detail here. I hope it's not undefined behavior... * in C++, it is, if the object the casted pointer is pointing to is * const, AFAIK. Only if it is non-const but pointed to by a const * pointer casting away const-ness is well-defined. * But I think the rules differ in C. (C != C++!) */ free((dll_node_t*) node); --(list->size); } void dll_rm_front(dll_t* list) { dll_rm(list, list->head); } void dll_rm_back(dll_t* list) { dll_rm(list, list->tail); } Questions A node stores its data in a member of type data_t. Should I replace data_t with void* and use that void* as a generic pointer to data? What do you think? There's a comment on const-correctness in the header file, literally: /* When reading through this code, you may encounter functions not being * strictly const-correct. This is because I wanted to make const-correctness * to depict the CONCEPTUAL const-ness, not const-ness due to some random * implementation-detail. */ Do you agree with me to make functions conceptually const or should I only use const when it's absolutely necessary (and let implementation details shine through)? Are the names dll_t and dll_node_t alright? Or could this be confused with Microsoft's Dynamic Link Libraries? Also, should I change the macro used as a header guard to DLL_H or is it fine as it stands? What do you think of the implementation and the approach? Does it seem usable? Is the code alright? Answer: Data storage If you change your data_t typedef to be anything other than void*, your linked list implementation has to be copied and modified to handle multiple types (so it's less generic); on the other hand, you get better type safety. The tradeoff is probably in how you're going to use it. One thought: I would suggest looking at how the linux kernel does linked lists: they have a list_head struct, which is then included inside the data types that you want to put into a list. So it looks something like (e.g., if you had a linked list of strings): struct list_head { struct list_head *next, *prev; }; struct element { char *s; struct list_head list; }; Then, you have a bunch of linked-list functions which operate on list_head pointers, and use an offsetof macro to get back from the list_head to the enclosing structure. Not to say that this is better, but it's arguably a more type-safe way to get 'generic' linked lists in C. Both approaches are valid, though (and yours is more 'classic'). Const correctness I would generally say that things should be const whenever possible, because it makes programs easier to reason about. I generally encounter the opposite problem to the one you're describing, though: something is conceptually const, but for incidental implementation reasons it needs to be mutable. DLL naming Well, 'dll' isn't the clearest name, because of the conceptual collision with Windows libraries. It probably isn't a big deal unless you're writing software on Windows and using dlls. I would be tempted to just call this module "list", or "ll", though. The only real constraint on the include guard macro is that it not collide with any other names in your program. I suspect that DOUBLY_LINKED_LIST_H is probably fine. (Obviously, if you have some style guide or standard, that probably specifies a convention). Implementation This is pretty nice code overall. If I were feeling picky: Names ending in _t are strictly reserved for the standard, iirc. Struct tags are in a different namespace, so it's totally reasonable to do typedef struct foo {} foo;. I'd be inclined to prefer consistency of bracing at least within a particular control structure (so if () {} else {} rather than if () ; else {} even if one branch has only one statement). I'd be inclined to break section up the files a little with comments---while I'm not a fan of those huge ASCII-art comment headers, I find files easier to read if they have little headers like /* --- type declarations --- */ ... /* --- function declarations --- */ ... /* --- function definitions --- */ Just a little extra stuff to help find your way around the file, and separate things which are conceptually different. It may be that not everyone agrees with me on that, though.
{ "domain": "codereview.stackexchange", "id": 18397, "tags": "c, linked-list, c11" }
Is there an easy way to show that $x^2-t^2=1/g^2$ for a (relativistic) body undergoing acceleration g?
Question: A professor asked me about the (c=1) equation: $$x^2 - t^2 = 1/g^2$$ which I used in a paper. Or with $c$: $$x^2 - (ct)^2 = c^4/g^2.$$ I told him that it was the exact equation of motion for a relativistic particle undergoing a constant acceleration $g$. He had some doubts about the equation. So I went back to my office and derived the equation over again, but it was quite messy. It's such a simple equation. Basically it says that to convert particle motion from Newtonian to relativistic, you have to replace parabolas with hyperbolas. Instead of speeding up indefinitely, the particle speed approaches $\pm c$. Is there a simple or short derivation? Answer: Yes--- this is directly analogous to the following statement from geometry: The plane curve with everywhere constant curvature is the circle. You could prove this by integrating the condition of constant curvature (which is just as messy as in relativity), or by doing an arclength parametrization (which is clean, see below). But easiest of all is to note that rotations around the center take the circle to itself, and every point on the circle transitively to every other point. Since curvature is rotationally invariant, the curvature at all points is the same. Similarly in relativity, the hyperbola $$ x^2-t^2 = R^2 $$ is invariant under boosts, and the boosts act transitively. So you conclude that the curvature is constant. The curvature is the rest-frame acceleration, and the result is that the hyperbola has a constant acceleration. The magnitude of the acceleration can be seen by looking at small t's (since at t=0, the velocity is 0, so relativity reduces to Newton/Galileo) $$ x = \sqrt{ R^2 +t^2} = R + {t^2\over 2R} + ... $$ So that the acceleration a is given by $$ a={1\over R}$$ It's the inverse radius of the Hyperbola, just like the curvature is the inverse radius of a circle in geometry. Arclength parametrization There are many problems in geometry/relativity that are simplified by arclength parametrization. In this parametrization, x(s) and y(s) obey $$\dot{x}^2 + \dot{y}^2 = 1$$ so that, differentiating $$\dot{x}\ddot{x} = - \dot{y}\ddot{y}$$ The curvature is the magnitude of the second derivative $$ \ddot{x}^2 + \ddot{y}^2 = {1\over R^2}$$ and substituting for $\ddot{y}$ using the relation gives $$ (1+ {\dot{x}^2\over\dot{y}^2}) \ddot{x}^2 = {1\over R^2}$$ and simplifying $$ {\ddot{x} \over \sqrt{1-\dot{x}^2}} = {1\over R }$$ This is an ordinary differential equation in $\dot{x}$ which integrates simply to give that x(s) is a sinusoid, and then y(s) is also a sinusoid. $$ {d\over ds}(\sin^{-1}(\dot{x})) = {1\over R} $$ $$ \dot{x}= \sin ({s-s_0\over R}) $$ $$ x - x_0 = R \cos({(s-s_0)\over R}) $$ In relativity, the same manipulations give a differntial equation for x with flipped sign under the square-root, and give the hyperbolic trigonometric functions. Here is an answer where I make use of arclength parametrization for a nontrivial problem, which can't be solved by symmetry: Is there an intuitive reason the brachistochrone and the tautochrone are the same curve? There are probably many fascinating curve-geometry problems in relativity which are analogs of the Brachistochrone and Isochrone, but nobody has ever formulated these. It's not hard to do, but they might not have an immediate physical interpretation. Two definitions of constant acceleration There are two different definitions possible for "constant acceleration". One is that you have a constant acceleration in your rest frame, and this obviously gives the invariant circle-like curve, the hyperbola. The other definition is a particle's motion in a constant E field. $$ {d\over dt} {dx\over d\tau} = E $$ The two definitions look different superficially, but they are the same. This is shown here: Knowing the mass and force acting on a particle, how do we derive the relativistic function for velocity with respect to time? The upshot of the linked argument is that while the $d/dt$ is not the same as $d/d\tau$, there is a geometric projection, the projection is the same hyperbolic trigonometric factor as the one involved in taking the x-component, rather than the component perpendicular to the motion, to define acceleration, so the end result is the same.
{ "domain": "physics.stackexchange", "id": 3517, "tags": "special-relativity, acceleration, relativity" }
How Is It Possible To Measure Extreme Temperatures? (>2 Billion Kelvin)
Question: Linked Article: Record Set for Hottest Temperature on Earth: 3.6 Billion Degrees in Lab Scientists have produced superheated gas exceeding temperatures of 2 billion degrees Kelvin, or 3.6 billion degrees Fahrenheit. This is hotter than the interior of our Sun, which is about 15 million degrees Kelvin, and also hotter than any previous temperature ever achieved on Earth, they say. I don't see how is it possible that these scientists manage to measure two billion Kelvin. Are there such measuring instruments that can measure extremely hot stuff without melting and still get a proper reading, or is it a theoretical deduction? Answer: Fusion is plasma physics, and in plasma physics the temperature is defined by the average kinetic energy of the ions and electrons in the plasma. Therefore the kinetic energy distributions have to be measured and they have developed ingenious methods of doing so. Fitting with the black body radiations curves allows an estimate of the temperature. There are more ingenious methods developed, using Thomson scattering, which allow by scattering light on different ions accurate measurements of temperature. Very high temperatures can be measured for the stars from their black body radiation and the spectral distribution of the light reaching us also.
{ "domain": "physics.stackexchange", "id": 3989, "tags": "temperature, measurements" }
Is this a nymph of a Zelus renardii or Zelus luridus?
Question: My mom found this insect on one of her plants, and she would like to know what it is and whether it is dangerous or harmful. I've done some research and I think it is a nymph of a Zelus renardii, but it could also be a nymph of a Zelus luridus, although the latter is usually found only in North America. Can anyone tell me which one it is, or at least whether it is indeed one of these two? Some more info: It was found in Milan, Italy, a few days ago It was on a geranium, where it can find the larvae of a butterfly called geranium bronze (Cacyreus marshalli) She's also found two more insects like this one on a Pittosporum She has seen it by day The body is mainly light-brown with some yellow and orange spots The legs are also light-brown, with some darker spots that seen from very close are actually spikes (see the last picture) The length of its body is around 1 cm, and it is arched upwards I've uploaded some more pictures here. You can ignore the "Not sharp" folder. In the "Sharp" one (which are mostly not that sharp either, but it's the best I have) there's a cropped picture next to each of the full-size ones. Those that I have attached here are chosen among the cropped ones. Answer: I agree this look like images I've seen of Zelus species nymphs, and I have no reason to immediately rule out Z. renardii. Though, nymphs of many of the Reduviidae look quite similar to me, and I feel like I've never seen a comprehensive guide to thoroughly/methodically distinguishing nymphs (especially from an internet photo). This is made more complicated given that Zelus is one of the most diverse genera in the Reduviidae family, so narrowing to species within the genus is difficult (i.e., time-consuming) for me. (I assume an expert specializing in these insects would know much more than me). The purpose of my post is simply to point out that Zelus renardii has been found in Italy, while I can't find evidence that Z. luridus has. Pinzari et al. (2018) provide a detailed recording of Z. renardii in Italy. They also note that (at least as of 2018), Z. renardii is the only member of this genus found in Europe: The only species of the genus that has been so far re-corded in Europe, is Z. renardii that has been found in Greece (Davranoglou 2011; Petrakis & Moulet 2011; Si-mov et al. 2017) including the island of Crete (van der Heyden 2015), Spain (Vivas 2012), Italy (Dioli 2013b), Turkey (Çerçi & Koçak 2016) and recently Albania (van der Heyden 2017). In Italy, Z. renardii was recorded only twice in the towns of Rome (Dioli 2013b) and Bari (Cor-nara et al. 2016), and never reported anymore. In this note, we add new records for this species in Italy. As you can see above, Dioli (2013) first recorded Z. renardii in Italy in 2013. A quick narrowed map search on inaturalist that focuses solely on the European continent suggests that, as of December 20, 2021, Z. renardii continues to be the only species recorded in Europe. Pinzari, M., Cianferoni, F., Martellos, S. and Dioli, P., 2018. Zelus renardii (Kolenati, 1856), a newly established alien species in Italy (Hemiptera: Reduviidae, Harpactorinae). Fragmenta entomologica, 50(1), pp.31-35. Dioli P. 2013b. Zelus renardii (Kolenati, 1856) (Insecta Heterop-tera Reduviidae). Quaderno di Studi e Notizie di Storia Natu-rale della Romagna, 38(133): 232–233.
{ "domain": "biology.stackexchange", "id": 11760, "tags": "species-identification, zoology, entomology" }
Charge between grounded plates
Question: A few days ago I saw in an article that if we place a positive charge $Q$ between 2 infinite ,parallel and grounded plates, then the sum of the induced charges on the plates has to be equal to $-Q$. I don't know how I could prove this statement using Gauss's law. $ $ Any ideas? Answer: Since the plates are infinite, we won't be able to get a Gauss's surface around them, but, to find the answer to this question, we don't have to. If the distance between the plates is not infinite, we could make the Gauss's surface big enough to achieve any level of accuracy. Since the potential of the plates is zero, there won't be any electric field on their external surfaces and no electric field around or inside the grounding wires (presumably, one wire for each plate). The field between the plates won't be zero, but, if the Gauss's surface is big enough, it could be made as small as we choose. Therefore, the flux through the Gauss's surface could be made as close to zero as we choose. If so, according to the Gauss's law, the charge enclosed inside the surface should be zero as well and, since the known charge between the plates is $Q$, the charge induced into the plates must be $-Q$. Obviously, these charge will be located on the inside surfaces of the plates.
{ "domain": "physics.stackexchange", "id": 49808, "tags": "electrostatics" }
Given a language L how can I derive its Boolean formula?
Question: Let: be given by Compute Boolean formulas for the following: This is part of my coursework; I have the answers but can't understand them. I want to develop some intuition on how I can solve these or a general framework on how I can approach them. Some guidance on resources is also appreciated. And sorry I couldn't figure out how to format it in Latex which worked over here. Answer: I'll just consider $\text{MOD}^1_{0,3}$, the other ones are similar. I'm assuming that you want a boolean formula $\phi$ such that $\text{MOD}^1_{0,3}(x_1, \dots, x_n) = 1 \iff \phi(x_1, \dots, x_n) \text{ is true}$. Note that $\text{MOD}^1_{0,3}(x)$ is true if and only if the number of variables set to $1$ is a multiple of $3$. A first "natural" approach to find a possible $\phi$ is that of explicitly considering all variable assignments with that property and or-ing them together. The resulting formula wold be: $$ \bigvee_{k=0,\dots,\lfloor n/3 \rfloor} \bigvee_{S \in \binom{\{1, \dots, n\}}{3k}} \left(\bigwedge_{i \in S} x_i \wedge \bigwedge_{i \in \{1, \dots, n\} \setminus S} \overline{x}_i \right). $$ While this works, this formula has exponentially many conjunctive clauses, each of which has $n$ literals. A second idea is that of examining one input variable at a time and keeping track of the remainder of the division between the number of true variables encountered so far and $3$. To this aim we introduce $2$ new variables $y_i, z_i$ for each $i = 0,\dots,n$ where if we interpret $y_i z_i$ as a binary number, it will be exactly $\left( \sum_{j=1}^i x_j \right) \bmod 3$. The formula will be a conjunction of sub-formulas. To ensure that $y_0=z_0 = 0$ we can use the sub-formula $\overline{y}_0 \wedge \overline{z}_0$. To correctly compute $y_i$ from $x_i, y_{i-1}, z_{i-1}$ (for $i = 1, \dots, n$) we can can write down a truth table to figure out that $y_i$ should be true if and only if the formula $\mathcal{Y}_i = (\overline{y}_{i-1} \wedge z_{i-1} \wedge x_i) \vee (y_{i-1} \wedge \overline{z}_{i-1} \wedge x_i)$ is true. Using the equivalence between $a \implies b$ and $(\overline{a} \vee b)$ we obtain the sub-formula $(\overline{\mathcal{Y}}_i \vee y_i) \wedge(\mathcal{Y}_i \vee \overline{y}_i)$. To correctly compute $z_i$ from $x_i, y_{i-1}, z_{i-1}$ (for $i = 1, \dots, n$) we can use a similar reasoning to obtain the sub-formula $(\overline{\mathcal{Z}}_i \vee z_i) \wedge(\mathcal{Z}_i \vee \overline{z}_i)$, where $\mathcal{Z}_i = (\overline{y}_{i-1} \wedge \overline{z}_{i-1} \wedge x_i) \vee (\overline{y}_{i-1} \wedge z_{i-1} \wedge \overline{x}_i)$. Finally, we need to check that $y_n$ and $z_n$ encode $0$ (i.e., $\sum_{j=1}^i x_j$ is a multiple of $3$). We can do so by using the sub-formula: $\overline{y}_n \wedge \overline{z}_n$. Notice that, for each $i=0, \dots, n$, we used a constant number of clauses each with constant-many literals. Overall, $\phi$ has $\Theta(n)$ clauses with $\Theta(1)$ literals each.
{ "domain": "cs.stackexchange", "id": 21398, "tags": "complexity-theory, circuits" }
Derive the velocity-additon formula from the Lorentz transformation
Question: In a Euclidian world the sum $s$ of two velocities $v$ and $u$ is so such that $s = v + u$. However, in the world of special relativity that's not the case. Instead, the velcity vector sum $s$ is such that $s = \frac{v + u}{1+vu} \; (c=1)$. I'm trying to deriving it and down below is my work so far. Any hints that would lead me forwards would be great. Consider two inertial reference frames $S$ ("the rest frame") and $S'$ ("the moving frame"). In S' we have a 4-velocity vector $\left(c \frac{d {x^0}'}{d \tau}, \frac{d {x^1}'}{d \tau}, \frac{d {x^2}'}{d \tau}, \frac{d {x^3}'}{d \tau}\right)$. I'm letting ${x^\mu}$ denote $x^\mu$ coordinates in $S$ and ${x^\mu}'$ denote $x^\mu$ coordinates in $S'$. During $d \tau$, a particle with the velocity $\left(c \frac{d {x^0}'}{d \tau}, \frac{d {x^1}'}{d \tau}, \frac{d {x^2}'}{d \tau}, \frac{d {x^3}'}{d \tau}\right)$ travels from $(0, 0, 0, 0)$ to $\left(c d {x^0}', d {x^1}', d {x^2}', d {x^3}'\right)$. To simplify the problem we're now going to assume that the relative velocity of $S'$ (the moving frame") is only in the x-direction, and the same is assumed about the 4-velocity vector in $S'$. Thus it simplifies into the event $\left(c d {x^0}', d {x^1}', 0, 0 \right)$. Now we transform the ${x^0}'$ term into $S$: $x^0 = \gamma(d {x^0}' - v d {x^1}')$ And the same for the ${x^1}'$ term: $x^1 = \gamma (d {x^1}' - v d {x^0}')$ So therefore, in $S$, the event is given by $(\gamma(d {x^0}' - v d {x^1}'), \gamma (d {x^1}' - v d {x^0}'), 0, 0)$ Now, here's my problem. In order to write an expression for the change in distance over time (that's the velocity) in $S$ coordinates, I'll need to know how to transform $d \tau$ into $S$. I already know ${x^1}$ in $S$ in terms of $S'$ coordinates, but I don't know how ${x^0}$ relates to $d \tau$. If I knew that, I could simply take $\frac{d {x^1}}{d {x^0}}$ and get an expression for the velocity in $S$. In other words, I need to know the coordinate of $d \tau$ in $S$. If I was unclear about something, please don't downvote but leave a comment and ask instead and I'll correct any mistakes or unclear formulations. Answer: Since all the velocities are constant working out $\frac{dx^{1}}{dx^{0}}$ is simple division (no calculus required). Note that the entries in your vector in $S$ are the values you're interested in: $$(dx^0, dx^1, 0, 0)=(\gamma(d {x^0}' - v d {x^1}'), \gamma (d {x^1}' - v d {x^0}'), 0, 0)$$. So we have: \begin{equation} \frac{dx^{1}}{dx^{0}} = \frac{d {x^1}' - v d {x^0}'}{d {x^0}' - v d {x^1}'} \end{equation} Dividing the numerator and denominator by $d {x^0}'$ we have: \begin{align} \frac{dx^{1}}{dx^{0}} &= \frac{\frac{d {x^1}'}{d {x^0}'} - v }{1 - v\frac{ d {x^1}'}{d {x^0}'}}\\ &= \frac{u - v }{1 - vu}\\ \end{align} Where the $-$ signs different to the standard formula is because your two velocities are in the same direction. You'd pretty much solved the problem yourself, you just hadn't realised it!
{ "domain": "physics.stackexchange", "id": 24265, "tags": "homework-and-exercises, special-relativity, velocity, inertial-frames, observers" }
If eigenstate for a Hermitian operator are orthonormal why are the energy eigenstates not so?
Question: My Quantum Mechanics notes says: We found the orthonormality relation holds for any Hermitian operator eigenstates: Upon reading this I would assume that this holds for Energy eigenstates too. Then i did a question and looked at the solution and saw the following: u0(ground state) and u1(first exited state) are energy eigenstates of the quantum Harmonic oscillator and so my question is if they are multiplied by one another in the final integral how come it does not go to zero. Any Help would be appreciated. Answer: Because your final integral (the third one) is not the inner product of two states. Basically I mean: \begin{align} \langle u_0|u_1\rangle \equiv \int dx\cdot u_0(x)u_1(x) = 0 \end{align} this is the orthogonality of two states. While: \begin{align} \langle u_0|x|u_1\rangle \equiv \int dx\cdot u_0(x)u_1(x)\cdot x \neq 0 \end{align} since this integral is not the inner product of them at all, but with an extra $x$ in the kernel.
{ "domain": "physics.stackexchange", "id": 45473, "tags": "quantum-mechanics, energy, hilbert-space, harmonic-oscillator, eigenvalue" }
How can the Poles of the Root Locus be negative?
Question: My understanding of drawing a root locus diagram is that stability requires all roots of the characteristic polynomial of the open loop transfer function to lie in the negative real part of the plane. In other words, it must have roots $(s+a)(s+b)...(s+n)$ where $s$ is a negative number. My question is that the Laplace Transform requires that the real part of $s$ be positive, so wouldn't the possibility of negative real parts of $s$ be a contradiction? Thanks. Answer: If the denominator polynomial is given by $$Q(s)=(s-s_0)(s-s_1)\ldots (s-s_{n-1})\tag{1}$$ then the corresponding time domain function is made up of a sum of scaled exponentials of the form $e^{s_it}u(t)$, where $u(t)$ is the unit step function. These terms decay only if $\textrm{Re}\{{s_i}\}<0$, so for stability the zeros of the denominator polynomial (i.e., the poles of the system function) must lie in the left half-plane. Let $h(t)$ be the impulse response of a causal LTI system. The transfer function is the Laplace transform of $h(t)$: $$H(s)=\int_{0}^{\infty}h(t)e^{-st}dt\tag{2}$$ This integral only converges in a region $\textrm{Re}\{s\}>c$ ("region of convergence"), with some real-valued constant $c$. That constant depends on the properties of $h(t)$. If $h(t)$ is a weighted sum of exponentials $e^{s_it}u(t)$ then $c$ equals the most positive real part of the complex numbers $s_i$: $$c=\max_i\big\{\textrm{Re}\{s_i\}\big\}\tag{3}$$ This makes sure that the damping by the term $e^{-st}$ in $(2)$ is enough to make $h(t)e^{-st}$ decay sufficiently such that the integral converges. For stability we require $c<0$, i.e., all poles lie in the left half-plane, and the imaginary axis of the $s$-plane $s=j\omega$ lies inside the region of convergence.
{ "domain": "dsp.stackexchange", "id": 7840, "tags": "continuous-signals, poles-zeros, laplace-transform, stability" }
What are shooting stars and how are they formed?
Question: What are shooting stars? How are they formed and how often do they occur during the night? Also, why are there more shooting stars on some nights than on others? Answer: A shooting star is a rock from space that is entering the atmosphere at such a great speed that the air superheats it to a bright white-hot glow. When one of these rocks is floating around in space, it's called a meteoroid (-oid sounds like some sort of space-y future-y thing: think asteroid, android, humanoid). When it's found in the ground after it's already landed, it's called a meteorite (-ite sounds like a mineral-y rock-type thing you find in the ground: think pyrite, graphite, kryptonite). For the brief period of time between when they are meteoroids and meteorites, they are simply called meteors, a.k.a. shooting stars. (Think: Aaahh! ...look out for that METEOR!)
{ "domain": "astronomy.stackexchange", "id": 52, "tags": "meteor" }
Which chemical properties make a substance explosive?
Question: I know that some chemical substances are used as explosives. Amongst the most famous nitroglycerin in dynamite and cyclonite in C-4. Which chemical properties (I suspect that physical properties have less of an effect) make a substance a good explosive? If we know, for example, the formula and its geometry, is it easy to predict how explosive it can be? Answer: There are, actually, several types of explosives by use: initiating (primary) explosives, secondary explosives and blasting agents. Initiating explosive must be sensitive to shock/friction, but not too sensitive. The most famous primary explosive is mercury fulminate, but others are known. To act as primary explosive, substance must have hi-energetic unstable groups, like peroxides, azides and similar. Secondary explosives are substances, that are not sensitive to shock/friction and requires initiating blast to explode. Unlike primary explosives, they can be manufactured as hi-density blocks with high speed of detonation. It is exactly what is needed for military applications. The most common type of secondary explosives are (substituted) polynitroarenes. Most well-known examples are TNT and picric acid. It is very beneficial to have zero oxygen balance for such explosives, i.e. to explode without extra oxygen produced and without extra reducing gases produced. TNT, for example, has negative oxygen balance, producing much carbon on explosion, and dinitromethane has positive oxygen balance, producing extra oxygen on explosion. A less stable class of secondary explosives is nitroamines, with hexo/octo-gen as most well-known example. Anyway, main variables here are relative stability and high density paired with medium-high energy of explosion. Tertiary explosives or blasting agents are explosives, used to move hight amounts of materials. They are usually used in big amounts in mining/engineering and must be cost-effective and produce much gases in explosion. The most common typeы of blasting agents are oxyliquits and compositions, based on ammonia nitrate. There are also special kinds of explosives/pyrotechnic mixtures. For example, a mixture used in car airbags must produce much gases very quickly, but said gases must have low temperature. If we know, for example, the formula and its geometry - is it easy to predict how explosive it can be? Actually, not that easy. Di/Trinitroarenes are usually explosive, but their stability and performance may vary greatly and depends on crystal structure, density and form (crystals/fine dust/puffy things).
{ "domain": "chemistry.stackexchange", "id": 450, "tags": "reaction-mechanism, theoretical-chemistry, explosives, nitro-compounds" }
Converting Pairwise single- linkage clustering distance data to "newick" format
Question: I have pairwise distance data for single linkage cluster and I would like to convert it to newick format. I was unable to find a conversion algorithm. I require newick format for visualization and annotation of a phylogeny. Here is the output. INFO : ====================================== INFO : Pairwise single linkage clustering INFO : ====================================== INFO : Hierarchical Tree INFO : ====================================== INFO : Node Item 1 Item 2 Distance INFO : 0 : 53 52 0.001 5zxf 5z02 INFO : -1 : 64 60 0.002 7bj6 7bir INFO : -2 : 62 -1 0.002 7biv INFO : -3 : 34 26 0.002 4wt2 4ode INFO : -4 : 65 -2 0.003 7bmg INFO : -5 : 25 13 0.003 4occ 4erf INFO : -6 : 29 -3 0.009 4ogt INFO : -7 : 39 38 0.010 4zyi 4zyf INFO : -8 : 50 48 0.011 5oc8 5ln2 INFO : -9 : 54 -8 0.012 6ggn INFO : -10 : 42 41 0.015 5hmi 5hmh INFO : -11 : -4 61 0.020 7bit INFO : -12 : 70 40 0.028 7qdq 5c5a INFO : -13 : 47 68 0.032 5laz 7na3 INFO : -14 : -9 45 0.035 5law INFO : -15 : 49 59 0.038 5oai 6q9o INFO : -16 : 32 -5 0.039 4qo4 INFO : -17 : -15 8 0.044 3uu1 INFO : -18 : 23 -16 0.047 4oas INFO : -19 : -14 -7 0.053 INFO : -20 : 24 -18 0.057 4oba INFO : -21 : -19 6 0.057 3lbl INFO : -22 : 43 -10 0.058 5hmk INFO : -23 : 44 19 0.059 5lav 4jvr INFO : -24 : -23 -20 0.061 INFO : -25 : -11 15 0.061 4hg7 INFO : -26 : 57 -24 0.062 6q9h INFO : -27 : 27 -6 0.065 4odf INFO : -28 : -25 -17 0.067 INFO : -29 : 14 -28 0.067 4hbm INFO : -30 : -13 -21 0.067 INFO : -31 : -27 -29 0.067 INFO : -32 : -26 -30 0.068 INFO : -33 : 58 21 0.068 6q9l 4mdn INFO : -34 : -31 -32 0.070 INFO : -35 : 17 5 0.071 4jv9 3lbk INFO : -36 : 30 -34 0.074 4ogv INFO : -37 : -33 2 0.077 1t4e INFO : -38 : 35 -36 0.079 4zfi INFO : -39 : 20 -38 0.086 4jwr INFO : -40 : -39 -37 0.094 INFO : -41 : 7 -40 0.106 3tj2 INFO : -42 : 51 -41 0.111 5trf INFO : -43 : 69 -42 0.112 7na4 INFO : -44 : 56 -43 0.113 6q96 INFO : -45 : 4 -44 0.127 3jzk INFO : -46 : 33 -45 0.129 4qoc INFO : -47 : 22 -46 0.137 4mdq INFO : -48 : -12 -47 0.151 INFO : -49 : 37 -48 0.155 4zyc INFO : -50 : 31 -49 0.156 4oq3 INFO : -51 : 12 -50 0.158 4ere INFO : -52 : -22 46 0.161 5lay INFO : -53 : -35 -51 0.182 INFO : -54 : 55 -53 0.186 6i29 INFO : -55 : 10 -54 0.224 3w69 INFO : -56 : 18 -55 0.238 4jve INFO : -57 : 9 -56 0.265 3vzv INFO : -58 : 28 -57 0.271 4ogn INFO : -59 : -58 1 1.000 1rv1 INFO : -60 : 66 -59 1.000 7na1 INFO : -61 : 0 -60 1.000 INFO : -62 : -52 -61 1.000 INFO : -63 : 11 -62 1.000 4dij INFO : -64 : 67 -63 1.000 7na2 INFO : -65 : 16 -64 1.000 4jv7 INFO : -66 : 36 -65 1.000 4zgk INFO : -67 : 3 -66 1.000 2lzg Answer: The problem with the tree format presented is that it does not conform to a known standard. Whilst its possible to write a parser I don't think its a good idea. This output is hierarchical clustering, UPGMA, that sort of thing. Its not phylogenetics because this is a linkage tree. Can you access the distance matrix prior to the clustering? If so the information below the line will help. The output should provide the raw distance matrix prior to hierarchical clustering and will certainly have generated it in the calculation. BTW that particular clustering method isn't cool compared with nj (below) for complex reasons. The calculation will be: Perform pairwise linkage analysis Perform cluster analysis on the resulting matrix You need neighbor-joining to convert the distance matrix into a newick-format. There is no possibility of a direct conversion. If you are using R its in the ape library via treenk <- nj(M) with M is the matrix. The treenk will be a format that can be read straight into ggtree Briefly, a distance matrix requires a clustering algorithm and neighbor-joining is by far the best clustering method developed in phylogenetics. The following is a phylogenetics example ... this is different from the example you have 'cause thats about linkage. data(mynucleotides) tr <- nj(dist.dna(mynucleotides)) plot(tr) I your case the final line will be something like ggtree(tr) ... with various options.
{ "domain": "bioinformatics.stackexchange", "id": 2301, "tags": "phylogenetics, phylogeny, ggtree" }
Why scalar function of vector can only depend on norm of vector?
Question: In Field Quantization by Greiner and Reinhardt as well as The Qunatum Theory of Fields by Weinberg, concerning the spectral function, the authors say a scalar function of the four-vector $p^\mu$ can only depend on $p^2$ and the step function $\theta(p^0)$. More specifically, they argue that $\Sigma_n(2\pi)^3\delta^4(q-p_n)|\langle 0|\phi(0)|n\rangle|^2$ can be expressed as $\rho(q^2)\theta(q_0)$. I cannot understand this statement. For example, $\delta^4(p-p_0)$ (where $p_0$ is some constant 4-vector) is a scalar function on $p$, but in no way can this function only depend on $p^2$ or $\theta(p)$. Can any one explain this to me? Answer: What you want is that your function does not transform under Lorentz transformations that take $$ p^\mu \to {\Lambda^\mu}_\nu p^\nu.$$ To build invariants from one vector there is only the possibility to construct the invariant product with itself $$ p^2 \equiv p^\mu p_\mu \to p^\mu p_\mu.$$ There is one more thing though. The Lorentz group has two branches: Momenta with positive time-like component (i.e. positive energies) will never get boosted to momenta with negative energy, and thus $\theta(p_0)$ also is invariant under Lorentz transformations. Summary: Only $p^2$ is invariant under the full Lorentz group; in addition $\theta(p_0)$ (where $p_0$ is the zero-component and NOT a different four-vector!!) is invariant if one restricts to the Lorentz transformations from one branch (i.e. excludes time reversal operations). Edit: True, $\delta^4(p^\mu - q^\mu)$ is also an invariant function. This can be seen by looking at how it operates on a Lorentz-invariant test function $f(p^2)$: $$ \int \mathrm d^4p \delta^4(p^\mu - q^\mu) f(p^2) = f(q^2)$$ The cheapskate explanation is that since $\mathrm d^4p$ and $f(p^2)$ are invariant, as is $f(q^2)$, so must be $\delta^4(p^\mu - q^\mu)$. But this can be seen more explicitly as well. Let us perform a Lorentz transformation on the left hand side of the above equation: $$\int\mathrm d^4p \delta^4(p^\mu - q^\mu) f(p^2) \to \int \mathrm d^4 p' \delta^4({\Lambda^\mu}_\nu (p^\nu - q^\nu)) f(p^2)$$ Here I already used that the measure picks up a factor of the determinant of the transformation but $\vert \Lambda \vert = 1$ for Lorentz transformations. We can then use that $\delta(\alpha x) = \delta(x) \frac{1}{\vert \alpha \vert}$, which also works for matrices (check that, it's a good excercise!) - where for matrices the $\vert \cdot \vert$ is the determinant. So $\delta^4({\Lambda^\mu}_\nu (p^\nu - q^\nu)) = \frac{1}{\vert \Lambda \vert} \delta^4(p^\nu - q^\nu) = \delta^4(p^\mu - q^\mu)$.
{ "domain": "physics.stackexchange", "id": 17929, "tags": "quantum-field-theory, special-relativity, vectors, invariants" }
Matplotlib-venn and keeping lists of the entries
Question: Having come upon the wonderful little module of matplotlib-venn I've used it for a bit, I'm wondering if there's a nicer way of doing things than what I have done so far. I know that you can use the following lines for a very simple Venn diagram: union = set1.union(set2).union(set3) indicators = ['%d%d%d' % (a in set1, a in set2, a in set3) for a in union] subsets = Counter(indicators) ... but also want to have lists of entries in the various combinations of the three sets. import numpy as np from matplotlib_venn import venn3, venn3_circles from matplotlib import pyplot as plt import pandas as pd # Read data data = pd.read_excel(input_file, sheetname=sheet) # Create three sets of the lists to be compared set_1 = set(data[compare[0]].dropna()) set_2 = set(data[compare[1]].dropna()) set_3 = set(data[compare[2]].dropna()) # Create a third set with all elements of the two lists union = set_1.union(set_2).union(set_3) # Gather names of all elements and list them in groups lists = [[], [], [], [], [], [], []] for gene in union: if (gene in set_1) and (gene not in set_2) and (gene not in set_3): lists[0].append(gene) elif (gene in set_1) and (gene in set_2) and (gene not in set_3): lists[1].append(gene) elif (gene in set_1) and (gene not in set_2) and (gene in set_3): lists[2].append(gene) elif (gene in set_1) and (gene in set_2) and (gene in set_3): lists[3].append(gene) elif (gene not in set_1) and (gene in set_2) and (gene not in set_3): lists[4].append(gene) elif (gene not in set_1) and (gene in set_2) and (gene in set_3): lists[5].append(gene) elif (gene not in set_1) and (gene not in set_2) and (gene in set_3): lists[6].append(gene) # Write gene lists to file ew = pd.ExcelWriter('../Gene lists/Venn lists/' + compare[0] + ' & ' + compare[1] + ' & ' + compare[2] + ' gene lists.xlsx') pd.DataFrame(lists[0], columns=[compare[0]]) \ .to_excel(ew, sheet_name=compare[0], index=False) pd.DataFrame(lists[1], columns=[compare[0] + ' & ' + compare[1]]) \ .to_excel(ew, sheet_name=compare[0] + ' & ' + compare[1], index=False) pd.DataFrame(lists[2], columns=[compare[0] + ' & ' + compare[2]]) \ .to_excel(ew, sheet_name=compare[0] + ' & ' + compare[2], index=False) pd.DataFrame(lists[3], columns=['All']) \ .to_excel(ew, sheet_name='All', index=False) pd.DataFrame(lists[4], columns=[compare[1]]) \ .to_excel(ew, sheet_name=compare[1], index=False) pd.DataFrame(lists[5], columns=[compare[1] + ' & ' + compare[2]]) \ .to_excel(ew, sheet_name=compare[1] + ' & ' + compare[2], index=False) pd.DataFrame(lists[6], columns=[compare[2]]) \ .to_excel(ew, sheet_name=compare[2], index=False) ew.save() # Count the elements in each group subsets = [len(lists[0]), len(lists[4]), len(lists[1]), len(lists[6]), len(lists[2]), len(lists[5]), len(lists[3])] # Basic venn diagram fig = plt.figure(1) ax = fig.add_subplot(1, 1, 1) v = venn3(subsets, (compare[0], compare[1], compare[2]), ax=ax) c = venn3_circles(subsets) # Annotation ax.annotate('Total genes:\n' + str(len(union)), xy=v.get_label_by_id('111').get_position() - np.array([-0.5, 0.05]), xytext=(0,-70), ha='center', textcoords='offset points', bbox=dict(boxstyle='round,pad=0.5', fc='gray', alpha=0.3)) # Title plt.title(compare[0] + ' & ' + compare[1] + ' & ' + compare[2] + ' gene expression overlap') plt.show() So, there's basically a lot of different cases, each handled manually, and I'm wondering if there's a more "automated" / less verbose / better way of doing this. For example, can I get out the entries from the three line code snippet in the beginning somehow? Answer: Perhaps something like the following? values_to_sets = {a : (a in set1, a in set2, a in set3) for a in union} sets_to_values = {} for a, s in values_to_sets.items(): if s not in sets_to_values: sets_to_values[s] = [] sets_to_values[s].append(a) print(sets_to_values) This first identifies each item with a tuple indicating which sets that item belongs to. Then you flip the dictionary mapping, where each tuple maps to a list of items belonging to the combination of sets indicated in the tuple. You could even expand this to an arbitrary number of sets: sets = [set1, set2, set3, set4] values_to_sets = {a : (a in s for s in sets) for a in union}
{ "domain": "codereview.stackexchange", "id": 11874, "tags": "python, pandas, matplotlib" }
Helmholtz equation and sources
Question: it is known that starting from the Maxwell equations it is possible to get the following Helmholtz equations: In time domain it corresponds to a sinusoidal EM field, according to the wave equation: Now my question is: is the time - behaviour of E/H always sinusoidal? It seems quite strange to me: I did not see any assumption of sinusoidal behaviour of current/charge sources. From this result it seems to me that sources can have any time - behaviour (also constant) and there will be a sine EM wave in time. I think I have missed some part of the reasoning. Answer: According to Fourier's Theorem, there are a very broad class of functions that can be approximated to arbitrary accuracy by sums of sinusoidal functions. This means that if you can solve the Helmholtz equation for a sinusoidal source, you can also solve it for any source whose behavior can be described by a Fourier series. In fact, since the Helmholtz wave equation is a linear PDE, you can solve it for almost any arbitrary source $f(r)$ by: Decomposing $f(r)$ into sinusoidal components, Solving the Helmholtz wave equation for each component, and Adding the solutions back together.
{ "domain": "physics.stackexchange", "id": 59704, "tags": "electromagnetism, waves, electromagnetic-radiation, magnetic-fields, maxwell-equations" }
Gazebo ROS Collision Detection
Question: Hello all, I am trying to get a topic with the collision by using the gazebo-ros-bumper plugin, but all of the resources I have found online have not worked for me. Here is my xacro code for the robot arm. <!-- ***************Robot Arms*************** --> <xacro:include filename="$(find robsim_description)/urdf/kuka.xacro" /> <!-- ***************Robot Hands*************** --> <xacro:include filename="$(find robsim_description)/urdf/sdhhand.xacro" /> <!-- ***************Joint*************** --> <xacro:rev_joint_block parent="arm_extension" child="sdh_gehaeuse" xyz="0 0 0.0411" rpy="0 0 0" lower="0" upper="0"/> <!-- ***************Gazebo Plugin************************ --> <gazebo> <plugin name="gazebo_ros_control" filename="libgazebo_ros_control.so"> <robotNamespace>/robarm</robotNamespace> </plugin> </gazebo> Here is the code for my kuka arm: <xacro:macro name="link_block" params="link xyz rpy filename material"> <link name="${link}"> <visual> <origin xyz="${xyz}" rpy="${rpy}"/> <geometry> <mesh filename="package://robsim_description/models/${filename}"/> </geometry> </visual> <collision> <origin xyz="${xyz}" rpy="${rpy}"/> <geometry> <mesh filename="package://robsim_description/models/${filename}"/> </geometry> </collision> <inertial> <mass value="1"/> <inertia ixx="0.1" ixy="0" ixz="0" iyy="0.1" iyz="0" izz="0.1"/> </inertial> </link> <gazebo reference="${link}"> <turnGravityOff>true</turnGravityOff> <material>Gazebo/${material}</material> </gazebo> </xacro:macro> <xacro:macro name="rev_joint_block" params="parent child xyz rpy lower upper"> <joint name="${parent}_${child}_joint" type="revolute"> <parent link="${parent}"/> <child link="${child}"/> <origin xyz="${xyz}" rpy="${rpy}"/> <axis xyz="0 0 1" rpy="0 0 0"/> <limit lower="${lower}" upper="${upper}" effort="300.0" velocity="1000.0"/> <joint_properties damping="0.0" friction="0.0"/> </joint> </xacro:macro> <xacro:macro name="transmission_block" params="parent child"> <transmission name="${parent}_${child}_trans"> <type>transmission_interface/SimpleTransmission</type> <joint name="${parent}_${child}_joint"> <hardwareInterface>PositionJointInterface</hardwareInterface> </joint> <actuator name="${parent}_${child}_motor"> <mechanicalReduction>1</mechanicalReduction> </actuator> </transmission> </xacro:macro> <!-- ***************Kuka Base Plate*************** --> <xacro:link_block link="base_link" xyz="0 0 0.016" rpy="0 0 0" filename="kuka_base_plate.dae" material="Grey"/> <!-- ***************Kuka A1 Joint***************** --> <xacro:link_block link="a1" xyz="0 0 0.016" rpy="0 0 0" filename="a1.dae" material="Orange"/> <joint name="base_a1" type="fixed"> <parent link="base_link"/> <child link="a1"/> </joint> <!-- ***************Kuka A2 Joint**************** --> <xacro:link_block link="a2" xyz="0 0 0" rpy="0 0 0" filename="a2.dae" material="Orange"/> <xacro:rev_joint_block parent="a1" child="a2" xyz="0 0 0.3265" rpy="0 0 0" lower="-2.96706" upper="2.96706"/> <xacro:transmission_block parent="a1" child="a2"/> <!-- ***************Kuka E1 Joint**************** --> <xacro:link_block link="e1" xyz="0 0 0" rpy="0 0 0" filename="e1.dae" material="Orange"/> <xacro:rev_joint_block parent="a2" child="e1" xyz="0 0 0" rpy="1.5707 3.14159 0" lower="0" upper="3.14159"/> <xacro:transmission_block parent="a2" child="e1"/> <!-- ***************Kuka A3 Joint**************** --> <xacro:link_block link="a3" xyz="0 0 0" rpy="0 0 0" filename="a3.dae" material="Orange"/> <xacro:rev_joint_block parent="e1" child="a3" xyz="-0.4 0 0" rpy="-1.5707 0 1.5707" lower="-2.0944" upper="2.0944"/> <xacro:transmission_block parent="e1" child="a3"/> <!-- ***************Kuka A4 Joint**************** --> <xacro:link_block link="a4" xyz="0 0 0" rpy="0 0 0" filename="a4.dae" material="Orange"/> <xacro:rev_joint_block parent="a3" child="a4" xyz="0 0 0" rpy="-1.5707 0 0" lower="-2.96706" upper="2.96706"/> <xacro:transmission_block parent="a3" child="a4"/> <!-- ***************Kuka A5 Joint**************** --> <xacro:link_block link="a5" xyz="0 0 0" rpy="0 0 0" filename="a5.dae" material="Orange"/> <xacro:rev_joint_block parent="a4" child="a5" xyz="0 -0.39 0" rpy="1.5707 0 0" lower="-2.0944" upper="2.0944"/> <xacro:transmission_block parent="a4" child="a5"/> <!-- ***************Kuka A6 Joint**************** --> <xacro:link_block link="a6" xyz="0 0 0" rpy="0 0 0" filename="a6.dae" material="Grey"/> <xacro:rev_joint_block parent="a5" child="a6" xyz="0 0 0" rpy="1.5707 0 0" lower="-2.96706" upper="2.96706"/> <xacro:transmission_block parent="a5" child="a6"/> <!-- ***************Kuka Tool Plate Joint*************** --> <xacro:link_block link="tool_plate" xyz="0 0 0" rpy="0 0 0" filename="tool_plate.dae" material="Grey"/> <xacro:rev_joint_block parent="a6" child="tool_plate" xyz="0 0.078 0" rpy="-1.5707 0 0" lower="-2.96706" upper="2.96706"/> <xacro:transmission_block parent="a6" child="tool_plate"/> <!-- ***************Kuka Arm Extention Joint*************** --> <xacro:link_block link="arm_extension" xyz="0 0 0" rpy="0 0 0" filename="arm_extension.dae" material="Grey"/> <joint name="arm_extension" type="fixed"> <parent link="tool_plate"/> <child link="arm_extension"/> </joint> Here is the code for the SDH Hand: <xacro:macro name="link_block" params="link xyz rpy filename material"> <link name="${link}"> <visual name="${link}_visual"> <origin xyz="${xyz}" rpy="${rpy}"/> <geometry> <mesh filename="package://robsim_description/models/${filename}"/> </geometry> </visual> <collision name="${link}_collision"> <origin xyz="${xyz}" rpy="${rpy}"/> <geometry> <mesh filename="package://robsim_description/models/${filename}"/> </geometry> </collision> <inertial> <mass value="1"/> <inertia ixx="0.1" ixy="0" ixz="0" iyy="0.1" iyz="0" izz="0.1"/> </inertial> </link> <gazebo reference="${link}"> <turnGravityOff>true</turnGravityOff> <material>Gazebo/${material}</material> </gazebo> </xacro:macro> <xacro:macro name="rev_joint_block" params="parent child xyz rpy lower upper"> <joint name="${parent}_${child}_joint" type="revolute"> <parent link="${parent}"/> <child link="${child}"/> <origin xyz="${xyz}" rpy="${rpy}"/> <axis xyz="0 0 1" rpy="0 0 0"/> <limit lower="${lower}" upper="${upper}" effort="300.0" velocity="1000.0"/> <joint_properties damping="0.0" friction="0.0"/> </joint> </xacro:macro> <xacro:macro name="transmission_block" params="parent child"> <transmission name="${parent}_${child}_trans"> <type>transmission_interface/SimpleTransmission</type> <joint name="${parent}_${child}_joint"> <hardwareInterface>PositionJointInterface</hardwareInterface> </joint> <actuator name="${parent}_${child}_motor"> <mechanicalReduction>1</mechanicalReduction> </actuator> </transmission> </xacro:macro> <!-- ***************SDH Hand Gehaeuse*************** --> <xacro:link_block link="sdh_gehaeuse" xyz="0 0 0.0743" rpy="0 0 0" filename="sdh_gehaeuse.dae" material="Grey"/> <!-- ***************Finger 1************************ --> <xacro:link_block link="gelenk_1" xyz="0 0 0" rpy="0 0 0" filename="sdh_gelenk_finger1_simplified.dae" material="Grey"/> <xacro:rev_joint_block parent="sdh_gehaeuse" child="gelenk_1" xyz="0.019052 -0.033 0.0908" rpy="0 0 1.5707" lower="-1.5707" upper="1.5707"/> <xacro:transmission_block parent="sdh_gehaeuse" child="gelenk_1"/> <xacro:link_block link="mittelteil_1" xyz="0 0 0" rpy="0 0 0" filename="sdh_mittelteil_finger1_mass.dae" material="Grey"/> <xacro:rev_joint_block parent="gelenk_1" child="mittelteil_1" xyz="0 0 0" rpy="0 -1.5707 0" lower="-1.5707" upper="1.5707"/> <xacro:transmission_block parent="gelenk_1" child="mittelteil_1"/> <xacro:link_block link="kuppe_1" xyz="0 0 0" rpy="0 0 0" filename="sdh_kuppe_finger1.dae" material="Grey"/> <xacro:rev_joint_block parent="mittelteil_1" child="kuppe_1" xyz="0.0865 0 0" rpy="0 0 0" lower="-1.5707" upper="1.5707"/> <xacro:transmission_block parent="mittelteil_1" child="kuppe_1"/> <!-- ***************Finger 2************************ --> <xacro:link_block link="gelenk_2" xyz="0 0 0" rpy="0 0 0" filename="sdh_gelenk_finger1_simplified.dae" material="Grey"/> <xacro:rev_joint_block parent="sdh_gehaeuse" child="gelenk_2" xyz="-0.038105 0 0.0908" rpy="0 0 -1.5707" lower="-1.5707" upper="1.5707"/> <xacro:transmission_block parent="sdh_gehaeuse" child="gelenk_2"/> <xacro:link_block link="mittelteil_2" xyz="0 0 0" rpy="0 0 0" filename="sdh_mittelteil_finger1_mass.dae" material="Grey"/> <xacro:rev_joint_block parent="gelenk_2" child="mittelteil_2" xyz="0 0 0" rpy="0 -1.5707 0" lower="-1.5707" upper="1.5707"/> <xacro:transmission_block parent="gelenk_2" child="mittelteil_2"/> <xacro:link_block link="kuppe_2" xyz="0 0 0" rpy="0 0 0" filename="sdh_kuppe_finger1.dae" material="Grey"/> <xacro:rev_joint_block parent="mittelteil_2" child="kuppe_2" xyz="0.0865 0 0" rpy="0 0 0" lower="-1.5707" upper="1.5707"/> <xacro:transmission_block parent="mittelteil_2" child="kuppe_2"/> <!-- ***************Finger 3************************ --> <xacro:link_block link="gelenk_3" xyz="0 0 0" rpy="0 0 0" filename="sdh_gelenk_finger1_simplified.dae" material="Grey"/> <xacro:rev_joint_block parent="sdh_gehaeuse" child="gelenk_3" xyz="0.019052 0.033 0.0908" rpy="0 0 1.5707" lower="-1.5707" upper="1.5707"/> <xacro:transmission_block parent="sdh_gehaeuse" child="gelenk_3"/> <xacro:link_block link="mittelteil_3" xyz="0 0 0" rpy="0 0 0" filename="sdh_mittelteil_finger1_mass.dae" material="Grey"/> <xacro:rev_joint_block parent="gelenk_3" child="mittelteil_3" xyz="0 0 0" rpy="0 -1.5707 0" lower="-1.5707" upper="1.5707"/> <xacro:transmission_block parent="gelenk_3" child="mittelteil_3"/> <xacro:link_block link="kuppe_3" xyz="0 0 0" rpy="0 0 0" filename="sdh_kuppe_finger1.dae" material="Grey"/> <xacro:rev_joint_block parent="mittelteil_3" child="kuppe_3" xyz="0.0865 0 0" rpy="0 0 0" lower="-1.5707" upper="1.5707"/> <xacro:transmission_block parent="mittelteil_3" child="kuppe_3"/> Originally posted by justinkgoh on ROS Answers with karma: 25 on 2016-07-21 Post score: 0 Original comments Comment by 130s on 2016-07-21: Where is your bumper plugin defined? And I'm also trying bumper simulation now and found the wiki might not be accurate. I'll edit it once I confirm the right way. Comment by justinkgoh on 2016-07-22: I have tried it in several places. Including the one you suggested in the gazebo wiki site. The other ones I have tried are from here and here. Answer: Which link do you want to create a bumper on? You need to create a contact sensor first. I had a hard time getting this to run as well. I've attached some example code which you can edit as necessary. This code is in my atlas.gazebo file <gazebo reference="your_link"> <!-- contact sensor --> <sensor type="contact" name="your_link_contact_sensor"> <update_rate>1000.0</update_rate> <always_on>1</always_on> <contact> <collision>bumper_collision</collision> <topic>/bumper_contact</topic> </contact> <plugin name="gazebo_ros_bumper_controller" filename="libgazebo_ros_bumper.so"> <alwaysOn>true</alwaysOn> <updateRate>1000.0</updateRate> <bumperTopicName>/robot_bumper</bumperTopicName> <frameName>world</frameName> </plugin> </sensor> Originally posted by Mav16 with karma: 38 on 2016-08-30 This answer was ACCEPTED on the original site Post score: 0
{ "domain": "robotics.stackexchange", "id": 25321, "tags": "ros, gazebo, collision, plugin" }
Does the inner core of the Earth drop?
Question: If standing on earth, I experience the planet's gravity. Rain drops are accelerated to move toward its centre and reach the crust. These attractions are mutual. This contrasts to e.g., the ISS with reduced / microgravity only. So I started to ponder about Earth's solid core, simplified to float, ball-like, in the outer core known to be a liquid. Equally, I simplify earth to a sphere with a tilted axis of rotation aligned parallel to the straight line from geographic south to north, too. (modified from this source) As seen by the tides, and its path around sun, planet earth experiences gravitational attraction with the sun (and its moon), too. If the planet were flexible like a bread dough, instead of a spherical shape, the planet would be constantly kneaded to exhibit a protrusion pointing toward sun, and to lesser degree, moon. Thus I speculate the inner core could equally move slowly / «sink» toward such an external gravitational partner because of its higher density (12.8 to 13 kg/L) compared to the one of the outer core (12.1 kg/L, both taken from here, lacking information about the viscosity of the melt). In the illustration, I marked the position of an excessively displaced core by a blue circle. Question: Is this line of thought about a «dropping Earth core» correct, is there experimental record for this? In analogy to the ultrasound at the physician, maybe echo waves would travel in shorter time from the mantle to inner core and back if this distance were shorter and thus allow a diagnosis. Given the mass and inertia of the inner core, these imagined movements possibly are small, too. Moving the core along the line S-N need not be the correct direction of movement to represent here. Answer: This contrasts to e.g., the ISS with reduced / microgravity only. I'm not sure how the ISS contrasts. Both raindrops and the ISS experience gravity and accelerate toward the earth. The only difference is that the raindrop will also experience drag and in short order will strike the surface. I speculate the inner core could equally move slowly / «sink» toward such an external gravitational partner because of its higher density If the earth were somehow fixed in space, but still in a gravitational field, you would be correct. The densest portion would stretch to the source of strongest gravitational attraction. But the earth is not fixed in space, it is in freefall. So the main effect the sun and moon have between one particle on earth and another are differential or tidal forces. These forces are much weaker than the earth's gravitational pull. So the densest materials are pulled to the center of the earth, not to one side.
{ "domain": "physics.stackexchange", "id": 71983, "tags": "newtonian-gravity, earth, geophysics" }
Given that A reduces to B in $O(n^2)$ and B is solvable in $O(n^3)$, solve A
Question: Suppose a problem A reduce to problem B and reduction is done in $O(n^2)$ time. If problem B is solved in $O(n^3)$ time then what about the time complexity of problem A? Approach: A is reduced to B . Here reduction is done at polynomial time. Here B is solved in polynomial time. So A should also be in polynomial time. Now A can not be harder than B, So I think A can be $O(n^3)$ or $O(n^2)$. But logically if I reduced A to B and if B is $O(n^3)$ then it makes no sense for A to be $O(n^2)$, else why would I reduce it to higher complexity? So A is $O(n^3)$. But my doubt is, we say while reduction that A can not be harder than B then how can we decide whether it is $O(n^2)$ or $O(n^3)$. Or is this argument only valid for P, NP classes of problem when I say A can not be harder than B or B must be at least as hard as A? Answer given is "A is $O(n^3)$", but why can't it be $O(n^2)$ as "A can not be harder than B" but can be of equal complexity? Or is reducibility just an argument for complexity classes? Explain if possible how reduction actually works, and why I couldn't apply it to my problem. Answer: You have a reduction, but you don't know what size the new problem will be. Say you have an instance of problem A of size n. And you can reduce it to an instance of problem B in time O (n^2). If you can reduce it to an instance of size $O(N^{1/2})$ then you are fine: You took O (N^2) for the reduction, and $O(N^{3/2})$ to solve the instance of B. If you reduce the instance of problem A to an instance of size O (n log n) of problem B, then you will take O (n^3 log^3 n) to solve the instance of B. So the time for the reduction and the time for solving B are not enough. You need to know the size of the new problem as well. (Of course you can't create an instance greater than O (n^2) in O (n^2) time, so the worst case is O (n^6), but it could be much better). The answer that was given (O (n^3)) is definitely wrong. It doesn't follow from the information you were given.
{ "domain": "cs.stackexchange", "id": 12721, "tags": "reductions, p-vs-np" }
How to extract robots coordinates using ICP algo
Question: I would like to know How to extract robots localization from the icp or ndt algo, currently I'm using scan registration for this reason Answer: The transformation T itself contains the location and orientation of your robot. Try to search for some related information regarding SE3 pose representation. Keywords: SE3, SO3, Rigid Body Kinematics, Matrix pose representation, coordinate transform Some related materials: https://www.seas.upenn.edu/~meam620/slides/kinematicsI.pdf Important: don't try to understand lie algebra. T is composed of rotation and translation. The rotation is 3x3 matrix that is starting from left-top of your T. Each column of the rotation matrix is the x,y,z axis direction of the robot. And the translation which start from the left-most column of your T is just xyz location of your robot with respect to the world coordinate. Direction is important. You need to find out if your T is world to robot or robot to world.
{ "domain": "robotics.stackexchange", "id": 2352, "tags": "ros, localization, mapping, frame, coordinate-system" }
What does nonnegative zero-phase response mean?
Question: I am not exactly sure what nonnegative zero-phase response means. If a filter is zero-phase (i.e. symmetric and non-causal), then what does nonnegative imply? And what are the conditions to satisfy it? Context: This is an error I get in Matlab when trying to design min-phase filters: Error using firminphase>checknonnegative (line 79) The filter has to have a nonnegative zero-phase response. Error in firminphase (line 38) checknonnegative(b); Error in firgr>genfilter (line 323) hRet = firminphase(hRet, s.zero, 'angles'); Answer: What they mean here is that the real-valued amplitude function of the linear phase FIR filter that you provide to the function must be non-negative, because it is interpreted as the desired squared magnitude of the minimum-phase filter. This amplitude function is referred to as zero-phase response, which is the frequency response of the filter when the coefficients are shifted such that they are centered around the origin, i.e., $b[n]=b[-n]$ is satisfied. Note that the filter length must be odd. If $N$ is the (odd) filter length, the zero-phase response is given by $$B_{zp}(e^{j\omega})=B(e^{j\omega})e^{j\omega(N-1)/2}$$ where $B(e^{j\omega})$ is the frequency response of the causal filter.
{ "domain": "dsp.stackexchange", "id": 9586, "tags": "filters, filter-design, finite-impulse-response, phase, minimum-phase" }
HackerRank week of code 32 competition: GeometrickTrick
Question: last week I entered HackerRank Week of Code 32, a week-long competition, with 6 coding challenges, ranging from easy to hard. I am satisfied with my result at this particular competition but I also would like to understand where I failed. The competition is over since monday morning so it's not to cheat in the competition that I ask help. The challenge I'm blocking on his of medium difficulty (says HackerRank competition, I found it hard enough^^). I would like your advice on how I could improve my code performance-wise. I'll announce the problem, and then show you what I've done GEOMETRIC TRICK: Consider a string \$s\$ of length \$n\$ consisting of the character in the set \$\{a,b,c\}\$. We want to know the number of different \$(i,j,k)\$ triplets (where \$0 \le i,j,k \lt n\$) satisfying two conditions: \$s[i] = “a”, s[j] = “b”, s[k] = “c”\$ \$(j + 1)^2 = (i + 1)(k + 1)\$ We consider two triples \$(i,j,k)\$, and \$(x,y,z)\$, to be different if and only if \$i \ne x\$ or \$(j \ne y)\$, or \$(k \ne z)\$. Given \$n\$ and \$s\$, find and print the number of different \$i,j,k\$ triples. My approach Example Given the string "ccaccbbbaccccca" of length 15, the final result is 2. {2,5,11} satisfy both conditions s[2] = 'a', s[5] = 'b' and s[11] = 'c' (5 + 1)² = (2 + 1)(11 + 1) {8,5,3} satisfy both conditions s[8] = 'a', s[5] = 'b' and s[3] = 'c' (5 + 1)² = (8 + 1)(3 + 1) We find 2 triples that match the 2 conditions so the answer is 2. The code gist link = https://gist.github.com/JulienRouse/cafbce417bbc2a4f6303df10df20d445 Code here: /** * Consider a string s of length n with alphabet {a,b,c}. * We look for the number of different triplet (i,j,k) where 0<=i,j,k<n, satisfying! * - s[i] = "a", s[j] = "b", s[k] = "c" * - (j + 1)² = (i + 1)(k + 1) * @param s A string we look the triplet in * @return Number of different triplets such as enonced above. */ public static int geometricTrickv2(String s){ Set<Integer> indexA = new HashSet<>(s.length()); Set<Integer> indexC = new HashSet<>(s.length()); List<Integer> indexB = new ArrayList<>(); for(int i=0;i<s.length();i++){ if(s.charAt(i)=='a') indexA.add(i); if(s.charAt(i)=='b') indexB.add(i); if(s.charAt(i)=='c') indexC.add(i); } int res = 0; for(int tmpB:indexB){ int powB = (int)Math.pow((double)(tmpB+1),2); for(int i=2;i<=Math.sqrt((double)powB);i++){ if(powB%i==0){ if(i != powB/i) if(indexA.contains(i-1)&&indexC.contains(powB/i-1)) res++; if(indexC.contains(i-1)&&indexA.contains(powB/i-1)) res++; else if(indexA.contains(i-1)&&indexC.contains(i-1)) res++; } } } return res; } Explanation First thing: I build 2 HashSet with the indexes of the letter 'a' and 'c' and a list of the indexes of the letter 'b' in the string s. Then, I'll work with the given condition \$(j + 1)^2 = (i + 1)(k + 1)\$, which can be seen as: find i and k such as \$i+1\$ and \$k+1\$ are complementary divisor of \$(j+1)^2\$ (By complementary I mean: say you have 25, his divisors are 1,5 and 25. 1 and 25 are complementary in the way that 1*25 = 25, 5*5=25 but 1*5!=25. so 1 and 25 are complementary, 5 is complementary with himself but (1 and 5) and (5 and 25) are not complementary ) To find all the divisor of n, I only need to search up until sqrt(n). (It's a property I remember from high school, hope I didn't screw up) because I can calculate the divisor and their complementary counterpart on the same iteration. Then once I am calculating those divisor, I need to check if they are in the HashSet containing the indexes of 'a' and 'c', and satisfying the condition. Complexity We say m = number of letters 'b' If I'm not mistaken, complexity is \$O(m \sqrt{m})\$ (For each index of 'b', I compute his divisor in \$\sqrt{m}\$ times and every other operation is \$O(1)\$ or not in the loop) My problem When I submitted my code to the challenge, the result where correct when string s was small, but quickly timed out for bigger input. There must be a better solution but I can't find so if anybody got suggestions on algorithms I would greatly appreciate. Also if you have any tips to give me about code clarity, about problem solving or anything that makes me learn and improve. It will be really great. Thanks for reading all the way, sorry for my English. Answer: You don't need the HashSets to see if \$s[i] = “a”\$ you only need to do s.chatAt(i) == 'a'. If you really want to minimize the time it takes then dumping it into a char[] would be best. Something to note is that you can square ints much faster doing the simple multiply with self method than convert to double and use call Math.pow. Also the square root of a square is the same as the original number. int powB = (tmpB+1)(tmpB+1); for(int i=2;i < tmpB;i++){ if(powB%i==0){ \$i, j, k\$ all have to be distinct because the characters they refer to must be different so you can save a few test and iterations there. The algorithm you have boils down to for(int j : indexB){ for(int i : getDividersFor((j+1)(j+1))){ int k = (j+1)/i - 1; i-=1; // check if i, j and k have the correct values. // and check for i and k swapped } } Where getDividersFor(n) has time complexity of \$O(\sqrt n)\$. But because n passed in is the square of j the total complexity is \$O(m^2)\$ Instead given a \$i\$ you can construct a \$k\$ such that \$(i+1)(k+1)\$ is a perfect square. First you factor \$i+1\$ into prime powers. Then you take all odd prime powers and multiply them together. For example for \$60 = 2^2 * 3^1 * 5^1\$ you multiply 3 and 5 to get 15 as the start value of k and \$15*60 = 900 = 30^2\$. That is the start value of \$k+1\$ and you multiply it with squares until you go past the end of the string: for(int i = 0; i < s.length(); i++){ if(s.charAt(i) != 'a' && s.charAt(i) != 'c')//cannot pass inner check continue; int k0 = extractOddPrimesAndMultiply(i+1); int j0 = (int)Math.sqrt((i+1)*k0) - 1; for(int factor = 1; j0*factor - 1 < s.length() && k0*factor*factor < i+1; factor++){ int k = k0*factor*factor - 1; int j = j0*factor - 1; //test string values and check for i and k swapped } } This actually has \$O(m \sqrt m)\$ complexity
{ "domain": "codereview.stackexchange", "id": 25783, "tags": "java, performance, algorithm, programming-challenge" }
Finding the partition function for a three-level system
Question: I am having difficulty finding the partition function of a system with two particles, each of which can be in any of three states with energies $0, \epsilon, 3\epsilon$. The system is in contact with a heat bath at temperature $T$. Since the system is in contact with a heat bath at temperature $T$, I believe that I'm going to need to use a canonical ensemble. Also, I think that the partition function should be a product of six terms, since there are $6$ possible ways to assign the possible energies to the energies to two particles. Any help is appreciated. I will update this post periodically with my attempts. Answer: Assuming the particles don't interact, there are nine possible microstates, and six unique energy levels. The energy levels and multiplicities are: (0,1), (1,2), (2,1), (3,2), (4,2), and (6,1). So for example, there are two states with energy level 3. From there, since we are assuming a canonical ensemble, your partition function becomes: $$ Z = \sum_{(\epsilon,\mu)}\mu\exp(-\beta \epsilon) $$ Where the sum is taken over all (energy, multiplicity) pairs.
{ "domain": "physics.stackexchange", "id": 52159, "tags": "homework-and-exercises, statistical-mechanics, partition-function" }
Using Sci-Kit Learn Clustering and/or Random-Forest Classification on String Data with Multiple Sub-Classifications
Question: I have a set of data with some numerical features and some string data. The string data is essentially a set of classes that are not inherently related. For example: Sample_1,0.4,1.2,kitchen;living_room;bathroom Sample_2,0.8,1.0,bedroom;living_room Sample_3,0.5,0.9,None I want to implement a classification method with these string-subclasses as a feature; however, I don't want to have them be numerically related or have the comparisons be directly based on the string itself. Additionally, if samples have no data in this column they should not be inherently related. Is there a way to implement these features as "classes" in a way that doesn't rely on a distance metric? I originally wanted to try converting the classes directly to numerical data, but I am worried that arbitrarily class 1 would be considered more closely related to class 2 than class 43. Answer: You use something called "dummy encoding".
{ "domain": "datascience.stackexchange", "id": 10841, "tags": "machine-learning, python, scikit-learn, machine-learning-model, multiclass-classification" }
How to harvest water passivley?
Question: I have been reading recently about methods to collect moisture from the air passively and turn it into water. However, is there any attempt currently for small-scale water harvesting? Methods I have found : 1- air well 2- Zibold's collector (building) 3- heat sinks collecter By small scale, I am referring to the size of a cup of water. Is there a way to condense water passively (no external power source)? (Here I am not concerned about the speed of generating water or whether the water is drinkable. I am targeting a method to condense water without supervision or external interference.) Answer: I think all the methods you list can be run using only the heat of the sun, and no other external power source. The general term for this type of water condenser is a solar still. If you search for "solar still" on YouTube you can find instructions for making a variety of home-made designs, as well as some more sophisticated commercial products.
{ "domain": "physics.stackexchange", "id": 88393, "tags": "condensed-matter, temperature, water, air" }
Electric flux through finite width/ infinitely long plane due to a point charge
Question: The question is as follows: Consider a point charge Q placed at $(0,h,0)$ (Cartesian coordinates). Find the flux in an area formed by $y=0$, $z\leq0$, $x\geq l$ and $x\leq a$ $( l\leq x\leq a )$. I tried this by considering the two extreme lines $x=l$ and $x=a$ and I constructed a cylinder (infinitely long) using the plane passing through $y=h$ and $x=l$. Then I tried taking some angles but I was unable to find any symmetry in the situation. Can someone please help me solve this? Answer: If Q is a point charge in empty space then the flux through a surface $\:S\:$ is \begin{equation} \Phi=\dfrac{\Theta}{4\pi}\dfrac{Q}{\epsilon_{0}} \tag{01} \end{equation} where $\:\Theta\:$ is the solid angle(*) by which the point Q "sees" the surface $\:S$. Now, if $\:0=\ell \leq a \:$ and the strip has a finite height $\:b\:$ along the negative $\:z\:$ then according to the Proposition-Practical Rule in my answer here we have (Figure 01) \begin{equation} \tan\Theta\left(b\right)=\dfrac{s}{h\!\cdot\!d}=\dfrac{a\!\cdot\!b}{h\!\cdot\!\sqrt{a^{2}+b^{2}+h^{2}}} \tag{02} \end{equation} so for an infinite strip (Figure 02) \begin{equation} \tan\Theta=\lim_{b\rightarrow \infty}\tan\Theta\left(b\right)=\lim_{b\rightarrow \infty}\dfrac{a\!\cdot\!b}{h\!\cdot\!\sqrt{a^{2}+b^{2}+h^{2}}} \nonumber \end{equation} that is \begin{equation} \boxed{\:\:\color{blue}{\tan\Theta=\dfrac{a}{h}}\:\:} \qquad 0=\ell \leq a \tag{03} \end{equation} If $\:0<\ell \leq a \:$ then we must subtract from the solid angle $\:\Theta_{1}\:$ of the infinite strip of width $\:a \:$ the solid angle $\:\Theta_{2}\:$ of the infinite strip of width $\:\ell \:$ \begin{equation} \Theta=\Theta_{1}-\Theta_{2} \tag{04} \end{equation} But \begin{equation} \tan\Theta_{1}=\dfrac{a}{h} \quad \text{and} \quad \tan\Theta_{2}=\dfrac{\ell}{h} \tag{05} \end{equation} so \begin{equation} \tan\Theta=\tan\left(\Theta_{1}-\Theta_{2}\right)=\dfrac{\tan\Theta_{1}-\tan\Theta_{2}}{1+\tan\Theta_{1}\tan\Theta_{2}}=\dfrac{\dfrac{a}{h}-\dfrac{\ell}{h}}{1+\dfrac{a}{h}\dfrac{\ell}{h}} \tag{06} \end{equation} that is (Figure 03) \begin{equation} \boxed{\:\:\color{blue}{\tan\Theta=\dfrac{h\left(a-\ell\right)}{h^{2}+a\ell}}\:\:} \qquad 0<\ell \leq a \tag{07} \end{equation} If $\:\ell<0 \leq a \:$ then we must add to the solid angle $\:\Theta_{1}\:$ of the infinite strip of width $\:a \:$ the solid angle $\:\Theta_{2}\:$ of the infinite strip of width $\:\vert\ell\vert=-\ell \:$ \begin{equation} \Theta=\Theta_{1}+\Theta_{2} \tag{08} \end{equation} But \begin{equation} \tan\Theta_{1}=\dfrac{a}{h} \quad \text{and} \quad \tan\Theta_{2}=\dfrac{\vert\ell\vert}{h}=\dfrac{-\ell}{h} \tag{09} \end{equation} so \begin{equation} \tan\Theta=\tan\left(\Theta_{1}+\Theta_{2}\right)=\dfrac{\tan\Theta_{1}+\tan\Theta_{2}}{1-\tan\Theta_{1}\tan\Theta_{2}}=\dfrac{\dfrac{a}{h}-\dfrac{\ell}{h}}{1-\dfrac{a}{h}\dfrac{-\ell}{h}} \tag{10} \end{equation} that is \begin{equation} \boxed{\:\:\color{blue}{\tan\Theta=\dfrac{h\left(a-\ell\right)}{h^{2}+a\ell}}\:\:}\qquad \ell<0 \leq a \tag{11} \end{equation} Combining (03),(07) and (11) we have in general \begin{equation} \boxed{\:\:\color{brown}{\tan\Theta=\dfrac{h\left(a-\ell\right)}{h^{2}+a\ell}}\:\:}\qquad \ell\leq a,\quad a\ge 0 \tag{12} \end{equation} (*) Examples of solid angles $\:(\rho\pi, \rho=1/4,1/2,1,2,4)\:$ are shown in the the Figure Solid Angles under my answer here : Flux through side of a cube. An other method to find a solution to this specific problem is based on the fact (could be proved easily) that in case of a solid angle $\:\Theta\:$ formed by three rays $\:\epsilon_{1},\epsilon_{2},\epsilon_{3}\:$ with $\:\epsilon_{3}\:$ normal to the plane of $\:\epsilon_{1},\epsilon_{2}\:$ (Figure 04) we have \begin{equation} \Theta=\phi \quad \Longrightarrow \quad \tan\Theta=\tan\phi \tag{13} \end{equation} where $\:\phi\:$ the plane angle formed by the rays $\:\epsilon_{1},\epsilon_{2}$. These are the cases of Figures 02 and 03.
{ "domain": "physics.stackexchange", "id": 48696, "tags": "gauss-law" }
Does Carbon act as a Faraday Cage?
Question: I am wondering if a GPS LTE-M tracker can be put inside carbon handlebars. I know the answer essentially boils down to Carbon acting as a Faraday cage but could not find a satisfying answer to this. Does Carbon block radio waves ? If yes or no, why - afaik it is not a metal ? Answer: Graphite is a pretty good conductor, so it should work as a Faraday cage, but I assume you would be working with carbon fiber. I don't think carbon fiber on its own conducts well enough. You could always test it.
{ "domain": "physics.stackexchange", "id": 64694, "tags": "material-science, radio" }
How do electrons know where to "drop to" when returning from an excited state?
Question: The Balmer series only shows electrons dropping to the energy level n=2 and the Lyman series only shows those that drop to n=1. How did they restrict the electron's energy transition so that the electrons only return to a specific energy level? Answer: Scientists don't control the energy level where an electron lands. They observe different series based on what equipment they use to make the measurements. For example, if scientists only look at the visible light from glowing hydrogen, the only the Ballmer series will be observed. Other light from other series are being emitted, but that light is not detected due to the choice of instruments.
{ "domain": "physics.stackexchange", "id": 88692, "tags": "electrons, spectroscopy" }
Does the Milky Way have dark matter satellite galaxies?
Question: This recent paper by Weinberg et al. discusses that one potential problem with our current model of Cold Dark Matter (CDM) is that is predicts a greater number of satellite galaxies for the Milky Way than are actually observed, and satellite galaxies with larger masses than those the Milky Way has (although the paper does say that many of the Milky Way's satellite galaxies may be too dim for us to currently observe). I know that at least dark matter galaxies are believed to have been observed (see this article). Is there any observational or other evidence for the existence of dark matter satellite galaxies to the Milky Way? And how have they been found? Edit: As has been pointed out, this is a question we likely don't have the answer to yet (otherwise there wouldn't be recent papers posing the question still), so perhaps a better question would be how could/would you find dark matter satellite galaxies of the Milky Way? Answer: This is actually a problem between simulations of structure formation and observations on a couple of different mass scales. Both galaxies and galaxy clusters appear to have nearly an order of magnitude more satellites than what is actually observed. The problem is dubbed the "missing satellite problem", or the Dwarf galaxy problem. People have been asking the question, what if these dwarf galaxies are simply not massive enough to attract enough gas gravitationally for them to be visible? Some interesting ideas and work has been done to determine if these structures actually do exist (Yoon, Johnston, and Hogg - Clumpy Streams from Clumpy Halos: Detecting Missing Satellites with Cold Stellar Structures). Also, Beth Willman has done some interesting work on detecting the least luminous galaxies (dwarf galaxy companions to the Milky Way). In other words, it is quite possible that there are small collections of stars, dust, and gas inside these substructures that are just so faint, we can't find them unless we're looking closely. I should also add that people have gone to lengths in the other direction, too. That is, to see how to alter the properties of dark matter in order to rid simulations of structures on that particular scale (see: Self-interacting dark matter). The LCDM cosmological model is a very robust and well-supported model for our universe on scales of around ~1 Mpc and larger. Some discrepancies do exist, of which the missing satellite problem is but one of them.
{ "domain": "physics.stackexchange", "id": 9652, "tags": "astrophysics, astronomy, dark-matter, galaxies, milky-way" }
Why rainbow colors are as they are?
Question: There are handful of questions related to rainbow formation here already, but after looking into them, I feel that I must ask yet another one. I did a little research on the subject, and most of the articles or youtube videos tend to focus on refraction-reflection-refraction in the single droplet part. The big picture, for some reason is expected to be self-evident after all that geometry and calculus put into finding maximum reflection angles for different wavelengths. Others will show a picture with two droplets and two rays of red and blue colors, where one ray of each color is missing observer's eye and have that as sufficient evidence. However, it's certainly not obvious moment for me. So if I get it right, abstracting away all the calculus-geometry stuff, if we take beam of parallel single wavelength rays hitting a perfect spherical droplet, it is going to be reflected in the shape of cone with the apex at the droplet, where half-angle depends on the wavelength (I like the image used for illustration in this question) Taking into account that white solar light is actually composition of spectrum, we can replace every droplet of water by a tiny light which will emit white light inside the cone with 40° half-angle, then on the edge of that cone we'll start losing violet, then blue, then green and so on up to 42° where we'll have only red left. Now from the observer's point of view, those droplets that are closer than 40° from antisolar point are going to reflect white light, and that matches with my observation: area inside rainbow is slightly brighter than outside. Yet as we get closer to 40°, the magic called "the rainbow" starts, and that's where my understanding gets in conflict with reality: Droplets at 40° reflect towards the observer all the light except violet. Respectively, I would expect to see inner rainbow ring as white except violet, i.e. bright green. Then with reduction of blue and then green it should have gotten more and more yellow. To my best understanding we should see kind of "cumulative spectrum" (in lack of better words I just coined this term), with no light outside the 42°(check), starting with red (check again), through the yellow to green at 40°, but without blue and violet (wrong), with just white inside the 40° ring (check again): Red => Red Orange => Red+Orange = Red Yellow => Red+Orange+Yellow = Orange Green => Red+Orange+Yellow+Green = Yellow Blue => Red+Orange+Yellow+Green+Blue = Green Violet => Red+Orange+Yellow+Green+Blue+Violet = White As apparently we are able to see blue and weak, but clear violet stripe in the rainbow, my understanding is wrong. So why don't we get red, yellow, green and blue light in it as well? Why do we see spectrum as if we were using prism, not the "cumulative spectrum"? Answer: With the addition of some good diagrams I think I now understand your question. This diagram does not show a key feature of the reflections. The intensity of the reflected rays varies and so you do not observe a uniform cone of reflected light. Here is a gif animation to show you what I mean. [Individual images were taken from an Atmospheric Optics webpage and combined to produce a gif file.] Parallel rays are coming in at the top of a water droplet and refracted, reflected and refracted again to emerge from the bottom half of the drop. What you should note is that for a given range of impact parameters of the incident rays the highest concentration of emergent rays occurs occurs around an angle of $137.5^\circ$, ie that is where the emergent light is brightest and light from around that angle swamps the light from that emerging at other angles. So you diagram should show a high intensity of red light around a particular direction and and much lower elsewhere. Here is a ray diagram to illustrate the "bunching" of light rays along a particular direction.
{ "domain": "physics.stackexchange", "id": 97137, "tags": "optics, visible-light, reflection, refraction" }
What is the reason behind the subphylum name "Urochordata" for tunicates?
Question: There are two major invertebrate subphyla of the chordates (phylum Chordata): Cephalochordata (the lancelets) Urochordata, aka Tunicata (the tunicates) My understanding is that the cephalochordates are named as such (meaning “head chords”) because the notochord reaches into the head. From Wiktionary: Any of the primitive fishlike creatures, of the subphylum Cephalochordata, including the lancelets, that lack a true spine but have a notochord which, in the case of cephalochordates, reaches into the head, contrary to the Urochordata. Urochordata, by contrast, means "tail chord", though I cannot find a reputable source (or any, really) that describes or details why this is the case. I can surmise it's simply because the notochord doesn't reach the head of a tunicate embryo -- as is corroborated by an image from Lemaire 20111 copied below. Image D' shows notochord in red. Credit: Lemaire 2011 However, I would prefer a quotable, reputable source that indicates explicitly that the Urochordates are in fact named as such due to their notochord not reaching their head. If this is not the case, then my question more broadly stands at: Why are the Urochordates named the way they are? 1: Lemaire, P., 2011. Evolutionary crossroads in developmental biology: the tunicates. Development, 138(11), pp.2143-2152. Answer: In 1877, Lankester proposed in "Notes on the Embryology and Classification of the Animal Kingdom" division of the group we now call Chordata into three parts: Urochorda Cephalochorda Craniata which is more or less the accepted division today, with Urochorda being called Urochordata now. In this essay, Lankester says: The evidence of degeneration is admitted as conclusive in the case of the parasitic Crustacea and Cirrhipedes. It is equally incontestable in that very large and varied group of non-parasitic organisms, the Tunicata (Urochordate Vertebrata).2 (in the above 'Vertebrata' is what we call 'Chordata'). He adds this footnote: 2The whole argument as to the Tunicates of course rests on the view- supported by many arguments, that the larval urochord, which many of them possess, is not a larval organ acquired by larval adaptation, but is hereditary and transmitted from adult ancestors. The term 'urochord' seems to be established and used without comment there, and probably is taken as simple neo-Latin for 'tail chord', although that may be somewhat loose, perhaps meaning the notochord is present but does not extend into the head. A 1913 Webster's Dictionary defines urochord as: (Zool.) The central axis or cord in the tail of larval ascidians and of certain adult tunicates. In 1882, Lankester futher discussed the anatomy of the tunicates in the context of the division of the chordata in a paper called "The Vertebration of the Tail of Appendiculariæ". This paper includes an illustration of a larval tunicate with the "notochord (urochord)" indicated.
{ "domain": "biology.stackexchange", "id": 9604, "tags": "zoology, terminology, nomenclature, invertebrates, etymology" }
What's the role of field equation in QFT?
Question: For free field theory, it seems the solutions of a field equation are used to give a representation of Poincare group, and the field equation is still satisfied after quantization. However for an interacting theory, such as QED, the field equation: $$\partial_\nu F^{\nu \mu} ~=~ e \bar{\psi} \gamma^\mu \psi.$$ I don't see any possibility of satisfying this equation using operators since LHS will only act nontrivially on bosonic sector of the Hilbert space and RHS only on fermionic sector, and I don't think perturbation technique can fix this since it's qualitatively not satisfied. Yet nobody seems to be bothered by this, so I'm wondering what's the role of field equation in QFT, especially for interacting ones. Answer: '' LHS will only act nontrivially on bosonic sector of the Hilbert space and RHS only on fermionic sector'': This would be the case in a free theory, but the field equation you wrote corresponds to an interacting theory. Its Hilbert space is not the Fock space one starts with, but is turned by renormalization into a different (and little understood) Hilbert space. (Actually, all separable Hilbert spaces in infinite dimensions are the same, but ''different'' conventially refers not to a structureless Hilbert space but to a Hilbert space with a good representation of the kinematic Lie algebra.) Actually, renormalization also changes the interpretation of the field equation, as the products of distributional fields at the same point on the right hand side must be interpreted with care. Edit: On a heuristic level, one can understand the ''mixing'' of bosonic and fermionic operators'' by considering naive (unrenormalized) perturbation theory of the operator equations. One finds that the solution of the field equations is a formal power series in the coupling constant, with the free field as the zero order part. The first and higher order part involves the interaction. Thus the free bosonic field acquires corrections involving the product of an even number of Fermionic fields, and therefore acts nontrivially on both the bosonic and the fermionic part of the state. Unforunately, this formal expansion is mathematically ill-defined, so this argument has only heuristic value.
{ "domain": "physics.stackexchange", "id": 4295, "tags": "quantum-field-theory, quantum-electrodynamics, fermions" }