text:
# Kratos Magnetostatic Application

(Difference between revisions)
Jump to: navigation, search
 Revision as of 16:30, 1 February 2010 (view source)JMora (Talk | contribs)← Older edit Revision as of 18:39, 1 February 2010 (view source)JMora (Talk | contribs) Newer edit → Line 7: Line 7: * the use of Kratos for basic problems; * the use of Kratos for basic problems; − At a first glance, it could be said that Electrostatics works with static charges whereas Magnetostatics does it with dynamic charges (or [http://en.wikipedia.org/wiki/Electric_current static currents]). That's partially true and we avoid by now to + At a first glance, it could be said that Electrostatics works with static charges whereas Magnetostatics does it with dynamic charges (or [http://en.wikipedia.org/wiki/Electric_current static currents]). That's partially true and we avoid by now to argue about it. On the opposite, we are going to consider Magnetostatics as a completely new phenomenon instead of thinking in a kind of 'dynamic' electrostatic. − , but we are going to consider Magnetostatics as a completely new phenomena instead of thinking in a kind of electrodynamics. + As Electrostatics, Magnetostatics establishes very basic principles of the Maxwell equations, it is an excellent work at academic level, but it is also a powerful conceptual (and eventually the resulting computing tool) to solve important industrial applications (electrical machines such as motors and transformers, circuit components such as coils, permanent magnets, sensors, magnetic field distribution, etc). − + − + − + − Magnetostatics + − + − Electrostatic establishes the most basic principles of the Maxwell equations and it is excellent to work at academic level. Nevertheless, some serious industrial applications can be solved by using just these simplest equations and simulation program (circuit components such as condensers and bipolar diodes, electrical field distribution for high voltage systems, etc). + == Theory == == Theory == − Magnetostatics[1][2][3] refers to the physical phenomena related to the presence of electric charges in the objects. + Magnetostatics[1][2][3] refers to the physical phenomena related to the presence of stationary electric currents in the objects (magnetic materials can be considered as those with internal microcurrents). That means that we ignore any electrostatic charge, the electric field and we presume a constant magnetic field with respect to time. === Basic principles === === Basic principles === Line 25: Line 19: ::[[Image:Cargas.jpg]] ::[[Image:Cargas.jpg]] − Our first Maxwell's equation: + Our third Maxwell's equation: − :$\vec{\nabla}\cdot\vec{D} = \rho$ + :$\vec{\nabla}\cdot\vec{B} = 0$ where: where: − :$\vec{D} = \varepsilon\vec{E} = \varepsilon_0\varepsilon_r\vec{E}$ + :$\vec{B} = \mu \vec{H} = \mu_0\mu_r\vec{H}$ − + − with: $\varepsilon, \varepsilon_0, \varepsilon_r$ the permittivity of the medium, of the free space and relative permittivity, respectively. + − + − The electric field is the gradient of an electrostatic potential ($V [Volts]\,$): + with: $\mu, \mu_0, \mu_r \,$ the (magnetic) permeability of the medium, of the free space and relative permeability, respectively. − :$\vec{E}=-\vec{\nabla} V$ + The magnetic field is the curl of a magnetic vector potential ($\vec{A} [Volt-seconds \; per \; metre]\,$): − Our second Maxwell's equation: + :$\vec{B}=\vec{\nabla} \times \vec{A}$ − :$\vec{\nabla}\times\vec{E} = 0$ + Our fourth Maxwell's equation: + :$\vec{\nabla} \times \vec{H} = \vec{J}$ − By combining these Maxwell's equations, we can easily can obtain the Poisson's equation: − :$\vec{\nabla} \varepsilon \vec{\nabla} V + \rho_v = 0$ + By combining these Maxwell's equations, we obtain: + :$\vec{\nabla} \times \frac{1}{\mu} \vec{A} - \vec{J} = 0$ + that can be reduced to the Poisson's equation for two dimension domains. ::[[Magnetostatics Basic principles | '''''Basic principles extended''''']] ::[[Magnetostatics Basic principles | '''''Basic principles extended''''']] Line 92: Line 85: == References == == References == − # [http://www.answers.com/topic/electrostatics Sci-Tech Encyclopedia: Electrostatics] + # [http://www.answers.com/topic/magnetostatics Reference Answers: Magnetostatics] − # [http://en.wikipedia.org/wiki/Electrostatics wikipedia Electrostatics] + # [http://en.wikipedia.org/wiki/Magnetostatics wikipedia Magnetostatics] − # [http://en.wikipedia.org/wiki/Static_electricity wikipedia Static electricity] + # [http://en.wikipedia.org/wiki/Magnetism wikipedia Static Magnetism] − # [http://en.wikipedia.org/wiki/Electric_charge wikipedia Electric charge] + # [http://en.wikipedia.org/wiki/Electric_currents wikipedia Electric currents] − # [http://en.wikipedia.org/wiki/Electric_force Electric force] + # [http://en.wikipedia.org/wiki/Lorentz_force Magnetic force] − # [http://www.colorado.edu/physics/2000/waves_particles/wavpart2.html Electric force animation] + # [http://en.wikipedia.org/wiki/Magnetic_flux Magnetic flux] − # [http://en.wikipedia.org/wiki/Electric_flux Electric flux] + # [http://en.wikipedia.org/wiki/Magnetic_field Magnetic field] − # [http://en.wikipedia.org/wiki/Electric_displacement_field Electric displacement field] + # [http://en.wikipedia.org/wiki/Poisson%27s_equation Poisson's Equation] # [http://en.wikipedia.org/wiki/Poisson%27s_equation Poisson's Equation] − # [http://electron6.phys.utk.edu/phys594/Tools/e&m/summary/electrostatics/electrostatics.html Electrostatics Summary] == The Finite Element Method for Magnetostatics == == The Finite Element Method for Magnetostatics ==

## General Description

The KRATOS Magnetostatic Application deals with the Finite Element Analysis of problems in magnetostatics. Though the mathematics and general formulation is quite similar to Electrostatics, Magnetostatics presents important differences at a conceptual and a programming level. Therefore, if you are a beginner in electromagnetism or programming electromagnetic applications, we strongly recommend you that you first start with the Electrostatic application.

The following description of the Kratos Magnetostatic Application takes part of:

At a first glance, it could be said that Electrostatics works with static charges whereas Magnetostatics does it with dynamic charges (or static currents). That's partially true and we avoid by now to argue about it. On the opposite, we are going to consider Magnetostatics as a completely new phenomenon instead of thinking in a kind of 'dynamic' electrostatic.

As Electrostatics, Magnetostatics establishes very basic principles of the Maxwell equations, it is an excellent work at academic level, but it is also a powerful conceptual (and eventually the resulting computing tool) to solve important industrial applications (electrical machines such as motors and transformers, circuit components such as coils, permanent magnets, sensors, magnetic field distribution, etc).

## Theory

Magnetostatics[1][2][3] refers to the physical phenomena related to the presence of stationary electric currents in the objects (magnetic materials can be considered as those with internal microcurrents). That means that we ignore any electrostatic charge, the electric field and we presume a constant magnetic field with respect to time.

### Basic principles

Our third Maxwell's equation:

$\vec{\nabla}\cdot\vec{B} = 0$

where:

$\vec{B} = \mu \vec{H} = \mu_0\mu_r\vec{H}$

with: $\mu, \mu_0, \mu_r \,$ the (magnetic) permeability of the medium, of the free space and relative permeability, respectively.

The magnetic field is the curl of a magnetic vector potential ($\vec{A} [Volt-seconds \; per \; metre]\,$):

$\vec{B}=\vec{\nabla} \times \vec{A}$

Our fourth Maxwell's equation:

$\vec{\nabla} \times \vec{H} = \vec{J}$

By combining these Maxwell's equations, we obtain:

$\vec{\nabla} \times \frac{1}{\mu} \vec{A} - \vec{J} = 0$

that can be reduced to the Poisson's equation for two dimension domains.

Basic principles extended

### Poisson's Equation in Magnetostatics

The detailed form of the Poisson's Equation[9] in Magnetostatics is:

$\frac{\partial}{\partial x}\cdot \left( \varepsilon_{x} \cdot \frac{\partial V(x,y,z)}{\partial x}\right) + \frac{\partial}{\partial y}\cdot \left(\varepsilon_{y} \cdot \frac{\partial V(x,y,z)}{\partial y} \right) + \frac{\partial}{\partial z}\cdot \left(\varepsilon_{z} \cdot \frac{\partial V(x,y,z)}{\partial z} \right) + \rho_v(x,y,z)=0$

Poisson's Equation extended

### Magnetostatic Boundary Conditions

For a domain ${\Omega} \,$, we should consider three different boundary conditions:

• Dirichlet boundary condition:
$\left . V - \bar V = 0 \right |_{\Gamma_{V}}$
• Neumann boundary condition:
$\left . \hat n \vec{D} - \bar D_n = 0 \right |_{\Gamma_{q}}$
• Infinit condition (when no physical boundary are presents -free space-):
$\left . \frac{\partial V}{\partial r} \right |_{\Gamma_{\infty}} \approx - \frac{V}{r}$

Boundary Conditions extended


text:
# Trigonometry Examples

Find the asymptotes.
For any , vertical asymptotes occur at , where is an integer. Use the basic period for , , to find the vertical asymptotes for . Set the inside of the cotangent function, bx+c, for equal to to find where the vertical asymptote occurs for .
Divide each term by and simplify.
Divide each term in by .
Reduce the expression by cancelling the common factors.
Cancel the common factor.
Divide by to get .
Divide by to get .
Set the inside of the cotangent function equal to .
Divide each term by and simplify.
Divide each term in by .
Reduce the expression by cancelling the common factors.
Cancel the common factor.
Divide by to get .
The basic period for will occur at , where and are vertical asymptotes.
The absolute value is the distance between a number and zero. The distance between and is .
The vertical asymptotes for occur at , , and every , where is an integer.
Cotangent only has vertical asymptotes.
No Horizontal Asymptotes
No Oblique Asymptotes
Vertical Asymptotes: where is an integer
No Horizontal Asymptotes
No Oblique Asymptotes
Vertical Asymptotes: where n is an integer
Use the form to find the variables used to find the amplitude, period, phase shift, and vertical shift.
Since the graph of the function does not have a maximum or minimum value, there can be no value for the amplitude.
Amplitude: None
Find the period using the formula .
The period of the function can be calculated using .
Period:
Replace with in the formula for period.
Period:
The absolute value is the distance between a number and zero. The distance between and is .
Period:
Period:
Find the phase shift using the formula .
The phase shift of the function can be calculated from .
Phase Shift:
Replace the values of and in the equation for phase shift.
Phase Shift:
Divide by to get .
Phase Shift:
Phase Shift:
Find the vertical shift .
Vertical Shift:
List the properties of the trigonometric function.
Amplitude: None
Period:
Phase Shift: ( to the right)
Vertical Shift:
Select a few points to graph.
Find the point at .
Replace the variable with in the expression.
Simplify the result.
Cancel the common factor of .
Write as a fraction with denominator .
Factor out the greatest common factor .
Cancel the common factor.
Rewrite the expression.
Multiply and to get .
The exact value of is .
Multiply by to get .
Find the point at .
Replace the variable with in the expression.
Simplify the result.
Cancel the common factor of .
Write as a fraction with denominator .
Factor out the greatest common factor .
Cancel the common factor.
Rewrite the expression.
Multiply and to get .
The exact value of is .
Multiply by to get .
Find the point at .
Replace the variable with in the expression.
Simplify the result.
Cancel the common factor of .
Write as a fraction with denominator .
Factor out the greatest common factor .
Cancel the common factor.
Rewrite the expression.
Multiply and to get .
Apply the reference angle by finding the angle with equivalent trig values in the first quadrant. Make the expression negative because cotangent is negative in the second quadrant.
The exact value of is .
Multiply by to get .
Multiply by to get .
Find the point at .
Replace the variable with in the expression.
Simplify the result.
Cancel the common factor of .
Write as a fraction with denominator .
Factor out the greatest common factor .
Cancel the common factor.
Rewrite the expression.
Multiply and to get .
Apply the reference angle by finding the angle with equivalent trig values in the first quadrant.
The exact value of is .
Multiply by to get .
Find the point at .
Replace the variable with in the expression.
Simplify the result.
Cancel the common factor of .
Write as a fraction with denominator .
Factor out the greatest common factor .
Cancel the common factor.
Rewrite the expression.
Multiply and to get .
Apply the reference angle by finding the angle with equivalent trig values in the first quadrant. Make the expression negative because cotangent is negative in the fourth quadrant.
The exact value of is .
Multiply by to get .
Multiply by to get .
List the points in a table.
The trig function can be graphed using the amplitude, period, phase shift, vertical shift, and the points.
Vertical Asymptotes: where n is an integer
Amplitude: None
Period:
Phase Shift: ( to the right)
Vertical Shift:

We're sorry, we were unable to process your request at this time

Step-by-step work + explanations
•    Step-by-step work
•    Detailed explanations
•    Access anywhere
Access the steps on both the Mathway website and mobile apps
$--.--/month$--.--/year (--%)

Visa and MasterCard security codes are located on the back of card and are typically a separate group of 3 digits to the right of the signature strip.

American Express security codes are 4 digits located on the front of the card and usually towards the right.
This option is required to subscribe.
Go Back

format: plain


text:
# $\text{Hom}_{\mathbb{Z}}(R,D)$ is an injective $R$-module when $D$ is a divisible $\mathbb{Z}$-module

$\DeclareMathOperator{Hom}{Hom}$Let $R$ be a ring with $1$, $D$ a divisible $\mathbb{Z}$-module. Denote $X=\Hom_{\mathbb{Z}}(R,D)$ as the set of homomorphisms from $R$ to $D$ when viewing $R$ and $D$ as $\mathbb{Z}$-modules. We can associate an $R$-module structure on $X$ by defining $(rf)(x) = f(xr)$ for $r\in R, f\in X$. I want to prove that $X$ is an injective $R$-module.

To accomplish this, it suffices to prove:

Given an injective $g: M\to N$, with $M,N$ being $R$-modules, the induced map $$g^{\ast}: \Hom_R(N,\Hom_{\mathbb{Z}}(R,D)) \to \Hom_R(M,\Hom_{\mathbb{Z}}(R,D))$$ is surjective.

I have made some progress in proving the claim, but I don't know utilize the assumption that $g$ is injective and $D$ is divisible. There is also a hint, which I don't know how to use either: namely $$\Hom_{\mathbb{Z}}(Y,D) \cong \Hom_{R}(Y,\Hom_{\mathbb{Z}}(R,D))$$ for any $R$-module $Y$, the map is given by: $f\mapsto \hat{f}$, with $\hat{f}(y)(r) = f(ry)$. Proving this does not require divisibility of $D$.

Any hint or help is appreciated.

The hint is apposite; composing $g^*$ with these isomorphisms gives a $\Bbb Z$-module map $$\text{Hom}_{\Bbb Z}(N,D)\to\text{Hom}_{\Bbb Z}(M,D).$$ This is the map induced by the injective homomorphism $g:M\to N$. This map is surjective, as $D$ is injective in the category of $\Bbb Z$-modules. Therefore $g^*$ is surjective.


text:
# Import Simulink figures in LaTeX

I am writing my Thesis report using LaTeX. I have to explain about a few models that I created in Simulink in my report. I do not know how to import these Simulink models into LaTeX. Can someone help me out with this?

• I think you have two options: (1) make a snapshot and insert the picture in your LaTeX file or (2) export the Simulink model to HTML, then convert to LaTeX: see here for this last step. – Count Zero Jun 7 '13 at 12:24

You can do the following; I use Matlab 2013, but I suspect that can also be done in older versions.

1. Go to File >> Print, then click on Print.
2. Under Device option, write -dpdf.
3. Under Send to, you have a choice of two radio buttons; select File.
4. Press Print; a dialog box will prompt you to choose a path for the file.

Then, in LaTeX, simply use \includegraphics from the graphicx package to insert the pdf you have just saved.

Note: In my experience, most people tend to insert Simulink diagrams as raster-graphics images of dimensions so small that the model is illegible, even when you zoom in on it. That problem is easily obviated by using a vector-graphics format (e.g. pdf), which I urge you to do.

• Take note that converting the block to pdf gives you some white spaces around the figure. – Hasan Zakeri Jun 7 '13 at 13:06
• @HasanZakeri Yes. That's what I was trying to fix. Matlab/Simulink doesn't seem to offer much flexibility in this regard. The only workaround is to modify the paper size option in the Print window. – jub0bs Jun 7 '13 at 13:08
• Or remove the surrounding white space with external tools, eg. ghostscript :) – Hasan Zakeri Jun 7 '13 at 16:39
• I sometimes use Adobe illustrator to crop pdf files. – Ali Nov 9 '13 at 12:16

saveas(h,'filename.ext')

or

saveas(h,'filename','format')

following the directions in this MathWoks link.

In you LaTeX file use (if you saved your Simulink model as an eps file):

\begin{figure}
\centering
\includegraphics{myfile.eps}
\end{figure}

Also, this site can be of interest.

• This works only for figures. The actual model cannot be saved this way. – Count Zero Jun 7 '13 at 12:58
• @CountZero: Yes. I write in the answer (if your saved your Simulink model as an eps file). Thanks. – user13907 Jun 7 '13 at 13:02
• @Papiro: Thanks, especially for the quick response. – Martin Scharrer Jun 7 '13 at 13:35

I always use this Mathworks code piece. It removes additional space and works with all figures, I encountered.

• Unfortunately, it works with figures not simulink models – percusse Jun 7 '13 at 13:51

## Snapshot of a Simulink model:

• Open the Simulink system which you would like to print to file.
• Switch to the Matlab application and run the following code:
• print -dpdf -s <outputFileName>.pdf %vector format
• print -dpng -r225 -s <outputFileName>.png %raster format

For vector format: I'm using r2013b, which has pdf capability despite the documentation completely omitting it. Your usage may vary.

For raster format: The default resolution, -r90 can be terrible. Look for washed out connection lines. I found this to occur straight through -r200 when creating .png files.

## Snapshot of a Stateflow model:

• Open the Stateflow system which you would like to print to file.
• Switch to the Matlab application and run the following code:
• sfprint(gcs, 'png', '<outputFileName>.png')

For vector format: sfprint does not yet have .pdf output capability. You'll need to use .eps or .svg and a converter. Packages exist within the latex environment to make the conversion. Even so, you may not want latex to convert each time you compile. [See Feature Requests, below.]

For raster format: sfprint does not yet have an option to specify resolution. Even so, I believe this command still provides improved resolution over the File --> Print method.

## .PDF Autocrop

To crop your .pdf down to its minimum margins, use the following code on the output .pdf from print:

• !pdfcrop <outputFileName>.pdf <outputFileName>.pdf

## Feature requests

In order to improve the process of exporting images from Mathworks products to a latex environment, I have recently requested that the Simulink and Stateflow teams consider the incorporation of additional functionality to the print and sfprint functions in future releases.

From what I understand, these functions have seen improvements over the past few years already, and I would thus consider them still open to additional development.

I requested the following features:

print:

• option to automatically crop margins/whitespace.
• option to specify margins/whitespace of crop option.

sfprint:

• option to print to .pdf. [option already exists in print].
• option to specify raster image resolution. [option already exists in print].
• option to automatically crop margins/whitespace.
• option to specify margins/whitespace of crop option.

## Contact Mathworks with additional insight.

My scope only considered pdflatex. Additional input from the community would likely be useful. Many of you may have needs which are not clear to me which would be better represented yourself. Your submissions would also demonstrate that support for the development of these features would be worthwhile.

To: US MathWorks Support <support@mathworks.com>
Re: Specifying image resolution with sfprint [ ref:_00Di0Ha1u._500i0THMmD:ref ]


text:
# NAG FL Interfacee01aaf (dim1_aitken)

## ▸▿ Contents

Settings help

FL Name Style:

FL Specification Language:

## 1Purpose

e01aaf interpolates a function of one variable at a given point $x$ from a table of function values ${y}_{i}$ evaluated at equidistant or non-equidistant points ${x}_{i}$, for $\mathit{i}=1,2,\dots ,n+1$, using Aitken's technique of successive linear interpolations.

## 2Specification

Fortran Interface
 Subroutine e01aaf ( a, b, c, n1, n2, n, x)
 Integer, Intent (In) :: n1, n2, n Real (Kind=nag_wp), Intent (In) :: x Real (Kind=nag_wp), Intent (Inout) :: a(n+1), b(n+1) Real (Kind=nag_wp), Intent (Out) :: c(n*(n+1)/2)
#include <nag.h>
 void e01aaf_ (double a[], double b[], double c[], const Integer *n1, const Integer *n2, const Integer *n, const double *x)
The routine may be called by the names e01aaf or nagf_interp_dim1_aitken.

## 3Description

e01aaf interpolates a function of one variable at a given point $x$ from a table of values ${x}_{i}$ and ${y}_{i}$, for $i=1,2,\dots ,n+1$ using Aitken's method (see Fröberg (1970)). The intermediate values of linear interpolations are stored to enable an estimate of the accuracy of the results to be made.

## 4References

Fröberg C E (1970) Introduction to Numerical Analysis Addison–Wesley

## 5Arguments

1: $\mathbf{a}\left({\mathbf{n}}+1\right)$Real (Kind=nag_wp) array Input/Output
On entry: ${\mathbf{a}}\left(\mathit{i}\right)$ must contain the $x$-component of the $\mathit{i}$th data point, ${x}_{\mathit{i}}$, for $\mathit{i}=1,2,\dots ,n+1$.
On exit: ${\mathbf{a}}\left(\mathit{i}\right)$ contains the value ${x}_{\mathit{i}}-x$, for $\mathit{i}=1,2,\dots ,n+1$.
2: $\mathbf{b}\left({\mathbf{n}}+1\right)$Real (Kind=nag_wp) array Input/Output
On entry: ${\mathbf{b}}\left(\mathit{i}\right)$ must contain the $y$-component (function value) of the $\mathit{i}$th data point, ${y}_{\mathit{i}}$, for $\mathit{i}=1,2,\dots ,n+1$.
On exit: the contents of b are unspecified.
3: $\mathbf{c}\left({\mathbf{n}}×\left({\mathbf{n}}+1\right)/2\right)$Real (Kind=nag_wp) array Output
On exit:
• ${\mathbf{c}}\left(1\right),\dots ,{\mathbf{c}}\left(n\right)$ contain the first set of linear interpolations,
• ${\mathbf{c}}\left(n+1\right),\dots ,{\mathbf{c}}\left(2×n-1\right)$ contain the second set of linear interpolations,
• ${\mathbf{c}}\left(2n\right),\dots ,{\mathbf{c}}\left(3×n-3\right)$ contain the third set of linear interpolations,
• $⋮$
• ${\mathbf{c}}\left(n×\left(n+1\right)/2\right)$ contains the interpolated function value at the point $x$.
4: $\mathbf{n1}$Integer Input
5: $\mathbf{n2}$Integer Input
On entry: n1 and n2 are no longer referenced, but are included for backwards compatability.
6: $\mathbf{n}$Integer Input
On entry: the number of intervals which are to be used in interpolating the value at $x$; that is, there are $n+1$ data points $\left({x}_{i},{y}_{i}\right)$.
Constraint: ${\mathbf{n}}>0$.
7: $\mathbf{x}$Real (Kind=nag_wp) Input
On entry: the point $x$ at which the interpolation is required. Note that x may lie outside the interval defined by the minimum and maximum values in a, in which case an extrapolated value will be computed; extrapolated results should be treated with considerable caution since there is no information on the behaviour of the function outside the defined interval.

None.

## 7Accuracy

An estimate of the accuracy of the result can be made from a comparison of the final result and the previous interpolates, given in the array c. In particular, the first interpolate in the $i$th set, for $i=1,2,\dots ,n$, is the value at $x$ of the polynomial interpolating the first $\left(i+1\right)$ data points. It is given in position $\left(i-1\right)\left(2n-i+2\right)/2$ of the array c. Ideally, providing $n$ is large enough, this set of $n$ interpolates should exhibit convergence to the final value, the difference between one interpolate and the next settling down to a roughly constant magnitude (but with varying sign). This magnitude indicates the size of the error (any subsequent increase meaning that the value of $n$ is too high). Better convergence will be obtained if the data points are supplied, not in their natural order, but ordered so that the first $i$ data points give good coverage of the neighbourhood of $x$, for all $i$. To this end, the following ordering is recommended as widely suitable: first the point nearest to $x$, then the nearest point on the opposite side of $x$, followed by the remaining points in increasing order of their distance from $x$, that is of $|{x}_{r}-x|$. With this modification the Aitken method will generally perform better than the related method of Neville, which is often given in the literature as superior to that of Aitken.

## 8Parallelism and Performance

e01aaf is not threaded in any implementation.

The computation time for interpolation at any point $x$ is proportional to $n×\left(n+1\right)/2$.

## 10Example

This example interpolates at $x=0.28$ the function value of a curve defined by the points
 $( xi -1.00 -0.50 0.00 0.50 1.00 1.50 yi 0.00 -0.53 -1.00 -0.46 2.00 11.09 ) .$

### 10.1Program Text

Program Text (e01aafe.f90)

### 10.2Program Data

Program Data (e01aafe.d)

### 10.3Program Results

Program Results (e01aafe.r)


text:
# Does fumaric acid form maleic anhydride upon heating?

Maleic acid (the cis isomer of the dicarboxylic acid $\ce{C4H4O4}$) readily forms its anhydride on heating. Clayden's organic chemistry textbook mentions this as a point of distinction between it and fumaric acid (the trans isomer), which fails to dehydrate to its anhydride upon heating. However, I have discovered that at temperatures above 200 $^{\circ}\mathrm{C}$, fumaric acid forms maleic anhydride as well.

Which is the correct answer? I don't think it is likely that fumaric acid can form the anhydride - even at higher temperatures - given the trans configuration and restricted rotation.

• Some calculations (values from NIST) reveal that the formation of maleic anhydride and water from fumaric acid is an endothermic reaction ($\Delta H\approx +65.28 \frac{kJ}{mol}$) but the change in entropy is positive ($\Delta S\approx 134.24 \frac{J}{mol\cdot K}$). This means that the reaction becomes spontaneous for temperatures above $213^\circ C$, but this is only "mildly" spontaneous ($\Delta G\approx -5 \frac{kJ}{mol}$ at $523\ K$). So, the use of a dehydrating agent to remove the water from the reaction mixture and drive the equilibrium forward (Le Chatelier's principle) is necessary. – Eashaan Godbole Jun 9 '17 at 3:20

Also, dehydrating fumaric acid with a dehydrating agent also forms maleic anhydride. This paper describe how to convert $\ce{C^{14}}$ labelled fumaric acid to maleic anhydride.
Maleic anhydride-2-$\ce{C^{14}}$ is readily obtained from fumaric acid-2-$\ce{C^{14}}$ through dehydration using phosphorus pentoxide getting 96% yield under controlled condition.


text:
Adds MULTIPOLYGONZ will be plotted in the coordinate system set by the user-specified extent argument as-is.

You can also use save_multipolygonz_to_obj() manually to convert sf objects

render_multipolygonz(
sfobj,
extent = NULL,
zscale = 1,
heightmap = NULL,
color = "grey50",
offset = 0,
obj_zscale = TRUE,
swap_yz = TRUE,
clear_previous = FALSE,
baseshape = "rectangle",
rgl_tag = "_multipolygon",
...
)

## Arguments

sfobj

An sf object with MULTIPOLYGON Z geometry.

extent

Either an object representing the spatial extent of the scene (either from the raster, terra, sf, or sp packages), a length-4 numeric vector specifying c("xmin", "xmax","ymin","ymax"), or the spatial object (from the previously aforementioned packages) which will be automatically converted to an extent object.

zscale

Default 1. The ratio between the x and y spacing (which are assumed to be equal) and the z axis in the original heightmap.

heightmap

Default NULL. Automatically extracted from the rgl window--only use if auto-extraction of matrix extent isn't working. A two-dimensional matrix, where each entry in the matrix is the elevation at that point. All points are assumed to be evenly spaced.

color

Default black. Color of the 3D model, if load_material = FALSE.

offset

Default 5. Offset of the track from the surface, if altitude = NULL.

obj_zscale

Default TRUE. Whether to scale the size of the OBJ by zscale to have it match the size of the map. If zscale is very big, this will make the model very small.

swap_yz

Default TRUE. Whether to swap and Y and Z axes. (Y axis is vertical in rayshader coordinates, but data is often provided with Z being vertical).

clear_previous

Default FALSE. If TRUE, it will clear all existing points.

baseshape

Default rectangle. Shape of the base. Options are c("rectangle","circle","hex").

rgl_tag

Default "". Tag to add to the rgl scene id, will be prefixed by "obj"

...

Additional arguments to pass to rgl::triangles3d().

## Examples

run_examples = length(find.package("sf", quiet = TRUE)) &&
length(find.package("elevatr", quiet = TRUE)) &&
length(find.package("raster", quiet = TRUE)) &&
if(run_examples) {
library(sf)
#Set location of washington monument
washington_monument_location =  st_point(c(-77.035249, 38.889462))
wm_point = washington_monument_location |>
st_point() |>
st_sfc(crs = 4326) |>
st_transform(st_crs(washington_monument_multipolygonz))

elevation_data = elevatr::get_elev_raster(locations = wm_point, z = 14)

scene_bbox = st_bbox(st_buffer(wm_point,300))
cropped_data = raster::crop(elevation_data, scene_bbox)

#Use rayshader to convert that raster data to a matrix
dc_elevation_matrix = raster_to_matrix(cropped_data)

#Remove negative elevation data
dc_elevation_matrix[dc_elevation_matrix < 0] = 0

#Plot a 3D map of the national mall
dc_elevation_matrix |>
plot_3d(dc_elevation_matrix, zscale=3.7, water = TRUE, waterdepth = 1,
soliddepth=-50, windowsize = 800)
render_snapshot()
}
#> Linking to GEOS 3.10.2, GDAL 3.4.2, PROJ 8.2.1; sf_use_s2() is FALSE
#> Warning: PROJ support is provided by the sf and terra packages among others
#> Warning: PROJ support is provided by the sf and terra packages among others
#> Mosaicing & Projecting
#> Note: Elevation units are in meters.

if(run_examples) {
#Zoom in on the monument
render_camera(theta=150,  phi=35, zoom= 0.55, fov=70)
#Render the national monument
rgl::par3d(ignoreExtent = TRUE)
render_multipolygonz(washington_monument_multipolygonz,
extent = raster::extent(cropped_data),
zscale = 4, color = "white",
heightmap = dc_elevation_matrix)
render_snapshot()
}

if(run_examples) {
#This works with render_highquality()
render_highquality(sample_method="sobol_blue", clamp_value=10, min_variance = 0)
}


text:
# Tree Harvesting Linear Programming Problem

### Tree Harvesting Linear Programming Problem

The State of Virginia is one of the largest produces of wood furniture in the United States, with the furniture industry accounting for 50% of value added to wood materials. Over the past 40 years the inventory volume of wood in Virginia’s forests has increased by 81%. Today, 15.4 million acres, which is well over half of the state, are covered in forest. Private owners hold 77% of this land. When making decisions about which trees to harvest, forestry professionals consider many factors and must follow numerous laws and regulations.
The figure below depicts a tract of forested land that has been sectioned off into 16 harvestable areas, indicated by dashed lines. Area E provides the only access to the forest via a paved road, so any timber cut ultimately must be transported out of the forest through Area E. Currently, there are no roads through this forest. So to harvest the timber, forest roads must be built. The allowable routes for these roads are also shown in the figure below. They are determined largely by the geography of the land and by the location of streams and wildlife habitat.
Not all areas of the forest have to be harvested. However, to harvest any area, a forest road must be built to that area. The cost of building each section of forest road (in $1000s) is indicated in the figure. Also, note that road connecting G->K or K->G costs the same,$12,000. Finally, the value of the harvestable timber in each area is estimated as follows:

Harvested Value (in $1000s) Area A B C D E F G H I J K L M N O P Value$13 $7$17 $19$8 $13$17 $18$13 $13$10 $20$8 $16$13 \$9

The diagram is listed below. I really need help on formulating this in LINDO
Attachments
Prob10 (1).doc
Titansguy2121

Posts: 1
Joined: Mon Mar 10, 2014 10:59 am
Reputation: 0

### Re: Tree Harvesting Linear Programming Problem

Presumably you want to maximize your profits. This is an integer programming problem as you have binary variables (variables that can either be 0 or 1) you want to determine like whether to build a road or not.

I would choose to have a binary variable for whether each road is built or not, and a binary variable for whether each area is reachable or not. This makes the objective function nice and linear. The constraints are given by the fact that whether an area is reachable or not depends on whether it's neighbouring areas are reachable and whether there is a road from such a neighbour.

As an example let:
$$v_G$$ = area G is reachable
$$v_F$$ = area F is reachable
$$v_K$$ = area K is reachable
$$r_{FG}$$ = road from F to G is built
$$r_{KG}$$ = road from K to G is built
be binary variables, then $$v_G$$ is clearly constrained by
$$v_G$$ = ($$v_F$$ AND $$r_{FG}$$) OR ($$v_K$$ AND $$r_{KG}$$)
where "OR" and "AND" are binary operators. Unfortunately this statement isn't linear, so we need to fix it.

We can replace "AND" with multiplications e.g.
$$x$$ AND $$y$$ AND $$z$$ = $$xyz$$
We can replace "OR" with multiplications and additions e.g.
$$x$$ OR $$y$$ OR $$z$$ = $$1-(1-x)(1-y)(1-z) = x+y+z-xy-xz-yz+xyz$$
we can replace a product of variables with an auxiliary binary variable, e.g. the set of linear constraints for the binary variable $$a$$
$$a \leq x$$
$$a \leq y$$
$$a \leq z$$
$$a \geq x+y+z-2$$
are equivalent to saying $$a=xyz$$.

Using these tricks you can convert the constraints into proper linear constraints.

Hope this helped,

R. Baber.
Guest

### Re: Tree Harvesting Linear Programming Problem

Sorry, I should have also added that you should add constraints that say that there are no circular paths, e.g.
$$r_{JK}$$ AND $$r_{KO}$$ AND $$r_{ON}$$ AND $$r_{NJ}$$ = 0.

R. Baber.
Guest

### Re: Tree Harvesting Linear Programming Problem

Apologies again, that still doesn't get rid of the problem of an isolated area thinking it is connected to region E (for example suppose only road AB is built then $$v_A=v_B=1$$ satisfies the constraints but is not what we intended).

What you need is two variables per road, e.g. $$r_{AB}$$ and $$r_{BA}$$, where
$$r_{AB}$$ = Timber in region A can get out by going through B,
$$r_{BA}$$ = Timber in region B can get out by going through A,
and an extra constraint that says $$r_{AB}$$ AND $$r_{BA}$$ = 0 (the route timber takes to get out never goes back on itself). You still need constraints that forbid cycles as well.

R. Baber.
Guest

### Re: Tree Harvesting Linear Programming Problem

I have the same problem in a linear programming class I am taking. I am having a hard time determining the OBJ Function. I understand the networking aspect moving grid to grid maximizing profit of harvesting each grid while keeping road cost at a minimum.

I get the constraints to keep from building the same road twice
ex) KJ +JK <=1
KG-JK-KL-FG<=0

I am going with combining cost & profit to approach this problem; would the OBJ Func. be where I combine this?
MAX 4BA-2BC....
Guest

### Re: Tree Harvesting Linear Programming Problem

The objective function would be something like:
Maximize $$13v_A -9 r_{AB} -9 r_{BA}$$... etc.
where 13 is the money made from harvesting $$A$$ and 9 is the cost of building a road between $$A$$ and $$B$$.

R. Baber.
Guest

### Re: Tree Harvesting Linear Programming Problem

I think you are using a different program from Lindo. I need assistance with formulating it in Lindo. I'm trying to translate it but it is kind of difficult. Thanks for the help though it's really appreciated!
Guest

### Re: Tree Harvesting Linear Programming Problem

Guest wrote:I have the same problem in a linear programming class I am taking. I am having a hard time determining the OBJ Function. I understand the networking aspect moving grid to grid maximizing profit of harvesting each grid while keeping road cost at a minimum.

I get the constraints to keep from building the same road twice
ex) KJ +JK <=1
KG-JK-KL-FG<=0

