text:
# Integrating over level sets of a function

+ 4 like - 0 dislike
10 views

I have a background in math, but I think the following construction appears often in physics.

Is there a term for a functional which maps one smooth function $f: R^n \rightarrow R$ to another $L(f):R \rightarrow R$ which represents the integral along each level set? That is, $L(f)(a) = \int_{f^{-1}(a)} d\mu$ where the measure $d\mu$ might be the induced measure from the metric on $R^n$, or it might also depend on the original $f$ in some intelligent way.

For instance, if the initial function is $f:R^2 \rightarrow R$ is defined $f(x)=x^2+y^2$ then $L(f)(a) = 2 \pi \sqrt{a}$.

If the original function is $f:R \rightarrow R$ is defined $f(x)=x^2$, then we'd have $L(f)(a)=0$ for $a<0$, $1$ for $a=0$, and $2$ for $a>0$. In both cases it might be more natural to integrate with a term derived from the value of $f'$ normal to the level set.

I suppose one could generalize to any smooth map $f:M \rightarrow M'$ from a Riemannian manifold to a another smooth manifold and get a new function that represents a computed volume of the preimage for each point: $L(f):M' \rightarrow R$.

My question: Is there a good way to compute $L(f)$ for some class of function $f$?

Any thoughts would be appreciated. It is reminiscent of (but I hope simpler than) stationary phase approximations and path integral calculations.

http://en.wikipedia.org/wiki/Stationary_phase_approximation

This post imported from StackExchange Mathematics at 2014-06-02 20:26 (UCT), posted by SE-user Obidiah

+ 2 like - 0 dislike

If I remember correctly, what you are describing is close to the concept of a distribution function (it is the name that I am slightly unsure about).

Given a measure space $(X,\mathcal{E},\mu)$, and a measurable function $f:X\to \mathbb{R}$, a concept often used in classical and harmonic analysis is the notion of the distribution function $\lambda_f:\mathbb{R}_+\to\mathbb{R}$ defined as

$$\lambda_f(a) = \mu\left( \{|f| < a\} \right)$$

that is, $\lambda_f$ is returns the measure of the set on which $|f|$ is bounded by $a$. One can reformulate the $L^p$ norms of $f$ in terms of the distribution function

$$\|f\|_{L^p(X,\mu)} = p \int_0^\infty t^{p-1}\lambda_f(t) dt$$

a device that is very useful for analytical estimates. Now, formally speaking the functional $L(f)$ you wrote down is very similar to the derivative $\lambda_f'$.

Another possibility that you may want to look into is the notion of pull-back distributions. If $f:M\to\mathbb{R}$ is a smooth map with non-vanishing gradient, then given any distribution (generalized function) $k$ on $\mathbb{R}$ you can define the pull-back distribution $f_*k$ on $M$. The definition of $f_*k$ depends closely on the notion of $L(f)$ you wrote down (see e.g. the introduction to distributions by Friedlander and Joshi), and is a generalization of the co-area formula.

I am not exactly sure how to answer your second question of "is there a good way to compute". If you are asking whether given an analytic expression for the function $f$ whether you can have a "closed form" expression for $L(f)$, the answer is surely no, since the expression also depends on the chosen Riemannian metric/volume form/measure on $M$. If you are asking whether there are any convenient expressions to capture $L(f)$, I think you need to say a bit more about why you care about $L(f)$. You can certainly just write $L(f) = f_*\delta_a$ as the pull-back of the Dirac delta distribution on $\mathbb{R}$; whether that expression is a useful one for your purpose, I don't know.

This post imported from StackExchange Mathematics at 2014-06-02 20:26 (UCT), posted by SE-user Willie Wong
answered Dec 30, 2010 by (570 points)
other way: $\lambda_{f}(a)=\mu(x:|f|>a)$ (Folland)

This post imported from StackExchange Mathematics at 2014-06-02 20:26 (UCT), posted by SE-user TKM
+ 1 like - 0 dislike

Using the Fourier transform representation of the Dirac measure on the level set, the volume of the level set (which is the required integral according to the examples given in the question) is given by (using the same notation as in the question):

$L(f)(a) = \frac{1}{2\pi} \int_{-\infty}^\infty \mathrm{d}k \,exp(-ika)\, \int\,|\nabla f|\,exp(ikf)\,\mathrm{d}\mu$

On a Riemannian manifold, the gradient is given by:

$\nabla f = \sum_{ij}g^{ij}\frac{\partial f}{\partial x^i}\frac{\partial}{\partial x^j}$

The two examples given in the question can be worked out according to this formula (the second example very easily, the first one involves integrals of trigonometric functions of a squared angle, but it can also be solved analytically).

This post imported from StackExchange Mathematics at 2014-06-02 20:26 (UCT), posted by SE-user David Bar Moshe
answered Dec 28, 2010 by (3,845 points)

 Please use answers only to (at least partly) answer questions. To comment, discuss, or ask for clarification, leave a comment instead. To mask links under text, please type your text, highlight it, and click the "link" button. You can then enter your link URL. Please consult the FAQ for as to how to format your post. This is the answer box; if you want to write a comment instead, please use the 'add comment' button. Live preview (may slow down editor)   Preview Your name to display (optional): Email me at this address if my answer is selected or commented on: Privacy: Your email address will only be used for sending these notifications. Anti-spam verification: If you are a human please identify the position of the character covered by the symbol $\varnothing$ in the following word:p$\hbar$ysicsOverfl$\varnothing$wThen drag the red bullet below over the corresponding character of our banner. When you drop it there, the bullet changes to green (on slow internet connections after a few seconds). To avoid this verification in future, please log in or register.


text:
### I/O Interfacing with current source and sink pins

Find out what is the difference between current sink and current source capable outputs of digital integrated circuits and microcontrollers

Current source and current sink are two commonly used terms that you will find in datasheets of microcontrollers and digital circuits. Even though most input pins of an IC nowadays are internally connected to the gate of MOSFET transistors which are voltage driven, there are situations when you have to take into account current capabilities (i.e. high speed switching or something else than a CMOS input is connected to an output pin). I'm thinking about LEDs and bipolar transistor driven devices, such as relay modules.

These inputs are current driven and need to source or sink currents to change state. Fortunately, most output pins of contemporary microcontrollers are push-pull type and can source and sink currents. This means you don't have to worry too much about the way you are connecting an LED to a digital output. But there are still in use circuits which can only sink or source currents. And if you're not paying attention to datasheet, you might very well fail to design a working circuit.

## Sink versus source

Current source means the pin can supply current to a load. Although that current is low (a few mA) is usually enough for driving an LED or the base of another transistor. Internally, when you set a source capable pin to high, a transistor switches on and "ties" that pin to VCC. A bigger load which needs current above the specifications of the device, will damage the output transistor.

On the other hand, current sinking pins drive loads by drawing currents from them. If you wonder how can this be, the only condition that needs to be met is to create a potential difference in order to determine a current flow. Therefore, a current sinking pin has an output transistor which "ties" it to ground when activated. The load must be connected between this pin and VCC and the current will flow when the output transistor is activated.

Internally, output transistors of output pins will have a weak pull-up or pull-down resistor. Actually, this may not be a resistor, but a very low constant current source/sink. This allows a very small current (less than 1 mA) to be sourced from a sinking pin, or to be sunk from a sourcing pin. But there are output pins which can sink and source similar amounts of current. This is because nowadays microcontrollers use push-pull output configurations. Let's see how this works with some explanatory schematics.

 Types of output pin configurations

## Current source

If the pin can supply current to a load, it's obvious you can connect a load to ground. This kind of output is active high.

 Current sourcing output connection

In the above example, assuming the P-channel MOSFET transistor is off, its drain-source resistance (Rds) is very high (a few giga-ohms). The current will flow through the blue LED, via the current limiting resistor (R_limit) and the internal pull-down resistor (R_pull) to ground. Since R_pull has a high resistance (and that's something you can't quite change), the blue LED may not light at all or it will be very dim.

When the transistor switches on, Rds goes low (less than 1 ohm). Current flows from VCC, through transistor D-S, then via R_limit it forward biases green LED and makes it light brightly. This time, the current amount flowing through LED is controllable by R_limit, and upper-limited by the capabilities of the transistor.

So, how can you make the blue LED light up (without changing the schematic)? There is a solution with a caveat. Add a parallel resistor to the internal pull-down (put your own pull-down resistor between output pin and ground).

 Adding a pull-down to current source output

Now, when the transistor is off, there is a higher and user selectable current flowing through the LED, with the help of Rext_pull. That is fine. The LED is on. But what happens when you want to turn it off? The transistor must source a high current through Rext_pull with the only purpose of keeping the output high. And that current must not exceed its limits. In other words, with a carefully chosen pull-down resistor you can achieve this, albeit increasing power requirements. This is actually a perfectly fine solution with inputs which require lower currents (transistors which need to be biased).

With this configuration, you made the output active low. And here comes the other potential issue. The initial state of the controller may cause problems. What I mean is that after power on, before the controller starts processing commands and setting the transistor, this is probably off. And your LED is on. This is completely undesirable in some situations. Take the example of a relay switching on a motor. You don't want it on for a fraction of second when you power-up the controller.

In other words, use current source outputs with ground connected loads.

As a side note, N-channel MOSFETs are preferred over P-channel ones in high power applications and are sometimes used to source current, with the load connected between source pin and ground. Although this increases the complexity of the driving circuitry (because gate voltage must be maintained higher than source voltage), it is commonly used to supply high amounts of current mostly because Rds(on) is lower for N-channel transistors, which results in less power losses across drain-source junction.

## Current sink

If the pin can draw current, you will connect the load to supply voltage. This kind of output is active low.

 Current sinking output connection

In the above example, assuming the N-channel MOSFET transistor is off, its drain-source resistance (Rds) is very high. The current will flow through the green LED, via the internal pull-down resistor (R_pull) and the current limiting resistor (R_limit). Since R_pull has a high resistance (and that's something you can't quite change), the green LED may not light at all or it will be very dim.

When the transistor switches on, Rds goes very low. Current flows from VCC, through blue LED and R_limit, then via transistor D-S to ground. The blue LED is now brightly on. The current amount flowing through LED is controllable by R_limit, and it upper limit is set by the capabilities of the transistor.

So, how can you make the green LED light up (without changing the schematic)? It the same way I shown above, with current source. This time, a pull-up is needed.

 Adding a pull-up to current sink output

The same issue will be encountered. By default, when transistor is off, the LED stays on. Rext_pull causes a high current flow only to keep the LED off (when transistor goes on).

In other words, use current source outputs with supply connected loads.

## Push-pull

This type of output configuration brings the best features, being able to both sink and source current. Instead of maintaining one of the states with a pull resistor, a second, complementary transistor is used.

 Push-pull output connection

