anchor stringlengths 0 150 | positive stringlengths 0 96k | source dict |
|---|---|---|
Stacked barchart, bottom parameter triggers Error: Shape mismatch: objects cannot be broadcast to a single shape | Question: I am working in python3 and I want to obtain a stacked barchart plot, showing three different variables on 5 different columns.
My code works fine if I do not add the 'bottom parameter' in plt.bar (but I need to, in order for the stacks to appear in the correct order):
import numpy as np
import matplotlib as plt
columns=['a','b','c','d','e']
pos = np.arange(5)
var_one=[40348,53544,144895,34778,14322,53546,33623,76290,53546]
var_two=[15790,20409,87224,22085,6940,27099,17575,41862,27099]
var_three=[692,3254,6645,1237,469,872,569,3172,872]
plt.bar(pos,var_one,color='green',edgecolor='green')
plt.bar(pos,var_two,color='purple',edgecolor='purple')
plt.bar(pos,var_three,color='yellow',edgecolor='yellow')
plt.xticks(pos, columns)
plt.show()
However, once I add the bottom parameter in bar.plot (as shown below):
import numpy as np
import matplotlib as plt
columns=['a','b','c','d','e']
pos = np.arange(5)
var_one=[40348,53544,144895,34778,14322,53546,33623,76290,53546]
var_two=[15790,20409,87224,22085,6940,27099,17575,41862,27099]
var_three=[692,3254,6645,1237,469,872,569,3172,872]
plt.bar(pos,var_one,color='green',edgecolor='green')
plt.bar(pos,var_two,color='purple',edgecolor='purple',bottom=var_one)
plt.bar(pos,var_three,color='yellow',edgecolor='yellow',bottom=var_one+var_two)
plt.xticks(pos, columns)
plt.show()
the code triggers the error
ValueError: shape mismatch: objects cannot be broadcast to a single shape
How could I fix it?
Answer: if you change your code to the following:
import numpy as np
import matplotlib.pyplot as plt
columns = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j']
pos = np.arange(9)
var_one = np.array([40348, 53544, 144895, 34778, 14322, 53546, 33623, 76290, 53546])
var_two = np.array([15790, 20409, 87224, 22085, 6940, 27099, 17575, 41862, 27099])
var_three = np.array([692, 3254, 6645, 1237, 469, 872, 569, 3172, 872])
plt.bar(pos, np.add(np.add(var_three, var_two), var_one), color='yellow', edgecolor='yellow')
plt.bar(pos, np.add(var_two, var_one), color='purple', edgecolor='purple')
plt.bar(pos, var_one, color='green', edgecolor='green')
plt.xticks(pos, columns)
plt.show()
The result will be like this: | {
"domain": "datascience.stackexchange",
"id": 6196,
"tags": "python, matplotlib"
} |
MoveIt RobotState initialisation | Question:
In the MoveIt tutorial for the kinematic part, the sample code does the following to get the robot joint position:
robot_model_loader::RobotModelLoader robot_model_loader("robot_description");
robot_model::RobotModelPtr kinematic_model = robot_model_loader.getModel();
ROS_INFO("Model frame: %s", kinematic_model->getModelFrame().c_str());
robot_state::RobotStatePtr kinematic_state(new robot_state::RobotState(kinematic_model));
kinematic_state->setToDefaultValues();
const robot_state::JointModelGroup *joint_model_group = kinematic_model->getJointModelGroup("right_arm");
const std::vector<std::string> &joint_names = joint_model_group->getVariableNames();
std::vector<double> joint_values;
kinematic_state->copyJointGroupPositions(joint_model_group, joint_values);
The full code is available from link.
However, this doesn't give the current robot joint position. If I print out the position using RobotState::printStateInfo, the position array is always the same no matter how the robot joint positions are.
I also tried RobotState::update(true), but it is the same.
I wonder if the robot state requires any initialisation?
Originally posted by linshenzhen on ROS Answers with karma: 15 on 2017-10-31
Post score: 0
Answer:
The "robot_description" param is just the description of the robot universally (it's loaded from the URDF). The robot model/state does not update automatically, so you're going to be getting back the default joint positions every time because you're just setting it to the default positions. You need to feed in the joint state using kinematic_state->setVariablePositions(...). How you get the joint positions is going to be dependent on your application, but it sounds like you're probably doing a conventional setup where you may be publishing to "joint_states", so you should subscribe to that topic, read the positions in and feed it to the model. The model won't do it for you automatically.
It's a good thing the state doesn't update automatically because it allows us to do things like setting the state to a hypothetical target and testing for things like collisions before actually moving there.
Originally posted by rivertam with karma: 56 on 2017-11-02
This answer was ACCEPTED on the original site
Post score: 2 | {
"domain": "robotics.stackexchange",
"id": 29246,
"tags": "moveit"
} |
Counting the nodes in a network in a distributed way | Question: There is a network with $n$ nodes. Each node can contact only the neighbouring nodes (the degree of each node is bounded, if that matters).
One of the nodes, say $s$, wants to know $n$. How can it do this?
Each node has $O(\log n)$ memory bits, so it can hold a counter, but not a list of all nodes.
If the network is a tree, I think the following (inefficient) protocol should work:
$s$ sends a "Count" message to itself.
When a node $v$ receives a "Count" message from node $u$, it acts in the following way:
Send every neighbour except $u$ a "Count" message and wait for the result.
Send $u$ a "Result" message containing the sum of all results (0 if there are no neighbours).
The problem with general graphs is that we may not remember which nodes we already counted, so we might count the same node twice. What to do?
Answer: For constant node degrees, the following simple algorithm seems to work:
The source node $s$ can initiate a BFS tree construction and then we simply accumulate the count upwards along the tree edges starting from the leafs and ending at $s$. Each node locally keeps track of its parent/children in the tree; note that we can do this using $O(\log n)$ space as the degree is constant and therefore each node knows if it is a leaf.
For arbitrary degree, there's also a slightly more complicated randomized distributed algorithm that gives a constant factor approximation of the number of nodes in a synchronous network where computation proceeds in synchronous rounds. (In each round, every node can reliably exchange $O(\log n)$ bits with each of its neighbors.)
Suppose that I have a network $G$ with diameter $Diam(G)$.
Each node $u$ generates a random value $x_u$ according to the exponential distribution with rate 1; we round $x_u$ to $\Theta(\log n)$ bits.
Node $u$ also has a local variable $minval_u$ where it keeps track of the minimum value encountered so far. Initially, $minval_u = x_u$.
For the next $Diam(G)$ many rounds, node $u$ sends $minval_u$ to its neighbors. Also, upon receiving $minval_v$ from some neighbor $v$, node $u$ sets $minval_u = \min(minval_u,minval_v)$.
After round $Diam(G)$, node $u$ computes its estimate of the number of nodes as $1/minval_u$.
Why does this algorithm work?
Our algorithm exploits the following nice property of the exponential distribution (see here):
If we have $n$ exponential random variables $X_1,\dots,X_n$ each of rate $1$, then the random variable $X = \min(X_1,\dots,X_n)$ is also exponentially distributed of rate $n$ and therefore has expected value $1/n$. At the end of the algorithm, the $minval_u$ variable corresponds to a sample of this random variable $X$. Therefore, to get the sought value $n$ (i.e. the number of nodes), we simply compute $1/minval_u$. To get a high probability bound, we can repeat the above $\Theta(\log n)$ many times and take the average of the produced estimates. | {
"domain": "cs.stackexchange",
"id": 4672,
"tags": "algorithms, graphs, reference-request, distributed-systems"
} |
Difference between MSK and GMSK? | Question: I try to understand differencies between MSK and GMSK on transmitter side.
Is GMSK the same than MSK except that a gaussian filter is applied on bits before modulating them?
Is the half symbol delay on the Q path from MSK also done in GMSK?
I was not able to find a reference document clearly describing the waveform.
Answer: Pure MSK has a linear phase trajectory from symbol to symbol over 90 degrees (resulting in the minimum frequency separation where the frequencies over a symbol duration are still orthogonal) while GMSK the phase trajectory is the integration of a Gaussian pulse resulting in no abrupt transitions but still transitions from 0 to 90 degrees over a symbol duration (for full response signaling). The abrupt transitions in MSK lead to higher frequency sidelobes which is less desirable when bandwidth and spectral occupancy is a premium. GMSK is a form of Continuous Phase Shift Keying (CPFSK), which reduces this spectral occupancy by maintaining a continuous phase as the transitions. GMSK provides continuous phase operation with Gaussian transitions with the minimum frequency spacing of MSK.
Since instantaneous frequency is the time derivative of phase, the frequency vs time for GMSK is a series of Gaussian filtered pulses, and thus we can implement a GMSK Modulator using a filter with a Gaussian impulse response at the control voltage input to an VCO (voltage controlled oscillator), or completely digitally with the Frequency Control Word input to an NCO (numerically controlled oscillator) and each symbol as an rectangular pulse to be shaped by the Gaussian filter. Since the phase transitions $\pm \pi/2$, implementation structures may also be similar to QPSK modulators with half a symbol offset to assist in keeping the trajectory on the unit circle as the state transitions between the 4 quadrature states ($0, \pi/2, \pi, 3\pi/2$). What is important to all implementations (MSK and GMSK) is that the amplitude is always constant and it is only the phase that changes. For MSK the phase changes at a constant rate (and then may abruptly reverse direction) while in GMSK the phase starts out slowly, increases in rate of change with maximum rate of change at mid symbol and then slowly decreases as it reaches the next state thus eliminating the abrupt change if the direction is to reverse.
This may be clearer by observing the frequency versus time and phase versus time waveforms shown below for both MSK and GMSK for "Full Response Signaling" which is when the impulse response for each symbol is complete over the duration of one symbol period. The Bandwidth-Time product (BT) for GMSK is the inverse of the overlap of symbols and thus for Full Response Signaling, $BT=1$.
With "Partial Response Signaling" (BT < 1) as typically done, we allow the symbols to overlap (planned inter-symbol interference) allowing us to squeeze more data in less time (higher bandwidth efficiency) at the expense of receiver complexity to unravel all that inter-symbol interference, optimally with a Viterbi decoder or simplified with minor loss using the Laurent Decomposition.
For further details also see this post. | {
"domain": "dsp.stackexchange",
"id": 10347,
"tags": "modulation, gmsk"
} |
Does the CHSH inequality fully characterise the local polytope? | Question: Consider the standard two-party CHSH scenario. Each party can perform one of two measurements (denoted with $x,y\in\{0,1\}$) and observe one of two outcomes (denoted with $a,b\in\{0,1\}$).
Let $P(ab|xy)$ be the probability of observing outcomes $a,b$ when choosing the measurements settings $x,y$. Local realistic theories are those that, for some probability distribution over some hidden variable $\lambda$, satisfy
$$P(ab|xy)=\sum_\lambda q(\lambda)P_\lambda(a|x)P_\lambda(b|y).\tag1$$
Define the local polytope $\mathcal L$ as the set of theories that can be written as in (1).
Note that we identify here a theory with its set of conditional probabilities: $\boldsymbol P\equiv (P(ab|xy))_{ab,xy}$.
Denote with $E_{xy}$ the expectation values $E_{xy}=\sum_{ab}(-1)^{a+b}P(ab|xy)$.
We then know that all local realistic theories $\boldsymbol P\in\mathcal L$ satisfy the CHSH inequality:
$$\Big|\sum_{xy}(-1)^{xy} E_{xy}\Big| = |E_{00}+ E_{01} + E_{10} - E_{11}|
= \left|\sum_{abxy}(-1)^{a+b+xy}P(ab|xy)\right| \le 2.\tag2$$
Is the opposite true? In other words, do all theories satisfying (2) admit local realistic explanations?
Answer: Not quite. Consider the following no-signalling distribution $PR_1$ which I will write in the form
$$
\begin{pmatrix}
p(00|00) & p(01|00) & p(00|01) & p(01|01) \\
p(10|00) & p(11|00) & p(10|01) & p(11|01) \\
p(00|10) & p(01|10) & p(00|11) & p(01|11) \\
p(10|10) & p(11|10) & p(10|11) & p(11|11) \\
\end{pmatrix},
$$
$$
PR_1 = \begin{pmatrix}
1/2 & 0 & 1/2 & 0 \\
0 & 1/2 & 0 & 1/2 \\
1/2 & 0 & 0 & 1/2 \\
0 & 1/2 & 1/2 & 0\\
\end{pmatrix}.
$$
This distribution has $E_{00} = E_{01} = E_{10} = - E_{11} = 1$ and so achieves the algebraic maximum of $4$ of the CHSH expression as you write it in the question. Now consider another no-signalling distribution $PR_2$, derived from $PR_1$ by relabelling the inputs of Alice ($x \mapsto x + 1 \mod 2$), i.e.
$$
PR_2 = \begin{pmatrix}
1/2 & 0 & 0 & 1/2 \\
0 & 1/2 & 1/2 & 0 \\
1/2 & 0 & 1/2 & 0 \\
0 & 1/2 & 0 & 1/2 \\
\end{pmatrix}.
$$
$PR_2$ is another no-signalling distribution that is not local $PR_2 \notin \mathcal{L}$ -- (sketch) the local set is closed under relabellings of inputs/outputs, $PR_2$ is a relabelling of $PR_1$ (and vice versa) and $PR_1 \notin \mathcal{L}$. Now $PR_2$ results in the expectation values $E_{00} = 1, E_{01} = -1, E_{10} = 1, E_{11} = 1$ and so $E_{00} + E_{01} + E_{10} - E_{11} = 0$. Therefore, we have found a distribution that cannot be explained by a local model but nevertheless satisfies the CHSH inequality.
We can however still get a converse statement by including relabelled versions of the CHSH inequality. Suppose a no-signalling distribution $p$ satisfies all of the following inequalities
$$
\begin{aligned}
|E_{00} + E_{01} + E_{10} - E_{11}| &\leq 2 \\
|E_{10} + E_{11} + E_{00} - E_{01}| &\leq 2 \\
|E_{01} + E_{00} + E_{11} - E_{10}| &\leq 2 \\
|E_{11} + E_{10} + E_{01} - E_{00}| &\leq 2
\end{aligned}
$$
then $p \in \mathcal{L}$. In other words $\mathcal{L}$ has $8$ non-trivial facets. | {
"domain": "quantumcomputing.stackexchange",
"id": 1591,
"tags": "bell-experiment, non-locality, nonclassicality"
} |
Where can I find Helium 3 in our solar system? | Question: What are the best locations within the solar system to find Helium 3 excluding the Sun? Where is Helium 3 most abundant after the Sun?
Answer:
Where is Helium 3 most abundant after the Sun?
Jupiter, by mass, and Uranus and Neptune, by accessibility. This ignores that getting to and returning from Uranus and Neptune is extremely difficult.
Except for the Sun's core, the helium in the Sun is primordial in the sense that that helium was present when the Sun first formed, and mostly primordial in the sense that most of that helium was created during the Big Bang. The atmospheres of the giant planets are mostly hydrogen and helium -- i.e., mostly primordial.
Saturn's atmosphere is significantly depleted of helium compared to the Sun (and estimates of helium produced in the Big Band), and Jupiter's is slightly depleted in helium. This depletion is thought to be the result of helium somehow precipitating out of those gas giants' atmospheres. The atmospheres of Uranus and Neptune are much closer to primordial. | {
"domain": "astronomy.stackexchange",
"id": 4186,
"tags": "solar-system, helium"
} |
Does anyone have a good source for writing a Finite Volume Solver | Question: As a pet project I want to try and write my own finite volume solver for a two-phase flow problem. However, while I understand the basics of FEM I have never written a code that solves anything before. Does anybody have a good resource to get started with? My ideal source would be something that covers the basics in a broad sense, and really emphasizes the coding aspects with examples.
Answer: Quoting myself from a related question,
On a more programmatical aspect, Toro's Riemann Solvers and Numerical Methods and LeVeque's Finite Volume Methods for Hyperbolic Problems are pretty much the bible for how to write code that will accurately model fluid flows. In both books, vector calculus and linear algebra are needed. LeVeque's book is written more towards undergraduates, but is good for anyone interested in numerical methods; it also includes references an older version of his Fortran code Clawpack (an open-source library).
I don't recall if two-phase flows are covered in those texts (my guess would probably be no), but my understanding is that it should be a matter of replacing the pressure in the Euler equations with the results from your pressure function (e.g., $p_\text{tot}=f(\rho_1,\,\rho_2, \cdots)$).
For sure, however, these texts would be able to provide you with sufficient background of FVM to be able to write a code that could be used for two-phase. | {
"domain": "physics.stackexchange",
"id": 98741,
"tags": "fluid-dynamics, resource-recommendations, computational-physics, software"
} |
turtlebot sim crashes on subscribing to any topic | Question:
First I run the turtlebot run launch file from the terminal:
$ roslaunch turtlebot_gazebo turtlebot_world.launch
Then in a new terminal:
$ rostopic echo /scan
As soon as I subscribe to the /scan topic i get the following error:
gzserver: /build/ogre-1.9-mqY1wq/ogre-1.9-1.9.0+dfsg1/OgreMain/src/OgreRenderSystem.cpp:546: virtual void Ogre::RenderSystem::setDepthBufferFor(Ogre::RenderTarget*): Assertion `bAttached && "A new DepthBuffer for a RenderTarget was created, but after creation" "it says it's incompatible with that RT"' failed.
Aborted (core dumped)
[gazebo-1] process has died [pid 21624, exit code 134, cmd /opt/ros/kinetic/lib/gazebo_ros/gzserver -e ode /opt/ros/kinetic/share/turtlebot_gazebo/worlds/playground.world __name:=gazebo __log:=/home/pranav/.ros/log/f18cc0fc-ccc2-11e7-9a30-9cb6d0e527e7/gazebo-1.log].
log file: /home/pranav/.ros/log/f18cc0fc-ccc2-11e7-9a30-9cb6d0e527e7/gazebo-1*.log
Originally posted by inani47 on ROS Answers with karma: 18 on 2017-11-18
Post score: 0
Original comments
Comment by monabf on 2018-01-25:
Hi @inani47, did you manage to fix that ? I am having the same issue of gazebo crashing with no reason when launching it with ros and this version of Ogre.
Comment by inani47 on 2018-04-08:
@monabf sorry for the late reply. I was able to resolve the issue by updating to a newer version of Gazebo. All the best!
Answer:
To expand - I also got around this by updating to a newer version of Gazebo (I'm running Kinetic on Ubuntu 16.04).
I followed the "Alternative Installation" instructions here (with an important exception noted below):
http://gazebosim.org/tutorials?tut=install_ubuntu
IMPORTANT NOTE - if you're on Kinetic, you want to install "gazebo7" NOT "gazebo9" (which would be for Melodic)
Hope that helps - I spent many hours on Google figuring this out. But now the examples in Chapter 7 of Programming Robots with ROS run (as far as I've tried).
Cheers,
/K
Originally posted by KFW with karma: 16 on 2018-07-29
This answer was ACCEPTED on the original site
Post score: 0 | {
"domain": "robotics.stackexchange",
"id": 29400,
"tags": "gazebo, turtlebot"
} |
Change turtlebot initial position in gazebo ros | Question:
When launching roslaunch turtlebot_gazebo turtlebot_world.launch, turtlebot initial position is always at the center (0,0,0).
How can I change this initial position? I want for example the turtleot to be at (5,0, 0) in my map.
Originally posted by kiko453 on ROS Answers with karma: 17 on 2019-12-04
Post score: 0
Answer:
The position of the robot is determined when calling the node spawn_model from the package gazebo_ros. This node is called at the line <include file="$(find turtlebot_gazebo)/launch/includes/$(arg base).launch.xml">. It will call the launch file kobuki.launch.xml. In this file you have :
<!-- Gazebo model spawner -->
<node name="spawn_turtlebot_model" pkg="gazebo_ros" type="spawn_model"
args="$(optenv ROBOT_INITIAL_POSE) -unpause -urdf -param robot_description -model turtlebot"/>
Your solution is to create a new launch file similar to turtlebot_world.launch and instead of using the include to kobuki.launch.xml copy the content direclty in your launch file and remove the argument $(optenv ROBOT_INITIAL_POSE) to set your pose, using the arguments -x, -y, -Y (for yaw) like this :
<!-- Gazebo model spawner -->
<node name="spawn_turtlebot_model" pkg="gazebo_ros" type="spawn_model"
args="-x 5 -y 0 -Y 0 -unpause -urdf -param robot_description -model turtlebot"/>
Or if you don't want to change anything you can directly set the envirronment variable ROBOT_INITIAL_POSE to the desired arguments :
export ROBOT_INITIAL_POSE="-x 5 -y 0 -Y 0"
Note that after executing this you have to use roslaunch in the same terminal.
Originally posted by Delb with karma: 3907 on 2019-12-04
This answer was ACCEPTED on the original site
Post score: 0
Original comments
Comment by kiko453 on 2019-12-04:
Hi many thanks. The first soplution worked fine, but now the origin of my robot in rviz does match anymore with the origin in gazebo. in the my_map.yaml file there is a field origin: [12.2, -12.2, 0.0]. How do I have to change it such the position match with the one I set in kobuki.launch.xml. In other what coordinate transformation do I have to apply?
Comment by Delb on 2019-12-06:
That would be related to the AMCL configration, there are the parameters initial_pose_x, initial_pose_y and initial_pose_a, you just need to set them at the same values as the parameters of spawn_model. | {
"domain": "robotics.stackexchange",
"id": 34086,
"tags": "ros, gazebo, ros-kinetic"
} |
Checking user authorization | Question: def user_not_authorized(exception)
message = t('flash.access_denied')
if exception.policy.class.to_s.underscore == 'group_policy' && current_user.students.size != 0
current_user.students.each do |student|
student.memberships.each do |membership|
if membership.group_id == exception.record.id
message = t('flash.pending_acceptance')
break # and I would like to break from the outer loop too
end
end
end
end
flash[:alert] = message
redirect_to request.referrer || root_path
end
This looks ugly to me. Is there a way to somehow compress those two each loops, where one should break both of them conditionally?
Answer:
There's no reason (as far as I can tell) to do string comparison to check a class. #is_a? would presumably work fine too. And it'd be stricter, which is desirable.
There's no reason to check students.size. If there are no students, the loop just won't do anything, so why bother checking first? Conversely, if there are any students you're actually doing 2 database queries: One to get the count/size of students, and another to fetch the actual records.
Presuming non-ancient Rails, you can simply say current_user.students.memberships to get all the memberships in 1 query (admittedly with a couple of JOINs), rather than loop through students individually, and then getting their memberships.
Continuing from #3, you can (presumably) collapse the entire things into 1 database query.
I'd probably start with something like
def user_not_authorized(exception)
redirect_path = request.referrer || root_path
if exception.policy.is_a?(GroupPolicy)
if current_user.students.memberships.where("group_id = ?", exception.record.id).any?
redirect_to redirect_path, alert: t('flash.pending_acceptance') and return
end
end
redirect_to redirect_path, alert: t('flash.access_denied')
end
Note that it doesn't actually load any records at all; it just checks if they're there or not.
In practice, I'd consider breaking it into separate methods where possible. It's not that great to have a naked query referencing a specific column name in the middle of your method.
Edit: Updated the code to return if the first redirect occurs, since you'd otherwise do two redirects in one action, which is not allowed. Thanks to tokland for catching that. Now the and return fix is about as quick and dirty as is gets, but check the comments for better ideas. | {
"domain": "codereview.stackexchange",
"id": 12663,
"tags": "ruby, ruby-on-rails, authorization"
} |
To what extent is my interpretation of computable numbers correct? | Question: Interpretation: Consider the comic strip below, where a person tries to prevent a robot from dismembering them by asking the robot to compute $\pi$ - the robot quickly produces an algorithm to calculate all of the digits of $\pi$ and begins dismembering the person. This is possible because $\pi$ is a computable number.
In contrast, if the person had asked the robot to calculate Chaitin's constant (assuming the robot didn't say something like "which Chaitin's constant?" or "insufficient parameters") or some other non-computable number, would the people have been able to escape the robot's dismembering?
As far as I understand (1)(2), the robot could make an algorithm to calculate the first $n$ digits for any $n$, but to attempt to compute "all" of Chaitin's constant would take an infinite amount of time, because each new digit would require a new program, or something like this.
Question: Is this interpretation at all correct or am I completely off the mark here? To what extent could one describe computable numbers as numbers which "prevent a robot in this specific situation from dismembering people"?
I.e., do all non-computable numbers have algorithmically random (decimal, binary, etc.) expansions?
Source.
Answer: This is exactly the incorrect interpretation of "computable", resulting of trying to replace the precise definition with (possibly misplaced) intuition.
$\pi$ or any other irrational number also has an infinite digit representation, so according to your logic, it shouldn't be computable. This just shows that it is meaningless to require all of the digits as output, and we actually need a "better" definition.
To fix this issue, we say a number $p$ is computable, if we can approximate $p$ up to any given precision. One way of formalizing this is requiring the existence of a program $M_p(n)$, which upon receiving a number $n$ outputs (in finite time) a number $\hat{p}$ such that $|\hat{p}-p|\le\frac{1}{n}$. The comic actually refers to this definition, as $\pi$ having an infinite expansion does not prevent the robot from dismembering the guy.
If your goal is to avoid dismembering, then it is not clear how to use uncomputable numbers. What exactly is the meaning of calculate $x$? If i ask for some fixed approximation of an uncomputable number, then the robot can give me one (sure, it has no way of algorithmically producing the approximation, but perhaps this is some weird robot with a table of all approximations to any natural constant up to $10^{-100}$). You would probably stand more chance with incompleteness issues, rather than with computability issues. I would ask the robot for a proof in $ZFC$ of its consistency. If it is consistent, he wont find any, and if it isn't, who wants to live anyway. | {
"domain": "cs.stackexchange",
"id": 8756,
"tags": "computability, computation-models, intuition"
} |
How are Bosons force-carriers? | Question: In QFT, the exchange of Bosons between certain particles is responsible for the effect of force. My question is how can exchanging bosons lead to a force. Is force defined differently in QFT? (Aka. Should I abandon my classical understanding of force as a contact or non-contact between objects, influencing their motion?)
Answer: First define what you mean by "force carrier". It is not a standard term (except possibly in pop physics where it is never clearly defined). If the question is "do bosons have momentum?" then the answer is yes. If question is "do electrons exchange photons when they approach one another in free space?" then the answer is no. If the question is "do electrons interact via the electromagnetic field, and are excitations of that field an example of bosons?" then the answer is yes. If the question is "ok, how is the interaction between electrons described in quantum field theory?" then the answer is something like the following.
The interaction between a pair of charged particles is set out by noting that there are primarily two fields involved: the ones called Dirac field and electromagnetic (EM) field. The interaction can be understood in terms of energy and momentum exchange between each electron and the surrounding EM field, and the propagation of energy and momentum within the EM field. That exchange and propagation is written down mathematically as a complicated integral which cannot be done in one go, but can be expressed as a series of terms. Each term in the series involves the energy and momentum of one or more contributions to the total interaction. This contribution is often called a "virtual particle" (e.g. a "virtual photon") but you should notice (and never forget) the word "virtual" here. Virtual photons are not real photons. They are not even particles. They don't propagate like particles (their quantum amplitude decays exponentially; each one is entirely confined within one interaction), and their energy-momentum involves a combination of energy and momentum that no real photon could ever have. The entities called virtual photons are contributions to a calculation; they help us track energy and momentum and other conserved quantities such as electric charge. They are bosons (this means they have a mathematical property called commutation between certain basic operations in the mathematics). | {
"domain": "physics.stackexchange",
"id": 93601,
"tags": "quantum-field-theory, forces, particle-physics, bosons"
} |
Reccurence $T(n) = \sqrt{n}T(\sqrt{n})+n$ | Question: Note: this is from JeffE's Algorithms notes on Recurrences, page 5.
(1). So we define the recurrence $T(n) = \sqrt{n}T(\sqrt{n})+n$ without any base case. Now I understand that for most recurrences, since we're looking for asymptotic bounds, the base case wouldn't matter. But in this case, I don't even see where we could define the base case. Is there any number we are guaranteed to hit as we keep taking square roots starting from any integer Do we just define $T(n) = a$ for $n<b$, for some reals $a$, $b$?
(2). On page 7, Erickson gets that the number of layers in the recursion tree L will satisfy $n^{{2}^{-L}} = 2$. Where is this coming from? I have no idea. I see that the number of leaves in the tree should sum to $\sqrt(n)\sqrt(n) = n$, but I have no idea where to go from there.
Any help is appreciated!
Notes I'm looking at: http://jeffe.cs.illinois.edu/teaching/algorithms/notes/99-recurrences.pdf
Answer: You should really be asking a third question: what happens if $n$ isn't a perfect square. The answer to this question is that the actual recurrence should have $T(\lfloor \sqrt{n} \rfloor)$ or $T(\lceil \sqrt{n} \rceil)$ instead of $T(\sqrt{n})$, though in the analysis we will only consider inputs which are "recursive" squares.
Regarding your first question, there can be more than one base case. For example, perhaps $T(n) = 1$ for all $n \leq 100$. You are guaranteed to eventually hit this base case. In this case, as in most cases, the exact form of the base case doesn't affect the big Theta asymptotics (but it does affect the hidden constant).
Finally, regarding your second question, suppose that your base case specifies $T(n)$ for $n \leq C$. The recursion tree (which is a particular interpretation of some features of the recurrence) has the following form:
The root is one instance of size $n$.
The root has $\sqrt{n}$ children which are instances of size $\sqrt{n}$.
Each node at depth 1 has $\sqrt{\sqrt{n}} = n^{1/4}$ children which are instances of size $\sqrt{\sqrt{n}} = n^{1/8}$.
More generally, a node at depth $d$ is an instance of size $n^{1/2^d}$. You can prove this by induction by checking the case $d = 0$ (where $n^{1/2^d} = n$) and calculating $\sqrt{n^{1/2^d}} = n^{1/2^{d+1}}$.
The recursion terminates when the instance has size at most $C$, and this happens when $n^{1/2^d} \leq C$. At the point that this happens, we have $n^{1/2^{d-1}} > C$ (assuming $n > C$), and so $\sqrt{C} < n^{1/2^d} \leq C$. Taking the logarithm, $\frac{1}{2} \log C < \frac{\log n}{2^d} < \log C$ and so $\frac{\log n}{2^d} = \Theta(1)$, implying $2^d = \Theta(\log n)$. We can conclude that $d \approx \log\log n$. This is the number of layers in the tree. Jeff uses $C = 2$, which is how he gets his particular formula. | {
"domain": "cs.stackexchange",
"id": 9239,
"tags": "recurrence-relation"
} |
Generally will the power output from a heat engine increase as the work from this engine increases? | Question: Generally speaking, does increasing a heat engine's work will essentially increase the power output? Whether this heat engine was a turbine, vechile or whatever.
Answer: When we talk about the work performed by a heat engine we usually mean the work per cycle. Power output, on the other hand, is work done per unit time. So
$$\text{Power }=\frac{\text{Work per cycle}}{\text{Time per cycle}}$$
If we keep time per cycle constant then power is proportional to work per cycle. But if we vary time per cycle, we can have high work per cycle with low power or low work per cycle with high power, or any combination we like. | {
"domain": "physics.stackexchange",
"id": 82517,
"tags": "thermodynamics, ideal-gas, power, heat-engine, carnot-cycle"
} |
Can someone clarify the units for the Nernst-Einstein relation? | Question: I am using the Nernst-Einsten relation as a way to calculate the dc ionic conductivity ($\sigma_{dc}$) of a membrane:
$$\sigma_{dc} = \frac{q^2CD }{k_BT}$$
where:
$q$ is the charge on ions [Coulombs]
$C$ is concentration or number density of ions [ions/$m^3$]
$D$ is the chemical Diffusion Coefficient ($m^2$/s)
$k_B$ is Boltzman's Constant [J/K]
$T$ is Temperature [K]
The units should work out to be $S/m$ or $A/Vm$, but I can only get it down to $A*ions/Vm$.
If I instead use $q$ as Coulombs/ion, the units work out to be $A/V*m*ions$.
I've seen the formula written this way in multiple sources so I'm convinced I am missing something obvious. Can someone please enlighten me? Perhaps I am misinterpreting what the 'ions' unit means in the context of ionic conductivity.
Answer: I don't see any problem with the dimensions. Let's have a look.
$$
\begin{align}
\left[\sigma_{dc}\right]&=\frac{[q]^2[C][D]}{[k_B][T]}\\
&=\frac{C^2m^{-3}m^2s^{-1}}{JK^{-1}K}\\
&=\frac{C^2}{Jms}=\frac{C}{s}\frac{C}{Jm}\\
&=A\frac{1}{\left(J/C\right)m}\\
&=\frac{A}{Vm}=A/Vm
\end{align}
$$
The dimension is correct. The source of your error is that you used ions/$m^3$ as the dimension for concentration (number of ions per volume). All it means is that this much of ions are present in unit volume of your sample. As the number of ions is dimensionless, the dimension of concentration is $m^{-3}$. | {
"domain": "physics.stackexchange",
"id": 34076,
"tags": "units, conductors, ions"
} |
Most general Feynman diagram | Question: What is the most general Feynman diagram?
Srednicki, in his Quantum Field Theory book, says:
The most general diagram consists of a product of several connected diagrams. Let $C_I$ stand for a particular connected diagram, including its symmetry factor. A general diagram $D$ can then be expressed as
$$ D = \frac{1}{S_D} \prod_I (C_I)^{n_I}$$
where $n_I$ is an integer that counts the number of $C_I$ ’s in $D$, and $S_D$ is the additional symmetry factor for $D$ (that is, the part of the symmetry factor
that is not already accounted for by the symmetry factors already included
in each of the connected diagrams). [see eqn (9.12)]
Can anyone please explain this for me? It would be very helpful if you exemplify this.
I have another question too. Can you give me a reference where phi-cubed theory is treated as I can use it as a reference while reading Srednicki.
Answer: To explain what Srednicki is doing:
$C_i$ labels the connected diagrams with symmetry factors associated with them (individual diagrams) included, $n_i$ represents the number of diagrams $C_i$ present in the disconnected diagram $D$ and $S_D$ is an extra symmetry factor for the entire disconnected diagram due to interchange of lines between different connected graphs. Note that because we have $n_i$ copies of $C_i$ in our disconnected diagram, not only can we interchange lines in the individual diagrams due to symmetries (which has already been taken into account), but we can also change lines between diagrams of the same type, this contributes to the overall symmetry factor of the diagram. As we have $n_i$ of each $C_i$ we find $S_D = \prod_i n_i!$, so each diagram $D$ can be written as: $$D = \prod_{i}\frac{1}{n_i!}{C_i}^{n_i}$$ | {
"domain": "physics.stackexchange",
"id": 8176,
"tags": "quantum-field-theory, feynman-diagrams"
} |
Halogenation of alcohols in the presence of ZnCl2 | Question: I know that $\ce{OH-}$ is usually a bad leaving group, but why does the following reaction occur via SN1 in presence of anhydrous $\ce{ZnCl2}$?
Answer: You are right, $\ce{OH-}$ is a bad leaving group. But the $\ce{HCl}$ in the reaction mixture protonates it. Thus, the bad leaving group $\ce{OH-}$ is converted to the good leaving group $\ce{H2O}$. Anhydrous $\ce{ZnCl2}$ might additionally facilitate the reaction by acting as a Lewis acid and it binds the expelled water thus preventing the back reaction. | {
"domain": "chemistry.stackexchange",
"id": 587,
"tags": "organic-chemistry, reaction-mechanism, alcohols"
} |
How can we see stars if their apparent width is less than a pixel? | Question: Stars are so far away that their apparent width is essentially zero when compared to any pixel of a camera or TV screen.
And yet we can still see them.
According to our eyes stars have a finite albeit very small width. Why is this, and what is this width?
Answer:
Stars are so far away that their apparent width is essentially zero when compared to any pixel of a camera or TV screen.
And yet we can still see them.
In an electronic sensor (CMOS or CCD for example), the pixel sums all the light that reaches it. Even if light only falls on a small part of the actual sensitive area of the pixel, it will generate photocurrent that the camera will record as part of the image.
Of course if the image of the star on the sensor is small enough, it might fall in a gap between the pixels. But there are also resolution limits to the optics forming the image that generally prevent this being an issue.
According to our eyes stars have a finite albeit very small width. Why is this, and what is this width?
This is the resolution limit of our eyes, determined mainly by diffraction from the aperture of the pupil of the eye. | {
"domain": "physics.stackexchange",
"id": 51931,
"tags": "stars, vision"
} |
Basic index question on tensor calculus | Question: after some calculations I obtain the next expression
$$\lambda^{c}\nabla_{a}g_{bc}=\lambda^{c}{}(\lambda_{c}\nabla_{a}\lambda_{b}-g_{be} \Gamma^{e}_{ad}\lambda^{d}\lambda_{c}) $$
So my question is if I can eliminate $\lambda^{c}$ of this equation, and get something like this
$$\nabla_{a}g_{bc}=\lambda_{c}\nabla_{a}\lambda_{b}-g_{be} \Gamma^{e}_{ad}\lambda^{d}\lambda_{c} $$
Answer: It depends on what $\lambda$ is. If the first equation is true for all $\lambda\in\mathbb{R}^n$, then the second equation follows. However, if it is true for a single $\lambda$, then from $\lambda^a A_a = \lambda^a B_a$ you can only conclude that $$A_a = B_a + k_a$$ for some $k\in\text{ker}(\lambda):=\{v\in\mathbb{R}^n \mid \lambda^a v_a = 0\}$. Thus, you can only specify the equation up to a term sent to zero when "applying" $\lambda$.
Cheers! | {
"domain": "physics.stackexchange",
"id": 67049,
"tags": "general-relativity, differential-geometry, differentiation, vector-fields"
} |
Understanding a diagram of Earth's radiation balance | Question:
Trying to understand this image. Can someone tell me if I have the right reasoning here:
Sun has 100% SW shooting to earth
30% of that 100% is reflected by clouds
70% remains
Of that 70%, 45% of that SW is absorbed by Earth's surface.
That leaves 25%, where does that go/factored into?
The entire right half of this diagram confuses me, what is happening there? Why is there a red line connecting 70%SW and 70%LW? What does "??%LW" mean?
Thank you
Answer: LW = Longwave radiation (i.e. Infrared radiation)
SW = Shortwave radiation (i.e. Visible + Ultraviolet light)
For the left part of the diagram, it shows that the 30% of the total incoming energy (mostly delivered as shortwave radiation) gets reflected by clouds and the Earth's surface. Therefore, 70% is the total absorbed by the planet (45% of it is absorbed by the Surface and 25% by the atmosphere).
The red line refers to the fact that given that Earth energy budget is assumed to be in balance, meaning that the same amount of energy that goes IN the system (as shortwave radiation) must go OUT the system, in the form of longwave radiation, that is the main kind of radiation the Earth emits given its temperature (see Wien's law). This energy balance assumption is a good one, because even if you think that more energy gets IN than OUT, that would lead Earth's temperature to increase, increasing then the amount of emitted energy (according to Stefan–Boltzmann law), until it reaches a point where the outgoing radiation released equals the amount received energy from the Sun. Therefore, establishing the energy balance.
Due to this balance, the right part of the diagram shows that the same 70% of the energy must be emitted back to space as longwave radiation (the same amount that was absorbed), and for that to be true, it is asking you what would be the required amount of energy that the atmosphere must emit towards Earth as LW radiation to keep the system in balance. Or at least that's my interpretation of the question marks in the absence of further information. | {
"domain": "earthscience.stackexchange",
"id": 1365,
"tags": "atmosphere, climate-change, climate, climate-models, atmospheric-radiation"
} |
Getting stuck trying to solve electromagnetic wave equation using Green's function | Question: I've recently learned about Green's function and am trying to derive an equation similar to that of the Biot-Savart law but for the electric field around a wire of changing current using the electric component of the electromagnetic wave equation:
$$\frac{\partial^2 E}{\partial t^2} = c^2\nabla^2E -c^2\mu_0 \frac{\partial J}{\partial t}$$
However, I am getting stuck on a step involving a dirac delta function in an integral and I'm not sure how to proceed next. Here are my steps:
Rewrite the wave equation so that we can use a Green's function for the 3-D wave equation:
$$\frac{1}{c^2}\frac{\partial^2 E}{\partial t^2}-\nabla^2E=-\mu_0 \frac{\partial J(t)}{\partial t}$$
From Wikipedia, the green's function is:
Resulting in the following equation to find $E$,
$$E=\int\limits_{\mathbb{R}^3}G(x)f(x) dr^3=-\frac{\mu_0}{4\pi}\int\limits_{\mathbb{R}^3}\frac{\delta^{3}(t-r/c)}{r}\cdot\frac{\partial J(t)}{\partial t}dr^3$$
At this point I'm a bit stuck, I'm not sure how to deal with the dirac delta inside the integral. One step I have tried is rewriting the current density of a thin wire as $J=I\cdot\delta_2(r)$,
$$E=-\frac{\mu_0}{4\pi}\int\limits_{\mathbb{R}^3}\frac{\delta_3(t-r/c)}{r}\cdot\frac{\partial I(t)}{\partial t}\delta^{2}(r)\cdot dr^3$$
Letting us rewrite the equation as a line integral, similar to how the Biot-Savart law is written,
$$E=-\frac{\mu_0}{4\pi}\int\limits_{a}\limits^{b} \left[ \iint \frac{\delta_3(t-r/c)}{r}\cdot\frac{\partial I(t)}{\partial t}\delta^{2}(r)\cdot dr^2 \right] dl$$
$$=-\frac{\mu_0}{4\pi}\int\limits_{a}\limits^{b} \frac{\delta^{3}(t-r/c)}{r}\cdot\frac{\partial I(t)}{\partial t} dl$$
But after this I'm completely lost. Based on Jefimenko's equations I need to get something like,
$$=-\frac{\mu_0}{4\pi}\int\limits_{a}\limits^{b} \frac{1}{r} \cdot \frac{\partial I(t-r/c)}{\partial t} dl$$
Which does seem to give the correct behavior, but I'm not exactly sure how multiplying $I(t)$ with a dirac-delta results in $I(t-r/c)$. I've tried finding a property that results in this, but I can't find anything.
I think I'm missing a step or doing something wrong. Because I'm a newbie in Green's functions and just this area of math in general, I would really appreciate an easy to understand answer. But really any help would be appreciated.
Answer: General considerations
I think it will help to carefully write out all the expressions. The PDE should be read component-wise
$$
\partial_{tt}\psi_j(x,t)-\nabla^2\psi_j(x,t)=F_j(x,t)
$$
Where $x\in\mathbb{R}^3$. I've replaced $J$ with a generic source $\mathbf{F}$, $\mathbf{E}$ with a generic field $\boldsymbol{\psi}$, and set all constants to unity. The causal Green's function is
$$
G(r,t)=\frac{\delta(t-r)}{4\pi r}
$$
The solution for $\psi_j$ is
$$
\psi_j(x,t)=\int dt' \int d^3x' \ G(x-x',t-t')F_j(x',t') \ \ + \ \ \text{surface terms}
$$
The surface terms are to match initial conditions which we can specify to vanish (see eg. Zangwill Modern Electrodynamics chapter 20). The delta collapses the $t'$ integral and we are left with
$$
\psi_j(x,t)=\frac{1}{4 \pi}\int d^3x' \ \frac{F_j(x',t-|x-x'|)}{|x-x'|}
$$
Note the arguments of the source appearing in the integrand.
The wave equation for $E$
Because $J$ and $\rho$ form part of a continuity equation, they cannot be specified completely independently. For $\psi=E$, the source should be $F_j=-(\partial_t J_j+\partial_j \rho)$, not just $\partial_t J$. You can check this by deriving it from Maxwell's equations. The expression for $E$ is
$$
E_j(x,t)=-\frac{1}{4\pi} \int d^3x' \ |x-x'|^{-1} \bigg[\partial'_{j} \rho(x',t-|x-x'|) \ + \ \partial'_{t}J_j(x',t-|x-x'|) \bigg]
$$
Note the primes on partial derivatives within the integral: the retarded time is $t_r:=t-|x-x'|$. You can see why it's preferable to write the integral as
$$
E_j(x,t)=-\frac{1}{4\pi} \int d^3x' \ |x-x'|^{-1} \bigg[\partial'_{j} \rho(x',t') \ + \ \partial'_{t}J_j(x',t') \bigg]_{t'=t_r}
$$
With $R_j:=x_j-x_j'$, and using the multivariate chain rule we find (Jackson chapter 6.5)
$$
\big[\partial'_j \rho(x',t') \big]_{t'=t_r} = \partial'_j \big[ \rho(x',t')\big]_{t'=t_r} - \hat{R} \big[ \partial'_t \rho(x',t')\big]_{t'=t_r}
$$
On integrating the term $|x-x'|^{-1}\partial'_j \big[ \rho(x',t')\big]_{t'=t_r}$ by parts, we find Jefimenko's equation for $E_j$.
Finally, if you want to specify a thin wire of arbitrary shape, the expression is not as simple as you may think. Start by parametrizing in $\tau$ such that the wire is the set of points $(x,y,z)=(p_1(\tau),p_2(\tau),p_3(\tau))$, then (up to a proportionality constant)
$$
J_j(\mathbf{x})= \int d\tau \ \frac{dp_j}{d\tau} \delta^{(3)}(\mathbf{x}-\mathbf{p}(\tau))
$$ | {
"domain": "physics.stackexchange",
"id": 84286,
"tags": "electromagnetism, waves, electromagnetic-radiation, greens-functions, dirac-delta-distributions"
} |
How to calculate the total resistance? | Question: So I am new to physics and I am trying to solve the total resistance of this circuit. My question is: because there is a battery in the same branch as R2 and a Capacitor in the same branch as R3, when calculating the Total resistance all the resistance should be R1//R2//R3, because there is no way to simplify the resistors?
Answer: Thévenin's theorem can be applied here. Essentially, in the equivalent circuit for calculation of time constant, short-circuit the EMF sources and treat the two ends of the capacitor as the entry and exit point of current. In your case:
Now calculate the equivalent resistance between A and B. | {
"domain": "physics.stackexchange",
"id": 97232,
"tags": "homework-and-exercises, electric-circuits, electrical-resistance, capacitance, batteries"
} |
C++ - Astar search algorithm using user defined class | Question: The objective of the post is to improve design and improve command on C++. Given a map, start point and end point, the shortest path to end point from the start point has to be found out using Astar (A*) algorithm. The algorithm uses an evaluation function f for each point or node in the map. The f depends on g and h. The g is distance from start point to the point under consideration(current point in the path). The h is a heuristic which provides an (under)estimate of the distance from current point to end point. The frontier is a set that contains all candidate points to form the path. The pseudocode/ algorithm:
1) The values of f, g and h for all points are initially set to infinity (a very high value);
2) The start point is assigned a g of 0 and its h is calculated using Manhattan distance. This is then inserted to the frontier. The end point is assigned an h of 0.
3) Until frontier is empty, do:
a) Extract the point (current point) with lowest f value from the frontier.
b) Check if it is the end point. If yes, report success. Else, continue.
c) Collect all the eligible neighbors of the current point and add them to the frontier. During this addition, their f, g, h and parent are updated.
d) Remove the current point from frontier.
4) If success is not reported in (3), report failure.
Here is the commented code:
#include <iostream>
#include <vector>
#include <stdexcept>
#include <set>
#include <algorithm>
// Class to handle individual nodes/ points/ location in the environment map
class Point
{
// The x coordinate of the point
int x_v = {-1};
// The y coordinate of the point
int y_v = {-1};
// The value at the point; either 1 or 0
int val_v = {0};
// The total estimated cost of a point; A star uses this value
double f_v = {100000};
// The cost to reach a point; A star uses this value
double g_v = {100000};
// The estimate of cost (heuristic) to reach end from current point; A star uses this value
double h_v = {100000};
// The parent of Point set by Astar so that path from start to end can be retrieved
Point* parent_v = nullptr;
public:
Point()
{}
Point(int xx, int yy, int vv) : x_v{xx}, y_v{yy}, val_v{vv}
{}
// Copy constructor
Point(const Point& p1)
{
x_v = p1.x();
y_v = p1.y();
val_v = p1.val();
f_v = p1.f();
g_v = p1.g();
h_v = p1.h();
parent_v = p1.parent();
}
~Point(){}
int val() const
{
return val_v;
}
int x() const
{
return x_v;
}
int y() const
{
return y_v;
}
double f() const
{
return f_v;
}
double g() const
{
return g_v;
}
double h() const
{
return h_v;
}
Point* parent() const
{
return parent_v;
}
void set_g(double g)
{
g_v = g;
f_v = g_v + h_v;
}
void set_h(double h)
{
h_v = h;
f_v = g_v + h_v;
}
void set_parent(Point* p)
{
parent_v = p;
}
// Assignment operator
Point& operator=(const Point& p1)
{
x_v = p1.x();
y_v = p1.y();
val_v = p1.val();
f_v = p1.f();
g_v = p1.g();
h_v = p1.h();
parent_v = p1.parent();
return *this;
}
//This operator has been defined so that std::set can use it as comparison object
friend bool operator<(const Point& p1, const Point& p2)
{
if(p1.x() < p2.x())
{
return true;
}
if(p1.x() == p2.x() && p1.y() < p2.y())
{
return true;
}
return false;
}
friend bool operator==(const Point& p1, const Point& p2)
{
return (p1.x() == p2.x()) && (p1.y() == p2.y());
}
friend bool operator!=(const Point& p1, const Point& p2)
{
return !(p1 == p2);
}
};
// Class to perform A star
class Astar
{
// The map of the environment
std::vector<std::vector<Point>> map_v;
// The size of the map
int map_x = {0};
int map_y = {0};
// The start and end points
Point* start_v;
Point* end_v;
// The variable to store path from start to end
std::vector<Point*> path_v;
public:
Astar(std::vector<std::vector<int>>&, std::pair<int, int>&, std::pair<int, int>&);
bool is_valid(int, int);
double manhattan(Point*);
bool search();
std::vector<Point*> path();
};
// Constructor that takes in map, start and end from the user/ main and converts it into variables of the class
Astar::Astar(std::vector<std::vector<int>>& map, std::pair<int, int>& start, std::pair<int, int>& end)
{
// Check and note down sizes
map_y = map.size();
if(map_y)
{
map_x = map[0].size();
}
if(map_x == 0 || map_y == 0)
{
throw std::invalid_argument{"The map is invalid!\n"};
}
// Create a map of Points
for(int i = 0; i < map_y; i++)
{
map_v.push_back(std::vector<Point>(map_x));
for(int j = 0; j < map_x; j++)
{
map_v[i][j] = Point(j, i, map[i][j]);
}
}
// Assign start and end
start_v = &map_v[start.first][start.second];
end_v = &map_v[end.first][end.second];
if(!is_valid(start_v -> x(), start_v -> y()))
{
throw std::invalid_argument{"Start point is invalid!\n"};
}
if(!is_valid(end_v -> x(), end_v -> y()))
{
throw std::invalid_argument{"End point is invalid!\n"};
}
}
// Check if a Point lies within boundaries of the map and if it is free space
bool Astar::is_valid(int x, int y)
{
if(x >= 0 && x < map_x && y >= 0 && y < map_y && map_v[y][x].val() == 0)
{
return true;
}
return false;
}
// Calculate Manhattan distance as a hueristic
double Astar::manhattan(Point* p)
{
return std::abs(p -> x() - end_v -> x()) + std::abs(p -> y() - end_v -> y());
}
// Perform the actual search
bool Astar::search()
{
// Create a frontier and insert the start node
std::set<Point*> frontier;
end_v -> set_h(0);
start_v -> set_g(0);
start_v -> set_h(this -> manhattan(start_v));
frontier.insert(start_v);
// As long as there are points in the frontier or until the end point is reached, the search continues
while(!frontier.empty())
{
// Find the Point with minimum value of f_v
auto curr_point = *(std::min_element(frontier.begin(), frontier.end(), [](const Point* p1, const Point* p2){return p1 -> f() < p2 -> f();}));
// If it is the end point, return success
if(*curr_point == *end_v)
{
std::cout << "Success!\n";
return true;
}
// Otherwise, find the eligible neighbors and insert them into frontier
int x = curr_point -> x();
int y = curr_point -> y();
std::vector<Point*> neighbors;
if(this -> is_valid(x, y - 1))
{
neighbors.push_back(&map_v[y - 1][x]);
}
if(this -> is_valid(x, y + 1))
{
neighbors.push_back(&map_v[y + 1][x]);
}
if(this -> is_valid(x + 1, y))
{
neighbors.push_back(&map_v[y][x + 1]);
}
if(this -> is_valid(x - 1, y))
{
neighbors.push_back(&map_v[y][x - 1]);
}
// Add neighbors to frontier if their g value is higher than necessary
// Update g, h (and f). Also set their parent.
for(auto& neighbor : neighbors)
{
if(neighbor -> g() > curr_point -> g() + 1)
{
neighbor -> set_g(curr_point -> g() + 1);
neighbor -> set_h(this -> manhattan(neighbor));
neighbor -> set_parent(curr_point);
frontier.insert(neighbor);
}
}
// Remove the current Point
frontier.erase(curr_point);
}
// If end point is not reached, report failure
std::cout << "Failure!\n";
return false;
}
// Retrieve the path and return it
std::vector<Point*> Astar::path()
{
auto p1 = end_v;
while(p1 != nullptr)
{
path_v.insert(path_v.begin(), p1);
p1 = p1 -> parent();
}
return path_v;
}
int main()
{
// Map of the environment to navigate
std::vector<std::vector<int>> mv = {{1, 0, 0, 1, 0, 0, 0, 0},
{0, 1, 0, 1, 1, 0, 0, 1},
{1, 0, 0, 0, 0, 0, 1, 0},
{0, 0, 1, 0, 0, 0, 0, 0},
{1, 0, 1, 0, 1, 1, 1, 1},
{0, 0, 0, 0, 0, 1, 0, 1},
{0, 0, 0, 0, 0, 1, 1, 0},
{0, 1, 0, 1, 0, 0, 0, 1}};
// The start and end points
std::pair<int, int> start = {5, 2};
std::pair<int, int> end = {2, 5};
// Create search object and perform search
Astar astar1{mv, start, end};
auto success = astar1.search();
// If search is successful, print the path
if(success)
{
auto path = astar1.path();
std::cout << "The result path: \n";
for(auto p : path)
{
std::cout << "{ " << p -> y() << ", " << p -> x() << "}" << "\t";
}
std::cout << "\n";
}
return 0;
}
1) In the above code, the user/ main provides input map via a std::vector<std::vector<int>> and it is converted to std::vector<std::vector<Point>>. The Point is a user defined class capable of handling a lot of operations. In the above code, the class Astar is responsible for conversion of the map into required type. Is this bad design? How can I can do it more elegantly without loosing the advantages of Point class? Suggestions for better data structures are welcome.
2) Comments on operator overloading, copy constructor etc. used in Point.
3) Are there any parts that are very inefficient? Any other suggestions, advice or improvements?
Answer: A std::vector<std::vector<int>> is an inefficient way to store a 2-dimensional array. Unfortunately, there is nothing in the standard C++ library that gives you an easy and safe 2-dimensional array.
However, in your case, in main() you could easily convert mv into a straightforward 2D array, like so:
int mv[8][8] = {{...same as you already have...}};
But then you'd have to pass both a pointer to that array and its dimensions to any class/function that uses it. It is not too hard to write a 2D array class yourself though, or search for some external library that implements one for you. Or stick with this for now.
As for the design with the classes Point and Astar, comments on overloading and so on, and other suggestions, see below.
Unnecessary hiding of variables
If you have a class that has variables that you should be able to read and set at will, and there are no side-effects or restrictions, then why not make them public? It saves you writing lots of getters and setters. So:
class Point {
public:
int x = -1;
int y = -1;
...
};
Or just write struct Point, which will make everything public by default.
Don't use initializer lists unnecessarily
It looks like you are mixing two styles of default initialization of member variables. You should either write:
int x = -1;
Or:
int x{-1};
What you write is actually an initializer list of one element.
Don't write an operator/constructor/destructor if it's equivalent to the default one
Your copy constructor does exactly what the default copy constructor would do, so there is no point in writing it out. It is only a potential source of errors and inefficiencies.
The same also applies to the destructor and the assignment operator.
Consider making Point part of Astar
Your Point class is specifically made for the A* algorithm. It then makes sense have it part of the namespace of the Astar class. Just move it inside the latter:
class Astar {
public:
class Point {
...
};
...
};
However, the class Astar is problematic in itself:
Don't conflate the algorithm and its input
Your class Astar is both the map and the methods to perform the A* algorithm. In a real application, the map is some datastructure used by many algorithms, and you want the A* algorithm to work on that datastructure. So it is much more natural to have a class Map, and a function Astar(...) that takes a Map, and the start and endpoints as arguments, and returns the resulting path.
Have a single function that calculates and returns a path
Your class requires you to do things in three stages:
construct Astar and have it copy the map data
call search() to have it calculate the path
call path() to retrieve the path
This is quite cumbersome. You typically want a single function that performs all these steps in one go, something that looks like:
std::vector<Point> Astar(const Map &map, const Point &start, const Point &end);
And those Points there should just be something that looks like std::pair<int, int>, and not contain any of the variables used by the A* algorithm internally.
The above function can signal that it didn't find a path by returning an empty vector.
Avoid returning raw pointers
Your function path() returns a std::vector<Point *>. It looks like a return by value, but this vector contains raw pointers to the data held by a variable of class Astar. However, you now introduce a potential issue: if the class Astar variable goes out of scope, the path vector now points to invalid memory. There are several solutions to this:
Return a pointer/reference to the vector inside class Astar (this still can be problematic, but now it is much more clear that it is just a pointer)
Return a deep copy (std::vector<Point>)
Use std::shared_ptr()
Avoid writing this->foo
Just write foo directly. For example, in Astar::search(), just call is_valid(x, y) instead of this->is_valid(x, y).
Minor style issues
You are putting spaces around the -> operator, but not around .. It is very uncommon to do that, just write foo->bar without spaces.
Instead of map_x and map_y, write width and height. When iterating over the map coordinates, use x and y as iterators instead of i and j. | {
"domain": "codereview.stackexchange",
"id": 32289,
"tags": "c++, object-oriented, constructor, overloading, a-star"
} |
Wave packet expression and Fourier transforms | Question: I read in the Wikipedia article on wave packets that a wave packet is defined as:
$$ \psi(x,t)=\frac{1}{\sqrt{2\pi}}\int_{-\infty}^{+\infty}g(k)e^{i(kx-\omega t)}\mathrm dk\tag a $$
where
$$ g(k)=\frac{1}{\sqrt{2\pi}}\int_{-\infty}^{+\infty}\psi(x,0) e^{-ikx}\mathrm dx\tag b$$
Now I'd like to understand mathematically where these formulas come from.
As an initial example, if you put $t=0$ in $\rm (a)$, you obtain
$$\psi(x,0)=\frac{1}{\sqrt{2\pi}}\int_{-\infty}^{+\infty}g(k)e^{ikx}\mathrm dk\tag c$$
and
$$ g(k)=\frac{1}{\sqrt{2\pi}}\int_{-\infty}^{+\infty}\psi(x,0) e^{-ikx}\mathrm dx,\tag d$$
and these last two formulas are clear $-$ it is the Fourier reverse transform theorem.
However, I don't understand where $\rm (a)$ comes from. I thought that maybe $(a)$ was expressed as the Fourier reverse transform of the function of the two variable $\psi(x,t)$, but in this case I obtain
$$ \psi(x,t)=\frac{1}{{2\pi}}\iint_{R^{2}}{\mathcal{F}[\psi(x,t)](w,k)} e^{i(kx+\omega t)}\:\mathrm dk\:\mathrm d\omega, \tag e$$
which is different from $\rm (a)$. So, finally, my question is: where does $\rm (a)$ comes from?
Answer: When we write down a wavepacket, we're trying to solve the following problem: Given an initial profile for our wavepacket, $\psi(x,0)$, what will it look like in the future? In other words, we want to find $\psi(x,t)$ given $\psi(x,0)$. To solve this problem, we need to have some wave equation that tells us how the wavepacket evolves in time. For different waves in different contexts, we'll have different wave equations. But we'll assume two things about the wave equation:
It is linear. This means that if $\psi_1(x,t)$ is a solution and $\psi_2(x,t)$ is a solution, then $a_1\psi_1(x,t)+a_2\psi_2(x,t)$ is a solution. Generalizing, it means that if $\psi_k(x,t)$ is a solution, so is $\int dk\ a_k\psi_k(x,t)$.
If we start with an initial profile $\psi(x,0)=e^{ikx}$, then the solution to our wave equation is $\psi(x,t)=e^{i(kx-\omega_k t)}$, where $\omega_k$ is a constant that may depend on $k$.
You can check for yourself that generic wave equations, such as the equation for a wave on a string, or the Schrodinger equation, satisfy these properties. Now, once we know the wave equation has these properties, we can solve our problem!
First, we realize that by property (2), all functions of the form $e^{i(kx-\omega_k t)}$ are solutions to our wave equation. That means that, by property (1), any linear combination of these functions is also a solution to our wave equation. So we can write down a guess for the solution:
$$
\psi(x,t)=\frac{1}{\sqrt{2\pi}}\int dk\ g(k)e^{i(kx-\omega_kt)}
$$
So far, $g(k)$ is just some unknown function. Any choice of $g(k)$ will give a solution to the wave equation, by properties (1) and (2). But we also need our solution to match with our initial profile, $\psi(x,0)$. Plugging in $t=0$ thus gives a condition on $g(k)$:
$$
\psi(x,0)=\frac{1}{\sqrt{2\pi}}\int dk\ g(k)e^{ikx}
$$
By Fourier's theorem, we can then immediately find the $g(k)$.
$$
g(k)=\frac{1}{\sqrt{2\pi}}\int dx\ \psi(x,0)e^{-ikx}
$$ | {
"domain": "physics.stackexchange",
"id": 42417,
"tags": "quantum-mechanics, wavefunction, fourier-transform"
} |
Specifics of decussation | Question: Beginner question here:
The definition of decussation I see is the crossing through the midline of a bunch of neurons. But I was wondering if there was a little more to it than this, because I'm given the impression in readings that this is a somewhat difficult task to perform developmentally, like the body might have to take extra effort to regulate the crossing so that the neurons do not interfere. So when nerves from both eyes cross, for example, do they pass AROUND each other or do the bundles of nerves all weave through each other?
Thanks in advance.
Answer: The optic nerve fibers cross inside the optic chiasm sharing the same shell:
The crossing fibers go ones between others, like on this classical picture - | {
"domain": "biology.stackexchange",
"id": 2127,
"tags": "neuroscience, human-anatomy, neuroanatomy"
} |
Question about capacitance on a double cylinder | Question: I had an exercise that I am struggling to solve, I have 2 concentric metal surfaces with $R_1= 1 \,\text{cm}$ and $R_2 = 2 \,\text{cm}$.
The cylinders have infinite extension along the direction normal to the paper and placed in free space.
The inner cylinder carries a charge of $Q_1 = 5 \,\text{mC}$ per meter length, and the outer cylinder carries a charge of $2 = −5 \,\text{mC}$ per meter length.
I need to calculate the capacitance per meter length of the double-cylinder structure.
I tried by going with the formula of capacitance since I know the magnitude of $Q$ and I could calculate the voltage across the 2 surfaces of the cylinders but I started getting weird numbers and I kind of got lost.
I added a picture of the whole exercise and the scheme as well.
Do you have any suggestions on how to solve this question?
Answer: Probably there are smarter ways to solve this problem, but I would do the following
Use Gauss law to compute the electric field between the cylinders. Let me define the linear charge density $\lambda = Q/l = 5\,m\mbox{C}/\mbox{m}$.
Let me remember that Gauss law states that the flux of the electric field across a surface $S$ is equal to the total charge inside the surface, divided by $\epsilon_0$ (as I guess there is nothing between the cylinders), i.e.
\begin{equation}
\Phi_S(\textbf{E}) = \frac{Q_{in}}{\epsilon_0}
\end{equation}
Given the geometry of the system, we can imagine that the electric field between the cylinders is directed radially and is symmetrical for rotations around the central axis of the system. If we make the smart choice of considering $S$ as a cylinder with radius $r$ coaxial with the metal surfaces, we have that the flux $\Phi_S(\textbf{E})$ simply becomes
\begin{equation}
\Phi_S(\textbf{E}) = \int_{S(r)}\textbf{E}(r)\cdot d\textbf{S}= E(r) 2\pi r l
\end{equation}
I would like to point out that the flux across the basis of the cylinder $S$ is zero.
Computing the charge inside $S$ is super easy as well, as we knon the linear charge density $\lambda$
\begin{equation}
Q_{in} = \lambda l
\end{equation}
Therefore, plugging in the last two expressions into the Gauss law, we end up with
\begin{equation}
E(r) 2\pi r l = \frac{\lambda l }{\epsilon_0}
\end{equation}
Thence, the radial (and only component) of the electric field inside the double cylinder is
\begin{equation}
E(r) = \frac{\lambda}{2\pi\epsilon_0r}\qquad\mbox{for}\qquad R_1\le r\le R_2
\end{equation}
I compute now the potential difference $\Delta V$ between the outer and inner cylinder
\begin{equation}
\Delta V = \int_{R_1}^ {R_2} E(r)\,dr = \frac{\lambda}{2\pi\epsilon_0}\int_{R_1}^ {R_2} \frac{1}{r}\,dr = \frac{\lambda}{2\pi\epsilon_0}\ln\left(\frac{R_2}{R_1}\right)
\end{equation}
I use the definition of capacitance
\begin{equation}
C = \frac{Q}{\Delta V} = 2\pi\epsilon_0\frac{\lambda l}{\lambda\ln\left(\frac{R_2}{R_1}\right)}=2\pi\epsilon_0\frac{l}{\ln\left(\frac{R_2}{R_1}\right)}
\end{equation}
Finally the capacitance per unit length is
\begin{equation}
\mathcal{C} = \frac{C}{l} = \frac{2\pi\epsilon_0}{\ln\left(\frac{R_2}{R_1}\right)}
\end{equation} | {
"domain": "physics.stackexchange",
"id": 66545,
"tags": "homework-and-exercises, electrostatics, electric-fields, capacitance"
} |
Feed API to display RSS feeds Ted talk | Question: I am trying to create a webpage that will read RSS feeds from the TED talk website and display it on a page. I am using Google's Feed API for this.
Here is the link to view the code online.
Could someone please tell me if there is a better way to display the data coming from the feed?
HTML
<!DOCTYPE html>
<!-- To change this license header, choose License Headers in Project Properties. To change this template file, choose Tools | Templates and open the template in the editor. -->
<head>
<title>TED Talks Google Feed API</title>
<link href='http://fonts.googleapis.com/css?family=Raleway' rel='stylesheet' type='text/css'>
<script src="js/main.js" type="text/javascript"></script>
<script src="js/jquery.js" type="text/javascript"></script>
<link href="css/main.css" rel="stylesheet" type="text/css"/>
<script src="js/google.js" type="text/javascript"></script>
</head>
<body style="font-family: Arial;border: 0 none;">
<h1>Welcome to the Ted talks Feed</h1>
<div id="dialog" title="Basic dialog"></div>
<div id="content">
<div class="inner">
</div>
</div>
</body>
Feed API (JavaScript)
google.load("feeds", "1");
// Our callback function, for when a feed is loaded.
function feedLoaded(result) {
if (!result.error) {
for (var i = 0; i < result.feed.entries.length; i++) {
var entry = result.feed.entries[i];
var link = '<a target=_blank; href="' + entry.link + '">' + 'View on Ted.com' + '</a>';
var image = result.feed.entries[i].mediaGroups[0].contents[0].thumbnails[0].url;
$(".inner").append('<div class="innerdetail viewmore" data-num="'+ i +'"> <img class="thumbnail" title="Click to view more" src="'+ image +'"/> <p class="title">'+ entry.title +' </p> <p class="snippet">' + entry.contentSnippet + '</p>'+ link + ' </div>');
}
//On click of the thumbnail(Image), we will display more data with more metadata.
$(".thumbnail").click(function() {
//Removing all arrows before initializing
$(".arrow-up").remove();
var parentClass = $(this).parent();
//Checking to see if the parent class already is expanded or not
if ($(parentClass).hasClass( "expandedMain" ) ) {
$("div").removeClass("expandedMain");
$(".expandedView").remove();
$(".arrow-up").remove();
}
else{
$(".arrow-up").show();
$("div").removeClass("expandedMain");
$(this).parent().addClass("expandedMain");
var plant = $(this).parent();
var DataCount = plant[0].dataset.num;
var entry = result.feed.entries[DataCount];
//Appending the cideo in a variable for use later
var video = '<video class="video" width="480" height="320" controls> <source src="'+ entry.mediaGroups[0].contents[0].url +'" type="video/mp4"></video>';
$(plant).append('<div class="arrow-up"></div> <div class="expandedView" data-category="'+ entry.categories[0] +'"><p class="title">'+ entry.title +' </p>' + video + '<p class="publishedDate">Published Date:'+ entry.publishedDate +' <p> <p class="fullcontent">' + entry.content + '</p></div>');
$(".expandedView").show(1000);
}
});
}
}
//On Load event
function OnLoad() {
var feed = new google.feeds.Feed("http://feeds.feedburner.com/tedtalks_video");
feed.includeHistoricalEntries(); // tell the API we want to have old entries too
feed.setNumEntries(250); // we want a maximum of 250 entries, if they exist
// Calling load sends the request off. It requires a callback function.
feed.load(feedLoaded);
}
google.setOnLoadCallback(OnLoad);
CSS:
h1{
text-align: center;
font-family: 'Raleway', arial, sans-serif;
}
a{
font-family: 'Raleway', arial, sans-serif;
font-size: 0.75em;
}
#content{
background: #e1e1e1;
width: 100%;
height: 100%;
display: block;
margin: 0 auto;
}
.thumbnail{
width: 100%;
max-width: 200px;
display: block;
height: 100%;
max-height: 150px;
cursor: pointer;
}
.innerdetail{
width: 200px;
display: inline-table;
height: auto;
margin: 1em;
border: 1px solid lightgray;
box-shadow: 0px 0px 2px black;
padding: 1em;
background-color: ghostwhite;
}
.title, .publishedDate{
font-size: 14px;
font-family: 'arial', sans-serif;
}
.snippet, .fullcontent{
font-size: 12px;
font-family: 'arial', sans-serif;
}
.expandedView{
width: 100%;
background-color: #ffffff;
height: auto;
left: 0px;
position: absolute;
transition: 1s ease;
box-sizing: border-box;
padding: 1em;
z-index: 1000;
cursor: default;
display: none;
box-shadow: inset 0px 0px 2px black;
}
.expandedView .title, .expandedView .publishedDate{
text-align: center;
}
.expandedView .title{
font-size: 16px;
font-family: 'Raleway', arial, sans-serif;
font-weight: bold;
margin: 0 auto;
}
.expandedMain{
height: 600px;
}
.video{
display: block;
margin: 0 auto;
z-index: 100;
}
.inner{
position: relative;
height: 100%;
width: 100%;
z-index: 1;
}
.close{
z-index: 1001;
cursor: pointer;
position: absolute;
top: 0;
right: 0;
}
.arrow-up {
width: 0;
height: 0;
border-left: 10px solid transparent;
border-right: 10px solid transparent;
border-bottom: 10px solid gray;
}
Answer: There are a couple things you could improve here. First, you should specify a character encoding for the document, like this:
<head>
<meta charset="utf-8">
<title>Page Title</title>
</head>
Next, your indentation is erratic:
<!DOCTYPE html>
<!-- To change this license header, choose License Headers in Project Properties. To change this template file, choose Tools | Templates and open the template in the editor. -->
<head>
<title>TED Talks Google Feed API</title>
<link href='http://fonts.googleapis.com/css?family=Raleway' rel='stylesheet' type='text/css'>
<script src="js/main.js" type="text/javascript"></script>
<script src="js/jquery.js" type="text/javascript"></script>
<link href="css/main.css" rel="stylesheet" type="text/css"/>
<script src="js/google.js" type="text/javascript"></script>
</head>
<body style="font-family: Arial;border: 0 none;">
<h1>Welcome to the Ted talks Feed</h1>
<div id="dialog" title="Basic dialog"></div>
<div id="content">
<div class="inner">
</div>
</div>
</body>
This should be indented like this:
<!DOCTYPE html>
<!-- To change this license header, choose License Headers in Project Properties. To change this template file, choose Tools | Templates and open the template in the editor. -->
<head>
<title>TED Talks Google Feed API</title>
<link href='http://fonts.googleapis.com/css?family=Raleway' rel='stylesheet' type='text/css'>
<script src="js/main.js" type="text/javascript"></script>
<script src="js/jquery.js" type="text/javascript"></script>
<link href="css/main.css" rel="stylesheet" type="text/css"/>
<script src="js/google.js" type="text/javascript"></script>
</head>
<body style="font-family: Arial;border: 0 none;">
<h1>Welcome to the Ted talks Feed</h1>
<div id="dialog" title="Basic dialog"></div>
<div id="content">
<div class="inner"></div>
</div>
</body>
The indentation on your CSS and JS is also erratic.
One excellent thing is that your HTML and CSS validates to the W3C validators:
HTML Validator
CSS Validator
Your JS does not validate at JSLint because your indentation is off. | {
"domain": "codereview.stackexchange",
"id": 11674,
"tags": "javascript, jquery, css, html5, rss"
} |
Derivation of isobaric heat capacity | Question: As I was thinking about isobaric processes, one thing came to mind: In a reversible isobaric process, the value of Cp (molar isobaric heat capacity) is bigger than Cv (molar isochoric heat capacity) by exactly one R (ideal cas constant). For example, for argon, Cp is 2.5R while for Cv it is 1.5R.
This is due to the derivation, where under the pV integral, pV can be substituted by RT for one mole of the gas. This is only possible though, if the gas is in equilibrium with the outside pressure the whole time:
https://en.m.wikipedia.org/wiki/Isobaric_process
So my question is, would the value of the molar isobaric heat capacity change, if we applied an irreversible isobaric change?
That is, the gas is heated much more quickly that it can expand, so that the pressure in the gas is higher than the outside pressure on the piston, so that the gas and outside pressure are not in equilibrium the whole time.
Answer: If the gas is initially in equilibrium with the surroundings and, in the final state, it is also in equilibrium with the surroundings, then $$p_{gas,init}=p_{gas, final}=P_{ext}$$then$$W=p_{ext}(V_{final}-V_{init})=p_{gas,final}V_{final}-p_{gas,init}V_{init}=\Delta (PV)_{gas}$$ | {
"domain": "chemistry.stackexchange",
"id": 17538,
"tags": "thermodynamics"
} |
Complete but not overcomplete subset of coherent state | Question: Define $$|z \rangle=e^{z \hat b^\dagger-z^* \hat b}|0\rangle$$
$|z\rangle$ is called coherent state, and we know $\{|z \rangle| z\in\mathbb{C}\}$ is overcomplete. So does there exist a complete but not overcomplete subset? How to construct it explicitly?
I try to restrict $z=r e^{i \theta}$ for fixed $r$ or $z\in \mathbb{R}$, but I find they are still overcomplete.
Answer: Complete sets of coherent states can be constructed in many ways. Historically, the most important examples of these complete sets are the Bargmann-Gabor frames, whose completeness was conjegtured by von-Neumann and proved by Perelomov and independently by
Bargmann, Buerta, Giradello and Klauder.
These proofs are known today as the coherent state density theorem.
The Bargmann-Gabor frames are sets of coherent states $|z\rangle$ corresponding to the lattice points:
$$z_{mn} = m \omega_1 + n \omega_2$$
($\omega_1$ and $\omega_2$ are not colinear).
The density theorem states that if the lattice unit cell area is greater than $\pi$ the set is not comlete, if the area is smaller than $\pi$ then it is supercomplete (contains many comlete bases) and if the area is exactly equal to $\pi$, then the set is complete and remains complete if exactly one element is removed. In the latter (complete) case, the set of coherent states is called a tight frame.
The Bargmann-Gabor frames and frames in general found many applications in mathematics (they consist the basis of the theory of wavelets), signal analysis, and physics. | {
"domain": "physics.stackexchange",
"id": 42449,
"tags": "quantum-mechanics, coherent-states"
} |
Torque, and the Law of the Lever | Question: How fundamental is the Law of the Lever? It seems that we simply define torque as being $r \times F$, if that's the case, then torque isn't a derived quantity, is it? Something like the Law of the Lever is distinct from Newton's Laws, then?
Answer: General remarks.
That's right.
Torque is defined as $\mathbf r\times\mathbf F$ where $\mathbf r$ is the position where the force is applied, and $\mathbf F$ is the force being applied.
The so-called Law of the Lever can then be derived from the following fact (which itself can be derived from Newton's Laws) about systems of particles:
The net external torque on a system of particles equals the rate of change of its total angular momentum;
\begin{align}
\boldsymbol\tau_\mathrm{ext} = \frac{d\mathbf L}{dt}.
\end{align}
For a proof, see
https://physics.stackexchange.com/a/55255/19976
Strictly speaking, as noted in the linked post, for this to be true, the particles in the system must interact according to forces that point in the direction of the lines joining them, but for macroscopic objects like levers, this condition is fulfilled.
Emergence of the Law of the Lever.
To see how this gives the Law of the lever, consider a light but very strong and rigid lever that is not rotating at all with a fulcrum that is a distance $d$ from one end, and a larger distance $D$ from the other. Suppose that you were to hang a mass $m$ from the end that is closer to the fulcrum.
If the lever is horizontal, what force $F$, would you need to exert on the opposite end so as to make it balance and therefore hold up the mass on the other side?
Well if we take the location where the fulcrum makes contact with the lever to be the origin, then the torque due to the hanging mass is $mgd$ while the force you exert on the other end would have a corresponding torque $-FD$. They have opposite sign because they tend to rotate the lever in opposite directions about the fulcrum. Since the level will be standing still, it's angular momentum will remain zero for all times, and the fact above then implies that the torques must sum to zero;
\begin{align}
mgd - FD =0.
\end{align}
It follows that
\begin{align}
F = \frac{d}{D}mg,
\end{align}
so the longer you make the part of the lever on the side opposite where the mass is hanging compared to the length of the part on the side where it is hanging, namely the smaller you make the ratio $d/D$, the lower the force $F$ you need to exert becomes. In fact, no matter how large $m$ is, if the level is long enough, you can make the force you need to exert to hold it up as small as you wish! This is the Law of the lever! | {
"domain": "physics.stackexchange",
"id": 16028,
"tags": "newtonian-mechanics, rotational-dynamics, torque"
} |
how to make ros cpplint use a relative path for header guard check | Question:
Is there a way to force the ccpplint used by ros2 in ament to use a relative path starting at ros2_overylay_ws/src instead of the explicit full path when checking header guards?
Originally posted by dennis.bergin on ROS Answers with karma: 1 on 2018-03-14
Post score: 0
Original comments
Comment by William on 2018-03-14:
Can you edit your question to also describe your folder layout exactly (maybe use the output of tree) and the exact command you're running and what folder it is in? Have you tried manually setting the --root option?
Comment by dennis.bergin on 2018-03-17:
I am using the command ament test . I am not sure how to add the --root option. A portion of my directory structure is as follows:
project location: /home/dennis/Projects/ros2_overlay_ws/src/small_robot
within small_robot :
common/include
common/src
vms/contoller/include
vms/controller/src
Comment by dennis.bergin on 2018-03-17:
the cpplint mesage is as follows:
No #ifndef header guard found, suggested CPP variable is: _HOME__DENNIS__PROJECTS__ROS2_OVERLAY_WS__SRC__SMALL_ROBOT__VMS__COMMON__INCLUDE__VMS_COMMON__ATTRIBUTE_HPP [build/header_guard] [5]
Comment by dennis.bergin on 2018-03-17:
The header guard for his file is #ifndef _SMALL_ROBOT__VMS__COMMON__ATTRIBUTE_HPP
I do not want to include the user specifc path portio "/home/dennis/projects/ros2_overlay_ws/src"
Comment by dennis.bergin on 2018-03-17:
lastly, sorry if my explanatio is confusing. I showed two example directory structures. the directory structure for the specific error message I provided is
small_robot/vms/common/attribute.h within /home/dennis/Projects/ros2_overlay_ws/src
Answer:
The ament_cpplint has two ways to detect the root for your source code:
It determines the --root by looking for known names in the path hierarchy, namely include, src, test. If you are using the latest release of ROS 2 (Ardent) this will likely not work for you. There was recently a fix for this logic (see https://github.com/ament/ament_lint/pull/94). You might want to consider to use a newer version of this package from source to make this work for your use case.
It also looks for the root of a git repository in case your code is using that. I guess that is not the case for you though.
Originally posted by Dirk Thomas with karma: 16276 on 2018-03-17
This answer was ACCEPTED on the original site
Post score: 1
Original comments
Comment by dennis.bergin on 2018-03-24:
Thank you for the information. I updated my version of ament. The problem has been alleviated. | {
"domain": "robotics.stackexchange",
"id": 30319,
"tags": "ros2"
} |
Why is the $S$-matrix calculated using the free vacuum state and not the full interacting vacuum state? | Question: Let $H = H_0 + H_I$ be a Hamiltonian that is the sum of a free Hamiltonian and an interacting Hamiltonian. Denote the free vacuum state by $| 0 \rangle$ and the full vacuums state by $|\Omega \rangle$. The $S$ matrix is computed as
$$\langle p_1\ldots p_n | S | p_{n+1}\ldots p_N\rangle = \langle 0 | a_{p_1}\ldots a_{p_n} S a^\dagger_{p_{n+1}}\ldots a^\dagger_{p_N} | 0 \rangle.$$
However scattering by definition involves interactions of particles, so why does the above use $|0\rangle$ and not $|\Omega\rangle$?
The motivation for this question came from studying the LSZ formula, which relates the $S$ matrix (using free vacuum states) to the Gell-Mann-Low formula (which is defined using the interacting vacuums state).
Answer: We calculate scattering matrix in order to take interactions into account. Scattering matrix calculation for scattering problems is like perturbation theory for eigenvalue problems - we attack the complex interacting problem using solvable non-interacting problem as the starting point. | {
"domain": "physics.stackexchange",
"id": 94184,
"tags": "quantum-field-theory, hilbert-space, scattering, interactions, s-matrix-theory"
} |
Acoustic Echo Cancellation | Question: I have the following diagram for acoustic echo cancellation
I'm having a hard time figuring out what's present on the top and bottom lines in terms of reflected echos, original signal etc. Here's what I think
I am assuming a situation in which I am talking in my microphone at home via some software to a meeting room in which a teleconfrencing setup is present. The microphone and speaker in the diagram repersent the teleconfrencing setup. My voice goes through the teleconfrencing speakers, hit's the walls of the meeting room and back into the microphone.
So, what I think is that the right after the microphone symbol in the diagram is my echoed voice x_echo[n]
On the bottom line at the speakers, only my original voice should be present since that's what's meant to be going through the speakers - so x[n].
Now, if that's the desired signal for my LMS adaptive filter, then how would my LMS adpative filter work, there would be no correlation at all.
Answer: The acoustic echo canceler (AEC) is supposed to cancel any signal in the microphone path that is correlated to the speaker signal. The microphone doesn't only pick up your voice but it also picks up the signal from the speaker, i.e., the signal from the far end. If there were no AEC, that signal from the speaker would be fed back to the far end, which is very disturbing. Since the speaker signal is available at the near end, it can be used as the input to the adaptive filter, which tries to remove any signal in the outgoing path that is correlated with the speaker signal. Basically, the adaptive filter will converge to the room impulse response between loudspeaker and microphone. | {
"domain": "dsp.stackexchange",
"id": 7038,
"tags": "linear-systems, adaptive-filters"
} |
Definition of the $Q$ factor? | Question: According to Wikipedia, the $Q$ factor is defined as:
$$Q=2\pi\frac{\mathrm{energy \, \, stored}}{\mathrm{energy \, \,dissipated \, \, per \, \, cycle}}.$$
Here are my questions:
Does the energy dissipated per cycle assume that the amplitude is constant from one cycle to the next.
Is it always calculated at the resonance frequency?
If the answer to 2 is yes can you explain why for a forced oscillator system with a damping coefficient of $\gamma$ and natural frequency $\omega_o$ the quality factor is $Q=\omega_o/\gamma$
and not some more complicated expression involving the actual resonant frequency (which is not quite $\omega_o$ and is given by
$$\omega_r=(\omega_0^2-\frac{\gamma^2}{2})^{\frac{1}{2}}$$
of the system? Is this just an approximation i.e. are we assuming that it resonates at $\omega_o$ but in fact the actual expression is a big more complicated?
Edit:
With using the actual value of $\omega_r$ I get:
$Q=(\omega_0^2-\frac{\gamma^2}{2})^{\frac{1}{2}}/\gamma$
is this more correct?
Answer: The answers currently posted are ignoring a few important details so I'm going to give my own.
I may rehash some things already said.
To make everything absolutely clear I write here a complete derivation of the forced damped oscillator with emphasis on the role of the $Q$ factor.
Basic equations
Consider the equation of motion of a forced, damped harmonic oscillator:
$$\ddot{\phi}(t)+2\beta\dot{\phi}(t) + \omega_0^2 \phi(t) = j(t) \,.$$
Here $\beta$ is a coefficient of friction (for the case where the friction force is proportional to the velocity $\dot{\phi}$), $j$ is an external forcing function, and $\omega_0$ is the un-damped frequency of the system.
We define the fourier transform $\tilde{\phi}(\omega)$ by the equation
$$\phi(t) = \frac{1}{2\pi}\int \tilde{\phi}(\omega)e^{-i \omega t}\,d\omega\,.$$
Plugging the Fourier transform into the equation of motion gives
$$\phi(\omega) = \frac{\tilde{j}(\omega)}{-\omega^2 - 2i\beta \omega + \omega_0^2}
= \frac{\tilde{j}(\omega)}{(\omega-\omega_+)(\omega - \omega_-)}$$
where $\tilde{j}$ is the Fourier transform of $j$ and
$$\omega_{\pm}\equiv -i\beta \pm \omega_0' \qquad
\omega_0'\equiv \omega_0\sqrt{1-\left( \frac{\beta}{\omega_0} \right)^2}\,.$$
My $\omega_0'$ is what you called $\omega_r$ if we set $\gamma / \sqrt{2} = \beta$.
Note that for light damping, i.e. the case $\beta \ll \omega_0$, we get $\omega_0' \approx \omega_0$.
In order to understand the meanings of the quality factor $Q$ we investigate these equations for two cases.
Free oscillation
First we consider the case where the forcing function is just an instantaneous whack at $t=0$.
This should cause the system to oscillate but with a decreasing amplitude as energy is lost to friction.
Mathematically we denote the instantaneous whack as $j(t) = A \delta(t)$.
This gives $\tilde{j}(\omega) = A$.
We find $\phi(t)$ by inverse Fourier transform
$$
\begin{align}
\phi(t)
&= \frac{1}{2\pi} \int \tilde{\phi}(\omega)e^{-i\omega t} \, d\omega \\
&= \frac{1}{2\pi} \int \frac{A e^{-i \omega t}}{(\omega-\omega_-)(\omega-\omega_+)} \, d\omega \\
&= \frac{A}{\omega_0'} e^{-\beta t} \sin(\omega_0' t) \, . \qquad(*)
\end{align}
$$
Let's understand this result.
At $t=0$ the system is at $\phi=0$.
This makes sense because we whack it at $t=0$ but it hasn't had time to go anywhere yet.
As time goes on, it oscillates at frequency $\omega_0'$ but with decreasing amplitude.
Note that the oscillation frequency in this case is not the un-damped frequency $\omega_0$; it is $\omega_0'$ which is slightly shifted because of the friction.
Larger friction causes a bigger shift in this free oscillation frequency.
Of course, as you can see, larger friction also causes the amplitude to decrease faster, which makes sense.
Now, what about $Q$?
Suppose $\phi$ represents the position of a mass on a spring.
In that case, the potential energy of the system is proportional to $\phi^2$.
Similarly, if $\phi$ represents the current in an LRC circuit then the the inductive energy is proportional to $\phi^2$.
Twice per oscillation all of the system's energy goes into the potential (or inductive) energy.
From Eq. $(*)$ that energy is
$$E(t) = E(0) e^{-2\beta t} \,.$$
Now we can easily find $Q$
$$Q \equiv \frac{\text{energy stored}}{\text{energy lost per radian}} =
\frac{E(t)}{-\frac{dE}{dt} \frac{dt}{d\,\text{radians}}}
= \frac{E(0)e^{-2\beta t}}{2\beta E(0) e^{-2\beta t}/\omega_0'}
= \frac{\omega_0'}{2\beta} \,.$$
This is almost exactly the same as your expression $\left( \omega_0^2 - \gamma^2 / 2 \right)^{1/2} / \gamma$ except that I think you have messed up a factor of $\sqrt{2}$ somewhere.
Anyway, the point is that your "more exact" formula for the $Q$ value is really just the $Q$ you get if you consider the case of free oscillation of the damped system.
Steady state driven system
Now let's consider the case where the system is subjected to constant driving of the form
$$j(t) = A \cos(\Omega t) \, .$$
Then
$$\tilde{j}(\omega) = \frac{(2\pi)A}{2}(\delta(\omega - \Omega) + \delta(\omega + \Omega))\,.$$
Plugging that into the integral and cranking away gives us
$$\phi(t) = \text{Re} \left[ e^{-i\Omega t} \frac{-A}{\Omega^2 + 2i\beta \Omega - \omega_0^2}\right]\, .$$
Let's look at the case where we're driving at the natural resonance frequency, i.e. $\Omega = \omega_0$.
In this case we get
$$\phi(t) = \frac{A}{2 \beta \omega_0}\sin(\omega_0 t)\,.$$
The power exerted by the driving force is $\text{force}\times\text{velocity}^{[a]}$:
$$P(t) = j(t)\dot{\phi}(t) = \frac{A^2}{2\beta}\cos(\omega_0 t)^2 = \frac{A^2}{4 \beta}[1 + \cos(2\omega_0 t)] \, .$$
Note that $P(t)$ is always positive.
This is actually the definition of resonance: the resonance frequency is the one such that the work done by the drive is always positive.
In an electrical circuit this is the same as saying that the resonance frequency is the one where the impedance of the damped oscillator is purely real.
No other frequency has this property, so we've just shown that $\omega_0$ is the resonance frequency of the damped system$^{[b]}$.
Since we're in steady state, this work must also be precisely the work lost by the system to the damping.
We can therefore compute the average power loss in one cycle:
$$\langle P_{\text{loss}}\rangle =
\frac{\omega_0}{2\pi} \int_{0}^{2\pi / \omega_0} P(t)\,dt = \frac{A^2}{4\beta}\,.$$
Great.
Now let's compute the energy stored.
By analogy to the case of a mass on a spring we know that the max potential energy is$^{[c]}$
$$U = \frac{1}{2} \phi_{\text{max}}^2 \omega_0^2 = (1/2)A^2 / 4\beta^2$$
and again since we're in steady state this is just the total stored energy.
Therefore, the $Q$ value is
$$Q \equiv \frac{\text{energy stored}}{\text{energy loss per radian}}=
\frac{U}{\langle P_{\text{loss}}\rangle / \omega_0}=
\frac{(1/2)A^2 / 4\beta^2}{A^2 / 4 \beta \omega_0} =
\frac{\omega_0}{2 \beta} \, .
$$
This is the expression is almost exactly the same as the one we found for free oscillation, except that now we have $\omega_0$ instead of $\omega_0'$.
Note that we have now answered your question #3, as we have shown that for steady state driving the $Q$ value involves $\omega_0$, not the more complex expression $\omega_0'$.
Answer to the original questions
We've seen that we can get two very slightly different expressions for $Q$ depending on whether we consider free oscillation or steady state driving.
In fact, when people talk about $Q$ they're really talking about the steady state driving one; to keep from getting confused the other expression really shouldn't be called "$Q$".
That said, for a system where $Q\gg1$ both expressions give extremely close numbers, so the distinction is mostly academic.
Does the energy dissipated per cycle assume that the amplitude is constant from one cycle to the next.
Yes, because when you talk about $Q$ you're implicitly talking about the steady state driving case in which everything is the same from cycle to cycle.
Is it always calculated at the resonance frequency?
By definition, yes. The $Q$ is defined as the energy stored divided by the energy loss per radian in the steady state driving case with drive at the natural oscillation frequency $\omega_0$.
If the answer to 2 is yes can you explain why for a forced oscillator system with a damping coefficient of $\gamma$ and natural frequency $\omega_0$ the quality factor is $Q=\omega_0/\gamma$ and not some more complicated expression involving the actual resonant frequency
This was demonstrated in detail in the above discussion/calculation.
Notes:
$[a]$: In fact because of the way the quantities are set up here, if $\phi$ is a displacement of a mass on a spring, then what I'm calling "power" is actually "power divided by mass".
$[b]$: See this SO question which I posted specifically to help generate this answer.
$[c]$: Again, if you go through and compare to the case of a mass on a spring you'll see that I've left out a factor of the mass. | {
"domain": "physics.stackexchange",
"id": 26467,
"tags": "harmonic-oscillator, definition, oscillators, resonance"
} |
Galaxy Spectra: Emission and Absorption Lines | Question: Spectra from galaxies include both absorption and emission lines. I do understand how both types of spectral lines are produced but I am not quite sure where each type is coming from when we observe a galaxy. Few month ago I was told that emission lines are coming from the gas of the galaxy and absorption lines are coming from the stars of the galaxy. Is that correct? If it is, why the opposite doesn't happen? Why can't we have absorption lines coming from the gas of the galaxy? I am mostly (but not exclusively) interested in the Hydrogen lines.
I have been looking at some spiral galaxy integral filed spectroscopy datacubes. I always see a very strong Ha emission line, never an Ha absorption line. Why?
Answer: A galaxy spectrum is a quite complex and complicated topic, and many entire careers are fully devoted to understanding them, so this can only be a simplified answer. It is still quite lengthy, though, so if you're impatient, I've summarised it at the bottom.
A blend of starlight of different spectral types makes up the continuum.
The light is emitted by stars in the galaxy. Stellar spectra are approximately a black body spectrum, but this mostly holds true for the most hot and luminous O and B type stars; for cooler stars, the image already gets quite a bit more muddled, as they will show more and more absorption happening in the stellar photosphere, as well as other effects that ruin the nice, smooth black body spectrum. These differences in spectra are actually the basis of the classification of stars in the spectral types O, B, A, F, G, K, M and L.
The spectrum of the galaxy, however, is a mix of all the stars within it. This will often be dominated by the hotter and heavier stars, but the other spectral types also blend in. There will generally be some stellar absorption features, but not many, and the combined light of the stars will often show a nice, relatively smooth profile. The shape of this composite spectrum depends heavily on the composition of stellar types - a young, irregular star-burst galaxy and an old, dying elliptical will show widely different shapes of the continuum.
Emission lines originate in the hot ISM and in stellar atmospheres
The galaxy will often have regions of star formation, in which the strong radiation ionize the surrounding interstellar medium, creating a so called HII Region. The ions and free electrons will recombine, and the excited states will decay, resulting in a cascade of electrons dropping between energy levels in the different atoms, resulting in a series of emission lines that is added to the spectrum. The energy radiated in all these lines doesn't come from the clouds themselves, but from the most energy-rich photons, so the gas will leave a drop in intensity on the blue side of these wavelengths in the spectrum (multiple drops of different strength, to be precise).
The absolute strengths of the emission lines depend on various parameters, of which star formation rate (SFR) is the most important - galaxies with ceased star formation show very few emission lines. The relative strengths of these lines depend on the chemical composition, temperature and other physical properties of the hot gas, so studying these line intensity ratios can often teach us a lot about the galaxies we observe.
Besides, sometimes we can also see flourescent lines, when photons from the hot gas excite atoms in colder, non-ionized clouds which then re-emit them in slightly different wavelengths. The wavelength offsets here can also tell us about the internal kinematics of the galaxy.
Below is a figure from this article that shows an average spectrum from a large number of star forming galaxies. Note the drop in flux on the blue side of the Lyman-$\alpha$ line. Taking the average will enhance the features that they have in common while suppressing features that are peculiar to individual galaxies. The caption below is mine from my Bachelor's project paper.
Absorption happens both in the cold, neutral ISM, the hot, ionized ISM and in stellar atmospheres
The very hot, ionized regions describes about are most likely to be found in the central regions of a galaxy. Further out, things are a bit cooler and calmer, and clouds of neutral hydrogen containing variable amounts of heavier elements are more numerous. When the combined light of the stars and the hot HII regions pass through these, some of it is absorbed by the colder atoms and re-emitted in random directions, with a probability of being re-emitted in the exact same direction it came in being practically zero. This means that these wavelengths will be deprived of photons, leaving the characteristic dark absorption lines in the spectrum - sometimes, but not always, at the same wavelengths where the stellar atmospheres have already done some of the absorption, so this needs to be taken into account when analysing a galactic spectrum.
Below is an example plot of absorption lines from multiple neutral gas clouds in a galaxy that I analysed for my Master's thesis. The light here comes from a quasar behind the galaxy, not the galaxy itself, but that has no impact on the absorbing gas.
The green markers show the centres of the individual lines, corresponding to a peculiar velocity for each gas cloud.
Due to internal dynamics, turbulence and rotation etc., these clouds will generally have different velocities than the stars and HII regions, giving them a slight red- or blueshift w.r.t. these. Sometimes, we can distinguish slightly offset absorption line sets from several neutral gas clouds within the galaxy, which can reveal yet more information about its internal workings.
Absorption like this happens in the dense, cold, neutral ISM as well as the hotter, less dense but more voluminous, ionized ISM. Different ionization degrees of the same atom will leave different sets of lines, so the same atom can be used to trace both hot and cold ISM. The difference between the line strengths can be used to assess the ionization degree of the parts of the galaxy we're looking at.
Emission and absorption of different hydrogen lines is not equally likely, and happens in different places
When it comes to Hydrogen lines particularly, the answer is not simple because the lines are very different. You will probably see absorption in Lyman-$\alpha$, because this is a very strong line, that is, if a photon of the right wavelength meets an atom at the right energy state, an absorption is very likely to happen - and these atoms are the most abundant in the Universe. But Lyman-$\alpha$ is complicated, and often you are likely to see both emission and absorption together creating a complicated line profile. Other lines, like the Balmer lines, are not very strongly absorbing, but emit very strongly, so you will mostly see emission from these lines.
To see why this is, remember how emission and absorption happens. Lyman-$\alpha$ is the transition between the ground state and the first excited state of the hydrogen atom. In cold gas, hydrogen spends by far the most of its time in the ground state. That means that there are lots of atoms around ready to absorb in Ly$\alpha$. But once the absorption has happened, the electron doesn't sit around in the first excited state for long, but spontaneously re-emits the photons and decays back to the ground state. In the hot ISM, therefore, we can have Lyman-$\alpha$ emission from recombined atoms, and in the cold ISM, there is strong absorption happening.
Here is Wikipedia's illustration of the Lyman and Balmer series, for reference:
The first Balmer line, H$\alpha$, on the other hand, is the transition between the first and second excited state of Hydrogen. This doesn't happen much in absorption, because atoms are unlikely to sit around in the first excited state for long. On the other hand, when an atom is ionized and recombines, or just strongly excited by an energetic photon, its path back to the ground state is likely to take it through one of the Balmer series transitions and then the Lyman-$\alpha$ transition.
Therefore, in the hot ISM, we are very likely to have Balmer emission, while it is very unlikely to have Balmer absorption in the cold ISM. When we do see Balmer absorption, it is most often in the stellar photospheres, because the high temperatures there means that there are many more atoms in higher energy states, so a H$\alpha$-wavelength photon is much more likely to encounter an atom there that is sitting around in the first excited state.
Summary:
Light profile is a composite of all the different star types, its shape depending on the composition of these, and sometimes with a few absorption lines visible from the stellar atmospheres.
A portion of the most energetic photons will ionize the gas surrounding the star forming regions, and will then be re-emitted as a cascading series of emission lines reflecting the temperature, chemical composition etc. of the region
A varying fraction of the light passes through cold, dense clouds as well as diffuse, hot, ionized clouds further out in the galaxy, which leaves one or more sets of absorption lines in the spectrum.
Lyman series emission and absorption are both very likely in the hot and cold ISM, respectively, because lots of recombination happens in the hot medium, while neutral hydrogen in the cold medium spends most of its time in the ground state, ready to absorb.
Balmer series emission is very likely to happen in the hot medium for the same reasons as Lymanseries emission, but absorption is unlikely to happen in the cold medium, because cold neutral hydrogen atoms don't sit around in the first excited state for very long.
[Later addition]
Here is a composite image of the galaxy known as ESO 338 IG04, observed in 3 different filters, that very nicely illustrates the origin of different kinds of radiation. It is taken from my supervisor's web page.
The green color tracks the UV continuum - this comes mainly from young, newly-formed stars, and is seen as little "knots" or "clumps" where the star formation is centered.
The red color tracks H$\alpha$ emission from the hot, ionized HII regions surrounding the star formation regions. These are seen to be a little more spread out thn the UV clumps, but to mostly lie fairly close to them.
The blue color tracks Lyman-$\alpha$, which also originates in the central, star forming knots, but because Ly$\alpha$ is such a strongly resonant transition, the photons are repeatedly absorbed and re-emitted in the neutral ISM until they finally escape the galaxy, far from where they were emitted. | {
"domain": "physics.stackexchange",
"id": 9415,
"tags": "astronomy, galaxies, spectroscopy"
} |
is it possible to add locations in map created by gmapping? | Question:
By moving the LiDAR in whole building, the map was created and also show on rviz. now i want to add specific locations in the building. Lets say i want to add location "Faculty Office" in map showing on rviz. please guide me how is it possible? If not possible by gmapping then guide me another technique through which it may possible.
Originally posted by john_vector on ROS Answers with karma: 3 on 2020-02-19
Post score: 0
Original comments
Comment by Delb on 2020-02-19:\
i want to add specific locations in the building
Can you be more specific please ? How an information like "Faculty Office" would be used by a program ? Do you mean something like if you give some coordinates you could get the name of the location pointed to ? That would require some post-processing to manually identify each location.
Comment by john_vector on 2020-02-19:
yeah exactly. if you give some coordinates you could get the name of the location pointed to. how can do that. kindly guide me
Comment by Delb on 2020-02-19:
I don't have examples or any procedure to follow but what you are looking for is called image segmentation (maybe even semantic SLAM). I believe OpenCV may have algorithms able to do this.
Answer:
Hi john_vector. What i have come to understand is that you want to create a map which would serve the purpose of showing different locations on it. So i came through this link(below) which is doing similar thing. Hope it helps :D
http://wiki.ros.org/rrt_exploration/Tutorials/singleRobot
Originally posted by Raza Jafri with karma: 16 on 2020-07-31
This answer was ACCEPTED on the original site
Post score: 0 | {
"domain": "robotics.stackexchange",
"id": 34466,
"tags": "ros-melodic"
} |
Can decarboxylation be done under carbon dioxide? | Question: From Why is the decarboxylation of 2-hydroxybenzoic acid (and related compounds) done 'under nitrogen'? I confirmed that nitrogen is used to exclude oxygen - in order to prevent oxidation of the material.
Can $\ce{CO_2}$ be substituted for nitrogen, or will the presence of carbon dioxide slow down the decarboxylation reaction (which is causing carbon dioxide to be released)?
Answer: Because nitrogen is the standard inert gas in lab practice. If you are "rich" You can use argon, but carbon dioxide is seldom used, because it won't work on alkaline solutions.
or will the presence of carbon dioxide slow down the reaction
First, what you presumably mean is influencing the equilibrium unfavourably, don't you? You should learn to discern kinetics and equilibrium.
Answer: not really. Whether you have a carbon dioxide atmosphere or not will shift the decomposition temperature not more than some degrees. | {
"domain": "chemistry.stackexchange",
"id": 3028,
"tags": "organic-chemistry"
} |
Data structure limited by range | Question: For a utility class, I've created a particular implementation of a list where the list's items can be limited to a specific range, using the google guava Range utility. Items in the list must accordingly implement Comparable. When an item is added or retrieved from the list, they will be within the specified range.
Note: I'm using this class to store commits/revisions from git or svn repositories, then users can limit information to a specific range. I know I could simply filter out information, but I decided to go all out and see if I could turn it into a learning experience
I have two different implementations of this:
Accept any items, but hide them based on the range. The range could then be modified, and previously hidden items could be exposed.
Only accept items within the range, and when the range is updated, all items outside of the range are discarded.
I've tried to mimic the way that the native Java libraries organize and abstract out their list implementations.
The code is broken up into many different files, so I will post the relevant ones here, and leave a link to my GitHub where the others are located.
Here's my AbstractRangedArrayList implementation:
package com.pwhiting.collect;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import com.google.common.collect.Lists;
import com.google.common.collect.Range;
public abstract class AbstractRangedList<C extends Comparable<?>> implements RangedList<C >{
protected final List<C> data;
protected List<C> limitedData = Lists.newArrayList();
protected Range<C> range = Range.all();
public AbstractRangedList() {
this(new ArrayList<C>());
}
public AbstractRangedList(final List<C> data) {
this.data = data;
includeAll();
}
public RangedArrayList<C> copy() {
final RangedArrayList<C> theCopy = new RangedArrayList<C>(data);
theCopy.range = range;
theCopy.limitedData = Lists.newArrayList(limitedData);
return theCopy;
}
@Override
public C get(final int index) {
return isLimited() ? limitedData.get(index) : data.get(index);
}
@Override
public Range<C> getRange() {
return range;
}
@Override
public void includeAll() {
limitedData = Lists.newArrayList();
range = Range.all();
}
@Override
public boolean isLimited() {
return !this.range.equals(Range.all());
}
@Override
public Iterator<C> iterator() {
return isLimited() ? limitedData.iterator() : data.iterator();
}
@Override
public void limitToRange(final Range<C> range) {
includeAll();
this.range = range;
for (final C c : data) {
if (range.contains(c)) {
limitedData.add(c);
}
}
}
@Override
public int size() {
return isLimited() ? limitedData.size() : data.size();
}
/**
* Called when data is added to check to add to limited data
*/
protected void reassess() {
limitToRange(getRange());
}
@Override
public void clear() {
data.clear();
limitedData.clear();
}
@Override
public boolean contains(Object o) {
return isLimited() ? limitedData.contains(o) : data.contains(o);
}
@Override
public boolean containsAll(Collection<?> c) {
return isLimited() ? limitedData.containsAll(c) : data.containsAll(c);
}
@Override
public int indexOf(Object o) {
return isLimited() ? limitedData.indexOf(o) : data.indexOf(o);
}
@Override
public boolean isEmpty() {
return isLimited() ? limitedData.isEmpty() : data.isEmpty();
}
@Override
public int lastIndexOf(Object o) {
return isLimited() ? limitedData.lastIndexOf(o) : data.lastIndexOf(o);
}
@Override
public ListIterator<C> listIterator() {
return isLimited() ? limitedData.listIterator() : data.listIterator();
}
@Override
public ListIterator<C> listIterator(int index) {
return isLimited() ? limitedData.listIterator(index) : data.listIterator(index);
}
@Override
public boolean remove(Object o) {
boolean result = false;
if (isLimited()){
result = limitedData.remove(o);
}
result |= data.remove(o);
return result;
}
@Override
public C remove(int index) {
C c = data.remove(index);
reassess();
return c;
}
@Override
public boolean removeAll(Collection<?> c) {
return data.removeAll(c) || limitedData.removeAll(c);
}
@Override
public boolean retainAll(Collection<?> c) {
boolean v = data.retainAll(c);
reassess();
return v;
}
@Override
public List<C> subList(int fromIndex, int toIndex) {
return isLimited() ? limitedData.subList(fromIndex, toIndex) : data.subList(fromIndex, toIndex);
}
@Override
public Object[] toArray() {
return isLimited() ? limitedData.toArray() : data.toArray();
}
@Override
public <T> T[] toArray(T[] a) {
return isLimited() ? limitedData.toArray(a) : data.toArray(a);
}
}
And here's the actual RangedLimitedList implementation:
package com.pwhiting.collect;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
* Represents a data structure whose data entries can be restricted to a certain
* range. New elements added to this list are kept, but also hidden if they do
* not fall into the range.
*
* @author phwhitin
*
* @param <T>
* @param <C>
*/
public class RangedArrayList<C extends Comparable<?>> extends AbstractRangedList<C> {
public RangedArrayList() {
super(new ArrayList<C>());
}
public RangedArrayList(final List<C> data) {
super(data);
}
@Override
public boolean add(final C c) {
return range.contains(c) ? data.add(c) && limitedData.add(c)
: data.add(c);
}
@Override
public void add(int index, C element) {
data.add(index, element);
reassess();
}
@Override
public boolean addAll(Collection<? extends C> c) {
boolean v = data.addAll(c);
reassess();
return v;
}
@Override
public boolean addAll(int index, Collection<? extends C> c) {
boolean v = data.addAll(index, c);
reassess();
return v;
}
@Override
public C set(int index, C element) {
C v = data.set(index, element);
reassess();
return v;
}
}
Again, I've omitted some of the classes for brevity's sake, but they are on my GitHub at the link provided above, should you need to view them to pass judgement.
I want to know if there is a more efficient way I could have done this, or perhaps a better structure I could have chosen. I'm not necessarily concerned with whether or not something like this already exists, it's mostly a thought experiment.
Answer: Inefficient adds
protected final List<C> data;
protected List<C> limitedData = Lists.newArrayList();
protected Range<C> range = Range.all();
When you use any of the four methods to add elements to the range, they end up \$\mathcal{O}(n)\$ where \$n\$ is the final number of elements in the list. This is because limitToRange always rebuilds limitedData from data.
protected final NavigableSet<C> data = new TreeSet<>();
protected Set<C> limitedData = data;
protected Range<C> range = Range.all();
With this data structure, adding would be \$\mathcal{O}(\log n)\$ and the limiting operation would be only the efficiency of the subset operations.
public void limitToRange(final Range<C> range) {
includeAll();
this.range = range;
for (final C c : data) {
if (range.contains(c)) {
limitedData.add(c);
}
}
}
becomes
public void limitToRange(final Range<C> range) {
this.range = range;
if (range.hasLowerBound()) {
boolean lowerClosed = range.lowerBoundType() == BoundType.Closed;
if (range.hasUpperBound() {
boolean upperClosed = range.upperBoundType() == BoundType.Closed;
limitedData = data.subSet(range.lowerBound(), lowerClosed, range.upperBound(), upperClosed);
} else {
limitedData = data.tailSet(range.lowerBound(), lowerClosed);
}
} else if (range.hasUpperBound() {
boolean upperClosed = range.upperBoundType() == BoundType.Closed;
limitedData = data.headSet(range.upperBound(), upperClosed);
} else {
limitedData = data;
}
}
This is limited by the time it takes to do the Set limiting operations.
Now, you might reasonable argue that Set doesn't support all the List operations, but if they are important to you, you could implement your own tree type that did.
Note that your current implementation already breaks the contract that if you set something at position i and then get from position i, you get back the same item. So in a very real way, it's not a List either. | {
"domain": "codereview.stackexchange",
"id": 21148,
"tags": "java"
} |
What are the correct symbols for vernal and autumnal equinox? | Question: What are the correct symbols for vernal and autumnal equinox?
I have seen people use both ♈︎ (\Aries) and $\gamma$ (\gamma) to denote vernal equinox. However, I have never seen the symbol for autumnal equinox. Should it be either ♎︎ (\Libra) or $\Omega$ (\Omega)?
Are ♈︎ and ♎︎ the conventional symbols to use?
Are $\gamma$ and $\Omega$ sometimes used just because they resemble the above symbols?
An alternative name for vernal equinox is First Point of Aries. Is there a similar name (First Point of Libra) for autumnal equinox?
Answer: The Wikipedia article on astronomical symbols says:
The zodiac symbols are also sometimes used to represent points on the ecliptic, particularly the solstices and equinoxes.
Each symbol is taken to represent the "first point" of each sign.
Thus, ♈ the symbol for Aries, represents the March equinox; ♋, for Cancer, the June solstice; ♎, for Libra, the September equinox; and ♑, for Capricorn, the December solstice.
The article cites Roy and Clarke, Astronomy: Principles and Practice.
This question copies an example usage of ♈ and ♎ from that book.
Stellarium uses the same symbols if you set View: Markings to show the equinoxes and solstices.
$\gamma$ is a poor substitute but clear enough if ♈ is unavailable.
Since $\Omega$ stands for an orbit's longitude of ascending node (angle ♈-☉-☊), it would be a confusing substitute for ♎.
"First point of Libra" is archaic but correct.
These names and symbols represent tropical zodiac signs, not IAU constellations.
♎ is fixed at ecliptic longitude 180° regardless of constellation boundaries.
Its location in Virgo this century doesn't change its name or symbol. | {
"domain": "astronomy.stackexchange",
"id": 4387,
"tags": "history, symbols, nomenclature"
} |
What is the most complex plant form? | Question: At school we were told on scale of 0 through 1000 the animal kingdom ranges from amoeba the simplest/primitive being at 0, and Humans the most complex animals at 1000; what are the equivalent complexity species (?) in the plant kingdom? What is the least complex plant, and the most complex?
Answer: That whole thing of being more complex is non-sense, you can't say that for animals and you can't say that for plants either. It all depends on how you look at it. Average number of cells? Size of genome? Size of the proteome? Adaptability to different environments? Mental abilities? You can't place human on the top of any of them (maybe we could argue about if you define it as mental abilities but that doesn't sound right) and you can't place amoeba at the bottom either.
Also, if you look at a phylogenetic tree, an organism is also not more complex by the number of nodes it has behind them (I've seen people thinking this means more evolved and associate that with more complex). | {
"domain": "biology.stackexchange",
"id": 528,
"tags": "taxonomy"
} |
Axis of rotation and rotating rigid body | Question: We know that angular momentum of a solid disk rotating with angular velocity $\omega$ is given by $I\omega$ about its center. Now if I chose any axis (parallel to above), will it have same magnitude of angular momentum as in the above case? If not how should I tackle this axis of rotation?
Answer: When youare talking about angular momentum about any axis(inluding one that passes through center of mass), you carry out the "formula":$\vec{L}=\vec{L_{com}}+I_{com}\vec{\omega}$ where direction of $\vec{L_{com}}$ and $I_{com}\vec{\omega}$ is to be kept in mind, during vector summation.While we calculate $\vec{L}$, about COM, $\vec{L_{com}}$ becomes zero because, PERPENDICULAR distance between COM and point of reference becomes zero.Also note that $\vec{L}$ about any axis is NOT equal to $I_{axis}\vec{\omega}$. This is ONLY true if and only if the body is actually rotating about that axis or the point of contact is instantaneously at rest at that point( i.e. the body is instantaneously rotating about that point, as is the case during pure rolling motion of a ball or body on ground). Now by parallel axis theomem we can calculate $$I_{axis} = I_{\mathrm{cm}} + md^2$$. | {
"domain": "physics.stackexchange",
"id": 30134,
"tags": "homework-and-exercises, rotational-dynamics, rotation, rotational-kinematics"
} |
Approximate the change in perceived gain from applying transfer function to audio signal | Question: I have an audio signal that I am applying an analogue transfer function $H(s)$ to. I would like to approximate the change in gain ($\Delta \text{ Gain}$) as perceived by the listener for an arbitrary audio signal sent through the filter $H(s)$.
I was thinking something along the lines of:
$$
\Delta \text{Gain} = \frac {\displaystyle\int_{0}^{\pi} \lvert H(\omega)\rvert d\omega} {\pi}
$$
This is based on an assumption that the formula above gives a sensible approximation of gain across the spectrum by calculating the averaging gain.
Is my thinking sensible or is there some proper theory that will give a better answer that I can refer to?
Answer:
I would like to approximate the change in gain ($\Delta \text{ Gain}$) as perceived by the listener for an arbitrary audio signal sent through the filter $H(s)$.
That's not possible, since the filter's response and perceived loudness depend on the frequency content of the signal, which is unknown.
In other words, if your filter is a high shelf, which boosts everything above 5 kHz, then:
For a signal that contains high frequency content, it will boost the perceived loudness
For a low frequency signal that consists only of bass, there will be no change
Since you're ok with an approximation, you can make an educated guess what the change will be based on a typical music spectrum, which is probably the best you can do. This paper contains a model of typical music spectra:
Long-term Average Spectrum in Popular Music and its Relation to the Level of the Percussion
So the steps would be:
Generate the typical music spectrum, either from papers like above, or from measurements
Pass it through a psychoacoustic loudness filter (like 468-weighting or A-weighting)
Measure the RMS level
Pass it through your filter under test
Measure the RMS level
The ratio between 5 and 3 will be the change in perceived loudness. | {
"domain": "dsp.stackexchange",
"id": 6339,
"tags": "audio, power-spectral-density, transfer-function"
} |
Meaning of "external demands" in a paper describing the gut-brain axis | Question: From "Brain Gut Microbiome Interactions and Functional Bowel Disorders":
In response to external and bodily demands, the brain modulates individual cells (ECC – enterochromaffin cells; SMC – smooth muscle cells; ICC – interstitial cells of Cajal) within this network via the branches of the autonomic nervous system (ANS) (sympathetic and parasympathetic/vagal efferents) and the hypothalamic pituitary adrenal (HPA) axis.
What is the meaning of "external demands"? What other possible demands can the brain strive to meet by modulating the activity of the neural network of the gut?
Answer: From the context, it seems to refer to those demands outside of the human body. i.e. perceptions of the external world. Examples could include a perceived threat, diunal cycles, or stress about that public presentation you're giving later.
If you are about to be chased by a dangerous predator, a sudden urge to poop would probably impair your chances of survival. Luckily, when our sympathetic nervous system kicks in, our GI motility slows down, so our body can focus on surviving the external threat and live to poop another day. | {
"domain": "biology.stackexchange",
"id": 10564,
"tags": "neuroscience, neurophysiology, gut-bacteria"
} |
Why would I use three state variables for a second order system? [state space modeling] | Question: I'm currently being asked to write a state space model of a falling object (equation attached).
I had taken a linear systems course five years ago in which I did a lot of conversion between high order differential equations and systems of first order linear equations. However, this task seems odd for a few reasons:
Most nth ordered differential equations that I had converted only required n state variables. For example, if I had a second order differential equation, I needed two state variables. In this problem, it's asking for 3 state variable which seems odd. Is the third state variable even necessary?
This differential equation directly includes the independent variable (time) itself. It also includes an initial condition p0 which seems odd.
I'm able to derive a solution to this problem, however it just seems very odd in how I'm doing it. This is my solution:
Answer: I'll point out that your solution:
$$
\dot{X} = \left[\begin{matrix}
\dot{p} \\
\ddot{p} \\
\dddot{p}\end{matrix}\right] = \left[\begin{matrix}
x_2 \\
x_3 \\
0 \end{matrix}\right]= \left[\begin{matrix}
0 & 1 & 0 \\
0 & 0 & 1 \\
0 & 0 & 0 \end{matrix}\right] \left[\begin{matrix}
x_1 \\
x_2 \\
x_3 \end{matrix}\right]\\
$$
multiplies out to:
$$
\dot{p} = \dot{p} \\
\ddot{p} = \ddot{p} \\
$$
which is a trivial statement and doesn't express the system you presented.
I am not a fan of this question (not you, but the question you were asked to solve.) As others have mentioned, there's no reason to have acceleration $\ddot{p}$ as a state, because you get acceleration when you take the derivative of your state vector if your state vector includes speed. That is, if $x = \left[\begin{matrix}
p \\
\dot{p} \end{matrix}\right]$, then $\dot{x} = \left[\begin{matrix}
\dot{p} \\
\ddot{p}\end{matrix}\right]$.
Further, in order to get the solution here, I believe the question is wanting you to rearrange the equation in the form of $\ddot{x} = \text{<stuff>}$, but you wind up with an expression that implies that acceleration is a function of position and speed, which is not the case. Position is a function of speed and acceleration. | {
"domain": "robotics.stackexchange",
"id": 1999,
"tags": "control"
} |
Using groups with dynamic_reconfigure, rqt_reconfigure | Question:
Reading about and playing around the almost secret concept of using "groups" with dynamic_reconfigure.
I have the following questions:
What is the group "state" attribute used for? rqt_reconfigure plugin does not seem to do anything with it.
rqt_reconfigure has classes called CollapseGroup, TabGroup, etc.... Can I use "groups" in a way so that they can appear tabbed, collapsed, hidden etc...?
Save/reload yaml from rqt_configure works fine, except when the configuration contains groups. Then the loading generates an error on the server side:
[ERROR] [1527081248.063225]
[/dynamic_tutorials]: Error processing
request: 'list' object has no
attribute 'items' ['Traceback (most
recent call last):\n', ' File
"/opt/ros/kinetic/lib/python2.7/dist-packages/rospy/impl/tcpros_service.py",line
625, in _handle_request\n response
= convert_return_to_response(self.handler(request),
self.response_class)\n', ' File
"/opt/ros/kinetic/lib/python2.7/dist-packages/dynamic_reconfigure/server.py",
line 135, in _set_callback\n return
encode_config(self.update_configuration(decode_config(req.config,
self.type.config_description)))\n', '
File
"/opt/ros/kinetic/lib/python2.7/dist-packages/dynamic_reconfigure/encoding.py",
line 312, in decode_config\n
add_params(d['groups'],
description)\n', ' File
"/opt/ros/kinetic/lib/python2.7/dist-packages/dynamic_reconfigure/encoding.py",
line 308, in add_params\n for nr,
dr in descr['groups'].items():\n',
"AttributeError: 'list' object has no
attribute 'items'\n"]
My cfg looks like:
#!/usr/bin/env python
PACKAGE = "dynamic_tutorials"
from dynamic_reconfigure.parameter_generator_catkin import *
gen = ParameterGenerator()
gen.add("my_int_param", int_t, 0, "An Integer parameter", 50, 0, 100)
gen.add("my_bool_param", bool_t, 0, "A Boolean parameter", True)
mygroup = gen.add_group("MyGroup")
mygroup.add("my_double_param", double_t, 0, "Some double param", 100, 0, 200)
exit(gen.generate(PACKAGE, "dynamic_tutorials", "Tutorials"))
Originally posted by knxa on ROS Answers with karma: 811 on 2018-05-23
Post score: 2
Original comments
Comment by lucasw on 2019-04-21:
I'm getting the same error though only when the dynamic reconfigure server is a rospy one, an identical cfg with C++ server works fine (https://github.com/lucasw/dynamic_reconfigure_tools/tree/master/dynamic_reconfigure_example). My Reconfigure client (C++ ) must be doing something wrong/unexpected with the request, but it isn't clear what. https://github.com/lucasw/imgui_ros/issues/9
Comment by lucasw on 2019-04-22:
I changed the dynamic reconfigure request to only have one value in it (before it was resetting all the values when only one had changed), and the error went away. It seems like a rospy dynamic reconfigure server bug.
Answer:
Answering my own question:
The server configuration can indicate how a group should be presented in a GUI by setting the "type" attribute.
For example:
mygroup = gen.add_group("MyGroup", type="tab")
Other type values are 'hide', 'collapse', 'apply'.
The rqt_reconfigure actually obeys the 'type' indication.
The state attribute has effect only for the 'hide' and 'collapse' types.
The server may in the callback change the 'state' attribute to hide/collapse a group in the rqt_reconfigure, example:
def callback(config, level):
# example: change visibility state of group
config.groups.groups.MyGroup.state = False
I have no solution on the exception generated by load/reload and the same problem is actually seen when toggling the checkbox for a group with type 'collapse'. I have filed a bug report.
Originally posted by knxa with karma: 811 on 2018-05-25
This answer was ACCEPTED on the original site
Post score: 1 | {
"domain": "robotics.stackexchange",
"id": 30886,
"tags": "ros, rqt-reconfigure, ros-kinetic, dynamic-reconfigure"
} |
Attempt at templates by creating a class for N-dimensional mathematical vectors | Question: Originally I had tried to implement this topic after having learned about Inheritence and posted it on here, but that forced complexity and the main suggestion was that this was ideal for templates. Now that I've learnt about templates I was hoping someone could review my code for a basic implementation of mathematical vectors.
One thing I will note: There probably is a way to generalise the cross-product to N-dimensions but I wasn't too interested in finding out how since that's a more mathematical query, I just wanted to code so I only have cross product for three dimensions.
My main concerns are the uses of headers and source files, is it okay to have all of the implementation in one header file and the few necessary non-template functions defined in source files (like cross_product)?
And how should I treat friendship for cross_product? It only needs to be friends with Vector<3>, but I couldn't see a way of making exclusive Vector<3> friendship without using template specialisation, which seemed a bit too much. So it is friends with all Vector<N> but only accesses members of Vector<3>s.
Inside Vector.h:
#ifndef MATHSVectors
#define MATHSVectors
#include <string>
#include <iostream>
#include <initializer_list>
#include <stdexcept> //for the exceptions
#include <cmath> //sqrt, sin, cos, abs
//main template forward declaration
template <unsigned N> class Vector;
template <unsigned N> std::ostream& operator<< (std::ostream&, const Vector<N>&);
template <unsigned N> std::istream& operator>> (std::istream&, Vector<N>&);
template <unsigned N> bool operator==(const Vector<N>&, const Vector<N>&);
template <unsigned N> bool operator!=(const Vector<N>&, const Vector<N>&);
template <unsigned N> Vector<N> operator+(const Vector<N>&, const Vector<N>&);
template <unsigned N> Vector<N> operator-(const Vector<N>&, const Vector<N>&);
template <unsigned N> Vector<N> operator*(const Vector<N>&, double);
template <unsigned N> Vector<N> operator*(double, const Vector<N>&);
template <unsigned N> Vector<N> operator/(const Vector<N>&, double);
template <unsigned N> double dot_product(const Vector<N>&, const Vector<N>&);
//in Vector.cpp
bool double_equals(double, double);
double approximate(double, double);
Vector<3> cross_product(const Vector<3>&, const Vector<3>&);
template <unsigned N> class Vector{
friend std::ostream& operator<< <N>(std::ostream&, const Vector&);
friend std::istream& operator>> <N>(std::istream&, Vector&);
friend bool operator== <N>(const Vector&, const Vector&);
friend Vector operator+ <N>(const Vector&, const Vector&);
friend Vector operator- <N>(const Vector&, const Vector&);
friend Vector operator* <N>(const Vector&, double);
friend Vector operator/ <N>(const Vector&, double);
friend double dot_product<N>(const Vector&, const Vector&);
friend Vector<3> cross_product(const Vector<3>&, const Vector<3>&);
public:
Vector() = default;
Vector(std::initializer_list<double>); //implicit conversion means we can assign from an initializer_list<double>
explicit operator bool() const;
double& operator[](size_t p);
const double& operator[](size_t p) const;
Vector& operator+=(const Vector&);
Vector& operator-=(const Vector&);
Vector& operator*=(double);
Vector& operator/=(double);
double length() const;
Vector& normalise();
Vector& rotateCoordinates(size_t, size_t, double); //radians
private:
double x[N] = {};
};
template <unsigned N> std::ostream& operator<<(std::ostream& os, const Vector<N>& rhs){
os << "[";
for(unsigned it = 0; it != N; ++it){
os << approximate(rhs.x[it], 0);
if(it != N-1) os << ", ";
}
os << "]";
return os;
}
template <unsigned N> std::istream& operator>>(std::istream& is, Vector<N>& rhs){
Vector<N> errorRet = rhs;
for(unsigned it = 0; it != N; ++it)
is >> rhs.x[it];
if(!is)
rhs = errorRet;
return is;
}
template <unsigned N> bool operator==(const Vector<N>& lhs, const Vector<N>& rhs){
for(unsigned it = 0; it != N; ++it)
if(!double_equals(lhs.x[it], rhs.x[it])) return false;
return true;
}
template <unsigned N> bool operator!=(const Vector<N>& lhs, const Vector<N>& rhs){
return !(lhs == rhs);
}
template <unsigned N> Vector<N> operator+(const Vector<N>& lhs, const Vector<N>& rhs){
Vector<N> sum = lhs;
sum += rhs;
return sum;
}
template <unsigned N> Vector<N> operator-(const Vector<N>& lhs, const Vector<N>& rhs){
Vector<N> sum = lhs;
sum -= rhs;
return sum;
}
template <unsigned N> Vector<N> operator*(const Vector<N>& rhs, double d){
Vector<N> product = rhs;
product *= d;
return product;
}
template <unsigned N> Vector<N> operator*(double d, const Vector<N>& rhs){
return rhs*d;
}
template <unsigned N> Vector<N> operator/(const Vector<N>& rhs, double d){
Vector<N> remain = rhs;
remain /= d;
return remain;
}
template <unsigned N> double dot_product(const Vector<N>& lhs, const Vector<N>& rhs) {
double sum = 0;
for(unsigned it = 0; it != N; ++it)
sum += lhs.x[it]*rhs.x[it];
return sum;
}
template <unsigned N> Vector<N>::Vector(std::initializer_list<double> li){
if(N != li.size()) throw std::length_error("Attempt to initialise Vector with an initializer_list of different size.");
for(unsigned it = 0; it != li.size(); ++it)
x[it] = *(li.begin()+it);
}
template <unsigned N> Vector<N>::operator bool() const {
return !(*this == Vector<N>());
}
template <unsigned N> double& Vector<N>::operator[](size_t p){
if(p >= N) throw std::out_of_range(std::string("Invalid coordinate specified for function ") + __func__);
return x[p];
}
template <unsigned N> const double& Vector<N>::operator[](size_t p) const {
if(p >= N) throw std::out_of_range(std::string("Invalid coordinate specified for function ") + __func__);
return x[p];
}
template <unsigned N> Vector<N>& Vector<N>::operator+=(const Vector<N>& rhs){
for(unsigned it = 0; it != N; ++it)
x[it] += rhs.x[it];
return *this;
}
template <unsigned N> Vector<N>& Vector<N>::operator-=(const Vector<N>& rhs){
for(unsigned it = 0; it != N; ++it)
x[it] -= rhs.x[it];
return *this;
}
template <unsigned N> Vector<N>& Vector<N>::operator*=(double d){
for(unsigned it = 0; it != N; ++it)
x[it] *= d;
return *this;
}
template <unsigned N> Vector<N>& Vector<N>::operator/=(double d){
if(d == 0) throw std::domain_error(std::string("Division by zero in function ") + __func__);
for(unsigned it = 0; it != N; ++it)
x[it] /= d;
return *this;
}
template <unsigned N> double Vector<N>::length() const {
double sum = 0;
for(unsigned it = 0; it != N; ++it)
sum += x[it]*x[it];
return sqrt(sum);
}
template <unsigned N> Vector<N>& Vector<N>::normalise() {
if(!(*this)) return (*this); //null vector
return (*this)/=length();
}
template <unsigned N> Vector<N>& Vector<N>::rotateCoordinates(size_t i, size_t j, double angle){
if(i >= N || j >= N) throw std::out_of_range(std::string("Invalid coordinate specified for function ") + __func__);
double newI = x[i]*cos(angle) - x[j]*sin(angle);
double newJ = x[j]*cos(angle) + x[i]*sin(angle);
x[i] = newI;
x[j] = newJ;
return *this;
}
#endif
Inside Vector.cpp:
/* A few notes about dealing with doubles
1 i. The double compare function needs to be changed. It is not a transitive equality operation. A method to
fix this would be to snap the doubles on to a grid and return true if two doubles snap on to the same section
of the grid. I don't know how to implement this just yet - wait until I've read more about float comparisons.
2. Doubles can get stored as negative zero, so adding +.0 when outputting the vector prevents displaying "-0".
*/
#include "Vector.h"
using namespace std;
const double epsilon = 1e-6; //double tolerance
bool double_equals(double a, double b){
return abs(a-b) < epsilon;
}
double approximate(double a, double b){
return double_equals(a,b) ? b : a;
}
Vector<3> cross_product(const Vector<3>& lhs, const Vector<3>& rhs){
double newX = (lhs.x[1]*rhs.x[2]) - (lhs.x[2]*rhs.x[1]);
double newY = (lhs.x[2]*rhs.x[0]) - (lhs.x[0]*rhs.x[2]);
double newZ = (lhs.x[0]*rhs.x[1]) - (lhs.x[1]*rhs.x[0]);
return Vector<3>({newX, newY, newZ});
}
Answer: This looks pretty good. I don't have any deal-breaker comments, just a bunch of minor ones.
Prefer std::array
Just straight up std::array<double, N> x instead of double x[N]. Raw arrays are broken. There's not really any real difference for the purposes of your use-case, but it's just a more pleasant type to deal with in general.
Throwing and non-throwing
For functions that throw, there's an extra mechanism that needs to exist to support that use-case. Plus even an always-predicted branch is going to be more code that no branch. To that end the standard containers offer throwing and non-throwing functions. If you rewrite your two operator[]s to be non-throwing:
template <unsigned N>
double& Vector<N>::operator[](size_t p) {
return x[p];
}
And introduce a throwing alternative:
template <unsigned N>
double& Vector<N>::at(size_t p) {
if(p >= N) throw std::out_of_range(std::string("Invalid coordinate specified for function ") + __func__);
return (*this)[p];
}
That will give you two benefits. First, users of your class would expect operator[] to not throw since that's pretty typical. But second, you no longer need to friend any of the free functions. cross_product only needed to be a friend because you wanted to avoid the throwing, now that's just a non-issue.
Use some standard algorithms
Your equality operator can be reimplemented with std::equal:
template <unsigned N>
bool operator==(const Vector<N>& lhs, const Vector<N>& rhs) {
return std::equal(lhs.x.begin(), lhs.x.end(), rhs.x.begin(), double_equals);
}
Similarly, operator bool doesn't need to construct a whole new vector, just check the one you have against zero with std::any_of:
template <unsigned N>
Vector<N>::operator bool() const {
return std::any_of(lhs.x.begin(), lhs.x.end(), [](double v){
return !double_equals(v, 0.0);
});
}
Initialization from std::initializer_list<double> can use std::copy:
std::copy(x.begin(), x.end(), li.begin());
Normalize
I suspect the typical case here might be for valid vectors, so prefer to take the length first and compare that against zero, rather than invoking operator!:
double magnitude = length();
if (magnitude > 0) {
(*this) /= magnitude;
}
return *this;
I also question the name length(). That seems to suggest that this is a container more along the lines of std::vector, but really you're talking about the norm of the vector. So a better name, please.
Use range-based for
Whenever you loop in a way that doesn't actually involve the index, prefer to use range-based for. It's just easier to write. For instance, your operator*=:
for (double& val : x) {
val *= d;
}
return *this;
Friend Operators
Rather than forward declaring template functions, then friending them, prefer to write these operators as non-member non-template friends. So operator+ would be:
template <unsigned N>
class Vector {
public:
friend Vector operator+(Vector const& lhs, Vector const& rhs) {
Vector sum = lhs;
sum += rhs;
return sum;
}
};
This will be found by ADL and nothing else, and then you also don't have to worry about some of the other issues that writing function templates leads you to. It's just simpler.
rotateCoordinates
This seems like it should be a non-member to me. | {
"domain": "codereview.stackexchange",
"id": 16992,
"tags": "c++, c++11, template, coordinate-system"
} |
Does Toffoli AND conjugate affect superposition if used in Shor's algorithm? | Question: I have come across several papers that use Toffoli AND conjugate to minimize the T-depth. But since it contains a measurement, does it affect Shor's algorithm (in terms of interference, entanglement, or superposition), when used within the reversed modular multiplication circuit, such as in Vedral et al's implementation?
Toffoli AND conjugate (d), source.
Vedral et al's modular exponentiation circuit, source: Nakahara et al's book: Quantum Computing - From Linear Algebra to Physical Realizations:
Answer: No, it doesn't cause problems. These implementations of the operations are exactly equivalent to implementations that don't use measurement. The measurements are carefully chosen to not measure anything affecting the surrounding algorithm, and the classically controlled operations are chosen to correctly repair any kickback effects from the measurement result varying.
You can verify this in simulators. For example, here is a circuit with state displays showing that the density matrix of two qubits is correctly restored by an uncomputation procedure involving a measurement:
For contrast, here's an operation that's not correctly uncomputed: | {
"domain": "quantumcomputing.stackexchange",
"id": 2604,
"tags": "entanglement, measurement, shors-algorithm, superposition"
} |
Box Blur algorithm | Question: This is a challenge from CodeSignal.
For
image = [[1, 1, 1],
[1, 7, 1],
[1, 1, 1]]
the output should be boxBlur(image) = [[1]].
To get the value of the middle pixel in the input 3 × 3 square: (1 + 1 + 1 + 1 + 7 + 1 + 1 + 1 + 1) = 15 / 9 = 1.66666 = 1. The border pixels are cropped from the final result.
For
image = [[7, 4, 0, 1],
[5, 6, 2, 2],
[6, 10, 7, 8],
[1, 4, 2, 0]]
the output should be
boxBlur(image) = [[5, 4],
[4, 4]]
There are four 3 × 3 squares in the input image, so there should be four integers in the blurred output. To get the first value: (7 + 4 + 0 + 5 + 6 + 2 + 6 + 10 + 7) = 47 / 9 = 5.2222 = 5. The other three integers are obtained the same way, then the surrounding integers are cropped from the final result.
Here's my code:
function boxBlur(image) {
const SQUARE = 3
const outerArr = []
for (let i = 0; i < image.length; i++) {
const innerArr = []
for (let j = 0; j < image[0].length; j++) {
if (image[i][j] !== undefined && image[i][j+2] !== undefined && image[i+2]) {
let sum = 0
for (let k = 0; k < SQUARE; k++) {
for (let y = 0; y < SQUARE; y++) {
sum += image[i+k][j+y]
}
}
innerArr.push(Math.floor(sum/9))
}
}
if (innerArr.length) outerArr.push(innerArr)
}
return outerArr
}
```
Answer: Some suggestions on coding style:
Your choice in variables is somewhat confusing i, j? For an algorithm operating on a 2D image, the names x and y would be better. And dx, dy for the offsets in the inner loop.
You defined the width of your kernel as SQUARE, yet you hardcode 2 in the expression image[i][j+2].
Your boundary checks can be more efficient. Why check for undefined if you know the exact size of the image? You can loop i from 0 to image.length - SQUARE, and loop j from 0 to image[0].length - SQUARE and remove the if statement:
for (let i = 0; i < image.length - SQUARE; i++) {
for (let j = 0; j < image[0].length - SQUARE; j++) {
// no if-statement needed anymore
...
}
}
Note that the naive algorithm works fine for small kernels, but can be done more efficient using a summation map where you first calculate the total sum of all preceding values in a preprocessing step, and then calculate the sum of the pixels in the square using the summation map of the 4 corner points. That way, the algorithm speed becomes independent of the size SQUARE of your kernel. | {
"domain": "codereview.stackexchange",
"id": 44029,
"tags": "javascript, algorithm"
} |
What is gravitaional field $\Phi$ vs gravitational potential $U$ | Question: I am confused about my teachers notation.
I have a set of problems about "gravitational potential $\Phi$."
But is $\Phi$ normally written as $U$ is a lot of caseses? Is there a difference?
Rant or My Understanding
I think that he wants an equation for the field rather than a given point but I am confused on really how to do that. My brain will not grasp the idea of finding the potential everywhere in these problems even though I know what that means.
Examples
Note: I am not asking for solutions I am posting these for insight on what my teacher means.
ex.1)
A thin uniform disk of radius $a$ and mass $M$ lies in the $(x,y)$ plane centered on the origin. Find an integral expression for the gravitational potential $\Phi (x,y)$ for a general point in the (x,z) plane.
ex.2)
Find the gravitational force at a point a distance, $D$,from the base of a homogeneous cone of length $L$ base radius $R$, and mass $M$. The point is along the $z$ axis of the cone.
Conclusion
Any insight is helpful. I may not be asking my question properly in which case leave a comment and I can revise this accordingly.
I find that I am stuck at writing the integral on these problem; even though I think I have all the parts to go into the integral. I am confused on what I am integrating.
Is there an equation that looks like this:
$$
\Phi (r)=\int F(r)dr\quad\text{?}
$$
Answer: I'm going to assume you (and your prof or teacher) are using standard notation.
In that case, $U$ denotes the gravitational potential energy of a configuration of two (or more) objects interacting gravitationally. $\Phi$ denotes the gravitational potential of one object. The difference between them, is that $U$ requires (at least) two objects in order to be defined, while $\Phi$ is the potential of one object. If we are working in the two-body case, one (usually more massive) body with mass $M$ and one (usually smaller, test-body) with mass $m$, then once I figure out the gravitational field of: $\Phi=-GM/r$, I can easily obtain the gravitational potential energy of the two bodies together by: $U=m\Phi = -GMm/r$.
$U$ and $\Phi$ are related, but they are definitely NOT the same thing! You can tell just by the units. $U$ has units of energy whereas $\Phi$ has units of energy/mass.
Generally you obtain the gravitational potential $\Phi$ by breaking down the gravitating objects into small (differential) chunks, and then adding up each chunk's contribution to the overall gravitational potential.
So the general method of finding $\Phi$ is usually starting off with an integral like (treating each $dm$ as a point source):
$\Phi = -\int \frac{Gdm}{\vec{r}}$
And then expressing $dm$ as some product of a density (function) $\rho(\vec{r})$ and a small volume element $dV$ and then taking the volume integral over the gravitating object.
The gravitational $field$ is then a vector field of forces:
$\vec{F} = -\nabla \Phi$ | {
"domain": "physics.stackexchange",
"id": 44961,
"tags": "gravity, terminology, potential, potential-energy, notation"
} |
Problem conserving 4-momentum at CoM frame in an inelastic collision | Question: I am confused about the case where mass is not conserved in a collision (not due to relativistic factors). The center of momentum (CoM) frame is not the same before and after the collision.
Let's call frame 1 the initial CoM frame, and frame 2 the final CoM frame. So on the one end in frame 2: $p^{(2)}_{final}=0$ because it is the CoM frame. But on the other end in frame 1: $p^{(1)}_{initial}=0$, because it is also the CoM frame. As I understand it, there cannot be another frame where $p_{initial}=0$ apart from frame 1, therefore $p^{(2)}_{initial}\neq0$. So 4 momentum is not conserved.
Actually the Wiki page on CoM frame suggests there are several CoM frames, but I am assuming they do not differ by velocity but rather by point of origin?
In the simpler, non relativistic case, I found that by calculating $p_{initial}$ in the 2nd frame:
$$p^{(2)}_{initial} = p^{(Lab)}_{initial} \cdot \text{const} \neq 0$$
EDIT:
Here is the non-relativistic calculation (relativistic does not help). The process (in lab frame) is: $(M,\bar{\omega}) + (m,\bar{u}) \rightarrow (M+\delta,\bar{v}) + (m,\bar{u'})$. The velocity of the center of momentum in frame 2 is $\bar{s}^*$.
$$M^*=M+\delta \qquad \mu = \frac{M}{m} \qquad \mu^*=\frac{M^*}{m} \qquad \bar{s}^* = \frac{\mu^*\bar{v}+\bar{u'}}{1+\mu^*}$$
$$p^{(2)}_{initial}=M (\bar{w}-\bar{s^*}) + m (\bar{u}-\bar{s^*})=\left\{ M \bar{w} + m \bar{u} \right\} - \left\{ M \bar{s^*} + m \bar{s^*} \right\} $$
Using conservation of momentum in lab frame:
$$= \left\{ M^* \bar{v} + m \bar{u}' \right\} - \left\{ M \bar{s^*} + m \bar{s^*} \right\}$$
$$= m \left( \left\{ \mu^* \bar{v} + \bar{u}' \right\} - \bar{s^*} \left\{ \mu + 1 \right\} \right)$$
$$= m \left( \left\{ \mu^* \bar{v} + \bar{u}' \right\} - \frac{\mu^*\bar{v}+\bar{u'}}{1+\mu^*} \left\{ \mu + 1 \right\} \right)$$
$$= m \left\{ \mu^* \bar{v} + \bar{u}' \right\} \left( 1 - \frac{1}{1+\mu^*} \left\{ \mu + 1 \right\} \right)$$
$$= \left\{ M^* \bar{v} + m \bar{u}' \right\} \frac{\delta }{\delta +m+M}$$
$$= p^{(2)}_{initial} = p^{(lab)}_{initial} \frac{\delta }{\delta +m+M} \neq 0$$
But hey, you might think $\bar{s^*}$ isn't the right velocity, well lets see; Here is the (final) momentum in the center of momentum frame:
$$p^{(2)}_{final} = M^* (\bar{v}-\bar{s^*}) + m (\bar{u'}-\bar{s^*}) $$
$$= M^* \left(\bar{v}-\frac{\mu^*\bar{v}+\bar{u'}}{1+\mu^*}\right) + m \left(\bar{u'}-\frac{\mu^*\bar{v}+\bar{u'}}{1+\mu^*}\right)$$
$$= \left(M^* \bar{v}+m \bar{u'}\right) - (m + M^*) \left(\frac{\mu^*\bar{v}+\bar{u'}}{1+\mu^*}\right)$$
$$= \left(M^* \bar{v}+m \bar{u'}\right) - (m + M^*) \left(\frac{M^*\bar{v}+m \bar{u'}}{m + M^*}\right)$$
$$= \left(M^* \bar{v}+m \bar{u'}\right) - \left(M^*\bar{v}+m \bar{u'}\right) = 0$$
What am I not taking into consideration? What is the initial state of frame 2, $p^{(2)}_{initial}$?
Answer: What is missing: this must be recognized as a relativistic process and be treated accordingly.
Why is it a relativistic process: energy transforms into mass or conversely. This is something that cannot be accounted for using only classical mechanics. In older times I would've added "because it needs to account also for relativistic mass", but since using the term "relativistic mass" seems to be discouraged as of lately, I will "refrain".
What to do: Write energy-momentum conservation properly in the Lab frame:
$$
( E_\omega/c, p_\omega ) + ( E_u/c, p_u ) = ( E_\nu/c, p_\nu ) + ( E_{u'}/c, p_{u'} ) = ( E_{Lab}/c, p_{Lab} )
$$
Here energies and momenta relate to velocities and rest masses as
$$
E_\omega/c = \gamma_\omega M_0c, \;\; p_\omega = \beta_\omega(E_\omega/c) = (\beta_\omega c)(\gamma_\omega M_0) = (\gamma_\omega M_0)\omega
$$
$$
E_u/c = \gamma_u m_0c, \;\; p_u = \beta_u(E_u/c) = (\beta_u c)(\gamma_u m_0) = (\gamma_u m_0)u
$$
etc, with the usual relativistic notation for adimensional velocities $\beta_\omega$, $\beta_u$, and $M_0$, $m_0$, etc, the rest masses for the corresponding particles. Note that you can write the momentum conservation law in the quasi-classical form
$$
M\omega + mu = (M + \delta)\nu + mu'
$$
only provided the masses $M$, $m$ are understood to be the "relativistic" masses $\gamma_\omega M_0$, $\gamma_u m_0$ in the Lab frame, not the rest masses $M_0$, $m_0$. This is what caused you trouble.
If we want to transform to the COM frame, we need only identify the correct boost velocity from the total energy and momentum, $\beta = p_{Lab}c/E_{Lab}$, and apply the corresponding Lorentz transform. The new energies and momenta read:
$$
p'_\omega = \gamma [ p_\omega - \beta E_\omega/c ], \;\;
E'_\omega/c = \gamma [E_\omega/c - \beta p_\omega ]
$$
$$
p'_u = \gamma [ p_u - \beta E_u/c ], \;\;
E'_u/c = \gamma [E_u/c - \beta p_u ]
$$
$$
p'_\nu = \gamma [ p_\nu - \beta E_\nu/c ], \;\;
E'_\nu/c = \gamma [E_\nu/c - \beta p_\nu ]
$$
$$
p'_{u'} = \gamma [ p_{u'} - \beta E_{u'}/c ], \;\;
E'_{u'}/c = \gamma [E_{u'}/c - \beta p_{u'} ]
$$
Now we can check that, given energy-momentum conservation in the Lab frame, in the COM we find
$$p'_\omega + p'_u = \gamma [ (p_\omega + p_u) - \beta (E_\omega + E_u)/c ] = \gamma ( p_{Lab} - \beta E_{Lab}/c ) = \gamma ( \beta E_{Lab}/c - \beta E_{Lab}/c ) = 0
$$
and similarly,
$$
p'_\nu + p'_{u'} = \gamma [ (p_\nu + p_{u'}) - \beta (E_\nu + E_{u'})/c ] = \gamma ( p_{Lab} - \beta E_{Lab}/c ) = \gamma ( \beta E_{Lab}/c - \beta E_{Lab}/c ) = 0
$$
So there is a single COM after all, as expected. | {
"domain": "physics.stackexchange",
"id": 24055,
"tags": "special-relativity, kinematics, conservation-laws, collision, inertial-frames"
} |
What is the most appropriate way to estimate the helium composition of a star? | Question: Say we have to estimate the helium content in Proxima Centauri.
We begin by calculating the content of helium in the Sun (source): $24.85$% of $2.10^{30}$ kg.
Mostly all the energy is generated due to the product of nuclear fusion of hydrogen into helium by way of the proton–proton (PP) chain mechanism and the luminosity of Proxima Centauri is $0.00005\ L_☉$.
Thus, would it be a good approximation to say that the helium content is $0.00005 * 0.2485 * 2 * 10^{30}$?
Would you suggest a better way of estimating the helium content?
Answer: Nearly all the helium in the photosphere of the sun comes from the helium in the interstellar gas that collapsed to form the sun. That helium was produced shortly after the Big Bang (in about the first 20 minutes) while the universe was hot and dense enough for hydrogen to fuse to helium. That produces a universe in which ordinary matter is about 25% helium and 75% hydrogen. (by mass) Over the eons, the gas is enriched in helium somewhat by previous stars to about 27% helium.
The outer layers of the sun still have this 25%-75% composition. Some of the helium has settled under gravity, reducing the composition of the photosphere to your 24.85% helium. The core is enriched in helium by fusion reactions. It isn't constant. The outer core is about 30% helium. The inner core has as much as 65% helium. The average composition is about 28% helium, only slightly more than what it started with.
Proxima Centauri is fully convective, which means that helium from the core gets mixed up through the whole star. But it is such a dim candle that it has hardly produced any more helium than when it formed: about 27%.
So for any star, no matter how bright or dim (with a few exceptions) the helium composition is about 25%, or a little more. | {
"domain": "astronomy.stackexchange",
"id": 4389,
"tags": "star, luminosity, helium"
} |
Struct that parses full name into first name, middle name, last name and suffix | Question: The struct below parses full name into first name, middle name, last name and suffix.
Perhaps Builder pattern is more appropriate here? I remember there was a principle referring to the number of constructor parameters which Builder solves.
record vs struct? Records inherit from IEquatable. https://sharplab.io/#v2:CYLg1APgAgzABAJwKYGMD2DhwB4FgBQA3gXHAJYB2ALnAIYDcBAvgUA=
Is it a good idea to replace Parse with TryParse pattern?
Code
/// <summary>
/// Represents a person's name.
/// </summary>
public struct FullName : IEquatable<FullName>, IFormattable
{
/// <summary>
/// Initializes a new instance of the <see cref="FullName" /> struct.
/// </summary>
/// <param name="firstName">The given name.</param>
/// <param name="lastName">The family name.</param>
/// <param name="middleName">The middle name.</param>
/// <param name="suffix">The suffix.</param>
public FullName(string? firstName, string? lastName = default, string? middleName = default,
string? suffix = default)
{
FirstName = firstName;
MiddleName = middleName;
LastName = lastName;
Suffix = suffix;
}
/// <summary>
/// Gets or sets the person's first name.
/// </summary>
public string? FirstName { get; set; }
/// <summary>
/// Gets or sets the middle name.
/// </summary>
public string? MiddleName { get; set; }
/// <summary>
/// Gets or sets the person's last name.
/// </summary>
public string? LastName { get; set; }
/// <summary>
/// Gets or sets the suffix. (e.g. PhD, Jr, etc)
/// </summary>
public string? Suffix { get; set; }
/// <summary>
/// Parses the specified text.
/// </summary>
/// <param name="text">The text.</param>
public static FullName Parse(string text)
{
if (string.IsNullOrEmpty(text))
{
return new FullName();
}
var parts = text.Split(' ');
string? Get(int idx)
{
return idx >= parts.Length ? null : parts[idx];
}
switch (parts.Length)
{
case 1:
case 2:
return new FullName(Get(0), Get(1));
case 3:
var last = Get(2);
return IsSuffix(last)
? new FullName(Get(0), Get(1), default, last)
: new FullName(Get(0), Get(2), Get(1));
case 4:
return new FullName(Get(0), Get(2), Get(1), Get(3));
}
return new FullName();
}
#region IFormattable
/// <summary>Converts to string.</summary>
/// <returns>A <see cref="System.String" /> that represents this instance.</returns>
public override string ToString()
{
return string.Join(" ", FirstName, MiddleName, LastName, Suffix).Replace(" ", " ").Trim();
}
/// <summary>
/// Converts to string.
/// </summary>
/// <param name="format">The format.</param>
/// <returns>
/// A <see cref="System.String" /> that represents this instance.
/// </returns>
public string ToString(string format)
{
return ToString(string.Concat("{0:", string.IsNullOrEmpty(format) ? "G" : format, '}'), Formatter);
}
/// <summary>
/// Converts to string.
/// </summary>
/// <param name="format">The format.</param>
/// <param name="formatProvider">The format provider.</param>
/// <returns>
/// A <see cref="System.String" /> that represents this instance.
/// </returns>
public string ToString(string? format, IFormatProvider? formatProvider)
{
return string.Format(formatProvider ?? Formatter, string.IsNullOrEmpty(format) ? "{0:G}" : format, this);
}
public static implicit operator string(FullName obj)
{
return obj.ToString();
}
public static explicit operator FullName(string obj)
{
return Parse(obj);
}
#endregion IFormattable
#region IEquatable
/// <summary>
/// Determines if the specified names are equal.
/// </summary>
/// <param name="a">The first name.</param>
/// <param name="b">The other name.</param>
/// <param name="comparison">The comparison (defaults to <see cref="StringComparison.InvariantCultureIgnoreCase" />).</param>
public static bool Equals(FullName a, FullName b,
StringComparison comparison = StringComparison.InvariantCultureIgnoreCase)
{
return
string.Equals(a.FirstName, b.FirstName, comparison) && string.Equals(a.MiddleName, b.MiddleName, comparison)
&& string.Equals(a.LastName, b.LastName, comparison)
&& string.Equals(a.Suffix, b.Suffix, comparison);
}
public static bool operator ==(FullName x, FullName y)
{
return Equals(x, y);
}
public static bool operator !=(FullName x, FullName y)
{
return !Equals(x, y);
}
/// <summary>
/// Indicates whether the current object is equal to another object of the same type.
/// </summary>
/// <param name="other">An object to compare with this object.</param>
/// <returns>
/// true if the current object is equal to the <paramref name="other">other</paramref> parameter; otherwise, false.
/// </returns>
public bool Equals(FullName other)
{
return Equals(this, other);
}
/// <summary>
/// Determines whether the specified <see cref="System.Object" />, is equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="System.Object" /> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="System.Object" /> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object? obj)
{
return obj is FullName name && Equals(this, name);
}
public override int GetHashCode()
{
return
FirstName?.GetHashCode() ?? 0 ^
MiddleName?.GetHashCode() ?? 0 ^
LastName?.GetHashCode() ?? 0 ^
Suffix?.GetHashCode() ?? 0;
}
#endregion IEquatable
#region Backing Members
internal static bool IsSuffix(string text)
{
// NOTE: A suffix is a string that ends with a period (.)
// or has a uppercase beyond the first character.
if (string.IsNullOrEmpty(text))
{
return false;
}
if (text[^1] == '.')
{
return true;
}
for (var i = 1; i < text.Length; i++)
{
var c = text[i];
if (char.IsLetter(c) && char.IsUpper(c))
{
return true;
}
}
return text.Length is 3 or 4 || IsAllCaps(text);
}
internal static bool IsAllCaps(string text)
{
return text.All(c => !char.IsLetter(c) || !char.IsLower(c));
}
private static NameFormatter? _formatter;
private static NameFormatter Formatter => _formatter ??= new NameFormatter();
#endregion Backing Members
}
internal class NameFormatter : ICustomFormatter, IFormatProvider
{
public string Format(string? format, object? arg, IFormatProvider? formatProvider)
{
if (arg is FullName name)
{
var n = format.Length;
var builder = new StringBuilder();
for (var i = 0; i < n; i++)
{
char c;
switch (c = format[i])
{
default:
builder.Append(c);
break;
case 'G':
builder.Append(name.ToString());
break;
case 'S':
builder.Append(string.Join(" ", name.FirstName, name.LastName).Trim());
break;
case '1':
case 'f':
case 'F':
builder.Append(name.FirstName);
break;
case '2':
case 'm':
case 'M':
builder.Append(name.MiddleName);
break;
case '3':
case 'l':
case 'L':
builder.Append(name.LastName);
break;
case '\\': /* Escape */
builder.Append(i + 1 < n ? format[++i] : c);
break;
}
}
return builder.ToString().Trim();
}
return GetFallbackFormat(format, arg);
}
public object? GetFormat(Type? formatType)
{
return formatType == typeof(ICustomFormatter) ? this : null;
}
private string? GetFallbackFormat(string format, object? arg)
{
if (arg is IFormattable formattable)
{
return formattable.ToString(format, CultureInfo.CurrentCulture);
}
return arg != null ? arg.ToString() : string.Empty;
}
}
Unit tests
public sealed class FullNameTests
{
[Theory]
[InlineData("Иван Иванов", "Иван", default, "Иванов")]
[InlineData("Анна-Мария Драганова Иванова", "Анна-Мария", "Драганова", "Иванова")]
public void Build_ShouldReturnCorrectUsernamePassword_WhenGivenFullName(
string fullName,
string expectedFirstName,
string expectedMiddleName,
string expectedLastName)
{
// Arrange
// Act
var actual = FullName.Parse(fullName);
// Assert
actual.FirstName.Should().Be(expectedFirstName);
actual.MiddleName.Should().Be(expectedMiddleName);
actual.LastName.Should().Be(expectedLastName);
}
}
Answer: Lots of questions here.
/// <param name="firstName">The given name.</param>
/// <param name="lastName">The family name.</param>
/// <param name="middleName">The middle name.</param>
/// <param name="suffix">The suffix.</param>
Why are you expecting first-last-middle? Why would someone not put their middle name in the middle?
public string? FirstName { get; set; }
For the name properties, why do they have public setters? Are you expecting external classes to change someone's name? I would make them private or protected: public string? FirstName { get; protected set; }, etc.
for (var i = 1; i < text.Length; i++)
{
var c = text[i];
if (char.IsLetter(c) && char.IsUpper(c))
{
return true;
}
}
For checking if a name is a suffix or not, why do you keep looking past the second letter? If someone's name were Betsy DeVos (American politician) then the last name DeVos would trigger as a suffix because you keep looking for a capital letter. I would flip the check here, if any letter is NOT capital then it's false (not a suffix). If you check all the letters and don't return false; then you should return true.
if (string.IsNullOrEmpty(text))
{
return new FullName();
}
Why would you allow an empty name? You're in Parse(), not TryParse(), so (IMO) it's okay to throw here. I'd do an invalid argument exception. Speaking of which, I think you could easily implement a TryParse as well, if you throw from Parse:
public static bool TryParse(string text, out FullName name)
{
name = new FullName();
try
{
name = Parse(text);
return true;
}
catch
{
return false;
}
}
anything that's not valid causes Parse to fail, which would cause TryParse to return false. Since it's returning false the out name is assumed to be invalid.
return text.Length is 3 or 4 || IsAllCaps(text);
Back on the IsSuffix check, why does it matter about the length? I think your code would take Lana Del Rey (American singer) and treat her last name as a suffix because it's three letters long.
switch (parts.Length)
{
// ...
case 4:
return new FullName(Get(0), Get(2), Get(1), Get(3));
}
Last comment here, George H. W. Bush (former American president) has two middle names, which would trigger Bush to get treated as a suffix, both for being 4 letters long and for being the fourth argument in the name. And, because of the first-last-middle scheme, his name would get scrambled. This is also not mentioning people like José María Álvarez del Manzano y López del Hierro (Spanish politician), whose paternal surname is Álvarez del Manzano.
Ultimately, if you've got the ability to enforce first-last-middle, then I'd argue to enforce a comma to separate the suffix, like Charles Philip Arthur George, III or Saul Goodman, Esq. | {
"domain": "codereview.stackexchange",
"id": 43986,
"tags": "c#, parsing, .net"
} |
Maximum Limit of String in ROS2 | Question:
I am currently interfacing ROS2 with native RTI DDS Connext through RTI Connector for python.
In my ROS2 node, I have a custom message type which uses header messages from std_msgs. Now the header has a member string frame_id_. When the idl is generated for this msg, the size of the string is allocated as 2147483647 bytes. I can see this in the RTI Admin console. Now to match the Types in native DDS and ROS2, I need to give the same string size in RTI Connext through a QoS.xml file. But the problem is, this is too big a size for RTI to handle and the program crashes.
As a workaround, I modified the header_.idl in ROS2 lying in ROS2_base_ws/install/std_msgs/dds_connext/Header_.idl as string<255> frame_id_ i.e. I limited the max size of this string.
I recompiled it and ran the same node, but it always has the previous size i.e. 2147483647 bytes
Any other workaround ?
Originally posted by aks on ROS Answers with karma: 667 on 2018-08-01
Post score: 0
Answer:
Follow up of answer given at https://answers.ros.org/question/299305/how-is-the-size-of-a-string-allocated-in-ros2-idl/?answer=299311#post-id-299311
The way unbounded string are generated for connext is by using the -unboundedSupport flag of the connext generator: https://github.com/ros2/rosidl_typesupport_connext/blob/d3fd38825c4e460e156718c360886b43b20cc0c8/rosidl_typesupport_connext_cpp/rosidl_typesupport_connext_cpp/__init__.py#L79.
By not passing this flag when generating the connext code it should default to 255 as per their help message
-unboundedSupport Generates code that supports unbounded sequences and
strings.
This option is not supported in ADA.
When the option is used the command-line options sequenceSize and
stringSize are ignored.
This option also affects the way unbounded sequences are deserialized.
When a sequence is being received into a sample from the DataReader's
cache, the old memory for the sequence will be deallocated and memory
of sufficient size to hold the deserialized data will be allocated.
When initially constructed, sequences will not preallocate any
elements having a maximum of zero elements.
-stringSize <Unbounded strings size>: Size assigned to unbounded strings
The default value is 255
Note that based on the help message the size of the string allocated should be 0 and reallocated when needed so you should never reach the point where you allocate 2147483647 bytes.
A maybe easier way to fix your issue is to use the same -unboundedSupport flag when generating code for your native DDS application, this way you don't need to modify either the msg files or the Connext code generation within ROS 2.
Originally posted by marguedas with karma: 3606 on 2018-08-01
This answer was ACCEPTED on the original site
Post score: 0
Original comments
Comment by aks on 2018-08-01:
@marguedas : Is this file placed in src/ros2/rosidl_typesupport/rosidl_typesupport_cpp/rosidl_typesupport_cpp/__init__.py ? If yes, then I dont have the same file as the link you posted.
Comment by marguedas on 2018-08-01:
Based on the URL it is located at ros2/rosidl_typesupport_connext/rosidl_typesupport_connext_cpp/rosidl_typesupport_connext_cpp/__init__.py
The exact location can be different based on what version of ROS 2 you are using, my answers assume you are using ROS Bouncy
Comment by aks on 2018-08-01:
I am using ROS2 Ardent and I dont have any folder as rosidl_typesupport_connext located in ROS2.
Comment by aks on 2018-08-01:
@marguedas : I also posted a continuation to this here. This describes the strange behaviour also in the default examples.
Comment by marguedas on 2018-08-01:
Yes in ardent this package was located in the rmw_connext repository: ros2/rmw_connext/rosidl_typesupport_connext_cpp/rosidl_typesupport_connext_cpp/__init__.py | {
"domain": "robotics.stackexchange",
"id": 31437,
"tags": "ros, ros2, header, dds"
} |
What does it mean for $P$ functions to be "more singular than a delta"? | Question: Consider the Glauber-Sudarshan $P$ representation of a state $\rho$, which is the function $\mathbb C\ni\alpha\mapsto P_\rho(\alpha)\in\mathbb R$ such that
$$\rho = \int d^2\alpha \, P_\rho(\alpha) |\alpha\rangle\!\langle\alpha|.$$
Something that is often mentioned about the $P$ representation is that a state is nonclassical when $P_\rho$ is either non-positive or more singular than a Dirac delta function.
On the other hand, the $P$ representation of a coherent state $|\alpha\rangle$ is $P_\alpha(\beta)=\delta^2(\alpha-\beta)$, which does also arguably look "more singular than a $\delta$ function", in that it contains the square of a delta function, while $|\alpha\rangle$ is clearly not nonclassical.
So what gives? What exactly does "more singular than a delta" mean? The Wikipedia page gives the general expression for the $P$ function of a generic state, and this expression involves terms of the form $\big(\frac{\partial}{\partial r}\big)^\ell \delta(r)$, which I'm guessing are the source of "high degree of nonsingularity", and I'm aware that this is quite different than the $\delta^2$ term in the expression above, which is just the "standard" $\delta$ for the two-dimensional case, but I still find it quite unclear how exactly I should think about functions that are "more singular than a delta".
One possible way to understand what such functions actually represent is via some corresponding sequence of functions. For example, I can understand $\delta(x)$ as the limit of suitably normalised functions peaked around the origin, and $\delta^2(x)$ as the same thing for functions $\mathbb C\simeq \mathbb R^2\to\mathbb R$. Are there similar representations for the more nonsingular cases?
Answer: As you mention, the distinction here is that $\delta^2(\alpha-\beta)$ is not a derivative of a delta function, it is simply a delta function in two dimensions. Adding extra dimensions does not change the nature of the delta function in terms of how it behaves in integrals.
I will use the notation $\delta^2(\alpha-\beta)=\delta(x-x_0)\delta(y-y_0)$ because we typically abuse notation when we have functions of $\alpha$ and $\alpha^*$. We can consider $x$ and $y$ to be the real and imaginary parts of $\alpha$ and similarly $x_0$ and $y_0$ for $\beta$.
If you have any function of $\alpha$ and $\alpha^*$, ie a function of $x$ and $y$, you can integrate it with the two-dimensional delta:
$$\int dx dy \,\delta(x-x_0)\delta(y-y_0)f(x,y)=f(x_0,y_0).$$ This simply uses the definition of a delta function twice, so it does not give us any more trouble than one delta function. Of course, we need $f(x,y)$ to be finite at $(x_0,y_0)$, instead of just needing a function to be finite for some value of one parameter, so perhaps that is asking for more.
Now, if we have derivatives of delta functions, we consider them in terms of chain rule / integration by parts:
$$\int dx dy \,\frac{\partial^m}{\partial x^m}\delta(x-x_0)\frac{\partial^n}{\partial y^n}\delta(y-y_0)f(x,y)=(-1)^{m+n}\frac{\partial^{m+n}f(x,y)}{\partial x^m \partial y^m}\bigg{|}_{x=x_0,y=y_0}.$$ For this integral to converge, we need a lot more: we need $f(x,y)$ to be nonsingular after taking a whole bunch of derivatives! This is what it means for a function to be more singular than a delta function: it means that, when taken as a distribution and being used for integration, it asks more out of the function $f(x,y)=f(\alpha,\alpha^*)$ being integrated than what a delta function asks.
Edit: The steps with integration by parts also ask more from a function's behaviour at the limits of integration (often $x,y\to\pm\infty$). The delta function goes to zero very quickly so that is not normally an issue, but I can imagine there being functions that do not work so well once you take enough derivatives.
Further edit: One can show using integration by parts using a suitable trial function that $f(x)$ that $$\frac{\partial \delta(x)}{\partial x}=-\frac{\delta(x)}{x}.$$ This is where the singular nature of the distribution itself comes in to play: the distribution is only nonzero when $x=0$, but then there is a factor of $x$ in the denominator, which makes things singular. The more derivatives we take of a delta function, the higher the power of $x$ in the denominator.
Further edit continued: $\delta(x)$ seems singular at $x=0$, but it can be integrated and has area 1: $\int_{-\infty}^\infty dx \,\delta(x)=1$. On the other hand, $\partial_x \delta(x)$ "has no area" because $\int_{-\infty}^\infty dx \,\partial_x\delta(x)=0$. Still, if we multiply it by $x$, it regains an area of one: $\int_{-\infty}^\infty dx \,x\partial_x\delta(x)=-1$. This keeps going: for higher numbers of derivatives, derivatives of $\delta(x)$ seem to have no area, unless they are first multiplied by higher powers of $x$. So to "tame the singularity" of a derivative of a delta function, we need to do more work (multiply by $x^m$ then integrate) than to "tame the singularity" of a delta function (just integrate). | {
"domain": "physics.stackexchange",
"id": 79006,
"tags": "quantum-mechanics, quantum-information, quantum-optics, phase-space, quasiprobability-distributions"
} |
carbon electrodes have potential difference even with no electrical input? | Question: What is happening in this photo? I set up a simple electrolytic cell today of copper (II) sulfate solution with carbon electrodes. It was connected to a powerpack (set at ~8.0V), and a variable resistor with the resistance cranked up to its maximum as in the image below. You can also see the ammeter and the voltmeter in the photo.
When the powerpack was switched off, the current fell immediately to zero, as expected, but the voltmeter still read a non-zero number (initially 0.80V, then later seemed to decrease to 0.18 V). I turned the electrodes upside-down so that the clean ends were in solution (rather than the end covered in copper), but reading still read the same. Removed the electrodes to a beaker of water (but not deionised water), and it still read 0.18V or close to.
Tried the exact same thing with pure copper electrodes, but it read 0.00V immediately upon turning off the power supply.
Tried completely taking the leads out of the power supply (which was off anyway), and the carbon rods still read a non-zero value even with the circuit obviously incomplete.
What's happening here? Copper electrodes did not show the same effect. Is there something about carbon electrodes in particular that can make them act as a capacitor? The current stayed at 0.00A the whole time. This effect was NOT seen when the electrodes were lifted out of the solution/water.
Edit, to respond to the answer below:
This would be the most interesting answer.
I did consider initially this, so first I tried up-ending the
electrodes so the clean ends were in solution, but the reading
remained the same. Second, it showed no such behaviour with the pure
copper electrodes.
I think it's unlikely to be a case of the voltmeter left floating.
Surely if that had been it, regardless of which electrodes (copper or
carbon) were used, random static charges would've been present? Plus,
the phenomenon was reproduced when I swapped out different electrodes
and then swapped back in the funny-acting ones, so the behaviour
wasn't exactly random.
However, I did forget to mention, that I also tested this with a
second clean set of carbon electrodes and got 0.00V! Support for 2nd
explanation (but if so, how does that work exactly?). I still would've
liked it to have been the 1st explanation.
I also note that I left the apparatus overnight, and by next morning
the reading was 0.02V. I've unfortunately have had to clear the
materials away now, but if I get a moment I may try replicating the
result.
Answer: Some possibilities:
Porous carbon electrodes do act as a capacitor, the basis for supercapacitors (aka ultracapacitors).
You are electrolytically depositing copper on the negative electrode when you run current through the solution, even though it might not be enough to see. This creates an electrochemical cell.
Simply disconnecting the power supply leads will leave a high-impedance voltmeter floating, so it might be detecting random static charges. You might need to bypass the voltmeter with a high resistance (10 or 20 megohms) to reduce static sensitivity. | {
"domain": "chemistry.stackexchange",
"id": 4089,
"tags": "electrochemistry, electrolysis"
} |
mouse movement causes Gazebo death | Question:
I repost this from the DRC web site. I have had the same problem, and avoid moving my mouse over the Gazebo window as much as possible.
I realize this sounds like a totally bogus bug report and I am engaging in voodoo computer science, but there is no core dump or other evidence I can provide. Perhaps an instrumented version of Gazebo could be created that reports more information about why it quits or crashes.
From rel_dude, posted at
http://forum.theroboticschallenge.org/index.php?board=6.0
I have tried installed the DRC Simulator using these installation instructions: http://gazebosim.org/wiki/InstallDRC
However, the simulator keeps crashing. It seems to happen mostly when hovering over the control menu (with the rotation controls, for instance) although not exclusively.
The terminal shows: "Warning [gazebo_main.cc:57] escalating to SIGKILL on server"
Originally I thought it might be a problem with nVidia drivers although it seems to happen on non-nVidia cards as well.
Originally posted by cga on Gazebo Answers with karma: 223 on 2012-11-01
Post score: 0
Original comments
Comment by DRC_Justin on 2012-11-05:
I have observed this issue as well, but only when running the basic Gazebo v1.2.x. If you run the full DRCSim package including the ROS libraries, I believe this may not be as significant of a problem. But the OSRF team can answer better than I.
Answer:
That sounds like bug #119. We believe that it was fixed in pull request #59. That fix will be included in a near-term patch release.
Originally posted by gerkey with karma: 1414 on 2012-11-05
This answer was ACCEPTED on the original site
Post score: 0 | {
"domain": "robotics.stackexchange",
"id": 2786,
"tags": "gazebo"
} |
How to rewrite the frameid in a rosbag? | Question:
I recorded a rosbag and tried to visualize it in Rviz. I get the following message MessageFilter [target=left_hand ]: Discarding message from [unknown_publisher] due to empty frame_id. This message will only print once. On doing a rostopic echo, I can see that the frame_id is empty. I ran rosrun tf view_frames to generate the pdf.
How do I rewrite the header frame id?
Originally posted by Joy16 on ROS Answers with karma: 112 on 2017-04-17
Post score: 0
Answer:
rosbag has a python API that you can use for reading and creating new bag files; have a look at the rosbag cookbook and the rosbag API
Originally posted by ahendrix with karma: 47576 on 2017-04-17
This answer was ACCEPTED on the original site
Post score: 1 | {
"domain": "robotics.stackexchange",
"id": 27629,
"tags": "rosbag"
} |
If a surface can be only be scratched by a harder material then why finger rings wear out after few years? | Question: A surface can only be scratched by a harder material. But we see so many examples where this is not true.
Stone floor becomes smooth even if pedestrians walk barefoot. How can human skin be harder than stone?
Metal rings like gold, silver and brass become smooth after being continuously worn.
St Peter's foot at Peter's Basilica in Rome worn out due to people touching it for years.
Is it because of chemical reaction with water, sweat etc. eating away the metal? Or can a surface be scratched very slightly even by a softer material?
Answer: There are three major items you're missing:
A soft surface can be contaminated with hard grains
Other answers have touched on this already, but it's worth repeating here. If I'm walking up a stone staircase barefoot, I have to work very hard to make sure that the only material in contact with the stone is my skin. Almost certainly my feet will pick up grains of varying size and hardness from the soil and the rest of the environment. The action of walking will move those grains around on the stone's surface, like a low-quality polishing cloth, selectively breaking off sharp protrusions — the fragments of which become fresh polishing grains.
Even for a hands-only artifact like St. Peter's foot: suppose I'm the last person to touch it for the day, and my hands are sweaty. When the water from my sweat has evaporated, there will be a rime of salt crystals left behind, to be unwittingly smeared by the next person to touch that spot.
A soft surface can still damage a hard surface
A surface can only be scratched by a harder material.
This is an approximate statement, not an exact law.
Suppose I have a mass which is suspended between two springs of equal stiffness:
--((((((-- [mass] --((((((--
(I don't seem to have a good "coil" character on my ASCII keyboard.) If I push the two ends of this apparatus together, because the springs have the same stiffness, they'll compress the same amount. However, suppose that I stiffen the left side by adding some more springs in parallel:
--((((((-- [ ]
--((((((-- [mass] --((((((--
--((((((-- [ ]
Now, if you compress the sides together, the mass is going to move until the force from the left and the force from the right are the same. But since we have more springs on the left, that side only needs to compress a third as much as the other. If the stiffness on either side is asymmetric, compression will push the mass towards the softer side. And if the stiffness is strongly asymmetric, it may be a useful approximation to say that "all" of the deformation is on the squashier side. But a useful approximation is still an approximation.
For "scratching" we are interested in plastic deformations, not in elastic deformations. But the same sort of rules apply for the plastic deformations that are the basis of the classic Mohs hardness test:
Frequently, materials that are lower on the Mohs scale can create microscopic, non-elastic dislocations on materials that have a higher Mohs number. While these microscopic dislocations are permanent and sometimes detrimental to the harder material's structural integrity, they are not considered "scratches" for the determination of a Mohs scale number.
Skin, unlike stone, is subject to homeostasis
Here's an experiment you can probably do right now. Grab a pencil and make a mark on some scrap of paper. Then wet your thumb and use it to "erase" the mark you've just made. This works ... kind of. It's much, much less efficient than the rubber eraser on the back of the pencil. You're also much more likely to end up tearing a hole in the paper with a wet thumb than you are with a rubber eraser. And if you actually try it, you'll realize pretty quickly that, if you kept at it for long, you could give yourself an unpleasant abrasion injury, rubbing away the skin on your thumb nearly as much as rubbing away the fiber layers on the paper.
But, suppose you rub on a piece of paper until the paper is torn and your thumb is abraded. Put it away for a week and come back. The paper will still be torn, but your thumb will be intact again.
In the case of the statue in Rome, it has been an object of pilgrimage for centuries; many of the people who have touched it have produced entirely new pilgrims, their children, to return and touch it again. The statue has had no such advantage.
Fermi estimation: how much of the statue is removed by one touch?
Let's do an order-of-magnitude estimate.
Suppose the foot of the statue has been shortened by one centimeter from its original size. (One millimeter is too short; one decimeter is too long.)
How many people touch the statue in a year? A million seems high: that would be two per minute, round the clock. Call it 100,000 touches per year.
How long has the wear been taking place? The statue might be 1000 years old (with a most probable sculptor active before the year 1300), but the pilgrimage industry is much more vigorous with the advantages of modern travel. Ten years is clearly too short. Call it 100 years.
So with these ballpark estimates, we have a centimeter of the statue removed by $10^7$ touches, or each touch shortening the statue by a nanometer. Pure copper has a lattice spacing of about 0.36 nm; our order-of-magnitude estimate is consistent with the "average touch" removing one-ish layers of copper atoms from the bronze of the statue. That size of an effect seems much easier to imagine causes for. | {
"domain": "physics.stackexchange",
"id": 83750,
"tags": "friction, material-science"
} |
One loop diagram in $\phi^4$ theory | Question: I know that in the $\phi^4$ theory the tree-level diagram for two in-going and two out-going particles is simply a 'cross' where all the external legs meet at one point.
I'm now interested in a slightly more complicated case where I have 4 rather than 2 outgoing particles and I want not only the tree level diagram but also the one loop diagram. I think I know what the tree-level diagram looks like, but I have some trouble drawing the one loop one. I know that each vertex needs to have 4 lines connected to it. I managed to come up with something but it was just trial and error and I'd like someone to verify whether what I've done is right.
My attempt is:
Answer: Yes, that is the correct one loop topology that appears assuming no snail and/or one particle reducible contributions (inclusion of these gives you a plethora of other diagrams, such as ones where you decorate the tree level contribution with snails etc). With a labelling of the external momenta in place, you can show by simple combinatorics the number of inequivalent permutations of the external legs you have. The contributing diagrams are essentially generated by attaching two legs to each vertex of a triangle.
Naively there are $6!$ permutations of the external legs but to avoid overcounting due to equivalent diagrams related by vertex relabelling we have to thereby divide out by the cardinality of the symmetry group of the triangle which is $|S_3| = 3!$ Now, we also need to divide out by the permutation of two legs at each of the three vertices. So the number of contributing diagrams is $6!/(3! \cdot (2!)^3) = 15$.
The same argument can be applied to e.g the more familiar one loop contribution to $2 \rightarrow 2$ scattering within $\phi^4$ (the so-called dinosaur diagram discussed in many QFT books in the pursuit of renormalisation of the theory at one loop). By exactly the same argument the number of contributing diagrams is $4!/(2! \cdot (2!)^2) = 3$, the $s, t$ and $u$ like channel contributions. | {
"domain": "physics.stackexchange",
"id": 40367,
"tags": "homework-and-exercises, quantum-field-theory, scattering, feynman-diagrams"
} |
Navigating using RGBDSLAM | Question:
Has anyone used RGBDSLAM for navigation and/or obstacle avoidance? If yes, are there any available packages? I was thinking of combining RGBDSLAM with the explore package, but I might not have enough experience yet to program it myself.
Originally posted by Zayin on ROS Answers with karma: 343 on 2013-05-27
Post score: 0
Original comments
Comment by ayush_dewan on 2013-05-27:
What kind of camera are you using for RGBD slam??
Comment by Zayin on 2013-05-27:
Asus Xtion
Answer:
I am not sure whether a specific package exist for exploring using RGBD slam. If exploring is ur final aim then u can use pointcloud_to_laserscan package and then, those laserscan can be used to create 2d map which can be used for exploration. Checkout turtlebot navigation packages. It covers lot of details but instead of a stereo camera, it uses Kinect.
Hope this helps...
Originally posted by ayush_dewan with karma: 1610 on 2013-05-27
This answer was ACCEPTED on the original site
Post score: 2
Original comments
Comment by Zayin on 2013-05-27:
Thanks, I will look into that. However, that means that the robot could bump into higher objects that can't be detected on a 2D floor map.
Comment by ayush_dewan on 2013-05-27:
If there are some objects hanging in the air, then it might happen ...
Comment by Zayin on 2013-05-28:
My robot is about 1m high (it has an arm, etc), so it could bump into a table with legs or something of the sort. That's why I wanted to use 3D nav & obstacle avoidance. I guess I could extract a few 2D maps at different z coordinates.
Comment by gautam2410 on 2013-08-12:
So did you make any progress with this? Actually, I am working on a similar project and would really appreciate it if you could help me out.
Thanks..
Comment by Zayin on 2013-08-13:
Unfortunately, I haven't. I realized that my robot's computer lacks GPU resources to use RGBDSLAM for such a task... The program becomes too slow after mapping a small room. Hence, I'm just using the standard explore package.
Comment by Zayin on 2013-08-13:
Maybe this would help you if you're interested in explore: http://answers.ros.org/question/64461/fuerte-explore-package-in-a-real-environment-problem-again/
Comment by gautam2410 on 2013-08-13:
I'll look into the modified explore package you developed...Thanks | {
"domain": "robotics.stackexchange",
"id": 14319,
"tags": "ros, slam, navigation, avoidance"
} |
Horizontal component of Coriolis force in an aircraft: compensating force with its wings angle | Question: I have the following problem:
"An aircraft is flying at 800 km/h in latitude 55◦ N. Find the angle through which it must tilt its wings to compensate for the horizontal component of the Coriolis force."
What I understand is that the aircraft follows the trajectory of the Earth's circle in latitude 55. So, since the Coriolis force (Fc) is the vectorial product -2w^r' (w is the angular momentum and r' the velocity in the rotating frame), it points inside or outside the Earth.
In the image, we have the first case:
So, if the aircraft is moving westward, we have the situation in the image, there is a component of the Coriolis Force trying to move the direction of the aircraft northward.
The problem is that I simply can't go on with these informations and find the angle (the answer is 0,155◦).
My specific question may be simpler than the concepts of the problem itself, but there it is: how can I compensate a force northwards only changing the angle of the flight? I can understand if there is a wind pushing the aircraft, I can find a direction to the velocity of the airplane that have one component that exactly vanishes the wind contribution. But how can I vanish a force? Is there a force that appears by changing the angle of the flight?
And more than that, if I change the angle, that wouldn't change also the direction and size of the Coriolis force and we should need another angle to compensate this new component of the Coriolis force?
(I'm not a native speaker, sorry for any language mistake)
Answer: On a level flight, you know that all the vertical forces must sum to zero (or you'd be accelerating upward or downward).
By banking the airplane, you can change the direction of the force from the wings. When flying straight, all force is vertical. When banking, a component of the force is vertical and a component is horizontal. The relative sizes of the components depend on the bank angle.
When considering the Coriolis force, you need the wing to continue to supply a vertical force equal to the vertical force when not banked and a horizontal force of some amount. That can only happen at some particular angle. | {
"domain": "physics.stackexchange",
"id": 55786,
"tags": "rotational-dynamics, aircraft, coriolis-effect"
} |
Developing a method of programming a multi-level menu | Question: I am attempting to create my own speech to text assistant. This involves the user speaking and the assistant responding to the user's input. I do this by looking for keywords that indicate the user wants to initiate a certain command. However, some commands can only be accessed if prior commands have been called already (e.g. Open Contacts > Search for Jim > Edit Number). I don't want Edit Number to be called unless Open Contacts and "Search for XXX" is called first.
Because of this, I have resorted to using an Enum class to label where the user is in the sequence of commands. Then, I use a switch to determine which lines of code to execute once I identify where the user is in the program. This seems unnecessarily complex and not easily maintainable. I was not able to find anything online about this since I don't know any keywords for this technique/process.
Is there a more efficient and maintainable way of programming the navigation for a menu interface such as this?
public void interpretResults(String results){
switch (primaryStage) {
case firstStage:
switch (results) {
case "identification":
case "id":
setMessage(EnumPPSAssistantMessages.message_IDNumber);
id = 0;
primaryStage = EnumStages.secondStage;
break;
case "lotnumber":
case "lot":
setMessage(EnumPPSAssistantMessages.message_lotNumber);
id = 1;
primaryStage = EnumStages.secondStage;
break;
case "list":
case "listall":
startNewActivity(ListAllOnline.class);
break;
case "usedcomponents":
case "usedcomponent":
setInput("Use component(s).");
case "usecomponents":
case "usecomponent":
setMessage(EnumPPSAssistantMessages.message_shopOrderNumber);
id = 3;
primaryStage = EnumStages.secondStage;
break;
case "bom":
case "billofmaterials":
setMessage(EnumPPSAssistantMessages.message_shopOrderNumber);
id = 2;
primaryStage = EnumStages.secondStage;
break;
case "returncomponents":
case "returncomponent":
setMessage(EnumPPSAssistantMessages.message_shopOrderNumber);
id = 4;
primaryStage = EnumStages.secondStage;
break;
case "usedparts":
case "usedpart":
setInput("Use part(s).");
case "useparts":
case "usepart":
setMessage(EnumPPSAssistantMessages.message_shopOrderNumber);
id = 5;
primaryStage = EnumStages.secondStage;
break;
case "returnparts":
case "returnpart":
setMessage(EnumPPSAssistantMessages.message_shopOrderNumber);
id = 6;
primaryStage = EnumStages.secondStage;
break;
case "pdf":
case "displaypdf":
setMessage(EnumPPSAssistantMessages.message_shopOrderNumber);
id = 7;
primaryStage = EnumStages.secondStage;
break;
case "commands":
setMessage(EnumPPSAssistantMessages.message_commands);
break;
case "":
default:
System.out.println("No match. Input is: " + temp);
setMessage(EnumPPSAssistantMessages.error_noMatch);
break;
}
break;
case secondStage:
switch (results) {
case "back":
case "go back":
id = -1;
primaryStage = EnumStages.firstStage;
setMessage(EnumPPSAssistantMessages.start_message);
return;
}
Variables.setVoiceOutput(func.formatSpeechInput(var.getVoiceOutput()));
setInput(var.getVoiceOutput());
switch (id) {
case 0:
case 1:
primaryStage = EnumStages.thirdStage;
break;
case 2:
startNewActivity(DisplayBillOfMaterials.class);
break;
case 3:
startNewActivity(ShopOrderTransactionPreCheck.class, new String[]{"type"}, new String[]{"usecomponents"});
break;
case 4:
startNewActivity(ShopOrderTransactionPreCheck.class, new String[]{"type"}, new String[]{"returncomponents"});
break;
case 5:
startNewActivity(ShopOrderTransactionPreCheck.class, new String[]{"type"}, new String[]{"useparts"});
break;
case 6:
startNewActivity(ShopOrderTransactionPreCheck.class, new String[]{"type"}, new String[]{"returnparts"});
break;
case 7:
startNewActivity(DownloadShopOrderPDF.class);
break;
case -1:
primaryStage = EnumStages.firstStage;
setMessage(EnumPPSAssistantMessages.start_message);
}
break;
}
}
Answer: Something I might do instead of using a switch with a bunch of constant strings. I might have a HashMap<String, Runnable> Where I would register each string and the action that should be taken.
e.g.
HashMap<String, Runnable> registeredAction = new HashMap<>();
Runnable runnable = new Runnable() {
@Override
public void run() {
setMessage(EnumPPSAssistantMessages.message_IDNumber);
id = 0;
primaryStage = EnumStages.secondStage;
}
});
registeredAction.put("some-value", runnable);
registeredAction.put("some-value-2", runnable);
Now when you want to perform an action you can just look it up.
Runnable action = null;
if((action = registeredAction.get("SomeString")) != null) {
action.run();
}
I don't think its best practice this is just how I would go about doing it. Instead of having a massive switch statement. | {
"domain": "codereview.stackexchange",
"id": 31671,
"tags": "java, android"
} |
How to tell the order of a Feynman diagram? | Question: How can we know the order of a Feynman diagram just from the pictorial representation?
Is it the number of vertices divided by 2?
For example, I know that electnro-positron annihilaiton is first order:
So what's the order of, for instance, a radiative penguin diagram (below) ?
Answer: Using elementary graph theory identities one can show that the number of loops in a connected diagram is related to the number of external lines and the number of vertices of type $i$ each of which has $n_i$ lines attached to it, is related by
$$
\sum \left(\frac{n_i}{2}-1\right) V_i -\tfrac{1}{2}E +1= L
$$
So you can see that for a fixed process (fixed $E$), knowing the number of vertices of each type is equivalent to knowing the number of loops (which can correspond to a multitude of diagrams in the same "order").
In the standard model we have two classes of vertices; those with three or four lines. So as you can see specifying the total number of vertices (equivalently the order with respect to the sum of powers of all coupling counstants), isn't going to uniquely fix the number of loops, however specifying the number of vertices of each class, you can get a one to one correspondence between loop order and coupling constant power order, in which case both are equivalent to the quantum mechanical expansion in powers of $\hbar$.
Derivation:
To derive this formula you can treat each external line as type of vertex with only one line attached to it. That is $E\equiv V_1$ and corresponding to it $n_1=1$. Then we can rewrite
$$
\sum \left(\frac{n_i}{2}-1\right) V_i +1= L
$$
This formula can be understood by recursion, first we prove it's true for zero vertices, but this is obvious since for zero vertices we do have $L=1$, just draw a circle!
Now to prove by recursion we assume the formula is correct, and prove that if we add one vertex of type $i$, we must introduce $(n_i/2-1)$ new loops. This can be easily seen by taking your diagram and putting a vertex anywhere on an internal line (notice that we no longer distinguish between internal and external lines because $E$ is just another type of vertex now).
When you insert this vertex, two of it's legs are already eaten automatically, so we need to connect the remaining $n_i-2$ legs, note that we must connect them with each other, because all other vertices are already saturated, and leaving a leg hanging is equivalent to introducing an external vertex which we are not doing by assumption. Now this is only possible if $n_i$ is even, in which case we get $(n_i-2)/2$ new loops, which proves the recursion for even vertices. If the vertex is odd, we must introduce them in pairs and the same discussion ensues. | {
"domain": "physics.stackexchange",
"id": 21146,
"tags": "quantum-field-theory, terminology, feynman-diagrams, perturbation-theory, interactions"
} |
How to calculate required torque | Question: Currently I'm doing a personal project, but I've some doubts about the calculation process. Well, I've a platform (2.30m length x 0.32m width). This platform is supported by 4 wheels with a diameter equals 120mm. This platform loads a motorbike. The maximum mass (platform + motorbike) that it will move is about 400kg. The surfaces contact are rubber with concrete (coefficient of friction 0.45). Rolling coefficient I think is 0.02). I'm uncertain wether to put 2 driven wheels or 4. The platform must travel a distance of 7 m. For the process I propose a speed of 0.1 m / s.
Well, How can I calculate the required torque to move this platform with a motorbike?
Answer: Let's get a few things out of the way first.
Torque or force have nothing to do with the speed, they interact with angular momentum or acceleration.
Also if the travel path is level you will be fine with just two driven wheels
To figure the force needed let's say we apply enough force so that at the end of the 7m the speed changes from zero to 0.1m/s' as you mention and then the brakes engage.
$ x=\frac{v^2}{2a} \ ,\ a=\frac{v^2}{2x}$
So $a=\frac{0.1^2}{2*7} =0.01/14=0.0007$
$ F=ma =400kg*9.8*0.0007=2.8N\quad 2.8*1.02 =2.86\ \text{after the friction } $
this force should be divided by two for individual wheel and converted to torque applied at radius of 0.06m.
$ 2.86/(2*0.06)=24Nm \ \text{torqe/wheel} $ | {
"domain": "engineering.stackexchange",
"id": 2876,
"tags": "mechanical-engineering, mechanical, industrial-engineering"
} |
Reference needed for lower bound on number of guards in three-dimensional art gallery guarding | Question: During my research (writing my master's thesis) I've stumbled across the book Art Gallery Theorems and Algorithms by O’Rourke.
In chapter 10 (pdf available on the above site), section 10.2.2. he shows a lower bound of $\Omega\left(n^{3/2}\right)$ on the number of guards needed in three-dimensional art gallery guarding. He says (bold marking is by myself):
In fact, we describe in this section a polyhedron constructed by Seidel that has these two properties.
I believe that the construction, as presented in the book, is not fully correct and thus I tried to find the original work by Seidel.
Sadly there is no reference in this section and the only reference in the book with Seidel is Constructing Arrangements of Lines and Hyperplanes with Applications by H. Edelsbrunner, J. O’Rourke, and R. Seidel which does not include the construction.
I have looked through Seidels Google Scholar page but there seems to be nothing relevant.
Do you have a source or know anything more about this construction?
What could be a good and accepted way for me to obtain information? Contacting either of the two?
Answer: To my knowledge, Seidel's construction has only been published in O'Rourke's book and nowhere else.
In one of his papers, Seidel even refers to O'Rourke's book for a description of his own construction. He writes on top of page 253 of his joint paper with Jim Ruppert:
"In his book [9, p. 255] O'Rourke describes n-vertex three-dimensional polyhedra that require $\Omega(n^{3/2})$ guards."
Jim Ruppert, Raimund Seidel: On the Difficulty of Triangulating Three-Dimensional Nonconvex Polyhedra. Discrete & Computational Geometry 7: 227-253 (1992) | {
"domain": "cstheory.stackexchange",
"id": 3900,
"tags": "reference-request, computational-geometry, polytope"
} |
Excel to JSON parser with http download | Question: I've been working on a project (link) to download a spreadsheet of known ransomware and properties and turn it into json so I can better consume the information within early detection projects.
I'm new to python - what can I be doing better? The destination json I'm converting can be found here.
update_json.py (entry point)
from excel_to_json import excel_to_json
from download_file import download_file
SOURCESHEET = 'https://docs.google.com/spreadsheets/d/1TWS238xacAto-fLKh1n5uTsdijWdCEsGIM0Y0Hvmc5g/pub?output=xlsx'
OUTPUTSHEET = '../RansomwareOverview.xlsx'
JSONFILE = '../ransomware_overview.json'
def write_json_file(json_data, filename):
output = open(filename, 'w')
output.writelines(json_data)
def generate_json(source_file, download_destination, json_file):
download_file(source_file, download_destination)
write_json_file(excel_to_json(download_destination), json_file)
generate_json(SOURCESHEET, OUTPUTSHEET, JSONFILE)
download_file.py
import urllib.request
def download_file(source, destination):
try:
urllib.request.urlretrieve(source, destination)
except IOError:
print('An error occured trying to write an updated spreadsheet. Do you already have it open?')
except urllib.error.URLError:
print('An error occured trying to download the file. Please check the source and try again.')
excel_to_json.py
import simplejson as json
import xlrd
from collections import OrderedDict
def excel_to_json(filename):
wb = xlrd.open_workbook(filename)
sh = wb.sheet_by_index(0)
mw = wb.sheet_by_index(2)
# List to hold dictionaries
c_list = []
# Iterate through each row in worksheet and fetch values into dict
for rownum in range(1, sh.nrows):
wares = OrderedDict()
row_values = sh.row_values(rownum)
if row_values[6]=="":
name = row_values[0]
gre=[name]
elif "," in row_values[6]:
e=row_values[6].split(",")
ge = [row_values[0]]
gre=e+ge
else:
gre=[row_values[0],row_values[6]]
wares['name'] = gre
wares['extensions'] = row_values[1]
wares['extensionPattern'] = row_values[2]
wares['ransomNoteFilenames'] = row_values[3]
wares['comment'] = row_values[4]
wares['encryptionAlgorithm'] = row_values[5]
wares['decryptor'] = row_values[7]
if row_values[8]=="":
wares['resources'] = [row_values[9]]
elif row_values[9]=="":
wares['resources']=[row_values[8]]
else:
wares['resources'] = [row_values[8], row_values[9]]
wares['screenshots'] = row_values[10]
for r in range(1, mw.nrows):
rowe = mw.row_values(r)
if row_values[0] == rowe[0]:
wares['microsoftDetectionName']=rowe[1]
wares['microsoftInfo'] = rowe[2]
wares['sandbox'] = rowe[3]
wares['iocs'] = rowe[4]
wares['snort'] = rowe[5]
c_list.append(wares)
# Serialize the list of dicts to JSON
return json.dumps(c_list, indent=4)
Answer: Performance tips:
ujson can bring more speed
since both simplejson and xlrd are pure-python, you may get performance improvements "for free" by switching to PyPy
you may (or not) see speed and memory usage improvements if switching to openpyxl and especially in the "read-only" mode
in the excel_to_json function, you are accessing the same values from row_values by index multiple times. Defining intermediate variables (e.g. defining name = row_values[6] and using name variable later on) and avoiding accessing an element by index more than once might have a positive impact
I'm not sure I completely understand the inner for r in range(1, mw.nrows) loop. Can you break once you get the if row_values[0] == rowe[0] evaluated to True?
are you sure you need the OrderedDict and cannot get away with a regular dict? (there is a serious overhead for CPythons prior to 3.6)
instead of .dumps() and a separate function to dump a JSON string to a file - use .dump() method to dump to a file directly - make sure to use with context manager when opening a file
Code Style notes:
follow PEP8 guidelines in terms of whitespace usage in expressions and statements
properly organize imports
if row_values[6]=="": can be simplified to if not row_values[6]: (similar for some other if conditions later on)
the generate_json() call should be put into the if __name__ == '__main__': to avoid it being executed on import
the excel_to_json() function is not quite easy to grasp - see if you can add a helpful docstring and/or comments to improve on clarity and readability
Other notes:
improve variable naming. Variables like sh, mw, rowe are very close to being meaningless. I would also replace wb with a more explicit workbook
have you considered using pandas.read_excel() to read the contents into the dataframe and then dumping it via .to_json() (after applying the desired transformations)? | {
"domain": "codereview.stackexchange",
"id": 24555,
"tags": "python, python-3.x, excel"
} |
Asks the user to input 10 integers, and then prints the largest odd number | Question: I have written a piece of python code in response to the following question and I need to know if it can be "tidied up" in any way. I am a beginner programmer and am starting a bachelor of computer science.
Question: Write a piece of code that asks the user to input 10 integers, and then prints the largest odd number that was entered. if no odd number was entered, it should print a message to that effect.
My solution:
a = input('Enter a value: ')
b = input('Enter a value: ')
c = input('Enter a value: ')
d = input('Enter a value: ')
e = input('Enter a value: ')
f = input('Enter a value: ')
g = input('Enter a value: ')
h = input('Enter a value: ')
i = input('Enter a value: ')
j = input('Enter a value: ')
list1 = [a, b, c, d, e, f, g, h, i, j]
list2 = [] # used to sort the ODD values into
list3 = (a+b+c+d+e+f+g+h+i+j) # used this bc all 10 values could have used value'3'
# and had the total value become an EVEN value
if (list3 % 2 == 0): # does list 3 mod 2 have no remainder
if (a % 2 == 0): # and if so then by checking if 'a' has an EVEN value it rules out
# the possibility of all values having an ODD value entered
print('All declared variables have even values')
else:
for odd in list1: # my FOR loop to loop through and pick out the ODD values
if (odd % 2 == 1):# if each value tested has a remainder of one to mod 2
list2.append(odd) # then append that value into list 2
odd = str(max(list2)) # created the variable 'odd' for the highest ODD value from list 2 so i can concatenate it with a string.
print ('The largest ODD value is ' + odd)
Answer: Here are a couple of places you might make your code more concise:
First, lines 2-11 take a lot of space, and you repeat these values again below when you assign list1. You might instead consider trying to combine these lines into one step. A list comprehension might allow you to perform these two actions in one step:
>>> def my_solution():
numbers = [input('Enter a value: ') for i in range(10)]
A second list comprehension might further narrow down your results by removing even values:
odds = [y for y in numbers if y % 2 != 0]
You could then see if your list contains any values. If it does not, no odd values were in your list. Otherwise, you could find the max of the values that remain in your list, which should all be odd:
if odds:
return max(odds)
else:
return 'All declared variables have even values.'
In total, then, you might use the following as a starting point for refining your code:
>>> def my_solution():
numbers = [input('Enter a value: ') for i in range(10)]
odds = [y for y in numbers if y % 2 != 0]
if odds:
return max(odds)
else:
return 'All declared variables have even values.'
>>> my_solution()
Enter a value: 10
Enter a value: 101
Enter a value: 48
Enter a value: 589
Enter a value: 96
Enter a value: 74
Enter a value: 945
Enter a value: 6
Enter a value: 3
Enter a value: 96
945 | {
"domain": "codereview.stackexchange",
"id": 4975,
"tags": "python, beginner"
} |
What does RR stand for in RR-manipulator? | Question: I have memorized RR-manipulator as having 2 arms from Google images but "arm" isn't spelled with "R". I also noticed that RRR-manipulator has 3 links. Does R stand for revolute?
Answer: The RR manipulator is commonly used as shorthand for a two revolute joint configuration in a single plane. This provides a reduced configuration space which is helpful for research and education use.
RRR is as you guessed a 3 joint system but usually still remaining in the plane.
I don't believe that there's an official definition for this but it's more of a common shorthand. Other abbreviations you may see are P for prismatic. And sometimes analyses leave the single plane, but use the same or similar shorthand for configuration space. The simplest versions have the plane oriented horizontally, but as you get into dynamic systems turning it vertical will increase the complexity adding weight/gravity. | {
"domain": "robotics.stackexchange",
"id": 2441,
"tags": "kinematics"
} |
Dividing the screen in two halves using LinearLayout | Question: I want to divide the screen in two halves. The layout is locked on portrait mode. The top half will have one button and the bottom half will have many buttons. That's why I choose this division, since the top half can be potentially scrollable.
This is my layout xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical" >
<LinearLayout
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1"
android:orientation="horizontal" >
<Button
android:id="@+id/play_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/play_button" />
</LinearLayout>
<LinearLayout
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1"
android:orientation="horizontal" >
<Button
android:id="@+id/button_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="button_1" />
<Button
android:id="@+id/button_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="button_2" />
<Button
android:id="@+id/button_3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="button_3" />
</LinearLayout>
</LinearLayout>
And this is how it looks like:
It looks as expected, but I was wondering if I'm doing it correctly. Is there a better, easier, more common, different, (etc) way to achieve this? Are there any mistakes or anti-patterns or bad things in there?
Answer: Your layout looks very good. android:layout_weight is the correct way to solve this.
A couple of other notes regarding your XML layout:
As your outermost LinearLayout has match_parent for both width and height, there is no need for android:gravity="center".
I would write 0dp instead of 0dip (even though it is the exact same thing). Using dp just seems more common to me. This is a very minor nitpick though :)
Don't hardcode strings in your XML. Use the strings.xml resource file and use android:text="@string/button3text"
You might know about this but either way you (and any future readers of this post) should also be aware that there exists android:layout_gravity. Although they sound similar, they are not the same thing. Read more about the differences between them in Android - gravity and layout_gravity
If, in the future you want to play around a bit more with layout_weights, you should take a look at What is android:weightSum in android, and how does it work?, especially this answer
If you would like to support landscape mode as well, I suggest learning how to use Android Fragments. If you would like to support older devices, there's a support package that can help with that. A Fragment has one onCreate method and one onCreateView method, which makes it easy to persist data between screen orientation changes (or other changes) while creating a new view for the data.
Summary:
Your layout looks excellent. At least in my eyes. | {
"domain": "codereview.stackexchange",
"id": 6478,
"tags": "android, xml, layout"
} |
Reason that integers are used for priorities instead of float | Question: Why are priorities always from a fixed set of integers? In operating systems priorities are integers typically between 1..MAX. But what is the reason that this is the case, when it would obviously be easier to place a new task between priority 2 and 3 with priority 2.5 instead? The way it is now, my scheduling can run out of priorities if my operating system has priorities between 1 and 10 and I need to schedule more than 10 different priorities or must re-arrange for a new task that should be between two subsequently scheduled tasks.
Answer: Historically, floating point has been slower than integer arithmetic, though this has not been the case for about 20 years on most non-embedded architectures.
The more compelling reason is to optimise FPU context switching.
When an operating system switches between two threads (not to mention the fact that the operating system itself is software that uses CPU registers), the contents of the CPU registers needs to be saved and restored. A typical modern CPU might have 16 or so general-purpose 64-bit registers, so that's 128 bytes.
Modern FPUs, however, have wide SIMD registers, and thus carry much more state; on modern Intel-esque CPUs, for example, you need 512 bytes.
You could save and restore these on every context switch, but that would incur a nontrivial cost. Instead, most system services, device drivers, and system programs (not to mention the OS itself) are written so they don't use the FPU. Not only does merely invoking a system call not require saving and restoring the FPU, neither does context switching to a system service and back again.
To support this, you need a few things:
The compiler needs a mode where it will never generate any instructions which involve the FPU. This ensures that the kernel and other system software never changes the FPU state implicitly.
The CPU needs a mode or flag where it traps to the operating system when a FPU instruction is executed. This flag is set whenever the CPU context switches to a thread for which the FPU state is "stale", and the FPU state is switched if the trap happens.
Note that while this optimisation "works", it has been the source of a Spectre-like security vulnerability on recent Intel CPUs, where it can leak information when the FPU operation is executed speculatively. But even without the full lazy FPU switch optimisation, this still allows saving and restoring FPU context only when a context switch actually occurs, rather than on every system call. | {
"domain": "cs.stackexchange",
"id": 18582,
"tags": "process-scheduling, multi-tasking"
} |
$ J^2=(L+S)^2 $ versus $ (P - \frac{q}{c} A)^2 $ | Question: The total angular momentum J can be written as $$ J^2 = L^2 + S^2 + 2 L \cdot S .$$ Now, I assume this is a simplification of a more general tensor rule that $$ (M + N )^2 = M^2 + N^2 + M \cdot N + N \cdot M ,$$ where $ M = A \otimes B $, for instance, and $ N = C \otimes D .$
I'm questioning my understanding of this rule now. I thought it came from something as simple as $$( M + N ) (M + N ) = A^2 \otimes B^2 + A C \otimes B D + C A \otimes D B + C^2 \otimes D^2 = M^2 + N^2 + M \cdot N + N \cdot M .$$
This "proof" does not extend to 3 dimensions. For example, for the exercise to compute $ (\bar P - \frac{q}{c} A)^2 $ , one may write this as $ P^2 + A'^2 + P \cdot A' + A' \cdot P $ according to Sakurai, where I've allowed the $ A' $ to swallow the constants to its left.
So, what gives? How would you go about showing this identity? If I blindly multiply as I did in the 2D case, you would receive several cross terms. Even just computing $ (\bar P)^2 $ would result in a 9-term sum since there are 3 separate terms in $ \bar P = P_x \otimes I \otimes I + I \otimes P_y ... $ etc.
I'm guessing I'm either getting the "tensor multiplication" rules wrong, or I'm getting the definition of $ ^2 $ wrong for tensor multiplication.
EDIT: after clarification for a different question, I see that $ P_x \ne P_x \otimes I \otimes I$ Idk why but I associated "different directions" to "different tensor spaces". I think this was what Zero was getting at (thanks). But the two answers below still hold so that you don't get ugly cross terms like $ P_x P_y $ or something when doing the square.
Answer: Let's go slowly and explicitly spell everything out. First, $\mathbf{J}$ is a vector operator, which means it's actually a set of three operators $$\mathbf{J} = (J_x, J_y, J_z).$$
Now, as I explain here, the definition of the square of a vector operator is
$$J^2 = J_x^2 + J_y^2 + J_z^2.$$
The components $J_i$ are defined to be the sum of the angular momentum and spin components. However, these act on the position and spin degrees of freedom, which are completely independent; particles with both position and spin have states which live in the tensor product of these two spaces. To make this tensor product structure explicit, we have
$$J_i = L_i \otimes I_s + I_p \otimes S_i$$
where $I_s$ is the identity operator in spin space, and $I_p$ is the identity operator in position space. Then
$$J_i^2 = (L_i \otimes I_s + I_p \otimes S_i)^2 = L_i^2 \otimes I_s + 2 L_i \otimes S_i + I_p \otimes S_i^2$$
where we used the basic tensor product identity $(A \otimes B)(C \otimes D) = AC \otimes BD$. Finally, by definition,
$$L^2 \equiv \sum_i L_i^2 \otimes I_s, \quad S^2 \equiv \sum_i I_p \otimes S_i^2, \quad L \cdot S \equiv \sum_i L_i \otimes S_i$$
which gives the final result. The reason it looks different from $\pi^2 = (p - qA/c)^2$ is because, while both $\pi$ and $\mathbf{J}$ are vector operators, the individual operators $J_i$ are themselves built from tensor product, while the $\pi_i$ aren't.
It's understandable to be confused, because the equation you asked about combines two subtleties in notation: inner products of vector operators, and operators built from tensor products. In both cases, textbooks tend to use compact notation that suppresses the implementation details, which is perfectly reasonable, but definitely rough the first time you run into it. | {
"domain": "physics.stackexchange",
"id": 84933,
"tags": "quantum-mechanics, operators, angular-momentum, momentum"
} |
Physical Interpretation of the Integrand of the Feynman Path Integral | Question: In quantum mechanics, we think of the Feynman Path Integral
$\int{D[x] e^{\frac{i}{\hbar}S}}$ (where $S$ is the classical action)
as a probability amplitude (propagator) for getting from $x_1$ to $x_2$ in some time $T$. We interpret the expression $\int{D[x] e^{\frac{i}{\hbar}S}}$ as a sum over histories, weighted by $e^{\frac{i}{\hbar}S}$.
Is there a physical interpretation for the weight $e^{\frac{i}{\hbar}S}$? It's certainly not a probability amplitude of any sort because it's modulus squared is one. My motivation for asking this question is that I'm trying to physically interpret the expression
$\langle T \{ \phi(x_1)...\phi(x_n) \} \rangle = \frac{\int{D[x] e^{\frac{i}{\hbar}S}\phi(x_1)...\phi(x_n)}}{\int{D[x] e^{\frac{i}{\hbar}S}}}$.
Answer: "It's certainly not a probability amplitude of any sort because it's modulus squared is one." This does not follow... Anyway, an (infinite) normalisation factor is hidden away in the measure. The exponential has the interpretation of an unnormalised probability amplitude. Typically you don't have to worry about the normalisation explicitly because you compute ratios of path integrals, as your example shows. The book about the physical interpretation of path integrals is the original, and very readable, one by Feynman and Hibbs, which now has a very inexpensive Dover edition. I heartily recommend it. :) (Though make sure you get the emended edition as the original had numerous typos.) | {
"domain": "physics.stackexchange",
"id": 24402,
"tags": "quantum-mechanics, quantum-field-theory, path-integral"
} |
Why does the cart move? | Question: A while ago someone proposed the following thought experiment to me:
A horse attached to a cart is resting on a horizontal road. If the horse attempts to move by pulling the cart, according to the 3rd Newton's Law, the cart will exert a force equal in magnitude and opposite in direction, cancelling each other out and thus the horse and the cart should not move. And yet it moves (pun intended ;) Why?
I never got a satisfactory answer, my guess is that the answer lies in the frames of reference involved: horse-cart and horse-road. Any ideas?
Answer: The opposing force always work on a different body, thats why they dont cancel. For instance the moon pulls the earth and the earth pulls the moon with same force. Also, the horse dont move by pulling the cart, but by pulling the earth. | {
"domain": "physics.stackexchange",
"id": 175,
"tags": "classical-mechanics, newtonian-mechanics"
} |
How many mines are there on Earth, and what is their output in tonnes? | Question: I am writing a space colonization game, and I need some guidance on default values for mine productivity. If you also know an estimate of how much people work on them, that's a bonus. Thanks in advance :)
Answer: You can get estimates from the USGS mineral yearbooks. For example, the entry on Australia has a data table with the amounts of mined resources. Or, the entry on copper lists both US production and international production, including numbers of people employed.
More number are available from government statistics websites, regarding employment. For example Australia and USA.
Digging through those websites will give you an order of magnitude of what to expect. | {
"domain": "earthscience.stackexchange",
"id": 1669,
"tags": "economic-geology, mining"
} |
UnicodeEncodeError while installing ROS on Debian | Question:
Hi all,
I am trying to instal ROS hydro on a Debian system following the guide on the wiki.
When I executed:
./src/catkin/bin/catkin_make_isolated --install --install-space /opt/ros/hydro
I got this error:
==> Processing catkin package: 'catkin'
Makefile exists, skipping explicit cmake invocation...
==> make cmake_check_build_system in '/root/ros_catkin_ws/build_isolated/catkin'
==> make -j4 -l4 in '/root/ros_catkin_ws/build_isolated/catkin'
Unhandled exception of type 'UnicodeEncodeError':
Traceback (most recent call last):
File "./src/catkin/bin/../python/catkin/builder.py", line 832, in build_workspace_isolated
number=index + 1, of=len(ordered_packages)
File "./src/catkin/bin/../python/catkin/builder.py", line 585, in build_package
destdir=destdir
File "./src/catkin/bin/../python/catkin/builder.py", line 378, in build_catkin_package
if has_make_target(build_dir, 'install'):
File "./src/catkin/bin/../python/catkin/builder.py", line 389, in has_make_target
output = run_command(['make', '-pn'], path, quiet=True)
File "./src/catkin/bin/../python/catkin/builder.py", line 208, in run_command
out.write(line)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xc9' in position 3: ordinal not in range(128)
<== Failed to process package 'catkin':
'ascii' codec can't encode character u'\xc9' in position 3: ordinal not in range(128)
Command failed, exiting.
Does anybody know what to do here?
Originally posted by josegaert on ROS Answers with karma: 56 on 2014-01-29
Post score: 1
Answer:
I found an anwser:
It has something to to with using a different languages. For now, Japanese systems and French (mine) systems have found to give the bug. You can solve it by putting your system in English for a while.
root@xwzy:~/ros_catkin_ws# env | grep LANG
LANG=fr_BE.UTF-8
LANGUAGE=fr_BE:fr
root@xwzy:~/ros_catkin_ws# export LANG=en_US.UTF-8
root@anoesjka:~/ros_catkin_ws# env | grep LANG
LANG=en_US.UTF-8
LANGUAGE=fr_BE:fr
And then it works.
Originally posted by josegaert with karma: 56 on 2014-01-29
This answer was ACCEPTED on the original site
Post score: 3
Original comments
Comment by Dirk Thomas on 2014-01-30:
For reference this is an open ticket which we haven't found a fix for yet: https://github.com/ros/catkin/issues/578 | {
"domain": "robotics.stackexchange",
"id": 16818,
"tags": "ros-hydro, debian"
} |
The final step in kalman filter to correct/update the covariance matrix | Question: I see that, in the correction step of Kalman filter, there is an equation to update the covariance matrix. I have been using it in the form:
P = (I - KH)P'
Here P is the covariance matrix, K is the Kalman Gain and H is the observation model. The I is the identity matrix. However, I also see a different equation in some literature:
P = P' - KSKT
where
S = HPHT + Q
where Q is the noise matrix for the observation model. Are these two equations same? If so, how to prove it?
Answer: The Kalman Gain is defined as the following:
$K = PH^T (HPH^T + Q)^-1$
From your question, we need to prove:
$P - KSK^T = (I - KH)P$
primes omitted for simplicity
Canceling P, and substitute S with the provided definition:
$K (HPH^T + Q)K^T = KHP$
Substitute the first K on the left hand side with the definition of the Kalman gain provided:
$PH^T (HPH^T + Q)^-1 (HPH^T + Q)K^T = KHP$
S and it's inverse reduces to identity, we are left with:
$PH^TK^T = KHP$
From the transpose property of matrices $(ABC)^T = C^T B^T A^T$ we can rearrange LHS with $P$ as $A$, $H^T$ as $B$, and $K^T$ as $C$:
$(KHP^T)^T = KHP$
Since covariance matrix is symmetric, and KHP must be symmetric (this can be inferred from $P' = P - KHP$) therefore:
$KHP = KHP$ | {
"domain": "robotics.stackexchange",
"id": 1632,
"tags": "kalman-filter"
} |
Minimum $E$ of $p\bar{p}$-collision for $q\bar{q}$ pair with mass $m_q$ | Question: I am currently working out the energy required to create a particle anti-particle pair from a collision of a proton travelling along the x-direction with an anti-proton which is at rest. The particle has a mass $m_q$.
Conservation of 4-momentum in the rest frame of the target anti-proton ($c=1$):
$p_1=(m_\text{p},0,0,0)$
The moving proton has this minimum energy, the quantity we are trying to find:
$p_2=\left(E, \sqrt{E^2-m_p^2 },0,0\right)$
Then what I find confusing is the terminology, it says that $p_{q\bar{q}}=\left(\sqrt{p^2+4 m_q^2 },p,0,0\right)$
Where has this $p$ come from and what is it? Is it the momentum of the center of mass of the $q\bar{q}$ system? Also, we don't seem to have taken much care about reference frames here, or rather I havn't thought about them really which is worrying.
Finally, it says that the minimum energy, E, the $q\bar{q}$-pair will be at rest in the CMF frame. What is this frame referring to? The center of mass of the particle/anti-particle pair? I understand that the threshold energy to produce these will be a combination of the energy of the proton and their rest masses but I don't know how we have the equation (above)
Answer: It seems you are correct the $p$ is the momentum of the center of mass (COM) of your $qq$ (sorry don't know how to add bars) system in the lab frame. Due to conversation of momentum the $qq$ system may only have momentum in the x direction since that is your initial conditions.
With regards to the 2nd part of your question in the CMF (center of mass frame) of the $qq$ system the $qq$ pair will have equal and opposite momentums; however, in the case where the E of the initial condition is just sufficient to produce the $qq$ pair they can have no additional kinetic energy, thus they will be at rest in their CMF. Again due to conservation of momentum the $qq$ COM must still be moving in the x direction in the lab frame. | {
"domain": "physics.stackexchange",
"id": 7036,
"tags": "homework-and-exercises, particle-physics, special-relativity, momentum, collision"
} |
Draw outline of a text in an image | Question: I need to draw an outline of text in an image. Consider the below image as an example.
Can anyone suggest me a direction to achieve this? I don't have experience in image processing. Any tools/lib or anything that can generate this kind of image will be helpful.
Answer: Here's a rudimentary answer using MATLAB that provides a good alternative to the convex hull as Emre has mentioned. The basic algorithm is the following:
Binarize the image and invert the text so white is text while black is background
Find the minimum spanning bounding boxes for each of the characters
Create a new output image that takes the co-ordinates of each of the bounding boxes and fills them in with white.
Do a morphological closing with a relatively large structuring square element to mash all of the text into a single object
Find the perimeter of this object - This is your boundary of your text
A small note: I had to play around with the size of my structuring element until the results looked right. You should choose the size of it based on how big the tallest letter is, and a few more pixels around the structuring element so that when you close, you are able to join neighbouring bounding boxes together. Also, as noted by Selim Arikan in the comment below, it is recommended to add a few pixels of dilation to the perimeter depending on the typeface size. I haven't done that in this implementation, but it's fairly simple to do.
Without further ado, here's my code, along with the example image that I used:
Input Image
Code
% Clear all varibles and close all windows
clear all;
close all;
% Read in image
imorig = imread('https://i.stack.imgur.com/uOyDn.png');
% Threshold and invert
im = ~im2bw(imorig);
% Find bounding boxes of all characters
s = regionprops(im, 'BoundingBox');
bbox = round(reshape([s.BoundingBox], 4, []).');
% Create a blank image and for each box, fill in with white
outImg = false(size(im));
for idx = 1 : size(bbox,1)
outImg(bbox(idx,2):bbox(idx,2)+bbox(idx,4), ...
bbox(idx,1):bbox(idx,1)+bbox(idx,3)) = true;
end
% Close with a very large structuring element
se = strel('square', 20);
outImg2 = imclose(outImg, se);
% Find the perimeter of this object, then take the original image and
% the pixels that belong to this boundary. Colour all of these pixels red
% for illustration
redChan = imorig(:,:,1);
greenChan = imorig(:,:,2);
blueChan = imorig(:,:,3);
perim = bwperim(outImg2,8);
redChan(perim) = 255;
greenChan(perim) = 0;
blueChan(perim) = 0;
out = cat(3,redChan,greenChan,blueChan);
figure;
subplot(1,2,1);
imshow(imorig);
title('Original image');
subplot(1,2,2);
imshow(out);
title('Image with perimeter overlaid');
Output Image
Edit: July 20th, 2014
Here is an OpenCV / Python implementation of what I did above. The main differences are:
The regionprops method in MATLAB does not exist in Python / OpenCV. However, there is a findContours method which provides a list of points that traces over every boundary of each of the letters in the image. This is essentially a list of a list of points... woah! Basically, this returns a list. For each element in this list, this contains a list of 2D points that trace around a particular object.
For each object, I find the minimum and maximum of the rows and columns and this denotes the minimum spanning bounding box for each object. I then fill in this box with white.
It's also a good idea where if an image serves as input into the function, you provide a copy of the image as the input to avoid shadowing and accidental overwriting. You use the .copy() method for each of these images.
I padded the boundaries of the image by 20 pixels to allow for a tighter boundary as per your request.
You will need the numpy, scipy and opencv modules before you run this method. If you need help in installing these modules, let me know in a comment.
Without further ado, here's the code.
import cv2 # For OpenCV modules (Morphology and Contour Finding)
import numpy as np # For general purpose array manipulation
# Load in image
img = cv2.imread('uOyDn.png', 0)
# Create a new image that pads each side by 20 pixels
# This will allow the outlining of the text to be tighter
# Create an image of all white
imgPad = 255*np.ones((img.shape[0] + 40, img.shape[1] + 40),
dtype='uint8')
# Place the original image in the middle
imgPad[20:imgPad.shape[0]-20, 20:imgPad.shape[1]-20] = img
# Invert image
# White becomes black and black becomes white
imgBW = imgPad < 128
imgBW = 255*imgBW.astype('uint8')
# Find all of the contours in the image
contours,hierarchy = cv2.findContours(imgBW.copy(), cv2.RETR_LIST,
cv2.CHAIN_APPROX_NONE)
# New image that places square blocks over all letters
imgBlocks = np.zeros(imgBW.shape, dtype='uint8')
# For each contour...
for idx in range(len(contours)):
# Reshape each contour into a 2D array
# First co-ordinate is the column, second is the row
cnt = np.reshape(contours[idx], (contours[idx].shape[0],
contours[idx].shape[2]))
# Transpose to allow for max and min calls
cnt = cnt.T
# Find the max and min of each contour
maxCol = np.max(cnt[0])
minCol = np.min(cnt[0])
maxRow = np.max(cnt[1])
minRow = np.min(cnt[1])
# Use the previous to fill in a minimum spanning bounding
# box around each contour
for row in np.arange(minRow, maxRow+1):
for col in np.arange(minCol, maxCol+1):
imgBlocks[row,col] = 255
# Morphological closing on the image with a 20 x 20 structuring element
structuringElement = cv2.getStructuringElement(cv2.MORPH_RECT, (20,20))
imgClose = cv2.morphologyEx(imgBlocks.copy(), cv2.MORPH_CLOSE, structuringElement)
# Find the contour of this structure
contoursFinal,hierarchyFinal = cv2.findContours(imgClose.copy(), cv2.RETR_LIST,
cv2.CHAIN_APPROX_NONE)
# Take the padded image, and draw a red boundary around the font
# First, create a colour image
imgPadColour = np.dstack((imgPad, imgPad, imgPad))
# Reshape the contour points like we did before
cnt = np.reshape(contoursFinal[0], (contoursFinal[0].shape[0],
contoursFinal[0].shape[2]))
# Careful - pixels are packed in BGR format
# As such, for each point in the outer shape, set to red
for (col,row) in cnt:
imgPadColour[row][col][0] = 0
imgPadColour[row][col][1] = 0
imgPadColour[row][col][2] = 255
# Crop out image for final one
imgFinal = imgPadColour[20:imgPad.shape[0]-20, 20:imgPad.shape[1]-20]
# Show both images
cv2.imshow('Original Image', img)
cv2.imshow('Image with red outline over text', imgFinal)
cv2.waitKey(0)
cv2.destroyAllWindows()
The output will show you two windows. One of the original image, and the other is the output. You'll need to move one of the windows out of the way, as they will appear one on top of the other. Note that you need to download the images to your computer before you run this method. | {
"domain": "dsp.stackexchange",
"id": 1981,
"tags": "image-processing"
} |
simplified into asymptotic notation | Question: I have a function that needs to be represented in theta form.
The below is my answer.
But the correct answer is (n.2^n)
Can someone please explain me how??
Answer: Assuming $\log=\log_2$, we have
$$2^{n+\log_2 n}=2^n \cdot 2^{\log_2 n}=n \cdot 2^n$$
where we used main property(or definition) of $\log$: $a^{\log_a b}=b$, for appropriate $a,b$. | {
"domain": "cs.stackexchange",
"id": 18977,
"tags": "algorithms, algorithm-analysis, big-o-notation"
} |
What is the scaling function and wavelet function at wavelet analysis? | Question: I'm trying to looking the meaning and functionality about scaling function and wavelet function at wavelet analysis. I have googling already. But I can't find and understand the meaning.
What does those affect to analysis?
Does anyone help me to understand roughly?
Answer: Wavelets are functions which are form by two resulting coefficients. The detail coefficient and the scale coefficient. From wikipedia Wavelets are defined by the wavelet function ψ(t) (i.e. the mother wavelet) and scaling function φ(t) (also called father wavelet) in the time domain.
The wavelet function is in effect a band-pass filter and scaling it for each level halves its bandwidth.
The scaling and detail basically divide the signal into two applying a high-pass filter resulting into the detail coefficients - (which is the highest level of the transform) and a low-pass filter which results in the scaling coefficients - (which is the lowest level of the transform). This coefficients are calculated for each frequency of the discrete wavelet.
used to for example to extract the deterministic part of a signal and the stockastic part of the signal. They are also used through different procedures to denoise via thresholding the coefficients. | {
"domain": "dsp.stackexchange",
"id": 2687,
"tags": "wavelet"
} |
Lorentz similarity transforms | Question: I am reading Peskin-Schröder, p. 36. Here is what I don't understand: They define a similarity transform in the coordinate space as:
$$x^{\mu} \rightarrow x'^{\mu} = \Lambda^{\mu}_{\nu} x^{\nu}$$
Then their field transform becomes:
$$\phi(x) \rightarrow \phi'(x) = \phi(\Lambda^{-1} x)$$
How is it that $\Lambda$ got inverted? How to see (prove) it? There are also the derivative and double derivative of the field, but I think if I get how the previous step is done, I will be able to figure out those myself.
Answer: The idea is that the transformation of fields
$$\phi \to \phi'\tag {1}$$
induced by a coordinate transformation
$$x \to x' = \Lambda x \tag {2}$$
is such that if we simultaneously change coordinates and fields, then nothing changes.
In other words, the right hand side of (1) must be defined in order to fulfill
$$\phi'(x') = \phi (x)\:.$$
Since, from (2), $$x =\Lambda^{-1}x'\:,$$
we are committed to define $\phi'$ as the function
$$\phi'(y) := \phi (\Lambda^{-1}y)$$
for every spacetime point $y $. | {
"domain": "physics.stackexchange",
"id": 33439,
"tags": "field-theory, lorentz-symmetry"
} |
Why is volume inversely proportional to pressure? | Question: If temprature is directly proportional to volume (Charles's law) and
temperature is directly proportional to pressure (Gay-Lussac's law), then why is pressure and volume are inversely proportional?
Answer: Given you know and understand Charles' and Gay-Lussac's laws, it's not about chemistry, rather, simple ratios:
$$
\begin{cases}
T \propto V\\
T \propto p
\end{cases}
\implies
p \propto \frac 1 V
$$
which, as Zenix commented, is a math form of Boyle's law. | {
"domain": "chemistry.stackexchange",
"id": 13052,
"tags": "physical-chemistry, thermodynamics, gas-laws, gas-phase-chemistry"
} |
Do I need to bandpass filter the signal before applying the Zoom FFT algorithm? | Question: Let's say I have an acoustic signal that I want to make a spectrogram of filled with broadband noise and tonals, sampled at oh, $44100\textrm{ kHz}$, and I want to zoom in on the band between $2600\textrm{ Hz}$ and $3000\textrm{ Hz}$ (or any band of frequencies, really).
The zoom FFT algorithm says to accomplish this, one simply has to frequency translate, then lowpass filter, then decimate and FFT the resulting lower frequency signal.
However, most of the diagrams I see explaining zoom FFT only show discrete bands with no noise in between, which begs the question:
Would I need a bandpass filter to prevent aliasing during the frequency translation step of the Zoom-FFT algorithm if I have a noisy signal containing energy at all frequencies?
I'm thinking yes, since there's a chance that during the frequency translation some unwanted noise would get shifted into my new band of interest due to aliasing, but I'm not sure.
The processing chain I envision is as follows:
$$\boxed{\text{BPF}}{\rightarrow}\boxed{\text{Frequency Xlate}}{\rightarrow}\boxed{\text{Bandlimited downsample}}{\rightarrow}\boxed{\text{FFT}}{\rightarrow}\boxed{\text{Display processing}}$$
Would this be correct?
Answer: Your BPF is superfluous. Frequency translation (if very simply done by $\cdot e^{j2\pi \Delta f n}$) is a circular shift of the whole Nyquist band.
When you calculate the Fourier of that, you'll notice there's no chance of aliasing at all.
The only step that leads to aliasing is the downsampling, and that's why ever decimator comes with an appropriate filter - in your case, the LPF you already have. You usually implement the filtering and down sampling as one entity - no use in calculating filter output that you'll throw away in the next step.
So:
$\cdot e^{j2\pi \Delta f n} \rightarrow \text {decimating LPF}\rightarrow \text {DFT}$ | {
"domain": "dsp.stackexchange",
"id": 5168,
"tags": "fft, power-spectral-density, spectrogram"
} |
Parameter tuning for machine learning algorithms | Question: When it comes to the topic of tuning parameters, most of the time you read grid search. But if you have 6 parameters, for which you want to test 10 variants, you get to 10^6 = 1000000 runs. Which in my case would be several months of processing time.
That's why I was looking for an alternative. On the Kaggle website, I found a tutorial that uses a different approach. It almost works like this:
1) Test all 6 parameter individually with the other 5 parameters as default value and plot the results
2) Change the default values for alle 6 parameters to the best value of the associated plot
3) Test all 6 parameter individually with the other 5 parameters as last best value and plot the results
4) Repeat step 2 and 3 until the results does not change anymore
This approach has the advantage of requiring much fewer runs. Is this a scientifically accepted procedure? And does this approach have a name in the literature?
Answer: In general, your approach will get stuck in local minima. This is why it is not scientifically accepted.
(Notice that this may be different in very special cases, in particular if the performance of the algorithm is a strictly convex function of all input parameters).
To see how the approach fails, suppose your machine learning algorithm has two parameters, $x$ and $y$, which can be either $0$ or $1$. The default values are $x=1$ and $y=1.$
The performance of your machine learning algorithm is $f$ and should be as high as possible.
Assume the following performance levels $f(x,y)$:
| x=0 | x=1
----|-----|-----
y=0 | 0.9 | 0.2
y=1 | 0.1 | 0.3
Your approach would do the following:
First, choose the default value $x=1$ and compute $f(x=1, y=0) = 0.2$ and $f(x=1, y=1) = 0.3$. Second, choose the default value $y=1$ and compute $f(x=0,y=1)=0.1$ and $f(x=1, y=1) = 0.3$.
Change the default values to the best value. In this case, this requires no change since $x=1$ and $y=1$ are the best values, respectively.
The result did not change. Report $(x=1, y=1)$ as the best parameter combination.
But the global performance maximum occurs at $(x=0, y=0).$ | {
"domain": "datascience.stackexchange",
"id": 2574,
"tags": "hyperparameter, hyperparameter-tuning, grid-search"
} |
Energy basis to the X basis | Question: On Shankar page 217 when going from the operator representation to the differential representation he starts with
$$a|0\rangle = 0$$
And says that with a projection on the X basis we get
$$|0\rangle \rightarrow \langle x|0\rangle = \psi_0(x)$$
And with $$a=\frac{1}{\sqrt{2}}\left(y+\frac{d}{dy}\right)$$
It’s stated that in the X basis of our first equation ($a|0\rangle=0$) we get $$\left(y+\frac{d}{dy}\right)\psi_0(y)=0$$
I’m wondering how this makes any sense. From the way it’s set up it sounds like he’s doing $$\langle x|a|0\rangle$$ which would be annihilated as per the first equation. But the result he gets is the same as if he did $$a \langle x|0\rangle$$ but you can’t just pull the $a$ out because it has a $p$ in its definition. What is going on here?
Answer: First, we need to lay out some preliminaries in the language of Shankar's book. If you want, you can skip to the bottom where I apply the following to your question.
When you express a state $|\psi\rangle$ in the position basis, what you're doing is applying the identity operator $\mathbb{1} = \int dx \ |x\rangle\langle x|$ and defining $\langle x | \psi \rangle \equiv \psi(x)$ to be the position-space wave function corresponding to the state $|\psi\rangle$.
$$ |\psi \rangle = \int dx \ |x \rangle\langle x | \psi \rangle \equiv \underbrace{\int dx \ |x \rangle \underbrace{\psi(x)}_{\text{Wavefunction}}}_{\text{Entire state}}$$
When you express an operator $\hat O$ in the position basis, what you're doing is applying the identity operator $\mathbb{1} = \int dx |x \rangle\langle x |$ from the right and $\mathbb{1} = \int dx' |x' \rangle\langle x' |$ from the left and defining $ \langle x'|\hat O|x\rangle \equiv O_{xx'}$ to be the position-space representation of the operator $\hat O$.
$$\hat O = \iint dx \ dx'\ |x'\rangle\langle x'|\hat O |x \rangle \langle x | \equiv \iint dx\ dx' \ |x'\rangle O_{xx'} \langle x|$$
( Note that $\hat O$ eats states and spits out other states, while $O_{xx'}$ eats (wave)functions and spits out other functions.)
From here, we can write, we can write
$$\hat O |\psi\rangle = \left(\iint dx\ dx' |x'\rangle O_{xx'} \langle x| \right)\left(\int dy \ |y\rangle \psi(y)\right)$$
$$ = \iiint dx \ dx' \ dy \ |x'\rangle O_{xx'} \langle x|y\rangle \psi(y)$$
We can use the fact that $\langle y|x\rangle = \delta(x-y)$ to eliminate the integration over $y$ and yield
$$\hat O | \psi\rangle = \iint dx \ dx' |x'\rangle O_{xx'} \psi(x)$$
This is the most general possible expression for action of the operator $\hat O$ on the state $|\psi\rangle$ as expressed in the position basis.
In your question, you refer to $\hat a \equiv \frac{\hat X + i\hat P}{\sqrt{2}}$ (where we've set all the constants equal to 1 for simplicity - you can put them back in as an exercise). In the position basis, we have that
$$X_{xx'} \equiv \langle x' | \hat X | x\rangle = x \delta(x-x')$$
and
$$P_{xx'} \equiv \langle x' | \hat P | x\rangle = -i\delta'(x-x') = -i \delta(x-x') \frac{d}{dx'}$$
and so
$$a_{xx'}\equiv \langle x' | \hat a | x\rangle = \delta(x-x') \left(\frac{x + \frac{d}{dx'}}{\sqrt{2}}\right)$$
The wavefunction of your state is unknown at the moment, but you can call it $\psi_0(x)$. Plugging the operator $a_{xx'}$ into the integral we found earlier yields
$$\hat a|0\rangle = \iint dx \ dx' |x'\rangle \delta(x-x') \left(\frac{x + \frac{d}{dx'}}{\sqrt{2}}\right) \psi_0(x) = \int dx |x\rangle \frac{1}{\sqrt{2}} \left( x + \frac{d}{dx}\right)\psi_0(x) $$
which means that $\hat a|0\rangle$ yields a new state whose wavefunction is given by
$$\phi(x) = \frac{1}{\sqrt{2}}\left(x + \frac{d}{dx}\right) \psi_0(x) = 0$$
where the last equality arises because we know that $\hat a$ annihilates the state $|0\rangle$. | {
"domain": "physics.stackexchange",
"id": 53195,
"tags": "quantum-mechanics, operators, harmonic-oscillator"
} |
Recieving a costmap2dros timeout | Question:
Hi everyone,
New to ROS so I'm trying to set up the system with the map and everything to work following the tutorials but I seem to have issues with the costmap2dros giving me timeouts. I finally managed to recieve a map in rviz which I consider a tremendous accomplishment considering the difficulties it has brought me. Anyway, my costmap parameters look as follows:
local_costmap:
global_frame: odom
robot_base_frame: base_laser/base_link
update_frequency: 5.0
publish_frequency: 2.0
static_map: false
rolling_window: true
width: 6.0
height: 6.0
resolution: 0.05
global_costmap:
global_frame: /map
robot_base_frame: base_link
update_frequency: 5.0
static_map: true
obstacle_range: 1.0
raytrace_range: 1.5
robot_radius: 0.1
inflation_radius: 0.1
transform_tolerance: 0.3
robot_radius: 0.20
observation_sources: my_sensor
laser_scan_sensor: {sensor_frame: /base_laser, data_type: LaserScan, topic: scan, marking: true, clearing: true}
I have also attached the map yaml code below as maybe there lies the issue:
image: map1.png
resolution: 0.01
origin: [0.0, 0.0, 0.0]
occupied_thresh: 0.56
free_thresh: 0.1
negate: 0
and finally the launch file... I hope that maybe you can spot a mistake I made somewhere here:
<launch>
<include file="$(find amcl)/examples/amcl_omni.launch" />
<node pkg="my_sensor" type="my_sensor" name="my_sensor" output="screen">
<param name="sensor_param" value="param_value" />
</node>
<node pkg="my_odom" type="my_odom" name="my_odom" output="screen">
<param name="odom_param" value="param_value" />
</node>
<node pkg="robot_setup_tf" type="tf_broadcaster" name="transform_configuration_name" output="screen">
<param name="transform_configuration_param" value="param_value" />
</node>
<node pkg="robot_setup_tf" type="tf_listener" name="transform_configuration_name2" output="screen">
<param name="transform_configuration_param2" value="param_value" />
</node>
<node name="map_server" pkg="map_server" type="map_server" args="/home/maciejm/catkin_ws/src/map1.yaml"/>
<node pkg="move_base" type="move_base" respawn="false" name="move_base" output="screen">
<rosparam file="$(find my_robot_name_2dnav)/costmap_common_params.yaml" command="load" ns="global_costmap" />
<rosparam file="$(find my_robot_name_2dnav)/costmap_common_params.yaml" command="load" ns="local_costmap" />
<rosparam file="$(find my_robot_name_2dnav)/local_costmap_params.yaml" command="load" />
<rosparam file="$(find my_robot_name_2dnav)/global_costmap_params.yaml" command="load" />
<rosparam file="$(find my_robot_name_2dnav)/base_local_planner_params.yaml" command="load" />
</node>
<node pkg="tf" type="static_transform_publisher" name="link1_broadcaster" args="1 0 0 0 0 0 1 map odom 100" />
</launch>
Originally posted by maciejm on ROS Answers with karma: 33 on 2015-12-08
Post score: 0
Answer:
I found the error to be a bad configuration here with the odometry details. I recieved source code that was supposed to make it work without realising that the odom file was looking for base_footprint rather than base_link which I solved. Also had to switch off static transform publisher as mapping with tf_broadcaster proved just as useful.
I hope it helps people in the future.
Kind regards,
MaciejM
Originally posted by maciejm with karma: 33 on 2015-12-09
This answer was ACCEPTED on the original site
Post score: 0
Original comments
Comment by dpingk on 2017-02-15:
So, where did you corrected? tell me directly cause this problem drive me crazy ... thx in advance. | {
"domain": "robotics.stackexchange",
"id": 23178,
"tags": "ros, navigation, 2dcostmap"
} |
Follow-up zp-Tree to represent Trees as nested arrays: 3rd (final?) revision | Question: This is a follow-up on my previous post.
I have made modifications based on the feedback received on the previous post, hence I request a third (final?) review on the modified code if ok.
Note: review purpose is just to check good practices (code / performance wise) and see if anything's missing.
I did all updates as proposed by @EngineerDollery in the previous post.
Other than that I separated prototype methods (API) from private methods more clearly;
Thanks to @EngineerDollery for the reviews so far.
/**
* zp-Tree
* This Tree constructor is essentially a decorator for an array "tree of nodes" passed in.
* Purpose:
* - Enter tree as arrays of nested objects Format
* - Easily find / insert / delete Nodes
* - Find parent / child / next / previous Nodes
* - Respect nodes order: array will provide natural ranking
* Inspired by js-tree: https://github.com/wangzuo/js-tree/blob/master/index.js
*
* @author Kim Gysen
*/
/**
* @typedef Node
* @property{number} _cid The internal id used by zp-Tree
* @property{?Node} prev The previous Node in the tree
* @property{?Node} next The next Node in the tree
* @property{?Node} parent The node's parent Node
* @property{?Array} children The node's childe nodes
* @property{number} level The node's depth level
* @property{boolean} isLeaf The node is (not) a leaf
*/
var CONSTRUCT_MODE = Object.freeze({
DEEP: { value: 0, desc: "Construct all children", is: function( mode ){ return ( this === mode ) } },
SHALLOW: { value:1, desc: "Construct only top level", is: function( mode ){ return ( this === mode ) } }
});
/**
* Tree constructor function
* @constructor
* @param {type} Array
* @returns {type} Tree
*/
function Tree( tree ){
tree = tree || [];
if( !_isArray( tree ) ) throw "Array is required!";
this.tree = tree;
this.index = {};
this._cid = 1;
_buildTree.call( this, tree );
};
var proto = Tree.prototype;
/**************** Prototype methods ****************/
/**
*
* @param {number} _cid
* @returns {Node} node
*/
proto.findNode = function( _cid ){
var node = this.index[ _cid ] || null;
return node;
};
/**
* Inject node into the tree at specific parent / index
* @param {type} Node
* @param {?number} parent_cid
* @param {number} idx
* @returns {Node} node
*/
proto.insertNode = function ( node, parent_cid, idx ){
var parentNode = this.findNode( parent_cid );
_buildTree.call( this, [ node ], null, CONSTRUCT_MODE.DEEP );
if( !parentNode ){
node = this.addRootNode( node, idx );
} else {
node = this.addChildNode( node, parent_cid, idx );
};
return node;
};
/**
* Inject as root node at specified index
* @param {Node} node
* @param {number} idx
* @returns {Node} node
*/
proto.addRootNode = function( node, idx ){
if( !_indexWithinTree( this.tree, idx ) ) {
this.tree.push( node );
} else {
this.tree.splice( idx, 0, node ); //Adds a node to the base @ provided index
};
_buildTree.apply( this, [ this.tree, null, CONSTRUCT_MODE.SHALLOW ] );
return node;
}
/**
* Inject as child node of a defined parent at specified index
* @param {Node} node
* @param {number} parent_cid
* @param {number} idx
* @returns {Node} node
*/
proto.addChildNode = function( node, parent_cid, idx ){
var parentNode = this.findNode( parent_cid );
if( parent_cid && !parentNode ) throw "Node insertion failed: Provided parent node doesn't exist. Use 'addRootNode( node, idx ) to create a new root node.";
if( !_hasChildren( parentNode ) ){
idx = 0;
parentNode.children = [];
};
parentNode.children.splice( idx, 0, node );
_buildTree.apply( this, [ parentNode.children, parentNode, CONSTRUCT_MODE.DEEP ] ); //DEEP required for syncing childNode.level
return node;
}
/**
* Removes a node from the tree
* @param {number} node__cid
* @returns {undefined}
*/
proto.removeNode = function( node__cid ){
var node = this.findNode( node__cid );
if ( node ){
var nodes = _hasParent( node ) ? node.parent.children : this.tree;
nodes.splice( node.idx, 1 );
_removeNodeFromIndex.call( this, node );
if( node.parent) _buildTree.apply( this, [ nodes, node.parent, CONSTRUCT_MODE.SHALLOW ] );
};
};
/**
* Deletes the original node, injects the new node at equal index
* @param {number} node__cid
* @param {Node} newNode
* @returns {Node} newNode
*/
proto.replaceNode = function( node_cid, newNode ){
var node = this.findNode( node_cid );
if ( node ){
newNode.idx = node.idx;
this.removeNode( node._cid );
newNode = this.insertNode( newNode, node.parent, node.idx );
} else {
throw "the node's cid doesn't exist";
};
return newNode;
};
/**************** Private methods ****************/
function _buildTree( tree, parent = null, constructMode = CONSTRUCT_MODE.DEEP ){
tree.forEach( function (node, idx) {
node = _buildNode.apply( this, [ tree, node, parent, idx ] );
_addNodeToIndex.call( this, node );
if( constructMode.is( CONSTRUCT_MODE.DEEP ) ) {
if( _hasChildren( node ) ) _buildTree.apply( this, [ node.children, node, CONSTRUCT_MODE.DEEP ] );
};
}, this);
};
function _buildNode( tree, node, parent, idx ){
if( !node._cid ) node._cid = this._cid++;
node.parent = parent;
node.level = _hasParent( node ) ? parent.level + 1 : 0;
node.prev = idx > 0 ? tree[ idx - 1 ] : null;
node.next = _indexWithinTree( tree, idx + 1 ) ? tree[ idx + 1 ] : null;
node.idx = idx;
node.isLeaf = !_hasChildren( node );
node.isBase = !_hasParent( node );
return node;
};
function _addNodeToIndex( node ){
this.index[ node._cid ] = node;
return node;
}
function _removeNodeFromIndex( node ){
delete this.index[ node._cid ];
if( _hasChildren( node ) ){
node.children.forEach( function( childNode, idx ){
delete this.index[ childNode._cid ];
if( _hasChildren( childNode ) ) _removeNodeFromIndex.call( this, childNode );
}, this);
}
}
function _indexWithinTree( tree, idx ) {
return !( idx >= tree.length || idx < 0 );
}
function _hasParent( node ){
return !!node.parent;
}
function _hasChildren( node ){
return ( node.children && node.children.length );
}
function _isArray( arr ){
return ( arr.constructor === Array );
}
module.exports = Tree;
Answer: It just keeps getting better, but I suppose we have time for one more iteration :)
1) findNode() could be a single line function, but you're declaring an unnecessary symbol.
2) There are extra blank lines everywhere. Blank lines are used to show a break in program flow, but aren't usually placed before a close-brace. So, in addRootNode(), for example, there is a blank line before the } else { line (also repeated elsewhere), which is spurious, and in removeNode() there is no blank line before the if statement, but there should be.
3) hasParent() is returning a !! -- that's probably overkill :)
4) buildTree() has this:
if( constructMode.is( CONSTRUCT_MODE.DEEP ) ) {
if( _hasChildren( node ) ) _buildTree.apply( this, [ node.children, node, CONSTRUCT_MODE.DEEP ] );
};
Which could be simplified to:
if (constructMode.is(CONSTRUCT_MODE.DEEP) && _hasChildren(node))
buildTree.apply(this, [node.children, node, CONSTRUCT_MODE.DEEP] );
5) Although it is purely stylistic, the spacing around your parenthesis and braces is non-canonical. Typically we would have no spaces inside parenthesis or braces. The code I have shown in point 4 shows canonical formatting for JS.
Typically, this:
if( !parentNode ){
would be written like this:
if (!parentNode)
6) And, although a lot of people (who are wrong) may disagree with me, I don't use braces where I only have a single target statement on each branch of an if statement. So this:
if( !parentNode ){
node = this.addRootNode( node, idx );
} else {
node = this.addChildNode( node, parent_cid, idx );
};
Becomes this:
if (!parentNode)
node = this.addRootNode(node, idx);
else
node = this.addChildNode(node, parent_cid, idx);
7) That last example was about formatting, but now that the code is clear and easy to read we can see that the last bit of code should really have been an assignment with a ternary operator:
node = !parent ? this.addRootNode(node, idx) : this.addChildNode(node, parent_cid, idx);
This is to show 'intent'. Your intent here is not to branch the program flow, but instead to assign a value to node. The if statement approach communicates that it is important to branch here -- so as a reader I focus on that, the condition, etc. The second form, with the ternary operator, communicates that it is important to set a value to a variable here, so I focus on that. Of the two, the latter focus is the correct one, the branch is unimportant in this context.
Notes:
Point's 2, 5, and 6, are about writing canonical code, so that the maximum number of people can read your code -- if you follow the same formatting standards as everyone else then people can spend more time figuring out what your code does and admiring its simplicity rather than spending time trying to decipher the way its written. | {
"domain": "codereview.stackexchange",
"id": 19867,
"tags": "javascript, tree"
} |
Master equation approach only suitable for good cavity laser? | Question: As I understand, master equation and quantum Langevin equation are equivalent formalisms. However, in a Review of Modern Physics article titled sub-Poissonian processes in quantum optics, the author says:
"The above analysis, based on the master-equation approach, assumes that different time scales govern the decay of the field in the cavity and the interaction time between the atom and the cavity mode. For lasers, this means that $t_{cav}\gg\tau_a,\tau_b$, while for micromasers one must have $t_{cav}\gg t_{int}$. This precludes consideration of effects associated with atomic dynamics, which will be considered in the next section, using the Heisenberg-Langevin approach."
So it seems Heisenber-Langevin formalism is more capable than master equation in certain cases. This is inconsistent with their equivalence. Could anyone point me out where I understand wrongly?
Thanks!
Answer: Note that the paper does not really claim that the Heisenberg-Langevin formalism is more powerful. All it says is that the
analysis (emphasis mine), based on the master-equation approach ... precludes
consideration of effects associated with atomic dynamics
So, it is not the tool which is lacking, but how it has been used.
In section V, the author derives a master equation, while making the assumptions clear: $t_\mathrm{cav} \gg t_\mathrm{int} $. This does not include the dynamics of the atomic levels $a$ and $b$, and hence the master equation derived under this approximation does not yield the effects of short timescale behaviour. The Liouvillian in equation 5.9 has only the operators associated with the cavity in it.
In the analysis of section VI. A, the dynamics of the atomic operators $\sigma^j_a$, $\sigma^j_b$ and $\sigma^j$ are explicitly considered.
In short, yes, the master equation and Heisenberg-Langevin formalisms are equivalent, but in some situations it is more convenient to think in terms of one of them. Had the author included effects of the atomic dynamics in the master equation, the result might have been the same (I say "might" because I did not read the paper: I think the two methods are used to look at two different regimes, where an approximation for one may not hold in another. However, if it were done exactly, then in principle the equations of motion of observables would be identical). | {
"domain": "physics.stackexchange",
"id": 30077,
"tags": "laser, quantum-optics"
} |
Simulating memcache get and set race condition and solving it with add | Question: Memcache get and set can hit a race condition if you use them together to achieve something like locking because it is not atomic. A Simple memcache locking logic using get and set would look like:
def access(resource):
if memcache.get(resource):
return "Access Denied"
else:
memcache.set(resource, timestamp)
return "Access Granted and Lock Obtained"
If this code is running in multi-threaded web applications, you can have a scenario where two get can happen together. Hence both will get the access the resource.
add doesn't get into this problem because it just sets the key only if the key does not exists. It also makes only a single roundtrip and hence it is atomic by default.
The same API with add would look like:
def access(resource):
if memcache.add(resource, timestamp):
return "Access Granted and Lock Obtained"
else:
return "Acess Denied"
Now, I am writing a script to simulate this race condition while using get , set and prove that using add solves the concurrent access problem with this naive memcache lock implementation. I am using files as my resource here. Multiple users can see the same file in the web application front-end and move it to another location if they get a lock to that file. However, sometimes get, set race condition happens giving access to the file for two users leading to file not found error for one of the users. Using add doesn't lead to this problem.
The script uses threading to simulate this scenario. If a file not found error happens then its considered a failure. I have two variants of the move function, one using get, set and another using add which can be used in the run method of the thread to demonstrate both functionalities.
Can anyone review this and tell me if this code is fine? A high level logical review is also fine if it is hard to set this up in your machine. One thing I notice is that the ratio of error is pretty high, but is this because I am actually doing threading which really is not random.
Pre-requisites: You need memcache module and memcached server running on port 5551 to run this. You also need a folder called archive to move the files.
import memcache
import signal
import sys
import shutil
import os
import threading
import time
mc = memcache.Client(['127.0.0.1:5551'], debug=0)
cwd = os.getcwd()
error = 0
processed = 0
def touch(fname, times=None):
with open(fname, 'a'):
os.utime(fname, times)
def signal_handler(signal, frame):
print('You pressed Ctrl+C!')
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
print("Ctrl-C exits")
def create_files():
for fname in range(1,11):
touch(str(fname) + ".txt")
def move_files_get_set():
global error
global processed
files = [file for file in os.listdir(".") if file.endswith(".txt")]
for file in files:
if os.path.isfile(file) and not mc.get(file):
processed = processed + 1
mc.set(file, int(round(time.time() * 1000)))
try:
shutil.move(os.path.join(cwd, file), os.path.join(cwd, "archive", "%s" % file))
except Exception as e:
print(e)
processed = processed - 1
error = error + 1
print("%s errors happened with %s" % (error, processed))
mc.set(file, None)
def move_files_add():
global error
global processed
files = [file for file in os.listdir(".") if file.endswith(".txt")]
for file in files:
if os.path.isfile(file) and mc.add(file, int(round(time.time() * 1000))):
processed = processed + 1
try:
shutil.move(os.path.join(cwd, file), os.path.join(cwd, "archive", "%s" % file))
except Exception as e:
print(e)
processed = processed - 1
error = error + 1
print("%s errors happened with %s" % (error, processed))
mc.set(file, None)
class myThread (threading.Thread):
def __init__(self, threadID, name, counter):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
def run(self):
print "Starting " + self.name
move_files_get_set()
print "Exiting " + self.name
def trigger():
while True:
create_files()
t1 = myThread("1", "Thread 1", "1")
t2 = myThread("2", "Thread 2", "2")
t1.start()
t2.start()
t1.join()
t2.join()
Answer: You have a race condition!
But not just the one you expected. Let's take out the 'beef' of the algorithm, and make something simpler:
import threading
processed = 0
def move_files_get_set():
global processed
for val in xrange(100000):
processed = processed + 1
class myThread (threading.Thread):
def __init__(self, threadID, name, counter):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
def run(self):
print "Starting " + self.name
move_files_get_set()
print "Exiting " + self.name
def trigger():
t1 = myThread("1", "Thread 1", "1")
t2 = myThread("2", "Thread 2", "2")
t1.start()
t2.start()
t1.join()
t2.join()
print processed
if __name__ == "__main__":
trigger()
What I did was basically take out everything related to memcache and files.
Here's the output:
$ python base.py
Starting Thread 1
Starting Thread 2
Exiting Thread 1
Exiting Thread 2
123418
$ python base.py
Starting Thread 1
Starting Thread 2
Exiting Thread 2
Exiting Thread 1
182550
Another race condition
In move_files_add.
def move_files_add():
global error
global processed
files = [file for file in os.listdir(".") if file.endswith(".txt")]
for file in files:
if os.path.isfile(file) and mc.add(file, int(round(time.time() * 1000))):
processed = processed + 1
try:
shutil.move(os.path.join(cwd, file), os.path.join(cwd, "archive", "%s" % file))
except Exception as e:
print(e)
processed = processed - 1
error = error + 1
print("%s errors happened with %s" % (error, processed))
mc.set(file, None)
What can happen is:
* p1: os.path.isfile(file) -> true
* p2: os.path.isfile(file) -> true
* p1: mc.add(file, bla) -> true
* p1: shutil.move() -> done
* p1: mc.set(file, None) -> done
* p2: mc.add(file, bla) -> true
* p2: shutil.move() -> KABOOM!
Moving files the correct way
When doing files, and there is a risk of race conditions, (almost) always use the following pattern:
try:
os.rename(source, target)
except FileNotFoundError:
# Oops, too late!
Now, os.rename has a problem, it only works on the same filesystem. So depending on your needs you could do something like:
try:
os.rename(source, tempfile_in_same_dir_as_source)
except FileNotFoundError:
# Oops, too late! No worries.
pass
else:
# Yes, it worked. Now we just need to make sure it's moved
# to the right target location.
shutil.move(tempfile_in_same_dir_as_source, target) | {
"domain": "codereview.stackexchange",
"id": 20327,
"tags": "python, multithreading, cache, locking, memcache"
} |
updating the URDF after changing the physical device on the robot | Question:
Hello !
I'm working on my robot arm for grasping task using a RGBD camera to detect an object and feedback the position of an object to grasp.
Recently, I changed the camera on the robot, so I have to also update the URDF for the MoveIt, but I'm not sure that updating only the URDF is the right answer.
So my question is I would like to know the process of updating, after I changed the physical device on the robot
If more detail is needed, please tell.
I'm new to ROS so If I say something not right, please let me know.
Thank you in advanced
Originally posted by prem_ on ROS Answers with karma: 3 on 2021-10-10
Post score: 0
Answer:
There is no generic answer to your question, because it depends on your old and new setup. You need to understand what processing was done on the old camera data, and how the new camera is different. Here are some questions to think about (I'm not looking for answers, this is intended to guide your investigation):
Have you changed the algorithm used to determine depth?
Is the old/new camera calibrated?
Has the camera's Optical Transform Frame changed?
What information is used by the image analysis code?
Originally posted by Mike Scheutzow with karma: 4903 on 2021-10-11
This answer was ACCEPTED on the original site
Post score: 0
Original comments
Comment by prem_ on 2022-10-22:
Thank you very much for your replying, and sorry for late response.
I have come to understand that If I make some changes to the URDF, I have to update the moveit config using the moveit assistant and go through some basic setup like self-collision checking, updating SRDF, etc.
But your questions have made me understand a lot in another point of view.
Thank you again! | {
"domain": "robotics.stackexchange",
"id": 37000,
"tags": "ros, urdf, moveit, ros-melodic"
} |
"sudo apt-get install ros-groovy-joystick_drivers" doesn't work | Question:
Hi there. I have installing problems.
"sudo apt-get install ros-groovy-actionlib" works fine, but
"sudo apt-get install ros-groovy-joystick_drivers" don't.
I just get:
Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package ros-groovy-joystick_drivers
Any Idea why?
I am working with Ubuntu 12.04.
Thanks.
Originally posted by DIDI on ROS Answers with karma: 32 on 2013-02-19
Post score: 0
Answer:
Underscores are replaced by hyphens in the Ubuntu packages. That means you have to run
sudo apt-get install ros-groovy-joystick-drivers
Hint: You can use tab-completion while typing: hit "tab" while completing the package name.
Originally posted by AHornung with karma: 5904 on 2013-02-19
This answer was ACCEPTED on the original site
Post score: 3
Original comments
Comment by jarvisschultz on 2013-02-19:
Note you could also use apt-cache to search for packages e.g. apt-cache search ros.*joystick shows the name of the package you were trying to install. As well as a small description of the package. | {
"domain": "robotics.stackexchange",
"id": 12954,
"tags": "ros"
} |
Is beta decay accelerateable? | Question: Is there any way to alterate weak interaction and thus the rate of beta decay by making it slower or faster? If yes, how? Would radiating some extra bosons or neutrinos, perhaps in a focused beam, change the rate somehow?
Answer: No nuclear reaction rates can be altered as far as we know, other than by the well-known method of hitting the nuclei with neutrons.
Having said that, some people keep reporting correlations with solar activity, possibly related to some undetermined neutrino-based reactions
some not so recent articles with links to papers on the subject:
https://copaseticflow.blogspot.com/2013/05/solar-neutrinos-and-radioactive-decay.html
https://en.wikipedia.org/wiki/GSI_anomaly | {
"domain": "physics.stackexchange",
"id": 62698,
"tags": "nuclear-physics, radiation, radioactivity, weak-interaction, half-life"
} |
How can I determine how much energy a sensor pixel can withstand before exploding? | Question: I am trying to design a camera system to image a laser beam. I know the sensor is a Sony IMX226, and I have the data sheet for this sensor. The data sheet, however, does not list a maximum energy threshold for the sensor. It does give a decibel range though.
In theory, if I could determine the minimum energy to activate a pixel, then I could also determine the maximum energy a single pixel could handle, right? The data sheet gives minimum voltages, and saturation voltages, but I am unsure if this can be translated into light energy per pixel.
Any help determining the maximum energy per pixel before it destroys the pixel would be most appreciated!
Answer: This isn't trivial. Silicon sensors can generally handle power well above saturation without damage. Usually, the limit is temperature. So, what you need to do is a heat transfer calculation involving the power of your laser, the area its image covers, the thickness of the silicon, the nature of the substrate, ... | {
"domain": "physics.stackexchange",
"id": 89203,
"tags": "laser, electronics, camera, sensor, radiative-transfer"
} |
Discrete optimisation in 5 variables | Question: I need to solve the following optimisation problem and I can't come up with any solutions. Is there any algorithm to solve this type of problem. I tried to think of a greedy algorithm or brute force, but couldn't solve it.
Input :
$ n_1, n_2, n_3, n_4, n_5$ : Positive integers
$ a_1, a_2, a_3, a_4, a_5 $ : Positive integers
$ p_1, p_2, p_3, p_4, p_5 $ : Positive integers
$ Q $ : Positive integer
Output :
$ m_1, m_2, m_3, m_4, m_5$ : Non- negative integers
Minimize :
$ \sum_{i=1}^{5}{m_i a_i p_i}$
Constraints :
$ \forall i : m_i \geq n_i $ OR $ m_i = 0 $
$ \sum_{i=1}^{5}{m_i a_i} \geq Q$
Answer: First of all, we can enumerate over all 32 possibilities of which of the two alternatives is chosen for each $m_i$ (whether $m_i \geq n_i$ or $m_i = 0$). We will analyze, for simplicity, the case where $m_i \geq n_i$ for all $i$. Let $\mu_i = m_i - n_i$, so that $\mu_i$ is some arbitrary non-negative integer. We now want to minimize the quantity $\sum_i \mu_i a_i p_i$ under the constraint $\sum_i \mu_i a_i \geq P$ (where $P$ is a function of other known parameters).
You can now reduce your problem to KNAPSACK as described in a question on cstheory. | {
"domain": "cs.stackexchange",
"id": 6976,
"tags": "algorithms, optimization, dynamic-programming, discrete-mathematics, greedy-algorithms"
} |
What's the difference between LSTM and GRU? | Question: I have been reading about LSTMs and GRUs, which are recurrent neural networks (RNNs). The difference between the two is the number and specific type of gates that they have. The GRU has an update gate, which has a similar role to the role of the input and forget gates in the LSTM.
Here's a diagram that illustrates both units (or RNNs).
With respect to the vanilla RNN, the LSTM has more "knobs" or parameters. So, why do we make use of the GRU, when we clearly have more control over the neural network through the LSTM model?
Here are two more specific questions.
When would one use Long Short-Term Memory (LSTM) over Gated Recurrent Units (GRU)?
What are the advantages/disadvantages of using LSTM over GRU?
Answer: On the same problems, sometimes GRU is better, sometimes LSTM.
In short, having more parameters (more "knobs") is not always a good thing. The training process needs to learn those parameters. There is a higher chance of over-fitting, amongst other problems.
The parameters are assigned specific roles inside either GRU or LSTM, so if that role is less important for a specific learning challenge, then it can be wasteful or even counter-productive to have the system attempt to learn values for them.
The only way to find out if LSTM is better than GRU on a problem is a hyperparameter search. Unfortunately, you cannot simply swap one for the other, and test that, because the number of cells that optimises a LSTM solution will be different to the number that optimises a GRU.
When would one use Long Short-Term Memory (LSTM) over Gated Recurrent Units (GRU)?
When it proves better, experimentally. In some problem domains, this may be established and you can check. However, in other problem domains if either GRU or LSTM works well enough to solve a problem (and the superiority of either LSTM or GRU is not the main point of the work), then it may not so clear. | {
"domain": "ai.stackexchange",
"id": 2001,
"tags": "comparison, recurrent-neural-networks, long-short-term-memory, gated-recurrent-unit"
} |
What is the Critical impact parameter for photons of a black hole? | Question: What is the "Critical impact parameter" for photons of a Black hole with a Radius $r$?
Here I'm defing the Critical impact parameter $C$ as the value such that.
A photon with an impact parameter > C will be deflected by the black hole.
A photon with am impact parameter < C will be pulled into the black hole.
Answer: The impact parameter $b$ of a scattering orbit is given by (in units with $G=c=1$)
$$ b= \frac{L}{E}$$
A critical photon trajectory will have the same ratio $L/E$ as the photon orbit. This we can calculate by taking the expressions for $E$ and $L$ for circular orbits in Schwarschild spacetime:
$$ E= M\frac{r-2M}{\sqrt{r(r-3M)}}$$
and
$$ L= M^{3/2}\frac{r}{\sqrt{(r-3M)}}$$
Taking the ratio and the limit $r\to 3M$ (i.e. the photon radius) you find
$$ b= 3\sqrt{3} M$$
or (restoring $G$ and $c$),
$$ b= 3\sqrt{3} \frac{GM}{c^2} $$. | {
"domain": "physics.stackexchange",
"id": 99581,
"tags": "black-holes, photons, scattering, definition"
} |
Using multiple arduinos / running multiple nodes | Question:
Hi, I have two arduinos (Uno and Duemilanove) and I want to use the two of them in parallel on one machine. However, rosserial_python does not accept multiple /dev files as parameters, so I cannot give the addresses of both arduinos to one rosserial_python node.
The other option is running multiple rosserial_python nodes with each having different parameters, but ROS does not allow that since there are multiple nodes with the same name. It should be possible to run multiple nodes on one machine, but I don't know how. Any help is appreciated, thanks in advance!
Originally posted by Hououin Kyouma on ROS Answers with karma: 205 on 2012-01-18
Post score: 2
Answer:
Renaming the nodes should work, but you may find it more convenient to run each robot in a separate namespace.
That can be done in roslaunch using the ns attribute of the <node> or <group> tags. Or, directly with rosrun using the ROS_NAMESPACE environment variable.
Originally posted by joq with karma: 25443 on 2012-01-19
This answer was ACCEPTED on the original site
Post score: 1 | {
"domain": "robotics.stackexchange",
"id": 7931,
"tags": "arduino, rosserial"
} |
How to sample for K-Ar dating? | Question: How much sample of volcanic rock is required to undertake a K-Ar date measurement, and does it matter if the rock contains vesicles? Are there tricks of the trade to get a good sample?
Answer: I run an argon lab which does also K-Ar measurements.
The sample amount depends on the age because you need enough signal strength to measure the radiogenic argon component precisely. Young rocks have very low 40Ar* and to get enough volts on the detector you need more sample. Having the incorrect amount is akin to trying to measure micrometers with a yardstick.
For K measurements 30 mg in our lab is routine.
For the argon measurement we usually use about 2 mg; for very young rocks up to 200mg for rocks with ca. 2% K. We can date volcanic rocks of less than 20000 years using this technique and have dated historic eruptions successfully in our lab.
Usually customers can say if the rocks are very young, so I usually prepare the sample amount accordingly. I had a couple of completely blind samples where I had no idea of the age of the sample a priori, I ran a test with a ca 4 mg which yielded almost no gas, so I re-ran with more material.
Regarding sampling technique itself- look for minerals with more potassium, such as muscovite, biotite, amphiboles, or more felsic rocks. If the rocks are obviously weathered, they are not suitable.
I also have to say that Ar/Ar is a more accurate tool for most rocks and minerals, and then just a few mg is enough if the samples are Mesozoic or older. If they are very young, higher sample amounts are required as with the K-Ar technique. | {
"domain": "earthscience.stackexchange",
"id": 1473,
"tags": "dating, age"
} |
Why can't a causal digital filter have an infinitely sharp transition between the passband and the stopband? | Question: In DSP book by Proakis and as well as in this pdf, it is mentioned that practical causal digital filters cannot have an infinitely sharp transition from Pass-band to Stop-band. Why is it so? Can you please provide a detailed explanation (with proof)?
Edit 1: In the book in was just mentioned that is a consequence of the Gibbs phenomenon, which results from the truncation of h(n) to achieve causality. I didn't understand how.
Answer: I don't have a concrete proof for this one. However, I can tell you this...
Consider a perfect low pass filter. The time domain representation is a sinc. And for any system to have a sharp transition band, a base signal has to be multiplied with a rectangular waveform in the frequency domain. Which implies that, the time domain signal of the same has to be convoluted with a sinc in time domain. We know that sinc function is a non causal signal.
Hence proved. | {
"domain": "dsp.stackexchange",
"id": 9789,
"tags": "filters, digital-filters, causality"
} |
LSTM text classifier shows unexpected cyclical pattern in loss | Question: I'm training a text classifier in PyTorch and I'm experiencing an unexplainable cyclical pattern in the loss curve. The loss drops drastically at the beginning of each epoch and then starts rising slowly. However, the global convergence pattern seems OK. Here's how it looks:
The model is very basic and I'm using the Adam optimizer with default parameters and a learning rate of 0.001. Batches are of 512 samples. I've checked and tried a lot of stuff, so I'm running out of ideas, but I'm sure I've made a mistake somewhere.
Things I've made sure of:
Data is delivered correctly (VQA v1.0 questions).
DataLoader is shuffling the dataset.
LSTM's memory is being zeroed correctly
Gradient isn't leaking through input tensors.
Things I've already tried:
Lowering the learning rate. Pattern remains, although amplitude is lower.
Training without momentum (plain SGD). Gradient noise masks the pattern a bit, but it's still there.
Using a smaller batch size (gradient noise can grow until it kinda masks the pattern, but that's not like solving it).
The model
class QuestionAnswerer(nn.Module):
def __init__(self):
super(QuestionAnswerer, self).__init__()
self._wemb = nn.Embedding(N_WORDS, HIDDEN_UNITS, padding_idx=NULL_ID)
self._lstm = nn.LSTM(HIDDEN_UNITS, HIDDEN_UNITS)
self._final = nn.Linear(HIDDEN_UNITS, N_ANSWERS)
def forward(self, question, length):
B = length.size(0)
embed = self._wemb(question)
hidden = self._lstm(embed)[0][length-1, torch.arange(B)]
return self._final(hidden)
Answer: It turns out that the zig-zag pattern is an inherent effect of using a word embedding layer. I don't fully understand the phenomenon, but I believe it has a strong correlation with the embeddings acting as a sort of memory slots, which can change relatively quickly, and the LSTM generating a summary of the sequence, so that the model can remember past combinations.
I found this plot of a training loss curve of word2vec and it exhibits the same per-epoch pattern.
Edit
After conducting several experiments, I've isolated the causes. It seems that this is an indirect effect of having a large model capacity. In my case, I had too large word embeddings (size 1024) and too many classes (2002), which also increases model capacity, so the model was doing an almost per-sample learning. Reducing both resulted in a smooth-as-silk learning curve and a better generalisation. | {
"domain": "ai.stackexchange",
"id": 1284,
"tags": "long-short-term-memory, objective-functions, pytorch, learning-curve"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.