I am going with combining cost & profit to approach this problem; would the OBJ Func. be where I combine this?
MAX 4BA-2BC....

I thought the objective function would look something like this. MAX 4BA + 2BC + 7FB + 8HD - 2EF + 4FG + 6GH + 0EI + 1IJ - 3JK + 10KL + 0IM + 0JN + 5NO + 0KO + 0LP

but I could be totally wrong
Guest

### Re: Tree Harvesting Linear Programming Problem

Guest wrote:I think you are using a different program from Lindo. I need assistance with formulating it in Lindo. I'm trying to translate it but it is kind of difficult. Thanks for the help though it's really appreciated!

I'm not actually using any program. From my understanding of LINDO it can accept anything that looks like a linear program (e.g. expressions that look like $$4x+y+6z \leq 2$$ but not things like $$xy=1$$ as $$xy$$ is a non-linear term). It also allows constraints on the types of variables, like $$x$$ must be 0 or 1, which I think LINDO specifies with the "INT" keyword. Problems of this form are more generally known as integer programming problems and there are well known ways of converting expressions such as $$x$$ AND $$y$$=0 (which is a more natural way of phrasing constraints in the problem you're trying to solve) into linear constraints which integer programming solvers like LINDO prefer. All I was trying to do was point out how such conversions work, unfortunately you still have to do a lot of the work yourself, as LINDO won't do this conversion for you (and neither will I ). Good luck with translating the problem,