There is not much to say here. When one of the transistors is switched on, the other goes off. In this way, in each state, the current flows through the load via one of the transistors. Loads may be connected either way (to ground or to supply voltage) since sink and source currents are usually equal.

## Practical example

Enough theory, let's build something. Where can I find such a limited digital IC which can only sink or source current? Well, apparently the bus I/O expander PCF8574 can only sink current on its parallel output port. It doesn't say that on the first page of the datasheet? Yeah, I know, I found it the hard way (after building a PCB where it should drive ground connected LEDs). They even say "Latched Outputs With High-Current Drive Capability for Directly Driving LEDs". This was all I needed to throw away the datasheet and build my LED driver with this amazing IC. Only to find I missed something - and I am not the only one. I extracted the following from datasheet:

• Absolute maximum ratings:
• Continuous output low current (IOL): 50 mA;
• Continuous output high current (IOH): -4 mA;
• Recommended operating conditions:
• High-level output current (IOH): -1 mA;
• Low-level output current (IOL): 25 mA.

Note the convention to define sourced current as negative. The parallel port of PCF8574 can also be set to input and I'm assuming this is why they used this kind of output limitation. In fact the ports of PCF8574 are push-pull, however the source of the P-channel transistor is current limited (the current source in schematic below is 100 μA).

 I/O ports of PCF8574 (extracted from datasheet)

Let's connect a couple of LEDs to the outputs of this IC and see what happens. On a breadboard, I wired one LED to ground and the other to VCC and tried to drive both. For consistency, I used identical LEDs (5 mm red LED with a forward voltage drop of about 1.91 V - measured with my GM328A component tester).

 LEDs driven by PCF8574. Top LED is properly connected, active low.Bottom LED needs current from the output pin because it is connected to ground.

The results are clear. With a 330 ohms limiting resistor, the current through the properly connected LED is 8.5 mA, at a pin low voltage level of 117 mV (close to ground). The current through the other LED is only 162 μA at a pin high voltage level of 1.775 V (far from 5 V supply voltage)! This high efficiency LED still emits light, even it isn't properly forward biased.

#include <Adafruit_PCF8574.h>

void setup() {
pcf.begin(0x20, &Wire);
pcf.pinMode(7, OUTPUT);
pcf.digitalWrite(7, LOW);  // current sinking LED
pcf.pinMode(2, OUTPUT);
pcf.digitalWrite(2, HIGH);  // current sourcing LED
}

void loop() {
}

I used the above code to set PCF8574 pins to output, taking into account active low or active high state for each connection type. It requires Adafruit library for this IC.

## Conclusion

Having a good knowledge of output pins current capabilities will help you avoid potential interfacing issues when interconnecting various peripherals with microcontrollers or other digital ICs. I think PCF8574 is a rare example of current sink only output pins in today's digital IC market.

The first question that comes to my mind is if it is really suitable for driving HD44780 LCDs? Well, as far as I can understand from the datasheet, all inputs are used to drive gate of MOS transistors. And, with the exception of E signal, all of them are pulled-up with a maximum current of 250 μA (page 51 of datasheet). Leakage current is less than 1 μA. Therefore PCF8574 can drive HD44780 while being used within datasheet specification.

In the next post we'll see what else can be driven by PCF8574.

format: plain


text:
# Sect. 4.1 Antiderivatives Sect. 4.2 Area Sect. 4.3 Riemann Sums/Definite Integrals Sect. 4.4 FTC and Average Value Sect. 4.5 Integration by Substitution.

## Presentation on theme: "Sect. 4.1 Antiderivatives Sect. 4.2 Area Sect. 4.3 Riemann Sums/Definite Integrals Sect. 4.4 FTC and Average Value Sect. 4.5 Integration by Substitution."— Presentation transcript:

Sect. 4.1 Antiderivatives Sect. 4.2 Area Sect. 4.3 Riemann Sums/Definite Integrals Sect. 4.4 FTC and Average Value Sect. 4.5 Integration by Substitution Sect. 4.6 Numerical Integration and Trapezoidal Rule Particle Motion CHAPTER FOUR: INTEGRATION

Write the general solution of a differential equation. Use indefinite integral notation for antiderivatives. Use basic integration rules to find antiderivatives. Find a particular solution of a differential equation. Sect. 4.1 Antiderivatives and Indefinite Integration

A physicist who knows the velocity of a particle might wish to know its position at a given time. A biologist who knows the rate at which a bacteria population is increasing might want to deduce what the size of the population will be at some future time. Introduction

DIFFERENTIAL EQUATIONS A differential equation is an equation that contains a derivative. By antidifferentiating, we can solve this equation for y.

Integrand Variable of Integration Constant of Integration Read: The antiderivative of f with respect to x or the indefinite integral of f with respect to x is equal to….. Indefinite Integrals The family of all functions that are antiderivatives of f (x) is called the indefinite integral. Integral Sign

Some General Rules They are just the derivative rules in reverse. Differentiation Formula Integration Formula

Some More General Rules Differentiation Formula Integration Formula Sum / Difference Rule for Integrals Power Rule for Integrals

Integrate

OTHER INTEGRALS THAT SHOULD BE KNOWN

Integrate

You Try… Integrate the following.

Rewriting before integrating

You Try… Find the antiderivative.

Initial Conditions and Particular Solutions When we find antiderivatives, we are creating a family of curves for each possible value of c, called the general solution. C=0 C=1 C=3 When we find the value of C, given a point on y (called an initial condition), we are able to find a particular solution.

Ex: Find the general solution of the equation F’(x) = and find the particular solution given the point F(1) = 0. Now plug in (1,0) and solve for C. 0 = -1 + C C = 1

Find the function f (x) for which and f (1) = 3. You Try… So, 3 = 1 + C and therefore, C = 2. Therefore, our function is

Given: Integrate: Substitute x=0 and 6 for f’(0) Thus c = 6 Integrate again: Substitute x = 0 and f(0)=3 c= 3 Find f(x) Answer: You Try…

Closure Explain how to integrate Explain how to check your answer the problem above.

SUMMARY for Integration A differential equation is an equation that contains a derivative. You can solve them analytically using integration. The integral of a derivative is called the antiderivative. Don’t forget to include an arbitrary constant. There are infinite solutions to a differential equation, but with an initial value you can solve for an arbitrary constant to help you calculate the final equation (particular solution). You SHOULD memorize the table of integrals on pgs. 244 & 391!! In addition, memorizing derivatives are very, very important!

Download ppt "Sect. 4.1 Antiderivatives Sect. 4.2 Area Sect. 4.3 Riemann Sums/Definite Integrals Sect. 4.4 FTC and Average Value Sect. 4.5 Integration by Substitution."

Similar presentations


text:
# Is it actually incorrect to say $x/1 = x$?

The rational numbers $\mathbb{Q}$ are defined as the field of quotients of $\mathbb{Z}$ under the relation $(a, b) \sim (c , d) \iff$ $ad = bc$. There is an obvious isomorphism between the subring $\{[(a, 1)] : a \in \mathbb{Z}$} and $\mathbb{Z}$ . So technically we only pair every integer $a$ with $[(a, 1)]$. They're not equal though. Am I just making a big deal out of nothing?

-
math.stackexchange.com/questions/14828/… related and probably a duplicate. –  user17762 Jan 16 '13 at 7:08

You are absolutely correct. However, this embedding $\iota\colon\mathbb Z\to \mathbb Q$ is canonical and it is customary to view it as the inclusion. Note that the same holds for $\mathbb N\to \mathbb Z$, $\mathbb Q\to\mathbb R$ and $\mathbb R\to \mathbb C$. However, once you have constructed either of these number sets from the one below, you are hardly interested in the ugly construction below the surface. You can either replace $\mathbb Q$ with $(\mathbb Q\setminus \iota(\mathbb Z))\cup \mathbb Z$ or simply demand that e.g. $\mathbb Q$ is an arbitrary field that is a superset of $\mathbb Z$ and has no proper subfield (and the explicit construction shows the existence of such a field)
There are many instances where an equivalence class is not denoted as such. For example, elements of the Hilbert space $\mathcal{H} := {L^{2}}(X,\Sigma,\mu)$ are equivalence classes of square-integrable functions, where two functions are said to be equivalent if and only if they differ on a $\mu$-null subset of $X$. However, one rarely denotes an element of $\mathcal{H}$ by $[f]_{\sim}$. Indeed, one simply picks a function $f$ that represents a given equivalence class and pretends that it is the class itself.
For your problem, the choice of $x$ as a representative of $[(x,1)]$ is canonical, so although the two objects are not exactly equal from the set-theoretic point of view, the usage of such a shorthand should not cause much confusion. In fact, we have been doing arithmetic this way since elementary school without much trouble! :)


text:
# A baked potato provides an average of 31 mg of vitamin C. If 5.0 lb. of potatoes has 15 potatoes, how many milligrams of vitamin C are provided per pound of potatoes?

May 15, 2018

$93$ miligrams
If $5$ pounds of potatoes are equal to $15$ potatoes, then a pound of potatoes is equal to $\frac{15}{5} = 3$ potatoes.
So, the total vitamin $C$ in a pound of potatoes is equal to:
(31 \ "mg")/(color(red)cancelcolor(black)"potato")*(3color(red)cancelcolor(black)"potatoes")/("pound")=93 \ "mg/pound"


text:
# MRI-related processing

## Importing and processing MRI data

1) Copy the data from the CD to a temporary directory on cibr server using the command scp (the same as in MEG data transfer). On the CD, the MR data might reside in directory DCM_xyz/DICOM or CDROM/a. The "xyz" are replaced by a study number. The path to the CD on each computer varies, but on the megprime computers it is /run/media/<username>/. An example command for copying the image files could thus be something like:

This will copy the DICOM images for subject S00001 to directory tmp under the home directory of the user. The user is specified with the 8-letter username. If you don’t have the ~/tmp directory yet, you can create it by commanding mkdir -p ~/tmp.

2) Start a connection to the CIBR server (like described elsewhere in the Intranet instruction pages) and launch a command terminal. To enable modification and later deletion of the data, you need to allow writing access for all the files. This is done most conveniently the following way: first, find your way to where the data are by commanding cd ~/tmp (if that is where you put your MRIs in step 1). Then, check the name of your imported directory (most often "a" or "S00001") and give yourself the write permission there: chmod -R +w S00001.

3) Start DicomBrowser and open all the MR slices you just copied to the server (use Ctrl-A). Check which series correspond to which files by navigating the tree structure on the left pane -- there are usually 4 series and the file names could be something like z123. The series we are interested in are most often called “Sag CUBE T1” and either “T2 FSE” or "Propeller T2", if both T1 and T2 have been acquired. You will need these information soon when running the FreeSurfer reconstruction pipeline.

