anchor stringlengths 0 150 | positive stringlengths 0 96k | source dict |
|---|---|---|
how is a pendulum clock's time and the time period of the pendulum in it related? | Question: I'm working out how much time a pendulum clock will gain or loose due to change of the length of the pendulum due to temperature. so far I've got, new time period, $$T_2=T_1(1+\frac12\alpha\Delta T)$$
due to $\Delta T$ change in temperature, when the coefficient of linear expansion of the pendulum material is $\alpha$. $T_1$ is the time period when there is no change in temperature.
Now, I can not understand how the time period of the pendulum and the time measured by the clock is related. Please help me with this and also mention if I am going correct or not.
Answer: You are on the right track.
For a mechanical pendulum, the relationship is linear. You don't need to know how many swings of the pendulum corresponds to how many seconds. If the pendulum is x% slower, it will report x% fewer seconds per day.
Now since length goes as $\ell = \ell_0(1+\alpha \Delta T)$ and period of pendulum as
$$T = 2\pi\sqrt{\frac{\ell}{g}}$$
We can do the Taylor expansion for $\ell$, noting that $\sqrt{1+x}\approx 1+\frac12 x$ for small $x$, to give us
$$T_2 = T_1 (1 + \frac12 \alpha \Delta T)$$
as you noted.
Now the number of swings per day times the time per swing should equal one day, or $N\cdot T=86400$. It follows that the number of seconds per day, N, is changed by
$$N_2 = N_1 \frac{T_1}{T_2} = \frac{N_1}{1+\frac12\alpha \Delta T} = N_1\left(1-\frac12\alpha T\right)$$
The difference in seconds per day then follows. I will leave that as an exercise. | {
"domain": "physics.stackexchange",
"id": 28245,
"tags": "homework-and-exercises, newtonian-mechanics, thermodynamics"
} |
Does the thickness of germanium dioxide affect the amount of infrared light that passes through it? | Question: Furthermore, what properties of germanium cause it to behave in this manner?
Answer: The thickness of any material will affect the amount of IR radiation that passes through it. The equation for the attenuation of radiation thru matter is given by this equation. $I = I_0\ e^{-kt}$ where k is the attenuation coefficient for radiation through the material and t is the thickness of the material.
Germanium dioxide is transparent to IR radiation but that doesn't mean 100% of IR passes through a thin layer of GeO2. There will be a small amount that gets attenuated. The equation above holds but k will be very small. Still, the thickness will determine how much IR passes through it. | {
"domain": "physics.stackexchange",
"id": 61710,
"tags": "optics"
} |
What is the gravity/inertia question? | Question: Is the discussion about how gravity and inertia are the same, about the idea that when you hit a ball, it doesn't come back but when you throw a ball up, it does come back?
Answer: This discussion has nothing to do with a ball being hit or thrown.
It is about why the inertial mass is equal to the gravitational mass
(see also inertial vs. gravitational mass).
But for explaining this I need to reach out more.
Inertial mass is how much a body refuses to be accelerated.
To accelerate a body with acceleration $\mathbf{a}$
you need to apply a force
$$\mathbf{F}_a=m_i \mathbf{a}.$$
The factor $m_i$ appearing here is called the inertial mass of the body.
On the other hand, gravitational mass is how much a body reacts to gravity.
When a body is in a gravitational field of strength $\mathbf{g}$
then it is subject to the gravitational force
$$\mathbf{F}_g=m_g\mathbf{g}.$$
The factor $m_g$ appearing here is called the gravitational mass of the body (or more precisely: the passive gravitational mass)).
Now it is known (already by Newton in 1680,
extending on Galilei's concepts from 1600) that for all bodies
these two masses ($m_i$ and $m_g$) are equal.
And therefore we usually call it just the mass of the body.
But why are these two equal? This is a simple but highly non-trivial question.
And even Newton didn't have an answer for this.
It took until 1915 (Einstein's theory of general relativity)
to get an explanation for this coincidence.
Actually this theory begins with the equivalence
principle, claiming that a gravitational field
and and an acceleration are not distinguishable from each other.
Or saying in other words: The gravitational force is also kind of
an inertial force, and therefore proportional to the inertial mass. | {
"domain": "physics.stackexchange",
"id": 73770,
"tags": "newtonian-mechanics, newtonian-gravity, projectile, inertia"
} |
Myhill-Nerode and closure properties | Question: It is well known that regular languages are characterized by the Myhill-Nerode equivalence. For language $L$ over $\Sigma^*$ define the equivalence $x\sim_L y$ over $\Sigma^*$ iff for all $z\in\Sigma^*$ we have $xz\in L \iff yz\in L$. Then $L$ is regular iff $\sim_L$ is of finite index, i.e., has a finite number of equivalence classes.
I know that the relation can be used to show that some languages are not regular, by indicating infinitely many strings that are not equivalent.
My question: can we easily use Myhill-Nerode to show closure properties of regular languages? Or should we use the "syntactic congruence" of languages?
As an example for prefix it is easy, as $x\sim_L y$ implies $x\sim_{\mbox{pref}(L)} y$. But how do we handle suffix, concatenation, star, mirror?
Answer: I do closure under boolean operations with the MyHill-Nerode characterisation. Never saw it done that way. A right congruence $\sim$ saturates a language $L$ if
$$
u \sim v \Rightarrow ( u \in L \leftrightarrow v \in L )
$$
or equivalently iff $L$ is an union of congruence classes. We use:
Theorem: (MyHill-Nerode) A language is regular if and only if there is a right-congruence of finite index that saturates $L$.
Now suppose we have regular languages $L_1, L_2 \subseteq X^{\ast}$, and denote $\sim_{L_1}, \sim_{L_2}$ some right congruences of finite index saturating them. Then
$$
u \sim v :\Leftrightarrow u \sim_{L_1} v \land u \sim_{L_2} v
$$
is a right congruence (the intersection of both), and it refines both. Furthermore we have
$$
[u]_{\sim} = [u]_{\sim_{L_1}} \cap [u]_{\sim_{L_2}}.
$$
Hence we have a finite number of equivalence classes. Also this gives that the intersection of equivalence classes $[u]_{\sim_{L_1}}$ and $[v]_{\sim_{L_2}}$ is either empty, or it has a common element $w$ and hence equals the equivalence class $[w]_{\sim}$. This gives that $L_1 \cap L_2$ is either empty or could be written as the union of equivalence class for $\sim$. By the above theorem $L_1 \cap L_2$ is regular.
For $L_1 \cup L_2$ it is an union of equivalence classes for $\sim_1$ and $\sim_2$, which are themselve unions of equivalence classes for $\sim$, hence it is also regular. And for complementation, this follows as the equivalence classes partition $X^{\ast}$, hence a right congruence working for $L_1$ works also for $X^{\ast} \setminus L_1$. $\square$
Additional comments: In your question you also mentioned the canonical Nerode right congruence
$$
u \equiv_L v :\Leftrightarrow (\forall w \in X^{\ast} : uw \in L \leftrightarrow vw \in L)
$$
with $L \subseteq X^{\ast}$. This is the coarsest right-congruence saturating $L$. Now maybe it might be natural to ask if we can construct the Nerode right congruence of $L_1 \cap L_2$ or $L_1 \cup L_2$ easily out of the ones for $L_1, L_2$, or if the resulting intersection congruence arises as some Nerode right congruence. Maybe we can find such simple formulas like
$$
u \equiv_{L_1\cap L_2} v \Leftrightarrow u \equiv_{L_1} v \land u \equiv_{L_2} v.
$$
But the above does not hold. And to my knowledge there does not exists any simple relation. For example consider $L_1 = (aa)^{\ast}$ and $L_2 = a(aa)^+$, then we have
$$
L_1 \cap L_2 = \emptyset, \qquad
L_1 \cup L_2 = X^{\ast} \setminus \{a\}.
$$
Now $\equiv_{L_1} \cap \equiv_{L_2}$ has at least four congruence classes, as it refines $\equiv_{L_2}$ which has exactly four congruence classes. But $\emptyset$ has precisely one class, and $X^{\ast} \setminus \{a\}$ has three (could all be easily seen by using minimal complete automata).
EDIT (2019.08.18).
The mirror and suffix operation are related to the left congruence
$$
u \equiv^L v \Leftrightarrow \forall w \in X^* : wu \in L \leftrightarrow wv \in L.
$$
If $\equiv^L$ has finite index, similar as for the prefix-operation and the right-congruence, $\equiv^{\operatorname{suffix}(L)}$ has finite index. And
$u \equiv_L v$ iff $\operatorname{mirror}(u) \equiv^{\operatorname{mirror}(L)} \operatorname{mirror}(v)$; and as the mirror operation is a bijection on $X^*$ the last equation gives that $\equiv^{\operatorname{mirror}(L)}$ has finite index iff $\equiv_L$ has finite index (note that the left congruence has the same index as the right congruence for the mirrored words, but in general a right congruence for $\operatorname{mirror}(L)$ might have exponential many more classes as is shown by standard contructions from automata theory).
So these operations are handled if we can show that both congruences have finite index at the same time or not. For this lets look at the syntactic congruence
$$
u \equiv_{S(L)} v \Leftrightarrow \forall x,y \in X^* : xuy \in L \Leftrightarrow xvy \in L.
$$
This congruence refines both congruences above, hence if it is finite, both congruence above are also finite. It is $u \equiv_{S(L)} v$ iff for all $w \in X^*$ we have $[wu]_{\equiv_L} = [wv]_{\equiv_L}$, hence we have a well-defined and injective map from the $\equiv_{S(L)}$-equivalence classes to the transformations on $\{ [w]_{\equiv_L} : w \in X^* \}$, and if the latter is a finite set, the set of those transformations is finite too, which implies that $\equiv_{S(L)}$ is of finite index. So in total we have that $\equiv^L$ has finite index if $\equiv_L$ has finite index, the reverse is implied similar. | {
"domain": "cs.stackexchange",
"id": 8317,
"tags": "regular-languages, closure-properties"
} |
Openni_Kinect problem | Question:
I have ubuntu running ros. I installed Openni_Kinect from the command "sudo apt-get install ros-electric-openni-kinect"
and now I tried this command to test if everything is working, roslaunch openni_camera openni_node.launch
and the error that I get is "[openni_camera] is not a package or launch file name"
any help welcomed
Originally posted by mlandergan on ROS Answers with karma: 3 on 2012-05-08
Post score: 0
Original comments
Comment by mlandergan on 2012-05-09:
I followed the steps that you gave me and everything seems to be working. Is there a way to check? and I then went and tried to install openni_kinect again but I get this error
Comment by mlandergan on 2012-05-09:
You might want to run 'apt-get -f install' to correct these:
The following packages have unmet dependencies:
ros-electric-common : Depends: yaml-cpp0.2.6-dev but it is not going to be installed
ros-electric-openni-kinect : Depends: ros-electric-image-common (= 1.6.1-s1328510857~oneiric) but it is
Answer:
Your environment is not set up correctly. The package openni_camera installs to /opt/ros/electric/stacks/openni_kinect/openni_camera, and that directory is apparently not on your ROS_PACKAGE_PATH environment variable. Follow these steps to fix this.
Originally posted by Martin Günther with karma: 11816 on 2012-05-08
This answer was ACCEPTED on the original site
Post score: 1 | {
"domain": "robotics.stackexchange",
"id": 9307,
"tags": "openni-kinect"
} |
Does universe calculate? | Question: This is probably totally naive (philosophical?) question. I am not mathematician nor physicist so maybe it is quite dumb question too.
IF universe does calculate, how does it cope with numbers like 1/3, PI, etc. ?
IF universe does not calculate, does this theoretically mean there could be (opposed to mathematics/physics) some other (non-invented yet) tool/mechanism for describing the universe, where there would be no need for approximations of numbers like 1/3, PI, etc?
If one would try to model a whole star (containing enormous number of different particles, external gravitational influences, etc.) as detailed as possible with nowadays knowledge of mathematics/physics, what would be the outcome of such a calculation if one would have to make numerous approximations (mentioned above) all the time?
Answer: The universe does not "calculate". The universe just exists as it is and evolves. We calculate things like how far a particle with a given speed goes in a given time because we don't actually have the particle or the time. The universe just has everything in a state, has the laws of nature in place, and everything works itself out.
In the universe an actual particle starts at some speed and time takes it however far it can go. No calculation required. The universe has all the resources necessary. With these, all it has to have is have initial conditions, have laws that guide the actions of things in it, and have time for the actions of those laws to run. This isn't a mechanism we can always use. There will always come a point where we don't actually have the thing/process we want to analyze, so we will have to use calculations and numbers to represent that thing/process. | {
"domain": "physics.stackexchange",
"id": 21228,
"tags": "universe"
} |
Schroedinger equation. Why Potential energy instead of Force? | Question: What is the reason Schroedinger equation is quoted in terms of potential energy instead of force?
Answer: Schrödinger's Wave Equation is an application of Hamiltonian Mechanics. Unlike Newtonian Mechanics, Hamiltonian Mechanics relies on knowing about the things that contribute to the energy of the system. If you know the things which contribute to the energy of a system, then you can determine things like forces, accelerations, and positions. (All through the miracle that is calculus!) These forces and accelerations can also change over time, and we can better understand how they evolve over time using Lagrangian and Hamiltonian Mechanics. Even better, with Lagrangian and Hamilitonian Mechanics, we don't have to know how these forces change over time, because we can figure it out with math!
This approach makes life easier, because we often want to know what the energy of a particle is. This is especially true of small particles because a lot of their behaviors depend on the particle's energy. The ability to simply set a term to 0 allows us to solve for simple situations, (such as a "particle in a box" and "free particle" situations, where the potential energy is very often 0) which then let us solve more complicated situations later using various techniques, like Perturbation Theory.
This approach is super awesome because humans are get pretty good at identifying the various things that contribute energy to a system. Forces in a system, however, can be tricky, and it can be hard to guess which forces happen when.
To concisely answer your question, the Schrödinger Wave Equation has values for energies because of Hamiliton (and Legrange), and it's super useful. | {
"domain": "physics.stackexchange",
"id": 13405,
"tags": "quantum-mechanics, forces, schroedinger-equation, hamiltonian-formalism, potential-energy"
} |
Watch a directory and insert new entries into database - Follow up | Question: This is now my new code implementing the recommendations from my previous question.
import os
import time
import mysql.connector
import MySQLdb
import ConfigParser
import base64
import logging
from logging.handlers import TimedRotatingFileHandler
import sys
import ast
import smtplib
from sendmail import send_mail
"""
TO DO:
1. Retry failure upload when mysql disconnects
"""
currdir = os.getcwd()
curr_datetime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
"""function that reads the config file"""
def read_Config(section, option):
conf_file = currdir + "\\Config\\config.ini"
config = ConfigParser.ConfigParser()
config.read(conf_file)
sections = config.sections()
def ConfigSectionMap(section):
dict1 = {}
options = config.options(section)
for option in options:
try:
dict1[option] = config.get(section, option)
if dict1[option] == -1:
# print("skip: %s" % option)
LOGGER.debug("skip: %s" % option)
except:
deb = "exception on %s!" % option
LOGGER.debug(deb)
write_log(wyko_no,'DEBUG',deb,cur_datetime)
dict1[option] = None
return dict1
res = ConfigSectionMap(section)[option]
return res
"""read configuration file"""
app_name = read_Config('application','app_name')
FILE_PATH = read_Config('application','file_path')
LOG_PATH = currdir + "\\" + read_Config('application','log_path') + "\\"
USER = read_Config('database','user')
PASSWORD = read_Config('database','password')
PASSWORD = base64.decodestring(PASSWORD) ##decode password, remove D and L from the string
HOST = read_Config('database','host')
DB = read_Config('database','db')
DB_PORT = read_Config('database','port')
RECEIVERS = ast.literal_eval(read_Config('email','receivers'))
SENDER = read_Config('email','sender')
SMTP = read_Config('email','smtp')
PORT = read_Config('email','port')
"""set up logger"""
LOGGER = logging.getLogger(app_name)
LOG_FILE = app_name + '.log'
LOG_PATH = LOG_PATH + LOG_FILE
LOGGER.setLevel(logging.DEBUG)
hdlr = TimedRotatingFileHandler(LOG_PATH, when="d", interval=1, backupCount=1)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s: %(message)s')
hdlr.setFormatter(formatter)
LOGGER.addHandler(hdlr)
sh = logging.StreamHandler(sys.stdout)
sh.setLevel(logging.DEBUG)
sh.setFormatter(formatter)
LOGGER.addHandler(sh)
"""insert csv to database"""
def insert_csv(file,filename):
try:
cnx = mysql.connector.connect(user = USER,
password = PASSWORD,host = HOST,
database = DB, port = DB_PORT)
cursor = cnx.cursor()
with open(file, 'rb') as f:
thedata = f.read()
curr_datetime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
sql = "INSERT INTO wyko_file(wyko_file,file_name,date_inserted) VALUES (%s,%s,%s)"
cursor.execute(sql,(thedata,filename,curr_datetime))
if cursor.rowcount != 0:
LOGGER.info("Transfer to database succesful!")
cnx.commit()
except (MySQLdb.OperationalError, MySQLdb.ProgrammingError), e:
LOGGER.error(e)
send_mail(SENDER,RECEIVERS,e)
finally:
cursor.close()
cnx.close()
"""main loop that watches the directory"""
def main():
try:
for dirpath, dirnames, files in os.walk(FILE_PATH):
for i in files:
file = dirpath+i
try:
LOGGER.info("Transferring file: " +i)
insert_csv(file,i)
except Exception, e:
LOGGER.error(e)
send_mail(SENDER,RECEIVERS,e)
finally:
os.remove(file)
LOGGER.info('File successfully removed from '+FILE_PATH+"\n"+"-"*80)
except Exception, e:
LOGGER.error(e)
send_mail(SENDER,RECEIVERS,e)
# break
if __name__ == "__main__":
LOGGER.info("Application starts running\n"+"-"*80)
main()
But upon deploying this application on a client, I have encountered an issue that this parser is eating up the resources on the client computer and causes applications to hang/lag. I think the code needs optimizing.
The parser is currently deployed on a Windows XP OS with 2GB of RAM.
Answer: Parsing configuration file
There are a few problems with your read_Config function:
ConfigParser objects are akin to dictionaries of dictionaries: there is no need to build dictionaries out of them, they already behave as such with a few extra functionnalities;
read_Config is called (and thus the file parsed) for each parameter you want to retrieve out of the file: this is a waste of resources, read the file once and return the parser object to extract parameters out of it;
read method of ConfigParser behave the same as open, it accepts relative path, no need to use getcwd for that;
read method of ConfigParser actually accept a list of filepaths (a single string is turned into a list of 1 element) and silently handle missing files (rationale in the docs); your code will fail if the file is not handled so I suggest using
with open(<path>) as config_file:
config.readfp(config_file)
instead to get a more descriptive error if anything goes wrong.
Too much “constants”
A lot of your constants are dependant of the result of your read_Config function.
At this point you may want to introduce a class in your design to improve readability and reusability. The various “constants” initialized out of read_Config will become the state (attributes) of your object.
Exception handling
You made a good point of handling specific exceptions in the method reviewed in your previous question but forgot to apply the advice in your read_Config function.
Also you should prefer the new style of variable naming in except clause using the as keyword: e.g. except Exception as e. This is the only way to write it in Python 3 and yours is considered deprecated.
Avoid repetitions
Almost all your except performs the same operation. For now it’s only two lines of code but someday you might want to improve them. Maybe that the send_mail function only uses str on your exception before sending the mail, leaving out the whole stacktrace with usefull informations and at some point you’ll want to improve that.
Use a function for that: any change will be applied anywhere for free.
Bugs?
What is this write_log function in read_Config? You neither define it nor import it.
In main you use finally to remove files whether or not they got into the database. You may want to use else instead to remove only if the sql insert succeded.
You removed a while True from your last question, is it expected?
Misc
Not sure which way is better but you can get your curr_daytimes using datetime.now().isoformat(' ') instead of using time;
Why are you using ast to parse the list of RECEIVERS? Can't you write it as a string of recipients separated by semi-colons and split it in your code?
Docstrings are “the string written the line right after a function declaration, if any” (not before).
smtplib, SMTP and PORT are never used.
Proposed alternative
import os
from datetime import datetime
from sys import stdout
import logging
import mysql.connector
import MySQLdb
import base64
from ConfigParser import ConfigParser
from sendmail import send_mail
def parse_config(config_filename):
"""function that reads the config file"""
config = ConfigParser()
with open(config_filename) as config_file:
config.readfp(config_file)
return config
class FolderWatcher(object):
def __init__(self, config_filename):
"""Read configuration file and store important data out of it"""
config = parse_config(config_filename)
app_name = config.get('application', 'app_name')
self.logger = logging.getLogger(app_name)
self.logger.setLevel(logging.DEBUG)
formatter = logging.Formatter(
'%(asctime)s - %(name)s - '
'%(levelname)s: %(message)s')
log_path = config.get('application', 'log_path')
handler = logging.handlers.TimedRotatingFileHandler(
os.path.join(log_path, app_name + '.log'),
when="d", interval=1, backupCount=1)
handler.setFormatter(formatter)
self.logger.addHandler(handler)
handler = logging.StreamHandler(stdout)
handler.setLevel(logging.DEBUG)
self.logger.addHandler(handler)
self.watched_folder = config.get('application','file_path')
self.mysql_credentials = {
'user': config.get('database','user'),
##decode password, remove D and L from the string
'password': base64.decodestring(config.get('database','password')),
'host': config.get('database','host'),
'database': config.get('database','db'),
'port': config.get('database','port'),
}
self.mail_sender = config.get('email', 'sender')
# You’ll need to modify your config file to get this line to work
self.mail_receivers = map(str.strip,
config.get('email', 'receivers').split(';'))
self.logger.info("Application {} starts running".format(app_name))
self.logger.info("-"*80)
def manage_exception(self, exception):
self.logger.error(exception)
send_mail(self.mail_sender, self.mail_receivers, exception)
def insert_csv(self, file_path, filename):
"""insert csv to database"""
try:
cnx = mysql.connector.connect(**self.mysql_credentials)
cursor = cnx.cursor()
with open(file_path, 'rb') as f:
data = f.read()
curr_datetime = datetime.now().isoformat(' ')
sql = ("INSERT INTO wyko_file(wyko_file,file_name,date_inserted)"
" VALUES (%s,%s,%s)")
cursor.execute(sql, (data, filename, curr_datetime))
if cursor.rowcount != 0:
self.logger.info("Transfer to database succesful!")
cnx.commit()
except (MySQLdb.OperationalError, MySQLdb.ProgrammingError) as e:
self.manage_exception(e)
finally:
cursor.close()
cnx.close()
def watch(self):
"""main loop that watches the directory"""
try:
for root, dirs, files in os.walk(self.watched_folder):
for filename in files:
file_path = os.path.join(root, filename)
try:
self.logger.info("Transferring file: "+filename)
self.insert_csv(file_path, filename)
except Exception as e:
self.manage_exception(e)
else:
os.remove(file)
self.logger.info(
'File {} successfully removed'.format(file_path))
except Exception as e:
self.manage_exception(e)
if __name__ == "__main__":
watcher = FolderWatcher(os.path.join('Config', 'config.ini'))
watcher.watch() | {
"domain": "codereview.stackexchange",
"id": 16532,
"tags": "python, mysql, file-system"
} |
Derivation of fraction of time when system has k requests | Question: I was going through Distributed Systems by Maarten van Steen & Andrew S. Tanenbaum. While going through size scalability of systems, I came across this in a note.
I want to know the derivation of this formula. Also, for $\left ( 1 -\frac{\lambda }{\mu} \right )$ to be greater than zero, $\lambda$ should be less than $\mu$. That means system rate of processing requests is faster than request arrival rate, then how come requests would accumulate at any moment? Even if the system starts processing after the first request arrives and meanwhile second request is already being buffered, the system would finish processing the first request before the second request completes arrival. So no request would remain in buffer then.
Answer: It took some time but I finally found how to derive the above equation. This thing requires the knowledge of continuous Markov chains. I learned about them from these two videos which was enough to understand the concept.
Video 1
Video 2
Now the derivation is here on Wikipedia. Basically, our system is an M/M/1 queue and can be modeled as in the following pic.
Each number represents the number of processes in the system. The rate matrix is written as follows.
$$
Q =
\begin{pmatrix}
-\lambda & \lambda & & & & \\
\mu & -(\mu+\lambda) & \lambda & & & \\
& \mu & -(\mu+\lambda) & \lambda & & \\
& & \mu & -(\mu+\lambda) & \lambda & \\
& & & & \ddots &
\end{pmatrix}
$$
In steady state ($Q \pi = 0$, where $\pi$ is just the probability distribution $P_{0}, P_{1}, P_{2}, \ldots$), the equations are
$$
\begin{eqnarray*}
\mu P_{1} &=& \lambda P_{0} \\
\lambda P_{0} + \mu P_{2} &=& (\lambda + \mu) P_{1} \\
\lambda P_{n-1} + \mu P_{n+1} &=& (\lambda + \mu) P_{n}
\end{eqnarray*}
$$
which gives
$$
P_{n} = \frac{\lambda}{\mu} P_{n-1},\quad\text{$n=1,2,...$}
$$
and the fact that system is going to be in any one of the following states at any moment of time leads to
$$
P_{0} + P_{1} + P_{2} + \ldots = 1
$$
So, finally we have
$$
P_{n} = \rho^{n}(1-\rho)
$$
where $\rho = \cfrac{\lambda}{\mu}$ in steady state. | {
"domain": "cs.stackexchange",
"id": 20515,
"tags": "distributed-systems"
} |
What is the theoretical reason for the dependence of the surface tension on the alcohol concentration in water? | Question:
The qualitative sketches I, II and III given
below show the variation of surface tension
with molar concentration of three different
aqueous solutions of$ \ce{ KCl, CH_3 (OH) }$and
$ \ce{CH3(CH2)_{11} O SO_3^{-} Na^+}$
at room temperature
What is the correct assignment(s) of sketches?
It is understandable that $ \ce{CH3(CH2)_{11} O SO_3^{-} Na^+}$ will have a sharp reduction surface tension with concentration (reference) and $\ce{KCl}$ increases surface tension with concentration since it is an inorganic salt. Through option elimination, we conclude that I must be methanol but would there be an independent way to conclude the same (without option elimination)?
I found this but the answers are not really authoritative.
Answer: Curve I could be that of a detergent, but sodium dodecyl sufate decreases the tension faster than methanol and displays a very distinct change in behavior with onset of micellization at the critical micelle concentration. Above that concentration the amount of free solute - the concentration of which is accountable for the change in surface tension - remains approximately constant.
Methanol on the other hand is not a detergent and does not micellize. It does however reduce the surface tension of water, presumably because it disrupts the hydrogen bonding network in water. The boiling point of water is similarly decreased by addition of methanol.
Note that a similar decrease is observed for ethanol solutions, but that in some regards the ethanol-water system is more complicated (forming for instance an azeotrope).
Beyond this it is not possible to generalize, as hydrogen bonding renders water a very complicated liquid. There are something called structure forming (kosmotropic) and structure destroying (chaotropic) solutes. The ions dissociating when $\ce{KCl}$ dissolves jointly appear to have a net kosmotropic effect, but you'd have to distinguish this from the boiling point elevation expected on statistical grounds (Raoult's law). For any non-associating (eg associating by H-bonding) liquid adding a solute is expected to raise the boiling point. But in the case of water the effect of adding a solute might be that you enhance H-bonding. So it can be an effect beyond the statistical one. | {
"domain": "chemistry.stackexchange",
"id": 15939,
"tags": "physical-chemistry, surface-chemistry, surfactants"
} |
How does the immune system "learn" from a vaccine? | Question: According to Wikipedia:
A vaccine typically contains an agent that resembles a disease-causing
microorganism, and is often made from weakened or killed forms of the
microbe, its toxins or one of its surface proteins. The agent
stimulates the body's immune system to recognize the agent as foreign,
destroy it, and "remember" it, so that the immune system can more
easily recognize and destroy any of these microorganisms that it later
encounters.
Question: How does the immune system ""remember"" a foreign agent introduced via a vaccine? And how does it learn how to deal with subsequent encounters?
Answer: Vaccines work by introducing an attenuated strain of the pathogen (or alternatively the antigens that are normally present on the pathogens surface) into the body, whereupon the body mounts an immune response. As this will (hopefully) be the first time that the body has encountered the antigens on the pseudo-pathogen's surface, the response is called the primary response.
This consists of two main divisions: the cell mediated pathway and the humoral pathway. In vaccination it is the humoral pathway that is important. This is where a division of white blood cells (B-Cells) produce antibodies that are complementary to the antigens on the pathogen surface, causing a negative effect to the pathogen (death, inability to reproduce, de-activation of toxins, etc.). However as each B-Cell produces a different antibody, there needs to be a mechanism to select the correct one:
Antigen Presentation (technically part of the cell-mediated-response) - a phagocyte engulfs the pathogen and displays the pathogenic antigens on its own surface.
Clonal Selection - B-Cells that are attracted to the invasion site attempt to bind their antibodies onto the pathogen's antigens. It takes time for this to occur successfully as you are essentially waiting for the correct mutation to happen.
Clonal Expansion - Once a complementary antibody producing B-Cell has been found it is then activated with the help of a T-Helper cell. This causes it to divide rapidly whereupon these cloned specific B cells can secrete their antibodies which will cause detriment to the pathogen.
It's at this point that I can start to answer your specific question. The large clone of B cells will then sub-divide into two types. Plasma Cells remain in the blood and produce antibodies to fight the infection. The other type, much smaller in proportion, are called Memory Cells. These cells have a very long lifetime and move to lymph nodes across the body (including the spleen), where they remain dormant until the same pathogen is found again.
When this is the case, the memory cells are activated by T-helpers so that they can divide into massive numbers of plasma cells to fight the infection the second time. This secondary response is a much faster as the clonal selection stage does not have to wait for the right mutation - they are already waiting in the lymph nodes. The response is also much stronger as each memory cell can produce large numbers of plasma cells - i.e. you can start with multiple activated B-cells (as many as you have memory cells) rather than just the one that has mutated into a complementary shape in the primary immune response.
The aim of the vaccine is for the secondary response to be so quick that potentially life threatening symptoms do not occur; the body has time to find and store the correct antigen in a safe environment as the pathogen has been deactivated. | {
"domain": "biology.stackexchange",
"id": 5102,
"tags": "immunology, epidemiology, vaccination"
} |
Does a photon honor the causality principle? | Question: We know that the faster you move, the slower your time is perceived from an external observer and the space along the direction of the movement shrinks.
Photons, having no mass, move at the speed of light c (in the vacuum) and for them the space has no meaning because it's collapsed into one single point (edit: better say into a single plane, because only the direction along the path collapses). Actually, they don't "move", just "are" at the same time in all places along their path.
In the same way, for them time has no sense. Because they don't "move" they take 0 time to reach their destination.
This seems to be odds we the causality principle, but of course I'm wrong.
I try to explain it with a simple example. Let say a photon is emitted from a very far star millions of years ago and I receive it in my eye now. It means its path was started on that star and ended in my retina.
It took millions of years, for us, and 0 seconds from its point of view.
So, I apologize for the stupid question, but how it was able to "know" that my retina will be there? If I was few cm apart, perhaps it would have continued for other million of years until it will eventually reach something other. But for it, the time is still 0.
How this could be explained?
And, we know the speed of light is less than c in other media. But it's not clear to me if from the point of view of a photon changes something. For it, the space and time are still 0? As an external observer I can say it still moves as fast as it can. From its point of view it's always in all points of its path.
Is it correct?
Answer: Instead of saying "space has no meaning because it's collapsed into one single point" it's a lot easier if you say that a photon is not at rest in any frame. Then all of the paradoxes you mention go away.
It's easy to use the Lorentz transformations (the mathematical core of special relativity) to show that it's impossible to transform a frame moving at $v<c$ to $c$, or vice versa. (Actually, the Lorentz transformations were developed / discovered a decade or so before Einstein proposed the theory of special relativity. His great insight was to realise that those transformations made more sense if you abolish the hypothesis of the luminiferous aether, and treat space and time as a united geometric structure).
In relativity theory, it simply doesn't make sense to talk about "the point of view of a photon". A photon doesn't have a point of view because it's not geometrically possible for an inertial reference frame to have a velocity of $c$ relative to any other inertial reference frame.
The geometrical structure of spacetime proposed by relativity theory has important implications for causality because no causal influence can travel faster than $c$. Two key concepts here are light cones, and the relativity of simultaneity. There are plenty of questions on this topic on the Physics stack, so I won't go into the details here, but very briefly, if a photon leaves spacetime event A and is absorbed at spacetime event B, then all observers will agree that A occurred before B, although different observers may measure different spatial distances between A & B and different time durations between A & B, but they will all agree that the (local) speed of the photon was $c$. We say that the spacetime interval between A & B is light-like (or null).
If spacetime events A & B have greater space separation than time separation, eg in my frame, B happens 1 second after A, but the distance between them is 2 light-seconds, then we say that the spacetime interval between them is space-like. No causal influence can travel between them, and different observers will disagree on whether A happened before B, or vice versa, and for some observers A & B occur simultaneously. Here's a nice diagram from the Wikipedia article on the relativity of simultaneity:
Events A, B, and C occur in different order depending on the motion of the observer. The white line represents a plane of simultaneity being moved from the past to the future. | {
"domain": "astronomy.stackexchange",
"id": 4157,
"tags": "photons"
} |
Symbolic Execution is a case of Abstract Interpretation? | Question: This is written in the wiki entry of Symbolic Execution, but I can't find any reference for it. Can anyone show me a pointer? Thank you.
Answer: I am not aware of a paper concerned with the comparison between symbolic execution and abstract interpretation. Nor do I think one is needed. Reading the original descriptions of these two techniques should be enough.
King, Symbolic Execution and Program Testing, 1976
Cousot, Cousot, Abstract Interpretation: a Unified Lattice Model for Static Analysis of Programs by Construction of Approximation of Fixpoints, 1977
(Conversely, if there would be some unexpected connection, then that would be worth describing. But I very much doubt this is the case.)
The main idea of symbolic execution is that, at an arbitrary point in execution, you can express the values of all variables as functions of the initial values. The main idea of abstract interpretation is that you can systematically explore all executions of a program by a series of over-approximations. (I can hear several AI enthusiasts groaning at the previous approximation.)
Thus, at least in the original formulation, symbolic execution was not concerned with exploring all possible executions. You can see this even in the title: it includes the word ‘testing’. But here's more from Section 8: "For programs with infinite execution trees, the symbolic testing cannot be exhaustive and no absolute proof of correctness can be established."
In contrast, abstract interpretation aims to explore all executions. To do so, it uses several ingredients, one of which is very similar to the main idea of symbolic execution. These ingredients are (1) abstract states, (2) joining and widening (hence, ‘lattice’ in the title).
Abstract states. The concrete state of a program at a particular point in time is basically a snapshot of the memory content (including the program code itself and the program counter). This has a lot of detail, which is hard to track. When you analyze a particular property, you may want to ignore large parts of the concrete state. Or you may want to care only whether a particular variable is negative, zero, or positive, but not care about its exact value. In general, you want to consider an abstract version of the concrete state. For this to work out, you must have a commutativity property: If you take a concrete state, execute a statement, and then abstract the resulting state, you should obtain the same result as if you abstract the initial state, and then execute the same statement but on the abstract state. This commutativity diagram appears in both papers. This is the common idea. Again, abstract interpretation is more general, for it does not dictate how to abstract a state -- it just says there should be a way to do it. In contrast, symbolic execution says that you use (symbolic) expressions that mention the initial values.
Joining and Widening. If program execution reaches a certain statement in two different ways, symbolic execution does not try to merge the two analyzes. That is why the quote above talks about execution trees, rather than dags. But, remember that abstract interpretation wants to cover all executions. Thus, it asks for a way to merge the analyses of two executions at the point where they have the same program counter. (The join could be very dumb ({a} join {b} = {a,b}) such that it amounts to what symbolic execution does.) In general, joining itself is not sufficient to guarantee that you'll eventually finish analyzing all executions. (In particular, the dumb join mentioned earlier won't work.) Consider a program with a loops: "n=input(); for i in range(n): dostuff()". How many times should you go around the loop and keep joining? No fixed answer works. Thus, something else is needed, and that is widening, which can be seen as a heuristic. Suppose you went around the loop 3 times and you learned that "i=0 or i=1 or i=2". Then you say: hmmm, ... let's widen, and you get "i>=0". Again abstract interpretation does not say how to do widening -- it just says what properties widening should have to work out.
(Sorry for this long answer: I really didn't have time to make it shorter.) | {
"domain": "cstheory.stackexchange",
"id": 4623,
"tags": "reference-request, lo.logic, program-analysis"
} |
Simple code that checks if you're old enough to drive | Question: I made this small system that checks if you're old enough to drive. I'm new to C#, but I do know most of the basics since I also know Java. I'm trying to make my code more efficient. Any suggestions or help would be appreciated.
using System;
using System.Threading;
class EfficientCode
{
static int age = 0;
static void Main(string[] args)
{
Console.WriteLine("This is just a simple project that takes simple and small information from you and uses it to process the information and checks whether you're allowed to drive or not. It also tells you how long is left till you drive.");
Thread.Sleep(8000); // adds a 8 second delay so that the user could first read the introduction
Start(); // after the 8 second delay it starts the system
}
static void Start()
{
Console.WriteLine("Enter your first name");
String firstName = Console.ReadLine();
Console.WriteLine("Enter your middle name");
String middleName = Console.ReadLine();
Console.WriteLine("Enter your last name");
String lastName = Console.ReadLine();
Console.WriteLine("Enter your age");
try
{
age = Convert.ToInt32(Console.ReadLine());
}
catch
{
Console.WriteLine("ERROR: Input AGE must be a number!");
Console.WriteLine("Reinitializing questions.");
Thread.Sleep(3000); // this adds a delay of 3 seconds
Start(); // restarts the questions
}
if (ConfirmInformation(firstName, middleName, lastName, age))
{
if (age >= 18)
{
Console.WriteLine("Congratulations! You're already old enough to drive.");
Environment.Exit(0); // Ends the system
}
else if (age == 17)
{
Console.WriteLine("You're almost there! You can get a learners permit.\nYou have 1 more year left to get an official drivers license!");
Environment.Exit(0); // Ends the system
}
else
{
Console.WriteLine("You'll get there. You're not old enough to have a license.");
int yearsLeft = 18 - age; // gets the years left to drive
Console.WriteLine("You still have " + yearsLeft + " years left to get a license.");
Environment.Exit(0); // Ends the system
}
}
else
{
Console.WriteLine("Reinitializing questions.");
Thread.Sleep(3000); // this adds a delay of 3 seconds
Start(); // restarts the questions
}
}
static bool ConfirmInformation(String firstName, String middleName, String lastName, int age)
{
Console.WriteLine("======================================");
Console.WriteLine("INFORMATION CHECK:");
Console.WriteLine("");
Console.WriteLine("FIRST NAME: " + firstName);
Console.WriteLine("MIDDLE NAME: " + middleName);
Console.WriteLine("LAST NAME: " + lastName);
Console.WriteLine("AGE: " + age);
Console.WriteLine("");
Console.WriteLine("Are all those information correct? (Y/N)");
Console.WriteLine("======================================");
String booleanInput = Console.ReadLine();
if (booleanInput.Equals("yes", StringComparison.OrdinalIgnoreCase) || booleanInput.Equals("y", StringComparison.OrdinalIgnoreCase))
{
return true;
}
else if (booleanInput.Equals("no", StringComparison.OrdinalIgnoreCase) || booleanInput.Equals("n", StringComparison.OrdinalIgnoreCase))
{
return false;
}
else
{
Console.WriteLine("ERROR: Input must be either YES or NO.");
return false;
}
return false;
}
}
Answer:
class EfficientCode could be improved by naming the class by the purpose of the code. Otherwise your naming is good.
static int age = 0; should be a local variable in Start()
Thread.Sleep(8000); // adds a 8 second delay so that the user could first read the introduction shouldn't be needed because you aren't clearing the Console hence the user could still read it.
Instead of try..catch you could take advantage of the int.TryParse() method which returns a bool indicating the success of "converting" the string to an int. If you would use int.TryParse like below you could omit the restarting in case of an error. If the call succeeds age holds the integer.
while(!int.TryParse(Console.ReadLine(), out age))
{
Console.WriteLine("ERROR: The entered AGE must be a number!");
Console.WriteLine("Enter your age");
}
ConfirmInformation() is doing a little bit to much. You should split it into 2 methods. One composing the output and one printing the output and asking for confirmation.
private static string ComposeOutput(String firstName, String middleName, String lastName, int age)
{
StringBuilder sb = new StringBuilder(100);
sb.AppendLine("======================================")
.AppendLine("INFORMATION CHECK:")
.AppendLine()
.AppendLine($"FIRST NAME: {firstName}")
.AppendLine($"MIDDLE NAME: {middleName}")
.AppendLine($"LAST NAME: {lastName}")
.AppendLine($"AGE: {age}")
.AppendLine()
.AppendLine("Are all those information correct? (Y/N)")
.AppendLine("======================================");
return sb.ToString();
}
This method uses the StringBuilder class. The AppendLine() method is returning the StringBuilder itself hence we can use the method calls fluently. It uses $-string interpolation as well.
The former ConfirmInformation() method could then look like so
private static bool ConfirmInformation(string information)
{
Console.Write(output);
while (true)
{
string input = Console.ReadLine().ToLowerInvariant();
if (input == "y" || input == "yes")
{
return true;
}
if (input == "n" || input == "no")
{
return false;
}
Console.WriteLine("ERROR: Input must be either YES or NO.");
Console.WriteLine();
Console.Write(output);
}
}
I have made a while(true) loop here because your user wouldn't want to restart the whole process if they made a mistake.
As a sidenode, the variable String booleanInput = Console.ReadLine(); is misleading. If Sam the maintainer would read this method the purpose of that variable wouldn't be seen at first glance. | {
"domain": "codereview.stackexchange",
"id": 36334,
"tags": "c#"
} |
Getting "maps" to a remote location with hector_mapping | Question:
We are working on generating maps to a remote command center. Our first premise was to have ROS running on multiple machines, with the sensors running on the robot and connecting to a roscore running on the remote PC. We almost have this working, but now realize this approach breaks if there are radio dropout zones (the roscore disconnects and the map breaks during the outage).
Next is to consider having the map generated at the robot (hector_slam running on the robot rather than the PC), but the map still needs to get transmitted back to the PC (and in real time if possible).
What does it take to get the maps transmitted to a remote location?
Originally posted by TJump on ROS Answers with karma: 160 on 2013-06-06
Post score: 0
Answer:
We just use plain ROS communication. Master runs on robot, operator station connects to robot's master and we just start the necessary GUI nodes. Example screencast of that here. That of course means we stream the full uncompressed nav_msgs/OccupancyGrid message over the wire, which is pretty wasteful.
Using appropriate compression the size of those could be reduced significantly. There is some discussion of this here. The compressed visualization transport for maps can be found here: http://code.google.com/p/rosjava/source/browse/?repo=android&r=5abc45517c0915ca8cf378cba7512dc12016888b#hg%2Fcompressed_visualization_transport
From our testing it turns out that bz2 compression is even better (and more general) than png, so we will likely use that in the future.
Some tools for doing that are available here. I won't be able to give any support in the next 3 weeks though, with VRC and RoboCup coming up :)
Originally posted by Stefan Kohlbrecher with karma: 24361 on 2013-06-06
This answer was ACCEPTED on the original site
Post score: 2
Original comments
Comment by TJump on 2013-06-06:
Thanks Stefan. This looks like our next step to try. Hopefully we can get this part working before RoboCup. | {
"domain": "robotics.stackexchange",
"id": 14443,
"tags": "ros, navigation, mapping, multiplemachines, hector-mapping"
} |
Can I see Uranus and Neptune with a household telescope? | Question: Can I see Uranus and Neptune with an iOptron telescope with a 600mm focal length. If so, can I expect to see them in colour, or simply as white objects?
Answer: Yes, you can.
I use a Newtonian reflector, 200mm objective, 1000mm focal length.
Uranus is sometimes right on the fringe of naked eye but looks a lot clearer as a small but recognisable blueish disc.
Neptune, sadly, just looks like a star to me ... but you can find it. | {
"domain": "astronomy.stackexchange",
"id": 2422,
"tags": "amateur-observing"
} |
rospy logging configuration file | Question:
The logging overview page for rospy (http://www.ros.org/wiki/rospy/Overview/Logging) mentions that as of Diamondback, logging is configured using a file in the fileConfig format.
Is there an example of how to set this up?
Also, do there exist handlers that publish to rosout, and can those be configured from the file as well?
Originally posted by bhaskara on ROS Answers with karma: 1479 on 2011-06-18
Post score: 2
Answer:
http://docs.python.org/library/configparser.html
http://docs.python.org/library/logging.config.html
You cannot configure rosout via the rospy logging format.
In the future, I hope to use a non-logging-module-based solution for rospy, as it is difficult to manipulate.
Originally posted by kwc with karma: 12244 on 2011-09-02
This answer was ACCEPTED on the original site
Post score: 0 | {
"domain": "robotics.stackexchange",
"id": 5879,
"tags": "ros, rosout, rospy, logging"
} |
Automaton for telling whether a binary number is a multiple of 3 | Question: I am designing an automaton which determines whether a binary number is divisible by 3:
$$ \{x \in \{0, 1\}^* \mid \text{$x$ represents a multiple of three in binary} \} $$
0
1
0F
0
1
1
2
0
2
1
2
This is the transition state diagram of the automaton, whose states are $0,1,2$; the states are drawn from left to right.
But here the automaton reads the input from left to right.
So at first I didn't think about the order (left to right or right to left); I tried to design an automaton which reads the binary from right to left but after much time I couldn't design any automaton which reads the binary right to left and tells whether it is divisible by 3.
Can someone help me out to design such an automaton, or is it possible to design an automaton which reads from right to left and can tell whether its input is divisible by 3?
Answer: When you read a number $b_0 \ldots b_{n-1}$ from the LSB to the MSB, its remainder modulo 3 is
\begin{align}
&b_0 + 2b_1 + 4b_2 + 8b_3 + 16b_4 + 32b_5 + \cdots \bmod 3 \\ = \,
&b_0 - b_1 + b_2 - b_3 + b_4 - b_5 + \cdots
\end{align}
In other words, when reading bits with even indices, the remainder modulo 3 increases by the bit read; and when reading bits with odd indices, the remainder modulo 3 decreases by the bit read.
To implement this using a DFA, you need to keep track both of the remainder modulo 3 and of the parity of the index of the current bit. In total, you will need 6 states, 2 of which will be accepting.
As Hendrik Jan mentions in the comments, in order to know whether the number is divisible by 3, we don't actually have to maintain the remainder modulo 3. Instead, we could compute the remainder of $(-1)^{|x|-1}x$, where $x$ is the input, since this remainder is zero iff the remainder of $x$ is zero. The advantage is that the new remainder is
$$
(-1)^{n-1} (b_0 - b_1 + \cdots + (-1)^{n-1} b_{n-1}) \bmod 3 =
b_{n-1} - b_{n-2} + \cdots + (-1)^{n-1} b_0 \bmod 3,
$$
which is just the remainder of the reverse of the input. So the DFA actually works whichever way you read the input — LSB to MSB or MSB to LSB.
More generally, the regular languages are closed under reversal. One way to see it is that if you have a DFA for your language, you can convert it to an NFA for the reversed language by changing the direction of the arrows and switching initial and final states; you can then determinize it to produce a DFA, if you so wish. | {
"domain": "cs.stackexchange",
"id": 19581,
"tags": "automata, finite-automata"
} |
human anti-mouse antibody | Question: I have heard about human anti-mouse antibodies (HAMAs) and read that HAMAs neutralize murine antibodies, therefore decreasing the effectiveness of those murine antibodies. Is this true that HAMAs neutralize the murine antibodies? How?
Answer: As mentioned in the comment, all antibodies have constant regions and variable regions. The variable regions are the binding sites on the ends of the two arms, and the constant regions are the rest of the molecule. When humans are injected with murine antibodies, the immune system recognises and sets up an immune response to them, through generation of HAMA. This affects the efficacy of the antibody because it is attacked the same way a pathogenic substance would be. Antibodies have different effects, but the most important one in this instance is through opsonisation (http://en.wikipedia.org/wiki/Opsonin#Examples). Because antibodies have two arms, they can bind multiple targets and cause a grouping and clumping. This also causes activation and phagocytosis through phagocytes (generally macrophages) which will ingest and destroy the therapeutic antibodies.
Antibodies that are mostly human with just mouse variable regions have been created to try and counter this problem, known as chimeric antibodies. Humanised antibodies are also available, which are entirely human with only the very tips of the variable regions (known as the hypervariable regions) are from mice. This reduces the problem as far as possible (http://en.wikipedia.org/wiki/Fusion_protein#Chimeric_protein_drugs). | {
"domain": "biology.stackexchange",
"id": 3134,
"tags": "immunology, antibody, antigen, mouse"
} |
Raman Spectroscopy and Phonon Modes | Question: How can someone use Raman Spectroscopy to obtain information for the phonon modes of a crystal? I am asking for some paper that contains information about Raman Spectroscopy and Phonons from an experimental point of view.
Answer: The photon momentum of visible light is small compared to phonon momentum in crystals so one can only see phonons at $\Delta k=0$.
But now there is the technique of (Resonant) X-ray Raman Scattering with resolution high enough to see phonons and magnons and measure their dispersion curves.
Introduction to High-Resolution Inelastic X-Ray Scattering, Baron (2015) | {
"domain": "physics.stackexchange",
"id": 71535,
"tags": "solid-state-physics, phonons, raman-spectroscopy"
} |
Where to find zero gravity far from a planet? | Question: suppose we have such a planet which nothing is around it(you can say it's alone in the universe) . I want to know where we can find a point that we didn't feel the gravity force of planet. if you have article or formulas about it I appreciate your help.
Answer: By Gauss's law for gravity,
$$
\oint_S \mathbf{g} \cdot \mathrm{d\mathbf{S}} = -4\pi GM$$
You seem to be looking for a point where the net gravitational flux is zero. This would happen only in a surface enclosing no mass!
For example, a shell. Or the example @Hritik has provided, a cavity in a sphere, where at any point in the cavity, the force would be zero. (No mass is enclosed by the cavity) | {
"domain": "physics.stackexchange",
"id": 41581,
"tags": "newtonian-gravity, planets"
} |
Could a strong enough electric field tear a hydrogen atom apart? | Question: A neutral hydrogen atom is composed of a proton and an electron.
The overall charge on the atom is zero but there are local charges within the atom as the negative and positive charge is not evenly distributed.
If a neutral hydrogen atom were placed in an electric field the electron and the proton would experience a force in opposite directions.
Could a strong enough electric field tear the electron and proton apart?
Answer: A hydrogen atom can be "torn apart" by a strong enough electric field. This means that the electron of the hydrogen atom will leave the proton. This phenomenon is called field ionization which is caused by a quantum mechanical tunneling process where no energy needs to be supplied to the electron. Without applied electric field, the electron sits in its lowest energy state in the Coulomb potential well of the positive nucleus. If a homogeneous electric field is superimposed on the $1/r^2$ Coulomb field, a potential barrier forms. When at sufficiently high applied field this barrier becomes very thin, the electron can tunnel through this barrier (tunnel effect) and leave the nucleus for good. | {
"domain": "physics.stackexchange",
"id": 46567,
"tags": "forces, electric-fields, atomic-physics, ionization-energy, ions"
} |
What are some possible reasons that your multiclass classifier is classifying alll the classes in a single class? | Question: I have unbalanced classes.
Group1 N = 140
Group2 N = 35
Group3 N = 30
I ran the code on this data and all the Groups got classified as Group1.
I thought that since group1 is the majority group this is not a surprise.
Then i ran the same code but this time with SMOTE, now all groups are 140, and i still got the same results, where all the groups were classified in Group1. Then i balanced the class weights (W/O SMOTE), but still got the same results. This was confusing to me. What am i doing wrong? Can someone help me understand this please? or what can i do to improve the model?
I tried 5 different classifiers (KNN, AdaBoost, SVC, RF, DT) and in 4 out of 6 i got the same result!
Here's the code:
#Splitting data to training and testing
X_train, X_test, y_train, y_test = train_test_split (X, y, test_size = 0.1, random_state=42)
#Apply StandardScaler for feature scaling
sc = StandardScaler()
X_train_std = sc.fit_transform(X_train)
X_test_std = sc.transform (X_test)
#SMOTE
sm = SMOTE(random_state=42)
X_balanced, y_balanced = sm.fit_sample(X_train_std, y_train)
#PCA
pca = PCA(random_state=42)
#Classifier regularization (SVC).
svc = SVC(random_state=42, class_weight= 'balanced')
pipe_svc = Pipeline(steps=[('pca', pca), ('svc', svc)])
# Parameters of pipelines can be set using ‘__’ separated parameter names:
parameters_svc = [{'pca__n_components': [2, 5, 20, 30, 40, 50, 60, 70, 80, 90, 100, 140, 150]},
{'svc__C':[1, 10, 100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 200, 250, 300, 400, 500],
'svc__kernel':['rbf', 'linear','poly'],
'svc__gamma': [0.05, 0.06, 0.07, 0.08, 0.09, 0.001, 0.002, 0.003, 0.004, 0.005, 0.006, 0.007,
0.008,0.009, 0.0001, 0.0002, 0.0003, 0.0004, 0.0005],
'svc__degree': [1, 2, 3, 4, 5, 6],
'svc__gamma': ['auto', 'scale']}]
clfsvc = GridSearchCV(pipe_svc, param_grid =parameters_svc, iid=False, cv=10,
return_train_score=False)
clfsvc.fit(X_balanced, y_balanced)
# Plot the PCA spectrum (SVC)
pca.fit(X_balanced)
fig1, (ax0, ax1) = plt.subplots(nrows=2, sharex=True, figsize=(6, 6)) #(I added 1 to fig)
ax0.plot(pca.explained_variance_ratio_, linewidth=2)
ax0.set_ylabel('PCA explained variance')
ax0.axvline(clfsvc.best_estimator_.named_steps['pca'].n_components,
linestyle=':', label='n_components chosen')
ax0.legend(prop=dict(size=12))
# For each number of components, find the best classifier results
results_svc = pd.DataFrame(clfsvc.cv_results_) #(Added _svc to all variable def)
components_col_svc = 'param_pca__n_components'
best_clfs_svc = results_svc.groupby(components_col_svc).apply(
lambda g: g.nlargest(1, 'mean_test_score'))
best_clfs_svc.plot(x=components_col_svc, y='mean_test_score', yerr='std_test_score',
legend=False, ax=ax1)
ax1.set_ylabel('Classification accuracy (val)')
ax1.set_xlabel('n_components')
plt.tight_layout()
plt.show()
#Predicting the test set results (SVC)
y_pred1 = clfsvc.predict(X_test)
# Model Accuracy, how often is the classifier correct?
Accuracyscore_svc = accuracy_score(y_test, y_pred1)
print("Accuracy for SVC on CV data: ", Accuracyscore_svc)
# Making the confusion matrix to describe the performance of a classifier
from sklearn.metrics import confusion_matrix
cm1 = confusion_matrix (y_test, y_pred1)
#accuracy
# Get accuracy score
accuracy1 = accuracy_score(y_test, y_pred1)
print('Accuracy1: %.2f%%' % (accuracy1 * 100.0))
#Checking shape after confusion matrix
print (X_test)
print (y_pred1)
print (cm1)
Answer: I found the reason finally. I was using the unstandardized X_test.
Thanks.
Edit:
previously i defined the y_pred like so;
y_pred = clf.predict (xtest)
and then constructed the confusion matrix like so;
cm = confusion_matrix (y_test, y_pred)
However, i forgot that i previously changed xtest using standard scalar like so;
x_test_std = sc.transform (xtest)
and that the new x_test that should be used is xtest_std not x_test.
When i realized this and used the proper x_test_std, everything worked and made much more sense. | {
"domain": "datascience.stackexchange",
"id": 4778,
"tags": "machine-learning, classification, machine-learning-model, multilabel-classification, class-imbalance"
} |
Number of spatial arrangements of tetrasubstituted biphenyl | Question:
According to my book 2-bromo-2'-(1-chloroethyl)-6'-iodo-6-(prop-1-en-1-yl)-1,1'-biphenyl has eight possible spatial arrangements. How can this be so? I can think of only four – left two groups being planar with right two groups up-down and down-up, and vice versa.
For this configuration of I and $\ce{CHClCH3}$ I can think of four, for I and $\ce{CHClCH3}$ interchanged I can think of four more, but that is not the same molecule and is just a configurational isomer.
Answer: There are three independent stereogenic centers or elements in this molecule,
chiral carbon atom of the chloroethyl group,
double bond of the propenyl group,
axis of the substituted biphenyl with bulky substituents at 2,2′,6,6′ positions.
Each of them has two configurations. It means that the total number of stereoisomers is 23 = 8. (No one of them is symmetrical and cannot be superimposed with its mirror image, no one can be superimposed with any other one.)
(1M)-2-bromo-2′-[(1R)-1-chloroethyl]-6′-iodo-6-[(1Z)-prop-1-en-1-yl]-1,1′-biphenyl
(1M)-2-bromo-2′-[(1S)-1-chloroethyl]-6′-iodo-6-[(1Z)-prop-1-en-1-yl]-1,1′-biphenyl
(1M)-2-bromo-2′-[(1R)-1-chloroethyl]-6′-iodo-6-[(1E)-prop-1-en-1-yl]-1,1′-biphenyl
(1M)-2-bromo-2′-[(1S)-1-chloroethyl]-6′-iodo-6-[(1E)-prop-1-en-1-yl]-1,1′-biphenyl
(1P)-2-bromo-2′-[(1R)-1-chloroethyl]-6′-iodo-6-[(1Z)-prop-1-en-1-yl]-1,1′-biphenyl
(1P)-2-bromo-2′-[(1S)-1-chloroethyl]-6′-iodo-6-[(1Z)-prop-1-en-1-yl]-1,1′-biphenyl
(1P)-2-bromo-2′-[(1R)-1-chloroethyl]-6′-iodo-6-[(1E)-prop-1-en-1-yl]-1,1′-biphenyl
(1P)-2-bromo-2′-[(1S)-1-chloroethyl]-6′-iodo-6-[(1E)-prop-1-en-1-yl]-1,1′-biphenyl | {
"domain": "chemistry.stackexchange",
"id": 10686,
"tags": "organic-chemistry, stereochemistry, isomers"
} |
(Beginner) Mastermind game in Python | Question: After completing an introduction to Python tutorial, I wanted to put my basic knowledge of control flow and data structures to use, and felt this was a great choice for my first program.
I created the below to run in Jupyter Notebook / Visual Studio Code terminal. It behaves like an over-the-board version, based on colours and pins.
Without experience of how to structure code I found myself putting everything into functions and used functions within functions, rightly or wrongly, leaving only a small amount of what I've called 'main game code'. Feedback on how I should structure properly, or resources to that effect would be greatly appreciated.
I used no guides nor copied online code, so the code is a bit bloated, I imagine, as a first attempt. I've tried to make it a bit more user friendly running in the terminal so there are a lot of input validations and line spaces as I wanted to actually play this with my housemate and it not be a horrible experience.
Summary of the rules
2 players, playing at least 2 games, each getting a chance to be the codemaker and codebreaker.
Two game modes: Beginner or Mastermind. The latter allows the codemaker to use colours more than once.
Three difficulty settings: Easy, Medium or Hard. The difficulty determines the number of guesses the codebreaker gets.
Points earned, and tallied across all games, by the player acting as codemaker for each guess the codebreaker makes, with a bonus point if the codebreaker fails entirely.
def getPlayers():
player1 = input("Player 1, you will start as the Codemaker. What is your name? ")
print("Player 1 is",player1,"and will start as the Codemaker")
print()
player2 = input("Player 2, you will start as the Codebreaker. What is your name? ")
print("Player 2 is",player2,"and will start as the Codebreaker")
return player1, player2
def checkUserInput(userInput):
try:
int(userInput)
return int
except (ValueError, TypeError):
try:
float(userInput)
return float
except (ValueError, TypeError):
return str
def getNumberOfGames():
while True:
numGames = input("How many games do you want to play? Min 2, Max 8. Remember, an even number of games must be played!")
userInputType = checkUserInput(numGames)
if userInputType == int:
if int(numGames) in range(2,9,2):
print()
print("You will be playing",numGames,"games")
print("----")
return numGames
break
else:
print("Your entry is incorrect, please try again")
def getMode():
D = {"B":"Beginner","M":"Mastermind"}
D2 = {"B":"the Codemaker cannot use the same colour more than once","M":"the Codemaker can use colours more than once"}
print("----")
print("Select game mode: Enter 'B' for Beginner, or, 'M' for Mastermind")
print()
while True:
mode = str.capitalize(input())
if mode in ("B","M"): #alternative way to write if mode == "B" or mode == "M"
print("You have selected",D[mode],"mode! In",D[mode],"mode",D2[mode])
print("----")
break
else:
print(mode,"is not a valid game mode, please select a game mode")
print()
return mode
def getDifficulty():
D = {"E":"Easy","M":"Medium","H":"Hard"}
D2 = {"E":12,"M":10,"H":8}
print("Select game mode: Enter 'E', 'M' or 'H' for Easy, Medium or Hard")
print()
while True:
difficulty = str.capitalize(input())
if difficulty in ("E","M","H"):
print("You have selected",D[difficulty],"difficulty! The Codebreaker will get",D2[difficulty],"chances to crack the code!")
print("----")
break
else:
print(difficulty,"is not a valid option, please select a difficulty")
print()
return difficulty, D2[difficulty]
def duplicateColours(L):
for x in L:
if L.count(x) > 1:
return True
break
else:
pass
return False
def getNewCode(mode):
D = {'W':'White','R':'Red','B':'Blue','Y':'Yellow','P':'Purple','O':'Orange','G':'Green','S':'Silver'}
L = []
print("Quickly, Codemaker! Enter a new 4 colour code to stop the Codebreaker from breaking into the vault!")
print("""
Select from the 8 available colours by typing the first letter of the colour:
White -- Enter 'W'
Red -- Enter 'R'
Blue -- Enter 'B'
Yellow -- Enter 'Y'
Purple -- Enter 'P'
Orange -- Enter 'O'
Green -- Enter 'G'
Silver -- Enter 'S'
"""
)
for cbsi in range (1,5):
while True:
print('Enter colour',cbsi)
inputColour = str.capitalize(input())
if D.get(inputColour) is None:
print("Codemaker, colour,'",inputColour,"'is not available, please select colour",cbsi,"again")
print()
else:
L.append(inputColour)
if mode == "B":
if duplicateColours(L) == True:
L.pop(len(L)-1)
print("Duplicate colours are not allowed in Beginner mode!")
print(L)
continue
print('Colour',cbsi,'is',inputColour)
print(L)
print()
break
print("Codemaker, your chosen code is",L,"keep it hidden from the Codebreaker!")
print()
print("!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!")
input("Press any key to scramble the screen!")
print("""
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
""")
print("----")
return L
def checkGuess(L, mode):
D = {'W':'White','R':'Red','B':'Blue','Y':'Yellow','P':'Purple','O':'Orange','G':'Green','S':'Silver'}
for x in L:
if D.get(x) is None:
print("Your guess contains colours that aren't available, please try again")
return False
break
else:
if mode == "B":
if duplicateColours(L) == True:
print("Duplicate colours are not allowed in Beginner mode! Please try again")
return False
break
return True
def getGuess(guesses):
L2 = []
while True:
print()
playerGuess = input("Codebreaker, what is your guess? Enter 4 colours using the first letter of the colour as your input, separated by commas: ")
print()
L2 = str.upper(playerGuess).split(",")
if len(L2) != 4:
print("Your guess does not contain 4 colours")
print()
else:
if checkGuess(L2, mode) == True:
print("Guess #",guesses+1)
print(L2)
break
else:
pass
return L2
def guessCheck(L,L2):
D = {'W':'White','R':'Red','B':'Blue','Y':'Yellow','P':'Purple','O':'Orange','G':'Green','S':'Silver'}
Ly = ["*","*","*","*"]
Lt1 = L.copy()
Lt2 = L2.copy()
for y in range(len(L2)):
if L[y] == L2[y]:
Ly[y] = "X"
Lt1[y] = "*"
Lt2[y] = "*"
for y in range(len(L2)):
if D.get(Lt2[y]) is not None:
if Lt1.count(Lt2[y]) != 0:
Ly[y] = "O"
Lt1[Lt1.index(Lt2[y])] = "*"
Lt2[y] = "*"
return Ly
def playGame(guesses, currentPlayer):
print("""
Available colours:
White (W), Red (R), Blue (B), Yellow (Y), Purple (P), Orange (O), Green (G), Silver (S)
""")
codemakerScore = 0
for x in range(guesses):
L2 = getGuess(x)
Ly = guessCheck(L,L2)
print(Ly," Help: 'X' = correct colour and order, 'O' = correct colour, wrong order, '*' = incorrect guess")
codemakerScore += 1
if L2 == L:
print()
print("!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+")
print("Congratulations, Codebreaker! You cracked the code")
print("!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+")
print()
break
if x == int(guesses)-1:
print("Codebreaker... You failed to crack the code. The Codemaker was granted a bonus point")
codemakerScore += 1
print("The Codemaker",currentPlayer,"gained",codemakerScore,"points this round")
print()
return codemakerScore
def getCurrentPlayer(player1,player2,numberOfGames):
if int(numberOfGames) %2 ==0:
currentPlayer = player1
else:
currentPlayer = player2
return currentPlayer
def updatePlayerScores(currentPlayer,codemakerScore,player1Score,player2Score):
if currentPlayer == player1:
player1Score += codemakerScore
else:
player2Score += codemakerScore
return player1Score,player2Score
def getWinner(player1Score, player2Score):
if player1Score > player2Score:
return player1
if player1Score == player2Score:
return "Draw"
else:
return player2
#Main game code********************************************
player1, player2 = getPlayers()
mode = getMode()
difficulty, guesses = getDifficulty()
numberOfGames = getNumberOfGames()
player1Score = 0
player2Score = 0
for x in range(len(numberOfGames)+1):
print()
currentPlayer = getCurrentPlayer(player1,player2,x)
print()
print(currentPlayer,"is the Codemaker")
print()
L = getNewCode(mode)
print()
print("Current scores are: ",player1,"=",player1Score," / ",player2,"=",player2Score)
codemakerScore = playGame(guesses,currentPlayer)
player1Score, player2Score = updatePlayerScores(currentPlayer,codemakerScore,player1Score,player2Score)
print("Current scores are: ",player1,"=",player1Score," / ",player2,"=",player2Score)
input("Press any key to continue")
winner = getWinner(player1Score,player2Score)
print()
print("After",numberOfGames,"games, the winner is: ",winner,"!")
print()
print("The final scores were ",player1,"=",player1Score," / ",player2,"=",player2Score)
Answer: It's a pretty good piece of code for someone just beginning, good job.
There are a couple of things, as always, that could be improved :
Making a better use of Python's functionalities
Languages all have some special functionalities that make the code easier to write/read. It's good to know these because well... they're there to be used.
1 ) String templating : Instead of writing print("Player 1 is",player1,"and will start as the Codemaker") you should write print(f"Player 1 is {player1} and will start as the Codemaker"). This is valid for all the cases where you mix strings with code.
2 ) Using tuples : So, for me it was a big thing when I started Python because I came from C# where tuples were... less powerful. There are some places where you have two dictionaries with the same keys, for example :
def getDifficulty():
D = {"E":"Easy","M":"Medium","H":"Hard"}
D2 = {"E":12,"M":10,"H":8}
print("Select game mode: Enter 'E', 'M' or 'H' for Easy, Medium or Hard")
print()
while True:
difficulty = str.capitalize(input())
if difficulty in ("E","M","H"):
print("You have selected",D[difficulty],"difficulty! The Codebreaker will get",D2[difficulty],"chances to crack the code!")
print("----")
break
else:
print(difficulty,"is not a valid option, please select a difficulty")
print()
return difficulty, D2[difficulty]
I think I would write it this way :
def getDifficulty():
possible_difficulties = {"E":("Easy", 12),"M":("Medium", 10),"H":("Hard", 8)}
print("Select game mode: Enter 'E', 'M' or 'H' for Easy, Medium or Hard\n")
while True:
difficulty_input = str(input()).upper()
if difficulty_input not in possible_difficulties.keys():
print(f"{difficulty_input } is not a valid option, please select a valid difficulty\n")
continue
chosen_difficulty = possible_difficulties[difficulty_input]
print(f"You have selected {chosen_difficulty[0]} difficulty! The Codebreaker will get {chosen_difficulty[1]} chances to crack the code!")
return chosen_difficulty
There are a couple things to unpack here:
1 ) I took some liberties with the variable names. Using single letters as variable names is almost always a bad idea.
2 ) I fused the two dictionaries by having a tuple value that contains the text and the number of chances. You could even use a named tuple instead of a plain tuple to really explain what is the purpose of the two values.
3 ) I removed some nesting. It's been proven (I believe) that nesting code inside loops and conditions reduces the code clarity. So I chose to first check if the input is invalid, if so, I use the continue keyword to return to the start of the loop. It's a personal preference to check for invalid input, but you could also check for a valid input and return the chosen difficulty :
def getDifficulty():
possible_difficulties = {"E":("Easy", 12),"M":("Medium", 10),"H":("Hard", 8)}
print("Select game mode: Enter 'E', 'M' or 'H' for Easy, Medium or Hard\n")
while True:
difficulty_input = str(input()).upper()
if difficulty_input in possible_difficulties.keys():
chosen_difficulty = possible_difficulties[difficulty_input]
print(f"You have selected {chosen_difficulty[0]} difficulty! The Codebreaker will get {chosen_difficulty[1]} chances to crack the code!")
return chosen_difficulty
print(f"{difficulty_input } is not a valid option, please select a valid difficulty\n")
I don't have time to make a longer review, but I have one last point, don't do this :
print("""
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
""")
I have to scroll like 4 or 5 mouse wheels to see the end of it and code should almost always be readable above all. If you want to print this, you should replace it with the following : print("*"*3000) or however long you want it to be. | {
"domain": "codereview.stackexchange",
"id": 42838,
"tags": "python, beginner, game"
} |
IUPAC rules on omission of locants in carboxylic acid | Question: I have been lately in debate with my teacher as to why did the IUPAC name the compound with the current official IUPAC name of 2-methylpropanoic acid. (CN: isobutyric acid)
My argument is that:
You can't attach a methyl in carbon 1 (because the bonds in carbon 1 will exceed 4)
You can't attach a methyl in carbon 3 (because it will become butanoic acid)
Placing the locant in a substituent with no other constitutional isomers will be useless when to be interpreted, will be a few more characters longer, and will be less pleasant for the eyes end ears (I mean, methylpropanoic acid a bit more pleasant to see and hear than 2-methylpropanoic acid, right?)
To verify my initial assumption, is the name of such compound 2-methylpropanoic acid? If it is, then we may proceed to the real question in the next paragraph.
So, where in the 2013 Blue Book or any updated IUPAC nomenclature guidelines with less complicated wordings in organic chemistry books (this has seniority over the former) can I see that you must not omit the locant in these cases (and why).
Additionally, how can I request to the Union to alter this notion to make it methylpropanoic acid because of the stated reasons? (It's a bit like ethan-1-ol and ethanol.)
Answer: According to the current version of Nomenclature of Organic Chemistry – IUPAC Recommendations and Preferred Names 2013 (Blue Book), the preferred IUPAC name is 2-methylpropanoic acid. The trivial name ‘isobutyric acid’ is no longer recommended (see Subsection P-65.1.1.2.4).
Concerning your objection
You can't attach a methyl in carbon 3 (because it will become butanoic acid)
IUPAC nomenclature doesn’t work like that. Generally, the complete information about a structure is explicitly given by the name and does not rely on any implied information or hidden logic involving other structures.
The given parent structure is propanoic acid. It includes two kinds of substitutable hydrogen. Therefore, the locant cannot be omitted in substituted propanoic acid, e.g. 2-chloropropanoic acid or 3-chloropropanoic acid.
This principle applies to any substituent. The special situation that replacing the chloro substituent in 3-chloropropanoic acid with a methyl substituent would actually lead to the name butanoic acid instead of 3-methylpropanoic acid does not change the preferred name for 2-methylpropanoic acid.
Nevertheless, there are a few exceptional cases where locants are omitted, but only when there is no ambiguity. For preferred IUPAC names, the nomenclature rules explicitly stipulate when locants are omitted. Most of these rules apply to the omission of the locant ‘1’. One case is the example given in the question:
(It's a bit like ethan-1-ol and ethanol.)
Homogeneous chains consisting of only two identical atoms such as ethane only have one kind of substitutable hydrogen. Therefore, the current IUPAC recommendations include a rule (in Subsection P-14.3.4.2) that the locant ‘1’ is omitted in monosubstituted ethane; i.e. ethanol (not ethan-1-ol) is the preferred IUPAC name. However, if any locants are essential for defining the structure, then all locants must be cited for the structure, e.g. 2-chloroethan-1-ol (not 2-chloroethanol; see Subsection P-14.3.3).
Coming back to carboxylic acids, acetic acid also has only one kind of substitutable hydrogen, i.e. all substitutable hydrogen atoms have the same locant. Therefore, explicitly according to Subsection P-14.3.4.6, this locant is omitted, e.g. chloroacetic acid (not 2-chloroacetic acid). | {
"domain": "chemistry.stackexchange",
"id": 9403,
"tags": "organic-chemistry, nomenclature"
} |
Why does the current age of the universe increase when dark energy is included? (open universe) | Question: When numerically solving the Friedmann equations for varying cases of an open universe (i.e. $\Omega_0 < 1$) I get the following evolution plots,
where the left plot is for an open universe containing only matter and the right plot is for an open universe containing 30% matter and 70% dark energy. As expected, in the dark energy case, the scale factor exponentially increases with time (accelerated expansion of the universe).
However, when looking at the current age of the universe (the time at which the scale factor $a=1$) it can be seen that for each age in the left plot, the corresponding line in the right plot has a significantly greater age. I would have thought that the inclusion of dark energy would cause the age of the universe to be smaller than the corresponding matter only case due to the negative pressure anti-gravity properties of dark energy pushing everything apart.
If anyone can explain the reason for this, I'd appreciate it.
EDIT:
In both plots the blue lines correspond to $\Omega_o = 0.1$, however the left plot is $\Omega_{m,0}=\Omega_0=0.1$, whereas the right plot is $\Omega_{\Lambda,0}+\Omega_{m,0}=\Omega_0=0.1$ (with $\Omega_{\Lambda,0}=0.07$ and $\Omega_{m,0}=0.03$), where $\Lambda$ and m denoted dark energy and matter respectively.
The time axes aren't very clear, apologies, the left plot axis starts at negative because I've set t=0 as the current age of the universe ($t(a=1)$) to more easily compare the shapes of the plots - I have taken these plots from a paper I've written so they may seem strange out of context.
Answer: If I understood your question correctly, you're asking why a universe with dark energy is older than a corresponding universe without dark energy but with the same matter density and Hubble constant.
The current age of a FRW universe is
$$
t = \int_0^1\frac{\text{d}a}{\dot{a}} = \int_0^1\frac{\text{d}a}{aH(a)},
$$
where, ignoring the radiation density,
$$
H(a) = \frac{\dot{a}}{a} = H_0\sqrt{\Omega_Ma + (1-\Omega_M -\Omega_\Lambda)a^2 + \Omega_\Lambda a^4}.
$$
since
$$
\Omega_\Lambda (a^4 - a^2) \leqslant 0
$$
for $\Omega_\Lambda\geqslant 0$ and $a\leqslant 1$, we get
$$
\begin{align}
H_\text{nde}^2(a) &= H_0^2[\Omega_Ma + (1-\Omega_M)a^2]\\
&\geqslant
H_0^2[\Omega_Ma + (1-\Omega_M -\Omega_\Lambda)a^2 + \Omega_\Lambda a^4]\\
&= H_\text{wde}^2(a)
\end{align}
$$
for $a\leqslant 1$, where '$\text{nde}$' and '$\text{wde}$'' stand for 'no dark energy' and 'with dark energy', respectively. Consequently, $t_\text{nde}\leqslant t_\text{wde}$.
The key point here is that we kept the present-day value $H_0$ constant. By definition $H_\text{nde}(1) = H_\text{wde}(1) = H_0$. But the expansion rate of a universe with dark energy eventually starts to accelerate, which means that $\dot{a}_\text{wde} = aH_\text{wde}$ must increase more rapidly than $\dot{a}_\text{nde} = aH_\text{nde}$ at a given $a$. We can only reconcile these two facts if $\dot{a}_\text{wde} \leqslant \dot{a}_\text{nde}$ for $a\leqslant 1$, and that $\dot{a}_\text{wde}$ is 'catching up' with $\dot{a}_\text{nde}$ until they are equal at $a=1$.
Edit
The reasoning remains the same if you're comparing a universe where $\Omega_M = \Omega_0$ with a universe where $\Omega_M + \Omega_\Lambda = \Omega_0$ for some fixed value of $\Omega_0$. In this case
$$
\Omega_\Lambda (a^4 - a) \leqslant 0
$$
and
$$
\begin{align}
H_\text{nde}^2(a) &= H_0^2[\Omega_0a + (1-\Omega_0)a^2]\\
&\geqslant
H_0^2[(\Omega_0 - \Omega_\Lambda)a + (1-\Omega_0)a^2 + \Omega_\Lambda a^4]\\
&= H_\text{wde}^2(a).
\end{align}
$$ | {
"domain": "physics.stackexchange",
"id": 48720,
"tags": "cosmology, time, space-expansion, dark-energy"
} |
Dynamic Programming for finding shortest alternating paths between all pairs of vertices in a graph | Question: I'm learning Dynamic Programming (By myself) and in the textbook there is this question:
Given two undirected graphs $G_1=(V,E_1)$ and $G_2=(V,E_2)$ over the same set of Vertices $V$ and a weight function $w: E_1 \cup E_2 \rightarrow \mathbb{R}$, let $P = \left\{e_1, e_2, ..., e_n \right\}$ be a path in $(V, E_1 \cup E_2)$.
We sat that P is alternating if for any $1 \leq i < n$ at least one of the following two conditions hold:
$e_i \in E_1, e_{i+1} \in E_2$
$e_i \in E_2, e_{i+1} \in E_1$
Write a DP algorithm that given $G_1, G_2$, returns the weights of the shortest alternating paths between all pairs of vertices in $V$
OK so I sat on this question for a long time but I can't seem to figure out how to do solve it. Since this is a shortest path between all pairs I tried to think of a solution which uses Floyd-Warshall algorithm, but I can't figure out how to factor in the addition of the alternating path.
Every solution I think of fails when inserting special Edge Cases.
Can anyone give a hint as to how to proceed?
Answer: Hint: Try to modify the Floyd–Warshall algorithm to account for edge types. As described in Wikipedia, we construct an array $A[i,j,k]$ which keeps the weight of the shortest path from $i$ to $j$ via the vertices $1,\ldots,k$. Instead, construct an array $A[i,j,k,x,y]$ which keeps the weight of the shortest path from $i$ to $j$ via the vertices $1,\ldots,k$ whose first edge belongs to $G_x$, and whose last edge belongs to $G_y$. | {
"domain": "cs.stackexchange",
"id": 3716,
"tags": "algorithms, dynamic-programming, shortest-path"
} |
android_core publish/subscribe very slow | Question:
Currently I am testing ROS to see if it would be worthwhile to convert some of our Android robotics code over to it. I've run into an issue where running any sort of Publisher/Subscriber as it is far too slow due to either the serialization of the messages or the number of messages being sent (I can't tell which).
Specifically, I am running an OrientationPublisher from android_gingerbread_mr1 and simply setting up a subscriber that takes the Pose and updates a text view on the screen. This slows the phone down so much and takes so many resources that attempting to press a button or anywhere on the screen for that matter, causes Android to kill the application for being unresponsive. I am currently using this phone (spec sheet in link): http://www.phonerated.com/cell-phone.php?phone=samsung+admire
Is there something I am doing wrong, or any suggestions on how to fix my issue?
Originally posted by alexdicarlo on ROS Answers with karma: 1 on 2012-06-05
Post score: 0
Answer:
There's several demos or ROS running on Android. You can see some of them on the ROS blog
Your problems sound more like a bug than performance issues. I suggest that you double check your threading model.
Originally posted by tfoote with karma: 58457 on 2012-06-05
This answer was ACCEPTED on the original site
Post score: 0
Original comments
Comment by damonkohler on 2012-07-02:
It could be both or either. Performance on Android isn't great, but has gotten much better (about an order of magnitude) in the last couple weeks. Expect more improvements to follow. | {
"domain": "robotics.stackexchange",
"id": 9679,
"tags": "ros, android-core, android-gingerbread, rosjava, android"
} |
recombination frequency problem | Question:
Three loci C, D and E are located on the same chromosome in this
order. We found that the frequency of recombinants between C and D is
10% and that between D and E it is 20%. Assuming that crossing over
occurs randomly on the chromosome, what is the expected frequency of
recombinants between C and E?
I know that it should be less than 30% (10%+20%) but the answer given is 26%. I don't understand how they figured that out.
Edit :
The frequency of recombination is <30% because of the chance that a crossover happens between C and D & also between D and E. The probability of that to happen is 2% (10/100 X 20/ 100)
So, why is it 26% instead of 28% ?
Another posssibility : Am I totally off the track ?
Answer: I got $26$% as the answer.
To get a recombination between C and E, there are two possible mechanisms:-
C and D produce a recombinant, but D and E remain linked, therefore the final genotype will be a recombinant considering C and E(Chiasmata between C and D). Here $P_1=P_{CD}\times P'_{DE}$ where $P$ is the probability of recombination and $P'=1-P$ is the probability of linkage.Hence $P_1=0.08$
C and D remain linked but D and E undergo recombination (Chiasmata between D and E). Here, $P_2=P'_{CD}\times P_{DE}=0.18$
If there is a chiasmata between both C and D, and D and E, the resultant will not have a recombination in C and E locus due to double crossing over. If there is no crossing over, there will be no recombination at either loci.
The net probability of recombination $P_{CE}$ will be the sum of these two, as any of these possibilities can occur to give a recombination between C and E. $P_{CE}=P_1+P_2=0.26$
And Biogirllajja, your calculation (the Edit) was almost correct, but you have to subtract $2$% from both $10$% and $20$%, because, both of them include the probability of crossover at one loci, including the case where the other loci has also crossed over. Hence, you need to subtract it from both, and then add to get $26$%. Tell me if you want me to expand on my explanation or provide some clarifications.
If we simply add the map distances, we get the actual map distance which disregards the possibility of double recombinations. All map units greater than 10cM have significant chances of double crossovers between them, and hence, the observed recombination frequency would be less than the expected 0.1. Hence, for distances greater than 10cM, the observed frequency of recombination will not be the same as (map distance/100). | {
"domain": "biology.stackexchange",
"id": 1712,
"tags": "homework, genetics, chromosome, recombination, genetic-linkage"
} |
Empty universe in the past, non-empty in the future | Question: My question is the following. Are there solutions to the Einstein field equations, which have the property that there is a hypersurface of constant time and to the past of that surface space is empty (Minkowski space-time) and to the future it is not (non-vanishing stress-energy tensor)? At first thought it seems strange to have nothing and suddenly something. On the other hand define $g_{\mu\nu}(x)$ to be the Minkowski metric for the past of the surface and any functions (sufficiently smooth) that match it on the surface and are different than the Minkowski for the future. There are many ways (infinitely many) to do this. Then one can define the stress-energy tensor using Einstein's equations. This would seem to work, but there are certain conditions on the tensor, for example positivity, or other restrictions for physical reasons that I am unaware of, so it may be there are no such functions.
So the questions is: does anyone know of an explicit example or a more convincing argument than "there are so many functions, there has got to be some that work"? Of course a reason why it doesn't work, if that is the case, would be good too.
Thanks.
Answer: I believe that no such spacetime exists, if the matter is assumed to satisfy an inequality known as the dominant energy condition. The dominant energy condition says that, if $\xi$ is a future-directed timelike vector, then $-{T^a}_b\xi^b$ is a future-directed timelike or null vector (sign conventions, etc., following Wald's book General Relativity). Heuristically, this condition means that an observer at any location will always measure an energy-momentum 4-current in his vicinity that is flowing at less than or equal to the speed of light.
With this condition, one can show that, if space is empty at one time (i.e., if there is a spacelike Cauchy hypersurface along which $T=0$), then it vanishes at all times (Wald, p. 219). If in addition spacetime is Minkowski along some Cauchy surface, then the initial value theorems say that it's Minkowski at all times (Wald, Chapter 10).
Heuristically, the above argument says that, if there's no matter at one time, but there is at a later time, then matter must have popped out of nowhere. The dominant energy condition doesn't allow that.
I don't know whether the result holds if you assume something weaker than the dominant energy condition (e.g., the aptly-named weak energy condition). Certainly you need some sort of restriction on the allowed properties of the matter, as Lubos Motl says: if any $T_{ab}$ is allowed, then any smooth metric is allowed. | {
"domain": "physics.stackexchange",
"id": 23788,
"tags": "general-relativity"
} |
What are the length and time scales in turbulence? | Question: I haven't been able to understand what are does someone mean by length and time scales, while talking about turbulence. Can someone explain it?
Answer: Basically, the scale of a certain parameter is the order of magnitude of that parameter. Being able to determine the scales of a parameters in a complex system (like turbulence problems) is very useful.
For turbulence, the size of the largest eddies is given by the characteristic length scale you are working with, $L$, and the smallest eddy size is given by the so called, Kolmogorov length scale, $\eta$.
This scale goes like, $\eta = \left(\frac{\nu^3}{\epsilon}\right)^{1/4}$, where $\nu$ is the viscosity and $\epsilon$ is the dissipation rate per unit mass.
It is interesting to note that $L/\eta= \text{Re}^{3/4}$.
Another commonly encountered length scale is known as Taylor micro-scale and provides a good estimate for the fluctuating strain rate field.
The times scale for the so called "large eddy turnover" is simply the time scale of the flow, $L/U$
The time scales for the small eddies can also be derived using the viscosity and dissipation, $t_\eta = \left(\frac{\nu}{\epsilon}\right)^{1/2}.$
Similarly, $t_L/t_\eta= \text{Re}^{1/2}.$
Good books I can suggest are the book S. B. Pope (Turbulent Flows) and T.H. Lumely (A first course in Turbulence). | {
"domain": "physics.stackexchange",
"id": 9674,
"tags": "turbulence"
} |
discrete Haar wavelet transform, fast and efficient method? | Question: I'm working on my own implementation of the discrete Haar wavelet transform, I understand the wavelet theory and how to construct the Haar matrix of size N to perform the transform, but obviously there is a problem using the Haar matrix in application - it's simply too big.
I am working on an application that applies the Haar transform to an audio signal. If I sample the signal at 44.1 kHz, even a one second recording would require a 2^16 by 2^16 Haar matrix to do the transform in one step, which is obviously impractical and a hardware constrained machine such as a phone wouldn't have the capability to hold such a matrix in memory.
The other method I've seen used is that a 2X2 Haar matrix is applied to the entire signal iteratively, and the results are stored in two arrays - one array holding the "average" Haar coefficients (first element of the output vector) and the other holding the "difference" coefficients (second element of the output vector). The process is then repeated over the "average" coefficients - as these coefficients are essentially the result of a lowpass filter. Each time the process is repeated the number of elements needed to process in the following step is halved, until only one lowpass coefficient is left. This seems fine, and definitely works but when I started to think about it, it just seems that it would be really slow.
My main question is, what's a good way to implement a fast and efficient haar transform? Or a practical way to apply one of these two methods?
PS: I've been learning about this completely on my own, so if I made some mistakes in my explanation or way of thinking about this stuff let me know.
PSS: I've never done any kind of audio processing before, so if you know about some other filters that I should apply to the raw signal before doing a wavelet transform let me know!
PSSS: I know that the Haar wavelet may not be the best for this type of signal processing, but when I tried to learn about using other DWTs such as the Daubechies wavelets, the literature seemed very confusing, or at least was directed at more advanced readers. If anyone could point me in the direction of how to implement other DWTs, that would be great.
Answer: The Haar wavelet is actually a part of the Daubechies wavelet, for the case D=2. There's some example code on wikipedia that shows the Daubachies transform.
The Haar transform is just a low pass filter combined with a high pass filter, with the coefficients being placed in the first and second halves of the signal. Then, this iteratively (or recursively) keep going.
The low pass filter is just the sum of two components while the high pass filter is their difference.
For the Haar wavelet case, you can check out my vectorized code on Github. Here, idwt2 stands for "Inverse Discrete Wavelet Transform 2D." | {
"domain": "dsp.stackexchange",
"id": 1300,
"tags": "filters, audio, algorithms, wavelet"
} |
camera_node not found in package uvc_camera? | Question:
Hi,
I'm using ubuntu 13.04 ros hydro and I'm trying to run the camera_node on my in uvc_camera package using a launch file containing :
But I get this error ERROR: cannot launch node of type [uvc_camera/camera_node]: can't locate node [camera_node] in package [uvc_camera].
Originally posted by Leyonce on ROS Answers with karma: 97 on 2014-04-01
Post score: 1
Answer:
The correct node is now uvc_camera_node.
Originally posted by Leyonce with karma: 97 on 2014-04-01
This answer was ACCEPTED on the original site
Post score: 2
Original comments
Comment by Leyonce on 2014-04-01:
I'm now wondering on why It was changed and not specified on wiki.ros.org/uvc_camera | {
"domain": "robotics.stackexchange",
"id": 17495,
"tags": "ros, roslaunch, uvc-camera"
} |
Adding SecureString support to Lib2GitSharp | Question: A library that I use doesn't support SecureString in its credentials for connecting to GitHub, so I'm submitting a pull request to add it. I know it's not ideal to pull the actual string out, but the idea here is to minimize the amount of time the string is in memory. Also, allowing client code to utilize the fact that WPF uses a SecureString for passwords without having to do this conversion themselves.
Am I handling the SecureString "correctly" here? I know very little about unmanaged memory.
Is it a poor decision to store the Username in one as well? I'm second guessing that decision now. NetworkCredential uses a plain string for this and the secure version only for the password.
Some notes:
I would use a constructor, but it's the style of the project to use an object initializer.
It's also in the style of the project to place the properties at the bottom like you'll see below.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LibGit2Sharp.Core;
using System.Security;
using System.Runtime.InteropServices;
namespace LibGit2Sharp
{
/// <summary>
/// Class that uses <see cref="SecureString"/> to hold username and password credentials for remote repository access.
/// </summary>
public sealed class SecureUsernamePasswordCredentials : Credentials
{
/// <summary>
/// Callback to acquire a credential object.
/// </summary>
/// <param name="cred">The newly created credential object.</param>
/// <returns>0 for success, < 0 to indicate an error, > 0 to indicate no credential was acquired.</returns>
protected internal override int GitCredentialHandler(out IntPtr cred)
{
if (Username == null || Password == null)
{
throw new InvalidOperationException("UsernamePasswordCredentials contains a null Username or Password.");
}
IntPtr passwordPtr = IntPtr.Zero;
IntPtr userNamePtr = IntPtr.Zero;
try
{
passwordPtr = Marshal.SecureStringToGlobalAllocUnicode(Password);
userNamePtr = Marshal.SecureStringToGlobalAllocUnicode(Username);
return NativeMethods.git_cred_userpass_plaintext_new(out cred, Marshal.PtrToStringUni(userNamePtr), Marshal.PtrToStringUni(passwordPtr));
}
finally
{
Marshal.ZeroFreeGlobalAllocUnicode(passwordPtr);
Marshal.ZeroFreeGlobalAllocUnicode(userNamePtr);
}
}
/// <summary>
/// Username for username/password authentication (as in HTTP basic auth).
/// </summary>
public SecureString Username { get; set; }
/// <summary>
/// Password for username/password authentication (as in HTTP basic auth).
/// </summary>
public SecureString Password { get; set; }
}
}
Answer: I don't see a problem with how the SecureString objects are handled - seems pretty solid to me, but I've never used those so I'm possibly missing something that someone else could point out here.
Sealed Class
I haven't looked at the actual project's source code, but general design guidelines have this to say about sealing classes:
DO NOT seal classes without having a good reason to do so.
However it also defines a number of "good reasons" for sealing a class, including:
The class stores security-sensitive secrets in inherited protected members.
In other words, a sealed class seems warranted here.
InvalidOperationException
Out of all possible existing exception classes in the framework, and instead of creating your own derived exception class, you chose to throw an InvalidOperationException in the implementation of the GitCredentialHandler override.
MSDN describes this exception as follows:
The exception that is thrown when a method call is invalid for the object's current state.
Turns out this was, in my own humble opinion, the best decision to make: throwing any other exception type here would violate POLS - when client code is calling this method and the object's state shouldn't allow it, the programmer has all rights to expect an InvalidOperationException to be thrown.
XML Documentation
This is an API - having complete and accurate XML documentation is ideal.
/// <summary>
/// Callback to acquire a credential object.
/// </summary>
/// <param name="cred">The newly created credential object.</param>
/// <returns>0 for success, < 0 to indicate an error, > 0 to indicate no credential was acquired.</returns>
I think this documentation could be better, but looking at the base class on GitHub I see that you've copied most of it from the base class, which is a good idea.
However the method can throw an InvalidOperationException - you could add something like this:
/// <exception cref="InvalidOperationException">
/// Thrown if this method is called when either <see cref="UserName"/> or <see cref="Password"/> is <c>null</c>.
/// </exception>
Style
You know me, I think this is too verbose:
IntPtr passwordPtr = IntPtr.Zero;
IntPtr userNamePtr = IntPtr.Zero;
Compared to:
var passwordPtr = IntPtr.Zero;
var userNamePtr = IntPtr.Zero;
Which is just as clear IMO. Not much gain here though. And given that the rest of the code seems to prefer the verbose way, sticking to the existing style is the best decision you could make.
And not only for usage of var:
I would use a constructor, but it's the style of the project to use an object initializer.
It's also in the style of the project to place the properties at the bottom like you'll see below.
UserName vs. Password
A user name can be sensitive information in certain circumstances - and although I don't think this is one, there's a saying that summarizes everything I'd have to say about whether or not having the user name as a SecureString is overkill:
Better safe than sorry.
-- unknown
However, the ironic part is this:
return NativeMethods.git_cred_userpass_plaintext_new(...);
Given that credentials end up being passed as plain text, I think I'd keep the user name as a plain string. | {
"domain": "codereview.stackexchange",
"id": 13615,
"tags": "c#, security, memory-management, git, securestring"
} |
How to represent a qubyte? | Question: I was not able to locate any visuals online. The visual I have in my head is a cube w/ bloch spheres as the eight vertices.
I am also curious about a matrix representation, although I am not sure how feasible this is as a qubyte has $2^8$ (256) states.
What is the best way to represent a qubyte?
Answer: I don't think you'll find a good visual representation. The Bloch sphere for a qubit is a particularly unique coincidence because the number of parameters to represent an arbitrary mixed state is only 1 more than the number of parameters required to represent an arbitrary pure state, and so the pure states can be thought of as the surface to a mixed state's volume.
A cube with Bloch spheres at the vertices is a fair representation if all 8 qubits remain separable at all times. However, you will get in a mess trying to represent entanglement in that picture (you'll need superpositions of several different separable states). As you've said, an arbitrary pure state of a qubyte has $2^8$ states, requiring $2^{16}-2$ real parameters to describe. 8 (pure) Bloch states give you access to only 16 parameters. You're probably best sticking to a complex vector of $2^8$ elements (minus 2 real parameters for global phase and normalisation). | {
"domain": "quantumcomputing.stackexchange",
"id": 235,
"tags": "entanglement, quantum-state"
} |
Lego NXT-ROS working on Groovy Galapagos? | Question:
Hi,
I'm just wondering does anyone know if the NXT-ROS package is compatible with the Groovy Galapagos release? There doesn't seem to be any documentation except the wiki and that recommends using the diamondback release(with electric being the newest release even mentioned.) Also are there any other packages that anyone could recommend to control a Lego NXT Robot?
Thanks in advance,
Tadhg Fitzgerald.
Originally posted by Tadhg Fitzgerald on ROS Answers with karma: 98 on 2013-01-20
Post score: 1
Original comments
Comment by Tadhg Fitzgerald on 2013-02-01:
I'll answer this since nobody else did; the answer is no, if you are using NXT-ROS you should use the Electric release
Answer:
Old, but just saw it.
Here I modified NXT for Groovy
https://github.com/maxsieber
Originally posted by msieber with karma: 181 on 2013-07-20
This answer was ACCEPTED on the original site
Post score: 1
Original comments
Comment by 130s on 2013-07-29:
Nice! Do you plan to make an announcement, integrate it into ROS wiki etc.? If it's at too early stage to "announce", then I'd suggest to start discussion in SIG like ros-sig-edu.
Comment by boog on 2013-07-30:
I'm trying to use the compass with this if you can help me please let me know.
Comment by msieber on 2013-08-01:
I will add my repo to the wiki soon.
As my modifications where very minor, I dont think we a need a SIG.
I started a related Question here: http://answers.ros.org/question/67831/is-there-a-newer-nxt_ros-stack-using-nxt-python-222-instead-of-120-on-raspberry-pi/
Comment by msieber on 2013-08-01:
@boog I don’t have a compass, also no Gyro IR or Color for further Testing :-(
You could try to build your compass like the AccelerometerSensor(DigitalSensor) and by looking in a newer version of nxt-python. If it works, Send me a Pull Request plz
Comment by boog on 2013-08-01:
I got it to work by combining a patch I found here https://code.google.com/p/foote-ros-pkg/issues/detail?id=24 my files are a mess otherwise would send you.
Comment by boog on 2013-08-01:
Do I have to do anything special to get yours working on a raspberry pi? Thanks.
Comment by msieber on 2013-08-01:
I did not look at the issues, my nxt-python version problem is also a Issue(15) there. It should work on the RPi. I only modified sensor car for my needs. Tell me if it works, or what your errors are.
Comment by boog on 2013-08-08:
@msieber, the nxt_msgs won't compile and neither will nxt_ros as it looks for an x86 lib in /usr/lib during rosmake. Any idea how to fix this? (On rpi).
Comment by msieber on 2013-08-12:
which lib ? | {
"domain": "robotics.stackexchange",
"id": 12506,
"tags": "ros, nxt, nxt-ros, lego, ros-groovy"
} |
What happens when water added to the ash? | Question: I am pouring some water (using falling by gravity) from my water bottle into the ash. The ash is not in heat conditions. Now the small particles from the ash come out proportional to the water flow.
Now my question is, why do the ash particles come out when pouring water?
Answer: You don't say what the ash is from, but fine ash is a flocculate of very small particles. As such, it has a very low density with air entrained within it.
When you add water the capillary forces produced by the water collapse the structure and expel the air trapped within it. The emerging air carries particles of the ash, hence you see puffs of ash as you add the water. | {
"domain": "physics.stackexchange",
"id": 23083,
"tags": "water, flow"
} |
Can we assign an Entropy-value to physical systems without modelling them by an ensemble / classical probabilities? | Question: The definition of entropy, be it Boltzmanns ($k_B \text{ln } \Omega $), Gibbs ($ - k_B \sum_i p_i \text{ln } p_i $) or Von-Neumann's ($ - k_B \text{Tr} \hat{\rho} \text{ln } \hat{\rho} $) always relies at least on some probability interpretation, (in the first case, it actually only applies to a system in equilibrium states). In the quantum mechanical case, there isn't an ensemble, but the classical probabilities manifest in the density operator.
Given these formulae, my first impression is that we can only talk about the quantity 'entropy', if we model a system as an ensemble and talk about probabilities.
I'd like to know if there is a definition of entropy that also applies to a micro-state. If that's not the case, what do we actually mean by the statement that 'the entropy of an isolated system increases with time'? What does it mean, especially if we (because we are some kind of omniscient entity) presume to know position and momentum of every particles?
Before I could say something about the entropy of this system, I would have to find an appropriate probability distribution for an ensemble describing the system. My first guess for such a probability distribution would be the one which models the timely behavior of the system. By 'timely behaviour' I mean that the probability density which I choose correctly recreates all the average values that I would also get by measuring the corresponding observables at a selection of different instants in time.
Would that be the right way to go?
Answer: This gets exactly into what is called "coarse graining." The idea goes as follows. Say you have some computer simulation where you know the position and momentum of every particle in a large box. There is indeed no way to assign an entropy to this microstate. If you know the microstate, then $\Omega = 1$, and $S = k \ln(\Omega) = k \ln(1) = 0$.
However, its sort of ridiculous to say you literally know all this data. What is maybe more reasonable is the following. First, break the large box up into a grid of a million tiny cubes of volume $1 \mathrm{mm}^3$. Maybe you know the energy $u$ and number of particles $n$ in each of these million tiny $1 \mathrm{mm}^3$ cubes. Then, in your simulation, say you calculate $u$ and $n$ for each tiny cube, i.e. you figure out the macrostate corresponding to the tiny cube's microstate.
You then calculate the entropy of that tiny cube's macrostate, using say the Sackur-Tetrode formula. You then sum up all the entropies of all the tiny cubes to get the overall entropy of the large box. This procedure is what is called 'coarse graining,' where the tiny yet finitely sized boxes are perhaps the 'coarse grains.'
What you'll see in your simulation is that the total entropy of the box will indeed increase in time. (This is just because the whole box's true microstate, which is essentially wandering the phase space randomly, is more likely to wander into a macrostate with more phase space volume.) You could start the simulation with all the particles in one corner of the box, and overtime they will go to occupy the whole thing homogenously. The distribution of number density/energy density/entropy density over the tiny boxes will smooth out in time, i.e. the gradients will dissipate.
Coarse graining perhaps gives us a mentally clear picture of what we mean when we say that entropy always increases in regular everyday objects. | {
"domain": "physics.stackexchange",
"id": 78146,
"tags": "statistical-mechanics, entropy, probability"
} |
How much work can the human body do before dying of exhaustion | Question: If we could assume:
We don't increase our energy from absorbing food.
Our human example in scope isn't starving or suffering from malnutrition.
I mean how much work can we do until the body would die from exhaustion.
Sometimes when we work out, we have this sudden 'burst' of energy. Where does this energy come from, and how long, biologically are we capable of converting this energy to the various forms of energy we expel from our bodies: heat, mechanical, etc..
Answer:
What is the potential energy of the human body?
36 MJ $\simeq$ 8600 kcal.
The basal metabolic state for a human is about 60 W. Let's assume (horrible) an immobile person dies after one week (604800 s) of starvation, he will have consumed 60 W * 604800 s = 36,288,000 J.
Where does this energy come from?
from the high energy chemical bonds of complex molecules we eat (and light for plants), which are gradually and sequentially oxydized in a controlled way by a set of enzymes. (some background: The energy released in each step in their degradation is used during cellular respiration by other processes, in particular ion pumps, that eventually produce a voltage difference in mithocondria. This $\Delta V$ is eventually used by a tiny nanometer rotary motor (F0F1) to produce ATP, the molecule consumed in a immense variety of processes, including mechanical muscle contraction.) | {
"domain": "physics.stackexchange",
"id": 26698,
"tags": "energy, energy-conservation, potential-energy, biophysics, biology"
} |
FM demodulation using complex differentiation | Question: I'm trying to implement the complex differentiation discriminator which is taken from Software-Defined Radio Using MATLAB, Simulink, and the RTL-SDR. The final result is $$s(t) = \frac{s_q'(t) s_i(t) - s_i'(t)s_q(t)}{s_i^2(t) + s_q^2(t)}$$ where $s_i(t)$ and $s_q(t)$ are in-phase and quadrature components. If we approximate the differentiation by $$\frac{dx}{dt} = \frac{x[n] - x[n-2]}{2T_s}$$then $s(t)$ becomes(ignoring the scale factor $\frac{1}{2T_s}$) $$s[n] = \frac{(s_q[n] - s_q[n-2])s_i[n] - (s_i[n] - s_i[n-2])s_q[n]}{s_i^2[n] + s_q^2[n]}$$but this is not correct: I don't understand why we need the single sample delay. In general, when do delays are necessary to keep the outputs of digital filters synchronized?
Answer: Note that ideally you would approximate the derivative at time instance $t=nT_s$ by the following central difference quotient:
$$\frac{dx(nT_s)}{dt}\approx\frac{x[(n+1)T_s]-x[(n-1)T_s]}{2T_s}\tag{1}$$
Since such a system is non-causal - because you would need to know the signal one time step ahead in order to compute the output - you add a delay of one sample, resulting in
$$\frac{dx[(n-1)T_s]}{dt}\approx\frac{x[nT_s]-x[(n-2)T_s]}{2T_s}\tag{2}$$
Consequently, in order to keep the inputs and outputs of the causal differentiator synchronized, you also need to delay the inputs by one sample. | {
"domain": "dsp.stackexchange",
"id": 10348,
"tags": "finite-impulse-response, digital-filters, demodulation, group-delay, finite-differences"
} |
Trace of commutators with flavor indices | Question: I want to explicitly write out the Lagrangian term
$$\operatorname{Tr}\bigg( \sum_{I\neq J}[\phi^I,\phi^J]^2\bigg) ,$$
where $I,J$ are flavor indices and $\phi$ is a scalar field. Why doesn't this commutator vanish? As I understand it those are different (flavored) scalar fields and therefore commute. I know that in the case of two gauge fields for example the commutator would be
$$
[A^\mu,A^\nu]=if^{abc} A^{\mu b} A^{\nu c}.
$$
Should I take into account a similar (independent) group theory structure for the flavour indices?
Answer: First of all, your equation for gauge fields (which has the index $a$ on one side but not the other) is not correct. The closest thing that commonly comes up is
\begin{equation}
[A^\mu, A^\nu] = if^{ab}_{\,\,\,\,\,c} A^\mu_a A^\nu_b T^c
\end{equation}
but this is a consequence of the gauge fields being valued in some Lie algebra. I.e. $A^\mu = A^\mu_a T^a$ where the generators satisfy
\begin{equation}
[T^a, T^b] = if^{ab}_{\,\,\,\,\,c} T^c.
\end{equation}
The same thing is going on with the scalars in your Lagrangian. It may look like there are only as many scalar fields as values that $I$ and $J$ can take. But the partially index-free notation hides the fact that $\phi^1$, $\phi^2$, etc are all matrices where each entry is a scalar field.
In other words, the $\phi^I$ are really $\phi^I_a T^a$ meaning they are in the adjoint representation of some (global or gauge) symmetry algebra. For gauge fields, this is an absolute necessity while for scalar fields, it is a choice. And one can certainly imagine theories where the scalars are not in the adjoint. But these types of scalars (and the exact interaction you wrote) show up in one of the most famous QFTs which is $\mathcal{N} = 4$ Super Yang-Mills with a $U(N)$ gauge group. In this case, $I$ and $J$ run from 1 to 6, reflecting the $SO(6)$ symmetry under which the supercharges are spinors. Holographically, this is the isometry group of the internal manifold in $AdS_5 \times S^5$. But each of $\phi^1, \dots, \phi^6$ is an $N \times N$ matrix. The reason for expecting this is that they have to be in the same super multiplet (superfield) as the $A^\mu$ which also are. | {
"domain": "physics.stackexchange",
"id": 80772,
"tags": "operators, gauge-theory, commutator, lie-algebra, trace"
} |
In a composite quantum system AB, in what sense does dynamical evolution of B commute with measurement on A? | Question: The following exercise is found on p. 152 in Benjamin Schumacher and Michael Westmoreland's book Quantum Processes, Systems and Information:
"The composite quantum system AB is initially in the state $|\Psi^{(AB)}\rangle$ and B evolves by the unitary operator $V^{(B)}$. Show that, for any A-state $|a^{(A)}\rangle$,
$$\left<a^{(A)}|1^{(A)} \otimes V^{(B)} | \Psi^{(AB)}\right> = V^{(B)}\left<a^{(A)}|\Psi^{(AB)} \right>."$$
(If notation is non-standard, $\left<a^{(A)}|\Psi^{(AB)} \right>$ is the partial inner product, which is equal to the (non-normalized) conditional state of system B given that a basic A-measurement on $|\Psi^{(AB)}\rangle$ results in outcome $|a^{(A)}\rangle$).
This is not difficult so show. What I find strange is the following passage interpreting the result:
"We can interpret this exercise by comparing two processes:
First we evolve the joint state $|\Psi^{(AB)}\rangle$ according to $1^{(A)} \otimes V^{(B)}$, then we use the result to find the conditional state for $|a^{(A)}\rangle$.
First we use $|\Psi^{(AB)}\rangle$ to find the conditional state for $|a^{(A)}\rangle$, then we evolve this state according to $V^{(B)}$
Both processes lead to exactly the same final state of B. The dynamical evolution of B commutes with the measurement process on A."
Here is my question: Is it not a bit misleading to say that both processes lead to the same final state of B? Clearly, by both processes, the final state of B depends on the result of the preceding A-measurement - but this result is non-deterministic, so the result of the A-measurement might be different in process 1 and process 2, resulting in different final states of B? The final state of B will only be the same in both processes, if the A-measurement by chance gives the same result in both cases. Or what? Am I missing something?
In case someone else has the book: The reason I'm asking the above question is that the authors, arguing on p. 153 that you can do "Type 1 quantum communication" by doing "Type 2 quantum communication", seems to need that you always get the exact same final B-state by both processes (or purhaps I just don't get their argument).
Answer: A weaker statement than that of "both processes lead to the same state" could be:
The statistics of a measurement of an observable $\Lambda$ on system $A$ will be the same whether it is measured before or after the evolution of $B$.
Meaning, the probability of observing each eigenvalue of a given observable is not influenced by the $B$ evolution, nor are the resulting post-measurement states.
To see this,let's work with density matrices instead. Call $\rho_{AB}=|\psi\rangle\langle\psi|_{AB}$, then to obtain the probability of observing the outcome $a$ if $|a\rangle_A$ is the eigenvector of some observable the experimentalist on the $A$ side (let's call her Alice) measures, we have to project the state onto the corresponding eigenspace and take the trace
$$ \mathrm{Tr}(|a\rangle\langle a|_A \otimes \mathbb{1}_B|\psi\rangle\langle\psi|_{AB})$$
You can convince yourself that this is equal to
$$ \mathrm{Tr}_A(|a\rangle\langle a|_A \mathrm{Tr}_B(|\psi\rangle\langle\psi|_{AB})=\mathrm{Tr}_A(|a\rangle\langle a|_A \rho_A)$$
Since, as you've shown, the $B$ evolution commutes with the projection, this probability is the same regardless of whether the observable is measured before or after the evolution: even more, you can see that the probability does not depend at all on the state $\rho_B$ (except for how $\rho_A$ itself depends on it).
To understand the somewhat stronger statement "both processes lead to the same final state on $B$", it's better to understand what we usually mean by state after a measurement. Suppose you have an observable $\Lambda$ with eigendecomposition $\Lambda=\sum_k \lambda_k P_k$ where $P_k$ is the projector onto the eigenspace of eigenvalue $\lambda_k$. For simplicity, let's say there are no degenerate eigenvalues, so that $P_k=|k\rangle\langle k|$ where $|k\rangle$ is an eigenvector of $\Lambda$.
$$ \Lambda |k\rangle=\lambda_k|k\rangle$$
Suppose also you have a quantum state $\rho$. The act of measuring $\Lambda$ corresponds to the quantum channel
$$ \rho\mapsto \mathcal M(\rho)=\sum_k \langle k|\rho |k\rangle |k\rangle\langle k|$$
I.e., the state $\rho$ is replaced by a state which is diagonal in the $|k\rangle$ basis, which can be interpreted as a classical probability distribution: the state $|k\rangle\langle k|$ has probability $\langle k|\rho |k\rangle$. If $\rho=|\psi\rangle\langle \psi|$ is a pure state then this probability turns into the familiar $|\langle \psi|k\rangle|^2$.
This is what you can think of as the state after the measurement, if you don't look at the measurement result: you know the state is one of the eigenvectors of $\Lambda$, and you know the probability of observing each one. If the state is bipartite, $\rho=\rho^{(AB)}$, you can very easily verify that
$$\mathcal M_A(V^B\mathcal \rho^{(AB)}V^{B\dagger})=V^B\mathcal M_A(\rho^{(AB)})V^{B\dagger}$$
or with more explicit notation
$$\mathcal M^A\otimes \mathrm{id}^B(\mathbb 1^A\otimes V^B\mathcal \rho^{(AB)}\mathbb 1^A\otimes V^{B\dagger})=(\mathbb 1^A\otimes V^B)\mathcal M^A\otimes \mathrm{id}^B(\rho^{(AB)})(\mathbb 1^A\otimes V^{B\dagger})$$
I.e., the final state on is the same regardless of whether you measure $A$ before or after evolving $B$. Notice that this implies both that the statistics of the $A$ measurement aren't influenced by the order of operations, but also that the final state on $B$ is the same regardless of the order.
The argument given in the book is valid for any single measurement result, I guess it's there to state the result before introducing channels, you can think of it not as saying "if we repeat the experiment twice" but more like "for each possible measurement result, we get the same state whether the measurement was performed before or after the evolution".
To give a more physical motivation, suppose that the two different processes somehow led to different states. Then there would be some experiment Alice could make to know whether or not Bob has already performed the unitary evolution, this would allow Alice and Bob to communicate in principle faster than the speed of light would allow, which wouldn't be good for quantum mechanics at all. | {
"domain": "physics.stackexchange",
"id": 66527,
"tags": "quantum-mechanics, hilbert-space, quantum-information"
} |
Why is the Bohm quantum potential considered a potential? | Question: In Bohmian mechanics, the term $$\begin{equation}
Q = -\frac{\hbar^2}{2m}\frac{\nabla^2 R}{R}
\end{equation}$$
is regarded as the quantum potential term. However this is merely a term from the real part of the quantum kinetic energy equation. $$\begin{equation}
T = -\frac{\hbar^2}{2m}\frac{\nabla^2 \Psi}{\Psi}
\end{equation}$$
I completely fail to see why this should be regarded as anything except kinetic energy. Can someone explain?
(Yes, I know about dividing by complex quantities. When you plug in the polar form of $\Psi$ the exponentials cancel and you're left with just $R$ so dealing with the $\Psi*$ is unnecessary.)
Answer: The notion that this is some kind of potential is historic. It was Bohm himself who introduced it. In recent times many researchers working on Bohmian Mechanics have mostly abandoned that notion except sometimes as a pedagogical analogy which can only be taken so far. Just like, for example, in special relativity the interpretation that mass increases for objects moving near the speed of light is no longer considered useful.
The origin for the notion of a quantum potential was that the Hamilton-Jacobi equations are very similar to the equation of motion for $S$, the phase of the wave function when it is written $\psi = R e^{iS/\hbar}$. The Schrodinger equation gives:
$$\frac{\partial S }{\partial t} = -\left(\frac{|\nabla S|^2}{2m} + V-\frac{\hbar^2}{2m}\frac{\nabla^2 R}{R}\right)$$
...which is just the Hamiltonian Jacobi equation but with an extra term, which you likely notice is equal to your $Q$. This could be interpreted as a modification to the potential. But as I already mentioned, this interpretation has shown its limits and is therefore not to be taken too literally. The notion of a wave function acting as a guide to point particles is sufficient. | {
"domain": "physics.stackexchange",
"id": 92229,
"tags": "quantum-mechanics, potential, schroedinger-equation, bohmian-mechanics"
} |
What is the term for hose fluctuating movements during flow? | Question: What do we call it when water flowing through a flexible hose causes it to act like snake movements if the hose were disturbed?
Can this movement be explained by the Coriolis force?
Answer: Here is my hypothesis. Consider a hose that is shaped like the diagram below, with two straight sections linked by a section of constant curvature:
The thick black arrows indicate the velocity of the flow. The flow in the second straight section has been deflected, so a force must have acted on it. The fluid dynamics of the situation might be complicated depending on how turbulent the flow is, but this force must ultimately come from the hose walls, since they're what constrains the fluid to flow in this particular direction.
By Newton's third law, there must have been an equal and opposite force on the hose walls during the curved section, as indicated by the thin red arrows. This force isn't to do with the Coriolis force, it's just the reaction force that must exist in order for the flow to be deflected. This force must cause the hose walls, and the liquid within them, to move. Note that there is a more or less constant force on the curved section of the hose, but no force at all on the straight sections - so the curved part is being pulled outwards to the left, but the straight parts aren't being pulled at all. After a little while, it must look something like this:
The original curved part has moved outwards (and is still moving), but this has created two new curved sections, which are now experiencing reaction forces in the opposite direction. These will then start to move as well, pulling yet more of the straight parts into curved configurations. The hose will begin to chaotically wriggle about with dynamics quite similar to the meandering of a river, although the details of their cause are quite different.
Whether this happens or not must depend on the speed of the flow (because a faster flow requires a larger reaction force to deflect it) and on the extend to which the hose resists these induced changes in its curvature. The latter is probably quite complicated, depending on the stiffness and elasticity of the hose walls, how much friction there is, and probably also on the viscosity and density of the fluid inside, and on whether the flow is turbulent. If the flow is fast, the hose is very flexible, and there is not much friction then I would expect it to wiggle a lot.
To answer the question in the title, I don't think there is an accepted term for this phenomenon, oddly enough. For example, this scholarly paper refers to it as "The fluidelastic instability behaviour of flexible tubes subjected to internal single-phase ... flows" - but I think you could probably get away with calling it "the flexible tube instability". | {
"domain": "physics.stackexchange",
"id": 71866,
"tags": "fluid-dynamics, soft-question, terminology"
} |
Covariance in PoseWithCovariance | Question:
How is the covariance field in the PoseWithCovariance
message interpreted?
Originally posted by Hordur on ROS Answers with karma: 544 on 2011-12-14
Post score: 1
Answer:
The "msg.covariance" field represents the uncertainty in the deterministic field "msg.pose".
This uncertainty is described by a normal distribution centered on the pose field so the probability of the state x follows: p(x)~ N(msg.pose,msg.covariance)
Originally posted by Pablo Iñigo Blasco with karma: 2982 on 2012-02-15
This answer was ACCEPTED on the original site
Post score: 3
Original comments
Comment by Pablo Iñigo Blasco on 2012-02-15:
Of course there is others ways to represent the pose uncertainty. For instance the PoseArray msg (particles) makes possible describing a more complex probabilistic distribution. In any case it has some drawbacks, most of algorithms based on particles usually have less computational efficence. | {
"domain": "robotics.stackexchange",
"id": 7641,
"tags": "geometry-msgs"
} |
Capillaries in series | Question: The velocity of fluid of viscosity $\eta$ through a capillary of radius $r$ and length $l$ at a distance $x$ from the center of the capillary is given by; $v=\frac{P}{4l \eta }(r^2-x^2)$ (where $P$ is the pressure difference at the two ends of capillary). With the help of this I can find the rate of flow of fluid out of the capillary equal to $\frac {dV_{out}}{dt} = \frac{\pi Pr^4}{8l \eta }$.
But what happens when the capillaries are in series with different radius and length?
Answer: Assuming the fluids are incompressible, the flow through each capillary must be the same. Also the sum of the pressures across each capillary must equal the total pressure. Therefore, you have the equations:
$P_1+P_2 = P$
$V_1 = \frac{\pi P_1 r_1^4}{8 l_1\eta} = V_2 = \frac{\pi P_2 r_2^4}{8 l_2\eta}$
Solve this system for $P_1$ and $P_2$ then plug back in to find the flow rate in terms of $P, r_1, l_1, r_2, l_2$. | {
"domain": "physics.stackexchange",
"id": 3889,
"tags": "fluid-dynamics, viscosity, capillary-action"
} |
When did the first annular eclipse happen? | Question: A few hundreds of millions of years ago, the moon was closer to the Earth than it is today and hence was of a bigger apparent size. This made every solar eclipse either total or partial. Over the course of time, due to tidal forces between the moon and the Earth, the moon slowly drifted far from Earth decreasing its apparent size when viewed from Earth and hence causing annular eclipses to happen.
That would mean there must have been some day in history when Earth witnessed its first ever annular eclipse. Is there an estimate on when this happened?
Answer: A quick and dirty estimate is as follows.
An angular eclipse occurs first if the Moon is at apogee and Earth at perihelion. Assuming that these two events coincide (which happens every ~8.85 years owing to lunar apsidal precession), an angular eclipse requires that ($a$ denoting orbital semi-major axis and $R$ radius)
$$
\frac{R_\supset}{(1+e_\supset)a_\supset} < \frac{R_\odot}{(1-e_\oplus)a_\oplus}
$$
or
$$
a_\supset > \frac{R_\supset}{R_\odot} \frac{1-e_\oplus}{1+e_\supset} a_\oplus\approx 348300\,\mathsf{km}
$$
where I assumed that the orbital eccentricities, Lunar and Solar radii, and Earth's semi-major axis didn't change (over the period considered here) and are given by
$e_\supset=0.0549$, $e_\oplus=0.0167$, $R_\supset=1737.1\,$km, $R_\odot=695510\,$km, and $a_\oplus=149.6\times10^6\,$km.
At the present we have $a_\supset=384400\,$km. If we assume an average annual change by 22 mm, we find a time of
$$1.6\times10^9\,\mathsf{years},$$
though it could have been more recent if the annual change of $a_\supset$ was larger some hundred million years ago (which may well have been the case).
In a similar way, one may also estimate when the last full Solar eclipse will occur. This time, the Moon is at perigee and Earth at apohelion, when
$$
a_\supset < \frac{R_\supset}{R_\odot} \frac{1+e_\supset}{1-e_\oplus} a_\oplus\approx 400800\,\mathsf{km}
$$
which last occurs in $430\times10^6$ or $745\times10^6$ years, depending on whether the current lunar recession rate of 38mm/yr or the long-term average of 22mm/yr is used. | {
"domain": "astronomy.stackexchange",
"id": 3855,
"tags": "earth, solar-eclipse, history"
} |
Shape of the rainbow | Question: I have watched Walter Lewin's lecture(http://www.youtube.com/watch?v=6QVbE_tU2sA) which was about the rainbows. But there is still a question bothering me.
I understood the first part of the lecture which he talked about axial symmetry that holds in the drop of water because the light beam is coming from a preferred direction. But I cannot understand that why he relates the semicircular shape of the rainbow to axial symmetry.
To make my question clearer, I say an example. Considering the red part of the rainbow for instance, we found that this color of rainbow is seen if we look about 42 degrees above the reference line(from the sun). But I think that for looking at other red parts of the bow, one should rotate his head and other red parts have different angles than 42.I know that all red parts should be at 42 degrees but I am confused and cannot understand it.
I have another problem and that is why we emphasize on $\varphi_{max}$. For example,at the angle of 40 degrees, we have both blue and red color but they always use 40 degrees just for blue but we can have a mixture of red and blue.
I will be thankful if you can help me with these.
Answer: After some search, I found a video on youtube which was about the rainbow.It says that
The set of all points which have a fixed angle between the sunlight, the raindrop and the observer creates the circular arc of the rainbow.
This picture helped me.
For the second question about the reason that we just see a special color at each angle, I watched Lewin's lecture at Delft University of technology.He mentioned the reason and said
At the maximum values of $\varphi$, there is
a peak in the intensity
of that special light.
Because of that, although all colors exist at e.g.$40.7^\circ$ but just one color is seen because the peak intensity of blue occurs at $40.7^\circ$ . | {
"domain": "physics.stackexchange",
"id": 8902,
"tags": "optics, everyday-life, refraction"
} |
If there is no gravity then why space curved around the Earth? | Question: As I got it from the Veritasium video on YouTube (I know, people told me before that the video isn't perfect and YouTube isn't the best place to get such knowledge): a satellite flies around the Earth not because of gravity (by relativity theory there is no such thing), it files always straight, but space around Earth is curved around it, so it flies around the Earth.
Also it was told that there is not gravity force, but isn't relativity theory told us that the stronger gravity (the bigger planet, star) the slower time goes near/on that planet?
(Probably it's not related to the question, but also interesting how "no gravity" relates to gravity waves?)
Answer: It’s just language. Physicists could stop using the word “gravity” and could say “curvature of spacetime” instead. But out of force of habit, we still talk about the “stronger gravity” near a planet or star instead of “more strongly curved spacetime” and we still talk about “gravitational waves” (note that gravity waves are something different) instead of “oscillations in the curvature of spacetime”. | {
"domain": "physics.stackexchange",
"id": 97521,
"tags": "general-relativity, gravity, spacetime, curvature"
} |
Why is awareness of itself such a point when speaking about AI? | Question: Why is awareness of itself such a point when speaking about AI? Does it always mean a starting point for apocalyptic nightmares to occur when such a level is reached or is it just a classical example about what could be a really abstract thing that machine cannot easily posses?
I would sleep my nights far more calmfully if the situation was the latter, and I understand the first does not automatically happen. The main thing I would like to discover is the starting point - which approach came first historically? Or is there another view point in the historical first occurrence of self awareness term?
Answer: Neil Slater has it right, there most probably is no fear of AI self awareness as some starting point of evil series of things to happen.
Wikipedia [1] puts self awareness talks to sci-fi section, among stories, not a real thing. Self-awareness is among a list of terms that tries to make machines or aliens similarly human than ordinary people and uses that as a method of story telling.
Self-awareness or other humanlike skills that we posses that the machines don't have yet and will not have in near future can twist minds and make a seed of conspiracy theories, but at least the exhaustive Wikipedia overview on topic did not speak anything about AI.
Maybe the concept of humanlike behaviour materialises on our minds as a term of self-awareness but my source puts the origin to different category.
[1] https://en.m.wikipedia.org/wiki/Self-awareness | {
"domain": "ai.stackexchange",
"id": 1418,
"tags": "philosophy, agi, history, self-awareness"
} |
How to use general expression for Noether's current to get the energy-momentum conservation law? | Question: The most general form of the Noether's current (see here and here) is given by $$j^\mu(x)=\sum\limits_a\frac{\partial \mathscr{L}}{\partial(\partial_\mu\phi_a)}\delta\phi_a -\theta^{\mu\nu}\delta x_\nu-K^\mu\tag{1}$$ where $$\theta^{\mu\nu}=\frac{\partial\mathscr{L}}{\partial(\partial_\mu\phi)}\partial^\nu\phi-\eta^{\mu\nu}\mathscr{L}.\tag{2}$$Using $(1)$, let us determine the conserved current due to spacetime translations for which $\delta x^\mu=a^\mu$ (a spacetime independent constant) and $\delta\phi_a=0$. Therefore, $$j^\mu(x)=-\theta^{\mu\nu}a_\nu-K^\mu.\tag{3}$$ Now conserved current implies $$\partial_\mu(\theta^{\mu\nu}a_\nu+K^\mu)=a_\nu\partial_\mu\theta^{\mu\nu}+\partial_\mu K^\mu=0.\tag{4}$$ If $K^\mu$ were zero (as is assumed in Ryder's book, for example), since $a_\nu$ is arbitrary, we would immediately get the usual conservation laws $$\partial_\mu\theta^{\mu\nu}=0\tag{5}$$ from which we obtained four conserved quantities: $P^\nu$.
In the general case, when $K^\mu\neq 0$, assuming that both $\theta^{\mu\nu}$ and $K^\mu$ vanish sufficiently rapidly at spatial infinity, I obtain, $$\frac{d}{dt}(a_\nu\theta^{0\nu}+K^0)d^3x=0.\tag{6}$$ The disturbing thing about this is that now I get only one conserved quantity $$Q=\int j^0d^3x=-\int(a_\nu\theta^{0\nu}+K^0)d^3x\tag{7}$$ because $a^\nu$ does not drop out from the equations and Lorentz indices are contracted! What is wrong with my analysis?
Addendum The analogue of Eq.$(7)$ is like obtaining $$p_x a_x+p_ya_y+p_za_z={\rm constant}$$ under a general spatial translation ${\bf r}\to {\bf r}+{\bf a}$ where ${\bf a}=a_x\hat{x}+a_y\hat{y}+a_z\hat{z}$. What would please me is that if I could show $p_{x,y,z}$ are intividually constants. Please let me know if I am making a conceptual/notational mistake.
Question How to apply general expression for Noether's current to get the energy-momentum conservation law?
Answer: Your $Q$ still is four independent quantities - one for each independent choice of the translation direction $a^\nu$.
Noether's theorem states that for a one-parameter continuous quasi-symmetry
\begin{align}
x^\mu & \mapsto x^\mu + \epsilon \delta x^\mu \\
\phi^a & \mapsto \phi^a + \epsilon \delta \phi^a
\end{align}
where the theory is quasi-symmetric under this transformation in a neighbourhood of $\epsilon = 0$ for constant $\delta x^\mu, \delta \phi^a$, you get the conserved current expression in your question. The transformation
\begin{align}
x^\mu & \mapsto x^\mu + a^\nu \\
\phi^a & \mapsto \phi^a
\end{align}
is not of this form, it is really a family of one-parameter symmetries, additionally parametrized by the four-vector $a^\mu$ - it is a generic infinitesimal translation, and the translation group is $\mathbb{R}^4$. There are four independent one-parameter continuous transformations here:
\begin{align}
x^\mu \mapsto x^\mu + \epsilon e^0 \\
x^\mu \mapsto x^\mu + \epsilon e^1 \\
x^\mu \mapsto x^\mu + \epsilon e^2 \\
x^\mu \mapsto x^\mu + \epsilon e^3
\end{align}
for $e^\mu$ the unit vector in the $\mu$-direction, and to each of these transformations Noether's theorem associates a conserved quantity. The usual derivation you cite where the $a^\nu$ is kept generic is just an efficient way to derive the conserved quantities for each of these transformations at once, where we can then choose e.g. $a = e^2$ at the end if we want the conserved quantity associated to the translation in the 2-direction. | {
"domain": "physics.stackexchange",
"id": 74638,
"tags": "lagrangian-formalism, conservation-laws, symmetry, stress-energy-momentum-tensor, noethers-theorem"
} |
jQuery grid-system - handing different row widths | Question: I made a function in jQuery for my home-made grid system. When a row has too many columns in it, it removes the HTML code from that row.
Normally in my grid system it fits 12 columns in 1 row, but with the function this can easily be changed.
One column with the size of 1 (declared as: column size-1) has a width of 1/12 (or 8.3333%).
function validateRowWidth() {
var _row = $('.row');
_row.each(function (index, element) {
var totalWidth = 0,
_columnSize = $(element).find('[class*="size-"]');
_columnSize.each(function (index, element) {
var width = $(element).outerWidth(true),
inProcent = Math.round((width / $(element).parent().width()) * 100);
totalWidth += inProcent;
});
if (totalWidth > 100) {
console.log('You have to many columns into your '+(index + 1)+'th row');
$(element).remove();
}
});
}
Is there any way I can improve this?
Answer: Things I pondered:
What's with the underscores everywhere?
Why not use regular jQuery convention and use this instead of element in your each iterator?
What's the use-case for this? A regular user will never see the console, so logging to it doesn't help anyone.
Even if someone is watching the console, what's the point of warning them when the row is just summarily removed? At least give the user a chance to fix the problem. It's worse if you're not looking at the console - then stuff is just gone with no explanation.
And the warning, "You have too many columns", isn't really truthful. The problem is that the columns - even if it's just 1 - are too wide. You code isn't checking how many there are.
But mostly: Why use percentages? Just compare widths directly. Saves you a whole lot of trouble (and code)
This seems clearer to me:
function validateRowWidth() {
$('.row').each(function (index) {
var row = $(this), // use `this`
widthSum = 0;
// sum up the (direct descendant) column widths
row.children('[class*="size-"]').each(function () {
widthSum += $(this).outerWidth(true); // 1 line is all you need here
});
// compare and warn if need be
if(widthSum > row.width()) {
// alert is not a great choice, but it's better than console.log,
// if this is user-facing. Explain the problem, and propose solutions.
alert("Row " + index + " is too wide. Remove one or more columns or make them narrower.");
}
});
} | {
"domain": "codereview.stackexchange",
"id": 8015,
"tags": "javascript, jquery"
} |
Is BEC the same as entanglement? | Question: I understand that Bose Einstein condensate is:
A Bose–Einstein condensate (BEC) is a state of matter of a dilute gas of bosons cooled to temperatures very close to absolute zero. Under such conditions, a large fraction of bosons occupy the lowest quantum state, at which point microscopic quantum phenomena, particularly wavefunction interference, become apparent.
I understand that all the particles in the condensate will be described by the same wavefunction.
Now entanglement is:
Quantum entanglement is a physical phenomenon which occurs when pairs or groups of particles are generated, interact, or share spatial proximity in ways such that the quantum state of each particle cannot be described independently of the state of the other(s), even when the particles are separated by a large distance—instead, a quantum state must be described for the system as a whole.
I understand that entangled particles can be described by the same wavefunction too.
So in both cases the particles can be described by the same wavefunction.
Question:
Is BEC the same as entanglement for a larger (macroscale) number of particles?
What is the real difference between BEC and entanglement, other then the number of particles?
Answer: The key difference is the entanglement. The particles in a BEC indeed overlap and therefore when in the BEC can be described by the same wave function. However, when a BEC gets released, the constituent parts will move away from each other and can be then described on their own. If we were to measure on of those particles it would not tell us anything about the other particles.
However, when you have entangled particles, their quantum states depend on one another. So if we have two entangled particles, a measurement of one will tell me the exact state of the other.
In the end, just because particles overlap in a BEC does not entangle them. | {
"domain": "physics.stackexchange",
"id": 51704,
"tags": "quantum-mechanics, wavefunction, quantum-entanglement, bose-einstein-condensate"
} |
Time series with additional information | Question: Given a time series with job-submission counts, how can I predict which certain features about the jobs?
I need to predict how many jobs and which jobs arrived in some system. Using pandas.groupby, I've sliced the data into 15 minutes intervals.
I can predict how many jobs arrived but also need to predict which type of job will arrive and some other features.
Answer: I'm assuming the displayed time series shows number of jobs submitted per 15 minute interval.
Categorical features
Divide the time series per category. If the jobs can be divided into type1, type2, type3 then make a time series for each type and predict each series individually. So type1-time series has number of type1-jobs per 15 minute interval.
Continuous features
For continues features e.g time-to-do-job you can divide the jobs into categories of time00,time10, time20, time30 for jobs that take 0-9 minutes, 10-19 minutes, 20-29 minutes etc respectively. As before generate a time-series per division.
Depending on how much data you have and how it is distributed you can make more groups or space them differently. | {
"domain": "datascience.stackexchange",
"id": 6640,
"tags": "time-series, pandas, boosting"
} |
Twistor Function for Coulomb Field | Question: In an article by Penrose in Hughston and Ward "Advances in Twistor Theory", it is claimed that the twistor function
$$ f(Z^\alpha) = \log{\frac{Z^1Z^2 - Z^0Z^3}{Z^2Z^3}}$$
produces an anti-self-dual Coulomb field. To my knowledge this is precisely a Maxwell field with $\mathbf{B} = -i\mathbf{E}$ and $\mathbf{E} \propto \mathbf{r}/r^3$. I am trying to verify this using the contour integral formula but am getting the wrong result. Could someone point out my mistake?
Consider an anti-self-dual (ASD) Coulomb field $F$. Then we may write
$$F_{ab} = F_{AA'BB'} = \phi_{AB}\epsilon_{A'B'}$$
by a standard argument. In particular then
$$E_x = F_{01} = \frac{1}{2}(F_{00'00'} - F_{00'11'} + F_{11'00'} - F_{11'11'}) = - \phi_{01}$$
Using the usual integral formula for the Penrose transform we have
$$\phi_{01}(t,x,y,z) = \frac{1}{2\pi i}\oint \rho_x \frac{\partial}{\partial \omega^0}\frac{\partial}{\partial \omega^1} f(Z^\alpha) \pi_{E'}d\pi^{E'}$$
yielding
$$\phi_{01}(t,x,y,z) = \frac{1}{2\pi i} \oint \frac{\pi_{0'}\pi_{1'}}{(x^{10'}\pi_{0'}^2+(x^{11'}-x^{00'})\pi_{0'}\pi_{1'} - x^{01'}\pi_{1'}^2)^2} \pi_{E'}d\pi^{E'}$$
Now choosing local coordinates $\pi_{E'}=(1,\xi)$ and recalling that
$$\left(\begin{array}{cc} x^{00'} & x^{01'} \\ x^{10'} & x^{11'} \end{array}\right) =\frac{1}{\sqrt{2}} \left(\begin{array}{cc}t+x & y+iz \\ y-iz & t-x \end{array}\right) $$
we get
$$\phi_{01} = \frac{1}{2\pi i}\oint d\xi \frac{\xi}{(1/\sqrt{2}(y-iz)+\sqrt{2}x\xi - 1/\sqrt{2}(y+iz)\xi^2)^2}$$
which has double poles at
$$\xi = \frac{-\sqrt{2}x \pm \sqrt{2x^2 + 2y^2 + 2z^2}}{-\sqrt{2}(y+iz)} = \frac{x \mp r}{y + iz}$$
Denote these $\xi_1$ and $\xi_2$. Then we have (mistake here, very obviously, in hindsight!)
$$\phi_{01}(t,x,y,z) = \frac{1}{2\pi i}\oint d\xi \frac{\xi}{(\xi -\xi_1)^2(\xi - \xi_2)^2}$$
The residue at $\xi_1$ is
\begin{align*}
r_1 &= \rho_{\xi_1}\frac{d}{d\xi}\frac{\xi}{(\xi - \xi_2)^2} \\
&= \frac{1}{(\xi_1 - \xi_2)^2} -2 \frac{\xi_1}{(\xi_1-\xi_2)^3} \\
&= \frac{\xi_1 - \xi_2 - 2\xi_1}{(\xi_1-\xi_2)^3} \\
&= -\frac{x(y+iz)^2}{2r^3}
\end{align*}
It is now manifest that no contour integral will reproduce the required Coulomb field. What have I done wrong? A hint would be greatly appreciated. Many thanks in advance!
(P.S. apologies for the length of this question! Also apologies for cross-posting from MathOveflow, I just get the feeling I'm more likely to find a response here!)
Answer: I simply misfactorised the quadratic - I knew it was a stupid mistake. I'm amazed that I didn't see it, but even more amazed that nobody else did! Here is the correct solution.
$$\phi_{01}(t,x,y,z) = \frac{1}{2\pi i}\oint d\xi \frac{\xi}{(x^{01'})^2(\xi -\xi_1)^2(\xi - \xi_2)^2}$$
The residue at $\xi_1$ is
\begin{align*}
r_1 &= \rho_{\xi_1}\frac{d}{d\xi}\frac{\xi}{(x^{01'})^2(\xi - \xi_2)^2} \\
&= \frac{1}{(\xi_1 - \xi_2)^2(x^{01'})^2} -2 \frac{\xi_1}{(x^{01'})^2(\xi_1-\xi_2)^3} \\
&= \frac{\xi_1 - \xi_2 - 2\xi_1}{(x^{01'})^2(\xi_1-\xi_2)^3} \\
&= -\frac{x(y+iz)^2}{2r^3(y+iz)^2}
\end{align*}
This is now the correct answer :). | {
"domain": "physics.stackexchange",
"id": 7421,
"tags": "mathematical-physics, integration, maxwell-equations, twistor"
} |
Is it possible that the Universe is expanding due to additional Big Bang events? | Question: Is it theoretically possible that the Universe is expanding due to additional Big Bang events that have occurred at the same location that the original Big Bang occurred at?
Perhaps there has been an ongoing series of smaller Big Bang events over the past 13.7 billion years, which although were not as massive in scale as the original Big Bang, have created a large amount of new space-time and new matter that has resulted in the Universe expanding.
Answer: You may need to revisit the theory behind the Big Bang. The Big Bang is more or less a description of what the early universe looks like if you view expansion in reverse. The single "Big Bang" at the beginning of our universe is the only "Big Bang" event predicted by expansion. Also, the Big Bang did not happen in a single place, it happened everywhere in the universe. Finally, the Big Bang did not create space-time, and the expansion of the universe is not the creation of new matter. The Big Bang describes a time when the metric of space-time was extremely dense, and expansion is the metric of space-time increasing as below:
The distance between points in space increases, but the same mass-energy is there as before. | {
"domain": "astronomy.stackexchange",
"id": 3181,
"tags": "universe, astrophysics, cosmology, big-bang-theory"
} |
Time complexity of $a^{n^b}; a,b>1$ | Question: What ist the time complexitiy of an algorithm with the running time of $a^{n^b}; a,b>1$? And how is it compared to factorial complexity O(n!)?
Answer: Let's consider $n!<e\left( \frac{n}{2} \right)^n=e^{n\ln n+1-n\ln2}$. On other hand $a^{n^b}=e^{n^b \ln a}$. Now we should compare $(n\ln n+1-n\ln2)$ to $n^b \ln a$, where right member wins, when $a,b>1$:
$$\frac{n\ln n+1-n\ln2}{n^b \ln a}\to 0$$ | {
"domain": "cs.stackexchange",
"id": 17303,
"tags": "time-complexity"
} |
Is Euclidean TSP strongly NP-hard | Question: Is Euclidean TSP strongly NP-hard? What I mean is if it is NP-hard with weights specified in unary?
Can someone provide a reference?
Answer: Yes, Papadimitriou in his "The Euclidean Traveling Salesman Problem Is NP-complete" paper reduces from Exact Cover to Euclidean TSP.
All the coordinates of the points are of polynomial magnitude.
And the required precision for the $L_0$ value in page 243 is to be able to distinguish between $a$ and ${(a^2+1)}^\frac12$. And near the end of page 241, he wrote "An adequate value of $a$ is 20." So the required precision is finite. Since you only have $n(4a + 13 + 2^\frac12)$, that would only magnify the difference.
All the page numbers above are in the proceedings containing his paper and can be seen once you have downloaded the paper. | {
"domain": "cs.stackexchange",
"id": 12003,
"tags": "np-complete, traveling-salesman"
} |
JavaScript-based War card game - follow-up | Question: Original Question
I have updated my code based on feedback from other users and am submitting this question for re-evaluation.
HTML
<!doctype html>
<html lang="en">
<head>
<title></title>
<link type="text/css" rel="stylesheet" href=styles.css />
</head>
<body>
<div id="player1CurrentCard" class="card">
<div class="warDeck">
<div class="warCardsHolder"></div>
<div class="text">
<p>War Deck</p>
</div>
</div>
<div class="cardHolder"></div>
<div class="text">
<p>Player 1 Card</p>
</div>
<div id="player1CurrentDeck" class="currentDeck">
<div class="currentCardsHolder"></div>
<div class="text">
<p>Current Deck</p>
</div>
</div>
<div id="player1WonDeck" class="wonDeck">
<div class="wonCardsHolder"></div>
<div class="text">
<p>Won Deck</p>
</div>
</div>
</div>
<div id="player2CurrentCard" class="card">
<div class="cardHolder"></div>
<div class="warDeck">
<div class="warCardsHolder"></div>
<div class="text">
<p>War Deck</p>
</div>
</div>
<div class="text">
<p>Player 2 Card</p>
</div>
<div id="player2CurrentDeck" class="currentDeck">
<div class="currentCardsHolder"></div>
<div class="text">
<p>Current Deck</p>
</div>
</div>
<div id="player2WonDeck" class="wonDeck">
<div class="wonCardsHolder"></div>
<div class="text">
<p>Won Deck</p>
</div>
</div>
</div>
<button id="play">Play</button>
<button id="reshuffle">Reshuffle</button>
</body>
<script src="classes.js"></script>
<script src="war.js"></script>
</html>
CSS
.card{
position: relative;
float: left;
width: 350px;
height: 500px;
text-align: center;
}
.wonDeck{
position: absolute;
left: 100px;
bottom: 0;
width: 75px;
height: 100px;
text-align: center;
}
.currentDeck{
position: absolute;
bottom: 0;
width: 75px;
height: 100px;
text-align: center;
}
.card{
margin: 0 5%;
}
.card:first-of-type{
margin-left: 0;
}
.card:last-of-type{
margin-right: 0;
}
.card .text{
position: absolute;
margin: 0 0 0 -25%;
left: 35%;
height: 30%;
width: 50%;
font-size: 26px;
color: rgb(150, 150, 150);
}
.wonDeck .text, .currentDeck .text{
position: absolute;
margin: 0 0 0 -25%;
left: 50%;
height: 30%;
width: 50%;
font-size: 16px;
color: rgb(150, 150, 150);
}
.warDeck .text{
position: absolute;
margin: 15% 0 0 -25%;
left: 50%;
height: 30%;
width: 50%;
font-size: 16px;
color: rgb(150, 150, 150);
}
.cardHolder{
position: absolute;
top: 0;
left: 0;
width: 75%;
height: 350px;
font-size: 26px;
color: rgb(0, 0, 0);
border: 1px dashed black;
background-color: rgba(0, 0, 0, 0.5);
}
.wonCardsHolder, .warCardsHolder, .currentCardsHolder{
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
font-size: 16px;
color: rgb(0, 0, 0);
border: 1px dashed black;
background-color: rgba(0, 0, 0, 0.5);
}
.warDeck{
position: relative;
float: right;
width: 75px;
height: 100px;
}
war.js
var play = document.getElementById("play");
var reshuffle = document.getElementById("reshuffle");
var cardHolder = document.getElementsByClassName("cardHolder");
var currentCardsHolder = document.getElementsByClassName("currentCardsHolder");
var wonCardsHolder = document.getElementsByClassName("wonCardsHolder");
var warCardsHolder = document.getElementsByClassName("warCardsHolder");
window.onload = function(){
Player1 = new Player("Player 1", [], []);
Player2 = new Player("Player 2", [], []);
Deck.StartGame(Player1, Player2);
}
play.onclick = function(){
PlayGame(Player1, Player2);
}
classes.js
function Player(name, currentDeck, wonDeck){
this.name = name;
this.currentDeck = currentDeck;
this.wonDeck = wonDeck;
}
function Card(options){
this.suit = options.suit;
this.faceValue = options.faceValue;
this.cardText = (function(){
switch(this.faceValue){
case 14:
{return "Ace"};
break;
case 13:
{return "King"};
break;
case 12:
{return "Queen"};
break;
case 11:
{return "Jack"};
break;
default:
{return String(this.faceValue);}
break;
}
}).call(this);
}
Player.prototype.GetCurrentCard = function(){
this.currentCard = this.currentDeck.shift();
}
Deck = {
suits: ["Clubs", "Diamonds", "Hearts", "Spades"],
cards: [14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2],
deck: [],
shuffledDeck: [],
BuildDeck: function(){
for(var suit = 0; suit < this.suits.length; suit++){
for(var card = 0; card < this.cards.length; card++){
this.deck.push(new Card({suit: this.suits[suit], faceValue: this.cards[card]}));
}
}
},
ShuffleDeck: function(unshuffledDeck, shuffledDeck){
while(unshuffledDeck.length){
var index = Math.floor(Math.random() * unshuffledDeck.length);
shuffledDeck.push(unshuffledDeck.splice(index, 1)[0]);
}
unshuffledDeck = [];
},
DistributeCards: function(player1Deck, player2Deck){
for(var i = 0; i < this.shuffledDeck.length / 2; i++){
player1Deck.push(this.shuffledDeck[i]);
player2Deck.push(this.shuffledDeck[this.shuffledDeck.length - i - 1]);
}
},
DealWarCards: function(player, warDeck, num){
for(var i = 0; i < num; i++){
player.GetCurrentCard();
warDeck.push(player.currentCard);
}
return warDeck;
},
StartGame: function(player1, player2){
this.BuildDeck();
this.ShuffleDeck(this.deck, this.shuffledDeck);
this.DistributeCards(player1.currentDeck, player2.currentDeck);
}
}
function PlayGame(player1, player2){
var player1WarDeck = [];
var player2WarDeck = [];
function GoToWar(){
console.log("War");
Deck.DealWarCards(player1, player1WarDeck, 2);
Deck.DealWarCards(player2, player2WarDeck, 2);
console.log(player1WarDeck, player2WarDeck);
if(player1WarDeck[player1WarDeck.length - 1].faceValue === player2WarDeck[player2WarDeck.length - 1].faceValue){
console.log("Tie");
Deck.DealWarCards(player1, player1WarDeck, 2);
Deck.DealWarCards(player2, player2WarDeck, 2);
GoToWar();
}
if(player1WarDeck[player1WarDeck.length - 1].faceValue > player2WarDeck[player2WarDeck.length - 1].faceValue){
player1.wonDeck = player1.wonDeck.concat(player1WarDeck, player2WarDeck);
console.log("Player 1 wins");
}
else{
player2.wonDeck = player2.wonDeck.concat(player1WarDeck, player2WarDeck);
console.log("Player 2 wins");
}
warCardsHolder[0].textContent = player1WarDeck[player1WarDeck.length - 1].cardText +" of " +player1WarDeck[player1WarDeck.length - 1].suit;
warCardsHolder[1].textContent = player2WarDeck[player2WarDeck.length - 1].cardText +" of " +player2WarDeck[player2WarDeck.length - 1].suit;
cardHolder[0].textContent = player1WarDeck[0].cardText +" of " +player1WarDeck[0].suit;
cardHolder[1].textContent = player2WarDeck[0].cardText +" of " +player2WarDeck[0].suit;
}
if(player1.currentDeck.length === 0){
ReshuffleDeck(player1);
}
else{
player1.GetCurrentCard();
}
if(player2.currentDeck.length === 0){
ReshuffleDeck(player2);
}
else{
player2.GetCurrentCard();
}
if(player1.currentCard.faceValue > player2.currentCard.faceValue){
player1.wonDeck.push(player1.currentCard);
player1.wonDeck.push(player2.currentCard);
}
else{
player2.wonDeck.push(player2.currentCard);
player2.wonDeck.push(player1.currentCard);
}
if(player1.currentCard.faceValue === player2.currentCard.faceValue){
player1WarDeck.push(player1.currentCard);
player2WarDeck.push(player2.currentCard);
GoToWar();
}
else{
cardHolder[0].textContent = player1.currentCard.cardText +" of " +player1.currentCard.suit;
cardHolder[1].textContent = player2.currentCard.cardText +" of " +player2.currentCard.suit;
currentCardsHolder[0].textContent = player1.currentDeck.length;
currentCardsHolder[1].textContent = player2.currentDeck.length;
wonCardsHolder[0].textContent = player1.wonDeck.length;
wonCardsHolder[1].textContent = player2.wonDeck.length;
warCardsHolder[0].textContent = "";
warCardsHolder[1].textContent = "";
}
if(player1.currentDeck.length === 52){
GameOver(player1);
}
if(player2.currentDeck.length === 52){
GameOver(player2);
}
}
function ReshuffleDeck(player){
Deck.ShuffleDeck(player.wonDeck, player.currentDeck);
}
function GameOver(player){
console.log(player.name +" wins!");
}
Final Submission
Answer: 1) Default your player initialization values so you don't have to pass in empty arrays.
function Player(name, currentDeck, wonDeck){
this.name = name;
this.currentDeck = currentDeck != undefined && currentDeck instanceof Array ? currentDeck : [];
this.wonDeck = wonDeck != undefined && wonDeck instanceof Array ? wonDeck: [];
}
var player1 = new Player("Player 1");
2) PlayGame, ReshuffleDeck, and GameOver are not classes, and thus should not be in classes.js
3) I intentionally omitted the break statements from the switch cases I recommended in your first post - the reason for this is that return will return from the function immediately, and thus will not fall through to the next case. Putting a break after a return statement is unreachable code and is unnecessary.
4) Not that it really matters in this particular instance, but getting the currentCard using .shift() grabs you the first item in the array, which would essentially be grabbing from the bottom of your stack of cards. .pop() would grab the card "on top". | {
"domain": "codereview.stackexchange",
"id": 24435,
"tags": "javascript, object-oriented, playing-cards"
} |
Why are syntax trees used in genetic programming? | Question: Reading a course on genetic programming, the first chapter describes the syntax tree as the basic representation of programs in genetic programming.
What are the reasons leading to the choice of a syntax tree in genetic programming? Are there any particular assets in using this representation?
Answer: In short: AST representations of programs are more easily analyzed,
manipulated, and transformed, while preserving and enforcing the existence of a
formally defined program meaning through the transformations.
I am asssuming that the reader knows already what is an abstract syntax tree (AST), and does not need to be shown examples.
The question is an issue about abstract objects (semantics) and their
representations (syntax). We are usually interested in the semantics,
applying transformations to entities to change or combine their
meanings, their semantics, which can belong to all kinds of domains.
But semantics is elusive, mathematical abstraction, and all we can
actually manipulate to express our intent is syntax representations.
That is the basis of all programming, but is also to be found in
logic, proofs, and finally all of mathematics. That is what makes the
choice of representations and notations often so important. Good choice
of representation will lead to easier, possibly more perspicuous or
intuitive understanding of the problem and be better adapted at
expressing answers, and proofs, for given questions.
The point is well known to programmers, as they are taught that it is essential to
choose the right data structure in order to implement an algorithmic
solution to a given problem. The choice of data structure is the choice of
representation. And I just made a similar answer to a question on
constructing (programming?) Turing Machines.
Note that there is a partially ambiguous use of the word syntax, which
can be any concrete representation of an abstraction, or can be
intended to mean only textual representation as strings (we are
getting close to Turing machines), possibly structured by some logical
system (a context-free (CF) grammar for example that specifies what
are the legitimate strings, the well-formed-strings.
In fact, the existing parsing-unparsing technology, especially for CF
grammars, makes it generally easy to switch between textual and an
associated tree representation, to the point that they are often not
distinguished much. Actually, mathematicians have been using tree
representation (formally defined as Algebras), long before that
technology existed, and this is what lead to using the representation of AST
in manipulating programs.
So what was so convenient about these tree (or AST) representations?
The key points are:
it is very convenient for associating precisely
semantic meaning to syntactic constructs, in a compositional way, by means of a simple
mathematical concept: the homomorphism;
it provides and enforces a syntactic type system (statement, expression, ...) that preserve the existence of some meaning when the program representation is transformed in a way that preserves the syntactic typing constraints;
it is easily manipulated to actually perform analysis and transformations;
it is easy to decorate it with localized information to help or guide these analyses and transformations.
First, if you take a string representation of a program, without
further structural information, there is no simple way to delimit
substrings that have naturally a meaning of their own (I am saying
naturally, because some people may always try to play at abstracting
syntactic context or indulge in syntactic (text oriented) continuation games - ignore this if
you do not get it).
The idea of a tree structure, with nodes labeled with operators, possibly
restricted by syntactic types (statement, expression, variable, ...)
is that they naturally decompose the syntactic structure into subparts
(the subtrees) that can have fairly naturally, and perspicuously with
respect to computational concepts, a semantic meaning of their own.
Then, if we associate a semantic function to each operator, we can get
the meaning of a tree representation by applying the semantic function
of the root operators to the semantic meaning of each of its subtrees.
If we also provide some semantics to leafs operators (which may be
defined as a mapping from syntactic representations to some semantic
domains possibly by other means, for example associating the integer
23 to the string "23"), we know how to define simply the semantics
of any well-formed tree, whether complete program or well-formed
program fragment. This is the basis of what is known as denotational semantics.
In other word, the homomorphism thus defined gives a rather simple and
tractable way to associate meaning to well-formed program fragments, by composing the meanings of its well-formed sub-fragments (this is known as semantic compositionality).
Then, it becomes much easier to attempt defining semantically
meaningful transformations. And semantics, what the program (fragment)
does is what we really care about.
Furthemore, AST are fairly easy to manipulate by programs to express these transformations that somewhat respect the semantic structure (as they manipulate subtrees that are semantically meaningful), which initially justified their use in program editors, program manipulation systems, and programming environment.
Actually, the concept of AST in programming appeared with the language
Lisp (and its ability to manipulate Lisp programs syntactically) in
the very late fifties. But it developed mostly in the seventies (Emily, Cornell synthesizer, Mentor/Centaur), and further in the eighties, at the
same time as denotational semantics (which is based on the above
approach), and most likely under the influence of denotational
semantics. The early work (LCF) on automated proofs about computation may also have been influencial.
From the point of view of genetic programming, the use of AST both facilitates and enforces the
creation of syntactic structures that are more likely to have some
meaning. Manipulating unstructured string representations would be
likely to result in being swamped with string representations to which
no meaning can be associated.
Another advantage of AST representations is that they are fairly easy
to decorate with additional information: precomputed semantic
properties, weights, or whatever is deemed useful for the intended
program transformation or manipulation, including genetically programed transformations.
A detailed example
This section has been added later to answer some comments.
I will try to work out one example in some details to explain the
relation between manipulations on the AST and their semantics
conterpart.
We take a very simple example of crossover between two ASTs:
T1=foo(exp1,exp2) and T2=bar(exp3, exp4). I keep it small for
readability. Actually, exp1 to exp4 are meant to be subtrees of
some AST, while you may also see what is around them as standing for
the rest of some AST (or some AST subtree) that is the context in
which they occur.
We suppose first that the language does not have typing (in the usual
sense of programing languages), and accept any value in any context
expecting a value, so that any expression can legitimately replace any
other.
Then given T1 and T2, it is legitimate to apply a crossover that swaps
exp1 and exp4, thus producing T1'=foo(exp4,exp2) and
T2'=bar(exp3, exp1). Note that the algorithm could also consider
only one of these two trees (I am incompetent regarding genetic
splicing strategies).
Now, let us see what can be said about semantics, without getting too
much into details.
Let $S$ be the semantic function, $V$ the domain of values, $M$ the
domain of environments that map identifiers to values. The semantics
$S$(exp) of an expression exp is a function $e: M\to V$ that takes
an environment $m$ as argument (so that we have values for
identifiers) and returns the value of the expression in that
environment.
Now, if the operators foo and bar are supposed to compute
respectively two functions $f$ and $b$ on their arguments,
the semantics of T1, for example, will be defined as
$S$(foo(exp1,exp2))=$S$(foo)($S$(exp1),$S$(exp2))=$\lambda m.f(e_1(m),e_2(m))$
You notice that the semantic function is not necessarily easy to define in the
complex case of a programming language, since for foo we have here
$S$(foo)=$\lambda e, e', m\,.\, f(e(m), e'(m))$.
This complexity results from the choice of the Abstract Syntax, that
considers here foo and bar as AST operator nodes. Instead, the AST
could have a call operator that has several daughters, for example
as in call(foo, exp1, exp2). Then the complexity of dealing with the
environment $m$ would be factorized in the semantics of call, while
the semantics of foo would simply be the function $f$.
Sorry for this complexity.
The whole point is that we can define the semantics of an AST subtree
such as exp1 independently of any context, but as a
function $e_1$. Whatever information it needs from the context to be
evaluated is summarized in the arguments (here the environment $m$)
that are passed to its semantics. And this information is in turn
passed to the semantic functions associated to subexpressions.
So now we know that a subtree of AST can have a well defined
semantics, independently of its context.
But what about the context? Does it have a well defined semantics when
a subtree is missing. The nice point is that it does.
If you consider the context foo(??,exp2), what can its semantics be.
The natural answer is that it is whatever semantics it would have if
you provided the missing part. In other words, it is a functional
semantics that takes as argument the semantics of the missing part.
This is very similar to the semantics of the complete expression
$S$(foo(exp1,exp2)) that we defined above, except that the missing
exp1 must be accounted for with an argument $e$ standing for the
semantics of whatever expression could replace exp1.
We had $S$(foo(exp1,exp2))=$\lambda m.f(e_1(m),e_2(m))$
So, without going into further details, you have
$S$(foo(??,exp2))=$\lambda e.\lambda m.f(e(m),e_2(m))$
Then, given that $S$(exp1)=$e_1: M\to V$,
we have
$S$(foo(exp1,exp2))= $S$(foo(??,exp2))($S$(exp1))
which is precisely what we would like: syntactic abstraction directly
translate into semantic abstraction.
Then we also have, of course:
$S$(foo(exp4,exp2))= $S$(foo(??,exp2))($S$(exp4))
In other words, both AST subtrees and AST contexts (of subtree) have
well defined semantics, that do not change, and they compose to give
the semantics of the whole AST tree when a subtree is placed in a
permitted context.
But of course: $S$(foo(exp1,exp2)) $\neq$ $S$(foo(exp4,exp2))
I hope this explains how things work. Using well-formed AST will
ensure that you are actually manipulating semantic fragments that
compose meaningfully.
Actually, things may be a bit more complicated, because you want to
include in the process what is usually called static semantics,
i.e. constraints on the AST that are usually checked at compile time.
The best known examples are type constraints for statically typed
languages, or declaration of identifiers when that is required. Thus
you may want to decorate ASTs with this statically computable
information, and use splicing techniques that will incrementally
preserve the information and check the required constraints on the AST, so that you produce only programs that at least compile.
Then as a last comment, I would like to remarks that linear genetic
programming seems to be doing pretty much the same, but restricts
splicing to sequences of statements, so that there is always some
executable semantics preserved. But I am not specialist of that. | {
"domain": "cs.stackexchange",
"id": 4702,
"tags": "algorithms, semantics, genetic-algorithms, syntax-trees, syntax"
} |
Robot_localization: odometry/gps no output info | Question:
Hi, I am working with robot localization in ubuntu 16.04. I am using bags files with IMU and two GPS. However the IMU data don't give me info about the orientation, so I use mine /get_orientation node to obtain the orientation with the two GPS, getting the robot orientation.
The ekf outputs are working, i am not sure if fine but at least is giving some output. However the problem is the navsat_transform_node wich its output is all zero. So I am not sure where is the problem in that node.
I add the files:
fix_back(gps):
header:
seq: 2733
stamp:
secs: 1455210306
nsecs: 652417898
frame_id: "gps"
status:
status: 1
service: 1
latitude: 42.1819562283
longitude: -8.73968366
altitude: 384.671
position_covariance: [1000000000000.0, 0.0, 0.0, 0.0, 1000000000000.0, 0.0, 0.0, 0.0, 16000000000000.0]
position_covariance_type: 0
/imu/data:
header:
seq: 145690
stamp:
secs: 1455210324
nsecs: 134030103
frame_id: "base_imu"
orientation:
x: 0.0
y: 0.0
z: 0.0
w: 0.0
orientation_covariance: [-1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0]
angular_velocity:
x: -0.0156264220278
y: 0.0181547511189
z: 0.0154273617187
angular_velocity_covariance: [0.0004, 0.0, 0.0, 0.0, 0.0004, 0.0, 0.0, 0.0, 0.0004]
linear_acceleration:
x: 0.0415387526155
y: -0.0178170949221
z: 0.0885146409273
linear_acceleration_covariance: [0.0004, 0.0, 0.0, 0.0, 0.0004, 0.0, 0.0, 0.0, 0.0004]
/get/orientation(topic with orientation wich is subscribed navsat node):
header:
seq: 1644
stamp:
secs: 1455210302
nsecs: 894764900
frame_id: "base_imu"
orientation:
x: 0.0
y: 0.0
z: 0.778295047494
w: 0.627898733114
orientation_covariance: [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
angular_velocity:
x: 0.0
y: 0.0
z: 0.0
angular_velocity_covariance: [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
linear_acceleration:
x: 0.0
y: 0.0
z: 0.0
linear_acceleration_covariance: [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
/odometry/gps:
I think that maybe the problem is in de frame id
header:
seq: 2691
stamp:
secs: 1455210292
nsecs: 652157068
frame_id: "odom"
child_frame_id: ''
pose:
pose:
position:
x: 0.0
y: 0.0
z: 0.0
orientation:
x: 0.0
y: 0.0
z: 0.0
w: 1.0
covariance: [1000000000000.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1000000000000.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 16000000000000.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
twist:
twist:
linear:
x: 0.0
y: 0.0
z: 0.0
angular:
x: 0.0
y: 0.0
z: 0.0
covariance: [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
/odometry/filtered:
header:
seq: 51683
stamp:
secs: 1577439407
nsecs: 801655531
frame_id: "odom"
child_frame_id: "base_link"
pose:
pose:
position:
x: 156563.13445
y: -43035.340716
z: 0.0
orientation:
x: 0.0
y: 0.0
z: 0.687894745035
w: 0.725810457181
covariance: [4.999999991019117e-10, 1.8213410266344878e-19, 0.0, 0.0, 0.0, 2.7155029258938172e-18, 1.8213410266344009e-19, 4.999999999627129e-10, 0.0, 0.0, 0.0, -4.734606596713057e-19, 0.0, 0.0, 4.99999999319995e-07, -1.4343813184271704e-13, -5.537703876135997e-14, 0.0, 0.0, 0.0, -1.4343813184271712e-13, 4.999532936965985e-07, -1.1681062864961878e-11, 0.0, 0.0, 0.0, -5.537703876135998e-14, -1.168106286496188e-11, 4.999790403984765e-07, 0.0, 2.7155029258938396e-18, -4.734606596713306e-19, 0.0, 0.0, 0.0, 4.999999685207372e-10]
twist:
twist:
linear:
x: 376.337918185
y: -1026.94096739
z: 0.0
angular:
x: 0.0
y: 0.0
z: 0.160520859566
covariance: [3.6023855883949554, 1.204648214979867, 0.0, 0.0, 0.0, 0.0017902513769453227, 1.2046482149798612, 0.7431464414456158, 0.0, 0.0, 0.0, 0.000144190040518795, 0.0, 0.0, 4.999876641741591e-07, -2.8393491075641632e-15, -1.1267194434469995e-15, 0.0, 0.0, 0.0, -2.839349107564164e-15, 4.999493611311244e-07, -1.188802486830638e-13, 0.0, 0.0, 0.0, -1.126719443447e-15, -1.1888024868306388e-13, 4.9994961353661e-07, 0.0, 0.001790251376945311, 0.00014419004051858424, 0.0, 0.0, 0.0, 0.03574059011903692]
Now configuration files:
ekf_template.yaml:
frequency: 30
sensor_timeout: 0.1
two_d_mode: true #false zona plana
transform_time_offset: 0.0
transform_timeout: 0.0
print_diagnostics: true
debug: false
debug_out_file: /path/to/debug/file.txt
publish_tf: true
publish_acceleration: false
map_frame: map # Defaults to "map" if unspecified
odom_frame: odom # Defaults to "odom" if unspecified
base_link_frame: base_link # Defaults to "base_link" if unspecified
world_frame: odom # Defaults to the value of odom_frame if unspecified
odom0: /get_orientation/odometry #position + orientation
odom0_config: [true, true, true,
true, true, true,
false, false, false,
false, false, false,
false, false, false]
odom0_differential: false
odom0_relative: true
odom0_nodelay: false
odom0_queue_size: 5
odom1: /odometry/gps #gps in UTM
odom1_config: [true, true, true,
false, false, true,
false, false, false,
false, false, false,
false, false, false]
odom1_nodelay: false
odom1_differential: false
odom1_relative: true
odom1_queue_size: 5
pose0: /get_orientation/pose_covariance #position + orientation
pose0_config: [true, true, true,
true, true, true,
false, false, false,
false, false, false,
false, false, false]
pose0_nodelay: false
pose0_differential: false
pose0_relative: true
pose0_queue_size: 5
imu0: /imu/data #imu data
imu0_config: [false, false, false,
true, true, true,
false, false, false,
true, true, true,
true, true, true]
imu0_nodelay: false
imu0_differential: false
imu0_relative: true
imu0_queue_size: 5
imu1: /get_orientation/imu_orientation #orientation + imu data
imu1_config: [false, false, false,
true, true, true,
false, false, false,
false, false, false,
false, false, false]
imu1_nodelay: false
imu1_differential: false
imu1_relative: true
imu1_queue_size: 5
imu0_remove_gravitational_acceleration: false
use_control: false
stamped_control: true #false
control_timeout: 0.5
control_config: [false, false, false, false, false, false]
acceleration_limits: [100.0, 0.0, 0.0, 0.0, 0.0, 1.0]
deceleration_limits: [100.0, 0.0, 0.0, 0.0, 0.0, 1.0]
acceleration_gains: [0.2, 0.0, 0.0, 0.0, 0.0, 0.5]
deceleration_gains: [0.2, 0.0, 0.0, 0.0, 0.0, 0.5]
process_noise_covariance: [0.05, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0.05, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0.06, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0.03, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0.03, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0.06, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0.025, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0.025, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0.04, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0.01, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.01, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.02, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.01, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.01, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.015]
initial_estimate_covariance: [1e-9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 1e-9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 1e-9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 1e-9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 1e-9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 1e-9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 1e-9, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 1e-9, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 1e-9, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 1e-9, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1e-9, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1e-9, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1e-9, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1e-9, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1e-9]
navsat_transform_template.yaml:
frequency: 30
delay: 3.0
magnetic_declination_radians: 0
yaw_offset: 0.0
zero_altitude: false
broadcast_utm_transform: false
broadcast_utm_transform_as_parent_frame: false
publish_filtered_gps: true #false
use_odometry_yaw: false
wait_for_datum: false
datum: [55.944904, -3.186693, 0.0, map, base_link]
The launch of both nodes:
ekf_tamplate.launch:
<launch>
<node pkg="robot_localization" type="ekf_localization_node" name="ekf_se" clear_params="true">
<rosparam command="load" file="$(find robot_localization)/params/ekf_template.yaml" />
</node>
<!-- TF'S -->
<node pkg="tf2_ros" type="static_transform_publisher" name="back_broadcaster"
args="-40.0 0.0 0.0 0.0 0.0 0.0 1.0 base_link gps_back" respawn="true" />
<node pkg="tf2_ros" type="static_transform_publisher" name="imu_broadcaster"
args="30.0 0.0 0.0 0.0 0.0 0.0 1.0 base_link base_imu" respawn="true" />
<node pkg="tf2_ros" type="static_transform_publisher" name="front_broadcaster"
args="40.0 0.0 0.0 0.0 0.0 0.0 1.0 base_link gps_front" respawn="true" />
</launch>
navsat_transform_template.launch
<launch>
<node pkg="robot_localization" type="navsat_transform_node" name="navsat_transform_node" clear_params="true">
<rosparam command="load" file="$(find robot_localization)/params/navsat_transform_template.yaml" />
</node>
</launch>
Here I uploaded the picture of rqt_graph wich maybe give some info to help.
https://www.dropbox.com/s/8yyi8ahkrumyd5x/rosgraph.png?dl=0
I think that this is the most important info to show you, if somebody need some additional info, ask me for them.
Thank you to everybody.
Originally posted by sergiootero on ROS Answers with karma: 26 on 2019-12-27
Post score: 0
Original comments
Comment by Tom Moore on 2020-01-06:
Where are you telling navsat_transform_node to listen to your new orientation topic? I don't see a remap.
Answer:
Hi Tom, I think i found the problem and it was that I had to change a frame_id I wasn´t see.
Thank you for your response, I'll continue trying
Originally posted by sergiootero with karma: 26 on 2020-01-13
This answer was ACCEPTED on the original site
Post score: 1
Original comments
Comment by Briant on 2021-01-18:
Hi,Sergiootero,I just met the same problem,how did you solve this,appreciate it if you could reply when you see it | {
"domain": "robotics.stackexchange",
"id": 34202,
"tags": "ros, navigation, ros-kinetic, navsat-transform-node, robot-localization"
} |
If gravity disappeared, would Newton's third law make everything that was pressed to the ground by gravity get pushed upwards? | Question: If gravity disappeared, would Newton's third law make everything that was pressed to the ground by gravity get pushed upwards?
Answer: As other answers explain, Newton's third law wouldn't push you upwards, because reaction disappears as soon of action (gravity) vanishes.
However, we need to keep in mind that we are siting on several thousand kilometres of rock heavily compressed by its own weight. If weight suddenly disappears, that rock will react like a spring and project itself and anything in the surface at very high speed to space. In fact, even the most conservative ballpark estimates of the elastic deformation of Earth in its present state are in the order of several kilometres, so that's the quite instant rebound we can expect. | {
"domain": "physics.stackexchange",
"id": 53267,
"tags": "newtonian-mechanics, forces, newtonian-gravity, free-body-diagram, planets"
} |
Is the Ising magnet relevant for magnets? | Question: To what extent is the Ising model for the ferromagnetic transition experimentally relevant for real ferromagnets ?
For example if one quantitatively compares the magnetization versus temprature data rescaled by the critical points, do the data match with Ising scaling ?
Any hints to compilations of data or comparisons would be appreciated.
Answer: The Ising model is rather too crude a model to be of relevance to most real magnets. There are however systems well described by it (or by some suitable extensions); see, for instance, The Ising model and real magnetic materials, W. P. Wolf, Braz. J. Phys. 30 (4), 2000.
The Ising model is actually better as a model for a fluid, a binary alloy or an adsorbed monolayer at a surface, for instance... The fact that this model has a large number of physically completely different interpretations is a consequence of its very simple and generic form (Bernoulli random variables locally coupled with a quadratic interactions).
Of course, if you are interested in a specific magnet, then you'd probably need to incorporate a lot of additional structure to the model. | {
"domain": "physics.stackexchange",
"id": 97073,
"tags": "statistical-mechanics, condensed-matter, ferromagnetism"
} |
Does Newton's Law of Universal Gravitation work when particles are very close? | Question: By Newton's Law of Universal Gravitation, the gravitational force between two particles is $Gm_1m_2/r^2$. Let's assume that the numerator is constant and happens to equal $1$.
Imagine that two particles that meet the above assumption are near each other in a vacuum. As they are colliding, the distance between them will at some point equal a Planck length. The force between them will then be: $1 /( 1.6 \times 10^{-35})^2\ \text{N}$. This is about $4\times 10^{69}\ \text{N}$.
Why doesn't this really happen?
Answer: I think the only issue with your scenario is using Newton's law of gravity to calculate the value of the attractive force between the particles. There is no reason to think that this situation 'cannot' happen.
In the situation you've described, each particle has a mass of $122,406 \text{ }\mathrm{kg}$, which yields a Schwarzschild radius of $1.818\times10^{-22} \text{ }\mathrm{m}$. But the Plank length is considerably smaller, at $1.616\times10^{-35} \text{ }\mathrm{m}$. To be within one Plank length of each other, they would both need to be black holes, with each singularity inside the other's event horizon (in addition to its own, of course). In other words, this scenario involves two black holes merging together. We seem to be well beyond the range of validity for Newtonian gravity.
Can two singularities get this close to one another? I guess so. Interpreted literally, a 'singularity' in GR is a true point particle. | {
"domain": "physics.stackexchange",
"id": 48758,
"tags": "newtonian-mechanics, forces, newtonian-gravity, singularities"
} |
how to go from a stabilizer state to a graph | Question: A comment (by Marcus Heinrich) in a
previous post says :
"any stabiliser state is locally Clifford equivalent to a graph state and vice versa".
I can go from a graph (defined by its adjacency matrix) to a set of stabilizers and the corresponding state. My question is for the other direction : if I have a set of stabilizers that define a $[[n,0,d]]$ code; is there a procedure to get an adjacency matrix that would correspond to it?
Answer: See this paper for a proof, but I will sumamrize the idea below.
Suppose you have a stabilizer state $|\psi\rangle$ and a set $\mathcal{S}$ of Paulis that generate its stabilizer group, $\langle S \rangle$.
You can represent the generators by a pair of matrices, $X$ and $Z$, such that $X[i, j] = 1$ if the $i$-th generator has a tensor factor of $\sigma_x$ in the $j$-th position.
For example, if you have generators $\sigma_x \otimes \sigma_x$ and $\sigma_z \otimes \sigma_z$ for the bell state, then the matrix you obtain is $X = \begin{pmatrix} 1 & 1 \\ 0 & 0 \end{pmatrix}$ and $Z = \begin{pmatrix} 0 & 0 \\ 1 & 1\end{pmatrix}$. Of course, you can always choose different generators, so this depiction is not unique.
If you do this procedure for a graph state $|G\rangle$ by using the natural generators of the stabilizer group of the graph state, you always obtain matrices where $X$ is identity, and $Z$ is exactly the adjacency matrix of the graph.
The claim now is: We can take any two matrices $X$ and $Z$ that encode a stabilizer group, and transform them into $X = I$ and $Z$ into a adjacency matrix.
This is done using something similar to a binary RREF procedure, where the binary addition of two rows is like multiplying two group generators to form a new group generator, or by swapping columns of the two matrix via conjugation by $H$ gate. This way, we can reduce $X$ matrix, obtaining identity, and it can be shown that $Z$ becomes symmetric. There are some additional details, but due to the structure of the matrices, we can always obtain an $X$ and $Z$ of this form. | {
"domain": "quantumcomputing.stackexchange",
"id": 5254,
"tags": "stabilizer-code, stabilizer-state, graph-states"
} |
Naked singularity: how would it behave? | Question: We know that the theory of cosmic censorship prevent singularities from existing without an event horizon that hides them from the Universe. Now let's assume that this theory is somehow false, and a naked singularity appears in the solar system. How would we notice it for the first time, what would it look like, how would it behave and could we use it for someting useful?
Answer:
We know that the theory of cosmic censorship prevent singularities from existing without an event horizon that hides them from the Universe.
We don't really know whether cosmic censorship is true or false. It isn't even clear how to state it rigorously as a hypothesis. For some info on the current state of CC, see this question. There are serious suggestions that gravitational collapse may in some cases result in the formation of a naked singularity.
Now let's assume that this theory is somehow false, and a naked singularity appears in the solar system. How would we notice it for the first time, what would it look like, how would it behave and could we use it for someting useful?
A naked singularity's very definition makes it impossible for GR to say how it would look or predict how it would behave. A singularity is by definition a situation you get when geodesics are incomplete. So for example, if a ray of light hits a singularity, by definition we can't use GR to trace the ray through the singularity and see where it goes when it emerges. More generally, naked singularities can in general emit arbitrary information and unlimited energy (in GR). That means that we can't use GR to predict what comes out of them (without even worrying about tracing rays through them). This is shown by John Earman's memorable figure and caption below:
The worry is illustrated in Fig. 3.1 where all sorts of nasty things -- TV sets showing Nixon's 'Checkers' speech, green slime, Japanese horror movie monsters, etc. -- emerge helter-skelter from the singularity.
The reason that GR can't predict what comes out of the naked singularity is simply that we can't even formulate the initial conditions in an appropriate way, because a Cauchy surface doesn't exist. For more on this, see this question.
If a naked (timelike) singularity did exist, then GR might be able to tell us about light rays that passed near it but not too close. That is, we might be able to construct a partial Cauchy surface, which might be good enough to tell us, for example, what distortions we would see in the background of stars. We would probably expect the large-distance behavior of such a spacetime to be characterizable just by its mass and angular momentum (assuming it doesn't have weird properties like the kind of topological behavior you get in things like Taub-NUT spacetimes), in which case the part of the sky far enough away from the singularity would probably look approximately like what you would get with a Kerr black hole. I would not expect to be able to extend this to regions very close to the singularity, where you would have closed, timelike curves, and therefore wouldn't even be able to formulate initial conditions for an optical simulation. | {
"domain": "physics.stackexchange",
"id": 59996,
"tags": "general-relativity, causality, singularities, time-travel"
} |
Representations of the Dirac algebra, hermitian adjoint and traces | Question: Strictly speaking this is a math question, but since the Dirac algebra is much more important in physics than in math I thought I'd have a better chance of getting an answer here.
The Dirac algebra can be defined as the Clifford algebra associated to the Minkowski metric. In physics texts it is not always clear if the real or the complex Clifford algebra is meant, I would say that morally it's the real one, but strictly speaking the complex one. The latter is isomorphic to the algebra of $4\times 4$ complex matrices, but not in a canonical way. By the Skolem-Noether theorem (and probably in some more elementary way as well) we see that all such isomorphisms are conjugate, and even that all complex representations of the real Dirac algebra (which is simple) are conjugate.
Now in physics texts the Dirac algebra is often defined to be an algebra of $4\times 4$ matrices, but with a representation of $\Bbb R^{1,3}$ contained within it, in the form of the four (unspecified) matrices $\gamma^\mu$.
In that context, there are obvious definitions of the trace and the Hermitian adjoint, namely as the trace and the Hermitian adjoint of the matrix. By the remark above and the fact that the trace is invariant under conjugation, we see that the trace is well-defined on the abstract algebra level. Of the Hermitian conjugate that is not so clear (I don't know if it's true).
This is unsatisfactory for several reasons:
We do really want to work with different representations, so it would be nice if we could define the trace in a way that is independent of a specific representation, or maybe some canonical representation like the regular representation or (even better) if there is some canonical 4-dimensional space on which it acts.
It doesn't work so well for other spaces $\Bbb R^{1,d}$.
Things like the trace identities are messy and hard to memorize.
My questions:
Does this only work well in $\Bbb R^{1,3}$?
Is it more correct or useful to view the Dirac algebra as the real or the complex Clifford algebra?
Is there a canonical, or representation-independent definition of the trace? Ideally one that works for all Clifford algebras.
Is there a canonical definition of the Hermitian adjoint, or maybe a Hermitian inner product?
Can the Dirac equation or more a Dirac spinor field be conveniently interpreted in terms of the abstract Dirac algebra without any explicit reference to a 4-dimensional representation of it?
EDIT
It isn't hard to show that the Dirac algebra has a unique anti-involution which I'll denote $\ast$ that satisfies $\gamma^{\mu\ast} = g^\mu_{\ \ \nu}\gamma^\nu$. If we call this the Hermitian adjoint, this would say that $\gamma^0$ is Hermitian, and $\gamma^i$ is anti-Hermitian. We could then demand that in a matrix representation, these map to a Hermitian and anti-Hermitian matrices. However, this is not automatic: it doesn't follow from the algebraic structure that this must be the case, and must be seen as an additional requirement on a representation of the Dirac algebra.
To be explicit, one could consider the real Clifford algebra or $\Bbb R^{1,1}$. This can be mapped isomorphically onto $\mathcal M_2(\Bbb R)$ in such a way that $\gamma^0$ is symmetric and $\gamma^1$ is antisymmetric. It can also be mapped onto a subalgebra of $\mathcal M_2(\Bbb C)$ in such a way that $\gamma^0$ is Hermitian, and $\gamma^1$ is anti-Hermitian.
Answer: Actually, your claim about "different representations" is kind of misplaced: We do not need to worry about different representations of the Clifford algebra, because it has at most two non-isomorphic irreducible representations, and those have the same dimensions. See, for example, this question and this question. However, we may choose different realizations of these representations as matrices, e.g. Weyl basis vs. Majorana basis.
You cannot define a trace or a Hermitian conjugate on the algebra itself because both the trace and the Hermitian conjugate are properties of a representation. Famously, the trace in a particular representation is called the character and an important tool to distinguish representations. This is usually done for groups, but since the spin and pin groups sit within the Clifford algebra, this applies equally well here.
Likewise, the abstract Clifford algebra does not carry a Hermitian product. The proper abstract definition of the (real) Clifford algebra in dimension $d= p+q$ is as the quotient of the tensor algebra $\bigoplus_{i = 0}^\infty \left(\mathbb{R}^d\right)^{\otimes i}$ modulo the relation $v\otimes v = \eta^{\mu\nu}v_\mu v_\nu$ where $\eta$ is the metric with signature $(p,q)$. It's a non-trivial (but not so hard) fact that all its representations are "pseudo-unitarizable" in the sense that we can choose a Hermitian product on the representation such that the Hermitian adjoint of all $\rho(\gamma^\mu)$ is $\eta_{\mu\mu}\rho(\gamma_\mu)$ (no summation convention), where $\eta$ is our spacetime metric.
Lastly, the Dirac algebra is just a tool to construct spinor representations, it is not the fundamental thing under which spinors transform. The crucial thing is that the second degree of the Clifford algebra contains the Lorentz algebra, so the representations of the Dirac algebra induce representations of the Lorentz algebra, and it's easier to find the (few) representations of the Dirac algebra than those of the Lorentz algebra. In particular, the Weyl and Majorana representations that exist in certain dimensions and signatures are not representations of the Dirac algebra (the full Dirac representation of dimension $2^{\lfloor d/2\rfloor}$ is always irreducible as a representation of the Clifford algebra), but only of the Lorentz algebra. The split into Weyl subrepresentations is the split into two eigenspaces of the top degree of the Clifford algebra, which represents parity, and the split into Majorana representations is rather complicated in arbitrary signature but has to do with the existence of so-called real structures.
Therefore, to expect the spinors to transform "abstractly" under the Clifford algebra is physically misguided - what we are actually after are representations of the Lorentz algebra $\mathfrak{so}(p,q)$. | {
"domain": "physics.stackexchange",
"id": 35263,
"tags": "representation-theory, dirac-equation, dirac-matrices, trace, clifford-algebra"
} |
Is there any chance we could eventually observe the supernova of the first (Population III) stars | Question: In an answer to my previous question about the first stars it was stated they probably formed at Z=20 to Z=60 and may have had a mass between tens to 100s to 1000s of times the mass of the Sun.
Given that, what would the dominant wavelength of the light emitted by these supernova and approximately how bright would they be in the reference frame of the supernova?
What would the wavelength and brightness of those supernova be if we observed them today?
Is there any chance that a current telescope, a planned telescope or a reasonably potentially possible future telescope could detect these supernova?
For this telescope, would the field of view be so narrow that we would be unlikely to ever see one of those supernova in a reasonable time?
Answer: The short answer is probably "yes we can", and possibly "we've already seen supernovae from the first galaxies", in the form of long-duration gamma-ray bursts. GRB 090429B has been given a redshift z=9.4, beating the previous record-holder GRB 090423 at z=8.2. As we continue to watch the skies, we're seeing more and more of these objects, and we'll gradually push back the boundary. I don't know what sets the upper limit on how far away we can see GRBs but I don't think it's a coverage problem: Swift covers something like a tenth of the sky.
Note that despite the high redshifts, they're probably not quite high enough to be the first stars. If someone reported a long GRB at z=15, then I'd think it more likely.
I'm not an observer, so I'm not sure about what colours and magnitudes are usually associated with supernova, but I can try. With a bit of Googling, Daniel Kasen's page suggests that they're relatively bright in most bands. Off the top of my head, I think we see them most in optical, but that might just be a selection effect. I think, until now, we've been finding Type Ia supernova up to about z=1.5. That boundary is being pushed, but I'm not sure how. (Possibly improved IR spectroscopy from a Hubble servicing?) The overall brightness of supernovae is of the order of 10$^{51}$ ergs. Type Ia's have typical absolute visual magnitude -19.3, according to Wiki.
As for other types of supernova, I suspect that as you move further out, isolating a single supernova in a low-resolution galaxy image is a major obstacle, but that's pure speculation on my part. That is, the supernova needs to be significantly brighter than the surrounding galaxy. Fortunately, I think this is the case for GRBs, but I'm doubt it for other supernova.
I'm much less knowledgable on this than my previous answer, so I welcome corrections. | {
"domain": "physics.stackexchange",
"id": 18437,
"tags": "astronomy, cosmology, supernova"
} |
How do I derive the Feynman rules for graviton-photon coupling? | Question: I am trying to study the coupling of the graviton field $h_{\mu\nu}$ to the electromagnetic field $A_\mu$ with respect to the following action:
$$ S_M = \int d^4x \ \sqrt{-g} \ (-\frac 1{4} g^{\mu\nu} g^{\rho\sigma} F_{\mu\rho} F_{\nu\sigma}) \tag1$$
where $g_{\mu\nu}(x) = \eta_{\mu\nu}+\kappa h_{\mu\nu}(x)$ and $\kappa^2 = 32\pi G_N .$ With a little bit of simplification, I can rewrite this in terms of the gauge vector field $A_\mu$, up to first order in $\kappa$ as:
$$ S_M = \int d^4x \ (1+\frac 1{2}{h_\mu}^\mu)\Big(-\frac1{4} F^2 - \kappa h^{\mu\nu} A_\sigma N^{\sigma\lambda}_{\mu\nu} A_\lambda \Big) \tag2$$
where $N^{\sigma\lambda}_{\mu\nu} := \eta^{\sigma\lambda}\partial_\mu\partial_\nu + \partial_\mu\partial^\sigma {\delta_\nu}^\lambda.$
Is this simplification helpful in deriving the graviton-photon vertex?
Please advise on how to derive the Feynman rules. (I still haven't got the hang of deriving Feynman rules from arbitrary lagrangians. I get stuck every time.)
The result should read
$$ \frac{i\kappa}{2} \Big[ k_1 \cdot k_2 \ (\eta^{\rho (\alpha}\eta^{\beta) \sigma} - \eta^{\rho \sigma}\eta^{\alpha \beta}) + \eta^{\rho \sigma} k_1^\beta k_2^\alpha + \eta^{\alpha \beta} k_1^{(\rho} k_2^{\sigma)} - (\eta^{\alpha (\rho} k_2^{\sigma)} k_1^\beta + \eta^{\beta (\rho} k_1^{\sigma)} k_2^\alpha) \Big] \tag3$$
where $k_1,k_2$ are the four-momentum of the incoming photons and two of the Lorentz indices belong to the external graviton.
Answer: I think you could not arrive at your desired Feynman rules because your second equation is wrong. You see, given your definition of the graviton field as a small perturbation to the Minkowski metric, we can rewrite
\begin{align*}
g^{\mu\nu} g^{\rho\sigma} F_{\mu\rho} F_{\nu\sigma} &\approx (\eta^{\mu\nu} \eta^{\rho\sigma} - \kappa h^{\mu\nu} \eta^{\rho\sigma} - \kappa h^{\rho\sigma} \eta^{\mu\nu}) F_{\mu\rho} F_{\nu\sigma} \\
&= F^2 + 2 \kappa {h^\mu}_\nu\ \partial_{[\mu}A_{\rho]} \partial^{[\rho}A^{\nu]}\,. \\
\end{align*}
Moreover, you made a mistake in your expansion of the invariant measure.
$$ \sqrt{-g} \approx 1 + \frac{\kappa}{2} \eta_{\alpha \beta}h^{\alpha \beta}$$
These considerations give your Interaction Lagrangian the following form:
$$ \boxed{\mathcal L_I = -\frac{\kappa}{4} \eta_{\alpha \beta}h^{\alpha \beta} \partial_{\mu}A_{\nu} \partial^{[\mu}A^{\nu]} - \frac{\kappa}2 {h^\mu}_\nu\ \partial_{[\mu}A_{\pi]} \partial^{[\pi}A^{\nu]}}\,. \tag4$$
You do not need to write your Lagrangian in the quadratic form (e.g. $A_\sigma \hat{N}^{\sigma\lambda}_{\mu\nu} A_\lambda$) unless, of course, you want to find the free propagator of your theory (which is $\hat{N}^{-1}$, if you have that free term in your Lagrangian, which you do not).
Note that there are six terms in the above Lagrangian which I will list down below.
$-\frac{\kappa}{4} \eta_{\alpha \beta}\ h^{\alpha \beta}\ \partial_{\mu}A_{\nu}\ \partial^{\mu}A^{\nu}$
$+\frac{\kappa}{4} \eta_{\alpha \beta}\ h^{\alpha \beta}\ \partial_{\mu}A_{\nu}\ \partial^{\nu}A^{\mu}$
$- \frac{\kappa}2 h^{\mu\nu}\ \partial_{\mu}A_{\pi}\ \partial^{\pi}A_{\nu}$
$+ \frac{\kappa}2 h^{\mu\nu}\ \partial_{\pi}A_{\mu}\ \partial^{\pi}A_{\nu}$
$+ \frac{\kappa}2 h^{\mu\nu}\ \partial_{\mu}A_{\pi}\ \partial_{\nu}A^{\pi}$
$- \frac{\kappa}2 h^{\mu\nu}\ \partial_{\pi}A_{\mu}\ \partial_{\nu}A^{\pi}$
For each of these terms, you can try to write down the momentum-space contribution to the vertex interaction,
as follows. Consider, without loss of generality, the first term from the above list: $-\frac{\kappa}{4} \eta_{\alpha \beta}\ h^{\alpha \beta}\ \partial_{\mu}A_{\nu}\ \partial^{\mu}A^{\nu}$.
Step 1: Start with the constant coefficients of the interaction term (such as $-\frac{\kappa}{4} \eta_{\alpha \beta}$). Write them down with an extra factor of $i$, the imaginary number.
Step 2: Assign to each field in the interaction term (such as $h^{\alpha \beta}$) a corresponding schematic in the Feynman diagram (such as $h^{\rho \sigma}$) and write down the Lorentz indices of the pairing in terms of Minkowski matrices (such as $\eta^{\alpha \rho}\eta^{\beta \sigma}$).
Step 3: Write down the derivatives that act on a certain field (such as $\partial_{\mu}A_{\nu}$) as the momentum of the corresponding field in the Feynman diagram (such as $\eta_{\nu\alpha}{k_1}_\mu$ for choice of $A_\alpha$ as the representative schematic).
Step 4: Add all possible contributions due to different choices of schematic assignments (such as $\eta_{\nu\beta}{k_2}_\mu$ for choice of $A_\beta$ as the representative schematic for $\partial_\mu A_\nu$).
The result should look like this.
$$ -\frac{i\kappa}{4} \eta_{\alpha \beta} \eta^{\alpha \rho}\eta^{\beta \sigma} (\eta_{\nu\alpha}{k_1}_\mu {\eta^\nu}_\beta {k_2}^\mu + \eta_{\nu\beta}{k_2}_\mu {\eta^\nu}_\alpha {k_1}^\mu) = -\frac{i\kappa}{2} (k_1 \cdot k_2) \ \eta^{\rho \sigma} \eta_{\alpha \beta} \tag{5.1}$$
You can consider the above steps as Feynman meta-rules to find the Feynman rules for any "well-behaved" theory. Try working out the other terms (#2 through #6) by yourself and see if you can get the following results from each of these terms.
$$ + \frac{i\kappa}{2} \eta^{\rho \sigma} {k_1}_\beta {k_2}_\alpha \tag{5.2}$$
$$ - \frac{i\kappa}{2} ({\eta_\alpha}^\sigma {k_2}^\rho {k_1}_\beta + {\eta_\beta}^\sigma {k_1}^\rho {k_2}_\alpha) \tag{5.3}$$
$$ + \frac{i\kappa}{2} (k_1 \cdot k_2)\ {\eta^\rho}_{(\alpha} {\eta_{\beta)}}^\sigma \tag{5.4}$$
$$ + \frac{i\kappa}{2} \eta_{\alpha\beta} {k_1}^{(\rho} {k_2}^{\sigma)} \tag{5.5}$$
$$ - \frac{i\kappa}{2} ({\eta_\alpha}^\rho {k_2}^\sigma {k_1}_\beta + {\eta_\beta}^\rho {k_1}^\sigma {k_2}_\alpha) \tag{5.6}$$
These are the ten terms that you wanted to have (eq. 3). I hope that helps. Please comment below if you do not understand something and need further clarification.
NOTE:
To understand why the meta-rules work the way they do, please read a standard book on Quantum Field Theory. I would recommend A. Zee: Quantum Field Theory in a Nutshell, Ch. 1.7. You will also find this resource quite useful. | {
"domain": "physics.stackexchange",
"id": 41025,
"tags": "quantum-field-theory, quantum-gravity, feynman-diagrams, qft-in-curved-spacetime"
} |
On the derivation of the canonical distribution | Question: in deriving the canonical distribution $\rho_c$ for a sistem (labeled by 1) of N identical particles in thermal equilibrium with a heat bath (labeled by 2), at one point I get into the Taylor expansion of the entropy of the reservoir . It is justified with the assumption that the dimensions of the latter are way more big that the ones of the system,
$$ E_2 \gg E_1; \quad N_2 \gg N_1; \quad E=E_1 + E_2 $$
So, doing the expansion,
$$ S_2(E_2 = E - E_1) \approx S_2(E_2 = E) -E_1 \Big(\frac{\partial S_2}{\partial E_2}\Big)_{E_2 =E} + (...) =k_B ln[\Gamma(E_2 = E - E_1)]$$
So, as I've already shown that $\rho_c \propto \Gamma_2(E_2 = E - E_1),$ taking the exponential of the expansion I can write
$$ \Gamma(E_2 = E - E_1) \approx exp\Big[\frac{S_2(E_2 = E)}{k_B}\Big]\cdot exp\Big[\frac{E_1}{k_B T}\Big]$$
After this, it's said that $S_2$ is evaluated at the fixed energy of the universe, and so it's a constant term, suggesting that it can be eliminated from the calculation. In fact, when it gets to the point of finding $\rho_c$, it is formulated as
$$ \rho_c = \frac{1}{Z}e^{-\frac{E_1}{k_B T}}$$
where Z is the partition function, that does not contain any term with $S_2$. So I don't get why I shall drop the term with the entropy of the reservoir. One idea is that I can directly eliminate the term $S_2(E_2 = E)$ in the Taylor expansion, or think of it as a sort of renormalization of the entropy, but I'm not sure these ideas are legitimate.
Answer: Here, $\rho_{c}(E_{1})$ is just the probability of the system $1$ being found at the given energy $E_{1}$, and so the constant pre-factor factors out of expression.
$Z$ is just the sum of all the $\Gamma(E_{2})$ as $E_{2}$ is varied over all possible discrete values (or we need an integral if the number of admissible energy values are continuous). Also, $\rho_{c}(E^{*}_{1})=\frac{\Gamma(E^{*}_{2}=E-E^{*}_{1})}{\sum_{E_{2}} \Gamma(E_{2})}$. The $exp[\frac{S_{2}}{k_{B}}]$ factors out of both the numerator and denominator of this expression. | {
"domain": "physics.stackexchange",
"id": 38938,
"tags": "statistical-mechanics, partition-function"
} |
Confusion in the Lagrangian description of Material Surface in Continuum Mechanics | Question:
In Lagrangian or Material description, the physical properties are
described in terms of the material coordinates and time. It focuses on
what is occurring at a fixed material point (or particle) labeled by
its material coordinates as time progresses.
My confusion: But the material surface (defined below) is written in terms of material coordinates only in case of the reference configuration and there is no time parameter. I understand that in reference configuration it is logical to not be dependent on time, but in the definition of material description, time is supposed to be included.
In Eulerian or Spatial description, the physical properties are
described in terms of the spatial coordinates and time. It focuses at
a fixed point in space as time progresses.
A material surface is a mobile surface in the space constituted
always by the same particles.
In the reference configuration, the material surface is defined
in terms of the material coordinates as f(X,Y,Z) = 0, where the set
of particles (material points) belonging to the surface are the same
at all times.
In the spatial description, it is defined as f(x,y,z,t) = 0. The
set of spatial points belonging to the surface depend on time, and
the material surface moves in space.
Answer: One way to think about this is to imagine that the body is made up of spheres and you're sitting on one of them. As the body deforms, all you can observe is the distance between you and neighboring spheres; but not how you're positioned in the surrounding space (with respect to a global coordinate system that's fixed in time).
The problem with a Lagrangian descriptions is that if the deformation is too large and you no longer can see your original neighbors, the description fails. | {
"domain": "engineering.stackexchange",
"id": 3924,
"tags": "fluid-mechanics, solid-mechanics"
} |
What's the meaning of a complex zero/pole? | Question: I have been studying signal processing and control for a while now, and I use Laplace and Fourier transforms almost everyday. Also another tools such as Nyquist or Bode plots.
However, I had never thought of this until today: what is the physical meaning of a complex number when dealing with frequencies?
This may sound silly, but I was asked this question and I didn't know what to answer. Why do we talk about $j\omega$ and not just $\omega$ in, for example, Fourier transforms and Bode or Nyquist plots? What is the physical sense of the real and imaginary part of a zero or a pole in the Laplace domain?
Answer: We usually talk of $j\omega$ when we're also interested in the Laplace transform of a signal / system, but want to just talk about the frequency response.
The physical meaning of the imaginary part is that it refers to purely sinusoidal signals and are constant "amplitude". The real part refers to signals for which the "amplitude" decays or grows exponentially. | {
"domain": "dsp.stackexchange",
"id": 8323,
"tags": "frequency-domain, laplace-transform"
} |
SPARK, ML: Naive Bayes classifier often assigns 1 as probability prediction | Question: Hi I am using Spark ML to optimise a Naive Bayes multi-class classifier.
I have about 300 categories and I am classifying text documents. The training set is balanced enough and there is about 300 training examples for each category.
All looks good and the classifier is working with acceptable precision on unseen documents. But what I am noticing that often when classifying a new document, the classifier is often assigning a very high probability to one of the categories (the prediction probability is almost equal to 1), while the other categories receive very low probabilities (close to zero).
What are the possible reasons for this phenomenon?
I can think of one possible reason, which is all the words in some documents did not appear with some categories in the training dataset? but I am not totally convinced of that especially that for most of the results, there is always one category who has very high probability and all the others have very low probability.
Is there any other explanations or reasons?
I would like to add that in SPARK ML there is something called "raw prediction" and when I look at it, I can see negative numbers but they have more or less comparable magnitude, so even the category with the high probability has comparable raw prediction score, but I am finding difficulties in interpreting this scores.
Answer: The reason NB is called "Naive" is that is makes the assumption that the predictive variables are all independent.
This assumption usually skews the model scores (which, under the above naive assumption are unbiased probability estimates) towards 0 or 1.
In your case, e.g., the presence of words flower and petal indicate gardening category, but, because the presence of these words is not independent (if one is present, the other is likely to be present too), the model will over-value their appearance. Taking the extreme case, if words A and B appear only together, then
P(Category=X | A & B) = P(Category=X | B) = P(Category=X | A)
and thus one should multiply by the odds ratio of A&B once, not twice, as the Naive Bayes algorithm requires.
Your remedy is to use calibration (a separate model which maps model scores to probabilities). | {
"domain": "datascience.stackexchange",
"id": 645,
"tags": "classification, apache-spark, multiclass-classification, naive-bayes-classifier"
} |
Shortest path between all pairs with colored nodes | Question: I got a question from my homework in each I have the solution, but not the algorithm. I want to check if I understood it correctly. The question is:
Let's say we have a directed graph with no cycles, it has N vertices and M edges.
Exactly 2018 vertices are colored green, and the others are black.
We know that in each shortest
path, each vertex is colored green,
perhaps without the first and the last node.
We can find the shortest path of all two pairs of nodes in: O(___) and not less
What I tried:
If we run the Floyd Warshall algorithm on the 2018 green vertices we get the shortest path between all pairs of greens. (This is O(1) because of the green vertices amount is constant).
Now for each (u,v) in VxV:
If both u and v are green we already have the shortest path from Floyd Warshall.
If one is green and the other black, we add the edge's weight that connects the source/destination to the green group and add the Floyd Warshall result.
If both u and v, are black, we add the lightest weight of each which connects to the green group.
I think my solution is kind of messy, and I do not know if it's 100% correct.
The solution is: We can find the shortest path of all two pairs of nodes in: O(n^2) and not less.
Answer: Your answer and reasoning are correct, but the last steps in your algorithm are wrong.
First, discard all edges with no green vertex. Then:
To find the shortest path between a green and black node, you have to consider all of the black node's green-adjacent edges, and add the shortest path to/from the green. There are at most 2018 of these, so it's still constant time.
To find the shortest path between two black nodes, you have to consider all combinations of their green-adjacent edges, and add the distance between the greens. There are at most 20182 of these combinations, so it's still constant time.
So you can certainly do this in O(n2) time, and you can't do any better, because that's also the size of the output.
It may be simpler just to show how you can optimize Floyd-Warshall to take O(n2) time when all edges are known to be green-adjacent. | {
"domain": "cs.stackexchange",
"id": 15402,
"tags": "shortest-path"
} |
Selection rules and type of photon? | Question: Let us consider the following matrix element:
$$\langle n',m',l'|x| n, m, l \rangle$$
For the corresponding radiative transition we have the selection rule that $\Delta m=\pm 1$. But will the photon emitted be circularly polarized i.e.:
$$|\psi \rangle=|\pm m=1 \rangle$$ or linearly polarized (i.e. a combination of two circularly polarized waves) i.e.:
$$|\psi \rangle=a(| m=1 \rangle+| m=-1 \rangle)$$
Answer: Given two states $|n,l,m⟩$ and $|n',l',m'⟩$, the following radiative transition matrix elements are nonzero:
$$\left\langle n,l\pm1,m+1 \middle| x+iy \middle| n,l,m \right\rangle,$$
$$\left\langle n,l\pm1,m-1 \middle| x-iy \middle| n,l,m \right\rangle,$$
and
$$\left\langle n,l\pm1,m \middle| z\middle| n,l,m \right\rangle,$$
and that's it (for transitions between states of definite angular momentum about the $z$ axis; you can also have transitions to e.g. $|n,l+1,m+1⟩+|n,l+1,m-1⟩$, using a linearly polarized photon in the $x$ direction and propagating in the $y,z$ plane, or to similar superposition states).
The first two correspond to absorption or emission of a circularly polarized photon propagating along the $z$ axis, with selection rule $\Delta m=±1$ on the atom, while the third one corresponds to absorption or emission of a linearly polarized photon polarized along the $z$ axis and propagating on any axis in the $x,y$ plane, with selection rule $\Delta m=0$ on the atom.
For further details, consult any advanced undergraduate textbook on quantum mechanics. | {
"domain": "physics.stackexchange",
"id": 31282,
"tags": "quantum-mechanics"
} |
CompletableFuture Chain (Monad) | Question: I wrote an application that has a modular structure. Each module communicates with different remote servers. Time for execution of a task in each module varies. So communication should be asynchron.
Plus some restrictions like flexibility, scalability and so on are put.
So i decided to use CompletableFutures to build a composition of functions (monade), that modules execute.
Each module has its own FixedThreadPool und a public function, that create and sends back a CompletableFuture. Something like that:
private final ExecutorService executorService = Executors.newFixedThreadPool(10);
public CompletableFuture<String> function1(final String rawReport, final UUID id) {
LOG.info("SEND a report for " + id);
return CompletableFuture.supplyAsync(() -> run(rawReport, id), this.executorService);
}
private String run(final String rawReport, final UUID id) {
// do something
}
The whole process through all modules is handled by ModuleChainHandler:
public CompletableFuture<Result> handler(final RunnerJob job) {
// @formatter:off
return this.scanExecuterRegistry.function1(job).
thenCompose(bArr -> this.module2.function2(bArr, job)).
thenCompose(metrics -> this.module3.function3(metrics, job)).
handle((vReport, throwable) -> {
if (vReport != null) {
this.module4.function4(vReport, job);
return builder().setResult(vReport).build();
} else {
return builder().setErrorMessage(throwable.getMessage()).build();
}
});
// @formatter:on
}
The BIGGEST problem (at the beginning) was to add an error handling. Because you cant throw an exception directly out of a future. I had to create an object with two state (result and error). If a completable future completes exceptionally, will be one action executed and the result object has an error massage and an empty result.
There is no so much real examples in internet except some poor tutorials. So just interesting, if you do it in the same way.
Answer: One thing that i'd like to propose is to replace CompletableFuture with home-brewed builder class that wraps CompletableFuture but will have more 'easy to read' interface. It would be something like this:
class FutureBuilder {
/**
* Wrapped 'completable future' instance
*/
CompletableFuture future;
...
public FutureBuilder execute(Function<...> task) {...}
public FutureBuilder whenComplete(Consumer<Report> handler) {...}
public FutureBuilder whenFail(BiComsumer<Report, Throwable> handler) {...}
...
/**
* This method should be called at the end to meet interface requirements
*/
public CompletableFuture build() {
return future;
}
...
}
So, it may be used in next way:
public CompletableFuture<Result> handler(final RunnerJob job) {
return new FutureBuilder ()
.execute(bArr -> this.module2.function2(bArr, job))
.execute(metrics -> this.module3.function3(metrics, job))
.whenComplete(r-> uilder().setResult(r).build())
.whenFail((r, e) -> {
this.module4.function4(r, job);
return builder().setErrorMessage(e.getMessage()).build();
})
.build();
}
I hope that is you are looking for. | {
"domain": "codereview.stackexchange",
"id": 23298,
"tags": "java, monads"
} |
PBP vs TBP geometry? | Question: Why are the axial bond lengths greater than those of the equatorial bonds in a trigonal bi-pyramid (TBP) geometry molecule; but the opposite is true for pentagonal bi-pyramid (PBP) geometry molecules? I think that it might have something to do with the angles between the bonds, so I thought of a possible explanation.
In a TBP molecule, the equatorial bonds are spaced apart from each other by 120 degrees, resulting in lesser repulsion; compared to the axial bonds at 90 degrees. The reduced repulsion leads to greater stability of the equatorial bonds.
In contrast, the equatorial bonds in a PBP molecule are separated by 72 degrees which results in them being less stable when compared to the axial bonds.
To what extent is this reasoning correct? Please provide a more detailed and accurate explanation, if there is one. Thanks!!
Answer: General Rule #1: Most elements use only s and p orbitals to form bonds, only transition elements and heavier elements use d, f, etc. orbitals in bonding.
General Rule #2: The more s-character in a bond the shorter the bond (reference). For example
a $\ce{C(sp^3)-C(sp^3)}$ single bond length is ~ 1.54 $\mathrm{\mathring{A}}$
a $\ce{C(sp^2)-C(sp^3)}$ single bond length is ~ 1.50 $\mathrm{\mathring{A}}$
a $\ce{C(sp)-C(sp^3)}$ single bond length is ~ 1.46 $\mathrm{\mathring{A}}$
In an earlier SE Chem post, the structure and bonding in the trigonal bipyramid molecule $\ce{PCl_5}$ was discussed. The molecular hybridization is pictured below. The axial bonds are hypercoordinate (this concept is explained in the earlier post) and they are constructed from p orbitals. The equatorial bonds are constructed from $\ce{sp^2}$ orbitals. General Rule #2 suggests that the equatorial bonds will be shorter than the axial bonds since the equatorial bonds contain more s-character.
As the following structural diagram shows, this is indeed the case.
Now let's turn our attention to the pentagonal bipyramid structure as found in $\ce{IF_7}$ for example. Here is the structure for this molecule
As you noted in your question, the equatorial bonds are now longer than the axial bonds. Based on what we've discussed thus far, we might make an initial "guess" that in $\ce{IF_7}$ the axial bonds have more s-character than the equatorial bonds. As it turns out, this is correct.
Here is a link to an article discussing the structure and bonding in $\ce{IF_7}$. Only the abstract is freely available. For completeness, I'll mention that there was an earlier SE Chem question related to $\ce{IF_7}$, but it doesn't seem to add much to the conversation. Returning to the published abstract, the key part of the abstract states,
"These features can be explained, however, by a bonding scheme
involving a planar, delocalized pxy hybrid on the central atom for the
formation of five equatorial, semi-ionic, 6-center 10-electron bonds
and an sp hybrid for the formation of two mainly covalent axial
bonds."
The abstract tells us that the equatorial bonds are formed from the $\ce{p_{x}}$ and $\ce{p_{y}}$ orbitals; the axial bonds are formed from the $\ce{sp_{z}}$ hybrid orbitals (after using two p orbitals for equatorial bonding we are left with one $\ce{p_{z}}$ orbital and one s orbital on the central iodine, hence, when they combine two sp hybridized orbitals result). That is the answer to the question. As we guessed, there is more s-character in the axial bonds than the equatorial bonds. Hence, the axial bonds are now shorter than the equatorial bonds.
For completeness
Someone, after reading that last paragraph, is going to notice that there are 5 equatorial fluorines, but only 4 bonding sites with the two p orbitals - what gives? First off, note that the $\ce{p_{x}}$ and $\ce{p_{y}}$ orbitals on iodine form hypercoordinate bonds with the p orbital on fluorine and so yes, there are only 4 equatorial points of attachment. But note that the abstract also mentioned that the equatorial bonds are semi-ionic. This suggests that we have a resonance structure where we have an [$\ce{IF_{6}^{+}}$][$\ce{F^{-}}$] ionic contributor. We can draw 4 more resonance structures just like this for the other 4 equatorial $\ce{I-F}$ bonds. This means that mixed in with our hypercoordinate p-p bonds is some ionic character - this allows us to make 5 equivalent equatorial bonds. Said differently, our 5 equatorial bonds are all identical resonance hybrids obtained by mixing 2 hypercoordinate p bonds (each one providing bonding for 2 fluorines) with 1 ionic bond (providing bonding for 1 fluorine). | {
"domain": "chemistry.stackexchange",
"id": 3248,
"tags": "bond, theoretical-chemistry, resonance, structural-formula, molecular-structure"
} |
What kind of fly is this? | Question: I found this dude hanging out in my sink, but he didn't fly away when I put a dish in the sink. Turned out it was dead. The front part looks exactly like a housefly. But, I've never seen the back end (abdomen) look like this. Any ideas?
Answer: This is probably a fly killed by the fungi Entomophthora muscae (or closely related) or maybe a Cordyceps fungus. These kinds of fungi mainly attacks insects, and you sometimes see attacks as white, swollen abdomens in flies.
(Picture of common infection, from bugguide.net)
These fungi are also known to change the behaviour of infected individuals, so that they e.g. climb up tall plants to die (sometimes called "zombie-insects"), to allow for better dispersal and transmission of the fungal spores. Lots of information about the behavioural modifications of hosts by fungi can be found in Roy et al. (2006), but they can involve both climbing to exposed locations and special mechanisms for host attachement at death:
In many cases the final interactions, or endgames, between a host and pathogen involve complex behavioral modifications such as the infected insect seeking an elevated position where wind currents can effectively disseminate conidia. Elevation seeking by insects at late stages of infection is a common phenomenon that was recognized by early insect pathologists who noted that diseased lepidopteran larvae, such as Lymantria monacha (the nun moth), infected with baculoviruses migrated to the tops of trees where they died (94). This host-altered behavior was named “Wipfelkrankheit” or “Wipfelsucht” (meaning tree top disease in German) for viral diseases (41) and “summit disease” for fungal diseases (24, 57, 106).
and
Some fungi do not produce rhizoids, but the host is held in situ by host structures alone, namely the legs or mouthparts (mandibles or stylets). The pose of the dead insect is generally characteristic of the pathogen species involved. For instance, E. grylli-infected grasshoppers (Figure 3a) and E. scatophagae–infected yellow dung flies (Figure 3b) seek elevated positions on grasses or other vegetation and cling tightly (death grip) with their legs (96). Tipulids infected with fungal species from the genera Eryniopsis and Entomophaga also attach to grasses with their long legs, often overhanging water (Figures 5b,c).
If you do google image searches on "Entomophthora fly abdomen" or "fly Cordyceps" you can see some examples of infections. I don't know about the fly species, but Musca domestica is probably likely.
For some more examples and information on Entomophthora muscae and related fungi see:
Roy et al. 2006. Bizzare Interactions and Endgames: Entomopathogenic Fungi and Their Arthropod Hosts. Annual Review of Entomology 51(1) (pdf)
Biological Control: Entomophthora muscae, webpage from Cornell Uni.
Harmon. 2012. Fungus that controls zombie-ants has own fungal stalker. Nature
Mind-controlling fungus turns insects into zombies (blog post) | {
"domain": "biology.stackexchange",
"id": 2945,
"tags": "entomology, species-identification, pathology"
} |
What is the probability of measuring $p$ in the momentum space? | Question: I have a wave function $\Psi (x,t)$. According to the Max Born postulate, $\lvert\Psi (x,t)\rvert ^2$ is the probability density. This quantity specifies the probability, per length of the $x$ axis, of finding the particle near the coordinate $x$ at time $t$.
If at $t=0$ I make a Fourier transform for the momentum space, $$\phi(p)=\frac{1}{\sqrt{2 \pi \hbar}} \int _{-\infty} ^{+\infty} \psi(x)e^{-ipx/\hbar} dx$$ does $\vert\phi(p)\rvert ^2$ specifies the probability of finding the particle near the momentum $p$ at time $t=0 \hspace{1mm}$?
In this sense, given $\Psi(x,t)$, how could I write $\phi(p)$ at any time $t$, i.e. $\Phi(p,t)\hspace{1mm}$?
Answer: You’re exactly right: $|\phi(p)|^2$ gives the probability of measuring momentum $p$ at time $t=0$. An analogous relation holds for the time-dependent case:
$$\Phi(p,t)=\frac{1}{\sqrt{2\pi\hbar}}\int_{-\infty}^{\infty}dx e^{-i px/\hbar}\Psi(x,t)$$
This is simply due to the fact that one independently transforms between position and momentum space and between time and frequency space.
For a “proof” that this is the case, consider:
$$\Phi(p,t)=\langle p|\Psi(t)\rangle=\int _{-\infty}^{\infty}dx \langle p|x\rangle\langle x|\Psi(t)\rangle= \int _{-\infty}^{\infty}dx \langle p|x\rangle \Psi(x,t)$$
Now, note that a free particle momentum eigenstate in the position basis is a plane wave $\langle x|p\rangle= \frac{1}{\sqrt{2\pi\hbar}} e^{i px/\hbar} $, so $\langle p|x\rangle=\langle x|p\rangle^*= \frac{1}{\sqrt{2\pi\hbar}} e^{-i px/\hbar}$. Finally then, we arrive at:
$$ \boxed{ \Phi(p,t)= \frac{1}{\sqrt{2\pi\hbar}} \int _{-\infty}^{\infty}dx e^{-i px/\hbar} \Psi(x,t)}$$ | {
"domain": "physics.stackexchange",
"id": 68811,
"tags": "quantum-mechanics, momentum, wavefunction, fourier-transform, born-rule"
} |
Wheeler-Feynman theory, QED without fields, vacuum polarization | Question: Initially Wheeler and Feynman postulated that, the electromagnetic field is just a set of bookkeeping variables required in a Hamiltonian description. This is very neat because makes the point of divergent vacuum energy a moot point (i.e: an example of asking the wrong question)
However, a few years later (1951), Feynman wrote to Wheeler that this approach would not be able to explain vacuum polarization.
Anyone knows what was the argument for saying so? I don't see how allowing both processes with entry and exit particles and processes that begin in pair-creation and end in pair-annihilation makes the existence of a field a requirement.
Answer: the original strategy of Feynman and wheeler was really about the desire to get rid of all self-interactions. In the modern language, it would eliminate most loop diagrams.
In particular, consider an electron propagator, in the modern language. One may attach a photon propagator on it. That modifies the electron's self-energy, and this is the kind of a term that the Wheeler-Feynman program wanted to eradicate completely. However, if you add another complexity to the photon propagator - namely an electron-positron loop in the middle - then it is a nontrivial contribution, especially because the vacuum polarization loop may be attached to different parts of the diagram as well.
Their very idea would be that it is impossible for the same electron propagator to have two photon end points attached - that would be connected with one another. That would throw the baby out with the bath water. At any rate, no complete theory of their picture exists (or is mathematically possible) and their dreams and partial hints have only been a motivation for them to get the really important insights.
Best wishes
Lubos | {
"domain": "physics.stackexchange",
"id": 393,
"tags": "quantum-field-theory, polarization, path-integral, vacuum"
} |
A photon travels in a vacuum from A to B to C. From the point of view of the photon, are A, B, and C at the same location in space and time? | Question: So, for a photon, everything just is ?
Answer: As other answers have pointed out, there is no point of view or frame of reference that keeps up with a photon. Never the less, the idea that such a frame of reference exists as the limit of infinite boosts is a very natural one that comes up over and over. Here is why there are problems with that idea.
Suppose you start at rest in a certain frame of reference, and accelerate at $1$ g for $1$ sec. This give you a new speed. Do this again and again.
As you travel faster and faster an observer in your starting frame sees you traveling closer and closer to the speed of light, your clock running slower and slower, and your ruler getting shorter and shorter. The limit of these measurements is you traveling at the speed of light, your clock stopped, and your ruler contracted to $0$ length.
It is natural, but wrong, to suppose that at this point your frame of reference is the same as a photon. Therefore photons experience no time, and see the entire universe as contracted to a plane.
First, the limit state doesn't match what we see when we observe photons.
Photons travel at a finite speed. As they advance, they change phase. So the idea that they are in a frame where no time passes and all points along their path have been compressed into the same point is wrong.
Second, you don't get closer to traveling as fast as a photon.
This can be illustrated by a hyperbolic tesselation of the plane. The tesselation below uses 30, 45, 90 degree triangles. It became famous when Escher used it as the basis of his Circle Limit woodcuts. In this post, it represents a $2D$ velocity space.
An observer is stationary in his reference frame. This velocity is the center point. The sides of the triangles represent boosts in various directions.
As you undergo boost after boost, the observer sees you travel faster and faster. Your velocity is a point farther and farther from the center of the circle. But each boost gives a smaller change to your velocity. You never reach the edge, which represents the speed of light.
After each boost, you can measure the speed of a photon. Each time, it is still passing you at the speed of light. You are no closer to its speed.
This video shows how velocity space appears to you as you try to accelerate to the speed of light. Or equivalently, try to reach the edge of velocity space. (It isn't quite the same tesselation, and the path isn't quite a straight line. But it gives the idea.)
All the triangles are the same, though the ones far away appear distorted. These triangles become normal as you approach them.
No matter how many boosts you undergo, you are still at rest in your own frame. From your point of view, you are in the center of the circle. You are a finite number of boosts from the observer and an infinite number from the circle. No part of the circle has become any closer or farther from you.
As you move from triangle to triangle, you stay at rest in your own frame, though you move far away from the observer. You see each boost as making the same change in velocity. Though the cummulative effect on the velocity of the observer gets smaller and smaller. The observer recedes at close to the speed of light, but never reaches it.
From your point of view, the observer is getting closer to a state where his ruler shrinks to $0$ and his clock stops. You might think the observer is closer to matching speed with a photon you send in his direction.
The observer thinks no such thing. He sees your photons arriving at the same speed as always, though they are increasingly red shifted.
Mathematically, you are advancing from 1 boost to 2 boosts to 3 boosts, etc. The limit of this sequence is an infinite number of boosts. This really means the sequence diverges and there is no limit. The definition of an infinite limit is that given any finite number, after enough steps you will pass that number. The limit is not a state where you are sitting on a point named infinity.
This means given any speed slower than light, after enough boosts you will be going faster than that speed. But there is never a state where you are going the speed of light.
If you try to construct a limit, it would go something like this:
For any $\epsilon > 0$, there is a point $P$ in velocity space where you would measure the velocity as $v_p$ such that ($c - v_p) < \epsilon$. But an observer at $P$ would see a photon pass him at $c$. So the limit as "$P \rightarrow $ the edge" is a state where the observer at P sees a photon pass him at $c$. This really means at all large boosts, an observer at $P$ sees a photon pass him at $c$.
The separation between the interior of the circle and the edge is absolute.
All points in the interior of the circle are an infinite number of boosts from the edge. No number of boosts brings an observer from the interior to the edge. Likewise, it never brings a photon from the edge into the interior.
Some references on the mathematics of the tesselation, and how Escher's woodcuts illustrate it:
TheFamilyof“CircleLimitIII”EscherPatterns
How Did Escher Do It?
Escher and Coxeter – A Mathematical Conversation
Edit - I have updated this answer to make it clearer.
In the meantime, the question has been closed as a duplicate. Site policy is to put all answers under one question and not encourage duplicate questions. So I have copied this answer to How does a photon experience space and time? | {
"domain": "physics.stackexchange",
"id": 76093,
"tags": "special-relativity, photons"
} |
Why is append() slower than + and is there some oversight in the map() solution which slows it down? | Question: I was trying out some variation in implementation of a leetcode example and was surprised by the runtimes. I was expecting it would be better to use map() than classic grandpa style for-loop
In short the problem is to find if a value in the list is smaller or larger than a threshold value
https://leetcode.com/problems/kids-with-the-greatest-number-of-candies/submissions/
Here are the three implementations:
72 ms 13.8 MB
Map over the input list and generate the list of bool
class Solution:
def kidsWithCandies(self, candies: List[int], extraCandies: int) -> List[bool]:
m=max(candies)-extraCandies
return list(map( lambda x: x>=m, candies))
40 ms 14 MB
For-loop and append() to list
class Solution:
def kidsWithCandies(self, candies: List[int], extraCandies: int) -> List[bool]:
m=max(candies)-extraCandies
ans=[]
for x in candies:
ans.append(x>=m)
return ans
28 ms 13.6 MB
Use + to append to list
class Solution:
def kidsWithCandies(self, candies: List[int], extraCandies: int) -> List[bool]:
m=max(candies)-extraCandies
ans=[]
for x in candies:
ans+=[(x>=m)]
return ans
Why is append() slower than + and is there some oversight in the map() solution which slows it down?
Answer: You ask whether there is an oversight in the map solution, slowing it down.
There is, in the form of lambda.
When passing lambda objects, map is slowed down, as shown here.
Passing proper function objects does not have the same restrictions.
Other than that, I was unable to confirm the large performance discrepancy you found between append (40ms) and __iadd__/+= (28ms).
In the below tests, append is faster than += by (just) about 2 percent.
That is negligible.
Below, five versions of your function are tested.
Next to kidsWithCandies_map_builtin, which uses the ge function of the operator module to get a callable ge(a, b) that returns the same as a >= b, the arguably most Pythonic approach is also tested, list comprehension.
from collections import defaultdict, namedtuple
from operator import ge
from pprint import pprint as pp
from timeit import timeit
from typing import List
candy_distribution = namedtuple(
"CandyDistribution", ["candies", "extra_candies", "solution"]
)
candy_distributions = [
candy_distribution([2, 3, 5, 1, 3], 3, [True, True, True, False, True]),
candy_distribution([4, 2, 1, 1, 2], 1, [True, False, False, False, False]),
candy_distribution([12, 1, 12], 10, [True, False, True]),
]
def kidsWithCandies_map_lambda(candies: List[int], extraCandies: int) -> List[bool]:
threshold = max(candies) - extraCandies
return list(map(lambda x: x >= threshold, candies))
def kidsWithCandies_map_builtin(candies: List[int], extraCandies: int) -> List[bool]:
threshold = max(candies) - extraCandies
thresholds = [threshold] * len(candies)
return list(map(ge, candies, thresholds))
def kidsWithCandies_append(candies: List[int], extraCandies: int) -> List[bool]:
threshold = max(candies) - extraCandies
ans = []
for x in candies:
ans.append(x >= threshold)
return ans
def kidsWithCandies_iadd(candies: List[int], extraCandies: int) -> List[bool]:
threshold = max(candies) - extraCandies
ans = []
for x in candies:
ans += [(x >= threshold)]
return ans
def kidsWithCandies_comprehension(candies: List[int], extraCandies: int) -> List[bool]:
threshold = max(candies) - extraCandies
return [element >= threshold for element in candies]
functions_to_runtimes = defaultdict(int)
for func in (
kidsWithCandies_map_lambda,
kidsWithCandies_map_builtin,
kidsWithCandies_append,
kidsWithCandies_iadd,
kidsWithCandies_comprehension,
):
for candy_supply in candy_distributions:
args = (candy_supply.candies, candy_supply.extra_candies)
assert candy_supply.solution == func(*args)
functions_to_runtimes[func.__name__] += timeit("func(*args)", globals=globals())
functions_to_runtimes = { # sort by value, ascending
k: v for k, v in sorted(functions_to_runtimes.items(), key=lambda item: item[1])
}
pp(functions_to_runtimes)
with an output of
{'kidsWithCandies_append': 2.2671058810083196,
'kidsWithCandies_comprehension': 2.3766544990066905,
'kidsWithCandies_iadd': 2.3180257579660974,
'kidsWithCandies_map_builtin': 2.9652103499975055,
'kidsWithCandies_map_lambda': 3.658640267996816}
So while there is not much of a difference between append, comprehension and in-place addition (+=), map is much improved by not using a lambda.
The most non-grandpa style approach is the list comprehension. map was even originally supposed to be dropped from Python 3; as such (but this is speculation), one can suspect that all the performance love and care went towards (list) comprehensions, append and +=. Others have tried here, but map, as a built-in, seems hard to introspect.
I omitted space complexity considerations because these seem similar for all approaches. | {
"domain": "codereview.stackexchange",
"id": 38174,
"tags": "python, performance, python-3.x"
} |
Doubt in K-L Transform equations | Question: I have a doubt, it may be silly. Please explain me.
In K-L Transform, For forward transform we have the below equation
For inverse transform we have the below equation
In reverse transform why the 'A' transpose is not common to both y and m(mean of x) as in Forward transform equation?
Answer: $y=A(x-m_x)$-->$A^Ty=A^TA(x-m_x)=x-m_x$-->$x=A^Ty+m_x$ | {
"domain": "dsp.stackexchange",
"id": 1463,
"tags": "image-processing, discrete-signals"
} |
SBPLLatticePlanner local planner | Question:
Dear all.
I have a differential mobile robot and I am successfuly using SBPLLatticePlanner as a global planner as part of the navigation stack. I tested the robot with :
base_global_planner: SBPLLatticePlanner
base_local_planner: dwa_local_planner/DWAPlannerROS
SBPLLatticePlanner:
allocated_time: 10
initial_epsilon: 15.0
lethal_obstacle: 20.0
And I also tested the robot by commenting out # base_local_planner: dwa_local_planner/DWAPlannerROS
I am using genmprim_unicycle.m to generate motion primitives.
I have experience some issues.
1.- When I comment out base_local_planner: dwa_local_planner/DWAPlannerROS and then I set the goal behind the robot from the current position, the robot does not turn back towards the goal. It starts shaking left-right instead.
2.-The robot does not follow the path close enough, meaning that in crashes with obstacles even though I have set inflation_radius accordingly to the footprint of the robot.
The questions are:
1 .- Is there any local base planner that must be use together with SBPLLatticePlanner.
2.- Which parameters I need to tune or set in order for the robot to turn back when I set the goal behind it?
In advance thank you for your replay.
Originally posted by acp on ROS Answers with karma: 556 on 2014-06-17
Post score: 0
Answer:
For (1) you can use either local planner (DWA or Trajectory Rollout) -- but you will almost certainly have to tune it for your robot. If you haven't supplied velocity and acceleration limits for your local planner, you will likely not get good results. See the Local Planner section of the Basic Navigation Tuning Tutorial for a list of things you probably want to tune.
For (2), you might have to come up with new motion primitives -- I'm not sure if the default ones include turning in place. I would certainly visualize the local and global plans in RVIZ though to be sure of which planner is actually not getting you to your goal.
Originally posted by fergs with karma: 13902 on 2014-06-20
This answer was ACCEPTED on the original site
Post score: 0
Original comments
Comment by acp on 2014-06-30:
Hi, thank you very much for your answer, I have solved the issues with unicycleplussidewaysplusbackturn.mprim, however I have another issue, Sometimes it get stuck when it gets trap in inflated obstacles even though there is enough space around the robot.
I found the package sbpl_recovery in this site thttps://github.com/ros-planning/navigation_experimental/tree/hydro-devel/sbpl_recovery hat I think it could help to recover when the robot gets trap. But the package does compile under Hydro due to changes in costmap2d. Or is there some other solution. | {
"domain": "robotics.stackexchange",
"id": 18295,
"tags": "ros, planner"
} |
Is my login system secure? | Question: I am recently making a CMS and I need a secure login system, so this is my code. How is it?
First: the HTMLcode for signup and login:
<div id="login" style="display: none">
<input type="text" name="email" id="login-email" placeholder=""><br><br>
<input type="password" name="password" id="login-password" placeholder=""><br><br>
<button type="button" id="submit-lodin"></button>
</div>
<div id="signup" style="display: none">
<input type="text" name="firstname" id="firstname" placeholder=""><br><br>
<input type="text" name="lastname" id="lastname" placeholder=""><br><br>
<input type="text" name="email" id="email" placeholder=""><br><br>
<input type="password" name="password" id="password" placeholder=""><br><br>
<input type="password" name="re_password" id="re_password" placeholder=""><br><br>
<button type="button" id="submit-signup"></button>
</div>
Second, the code for jQuery Ajax request for signup:
$(function(){
$("#submit-signup").click(function(){
var firstname = $("#firstname").val();
var lastname = $("#lastname").val();
var email = $("#email").val();
var password = $("#password").val();
var re_password = $("#re_password").val();
if(password === re_password){
if(validateEmail(email)){
if(firstname == "" || lastname == "" || email == "" || password == ""|| re_password == ""){
alert("");
}else{
$.ajax({
url : "resourcs/check_email.php",
type: "POST",
data : "firstname="+firstname+"&lastname="+lastname+"&email="+email+"&password="+password+"&re_password="+re_password ,
success : function(d)
{
if(d === "ok"){
$.ajax({
url : "resourcs/register.php",
type: "POST",
data : "firstname="+firstname+"&lastname="+lastname+"&email="+email+"&password="+password+"&re_password="+re_password ,
success : function(d2)
{
if(d2 === "ok"){
location.reload(true);
}else{
alert(d2);
}
}
});
}else{
switch(d){
case "error1":
alert("");
break;
case "error2":
alert("");
break;
case "error3":
alert("");
break;
case "error4":
alert("");
break;
};
}
}
});
}
}else{
alert("");
}
}else{
alert("");
}
});
});
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
My jQuery Ajax code for login:
$(function(){
$("#submit-lodin").click(function(){
var email = $("#login-email").val();
var password = $("#login-password").val();
if(email != "" && password != ""){
$.ajax("resourcs/login.php",{
type : "POST",
data : "email="+email+"&password="+password,
success : function(data){
if(data === "ok"){
location.reload(true);
}else{
alert(data);
}
}
});
}
});
});
My php code for login:
session_start();
include_once '../includes/config.php';
if(isset($_POST['email']) && isset($_POST['password'])&& $_POST['password'] != ""){
$email = mysql_real_escape_string(strip_tags($_POST['email']),$connect);
$password = mysql_real_escape_string(strip_tags($_POST['password']),$connect);
$sql = "select * from users where u_email = '$email'";
$query = mysql_query($sql) or die(mysql_error());
if(mysql_num_rows($query) > 0){
while ($row = mysql_fetch_object($query)) {
$salt = $row->u_salt;
$grade = $row->u_grade;
$id = $row->u_id;
}
$n_password = md5(md5($password).$salt);
$sql2 = "SELECT *
FROM users
WHERE u_email = '$email'
AND u_password = '$n_password'";
$query2= mysql_query($sql2) or die(mysql_error());
if (mysql_num_rows($query2) == 1){
$_SESSION ['login'] = "login";
$_SESSION ['user_id'] = $id;
$_SESSION ['email'] = $email;
$_SESSION ['grade'] = $grade;
echo"ok";
}else{
echo '';
}
} else {
echo '';
}
}
My php code for signup is:
session_start();
include_once '../includes/config.php';
$salt = '';
for ($i = 0; $i < 3; $i++)
{
$salt .= chr(rand(33, 126));
}
$email = mysql_real_escape_string(strip_tags($_POST["email"]),$connect);
$first_name = mysql_real_escape_string(strip_tags($_POST["firstname"]),$connect);
$last_name = mysql_real_escape_string(strip_tags($_POST["lastname"]),$connect);
$password = mysql_real_escape_string(strip_tags($_POST["password"]),$connect);
$re_password = mysql_real_escape_string(strip_tags($_POST["re_password"]),$connect);
$password_e = md5(md5($password).$salt);
$sql="INSERT INTO `users` (
`u_firstname` ,
`u_lastname` ,
`u_password` ,
`u_email` ,
`u_salt`
)
VALUES (
'".$first_name."',"
. " '".$last_name."',"
. "'".$password_e."', "
. "'".$email."',"
. " '".$salt."'
)";
$query=mysql_query($sql) or die(mysql_error());
if ($query){
$sql2 ="select * from users where u_email = '$email'";
$query2= mysql_query($sql2);
while ($row = mysql_fetch_object($query2)) {
$id=$row->u_id;
}
$_SESSION['login']="login";
$_SESSION['user_id']=$id;
$_SESSION['email']=$email;
$_SESSION['isadmin']=2;
echo 'ok';
}
Finally, my database structure is:
CREATE TABLE IF NOT EXISTS `users` (
`u_id` int(11) NOT NULL,
`u_firstname` varchar(255) CHARACTER SET utf8 NOT NULL,
`u_lastname` varchar(255) CHARACTER SET utf8 NOT NULL,
`u_password` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`u_email` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`u_grade` int(1) NOT NULL DEFAULT '1',
`u_salt` varchar(255) COLLATE utf8_unicode_ci NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
Are there any security flaws in this code?
Answer: Flow Security
You should repeat the email validation in Server side too (js validation could be bypassed)
You don't check if the user is already inserted during sign up. There is no unique key in your users table. So I can signup with your admin email and (according with your code) I'm in. If somewhere in your code you don't check the users.id but email only, then you have a problem.
You should not login the client after the sign up, expecially if you don't force an email check (validation link). Generally this is a possible backdoor if you have some other bug somewhere (as first point, for example). Another point is to allow bots to entry in restricted area. That's not a great idea.
Structure security
use unique key on fields that must be unique (email in this case)
Language security
mysql_real_escape_string is deprecated and it will be removed. You must use PDO:: and Prepared statement
md5 or sha-1 are not so great. Use scrypt if you can; bcrypt if you cannot.
If I use the character & in my password, then I have the account exploitable. Because your javascript code is:
--
data : "email="+email+"&password="+password,
With a real data will be:
data : "email=my@email.it&password=my&!verystrong!!_#@[**password,
So my very strong password will be truncated at 2nd char. Both login and signup have the same issue. So my password will be valid and never I can suspect this issue. But a bruteforce attack will be more effective (my password will be simply "my") | {
"domain": "codereview.stackexchange",
"id": 35908,
"tags": "javascript, php, jquery, html, mysql"
} |
Diffusion of perfume according to fick's law | Question: Fick's first law relates the diffusive flux to the concentration under the assumption of steady state. It postulates that the flux goes from regions of high concentration to regions of low concentration.
Does this mean if we place a perfume in open air (uncoverd) then by time the perfume container will become empty? i.e all the perfume will spread through the air?
Answer: Diffusion happens because all regions do not have the same concentration. So it will stop when concentration is same everywhere. The perfume container may never become absolutely empty of perfume molecules. Because that would mean absolute zero concentration.
For all practical purposes though given enough time a perfume container will lose enough perfume molecules that it becomes non-fragrant for human senses. | {
"domain": "physics.stackexchange",
"id": 62651,
"tags": "diffusion, chemical-potential"
} |
Grains of salt and ionic bonds | Question: It is widely known that sodium chloride (NaCl), as well as any other salt, is held together by ionic bonds. Na$^+$ ions are surrounded by Cl$^-$ ions and vice versa.
What puzzles me is the fact that we can grind salt and store the grains together, and they don't stick to each other. Why aren't salts sticky? Even when ground, a salt is always composed of positive and negative ions and while at a distance the charge should be almost 0, when two grains are up close they should feel each other's attraction and stick together.
I'm obviously not considering the effect of water, or any other solvent, because it would change the crystalline structure of the salt.
My intuition tells me that it's probably a matter of distance between the grains or maybe air is to "blame", but I'm not sure where to look to find an answer to my question.
Answer: The simple answer is that they do stick together, and in the case of nanoscopic crystals they may permanently bind. But for larger crystals they stick so weakly that even the gentlest breeze can pull them apart. So the question is: why do large crystals bind so weakly?
Let's start at the beginning.
The shape (or morphology) of a crystal that naturally grows can be characterised in two ways. One is in terms of the hypothetical ideal (so-called thermodynamic) morphology which is the structure with the lowest possible free energy. In the case of sodium chloride this is a cube with perfectly flat faces (facets).
In the real world, however, the rapid fluctuations that occur at the surface of a growing crystal can produce a radically different (so-called kinetic) morphology.
Sodium chloride does grow to form crystals that, overall, look pretty close to a cube. However, the surfaces are not perfectly faceted, they are extremely rough at the microscopic and nanoscopic scales - covered in terraces, steps and kinks (see the TLK model of crystal growth). So when two crystals come together, there are very few points of contact (and therefore binding):
It is also worth noting that ionic bonding is relatively weak (in comparison to covalent bonding).
In fact, here is an image of table salt under a microscope:
There are two important observations to make:
Notice how rough the surfaces are? Well they get even rougher as you zoom in!
In this particular photo there are two grains of salt (each about 0.1 mm in size) which are actually stuck together. How did this happen? The most likely mechanism (although there are others) is that when these two crystals were much smaller (nanoscopic in size) they bumped into each other. And because they were so small, they would have had relatively flat faces that could stick together. And then they grew, forever wed. If you're curious why they're aligned at a perfect 45 degrees to one another, see crystal twinning. | {
"domain": "physics.stackexchange",
"id": 42846,
"tags": "physical-chemistry"
} |
Is there a way to see what representations are currently displayed in PyMOL? | Question: I am using PyMol to visualize .pdb protein structures.
I show/hide representation a lot, and sometimes I get confused with what representations are currently displayed. So I end up with doing a lot of hides (basically trying to hide each representation).
Is there a command which shows me what representations are currently used.
For instance if I have used
show ribbon
show lines
show mesh
hide lines
and than use some sort of showRepresentation
it will return me ribbon, mesh
Answer: You can use "as" to switch to a particular style (http://pymolwiki.org/index.php/As
):
as cartooon, 11AS and chain a
You can also hide everything, to remove all representations (http://pymolwiki.org/index.php/Hide):
hide every, 11AS and not (n. ca+c+n and resi 5-10)
I'm a fairly expert user of PyMOL and I've never seen an API exposed which will show you what representations are being used. That's not to say that it doesn't exist, there are a variety of undocumented features and commands still.
The problem is it isn't as simple as ribbon,mesh. Every single atom can be displaying any combination of representations, so as an API call or command, it would have to return the status of every atom in your selection. If the displayed representations are exposed somewhere they're probably in a very low level format like that, and not of use unless you're a programmer. | {
"domain": "biology.stackexchange",
"id": 982,
"tags": "bioinformatics, structural-biology, pymol"
} |
What is the relationship between a digital audio signal and sound pressure level? | Question: I'm playing a pure tone on an iPad through a pair of "standard" earphones. From a programming perspective, the output level is in the range of $0$ to $1$ where $1$ means "full volume".
I've observed using a sound pressure level meter that when playing a pure tone at $1000 \text{Hz}$ with output level in $0$ to $1$ with step size $0.05$, that the relationship between output level and sound pressure level is logarithmic.
However, I'm not sure if this is correct or an issue with my use of a sound field sound pressure level meter (instead of a coupler).
Should doubling the output level double the sound pressure level? That is, should the relationship be linear? It makes intuitive sense to me that as the output level or voltage is increased, the earphone speaker will vibrate more, and thus the sound pressure will also increase.
Answer: As you say, pressure will be proportional to output level, if the output level is equivalent to voltage. But sound pressure level (SPL) is by convention expressed in the logarithmic decibel (dB) scale, with 0 dB referenced to some standard sound pressure level. The relationship is:
$$\text{SPL} = 20\log_{10}\left(\frac{A}{A_\text{ref}}\right) \text{ dB,}$$
with a reference output level $A_\text{ref}$ that would give an SPL reading of 0 dB. For measures of power such as $A^2$ the formula changes slightly:
$$\text{SPL} = 10\log_{10}\left(\frac{A^2}{A^2_\text{ref}}\right) \text{ dB.}$$
With $A$ and $A_\text{ref}$ non-negative, the equations are equivalent with the square inside the logarithm or outside it as a factor $2$. | {
"domain": "dsp.stackexchange",
"id": 5499,
"tags": "audio"
} |
Is this the correct answer for the cardinality of this set? | Question: This is a question from a practice quiz at my university.
Is the question asking for the cardinality of Σ1 = {a,b} to the power of four?
if that's the case, then the set would still have a cardinality of 2 since elements in a set are unique. It wouldn't be {a,b,a,b,a,b,a,b} right?
Answer: This is how you should solve it.
Let $\Sigma_1=\Sigma$
We are asked to find: $|\Sigma^ 4|$
Now
$$\Sigma^4 = \Sigma . \Sigma . \Sigma . \Sigma = \{a,b\} . \{a,b\}. \{a,b\} . \{a,b\}$$
$$\text{ Here . means the concatenation operator}$$
So this is equivalent to number of ways of forming strings of length $4$ with symbols from $\Sigma$.
We have $4$ places,
Each of the places have two choices to get filled : either $a$ or $b$.
So,
_ _ _ _
2 . 2. 2. 2
So answer is $2^4 =16$ | {
"domain": "cs.stackexchange",
"id": 17923,
"tags": "sets, finite-sets"
} |
Space complexity below $\log\log$ | Question: Show that for $l(n) = \log \log n$, it holds that $\text{DSPACE}(o(l)) = \text{DSPACE}(O(1))$.
It's well known fact in Space Complexity, but how to show it explicitly?
Answer: So here is the main idea behind this fact. Let us denote by $C$ all possible configuration of the $l(n)$-space bounded TM. Notice that $|C|\le 2^{c\cdot l(n)}$, where $c$ is a constant depending on $M$.
We assume that the input tape is a two-way tape. Let $w$ be a word of size $n$, such that for all smaller words $u$ we have $l(w)>l(u)$. When the head moves from position $i$ to position $i+1$ on the input tape, or vice versa, we record the current configuration of the computation in the crossing sequence $C_i$. Assume we have $i\neq j$ with $C_i=C_j$. Then we define as $w'$ the word obtained from $w$ by deleting everything between the characters number $i$ and $j$. We observe that $w'$ is a shorter word which uses the same amount of space. Contradiction, there is no such $w$.
If $l(n)\in o(\log\log n)$ then you have $o(\log n)$ configurations and $o(n)$ crossing sequences. Hence two crossing sequences are the same.
Notice that if your input tape is 1-way, then even with $o(\log n)$ space you are doomed. | {
"domain": "cs.stackexchange",
"id": 795,
"tags": "complexity-theory, regular-languages, space-complexity, lower-bounds"
} |
What is Byte Alignment Time in radio communication? | Question: According to this paper, which deals with time synchronization in wireless networks, this kind of delay occurs, however I do not understand its explanation. The paper says the reciever (radio) has to determine the bit offset of the message from a known synchronization byte.
The definition from the paper is:
Byte Alignment Time —the delay incurred because of the different byte alignment of the sender and receiver. This time is deterministic and can be computed on the receiver side from the bit offset and the speed of the radio.
If somebody familiar with this phenomenon, can you please explain it to me?
Answer: This happens on a bit level of the receiver electronics.
For every byte you have to receive 8 bits. At this point in communication you only decoded the signal (eg. converted the electrical power or voltage) levels to bits. You receive bits in the buffer.
You are constantly filling the buffer (on a bit level), so you can check the buffer to see if you received anything. First you receive a lot of 000000, but then at one point message arrives, and bits in the buffer start to have different values.
Now if you are lucky first bit of the message arrives on let's say 8th or 16th place in the buffer (or 0th). This are all the bits that also start a logical representation of a byte.
If you are not that lucky, you just pushed in a 0 on 8th place of a buffer, and you would start filling the message in on the 9th place, which would in mean first seven bits from the original first byte would be received as first byte. And a second byte would be received as a last bit of the original first byte and first 7 bits of the original second byte and so on. This would mess things up good.
You have to be able to slide in some zeros in to the buffer in order to check up with the start filling the message in on the "start of byte position" of the buffer. But since you know how many zeros you had to fill in, you know how much delay this added for certain message (if you know the frequency of transmission).
EDIT:
Just to make things more exact:
you push the preamble in the buffer at random bytes, this is how you know you are getting something. sync is then used to sync the trasmission (eg. fill in the zerros so you start on right bit position). | {
"domain": "engineering.stackexchange",
"id": 634,
"tags": "electrical-engineering, terminology, wireless-communication, rf-electronics, digital-communication"
} |
When is an exoplanet called a Super-Jupiter? or Super-Earth? | Question: Is there a recognized definition of what size an exoplanet gas planet has to be to be classed as a SuperEarth or SuperJupiter? Is it based on radius or mass? i.e. All gaseous exoplanets > 1 Jupiter Radii are therefore classed a SuperJupiter? I note on Nasa's page of type of Exoplanets they don't mention e.g. Hot/Super-Jupiters so can I assume those terms are unofficial and therefore there is no consensus?
How about SubEarths and SubJupiters?
Can you tell from the Semi-Major Axis as to whether an exoplanet is a Hot-Jupiter/Hot-Earth or does that require more indepth study than just working out the SMA?
Answer: Super-Jupiters are planets with large masses, greater than that of Jupiter.
The "Jupiter" dividing line is rather arbitrary. There is no fundamental change in properties at the Jupiter mass.
Super-Earths are planets with a mass greater than Earth up to about 10 times the mass of Earth. Planets with radii between 1.2 and 2 times that of Earth are also called Super-Earths, though these two definitions overlap.
"Mini-Neptunes" is also a term sometimes used.
Hot Jupiters are typically Jupiter sized planets with an orbital period of less than 10 days.
None of these definitions is "official". This just summarises general usage. | {
"domain": "astronomy.stackexchange",
"id": 5750,
"tags": "exoplanet"
} |
Calculation of Distance from measured Acceleration vs Time | Question: I have an Accelerometer connected to a device that feeds the instant values of the acceleration in the 3 directions. I've tried to calculate the distance for a vertical movement using these values with excel (applying two times an integration), but somehow it doesn't seem to work properly.
How would be a good way to calculate the traveled distance from the measured acceleration using excel tables?
Answer: Starting at ${position}_z$ = $z$ = 0 and $v(z) = 0$ and by tracking multiple acceleration values either with a time interval or at fixed intervals, $t$, then you can get the position.... somewhat. It will drift over time. Also, your device cannot rotate whatsoever, or else you need a gyroscope to track that and then use trigonometry to properly orient the x y and z values from the accelerometer. Assuming it's always oriented such that the $a(z)$ is always perfect vertical acceleration (if you're in a vehicle that's always flat, in which case z doesn't matter, or you're on a vertical guide rail),
$$p(z) = \int_0^t v(z) ~dt = \iint_0^t a(z) ~dt $$
Also, from here:
Short answer: Forget about it.
Longer answer:
Unless you're on a perfectly straight rail, you will not achieve what you want to do without (a) a set of gyros; and (b) Far more accurate sensors than what you have.
Accelerometers measure acceleration in the body fixed reference frame, whereas you need some displacement in an earth-fixed frame.
Therefore, you need not only to integrate the accelerometers, but rotate them into the earth-fixed frame before doing the integration.
This is assuming perfect sensors. MEMS sensors are far from perfect - I have written up a post on some of the errors here.
Consider two errors:
1. A bias on the accelerometer.
2. An initial attitude (tilt) error.
In addition to whatever acceleration signal there is, integrate a bias and you get a ramp error with time. Integrate the ramp and you get a quadratically increasing error with time. This will add up really, really quickly.
Consider a tilt error. You'll now be measuring some of the gravity vector in the forward (or whatever) direction. Integrate this error twice and you'll have the same problem as the bias.
So, my advice again is DON'T! Find another method.
Also, check this book out for more detailed designs, or use whatever sensors and algorithm these guys are on:
http://www.youtube.com/watch?v=6ijArKE8vKU
If you still want to give this a shot, use the Trapezoidal method in Excel, it's pretty easy. There's an explanation page here with a sample, but here's a more complete way:
1 Time [A] Acceleration [B] Velocity [C] Distance [D]
2 0 a(z) 0 0
3 1 a(z) =C2+(A3-A2)*(B2+B3)/2 =D2+(B3-B2)*(C2+C3)/2
4 2 a(z) =C3+(A4-A3)*(B3+B4)/2 =D3+(B4-B3)*(C3+C4)/2
5 3 a(z) =C4+(A5-A4)*(B4+B5)/2 =D4+(B5-B4)*(C4+C5)/2
6 4 a(z) =C5+(A6-A5)*(B5+B6)/2 =D5+(B6-B5)*(C5+C6)/2
7 5 a(z) =C6+(A7-A6)*(B6+B7)/2 =D6+(B7-B6)*(C6+C7)/2
8 6 a(z) =C7+(A8-A7)*(B7+B8)/2 =D7+(B8-B7)*(C7+C8)/2
9 7 a(z) =C8+(A9-A8)*(B8+B9)/2 =D8+(B9-B8)*(C8+C9)/2
10 8 a(z) =C9+(A10-A9)*(B9+B10)/2 =D9+(B10-B9)*(C9+C10)/2
11 9 a(z) =C10+(A11-A10)*(B10+B11)/2 =D10+(B11-B10)*(C10+C11)/2
12 10 a(z) =C11+(A12-A11)*(B11+B12)/2 =D11+(B12-B11)*(C11+C12)/2
... ... ... ... | {
"domain": "physics.stackexchange",
"id": 4593,
"tags": "newtonian-mechanics, kinematics, acceleration, integration"
} |
Idiomatic approach to applying a keyword replace algorithm to a Java 8 Stream | Question: I have an approach that seems to work though I feel like I must be misusing something to achieve it. I am implementing a keyword matching algorithm to a Java 8 IntStream. The goal is to walk over a stream of char values (created by calling .chars() on an input string called sentence). If a keyword matches it is returned with its replacement value otherwise the original characters are returned unmodified. The code I have written so far looks like this: The Replacer is implemented as a Consumer<Character> with some stateful properties:
class Replacer implements Consumer<Character> {
StringBuffer out;
StringBuffer buffer;
KeywordTrieNode current_keyword_trie_node;
KeywordTrieNode keyword_trie_root;
public Replacer(KeywordTrieNode keyword_trie_root) {
this.keyword_trie_root = keyword_trie_root;
this.current_keyword_trie_node = keyword_trie_root;
this.out = new StringBuffer();
this.buffer = new StringBuffer();
}
@Override
public void accept(Character c) {
KeywordTrieNode node = current_keyword_trie_node.get(c);
if (node != null) {
buffer.append(c);
current_keyword_trie_node = node;
} else {
String keyword = current_keyword_trie_node.get();
if (keyword != null) {
out.append(keyword);
} else {
out.append(buffer);
}
out.append(c);
buffer = new StringBuffer();
current_keyword_trie_node = this.keyword_trie_root;
}
}
@Override
public String toString() {
// Flush the buffer
String keyword = current_keyword_trie_node.get();
if (keyword == null) {
out.append(buffer);
} else {
out.append(keyword);
}
return out.toString();
}
}
Then to use this I have this function:
public String replace(String sentance) {
return replace(sentance.chars());
}
public String replace(IntStream stream) {
Replacer replacer = new Replacer(this.keyword_trie_root);
stream.mapToObj(c -> (char) c).forEachOrdered(replacer);
return replacer.toString();
}
Here the String is converted into a IntStream, the stream is then mapped into a stream of char values (which are autoboxed into Character which is needed for the underlying Map inside the keyword_trie_root). Then the replacer is passed to forEachOrdered allowing it to see each character and build a bigger and bigger StringBuffer until it's toString() is invoked (performing one final buffer flush). This doesn't feel like the correct use of Java streams but I'm hitting a bit of a wall when trying to reimagine this as a Combiner which I think is the correct way to solve this problem. Any ideas?
Answer: Bug:
Calling toString repeatedly will append the last keyword (or the buffer) multiple times. This is not really in line with how this should work.
Conventions:
Java coding conventions state that member names should be lowerCamelCase. the fields related to the keyword trie do not follow that convention.
Another convention that you seem to disregard here is that Tries usually enable quick searching through strings by virtue of allowing skipping characters before doing the next comparison. As such naming the KeywordTrie as "Trie" is not really correct.
Minor simplifications & fixes:
You should specify explicit visibilities on all your fields. It's almost never appropriate to use the default visibility in java. package-private is almost always wrong.
The names you're using are somewhat wordy for my own taste as well.
In addition you can initialize fields in a field initializer instead of the constructor to make the ctor simpler to read. Consider:
public class Replacer [...] {
private StringBuffer out = new StringBuffer();
private StringBuffer buffer = new StringBuffer();
private KeywordTrieNode currentNode;
private KeywordTrieNode trieRoot;
Design issues:
A consumer should not return a result. That's not what they do. They take an element and that's it.
What you have here is a Collector. Something that takes a Stream and collapses it into a value. Let's make sure we use the correct interface here:
public class Replacer implements Collector<Character, StringBuilder, String> {
This in turn gives us the following functions to implement:
BiConsumer<StringBuffer, Character> accumulator()
Set<Consumer.Characteristics> characteristics()
BinaryOperator<StringBuffer> combiner()
Function<StringBuffer, String> finisher()
Supplier<StringBuffer> supplier()
Let's start with the important stuff that governs how the Collector will be used by the Stream implementation. Our collector is Ordered, Sequential and changes stuff when the finisher is invoked. This means that none of the Characteristics for optimization apply:
public Set<Collector.Characteristics> characteristics() {
return Collections.emptySet();
}
Now we can deal with the stuff that we need to set up:
public BinaryOperator<StringBuffer> combiner() {
// explicitly doesn't do anything, supplier always returns the same object
return (a, b) -> a;
}
public Supplier<StringBuffer> supplier() {
return () -> {
return out;
};
}
Note that I assume we're using the same private fields (and constructor) as in the question, because they seem like an acceptable encapsulation of the problem you're trying to solve.
Now we need to implement the accumulation, this is basically your "accept":
public BiConsumer<StringBuffer, Character> accumulator() {
return (out, character) -> {
KeywordTrieNode next = currentNode.get(character);
if (next != null) {
buffer.append(character);
currentNode = next;
} else {
String keyword = currentNode.get();
out.append(keyword == null ? buffer : keyword)
.append(character);
buffer = new StringBuilder();
currentNode = trieRoot;
}
};
};
public Function<StringBuffer, String> finisher() {
return (out) -> {
String keyword = currentNode.get();
out.append(keyword == null ? buffer : keyword);
return out.toString();
};
}
With this implementation we can rewrite your replace function to look as follows:
public String replace(IntStream chars) {
return chars.collect(new Replacer(keywordTrieRoot));
} | {
"domain": "codereview.stackexchange",
"id": 31331,
"tags": "java, stream"
} |
Which kernel produces sharper image | Question: kernel A = [ 0 -1 0 -1 4 -1 0 -1 0 ]
and B = [-1 0 -1 0 4 0 -1 0 -1 ]
i have found the frequency spectrums with freqz2 function of Matlab.
A's spectrum has the highest magnitudes in the corners (1,1),(-1,-1),(1,-1),(-1,1)
and B's in (1,0),(0,1),(-1,0),(0,-1).
I know that the center of the frequency spectrum has the low frequency information and the corners the high frequency information such as edges. It appears that B filter produces a sharper image although A has higher magnitude in the corners. Why is this happening ?
Answer: The sharpness of an image depends on acutance and resolution. The quantification of image sharpness seems image content dependent to me, since (i) sometimes the noise at the low SNR region may be enhanced with an high-pass kernel, and (ii) your A and B work on the edges with different orientations.
Take a very simple example:
T = [1 0 1;...
0 1 0;...
1 0 1];
conv(T,A,'same') gives you
[4 -3 4;...
-3 4 -3;...
4 -3 4];
while conv(T,B,'same') results in:
[3 0 3;...
0 0 0;...
3 0 3];
Looks like kernel A is better in sharpening the 45 degree edges. Yet with
T = [0 1 0;...
1 1 1;...
0 1 0];
The performance of two kernels looks reversed (B appears to be better in horizontal and vertical edges enhancement). | {
"domain": "dsp.stackexchange",
"id": 1587,
"tags": "image-processing, filters, fourier-transform, frequency-spectrum, highpass-filter"
} |
makePlan of GlobalPlanner plugin | Question:
I have saved a few PoseStamped in a file to describe a fixed path in a fixed map, now I want to make a plan out of them and send it to move_base. I wrote my own globalplanner-plugin for move_base, and stacked all my Poses in the vector plan of makePlan(). When I am starting the navigation, everything starts fine but after the robot passes the first Pose, he starts driving forwards and backwards around that point...
This is my makePlan(), where poses is a vector and contains the different PoseStampeds:
bool MyGlobalPlanner::makePlan(const geometry_msgs::PoseStamped& start,
const geometry_msgs::PoseStamped& goal, std::vector<geometry_msgs::PoseStamped>& plan){
if(!initialized_){
ROS_ERROR("The planner has not been initialized, please call initialize() to use the planner");
return false;
}
plan.clear();
plan.push_back(start);
for(int i=0; i<poses.size();i++){
plan.push_back(poses[i]);
}
return true;
}
Originally posted by Timo1804 on ROS Answers with karma: 18 on 2017-08-08
Post score: 0
Original comments
Comment by naveedhd on 2017-08-09:
It would help to publish the plan also so you can visualise in rviz if it is what you expect.
Comment by Timo1804 on 2017-08-09:
I have published it as nav_msgs::Path and it looks fine. Also the plan of the LocalPlanner looks good until he passes the first Pose after start-pose.
Answer:
I have solved that problem. You mustn't put all poses in your vector plan. I think makePlan() is called every time when the robot passes the next PoseStamped and you only have to put start, your next pose and the goal into it.
I changed the makePlan() to:
plan.clear();
plan.push_back(start);
if(pose_num <= pose_num_max) plan.push_back(poses[pose_num]);
plan.push_back(goal);
pose_num++;
return true;
}
The start and goal argument is sent by move_base.
Originally posted by Timo1804 with karma: 18 on 2017-08-09
This answer was ACCEPTED on the original site
Post score: 0
Original comments
Comment by naveedhd on 2017-08-11:
This doesn't seems to be the case. Publishing just the plan from standard global planner is a list of all the poses, and if the robot doesn't get stuck, this is only called once by move_base.
Comment by aarontan on 2018-06-29:
I am trying to solve a similar issue, do you have a repo that you may share for this?
Comment by naveedhd on 2018-07-02:
try setting the planner_frequency to 0 in move_base dynamic reconfigure. This way move base will not feed plan again and avoid robot oscillating. | {
"domain": "robotics.stackexchange",
"id": 28558,
"tags": "ros, navigation, move-base, global-planner"
} |
What is 'Retention period' in chromatography and what is its importance? | Question: I heard people quite often speak about retention time/retention period in Chromatography and Mass Spectrometry. I see somewhere that it is the time duration between the injection time and the target compound peak. I have the following questions:
1)What is the purpose of defining that time?
2)If the compound peak is absent, how one can speak about retention time (I mean if the compound completely fragments)?
3)Is it has importance in mass spectrometry as well?
Answer: To answer your three questions in series:
1) The time is a measure of how strong the interaction of a compound is with the column used. The stronger the interaction the longer the compound will stay on the column and this is therefore a way to separate two compounds. For example one molecule with a weak interaction spending a minute on the column, the other spending 5. Collecting fractions of solvent from a liquid chromatography column will yield pure compounds. Note that the time is also a measure for the amount of 'solute' flushed over the column. Many chromatograms also report retention in column volumes of solute. I will not go into detail about that here. It might be worth a separate question.
2) If no peak is found, no retention time can be reported. In chromatography it never (actually almost always) good when a compound fragments/degrades. That means the technique is not suited for purification or analysis. In unique cases, the degradation can be used to analyse whether or not a compound will degrade when interacting with certain materials.
3) In mass spectrometry a retention time in the machine is, as far as I am aware a 'Time of Flight'. Compounds are quickly brought into a gaseous and charged state and are pulled through a magnetic field. Depending on the weight of a compound, the time it flies, is shorter or longer. That is a way of calculating the weight of a molecule. In some cases, for example small proteins, the molecules are purposefully fragmented. The fragments can then be used to reconstruct of what amino acids the protein is made of.
Hope this answers your question! If any clarification is needed, please, do ask :) | {
"domain": "chemistry.stackexchange",
"id": 2770,
"tags": "mass-spectrometry, chromatography"
} |
How much energy per area or volume is the solar wind producing? | Question: Would it be possible to erect essentially a giant loop of wire in interplanetary space to create an electric generator? If so, how much power can we get?
Answer: The energy in solar wind particles is much less than the energy in light. You would do better with solar panels, or just heating from absorbing light.
You can find enough to do some calculations here. The Solar Wind Energy Flux. See page 203 for mass density and speed of the slow and fast solar wind. Keep in mind this is rough. The solar wind goes up and down with the solar cycle. Gravity slows the solar wind as it travels away from the Sun. And other things are going on that affect its energy.
Taking the values in the link, the slow wind has a density of $0.8 \cdot 10^{-20}$ kg m/s$^2$ and travels at $4 \cdot 10^5$ m/s. So the kinetic energy in a cubic meter is $6.4 \cdot 10^{-10}$ Joule. If you set up a $1$ m$^2$ collector, $4 \cdot 10^5$ m$^3$ of solar wind would pass through it each second, so the total power available for harvesting would be $2.5 \cdot 10^{-4}$ Watts.
The fast solar wind energy is similar.
By contrast, NASA says the solar power passing through that same square meter on Earth is about $1370$ Watts. | {
"domain": "physics.stackexchange",
"id": 76261,
"tags": "electricity, estimation, power, solar-system, solar-wind"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.