R. Baber.
Guest

### Re: Tree Harvesting Linear Programming Problem

Guest wrote:I thought the objective function would look something like this. MAX 4BA + 2BC + 7FB + 8HD - 2EF + 4FG + 6GH + 0EI + 1IJ - 3JK + 10KL + 0IM + 0JN + 5NO + 0KO + 0LP

but I could be totally wrong

You are combining the road cost with the harvesting profit. This is fine for roads like H to D as the only point of building such a road would be to harvest D. However, what about road G to K was the road built to harvest G or to harvest K, when you write the coefficient of GK in your objective function what should you put? Both scenarios are possible. I get around this by having a separate variable for whether an area is harvested.

R. Baber.
Guest

### Re: Tree Harvesting Linear Programming Problem

MAX 8E-2EF+2BC+4FG+8HD+0EI-3JK-2GK+10KL+0LP+0IM+0JN+5NO-3OK-3NJ+0KO+4BA-7FB-5IE+0GF+8ON+5KG+0KJ-7FE+6GH+1JI
SUBJECT TO
2) BA-FB<=0
3) BC-FB<=0
4) HD-GH<=0
5) GH-GK-FG<=0
6) FG-EF-KG<=0
7) EF-E-EI<=0
IM-EI-IJ<=0
9) KG-JK-KL-FG<=0
10) LP-KL<=0
11) OK-JK-KL-NO<=0
12) JN-IJ-JK<=0
13) NO-JN-LK<=0
14) ON-KO-JN<=0
15) EI+IE<=1
16) FG+GF<=1
17) JI+IJ<=1
18) OK+KO<=1
19) JN+NJ<=1
20) ON+NO<=1
21) GK+KG<=1
22) JK+KJ<=1
23) GH+HG<=1
24) E<=1
25) GK-FG<=0
26) JI-KJ-EI<=0
27) KL+LK<=1
28) EF-EI<=0
29) BF+FB<=1
END