4) Using DicomBrowser, pseudonymize all the data:

• load all imported data under DICOM/S00001/ directory (use mouse or Ctrl-a to select all imported slices)
• select and double-click the field "patient name" to open the DICOM metadata viewer
• Replace fields “patient name”, “patient ID”, “birthday” and other possible identifiers with the subject’s pseudonym code and other non-identifiable data
• click “save” and be sure to select “overwrite existing files”

5) To start FreeSurfer processing, make sure that you have correct $SUBJECTS_DIR exported. A directory for storing the MRIs and FreeSurfer results is usually /projects/<project_name>/mri/. Please refer to “Preparing head models from MRI” below for further help. 6) After FreeSurfer processing is completed, remove the temporary MRI data directory created in step 1 with rm -rf ~/tmp/S00001 -- be very careful here to not delete anything by accident! Keep the MRI data discs in a safe place. ## Preparing head models from MRI ### 1. Using FreeSurfer to prepare MNE head models These instructions walk you through creating anatomically valid models to be used in MEG/EEG source estimation. Tested with versions FS 7.1, MNE 2.7 What do you need? • access to CIBR server • MEG data in CIBR server • MRI data in CIBR server — see separate instructions for importing and pseudonymizing Setting up The software are pre-installed and the commands readily linked. Some users experience problems because of tcsh-shell; in this case changing to bash with the command bash is a good idea. All subsequent commands will be in bash format. Before starting, we need to set some environmental variables, which in this case control basically data paths. The first is the directory for FreeSurfer processing results,$SUBJECTS_DIR, which defaults to shared directory /opt/freesurfer7/7.1.1-1/subjects. You should change this to point to the MRI directory under your project. The subject ID currently in process can be set in a similar way:

export SUBJECTS_DIR=‘/projects/xbrain/mri’

export SUBJECT=‘case_0001’

In this example, our project would be called xbrain and the subject code is case_0001. From now on, $SUBJECTS_DIR will refer to the project’s subjects directory, and$SUBJECT will refer to the subject being processed. Thereafter, you need to localize your MRI slice files, one for T1 and one for T2.

Running and checking FreeSurfer reconstructions

The FreeSurfer recon-all pipeline can be run either as one big or three smaller parts. Here, we run everything at once. For more information on the stages, see the Wiki at:

https://surfer.nmr.mgh.harvard.edu/fswiki/recon-all

The recon-all pipeline performs skull-stripping, segmentation, Talairach transformation and spherical morphing, among others. The command to run this pipeline for a new subject is:

recon-all -s $SUBJECT -i <a_T1_slice> -T2 <a_T2_slice> -T2pial -wsatlas -all Replace the arguments <a_T1_slice> and <a_T2_slice> by paths to DICOM slice files that you have imported to the server and identified with DicomBrowser. If you don’t have T2-data, omit the T2-related arguments. Please note, that it takes around 10—14 hours per subject to run the whole process. If FreeSurfer finishes without errors, you continue to checking the results. If there are errors, take action according to the software’s suggestions. There are several results to be inspected. In particular, check the skull stripping — the result should show only the brain, without remnants of skull, skin, dura etc. left. You can check the skullstrip result by commanding freeview -v$SUBJECTS_DIR/$SUBJECT/mri/T1.mgz$SUBJECTS_DIR/$SUBJECT/mri/brainmask.mgz:colormap=heat:opacity=0.5 If there are some skull/dura left, the -gcut option seems to often work reasonably well. It might also help to try different values of -wsthresh. These are explained in https://surfer.nmr.mgh.harvard.edu/fswiki/FsTutorial/SkullStripFix_freeview. Check the recon-all pipeline link above for instructions on manual editing, if needed. recon-all -skullstrip -clean-bm -gcut -subjid$SUBJECT

Check how it looks like:

freeview -v $SUBJECT/mri/brainmask.mgz$SUBJECT/mri/brainmask.gcuts.mgz:colormap=heat:opacity=0.3 &

and re-run the relevant parts of the pipeline:

recon-all -autorecon-pial -subjid $SUBJECT Then, you can also check that the white matter and pial surfaces are correct: freeview -v$SUBJECTS_DIR/$SUBJECT/mri/T1.mgz -f$SUBJECTS_DIR/$SUBJECT/surf/lh.pial$SUBJECTS_DIR/$SUBJECT/surf/rh.pial$SUBJECTS_DIR/$SUBJECT/surf/lh.white:edgecolor=red$SUBJECTS_DIR/$SUBJECT/surf/rh.white:edgecolor=red Set up MRIs and source space The original MRI slices and sets will be needed in later stages of the analysis, so let’s import them. Now that we have set up the environmental variables, it is enough to command mne_setup_mri and image stacks$SUBJECTS_DIR/$SUBJECT/mri/T1-neuromag and brain-neuromag will appear. The brain-neuromag stack will include the skull-stripped slices. You can add the T2-stack by adding --mri T2 to the command. Next, we can proceed to setting up the source space, which will define the possible locations for the estimated neuronal currents in subject’s brain (see MNE manual Ch. 3.5): mne_setup_source_space --ico 4 The switch --ico 4 can be replaced by some other options to produce different source spaces — check the MNE manual Ch. 3.5. for this. The option --ico 4 will produce a source space with 5124 potential source dipole locations, each with 3 possible orientations. The file$SUBJECTS_DIR/$SUBJECT/$SUBJECT-ico-4-src.fif will now contain the Elekta FIFF-format description of the source space. Check these results by loading an MRI stack to the MRIlab software and overlaying the source space points. The points corresponding to source space <name>-src.fif can be found in $SUBJECTS_DIR/$SUBJECT/bem/<name>-lh.pnt and -rh.pnt. You can import these points to MRIlab via the File menu —> Import points.

Building the forward BEM model

The forward model is a mathematical-physical description of the extra-cranial electromagnetic field that would be generated by given neuronal currents. Understandably, an accurate forward model is needed before trying to estimate the inverse, i.e. which sources generated a measured field. The first thing we need is a conductor model, which describes the anatomical regions and their electric conductivities in the head. In the general case, one could employ a simple homogeneously conductive sphere as the head model, but as we’ve got this far with MRIs already, we will use those anatomical information to establish a more realistic model of the individual subject’s head.

mne_watershed_bem --atlas

will produce descriptions of the inner and outer skull surfaces and skin. If this is not accurate enough, you can adjust the watershed algorithm pre-flooding parameter from 15 to, e.g., 25 using the original mri_watershed function and the switch -h:

mri_watershed -h 25 -atlas -useSRAS -surf $SUBJECTS_DIR/$SUBJECT/bem/watershed/$SUBJECT$SUBJECTS_DIR/$SUBJECT/mri/T1.mgz$SUBJECT/bem/watershed/ws

You can check the resulting boundaries with Freeview, for example:

freeview -v $SUBJECTS_DIR/$SUBJECT/mri/T1.mgz -f $SUBJECTS_DIR/$SUBJECT/bem/watershed/${SUBJECT}_inner_skull_surface:edgecolor=red It is known that identifying the boundary surfaces of conductivity changes is enough to construct a boundary element model (BEM), which can be used in magnetic field computations (forward modeling). An additional step here is to link these surfaces to the directory bem to be used by the software: ln -s$SUBJECTS_DIR/$SUBJECT/bem/watershed/$SUBJECT_inner_skull_surface $SUBJECTS_DIR/$SUBJECT/bem/inner_skull.surf

ln -s $SUBJECTS_DIR/$SUBJECT/bem/watershed/$SUBJECT_outer_skull_surface$SUBJECTS_DIR/$SUBJECT/bem/outer_skull.surf ln -s$SUBJECTS_DIR/$SUBJECT/bem/watershed/$SUBJECT_outer_skin_surface $SUBJECTS_DIR/$SUBJECT/bem/outer_skin.surf

Optionally, these surfaces can be estimated with another software called SimNIBS. See the instructions below for this.

As can be seen, we are producing a 3-layer BEM model. Now that we have the source locations and conductivity regions all set, we are ready to start working with the forward model. There is a convenience script for setting up the forward model in MNE software:

mne_setup_forward_model --surf --ico 4

Adding a switch --homog signifies a homogeneous 1-layer model, which is enough for many MEG applications — if you have EEG data or otherwise prefer to, creating a 3-layer model with the above command is as easy, only that computations will last a bit longer. The script produces files *-bem.fif and *-bem-sol.fif, which include the BEM geometry model and the computational solution. In addition, surface points are saved in MRIlab and FreeSurfer compatible formats. It’s a good idea to check that the surfaces are in the right places by overlaying them e.g. on the T1-neuromag images in MRIlab. You can also ask the software to --check or even --checkmore the results. For further details, see Ch. 3.7 of the MNE manual.

We usually don’t need to care about bad channels at this point, as we are using MaxFilter to identify, mark and fix those. If this has not been done properly, give a list of bad channels with the utility mne_mark_bad_channels.

As another alternative to mne_watershed_bem you can also use the Seglab software by Elekta Neuromag — as some other steps also differ, see the MNE manual appendix A.2.

### 2. Using the SimNIBS software

Magnetic resonance images are needed to construct accurate individual head models for source modelling in MEG. Instructions for importing MRI data provided by Synlab, pseudonymizing them and preparing MNE-compatible head models using the FreeSurfer pipeline can be found above.

SimNIBS is a toolkit originally made for simulating the electromagnetic fields due to brain stimulation. It should be able to provide better anatomical surface reconstructions than the watershed algorithm shipped along FreeSurfer. Moreover, there is a group who develops SimNibs. To get started, you need the MRI data imported and prepared with recon-all. In the most simple use case, the next step is running the commands in the example SimNIBS script at:

/opt/tools/cibr-meg/MRI/simnibs_example.sh

Processing all steps in the example script will take a couple of hours. The script produces surface files (*.surf) for inner and outer skull and skin surface in the subfolder m2m_<subject>/fsmesh. You will use these surfaces in the FreeSurfer-based pipeline for preparing the BEM head models, instead of the surfaces produced by the “watershed” algorithm. Note that you still need FreeSurfer results for example in setting up the source space for MNE.

Copy the surface mesh files to the bem-subfolder in subject’s FreeSurfer directory or make symbolic links there, which goes by something like:

ln -s /path/to/fsmesh/inner-skull.surf /path/to/subject/bem/inner_skull.surf

The validity of the produced surfaces is checked using FreeView; for example in folder /projects/training/MRI/:

will overlay the inner and outer skull surfaces with T1-weighted MR images, where you can visually confirm that the surfaces have been extracted correctly. You can then proceed with the FreeSurfer instruction above, by preparing the forward model using the command mne_setup_forward_model —homog —surf

[END OF MEG-INDEPENDENT PROCESSING]