This keeps giving me an optimal solution of 50 but the answer is 53. And all my roads don't connect. I'm missing something.
Guest

### Re: Tree Harvesting Linear Programming Problem

Sorry the answer is 43
Guest

### Re: Tree Harvesting Linear Programming Problem

I didn't want to do this, but here is an integer program that works.

Maximize 8-2AB+4BA+2BC-8CB-1BF-7FB+8HD+7DH-2EF-7FE+4FG+0GF+6GH+5HG+0EI-5IE+5KG-2GK+1IJ+1JI-3JK+0KJ+10KL+0LK+5MI+0IM-3NJ+0JN-3OK+0KO+0LP+11PL+5NO+8ON

Such that:

There are no loops:
AB+BA<=1
BC+CB<=1
BF+FB<=1
HD+DH<=1
EF+FE<=1
FG+GF<=1
GH+HG<=1
EI+IE<=1
KG+GK<=1
IJ+JI<=1
JK+KJ<=1
KL+LK<=1
MI+IM<=1
NJ+JN<=1
OK+KO<=1
LP+PL<=1
NO+ON<=1
EF+FG+GK+KJ+JI+IE<=5
EI+IJ+JK+KG+GF+FE<=5
JK+KO+ON+NJ<=3
JN+NO+OK+KJ<=3
EF+FG+GK+KO+ON+NJ+JI+IE<=7
EI+IJ+JN+NO+OK+KG+GF+FE<=7