### Preparing MNE inverse operators

MEG-MRI co-registration

So far, this work has been independent of the MEG data. Thus, it should suffice to perform these steps only once per subject. From now on, the data from the MEG measurement will be used to include information about measurement sensors and head position.

The first and possibly the most important thing to do is manually co-registrating the MEG and MRI data in the head coordinate frame. This will inform the forward and inverse solutions on head location, which is very important for the computations and validity of the results — any inaccuracy here will be propagated forward and probably elevated in data processing. This is also the step in the pipeline for which you acquired the extra digitisation points during subject preparation and documented the digitised anatomical landmarks. At this point it is also important that channel info are correct, in particular that EEG channels and only them are named as such. Note: See MNE manual 7.16.1 if you want to utilise a high-resolution head surface tessellation in co-registration.

There are good instructions for this step in the MNE manual, which are replicated below— other possibilities to establish the MRI-to-head transform include using “mne coreg” from MNE-python or the Elekta MRIlab software. This part needs to be done for each session, i.e. if the fiducials digitisation has changed or there are new MRIs (or preprocessing).

————————————————————————————————————————

12.11.1 Initial alignment

Follow these steps to make an initial approximation for the coordinate alignment.

In command terminal, go to the subject’s data directory — make sure you have exported the correct $subject and$subject_dir environmental variables

Launch mne_analyze

Select File/Load digitizer data... and load the digitizer data from the MEG data file

Bring up the viewer window from View/Show viewer...

Click Options... in the viewer window. Make the following selections:

1. Switch left and right cortical surface display off.
2. Make the scalp transparent.
3. Switch Digitizer data off.

Bring up the coordinate alignment window from Adjust/Coordinate alignment...

Click on the RAP (Right Auricular Point) button. It turns red, indicating that you should select the point from the viewer window. Click at the approximate location of this point in the viewer. The button jumps up, turns to normal color, and the MRI coordinates of the point appear in the text fields next to the button.

Proceed similarly for the other two landmark points: Nasion and LAP

Press Align using fiducials. Notice that the coordinate transformation changes from a unit transformation (no rotation, no origin translation) to a one determined by the identified landmark locations. The rotation matrix (upper left 3 x 3 part of the transformation) should have positive values close to one on the diagonal. The x and y values of the translation should be small and the z value should be negative, around -50 mm.

Make the Digitizer data visible from the options of the viewer window. After a while, the digitizer points will be shown. The color and size of the circles indicate whether and how much the point is inside (blue) or outside (red) of the scalp. The HPI coils are shown in green and the landmarks in light blue or light red color.

12.11.2 Refining the coordinate transformation

Before proceeding to the refinement procedure, it is useful to remove outlier digitizer points. To discard an outlier point:

1. Click on Omit in the Adjust coordinate alignment window.
2. Enter 10 for the distance of the points to be discarded.
3. Click done. Points further than 10 mm disappear.

The coordinate transformation can be adjusted manually with the arrow buttons in the middle of Adjust coordinate alignment dialog.

An automatic iterative procedure, Iterative Closest Point (ICP) matching is also provided. At each iteration step:

1. For each digitizer point, the closest point on the triangulated scalp surface is determined.
2. The best coordinate transformation aligning the digitizer points with the closest points on the head surface is computed.

In step 2 of the iteration, the nasion is assigned five times the weight of the other points, since it can be assumed that the nasion is the easiest point to identify reliably from the surface image.

The ICP alignment can be invoked by entering the desired number of iterations next to the ICP align button followed by return, or simply pressing ICP align. The iteration will converge in 10 to 20 steps.

Warning: Use the ICP alignment option in mne_analyze with caution. The iteration will not converge to a reasonable solution unless and initial alignment is performed first according to Section 12.11.1. Outlier points should be excluded as described above. No attempt is made to compensate for the possible distance of the digitized EEG electrode locations from the scalp.

You can also rotate the transformation using the arrow keys.In the end the co-registration process, you should see roughly the same number of small red and blue dots on the scalp, and landmarks and coils in the correct positions. Remember that we are aiming at millimeter-scale accuracy!

12.11.3 Saving the transformation

To create a MRI FIFF description file, which incorporates the coordinate transformation, click Save MRI set in the Adjust coordinate alignment dialog. This will create the MRI set file in directory $SUBJECTS_DIR/$SUBJECT/mri/T1-neuromag/sets. You can choose to save the transformation matrix alone, e.g. to file ./meg-mri-trans.fif, to facilitate scripting.

————————————————————————————————————————

The forward solution

Finally, the source model, the BEM model, the MEG measurement info and MEG/MRI transformation are brought together to compute the forward solution. The BEM model is read from the sub-directory bem, the MEG information is collected from the FIFF data file, and the MEG/MRI transformation from the file “$SUBJECTS_DIR/$SUBJECT/mri/T1-neuromag/sets/COR-<user>-<date>-<time>.fif”, defined above. The forward solution for this subject and measurement is then obtained by the following command:

mne_do_forward_solution --meas <data_file_name>

The output is the forward solution file in the measurement directory, automatically named according to MEG data and source space, maybe something like 003_block1d_raw-003-ico-4-src-fwd.fif — you can also specify output with the switch —fwd. You can specify other things, like source space, BEM and transformation with options --src, --bem and --trans or --mri, respectively. You can also add --megonly to use a 1-layer model.

In MNE-Python, forward solution is built with:

mne.make_forward_solution(data.info, trans.fif, src, bem)

A separate forward solution is computed for each measurement file, because head position varies between measurements.

Computing the noise covariance matrix

The role of the noise covariance matrix is to describe the noise components that are expected in the recorded channel data. There is a small discussion in the MNE manual Ch. 3.12 on how this matrix should be computed. In a nutshell, use data that is as similar to your data of interest as possible, but without the neuronal component of interest. Most commonly, for evoked studies we use the pre-stimulus baseline of the epochs, and for studying ongoing activity we use empty-room recordings (or sometimes rest periods). If you have applied some pre-processing to your data, you need to apply the same pre-processing steps to the data used to compute the noise covariance.

MNE-Python offers nicely developed tools for covariance estimation and inverse operator preparation, as well as many subsequent processing steps. Estimating noise covariance is implemented in functions mne.compute_covariance() and mne.compute_raw_covariance()

You can also use e.g. mne_browse_raw to compute noise covariance matrices (see the MNE manual to learn the details).

Calculating and applying the inverse operator

In mne_analyze, inverse operator is generated with the following command (options can vary):

mne_do_inverse_operator --fwd /projects/brainx/c007/c007-fwd.fif --loose 0.2 --depth --senscov /projects/brainx/c007/ER-cov.fif

The forward and noise covariance data are loaded from the previously saved files. You can then load the MEG data and and start playing with source models!

To generate an inverse operator in MNE-Python, say for example:

inv = mne.minimum_norm.make_inverse_operator(ave.info, fwd, ncov loose=0.2, depth=0.8)

Here, fwd and ncov are instances of forward solution and noise covariance matrix. Check possible options for different kinds of inverse models in the manual or on-line documentation. Note, that you can create beamformers in MNE-Python in a very similar fashion!


text:
# zbMATH — the first resource for mathematics

A characterization of separable utility functions. (English) Zbl 0459.90005

##### MSC:
 91B16 Utility theory
Full Text:
##### References:
 [1] J. Aczél Z. Daróczy: On Measures of Information and Their Characterizations. Academic Press, New York 1975. · Zbl 0345.94022 [2] M. J. Beckmann U. H. Funke: Product attraction, advertising, and sales: Towards a utility model of market behavior. Z. Oper. Res. 22 (1978), 1 - 11. · Zbl 0381.90022 [3] B. R. Ebanks: Branching measures of information on strings. Canad. Math. Bull. 22 (1979), 4, 433-448. · Zbl 0434.94002 [4] B. Jessen J. Karpf A. Thorup: Some functional equations in groups and rings. Math. Scand. 22 (1968), 257-265. · Zbl 0183.04004 [5] C. T. Ng: Representation for measures of information with the branching property. Inform. Contr. 25 (1974), 45-56. · Zbl 0279.94018 [6] J. Aczél Z. Daróczy: A mixed theory of information. I: Symmetric, recursive and measurable entropies of randomized systems of events. Rev. Fr. Automat. Inform. Rech. Oper., Inform. Teor. 72 (1978), 149-155. · Zbl 0382.94012 [7] B. R. Ebanks: Symmetric, $$\beta$$-recursive inset entropies. · Zbl 0711.94012
This reference list is based on information provided by the publisher or from digital mathematics libraries. Its items are heuristically matched to zbMATH identifiers and may contain data conversion errors. It attempts to reflect the references listed in the original paper as accurately as possible without claiming the completeness or perfect precision of the matching.


text:
# How do you write the complex number in trigonometric form -4+4i?

Nov 26, 2016

The answer is $= 4 \sqrt{2} \left(\cos \left(\frac{3 \pi}{4}\right) + i \sin \left(\frac{3 \pi}{4}\right)\right)$

#### Explanation:

Let $z = a + i b$ be a complex number.

To convert to trigonometric form

$z = r \left(\cos \theta + i \sin \theta\right)$

We calculate the modulus, ∥z∥=sqrt(a^2+b^2)

$z = - 4 + 4 i$

∥z∥=sqrt(16+16)=sqrt32=4sqrt2

$z = 4 \sqrt{2} \left(- \frac{4}{4 \sqrt{2}} + \frac{4 i}{4 \sqrt{2}}\right)$

$= 4 \sqrt{2} \left(- \frac{1}{\sqrt{2}} + \frac{i}{\sqrt{2}}\right)$

So, $r = 4 \sqrt{2}$

$\cos \theta = - \frac{1}{\sqrt{2}}$

$\sin \theta = \frac{1}{\sqrt{2}}$

We are in the second quadrant

$\theta = \frac{3 \pi}{4}$

$z = 4 \sqrt{2} \left(\cos \left(\frac{3 \pi}{4}\right) + i \sin \left(\frac{3 \pi}{4}\right)\right)$


text:
Browse Questions

# Kjeldahl's method cannot be used for estimation of nitrogen in $(i)\; C_6H_5NO_2 ;\; (ii)\;Pyridine; \;(iii)\;C_6H_5 - N = N -C_6H_5 ;\;(iv)\;C_6H_5NHCOCH_3$

$(a)\;(i),(ii) and\;(iii) \\ (b) \; (ii),(iii)\;and \;(iv) \\ (c) \;(i),(ii)\;and \;(iv) \\ (d)\;(i),(iii)\;and (iv)$

Kjeldahl method is not applicable to compounds containing nitrogen in nitro and azo groups and nitrogen present in rings (e.g. pyridine) as nitrogen of these compounds does not convert to ammonium sulfate under the conditions of this method.
Since these compounds are not completely converted into $(NH_4)_2\;SO_4$ during digestion.
$(i),(ii) and\;(iii)$ cannot be used for estimation of nitrogen using Kjeldahl's method.
Hence a is the correct answer.
edited Mar 20, 2014


text:
# Linear Homogeneous Equation (Allen 2017)

261 views

Consider a system of equations (λ – a)x + 2y +3z = 0, x +2(λ – b) y + 3z = 0, x + 2y + 3(λ – c) z = 0, which has a non-trivial solution.

Product of all values of λ for above system is

 (1) abc + a + b + c + 2 (2) abc + a + b + c – 2 (3) abc – a – b – c – 2 (4) abc – a – b – c + 2

Ans given is Option C.

Can anyone explain the complete solution?

$A=\begin{bmatrix} \lambda- a &2 &3 \\ 1& 2\lambda-2b &3 \\ 1&2 & 3\lambda-3c \end{bmatrix}$

$=\begin{bmatrix} -a+\lambda &2 &3 \\ 1&-2b+2\lambda &3 \\ 1&2 & -3c+3\lambda \end{bmatrix}$

We find the values of $\lambda$ which satisfy the characteristic equation of the matrix $A$, namely those values of $\lambda$ for which

$|A-\lambda I|=0$

$\begin{vmatrix} -a+\lambda &2 &3 \\ 1&-2b+2\lambda &3 \\ 1&2 & -3c+3\lambda \end{vmatrix}=0$

$\begin{vmatrix} -a+\lambda &2+0 &3+0 \\ 1+0&-2b+2\lambda &3+0 \\ 1+0&2+0 & -3c+3\lambda \end{vmatrix}=0$

$\begin{vmatrix} -a &2 &3 \\ 1&-2b &3 \\ 1&2 & -3c \end{vmatrix}+\begin{vmatrix} \lambda &0 &0 \\ 0& 2\lambda &0 \\ 0&0 & 3\lambda \end{vmatrix}=0$

$\begin{vmatrix} -a &2 &3 \\ 1&-2b &3 \\ 1&2 & -3c \end{vmatrix}+6\lambda ^{3}\begin{vmatrix} 1 &0 &0 \\ 0& 1 &0 \\ 0&0 & 1 \end{vmatrix}=0$

$-6abc+6a+6b+6c+12+6\lambda ^{3}=0$

$6\lambda ^{3}=6abc-6a-6b-6c-12$

$\lambda ^{3}=abc-a-b-c-2$

Hence,Option$(3)abc-a-b-c-2$.
0

Thank you @LeenSharma Veteran.

You made it look so simple.

M=$\begin{pmatrix} -a+\lambda &2 &3 \\ 1&-2b+2\lambda &3 \\ 1&2 & -3c+3\lambda \end{pmatrix}$=0

can be written as:-

M=$\begin{pmatrix} -a &2 &3 \\ 1&-2b &3 \\ 1&2 & -3c \end{pmatrix}$ / -6   -  $\lambda$/-6 $\begin{pmatrix} -1 &0 &0 \\ 0&-2 &0 \\ 0&0 & -3 \end{pmatrix}$=0

|M'-$\lambda$I|=0

:represent  $\lambda$ is eigen values of given matrix.....and product of all the values of is equal to the determinent of matrix M' /-6

M'=$\begin{pmatrix} -a &2 &3 \\ 1&-2b &3 \\ 1&2 & -3c \end{pmatrix}$   /-6