The roads are connected:
AB<=0
BA<=FB+CB
BC<=AB+FB
CB<=0
BF<=AB+CB
FB<=EF+GF
HD<=GH
DH<=0
EF<=1
FE<=BF+GF
FG<=EF+BF
GF<=HG+KG
GH<=FG+KG
HG<=DH
EI<=1
IE<=MI+JI
KG<=LK+OK+JK
GK<=HG+FG
IJ<=EI+MI
JI<=KJ+NJ
JK<=IJ+NJ
KJ<=GK+LK+OK
KL<=GK+JK+OK
LK<=PL
MI<=0
IM<=EI+JI
NJ<=ON
JN<=IJ+KJ
OK<=NO
KO<=JK+GK+LK
LP<=KL
PL<=0
NO<=JN
ON<=KO

There aren't two routes to the same area:
BA<=1
AB+FB+CB<=1
BC<=1
HD<=1
FE+IE<=0
EF+BF+GF<=1
FG+KG+HG<=1
GH+DH<=1
EI+JI+MI<=1
IJ+NJ+KJ<=1
JK+GK+LK+OK<=1
KL+PL<=1
IM<=1
JN+ON<=1
NO+KO<=1
LP<=1

All variables are binary.

The optimal value for the objective function is 43, there are 8 solutions given by building roads:
HD, GH, EI, KG, IJ, JK, KL, KO, ON
and optionally building (any subset of)
GF, IM, LP.