Det(M')devided by -6=option C

edited by
0

How did you split the matrix into two matrices?

@hs_yadav can you explain it further, pl.

0

If system has a non-trivial solution then determinant of matrix should be Zero.

## Related questions

1 vote
1
321 views
For what values of $\lambda$ the system of equations will have $2$ linear independent solutions - $x + y + z = 0$ $(\lambda + 1) y + (\lambda + 1) z = 0$ ($\lambda^{2}- 1) z = 0$ Now the problem i'm facing is if there is $2$ Linear ... rank of matrix will be $1$. Can anyone please explain in simple why the rank of matrix should be $1$ if we need $2$ Linear Independent solution. Thankyou.
Test the consistency of the following system of equations and solve if possible $3x + 3y +2z = 1$ $x + 2y = 4$ $10y + 3z = -2$ $2x - 3y -z = 5$


text:
# Thread: Finding a polynomial equation based off its graph

1. ## Finding a polynomial equation based off its graph

So it wants me to find a formula. I got ((-9)(x-1))/((x+3)(x-3)). The last part of the graph is not coming out correctly though. How do I alter the formula so that the right side of the graph flips over the x-axis?

2. ## Re: Finding a polynomial equation based off its graph

Hello, DasRabbit!

There are vertical asymptotes at $x = 3$ and $x = \text{-}3.$
$f(x)$ has $(x-3)(x+3)$ in the denominator.

With the "usual" vertical asymptote, the graph goes to $+\infty$ on one side
. . and to $\text{-}\infty$ on the other side (as it does at $x = \text{-}3$).

At $x = 3$, the graph goes to $+\infty$ on both sides.
This indicates that the factor $(x-3)$ in the denominator is to an even power.
. . Hence, the denominator has: . $(x-3)^2(x+3)$

Since there is a horizontal asymptote $(y = 0)$, the numerator has a degree less than 3.
. . Assume (for simplicity) that the numerator is linear.

We have: . $f(x) \:=\:\frac{ax+b}{(x-3)^2(x+3)}$

We want: $f(0) = \text{-}1\!:\;\frac{b}{(-3)^2(3)} \:=\:\text{-}1 \quad\Rightarrow\quad b \,=\,\text{-}27$

We want: $f(1) = 0\!:\;\frac{a+b}{(\text{-}2)^2(4)} \:=\:0 \quad\Rightarrow\quad\frac{a-27}{16} \:=\:0 \quad\Rightarrow\quad a \:=\:27$

Therefore: . $f(x) \:=\:\frac{27x - 27}{(x-3)^2(x+3)} \quad\Rightarrow\quad f(x) \:=\:\frac{27(x-1)}{(x-3)^2(x+3)}$

Test a few points to ensure that graph is on the correct sides of the x-axis.


text:
What is the theoretical upper limit on the rigidity of a material?

Take a perfectly rigid metal rod of length $2\ell$ and some uniform linear density. Place one end (‘south’) at $(0,-\ell)$ and the other (‘north’) at $(0, \ell)$. Over some reasonably short time interval $t$, perhaps on the order of a fraction of a second, displace the center of the rod eastward from $(0,0)$ to $(1,0)$. In practice it's very easy to do this so that the entire rod moves one unit eastward; in particular the north end moves from $(0, \ell)$ to $(1, \ell)$.

But this is actually a classical view of the situation. To see this, make $\ell$ very long, say on the order of ten light-seconds, and large enough to be bigger than $t\cdot c$. Then at time $t$ the center of the rod is at $(1,0)$ but the north end is still at $(0,\ell)$, because the north end can't have noticed yet that the middle has moved.

But this has an implication for the material properties of the bar. I claimed in the first paragraph that it was perfectly rigid, but it now appears that it isn't as rigid as all that. Purely from speed-of-light considerations we can conclude that even a perfectly elastic bar must temporarily deform in the process of being translated from $x=0$ to $x=1$.

It seems to me that if one assumed that the rod had length $2\ell$ and uniform linear density $\rho$, then one could calculate the amount of force required to translate it from $x=0$ to $x=1$ by pushing on the midpoint. Then supposing that the rest of the rod followed as quickly as speed-of-light propagation allows, one could calculate the stiffness of the rod, and this would be a theoretical upper bound on the maximum stiffness of any material whatever.

But I don't have enough expertise or understanding of materials calculations to do actually perform this one. Also I suspect I must have left out something important, for the same reason.

My questions are:

1. Can this calculation be done, or is there some reason the whole idea is unsound?
2. If it does make sense, what upper limit on material stiffness does this method produce?

I suppose that if it does work, the upper bound is vastly greater than the stiffness of any real material, but I don't mind that.

(I found the question Extended Rigid Bodies in Special Relativity, which is clearly related to this, but doesn't get at what I want. My earlier question Behavior of shock waves at relativistic speeds started out as an attempt to ask this one, and somehow went in a completely different direction by the time I posted it.)

• I would doubt there is such a limit. Rigidity is a statement about the material, which could be formulated in some local rest frame, whereas special relativity is essentially about kinematics. Dec 9, 2013 at 3:57
• @IsidoreSeville Er...rigidity is related to the speed of sound $v_s$ in the body and there is a hard limit $v_s < c$, so relativity does put a limit on rigidity. This is one of the arguments that without a modification to relativity all fundamental particles must by dimensionless. Dec 9, 2013 at 3:59
• @dmckee are you saying that there is a hard limit or there isn't? Your first sentence says there is, but your second sentence seems to be saying that the first sentence needs to be modified. Dec 9, 2013 at 4:04
• @NowIGetToLearnWhatAHeadIs: There are so called energy conditions, they do pose limitations on strains and tensions. (Although they are usually employed in general, not special relativity). Dec 9, 2013 at 4:22
• It comes down to: there can't be a perfectly rigid body, exactly because of special relativity. No matter what the macro force source, it comes down to fields imparting force on particles, and they can't be accelerated beyond said limits. Dec 9, 2013 at 12:39

Speed of sound is given by $$c=\sqrt{\frac{E}{\rho}}$$ - it depends on both density and Young's modulus. I would consider "rigidity" to be just the modulus, and if there is no theoretical limit on density then there is no theoretical limit on rigidity (following your logic).


text:
A Simple Console Based Keno/Lottery Game in C++

Earlier this week I provided this answer to the Original Poster of the question. Since I've already shown that I am not a C++ Guru, I have made the changes I suggested and I'm posting them for review. My question is what alternative Standard Template Library constructs I could have used to implement this. In case you aren't aware, copying is a major form of flattery.

The Basics of the game are:

• The user creates a balance of credits to play the game.

• Per game round the user enters a bet.

• The user then has the choice of either picking between 5 and 10 numbers between 1 and 60 or allowing the computer to pick between 5 and 10 numbers between 1 and 60.

• Each game round is scored based on the number of picks and the number of matches of those picks. Winnings are applied to the balance, bets reduce the balance.

• A zero balance prevents game play and allows the user to add credits.

The goals I had when writing this alternate solution are:

• Break the one file solution into multiple header and source files to provide better object oriented programming and reuse.

• Replace all C programming language constructs with C++ programming.

• Improve the readability and maintainability of the code.

• Follow the Single Responsibility Principle.

• Follow the DRY programming Principle.

• Reduce the number of lines of code in the solution.

Note: I was not successful in reducing the total number of lines of code, at least partially because breaking the code into header and source files adds some overhead lines of code, and because adding functions adds at least 3 lines of code for every new function. The original solutions is approximately 375 lines of code this alternate solution is approximately 440 lines of code.

One of the few major changes to the code, one is that the function kenoGameplay(Bank &credits) was turned into a class. The other is that an std::map() of multiple maps was used to replace a rather large case statement with embedded if statements in Award::awardWon(Bank &bank). A third was to decouple the Award class from the Bank class by adding another interface to the Bank class. A fourth was to change a C style array of integers into a std::vector. The final major change is that the random number generator now returns vectors of unique random numbers rather than a single random number and the interface is no longer a static member.

Possible Bugs in the Original that are Repeated Here

• If this were truly a Keno Game rather than a Lottery Game, then the bet should be used as a multiplier of the award, there is currently no reason to bet anything other than 1.
• Rather than forcing the user to bet every time allow them to choose to keep the same bet or change it.
• This program still uses the C standard library rand() function rather than more modern random number generators. This is offset somewhat by the fact that the implementation is now hidden and changing this will only force relinking after RandomNumber.cpp is recompiled.

Because I used Visual Studio 2015, this alternate solution is not portable without edits to remove stdafx.h from source files and replace #pragma once with guard bandes in the header files.

A specific question about the code is there a single STL construct I can use to replace this function, I don't think std::equal() will work since one vector is always length 15 and the other will vary between length 5 and length 10.

void KenoWinCalculator::calculateHits()
{
for each (auto playerPick in m_playerPick)
{
if (std::find(m_ComputerPick.begin(), m_ComputerPick.end(), playerPick) != m_ComputerPick.end())
{
m_hits++;
}
}
}

A second specific question I have is would it be better to use std::count() over std::find() in the above function.

EDIT
While I am specifically interested in STL improvements, all observations are good, since I'm far from perfect.

GetUserInput.h

#pragma once
#include <iostream>
#include <string>

template<typename T>
T PromptUserReturnResponse(const char* prompt)
{
T response;

std::cout << prompt << std::endl;
std::cin >> response;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

return response;
}

kenoGameConstants.h

#pragma once
static const int MIN_PICK_VALUE = 1;
static const int MAX_PICK_VALUE = 60;
static const int COMPUTER_PICK_COUNT = 15;

KenoGame1.cpp

#include "stdafx.h"
#include <iostream>
#include <string>
#include "Bank.h"
#include "KenoGamePlay.h"
#include "GetUserInput.h"

std::string welcomeUser()
{
std::cout << "******** WELCOME TO WORLD OF KENO ************** \n \n";
std::cout << "Hello! " << name << "...\n\n" << std::endl;

return name;
}

Bank StartTheBank()
{
Bank credits;

return credits;
}

int main() {
int programStatus = EXIT_SUCCESS;

std::string name = welcomeUser();
kenoGamePlay kenoGameController(StartTheBank());
programStatus = kenoGameController.GameLoop();

return programStatus;
}

kenogameplay.h

#pragma once
#include <iostream>
#include <vector>
#include "Bank.h"
//#include "RandomNumber.h"

class kenoGamePlay
{
private:
Bank &m_credits;
class RandomNumber *m_NumberGenerator;

protected:
int PlayOneGame();
std::vector<int> QuickPickNumbers();
std::vector<int> PlayerPicksNumbers();
bool IsQuickPick();
void DisplayIntegersInVector(std::vector<int> numbersToPrint) const
{
for each (auto num in numbersToPrint)
{
std::cout << num << "  ";
}
std::cout << "\n";

}

public:
kenoGamePlay(Bank &credits);
~kenoGamePlay() = default;
int GameLoop();

};

kenogameplay.cpp

#include "stdafx.h"
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include "kenoGameConstants.h"
#include "kenogameplay.h"
#include "KenoWinCalculator.h"
#include "Award.h"
#include "GetUserInput.h"
#include "RandomNumber.h"

static const size_t QUIT_VALUE = 100;
static const size_t MAX_NOS_PICKED = 10;
static const size_t MIN_NOS_PICKED = 5;
static const size_t INSERT_MONEY = 1;

kenoGamePlay::kenoGamePlay(Bank &credits)
: m_credits{credits}
{
m_NumberGenerator = new RandomNumber();
}

std::vector<int> kenoGamePlay::QuickPickNumbers()
{
int quickPickCount = 0;
char* Prompt = "How many number do you want the computer to pick (5-10)?";
do {
quickPickCount = PromptUserReturnResponse<decltype(quickPickCount)>(Prompt);
Prompt = "Invalid count value. Choose between 5 and 10 only.?";
} while (quickPickCount < MIN_NOS_PICKED || quickPickCount >  MAX_NOS_PICKED);

return m_NumberGenerator->GenerateAndGetVectorOfUniqueRandomNumbers(quickPickCount);
}

{
if (num >= MIN_PICK_VALUE && num <= MAX_PICK_VALUE) {
{
std::cout << "You already picked " << num << ". Please select another number. \n";
}
else
{
}
}
else
{
std::cout << "You entered an invalid number. Please try again \n";
}
}

std::vector<int> kenoGamePlay::PlayerPicksNumbers()
{
std::cout << "Pick between " << MIN_NOS_PICKED << " and " << MAX_NOS_PICKED <<
" unique numbers between " << MIN_PICK_VALUE << " and " << MAX_PICK_VALUE <<
". Enter " << QUIT_VALUE << " to QUIT entering numbers\n";

int num = 0;
{
num = PromptUserReturnResponse<decltype(num)>("Enter a number>>");
if (num == QUIT_VALUE)
{
{
}
else
{
std::cout << "You haven't selected enough numbers yet, please pick more numbers.\n";
}
}
else {
}
}

}

int kenoGamePlay::GameLoop()
{
int programStatus = EXIT_SUCCESS;
char continueGameplay = 'y';
bool isBetInvalid = true;
int insertMoneyReduceBet = 0;

while (programStatus == EXIT_SUCCESS && continueGameplay != 'n')
{
if (m_credits.isEnoughBalanceToPlayGame() || isBetInvalid == true)
{   // check if enough balance to play game

if (m_credits.isBetValid()) {
m_credits.updatebankBalance();
programStatus = PlayOneGame();
continueGameplay = PromptUserReturnResponse<decltype(continueGameplay)>("GAME OVER \nDo you want to play another round \n'y' to continue and 'n' to quit playing \n");
}
else
{
std::cout << "Invalid bet value." << std::endl;
isBetInvalid = true;
}
}
else
{
std::cout << "Not enough balance/valid bet. Please insert money( press 1) or place valid bet(press 2) to max bank balance " << m_credits.getBankBalance() << std::endl;
std::cin >> insertMoneyReduceBet;

if (insertMoneyReduceBet == INSERT_MONEY) {
insertMoneyReduceBet = PromptUserReturnResponse<decltype(insertMoneyReduceBet)>("Insert money ");
m_credits.setBankBalance(insertMoneyReduceBet);
}
else
isBetInvalid = true;
}
}

return programStatus;
}

int kenoGamePlay::PlayOneGame()
{
int programStatus = EXIT_SUCCESS;
std::vector<int> nosPicked = (IsQuickPick()) ? QuickPickNumbers() : PlayerPicksNumbers();

KenoWinCalculator winCalc(nosPicked);
winCalc.generateComputerPick(m_NumberGenerator);
winCalc.calculateHits();

Award wonAward(winCalc);
wonAward.awardWon(m_credits);

std::vector<int> playerPickedValues = winCalc.getPlayerPickValues();

DisplayIntegersInVector(playerPickedValues);

std::cout << "\nComputer selection: \t";
DisplayIntegersInVector(winCalc.getComputerPick());
std::cout << "\nno of hits: " << winCalc.getHitValue() << "\n" << "Your bank balance is: $" << m_credits.getBankBalance() << "\n"; std::cout.flush(); return programStatus; } bool kenoGamePlay::IsQuickPick() { return (PromptUserReturnResponse<char>("Do you want the computer to pick the numbers for you? [y]es or [n]o") == 'y'); }  Bank.h #pragma once class Bank { private: int m_bet; int m_bankBalance; public: Bank() : m_bet{ 0 }, m_bankBalance{ 0 } {} // this class maintains bet and player credit meter ~Bank() = default; void setBet(int betValue) { m_bet = betValue; } void setBankBalance(int balance) { m_bankBalance += balance; } void updatebankBalance() { m_bankBalance -= m_bet; } void depositWinnings(int winnings) { m_bankBalance += winnings; } int getBankBalance() const { return m_bankBalance; } bool isEnoughBalanceToPlayGame() const { return m_bankBalance >= m_bet; } bool isBetValid() const { return m_bet <= m_bankBalance && m_bet > 0; } };  RandomNumber.h #pragma once #include <vector> class RandomNumber { // Random number generator private: std::vector<int> UniqueRandomNumbersContainer; protected: int randomNumberGenerator(); public: RandomNumber(); ~RandomNumber(); void resetUniqueRandomNumbersContainer() { if (!UniqueRandomNumbersContainer.empty()) { UniqueRandomNumbersContainer.clear(); } } std::vector<int> getaVectorOfUniqueRandomNumbers() const { return UniqueRandomNumbersContainer; } std::vector<int> GenerateAndGetVectorOfUniqueRandomNumbers(size_t UniqueRandomNumberCount) { generateUniqueRandomNumbers(UniqueRandomNumberCount); return UniqueRandomNumbersContainer; } void generateUniqueRandomNumbers(size_t UniqueRandomNumberCount); };  RandomNumber.cpp #include <ctime> #include <algorithm> #include "stdafx.h" #include "RandomNumber.h" #include "kenoGameConstants.h" RandomNumber::RandomNumber() { srand(static_cast<unsigned int>(time(0))); } RandomNumber::~RandomNumber() { resetUniqueRandomNumbersContainer(); } int RandomNumber::randomNumberGenerator() { int randomRange = MIN_PICK_VALUE + MAX_PICK_VALUE; return (rand() % randomRange); } void RandomNumber::generateUniqueRandomNumbers(size_t UniqueRandomNumberCount) { if (!UniqueRandomNumbersContainer.empty()) { UniqueRandomNumbersContainer.clear(); } size_t generatedCount = 0; while (generatedCount < UniqueRandomNumberCount) { int rngValue = randomNumberGenerator(); if (std::find(UniqueRandomNumbersContainer.begin(), UniqueRandomNumbersContainer.end(), rngValue) == UniqueRandomNumbersContainer.end()) { UniqueRandomNumbersContainer.push_back(rngValue); generatedCount++; } } }  award.h #pragma once #include "KenoWinCalculator.h" #include "Bank.h" #include <map> class Award { private: // This class maintains pay table typedef std::map<int, int> HitMap; typedef std::map<int, HitMap> PlayerPickMap; int m_picks; int m_hits; PlayerPickMap MapSelector; public: Award(const KenoWinCalculator &calc); ~Award(); void awardWon(Bank &bank); };  Award.cpp #include <iostream> #include "award.h" #include "KenoWinCalculator.h" Award::Award(const KenoWinCalculator &calc) { m_picks = calc.getPlayerPickCount(); m_hits = calc.getHitValue(); // In each of the follow tuples the first number is the number of hits or matches // and the second number is the dollar reward. ie {4, 50} means 4 hits and$50.
HitMap Pick5Hits = { {4, 50}, { 5, 100} };
HitMap Pick6Hits = { {4, 100}, {5, 120}, {6, 150} };
HitMap Pick7Hits = { {3, 80}, {4, 90}, {5, 100}, {6, 120}, {7, 150} };
HitMap Pick8Hits = { {3, 80}, {4, 90}, {5, 100}, {6, 120}, {7, 150}, {8, 175} };
HitMap Pick9Hits = { {3, 80}, {4, 90}, {5, 100}, {6, 120}, {7, 150}, {8, 175}, {9, 200} };
HitMap Pick10Hits = { {3, 80}, {4, 90}, {5, 100}, {6, 120}, {7, 150}, {8, 175}, {9, 200}, {10, 250} };

MapSelector = { { 5, Pick5Hits}, {6, Pick6Hits}, {7, Pick7Hits}, {8, Pick8Hits}, {9, Pick9Hits}, {10, Pick10Hits} };
}

Award::~Award()
{
for each(auto hitmap in MapSelector)
{
hitmap.second.clear();
}
MapSelector.clear();
}

void Award::awardWon(Bank &bank) {
int amtWon = 0;

auto correctHitMap = MapSelector.find(m_picks);
if (correctHitMap != MapSelector.end())
{
HitMap HitMapTosearch = correctHitMap->second;
auto HitValueMap = HitMapTosearch.find(m_hits);
if (HitValueMap != HitMapTosearch.end())
{
amtWon = HitValueMap->second;
}
}

if (amtWon > 0) {
std::cout << "Congratulations you won \$" << amtWon << "!\n";
bank.depositWinnings(amtWon);
}
else
std::cout << "Sorry you lost\n";

std::cout << std::endl;     // flush the output
}

KenoWinCalculator.h

#pragma once
#include <vector>
#include "RandomNumber.h"

class KenoWinCalculator {

private:
std::vector<int> m_playerPick;                              // vector is used because the size is not fixed,
std::vector<int> m_ComputerPick;                            // player can choose any picks between 5 and 10 but computer's is fixed
int m_hits = 0;

public:
KenoWinCalculator(const std::vector<int> &playerPick);
~KenoWinCalculator() = default;
void generateComputerPick(RandomNumber* NumberGenerator);   // Generate COMPUTER_PICK_COUNT unique computer picked random values
void calculateHits();                                       // Calculates no of common nos between player and computer pick
int getHitValue() const { return m_hits; }
int getPlayerPickCount() const { return static_cast<int>(m_playerPick.size()); }
const std::vector<int>& getPlayerPickValues() const { return m_playerPick; }
std::vector<int> getComputerPick() const { return m_ComputerPick; }
};

KenoWinCalculator.cpp

#include <algorithm>
#include "kenoGameConstants.h"
#include "RandomNumber.h"
#include "KenoWinCalculator.h"

KenoWinCalculator::KenoWinCalculator(const std::vector<int> &playerPick) {
m_playerPick = playerPick;
}

void KenoWinCalculator::generateComputerPick(RandomNumber* NumberGenerator) {                           // Generate 10 unique computer picked random values
m_ComputerPick = NumberGenerator->GenerateAndGetVectorOfUniqueRandomNumbers(COMPUTER_PICK_COUNT);
}

void KenoWinCalculator::calculateHits()
{
for each (auto playerPick in m_playerPick)
{
if (std::find(m_ComputerPick.begin(), m_ComputerPick.end(), playerPick) != m_ComputerPick.end())
{
m_hits++;
}
}
}

• Just to make sure, are you only interested in improvements regarding STL usage or would you also like general hints and corrections? – Ben Steffan Jan 5 '18 at 20:08
• @BenSteffan General hints and suggestions are good, but I am interested in the STL usage. I'm aware that I could improve my naming conventions, the use of Camel Case versus First Cap is inconsistent. Feel free to review everything since it is a learning experience no matter what. – pacmaninbw Jan 5 '18 at 20:14
• Fine, then I'll go ahead. – Ben Steffan Jan 5 '18 at 20:15
• Does your program actually compile? A conforming compiler should reject it. – Ben Steffan Jan 5 '18 at 21:14
• I think I remember that Visual Studio allowed that one to slip. Give me 5 minutes, I'm nearly done with my answer that includes a description of what I am talking about. – Ben Steffan Jan 5 '18 at 21:32

A Serious Bug

I am sorry to be the bearer of bad message, but your whole programs behavior is currently undefined. You have stepped into the C++ reference-lifetime-trap. Lets take a look at this piece of code:

class kenoGamePlay
{
private:
Bank &m_credits;
//...
};

m_credits is a reference to a Bank-object. References as class members are rare and very dangerous, so let's pull out our alarm lights and go investigate whether the reference is justified and used correctly:

int main() {
//...
kenoGamePlay kenoGameController(StartTheBank());
//...
}

Bingo. You're assigning a non-const, non-rvalue reference from a temporary, which is actually not allowed by the standard (and my compiler rejects it correctly). However, even if it were, you'd have a problem anyways: Since the lifetime of the temporary ends immediately, you now have a dangling reference that points to an invalid location in memory (= a location where no object of type Bank lives). Doing accesses through such a reference is undefined behavior, and thus your whole program becomes undefined.

Fixing this, however, is not at all difficult: Just remove the reference and let m_credits be a normal object of type Bank.

In general, avoid using references as members unless you are 100% percent sure of what you're doing. In almost all cases, you are running a high risk of shooting yourself in the foot and blowing your whole leg off in the process.

Regarding KenoWinCalculator::calculateHits()

As far as my knowledge of the STL goes, there is no single function that would do what you require here. However, I came up with an implementation using both std::count_if as well as std::find, which, in my opinion, is about as concise as it will get:

void KenoWinCalculator::calculateHits()
{
m_hits += std::count_if(m_playerPick.begin(), m_playerPick.end(), [this] (int a) {
return std::find(m_ComputerPick.begin(), m_ComputerPick.end(), a) != m_ComputerPick.end();
});
}

1. if (std::count(gameNumbersToPlay.begin(), gameNumbersToPlay.end(), num) != 0): Why are you using std::count here? You only care if an element exists or not, so you can terminate your search as soon as you have found a matching element, which is exactly how std::find behaves.

2. Depending on how much you love the STL, you could consider replacing most of your for-loops with std::for_each. However, this is a disputable refactoring; many people are going to disagree with that style. Ultimately, it's a matter of personal taste.

Various Hints and Tips

1. for each (... in ...) is not valid C++. In fact, when first reading your code, I was really taken aback because I thought that this shouldn't ever compile. However, it turns out (after researching) that this is actually a MSVC extension, albeit a really useless and horrible one, in my opinion. Please, please, please use the standard for (... : ...) syntax, lest you want a mob of C++ programmers with pitchforks and and burning torches show up at your door.
2. Don't use std::endl. It's bad, because a) '\n' does the job just fine, and b) std::endl actually also calls flush() on your output stream, which is something you very rarely want. Just stick with '\n' and call flush() directly when you mean to.

3. Order your includes. Why? Because ordering includes makes it easier to verify whether all necessary includes are actually there, in two different ways: One, it makes it easier to manually verify that all necessary headers are there and two, the compiler will complain if you are missing an include in a header file if that header file is included before its missing header is included

(For example, imagine A.h depends on including vector. However, the author of A.h forgot the include, and now you're using the header in your project file B.cpp, which also requires #include <vector>. If you first include A.h and then vector, your compiler will complain that it can't resolve std::vector in A.h. If you include vector first, however, this error does not surface because now the include is there. This is known as include shadowing.)

So how should you be ordering those includes? First of all, nearly all people agree on alphabetic ordering. Secondly, it makes sense to group headers into categories such as "files from the current project", "library headers", "STL headers" etc. If you do this, it is recommended to write, from top to bottom, first the header the current .cpp file is implementing (if any), then headers from the current project (i.e. local/internal headers), then headers from different projects and libraries (i.e. external headers) and finally standard headers. This is most likely to prevent include shadowing bugs due to each header being checked in its implementation file (given that such a file exists).

4. Always use std::size_t over size_t; the existence of size_t in the global namespace is not guaranteed by the standard, but in the std namespace it is.

5. Avoid including iostream everywhere. The reason for this is that iostream usually injects static instances for cout, cerr and cin which can lead to binary bloat. More importantly, however, iostream is a code smell, because using std::cout and family is constraining your users and yourself. Imagine, for example, a bot, which wants to run some 1000 or 10000 games of Keno and log the results to a file, or a websocket, or any other I/O device. Currently, the only way for that bot to achieve this is by redirecting standard output, but that might not always be possible. Also, what if the bot actually only wants to log the output of DisplayIntegersInVector() to its destination, but doesn't care for the rest you write? Currently, it would need to parse the standard output for that, which, again, might be constraining or unfeasible.