Hope this helped,

R. Baber.
Guest


text:
# How much sub-questions impact one ordinal question in a survey?

I have a variable Net Promoter Score (NPS) which is an item on a survey, the answer format is ordinal, 0 to 10.

Then, there are sub-questions on the same survey, some are ordinal, some are categorical.

I would like to determine which sub-question or which group of sub-questions are the best predictors of NPS. The goal is to be able to prioritize which area(s) to focus on in order to improve NPS over time.

What would be some appropriate methods to identify and verify such a relationship?

I love your question, and I'm going to answer it a little more broadly then you asked. There are four main approaches that I would use to identify opportunities to improve Net Promoter Score, in order of analytical sophistication and the maturity of the project you're using NPS to evaluate. (For those not familiar, Net Promoter is a common satisfaction score methodology used by many companies. Unless you tend to avoid surveys, you have probably answered the "net promoter" question many times.)

1. Segmentation
2. Qualitative evaluation of open-ended responses
3. Quantitative evaluation of open-ended responses
4. Experimentation

Segmentation: A business can usually divide its customers into a small number of groups along a couple of key dimensions. For example, between "new" and "returning" customers, or "enterprise" and "small business". These will often closely align with the distinctions made in pricing and in the businesses financial reporting, and, happily, they often have dramatically different NP scores. The differences can sometimes surprise. The great thing about this approach is that it requires very little communications overhead. Most people listening to your data will already be familiar with the segments you describe and can envision the aspects of the product that could drive some groups to be more or less satisfied than others. It also makes it relatively easy to organize followup work and report on subsequent improvements.

Qualitative evaluation of open-ends: A common component of Net Promoter implementations is a followup question along the lines of "why did you answer the way that you did". Often, for a project new to Net Promoter, simply reading these responses and associating them with their ordinal responses will have people slapping their foreheads. "I thought our customers liked that feature!" "People love the rubberized grips - let's put them on everything!" This approach often peters out fairly soon, as a business identifies all the surface-level opportunities and makes strategic decisions to resolve or not resolve them.

Quantitative evaluation of open-ends: Following up on the qualitative evaluation, quantitative evaluation can yield some additional surprises. This approach would generally be to label each open-ended response with one or more categories, which can be done by hand at small scales, or using a variety of software at larger scales. This can reveal additional insights along the lines of "I knew that was an issue... but I didn't realize it affected 30% of our customers!" or "Most people who complain about xyz also complain about abc - maybe there is a common root cause"

Experimentation: It's often difficult to perform rigorous controlled-variable random-assignment experiments with Net Promoter. Because Net Promoter is intended to be a very holistic measure of the relationship between a company and its customers, companies are usually limited in their ability to experiment with the entirety of the relationship, due to the expense and risk of maintaining what might amount to two separate businesses at the same time. That said, other less rigorous forms of experiments are possible.

• Every major decision the business makes can be evaluated for its potential to impact NPS, and then the resulting changes can be subsequently measured. Because it fails to isolate a single variable at a time, care must be taken to build realistic predictions and also to be very cautious about results that were not predicted in advance.
• Sometimes we are lucky enough that natural experimental groups emerge that allow us to experiment with the past. A national retailer may roll out a new store format only on the west coast due to the logistical constraints of construction, or a content company may need to censor some types of searches in countries where the local regulations are different. It's not random assignment, but sometimes it's close.

Prediction: I know that I didn't address your real question about using other questions in surveys to "predict" NPS, and that's intentional. The approach that you describe has certain limitations and although I'm planning to try it again myself in the near future, I've had limited success with it in the past.

There are two main predictor approaches I've seen: correlation, and logit regression. Correlation looks at the strength of the relationship between two variables (do they always go up and down together? opposite? no relation?) The idea would be to find the variables most strongly correlated with NPS. Logit regression is a technique that takes all the variables you give it and uses them to try to predict the probability of a particular outcome. For example, you can try to predict the probability of each of your three NPS outcomes (Promoter, Neutral, Detractor). From this you can build a model that shows how much variation in different variables can affect NPS up or down, taking the NPS outcome with the highest predicted probability as the definitive outcome. I have also heard of people using Structural Equation Modelling with NPS, although I know little of this approach.

Some limitations of the predictor approach

• Few good independent variables in surveys: In order to be actionable, this approach requires that you think of NPS as a dependent variables and treat other questions as independent. But, even many of the "hard facts" type questions, such as you might use for your key customer segments are not truly independent from NPS. A returning customer is a returning customer in part because they had a positive experience in the past. Most customer satisfaction questions move together in lockstep, unless you have an offering with very distinctive and low-interacting components that can be performing at two different levels of service (a leisure hotel may try to break into the conference business and do so very poorly at first, in which case separate satisfaction questions on bedroom quality and conference room quality may be useful).
• Difficulty communicating: This analytical approach is usually quite far separated from the group that will be implementing recommendations. Because it relies on relatively sophisticated analysis, it's often difficult for implementors to take actions based on these sort of recommendations, because they don't understand what needs to be fixed.

The NPS works well as a performance monitoring or controlling tool. But what you want to find out is something else: You want to identify the true drivers of satisfaction.

The NPS is an aggregate score. If you want to say something about drivers of satisfaction, than you have to develop a model which explains the 10-point-scale "ultimate question".

However, rating scales are contaminated with scale usage heterogeneity (see paper). If you run a regression model, you will find that those sub-questions are highly correlated, causing high VIFs and maybe no significant betas, depending on how many sub-questions you have. You might also be overconfident in the significance of sub-questions, depending on the exact model set-up.

Consider this simple R script:

nobs=1000
p=12
means = rnorm(nobs)
vars = 1/rgamma(nobs,3,3)
data=matrix(,nobs,p)
for(i in 1:nobs){
data[i,]=rnorm(p,means[i],sqrt(vars[i]))
}
cor(data)

Despite the fact that there is no relationship between the 12 variables, the correlations are far from being 0.

If you further reduce the scale level (Promotor yes/no), you throw away information. However, scale-adjusting models are very challenging, especially when you have ordinal and categorical variables, and if you look for a ready-made solution.

You could treat bottom, middle and top box as categorical outcomes and use a Bayesian Network to model the relationships. BNs treat everything categorical, thus providing a nice general purpose tool.

Have you considered a conjoint experiment? Depending on the service or product this is a nice alternative.

Some good answers already here. Here is a much simpler one, which is really an addition to the good answers you have received, not a substitute. Ordered logistic regression is the appropriate tool for modelling an ordinal response variable. There is an implementation - polr() - in Benables & Ripley's library(MASS) in R.

Then you are back in the standard world of model selection, on which there are many good questions and good answers on Cross-Validated.

• Right, this probably the most straightforward approach. The categorical variables would need to be dummied up somehow, which is also easy. Feb 25, 2012 at 20:12


text:
1

11 i y2

The form of the integral in expression (7.34) lets us understand what will happen when t = s. If t < s, the lower limit is negative, so that as n the integral will approach 1. If t > s, the lower limit is positive so that as n increases the integral will approach 0. We have thus constructed an approximation to the derivative of the correlation function.

Equation (7.31) tells us what we need to do next. We have constructed an approximation to (S/St)x(t, s), and so to find the covariance of Gaussian white noise, we now need to differentiate Eq. (7.33) with respect to s. Remembering how to take the derivative of an integral with respect to one of its arguments, we have q q / n \fn I n(t — s)2\ . . .

qtqsX(t,s) = limn!ip22pexH--2-) ^ limn^i^n(t — s) (7.35)

Now, ^n(t — s) is a Gaussian distribution centered not at 0 but at t = s with variance 1/n. Its integral, over all values of t, is 1 but in the limit that n it is 0 everywhere except at t = s, where it is infinite. In other words, the limit of 6n(t — s) is the Dirac delta function that we first encountered in Chapter 2 (some 6n(x) are shown in Figure 7.10).

Figure 7.11. The spectrum of the covariance function given by Eq. (7.36) is completely flat so that all frequencies are equally represented. Hence the spectrum is "white." In the natural world, however, the higher frequencies are less represented, leading to a fall-off of the spectrum.

if e hite noise

Frequency

This has been a tough slog, but worth it, because we have shown that E{£(t)f(s)} = ¿(t — s) (7.36)

We are now in a position to understand the use of the word ''white'' in the description of this process. Historically, engineers have worked interchangeably between time and frequency domains (Kailath 1980) because in the frequency domain tools other the ones that we consider are useful, especially for linear systems (which most biological systems are not). The connection between the time and frequency (Stratonovich 1963) is the spectrum S(o) defined for the functionf(t) by

where the integral extends over the entire time domain of f(t). In our case then, we set s = 0 for simplicity, since Eq. (7.36) depends only on t — s; the spectrum of the covariance function given by Eq. (7.36) is then

where the last equality follows because the delta function picks out t = 0, for which the exponential is 1. The spectrum of Eq. (7.36) is thus flat (Figure 7.11): all frequencies are equally represented in it. Well, that is the description of white light and this is the reason that we call the derivative of Brownian motion white noise. In the natural world, the covariance does not drop off instantaneously and we obtain spectra with color (see Connections).

The Ornstein-Uhlenbeck process and stochastic integrals

In our analyses thus far, the dynamics of the stochastic process have been independent of the state, depending only upon Brownian motion. We will now begin to move beyond that limitation, but do it appropriately slowly. To begin, recall that ifX(t) satisfies the dynamics dX/dt = f(X) and K is a stable steady state of this system, so that f (K) = 0, and we consider the behavior of deviations from the steady state Y(t) = X(t) — K then, to first order, Y(t) satisfies the linear dynamics dY/dt = — |f '(K)| Y, wheref '(K) is the derivative off(X) evaluated at K. We can then define a relaxation parameter fi = |f'(K)| so that the dynamics of Y are given by

We call fi the relaxation parameter because it measures the rate at which fluctuations from the steady state return (relax) towards 0. Sometimes this parameter is called the dissipation parameter.

What is the relaxation parameter if f (X) is the logistic rX(1 — (X/ K))? If you have the time, find Levins (1966) and see what he has to say about your result.

We fully understand the dynamics of Eq. (7.39): it represents return of deviations to the steady state: which ever way the deviation starts (above or below K), it becomes smaller. However, now let us ask what happens if in addition to this deterministic attraction back to the steady state, there is stochastic fluctuation. That is, we imagine that in the next little bit of time, the deviation from the steady state declines because of the attraction back towards the steady state but at the same time is perturbed by factors independent of this decline. Bjornstadt and Grenfell (2001) call this process "noisy clockwork;'' Stenseth et a/.

(1999) apply the ideas we now develop to cod, and Dennis and Otten

(2000) apply them to kit fox.

We formulate the dynamics in terms of the increment of Brownian motion, rather than white noise, by recognizing that in the limit dt! 0, Eq. (7.39) is the same as dY = —fiY dt + o(dt) and so our stochastic version will become where a is allowed to scale the intensity of the fluctuations. The stochastic process generated by Eq. (7.40) is called the Ornstein-Uhlenbeck process (see Connections) and contains both deterministic relaxation and stochastic fluctuations (Figure 7.12). Our goal is to now characterize the mixture of relaxation and fluctuation.

To do so, we write Eq. (7.40) as a differential by using the integrating factor e^t so that

Figure 7.12. Five trajectories of the Ornstein-Uhlenbeck process, simulated for p = 0.1, dt = 0.01, q = 0.1, and Y(0), uniformly distributed between _ 0.01 and 0.01. We see both the relaxation (or dissipation) towards the steady state Y = 0 and fluctuations around the trajectory and the steady state.

Figure 7.12. Five trajectories of the Ornstein-Uhlenbeck process, simulated for p = 0.1, dt = 0.01, q = 0.1, and Y(0), uniformly distributed between _ 0.01 and 0.01. We see both the relaxation (or dissipation) towards the steady state Y = 0 and fluctuations around the trajectory and the steady state.

0 0


text:
# Google CodeJam 2016 - Python Counting Sheep

I decided to try some google codejam problems to get some more experience coding. The problem is at http://code.google.com/codejam/contest/6254486/dashboard, my solution is below. It gets the correct solution but would appreciate any tips on coding.

Problem

Bleatrix Trotter the sheep has devised a strategy that helps her fall asleep faster. First, she picks a number N. Then she starts naming N, 2 × N, 3 × N, and so on. Whenever she names a number, she thinks about all of the digits in that number. She keeps track of which digits (0, 1, 2, 3, 4, 5, 6, 7, 8, and 9) she has seen at least once so far as part of any number she has named. Once she has seen each of the ten digits at least once, she will fall asleep.

Bleatrix must start with N and must always name (i + 1) × N directly after i × N. For example, suppose that Bleatrix picks N = 1692. She would count as follows:

N = 1692. Now she has seen the digits 1, 2, 6, and 9. 2N = 3384. Now she has seen the digits 1, 2, 3, 4, 6, 8, and 9. 3N = 5076. Now she has seen all ten digits, and falls asleep. What is the last number that she will name before falling asleep? If she will count forever, print INSOMNIA instead.

Input

The first line of the input gives the number of test cases, T. T test cases follow. Each consists of one line with a single integer N, the number Bleatrix has chosen.

Output

For each test case, output one line containing Case #x: y, where x is the test case number (starting from 1) and y is the last number that Bleatrix will name before falling asleep, according to the rules described in the statement.

Code

import os

def getnumber(number,numberoftries):
N = number
digitlist = []
print "new case number = " + str(number)
for j in range(1,numberoftries):
N = str(N)
N.rstrip()
digits = []
for l in range(0,len(N)):
if N[l] not in digits:
digits.append(N[l])
# print digits
for l in range(0,len(digits)):
k = digits[l]
#  Add digits to digitlist
if k not in digitlist:
digitlist.append(k)
print digitlist
# check if we have all digits
count = 0
for k in range (0,10):
if str(k) in digitlist:
count = count + 1
if count == 10:
print "count = 10"
return str(N)
else:
N = number * (j+1)
print "number = " + str(N)
return "INSOMNIA"

numberoftries = 1000
inputfile = 'A-large-practice.in'
inputfilename = path + inputfile
outputfilename = path + 'largeoutput'
f = open(inputfilename, "r")
o = open(outputfilename,"w")
for i in range (1,int(numberofcases)+1):
N = int(N)
result = getnumber(N,numberoftries)
outputline = 'Case #' + str(i) + ': ' + str(result) + '\n'
o.write(outputline)
o.close()

In general, it is difficult to follow the logic and the code is not readable.

First, here are some general things you can improve:

• N.rstrip() does not modify a string in place and returns a new string instead. Since you are not assigning the result to anything, it does nothing
• according to PEP8, you should put underscores between the words in variable and function names - number_of_tries vs numberoftries or digitlist vs digit_list, get_number() vs getnumber()
• following the previous note - N is not a good variable name
• remove unused import
• count = count + 1 can be rewritten as count += 1
• put the main logic of the program into if __name__ == '__main__':
• use print() function instead of a statement for Python 3.x compatibility
• use with context manager when opening file(s) - this will ensure it being properly and safely closed
• use os.path.join() to join the path components (okay, you now need to get your import os back :)
• define constants in upper case (PEP8 reference)
• use list comprehensions
• use .format() instead of string concatenation
• use built-in sum() function to for counting
• loop over the items directly instead of indexes

The code after applying the changes:

import os

NUMBER_OF_TRIES = 1000
INPUT_FILE_NAME = 'A-large-practice.in'
OUTPUT_FILE_NAME = 'largeoutput'

def get_number(number, number_of_tries):
print("new case number = {number}".format(number=number))

digit_list = []
current_number = number
for j in range(1, number_of_tries):
number_as_string = str(current_number)

digits = []
for item in number_as_string:
if item not in digits:
digits.append(item)

for digit in digits:
if digit not in digit_list:
digit_list.append(digit)

count = sum(1 for k in range(0, 10) if str(k) in digit_list)
if count == 10:
print("count = 10")
return number_as_string
else:
current_number = number * (j + 1)
print("number = {number}".format(number=number))

return "INSOMNIA"

if __name__ == '__main__':
input_file_name = os.path.join(BASE_DIRECTORY, INPUT_FILE_NAME)
output_file_name = os.path.join(BASE_DIRECTORY, OUTPUT_FILE_NAME)

with open(input_file_name, "r") as input_file, open(output_file_name, "w") as output_file:
number_of_cases = next(input_file)
for case_number in range(1, int(number_of_cases) + 1):
number = int(next(input_file))
result = get_number(number, NUMBER_OF_TRIES)

output_file.write('Case #{case_number}: {result}\n'.format(case_number=case_number, result=result))

Alternative Solution:

We can also improve on both the performance and readability if we would use sets - collecting the digits seen so far until the length of the set is 10 (collected all digits) or we reach the maximum number of tries:

def get_number(number, number_of_tries):
digits = set([])  # keep track of all seen digits

current_number = number
for j in range(1, number_of_tries):
digits |= set(str(current_number))  # add new digits to the seen set

if len(digits) == 10:  # exit if collected all the digits
return current_number
else:
current_number = number * (j + 1)

return "INSOMNIA"


text:
# `(3/2)x - -4 = 13` Solve the equation for x.

To start this question, let's just rewrite it here quickly:

`3/2x - (-4) = 13`

Let's just simplify that minus negative 4 (remember, -- = +):

`3/2x+4 = 13`

Now we can subtract 4 from both sides. We could also get rid of the 3/2 first, but then we'd have to worry about mixing up what to do with the 4. It's usually best to isolate "x" on one side with the rest of the numbers on the other before you do any multiplication or division:

`3/2 x = 9`

Now, things get a little tricky. If you're good with fractions, this will be no problem. If you're not great with them, we can split up this fraction into two separate operations! Look here:

`(3x)/2 = 9`

If you'll notice, we just changed the fraction expression into a multiplication step followed by a division step! Now, we can go back to "doing the opposite as what's being done to x" or however you are used to solving this. Let's start by multiplying both sides by 2:

`3x = 18`

Now, we finish up the problem by dividing by 3:

`x = 6`

If you wanted to work with fractions, we can go back to that step:

`3/2 x = 9`

We'll multiply by the reciprocal:

`2/3*3/2 x = 2/3*9`

`x = 6`

That is exactly the same thing we did before, actually, but just combined into a single step!

I hope that helps!

Approved by eNotes Editorial Team


text:
Contests Virtual Contests Problems Submit Runs Status Rank List Forum

Time Limit: 1.0 Seconds   Memory Limit: 65536K
Total Runs: 205   Accepted Runs: 141    Multiple test files

The table surface is divided into N by M square cells. Some cubes are stacked one upon another over the cells, forming towers. For each cell the number of cubes stacked over it is given in the matrix A.

Your program must output the view of the table in ASCII graphics, where each cube is represented as shown below:

  +---+ / /| +---+ | | | + | |/ +---+  (here the characters used are '+', '-', '/', '|', their ASCII codes are ASCII 43, 45, 47, 124)

The dot (ASCII 46) must be used as a background.

### Constraints

1 ≤ N, M, Aij ≤ 50

### Input format

Input contains integers N M, followed by matrix A, row-by-row. The first row describes the cube tower furthest from the viewer, left to right, and the last row -- nearest to the viewer.

### Output format

Output must contain a string representation of the table view, with minimal number of lines required to show all cubes. Each line must contain a string of equal length, which is the minimal width required to show all cubes.

#### Sample input #1

3 4
1 1 1 1
1 2 1 1
1 1 1 1

#### Sample output #1

........+---+..........
......+/   /|-+---+---+
...../+---+ |/   /   /|
....+-|   | +---+---+ |
.../  |   |/   /   /| +
..+---+---+---+---+ |/.
./   /   /   /   /| +..
+---+---+---+---+ |/...
|   |   |   |   | +....
|   |   |   |   |/.....
+---+---+---+---+......

#### Sample input #2

3 5
2 2 1 2 2
2 2 1 1 2
3 2 1 2 2

#### Sample output #2

......+---+---+...+---+---+
..+---+  /   /|../   /   /|
./   /|-+---+ |.+---+---+ |
+---+ |/   /| +-|  /   /| +
|   | +---+ |/+---+---+ |/|
|   |/   /| +/   /   /| + |
+---+---+ |/+---+---+ |/| +
|   |   | +-|   |   | + |/.
|   |   |/  |   |   |/| +..
+---+---+---+---+---+ |/...
|   |   |   |   |   | +....
|   |   |   |   |   |/.....
+---+---+---+---+---+......

Source: Northeastern Europe 2003 Far-Eastern Subregion
Submit   List    Runs   Forum   Statistics

Tianjin University Online Judge v1.3.0
Maintance:G.D.Retop. Developer: SuperHacker, G.D.Retop