But if iostream is bad, how do you implement output functions? The answer is by refactoring your output functions to take an std::ostream as parameter and write to that instead. Syntax-wise, there is no change at all; the offered degree of flexibility, however, is much, much higher. (Don't forget to change #include <iostream> to #include <ostream>, though).

6. kenoGamePlay::DisplayIntegersInVector has two issues:

1. Why is that function part of kenoGamePlay? You don't do anything related to the class at all; this function should be freestanding.
2. The parameter numbersToPrint should not be passed by value, but by const& instead. std::vector is expensive to copy, and the function does nothing at all that would justify this extra cost.
7. Why are most member functions of kenoGamePlay protected? Is this class intended to be derived from? Doesn't look like it very much, since you have no virtual methods (not even a virtual destructor). If you still intend to derive from this, you should rethink your interface, if not, those members should be private.

8. Prefer using over typedef. It's more readable and more flexible.

9. Don't use single-letter string literals when not absolutely required. Writing "\n" hurts performance, especially when '\n' does the same thing in the same amount of characters.

10. You don't need to default all destructors manually; the compiler will generate a destructor for you automatically.

The bug I've found is somewhat unfortunate, but easy to fix. Apart from that, there are a lot of little things that you could do to improve your code, but apart from point 1 I didn't spot anything that would require immediate changes. However, it would be nice if you'd strive to make this code portable, i.e. remove #include "stdafx.h". Also, there are some irregularities in how you name things; you should decide on a coherent style for the sake of readability.

Regarding STL usage, I didn't actually find much that could be improved. Apart from replacing legacy C functionality (i.e. rand() and time()), there is not much to do in regards to making your code more C++-y.

• @BenSteffan, I had something similar but I didn't get even a warning on clang. When I approach things like this, I always ban constructors taking type&& and const type&&. There are better techniques described in this paper. – Incomputable Jan 6 '18 at 11:57


text:
🎉 The Study-to-Win Winning Ticket number has been announced! Go to your Tickets dashboard to see if you won! 🎉View Winning Ticket

Mass of a wire Find the mass of a wire that lies …

View
University of California, Berkeley
Problem 32

Find the area of one side of the "wall" standing orthogonally on the curve $2 x+3 y=6,0 \leq x \leq 6,$ and beneath the curve on the surface $f(x, y)=4+3 x+2 y$

Discussion

You must be signed in to discuss.

Video Transcript

Okay, folks. So in this video, we're gonna take a look at problem number 32 um, where were asked to find the area of one side of the wall, um, standing perpendicular early on a curve and beneath the curve, Um, and were given both of those cars. Okay, so, um, this might look like a word problem, but it's really not. It's really just regular line and girl problem. So in order for you to find an area, um, we're going to do basically the same thing that we did for, you know? Uh huh. Like simple two dimensional area finding problems where were given a curve aftereffects and were asked to find it. This this area, you know. So the way you do this kind of problem is I'm pretty sure you already know. You just integrate. Have effects along the thea the infinite decimal ice like Mindy X. Okay, so that's how you do. You know, a basic two dimensional area problem. And now that we're in three d, you know that the idea is really still the same? Um, So we're gonna we're gonna do an integral of F. But now it's not. It's more than just a function effects. It's also a function of why? Because, you know, we're in three D multiplied by instead of DX. We have DS. Okay, so So it's this is really kind of an analogy. Um, And I hope you understand that that even though we're in three D, the idea is still the same, you know, to find the area means to do in general a line, integral. All right. Anyway, that was the analogy. So now let's crank out some eligible. Here we have. Ah, an integral um Well, the function f is going to be four plus three x plus two. Why? So that's the function f multiplied by the Yes, but I'm not gonna write DS. I'm gonna write DS in another way because DS is simply a one plus y prime squared, multiplied by D X. Now, um, let me plug in the integration limits here. No, um, this is gonna be Let me write it this way. We have four plus three X plus two y. What is why prime? Well, why? Prime is first of all, um or that the curve that we're integrating over is two x plus three y equal six. And that means three y equals six minus two x. And why is two minus two you over three X and why Prime is negative to over three. So why Prime Squared is for overnight. Okay, multiplied by D x. No, this thing is someplace collaborative. 13 overnight multiplied by thin to grow of a plus, um, 5/3 X D. X from 0 to 6. Okay. And when you plug in the when you evaluate this thing, you get through 13 overnight, eight x plus 5/6 x squared between zero in six new. This is gonna be equal to route 13 overnight, 48 plus 30. So now we end up with 26 Route 13. And that's it for this view. This is the answer for problem number 32. Thank you for watching. Um, and this This is the answer. Thank you for watching by

Recommended Questions

You're viewing a similar answer. To request the exact answer, fill out the form below:

Our educator team will work on creating an answer for you in the next 6 hours.


text:
# Easy LBO

## 1. Introduction

We’re going to walk through a simple LBO model - it is not meant to be comprehensive. This model (and post) has the following objectives:

1. To teach core concepts and help you develop the understanding required to digest larger models. You can find a more complex LBO modeling guide here.

2. To serve as preparation for “paper LBOs.” We suggest practicing in Excel until you can complete it in less than 20 minutes. Then, try pen and paper.

Paper LBO
Often in PE interviews, in addition to a full-blown Excel modeling test, interviewers will grill candidates on LBO mechanics in person. You may have to calculate simplified debt paydown and returns calculations by hand. These are called “paper LBOs.”

Enough philosophizing, let’s get started. Here’s a blank copy of the model, and here’s a completed version with a new tab for each incremental step.

## 2. Core Assumptions

We tried to keep things as simple as possible, while still giving you a framework for more complex models. Below are the provided assumptions:

### Financials

• LTM Adj. EBITDA: $100mm • Annual EBITDA Growth: 6% • Annual CapEx:$30mm
• Annual D&A: $25mm • Annual Increase in NWC:$4mm
• Annual Tax Rate: 30%

### Transaction Assumptions

• Cash-free, debt-free: the company is sold with no debt and no excess cash. This is a common assumption.
• Transaction Multiple: 9x
• Transaction Expenses: $30mm ### Financing • Term Loan: 3x Leverage, 4% interest rate, 1% annual amort. • Senior Notes: 3x Leverage, 8% interest rate The assumptions under Financials are the bare-minimum required to calculate free cash flow. Under Transaction Assumptions and Financing we have enough information to determine the transaction structure. ## 3. Transaction The Sources & Uses section is one of the first steps in every LBO. Quite literally it represents the sources and uses of cash - where is the buyer getting the money from, and what precisely are they using it for? Let’s start with the Sources. 1. Since we know the leverage multiples for the term loan and the senior notes, we can calculate the debt raised for each tranche by multiplying the respective leverage multiple by LTM Adj. EBITDA. 2. We’ll come back to the sponsor equity. We’re going to use it as the plug to bridge the gap between total funds required and debt financing. Uses How do we get the equity purchase price? We have the LTM Adj. EBITDA and the Transaction Multiple, so we can calculate the Enterprise Value (a.k.a. the Transaction Value). Transaction Value = LTM EBITDA x Transaction Multiple We also know the relationship between Enterprise Value and Equity Value: Enterprise Value = Equity Value + Net Debt But remember: the transaction is cash-free, debt-free (net debt is$0), so the equity value equals enterprise value. Therefore, our Purchase Equity = LTM Adj. EBITDA x Transaction Multiple.

The transaction expenses are an illustrative assumption, so now we have total uses of cash.

Let’s go back to the Sources. We’ll set Sponsor Equity equal to the Total Uses - Debt. This mirrors actual deal dynamics - sponsors generally try to raise as much debt as possible. They pay for the rest.

Sponsor Equity = Total Uses - Term Loan - Senior Notes

Your Sources and Uses should look like this - check the completed model if you’re having trouble.

## 4. Cash Flows

Most of these line items should be familiar. Try to fill out as much as you can using the provided assumptions. You’re missing interest expense, so you can leave that out for now.

Your completed Cash Flows schedule should look like this:

You may be wondering: Where’s revenue? Good question. Since we’re making up numbers, no need to show revenue. EBITDA feeds into Net Income and, ultimately, Levered Free Cash Flow.

Here, using detailed financials is unimportant. For private equity investors, the opposite is true. Diligencing a company’s cash flows and building a detailed operating model are among the most important parts of the investment process.

For now, let’s stick to the financial mechanics.

## 5. Debt Schedule

Term Loan

1. Set the ending balance in the Closing column equal to the amount calculated in the Sources & Uses. This represents the amount outstanding immediately after the transaction closes.
2. Set the beginning balance in Year 1 equal to the ending balance at close.
3. Set the ending balance in Year 2 equal to the sum of the beginning balance, amortization and prepayment. Since amortization and prepayment are blank, the ending balance should equal the beginning balance. Copy these formulas across.

Ending Balance = Beginning Balance - Amortization - Prepayment.

4. Go back to our assumptions. We know that the Term Loan has annual amortization of 1%. This means that the company must pay 1% of the initial loan amount to the lenders each year. Try to fill out the correct formula, but be careful - loan amortization is a percentage of the initial amount, not the beginning balance each year.

Term Loans
Term Loans are a common source of debt financing for LBO transactions. To learn more, you can check out LeveragedLoan.com. Our more advanced LBO guide includes additional resources.

5. Onto Prepayment. For illustrative purposes, let’s set prepayment equal to available cash flow each year. This is a big simplification. Ordinarily, each debt tranche would have specific rules about when and how much they can be paid back early. Why would they want to limit being paid back early? If there weren’t limits to prepayment, companies could refinance outstanding debt whenever rates decreased, and they could leave debt in place whenever rates increased. Debt investors would be hosed. The reality is that companies do this anyways, but they have to pay debt investors extra fees for prepayment, and sometimes the fees can be quite onerous. Of course, the terms of prepayment and associated fees vary greatly by type of debt and specific issuance.

Cash Available for Prepayment = Levered Free Cash Flow - Mandatory Amortization

6. As a simplification, let’s calculate interest expense using the Beginning Balance each year. Ordinarily, we would use an average of the beginning and ending balances to account for the fact that debt is being repaid over the course of the year. This leads to Excel’s dreaded circular reference, as the more advanced guide explains. Let’s keep things simple.

Interest Expense = Beginning Balance x Interest Rate

Senior Notes
Now, it’s your turn. Replicate these calculations for the Senior Notes with a couple key differences:

1. Amortization is 0 in every year (you can hardcode it).
2. Prepayment is also 0.

Senior Notes are one of the types of debt that usually have steep penalties for prepayment. Furthermore, the term loan is senior to the notes in the company’s capital structure, which is a fancy way of saying the term loan must be paid back first.

Total Debt

1. Calculate total debt in each year as the sum of the ending balances.
2. Sum the total interest expense and link it back to the Cash Flows schedule.

Other Comments
We’re not calculating a cash balance anywhere, because all excess cash flow goes to paying down the Term Loan.

Your completed Debt Schedule should look like this:

## 6. Returns

Now let’s find out how much money this sponsor is going to make.

1. Link LTM Adj. EBITDA from the Cash Flows schedule.
2. Calculate the Transaction Value at exit for each year at each multiple.

We’re showing a range of multiples, because the sponsor never knows how much they’ll sell the business for. This allows us to answer questions like - if we exit in 5 years at 7.5x, what do returns look like?

3. Calculate the future equity value using the range of transaction values from the step above. We’re not building a cash balance, so Net Debt = Total Debt.

Equity Value = Transaction Value - Net Debt

4. Next up - MoIC: Multiple of Invested Capital. That’s PE speak for “how many times our money will we make?”

MoIC = Equity Value at Exit / Invested Equity

5. For simple transactions like this LBO (one cash inflow and only one outflow), we can derive the IRR from the MoIC:

IRR = MoIC ^ (1 / year) - 1

IRR and MoIC are the 2 most common metrics for evaluating PE transactions. And they’re better together. MoIC makes it easy to understand the profit from a transaction, but it does not take into account the time value of money. IRR does factor in time.

Your completed returns schedule should match this:

## 7. Next Steps

Congrats on completing the Easy LBO! Try the rest of our private equity modeling guides: