text:
# New URL for NEMO forge! http://forge.nemo-ocean.eu

Since March 2022 along with NEMO 4.2 release, the code development moved to a self-hosted GitLab.
This present forge is now archived and remained online for history.
coding_rules.tex in NEMO/trunk/doc/latex/global – NEMO

# source:NEMO/trunk/doc/latex/global/coding_rules.tex@11433

Last change on this file since 11433 was 11433, checked in by nicolasmartin, 3 years ago

Pre-implementation of new cover page and new headings style for reference manuals

#### Cover page

The layout of the frontpage has been completely redesigned,
a coloured banner has been added to emphasize the title and easily identify each manual
between them.
The chosen color for each document (blue for NEMO, gray for SI3 and green for TOP) will be
used throughout the manual for the links and in the chapter headings.
The list of authors (writers/editors/reviewers) for the version of the manual is given next to
the abstract, which is now included in the frontpage.
A link to an existing ORCID profile for the author precedes its name.
Few settings have been added to each definitions.tex in order to adjust the rendering of the cover page (vertical spaces above and below the title, a subtitle, the width for authors list and
abstract section)

• header: chapter number and title for even pages, same infos for section otherwise
• footer: name of the manual and page numbering with the total number of pages (reverse order between odd/even pages)

For the chapter heading, a new style 'Bjornstrup' from fncychap package is now use.

#### Abstract

Split the section in two paragraphs for all manuals

1. Common description with almost the same sentences only customized by the general infos of the model
2. Specific part for the characteristics of the model

#### Troubleshooting

As announced, I have introduced some icons from academicons and fontawesome packages.
It required to switch from pdflatex to xelatex for the compilation and it prevents from now
the building of the whole document.
Also the PDF generated does not look nice due to the font

Work in progress...

File size: 37.3 KB
Line
1
2\chapter{Coding Rules}
3\label{apdx:coding}
4
5\minitoc
6
7\newpage
8
9A "model life" is more than ten years.
10Its software, composed of a few hundred modules, is used by many people who are scientists or students and
11do not necessarily know every aspect of computing very well.
12Moreover, a well thought-out program is easier to read and understand, less difficult to modify,
13produces fewer bugs and is easier to maintain.
14Therefore, it is essential that the model development follows some rules:
15\begin{itemize}
16   \item well planned and designed
17   \item well written
18   \item well documented (both on- and off-line)
19   \item maintainable
20   \item easily portable
21   \item flexible.
22\end{itemize}
23
24To satisfy part of these aims, \NEMO is written with a coding standard which is close to the ECMWF rules,
25named DOCTOR \citep{gibson_rpt86}.
26These rules present some advantages like:
27\begin{itemize}
28   \item to provide a well presented program
29   \item to use rules for variable names which allow recognition of their type
30   (integer, real, parameter, local or shared variables, etc. ).
31\end{itemize}
32
33This facilitates both the understanding and the debugging of an algorithm.
34
35\section{Introduction}
36
37This document describes conventions used in \NEMO coding and suggested for its development.
38The objectives are to offer a guide to all readers of the \NEMO code, and to facilitate the work of
39all the developers, including the validation of their developments, and
40eventually the implementation of these developments within the \NEMO platform.
41
42A first approach of these rules can be found in the code in \path{./src/OCE/module_example} where
43all the basics coding conventions are illustrated.
44More details can be found below.
45
46This work is based on the coding conventions in use for the Community Climate System Model
47\footnote {\href{http://www.cesm.ucar.edu/working_groups/Software/dev_guide/dev_guide/node7.html}{UCAR conventions}},
48the previous version of this document (FORTRAN coding standard in the OPA System'') and
49the expertise of the \NEMO System Team.
50After a general overview below, this document will describe:
51
52\begin{itemize}
53   \item The style rules, $i.e.$ the syntax, appearance and naming conventions chosen to improve readability of the code;
54   \item The content rules, $i.e.$ the conventions to improve the reliability of the different parts of the code;
55   \item The package rules to go a step further by improving the reliability of the whole and
56   interfaces between routines and modules.
57\end{itemize}
58
59\section{Overview and general conventions}
60
61\NEMO has 3 major components: ocean dynamics (\path{./src/OCE}), sea-ice (\path{./src/ICE}) and
62marine biogeochemistry (\path{./src/MBG}).
63%, linear-tangent and adjoint of the dynamics ($TAM$) each of them corresponding to a directory.
64In each directory, one will find some FORTRAN files and/or subdirectories, one per functionality of the code:
65\path{./src/OCE/BDY} (boundaries), \path{./src/OCE/DIA} (diagnostics), \path{./src/OCE/DOM} (domain),
66\path{./src/OCE/DYN} (dynamics), \path{./src/OCE/LDF} (lateral diffusion), etc... \\
67All name are chosen to be as self-explanatory as possible, in English, all prefixes are 3 digits. \\
68English is used for all variables names, comments, and documentation. \\
69Physical units are MKS. The only exception to this is the temperature, which is expressed in degrees Celsius,
70except in bulk formulae and part of SI$^3$ sea-ice model where it is in Kelvin.
71See \path{.src/OCE/DOM/phycst.F90} files for conversions.
72
73\section{Architecture}
74
75Within each directory, organisation of files is driven by orthogonality,
76$i.e.$ one functionality of the code is intended to be in one and only one directory, and
77one module and all its related routines are in one file.
78The functional modules are:
79
80\begin{itemize}
81   \item \path{SBC}             surface module
82   \item \path{IOM}             management of the I/O
83   \item \path{NST}             interface to AGRIF (nesting model) for dynamics and biogeochemistry
84   \item \path{OBC}, \path{BDY} management of structured and unstructured open boundaries
85   \item \path{C1D}             1D (vertical) configuration for dynamics, sea-ice and biogeochemistry
86   \item \path{OFF}             off-line module: passive tracer or biogeochemistry alone
87   \item \path{...}
88\end{itemize}
89
90For example, the file \textit{domain.F90} contains the module \texttt{domain} and all the subroutines related to
91this module (\texttt{dom\_init, dom\_nam, dom\_ctl}).
92
93\section{Style rules}
94
95\subsection{Argument list format}
96
97Routine argument lists will contain a maximum 5 variables per line,
98whilst continuation lines can be used.
99This applies both to the calling routine and the dummy argument list in the routine being called.
100The purpose is to simplify matching up the arguments between caller and callee.
101
102\begin{forlines}
103SUBROUTINE tra_adv_eiv( kt, pun, pvn, pwn )
104
105      CALL tra_adv_eiv( kt, zun, zvn, zwn )
106\end{forlines}
107
108\subsection{Array syntax}
109
110Except for long loops (see below), array notation should be used if possible.
111To improve readability the array shape must be shown in brackets, $e.g.$:
112
113\begin{forlines}
114onedarraya(:)   = onedarrayb(:) + onedarrayc(:)
115twodarray (:,:) = scalar * anothertwodarray(:,:)
116\end{forlines}
117
118When accessing sections of arrays, for example in finite difference equations,
119do so by using the triplet notation on the full array, $e.g.$:
120
121\begin{forlines}
122twodarray(:,2:len2) =   scalar                      &
123   &                  * ( twodarray2(:,1:len2-1 )   &
124   &                  -   twodarray2(:,2:len2 ) )
125\end{forlines}
126
127For long, complicated loops, explicitly indexed loops should be preferred.
128In general when using this syntax, the order of the loops indices should reflect the following scheme
129(for best usage of data locality):
130
131\begin{forlines}
132DO jk = 1, jpk
133   DO jj = 1, jpj
134      DO ji = 1, jpi
135         threedarray(ji,jj,jk) = ...
136      END DO
137   END DO
138END DO
139\end{forlines}
140
141\subsection{Case}
142
143All FORTRAN keywords are in capital: \forcode{DIMENSION}, \forcode{WRITE}, \forcode{DO}, \forcode{END DO},
144\forcode{NAMELIST}, ... All other parts of the \NEMO code will be written in lower case.
145
147
148Comments in the code are useful when reading the code and changing or developing it. \\
149The full documentation and detailed explanations are to be added in the reference manual
150(TeX files, aside from the code itself). \\
151In the code, the comments should explain variable content and describe each computational step. \\
152Comments in the header start with !!''.
153For more details on the content of the headers, see Content rules/Headers in this document. \\
154Comments in the code start with !''. \\
155All comments are indented (3, 6, or 9 blank spaces). \\
156Short comments may be included on the same line as executable code, and an additional line can be used with
157proper alignment.
158For example:
159
160\begin{forlines}
161zx = zx *zzy   ! Describe what is going on and if it is
162!              ! too long use another ! for proper
163!              ! alignment with automatic indentation
164\end{forlines}
165
166More in-depth comments should be written in the form:
167
168\begin{forlines}
169   !  Check of some namelist values
170\end{forlines}
171
172or
173
174\begin{forlines}
175!
176!     !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
177!     !  Bottom boundary condition on tke
178!     !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
179!
180\end{forlines}
181
182Key features of this style are
183
184\begin{enumerate}
185\item it starts with a "!" in the column required for proper indentation,
186\item the text is offset above and below by a blank line or a content line built for underlying.
187\end{enumerate}
188
189\subsection{Continuation lines}
190
191Continuation lines can be used with precise alignment for readability. For example:
192
193\begin{forlines}
194avmu(ji,jj,jk) =   avmu(ji,jj,jk) * ( un(ji,jj,jk-1) - un(ji,jj,jk) )   &
195   &                              * ( ub(ji,jj,jk-1) - ub(ji,jj,jk) )   &
196   &             / (   fse3uw_n(ji,jj,jk)                               &
197   &                 * fse3uw_b(ji,jj,jk) )
198\end{forlines}
199
200Code lines, which are continuation lines of assignment statements, must begin to the right of the column of
201the assignment operator.
202Due to the possibility of automatic indentation in some editor (emacs for example),
203use a \&'' as first character of the continuing lines to maintain the alignment.
204
205\subsection{Declaration of arguments and local variables}
206
207In a routine, input arguments and local variables are declared 1 per line,
208with a comment field on the same line as the declaration.
209Multiple comment lines describing a single variable are acceptable if needed.
210For example:
211
212\begin{forlines}
213INTEGER             ::   kstp   ! ocean time-step index
214\end{forlines}
215
216\subsection{F90 Standard}
217
218\NEMO software adheres to the \fninety language standard and does not rely on any specific language or
219vendor extensions.
220
221\subsection{Free-Form Source}
222
223Free-form source will be used.
224The F90/95 standard allows lines of up to 132 characters, but a self-imposed limit of 80 should enhance readability,
225or print source files with two columns per page.
226Multi-line comments that extend to column 100 are unacceptable.
227
228\subsection{Indentation}
229
230Code as well as comment lines within loops, if-blocks, continuation lines, \forcode{MODULE} or
231\forcode{SUBROUTINE} statements will be indented 3 characters for readability
232(except for \forcode{CONTAINS} that remains at first column).
233
234\begin{forlines}
235MODULE mod1
236   REAL(wp) xx
237CONTAINS
238   SUBROUTINE sub76( px, py, pz, pw, pa,   &
239      &              pb, pc, pd, pe          )
240      <instruction>
241   END SUBROUTINE sub76
242END MODULE mod1
243\end{forlines}
244
245\subsection{Loops}
246
247Loops, if explicit, should be structured with the do-end do construct as opposed to numbered loops.
248Nevertheless non-numeric labels can be used for a big iterative loop of a recursive algorithm.
249In the case of a long loop, a self-descriptive label can be used ($i.e.$ not just a number).
250
251\subsection{Naming Conventions: files}
252
253A file containing a module will have the same name as the module it contains
254(because dependency rules used by "make" programs are based on file names).
255\footnote{
256  For example, if routine A "\forcode{USE}"s module B, then "make" must be told of the dependency relation which
257  requires B to be compiled before A.
258  If one can assume that module B resides in file B.o,
259  building a tool to generate this dependency rule ($e.g.$ A.o: B.o) is quite simple.
260  Put another way, it is difficult (to say nothing of CPU-intensive) to search an entire source tree to
261  find the file in which module B resides for each routine or module which "\forcode{USE}"s B.
262}
263
264\subsection{Naming Conventions: modules}
265
266Use a meaningful English name and the 3 letters'' naming convention:
267first 3 letters for the code section, and last 3 to describe the module.
268For example, zdftke, where zdf'' stands for vertical diffusion, and tke'' for turbulent kinetic energy. \\
269Note that by implication multiple modules are not allowed in a single file.
270The use of common blocks is deprecated in \fortran 90 and their use in \NEMO is strongly discouraged.
271Modules are a better way to declare static data.
272Among the advantages of modules is the ability to freely mix data of various types, and
273to limit access to contained variables through the use of the \forcode{ONLY} and \forcode{PRIVATE} attributes.
274
275\subsection{Naming Conventions: variables}
276
277All variable should be named as explicitly as possible in English.
278The naming convention concerns prefix letters of these name, in order to identify the variable type and status. \\
279Never use a \fortran keyword as a routine or variable name. \\
280The table below lists the starting letter(s) to be used for variable naming, depending on their type and status:
281%--------------------------------------------------TABLE--------------------------------------------------
282\begin{table}[htbp]
283  \begin{center}
284    \begin{tabular}{|p{50pt}|p{50pt}|p{50pt}|p{50pt}|p{50pt}|p{50pt}|p{50pt}|}
285      \hline
286      Type \par / Status                                                                          &
287      integer                                                                                &
288      real                                                                                &
289      logical                                                                                &
290      character                                                                                &
291      double \par precision                                                                       &
292      complex                                                                                \\
293      \hline
294      public \par or \par module variable                                                         &
295      \textbf{m n} \par \textit{but not} \par \textbf{nn\_}                                       &
296      \textbf{a b e f g h o} \textbf{q} \textit{to} \textbf{x} \par but not \par \textbf{fs rn\_} &
297      \textbf{l} \par \textit{but not} \par \textbf{lp ld ll ln\_}                                &
298      \textbf{c} \par \textit{but not} \par \textbf{cp cd cl cn\_}                                &
299      \textbf{d} \par \textit{but not} \par \textbf{dp dd dl dn\_}                                &
300      \textbf{y} \par \textit{but not} \par \textbf{yp yd yl}                                     \\
301      \hline
302      dummy \par argument                                                                         &
303      \textbf{k} \par \textit{but not} \par \textbf{kf}                                           &
304      \textbf{p} \par \textit{but not} \par \textbf{pp pf}                                        &
305      \textbf{ld}                                                                                &
306      \textbf{cd}                                                                                &
307      \textbf{dd}                                                                                &
308      \textbf{yd}                                                                                \\
309      \hline
310      local \par variable                                                                         &
311      \textbf{i}                                                                                &
312      \textbf{z}                                                                                &
313      \textbf{ll}                                                                                &
314      \textbf{cl}                                                                                &
315      \textbf{cd}                                                                                &
316      \textbf{yl}                                                                                \\
317      \hline
318      loop \par control                                                                           &
319      \textbf{j} \par \textit{but not} \par \textbf{jp}                                           &
320                                                                                &
321                                                                                &
322                                                                                &
323                                                                                &
324                                                                                \\
325      \hline
326      parameter                                                                                &
327      \textbf{jp}                                                                                &
328      \textbf{pp}                                                                                &
329      \textbf{lp}                                                                                &
330      \textbf{cp}                                                                                &
331      \textbf{dp}                                                                                &
332      \textbf{yp}                                                                                \\
333      \hline
334      namelist                                                                                &
335      \textbf{nn\_}                                                                               &
336      \textbf{rn\_}                                                                               &
337      \textbf{ln\_}                                                                               &
338      \textbf{cn\_}                                                                               &
339      \textbf{dn\_}                                                                               &
340                                                                                \\
341      \hline
342      CPP \par macro                                                                              &
343      \textbf{kf}                                                                                &
344      \textbf{sf}                                                                                &
345                                                                                &
346                                                                                &
347                                                                                &
348                                                                                \\
349      \hline
350    \end{tabular}
351    \label{tab1}
352  \end{center}
353\end{table}
354%--------------------------------------------------------------------------------------------------------------
355
356\subsection{Operators}
357
358Use of the operators \texttt{<, >, <=, >=, ==, /=} is strongly recommended instead of their deprecated counterparts
359(\texttt{.lt., .gt., .le., .ge., .eq., .ne.}).
361In general use the notation: \\
362$<Blank><Operator><Blank>$
363
364\subsection{Pre processor}
365
366Where the use of a language pre-processor is required, it will be the C pre-processor (cpp). \\
367The cpp key is the main feature used, allowing to ignore some useless parts of the code at compilation step. \\
368The advantage is to reduce the memory use; the drawback is that compilation of this part of the code isn't checked. \\
369The cpp key feature should only be used for a few limited options, if it reduces the memory usage.
370In all cases, a logical variable and a FORTRAN \forcode{IF} should be preferred.
371When using a cpp key \textit{key\_optionname},
372a corresponding logical variable \textit{lk\_optionname} should be declared to
373allow FORTRAN \forcode{IF} tests in the code and
374a FORTRAN module with the same name ($i.e.$ \textit{optionname.F90}) should be defined.
375This module is the only place where a \\#if defined'' command appears, selecting either the whole FORTRAN code or
376a dummy module.
377For example, the TKE vertical physics, the module name is \textit{zdftke.F90},
378the CPP key is \textit{key\_zdftke} and the associated logical is \textit{lk\_zdftke}.
379
380The following syntax:
381
382\begin{forlines}
383#if defined key_optionname
384!! Part of code conditionally compiled if cpp key key_optionname is active
385#endif
386\end{forlines}
387
388Is to be used rather than the \#ifdef abbreviate form since it may have conflicts with some Unix scripts.
389
390Tests on cpp keys included in \NEMO at compilation step:
391
392\begin{itemize}
393\item
394  The CPP keys used are compared to the previous list of cpp keys
395  (the compilation will stop if trying to specify a non-existing key)
396\item
397  If a change occurs in the CPP keys used for a given experiment, the whole compilation phase is done again.
398\end{itemize}
399
400\section{Content rules}
401
402\subsection{Configurations}
403
404The configuration defines the domain and the grid on which \NEMO is running.
405It may be useful to associate a CPP key and some variables to a given configuration, although
406the part of the code changed under each of those keys should be minimized.
407As an example, the "ORCA2" configuration (global ocean, 2 degrees grid size) is associated with
408the cpp key \texttt{key\_orca2} for which
409
410\begin{forlines}
411cp_cfg = "orca"
412jp_cfg = 2
413\end{forlines}
414
415\subsection{Constants}
416
417Physical constants ($e.g.$ $\pi$, gas constants) must never be hard-wired into the executable portion of a code.
418Instead, a mnemonically named variable or parameter should be set to the appropriate value,
419in the setup routine for the package.
420We realize than many parameterizations rely on empirically derived constants or fudge factors,
421which are not easy to name.
422In these cases it is not forbidden to leave such factors coded as "magic numbers" buried in executable code, but
423comments should be included referring to the source of the empirical formula.
424Hard-coded numbers should never be passed through argument lists.
425
426\subsection{Declaration for variables and constants}
427
428\subsubsection{Rules}
429
430Variables used as constants should be declared with attribute \forcode{PARAMETER} and
431used always without copying to local variables, in order to
432prevent from using different values for the same constant or changing it accidentally.
433
434\begin{itemize}
435\item
436  Usage of the \forcode{DIMENSION} statement or attribute is required in declaration statements
437\item
438  The ::'' notation is quite useful to show that this program unit declaration part is written in
439  standard FORTRAN syntax, even if there are no attributes to clarify the declaration section.
440  Always use the notation $<$blank$>$::$<$three blanks$>$ to improve readability.
441\item
442  Declare the length of a character variable using the \forcode{CHARACTER} (len=xxx) syntax
443  \footnote {
444    The len specifier is important because it is possible to have several kinds for characters
445    ($e.g.$ Unicode using two bytes per character, or there might be a different kind for Japanese $e.g.$ NEC).
446  }
447\item
448  For all global data (in contrast to module data, that is all data that can be access by other module)
449  must be accompanied with a comment field on the same line
450  \footnote {
451    This allows a easy research of where and how a variable is declared using the unix command:
452    grep var *90 | grep !:''.
453  }.
454  For example:
455  \begin{forlines}
456  REAL(wp), DIMENSION(jpi,jpj,jpk) ::  ua   ! i-horizontal velocity (m/s)
457  \end{forlines}
458\end{itemize}
459
460\subsubsection{Implicit None}
461
462All subroutines and functions will include an \forcode{IMPLICIT NONE} statement.
463Thus all variables must be explicitly typed.
464It also allows the compiler to detect typographical errors in variable names.
465For modules, one \forcode{IMPLICIT NONE} statement in the modules definition section is needed.
466This also removes the need to have \forcode{IMPLICIT NONE} statements in
467any routines that are \forcode{CONTAINS}'ed in the module.
468Improper data initialisation is another common source of errors
469\footnote{
470  A variable could contain an initial value you did not expect.
471  This can happen for several reasons, $e.g.$ the variable has never been assigned a value, its value is outdated,
472  memory has been allocated for a pointer but you have forgotten to initialise the variable pointed to.
473}.
474To avoid problems, initialise variables as close as possible to where they are first used.
475
476\subsubsection{Attributes}
477
478\forcode{PRIVATE} / \forcode{PUBLIC}:
479All resources of a module are \forcode{PUBLIC} by default.
480A reason to store multiple routines and their data in a single module is that
481the scope of the data defined in the module can be limited to the routines which are in the same module.
482This is accomplished with the \forcode{PRIVATE} attribute. \\
483\forcode{INTENT}:
484All dummy arguments of a routine must include the \forcode{INTENT} clause in their declaration in order to
485improve control of variables in routine calls.
486
488
489Prologues are not used in \NEMO for now, although it may become an interesting tool in combination with
490ProTeX auto documentation script in the future.
491Rules to code the headers and layout of a module or a routine are illustrated in the example module available with
492the code: \path{./src/OCE/module_example}
493
494\subsection{Interface blocks}
495
496Explicit interface blocks are required between routines if optional or keyword arguments are to be used.
497They also allow the compiler to check that the type, shape and number of arguments specified in the \forcode{CALL}
498are the same as those specified in the subprogram itself.
499FORTRAN 95 compilers can automatically provide explicit interface blocks for routines contained in a module.
500
501\subsection{I/O Error Conditions}
502
503I/O statements which need to check an error condition will use the \texttt{iostat=<integer variable>} construct
504instead of the outmoded \texttt{end=} and \forcode{err=}. \\
505Note that a 0 value means success, a positive value means an error has occurred, and
506a negative value means the end of record or end of file was encountered.
507
508\subsection{PRINT - ASCII output files}
509
510Output listing and errors are directed to \texttt{numout} logical unit =6 and
511produces a file called \textit{ocean.output} (use \texttt{ln\_prt} to have one output per process in MPP).
512Logical \texttt{lwp} variable allows for less verbose outputs.
513To output an error from a routine, one can use the following template:
514
515\begin{forlines}
516IF( nstop /= 0 .AND. lwp ) THEN   ! error print
517   WRITE(numout,cform_err)
518   WRITE(numout,*) nstop, ' error have been found'
519ENDIF
520\end{forlines}
521
522\subsection{Precision}
523
524Parameterizations should not rely on vendor-supplied flags to supply a default floating point precision or
525integer size.
526The F95 \forcode{KIND} feature should be used instead.
527In order to improve portability between 32 and 64 bit platforms,
528it is necessary to make use of kinds by using a specific module \path{./src/OCE/par_kind.F90}
529declaring the "kind definitions" to obtain the required numerical precision and range as well as
530the size of \forcode{INTEGER}.
531It should be noted that numerical constants need to have a suffix of \texttt{\_kindvalue} to
532have the according size. \\
533Thus \forcode{wp} being the "working precision" as declared in \path{./src/OCE/par_kind.F90},
534declaring real array \forcode{zpc} will take the form:
535
536\begin{forlines}
537REAL(wp), DIMENSION(jpi,jpj,jpk) ::  zpc      ! power consumption
538\end{forlines}
539
540\subsection{Structures}
541
542The \forcode{TYPE} structure allowing to declare some variables is more often used in \NEMO,
543especially in the modules dealing with reading fields, or interfaces.
544For example:
545
546\begin{forlines}
547! Definition of a tracer as a structure
548TYPE PTRACER
549   CHARACTER(len = 20)  :: sname  ! short name
550   CHARACTER(len = 80 ) :: lname  ! long name
551   CHARACTER(len = 20 ) :: unit   ! unit
552   LOGICAL              :: lini   ! read in a file or not
553   LOGICAL              :: lsav   ! ouput the tracer or not
554END TYPE PTRACER
555
556TYPE(PTRACER) , DIMENSION(jptra) :: tracer
557\end{forlines}
558
559Missing rule on structure name??
560
561\section{Packages coding rules}
562
563\subsection{Bounds checking}
564
565\NEMO is able to run when an array bounds checking option is enabled
566(provided the cpp key \texttt{key\_vectopt\_loop} is not defined). \\
567Thus, constructs of the following form are disallowed:
568
569\begin{forlines}
570REAL(wp) :: arr(1)
571\end{forlines}
572
573where "arr" is an input argument into which the user wishes to index beyond 1.
574Use of the (*) construct in array dimensioning is forbidden also because
575it effectively disables array bounds checking.
576
577\subsection{Communication}
578
579A package should refer only to its own modules and subprograms and to those intrinsic functions included in
580the Fortran standard. \\
581All communication with the package will be through the argument list or namelist input.
582\footnote{
583  The point behind this rule is that packages should not have to know details of
584  the surrounding model data structures, or the names of variables outside of the package.
585  A notable exception to this rule is model resolution parameters.
586  The reason for the exception is to allow compile-time array sizing inside the package.
587  This is often important for efficiency.
588}
589
590\subsection{Error conditions}
591
592When an error condition occurs inside a package, a message describing what went wrong will be printed
593(see PRINT - ASCII output files).
594The name of the routine in which the error occurred must be included.
595It is acceptable to terminate execution within a package, but
596the developer may instead wish to return an error flag through the argument list,
597see \textit{stpctl.F90}.
598
599\subsection{Memory management}
600
601The main action is to identify and declare which arrays are \forcode{PUBLIC} and which are \forcode{PRIVATE}. \\
602As of version 3.3.1 of \NEMO, the use of static arrays (size fixed at compile time) has been deprecated.
603All module arrays are now declared \forcode{ALLOCATABLE} and
604allocated in either the \texttt{<module\_name>\_alloc()} or \texttt{<module\_name>\_init()} routines.
605The success or otherwise of each \forcode{ALLOCATE} must be checked using
606the \texttt{stat=<integer\ variable>} optional argument. \\
607
608In addition to arrays contained within modules, many routines in \NEMO require local, workspace'' arrays to
609hold the intermediate results of calculations.
610In previous versions of \NEMO, these arrays were declared in such a way as to be automatically allocated on
611the stack when the routine was called.
612An example of an automatic array is:
613
614\begin{forlines}
615SUBROUTINE sub(n)
616   REAL :: a(n)
617   ...
618END SUBROUTINE sub
619\end{forlines}
620
621The downside of this approach is that the program will crash if it runs out of stack space and
622the reason for the crash might not be obvious to the user.
623
624Therefore, as of version 3.3.1, the use of automatic arrays is deprecated.
625Instead, a new module, \textit{wrk\_nemo.F90}, has been introduced which
626contains 1-,2-,3- and 4-dimensional workspace arrays for use in subroutines.
627These workspace arrays should be used in preference to declaring new, local (allocatable) arrays whenever possible.
628The only exceptions to this are when workspace arrays with lower bounds other than 1 and/or
629with extent(s) greater than those in the \textit{wrk\_nemo.F90} module are required. \\
630
631The 2D, 3D and 4D workspace arrays in \textit{wrk\_nemo.F90} have extents \texttt{jpi}, \texttt{jpj},
632\texttt{jpk} and \texttt{jpts} ($x$, $y$, $z$ and tracers) in the first, second, third and fourth dimensions,
633respectively.
634The 1D arrays are allocated with extent MAX($jpi \times jpj, jpk \times jpj, jpi \times jpk$). \\
635
636The \forcode{REAL (KIND = wp)} workspace arrays in \textit{wrk\_nemo.F90}
637are named $e.g.$ \texttt{wrk\_1d\_1, wrk\_4d\_2} etc. and
638should be accessed by USE'ing the \textit{wrk\_nemo.F90} module.
639Since these arrays are available to any routine,
640some care must be taken that a given workspace array is not already being used somewhere up the call stack.
641To help with this, \textit{wrk\_nemo.F90} also contains some utility routines;
642\texttt{wrk\_in\_use()} and \texttt{wrk\_not\_released()}.
643The former first checks that the requested arrays are not already in use and then sets internal flags to show that
644they are now in use.
645The \texttt{wrk\_not\_released()} routine un-sets those internal flags.
646A subroutine using this functionality for two, 3D workspace arrays named \texttt{zwrk1} and
647\texttt{zwrk2} will look something like:
648
649\begin{forlines}
650SUBROUTINE sub()
651   USE wrk_nemo, ONLY: wrk_in_use, wrk_not_released
652   USE wrk_nemo, ONLY: zwrk1 => wrk_3d_5, zwrk2 => wrk_3d_6
653   !
654   IF(wrk_in_use(3, 5,6)THEN
655      CALL ctl_stop('sub: requested workspace arrays unavailable.')
656      RETURN
657   END IF
658   ...
659   ...
660   IF(wrk_not_released(3, 5,6)THEN
661      CALL ctl_stop('sub: failed to release workspace arrays.')
662   END IF
663   !
664END SUBROUTINE sub
665\end{forlines}
666
667The first argument to each of the utility routines is the dimensionality of the required workspace (1--4).
668Following this there must be one or more integers identifying which workspaces are to be used/released.
669Note that, in the interests of keeping the code as simple as possible,
670there is no use of \forcode{POINTER}s etc. in the \textit{wrk\_nemo.F90} module.
671Therefore it is the responsibility of the developer to ensure that the arguments to \texttt{wrk\_in\_use()} and
672\texttt{wrk\_not\_released()} match the workspace arrays actually being used by the subroutine. \\
673
674If a workspace array is required that has extent(s) less than those of the arrays in
675the \textit{wrk\_nemo.F90} module then the advantages of implicit loops and bounds checking may be retained by
676defining a pointer to a sub-array as follows:
677
678\begin{forlines}
679SUBROUTINE sub()
680   USE wrk_nemo, ONLY: wrk_in_use, wrk_not_released
681   USE wrk_nemo, ONLY: wrk_3d_5
682   !
683   REAL(wp), DIMENSION(:,:,:), POINTER :: zwrk1
684   !
685   IF(wrk_in_use(3, 5)THEN
686      CALL ctl_stop('sub: requested workspace arrays unavailable.')
687      RETURN
688   END IF
689   !
690   zwrk1 => wrk_3d_5(1:10,1:10,1:10)
691   ...
692END SUBROUTINE sub
693\end{forlines}
694
695Here, instead of use associating'' the variable \texttt{zwrk1} with the array \texttt{wrk\_3d\_5}
696(as in the first example), it is explicitly declared as a pointer to a 3D array.
697It is then associated with a sub-array of \texttt{wrk\_3d\_5} once the call to
698\texttt{wrk\_in\_use()} has completed successfully.
699Note that in F95 (to which \NEMO conforms) it is not possible for either the upper or lower array bounds of
700the pointer object to differ from those of the target array. \\
701
702In addition to the \forcode{REAL (KIND = wp)} workspace arrays,
703\textit{wrk\_nemo.F90} also contains 2D integer arrays and 2D REAL arrays with extent (\texttt{jpi}, \texttt{jpk}),
704$i.e.$ $xz$.
705The utility routines for the integer workspaces are \texttt{iwrk\_in\_use()} and \texttt{iwrk\_not\_released()} while
706those for the $xz$ workspaces are \texttt{wrk\_in\_use\_xz()} and \texttt{wrk\_not\_released\_xz()}.
707
708Should a call to one of the \texttt{wrk\_in\_use()} family of utilities fail,
709an error message is printed along with a table showing which of the workspace arrays are currently in use.
710This should enable the developer to choose alternatives for use in the subroutine being worked on. \\
711
712When compiling \NEMO for production runs,
713the calls to {\texttt{wrk\_in\_use()} / \texttt{wrk\_not\_released()} can be reduced to stubs that just
714return \forcode{.false.} by setting the cpp key \texttt{key\_no\_workspace\_check}.
715These stubs may then be in-lined (and thus effectively removed altogether) by setting appropriate compiler flags
716($e.g.$ -finline'' for the Intel compiler or -Q'' for the IBM compiler).
717
718\subsection{Optimisation}
719
720Considering the new computer architecture, optimisation cannot be considered independently from the computer type.
721In \NEMO, portability is a priority, before any too specific optimisation.
722
723Some tools are available to help: for vector computers, \texttt{key\_vectopt\_loop} allows to unroll a loop
724
725\subsection{Package attribute: \forcode{PRIVATE}, \forcode{PUBLIC}, \forcode{USE}, \forcode{ONLY}}
726
727Module variables and routines should be encapsulated by using the \forcode{PRIVATE} attribute.
728What shall be used outside the module can be declared \forcode{PUBLIC} instead.
729Use \forcode{USE} with the \forcode{ONLY} attribute to specify which of the variables, type definitions etc...
730defined in a module are to be made available to the using routine.
731
732\subsection{Parallelism using MPI}
733
734\NEMO is written in order to be able to run on one processor, or on one or more using MPI
735($i.e.$ activating the cpp key $key\_mpp\_mpi$).
736The domain decomposition divides the global domain in cubes (see \NEMO reference manual).
737Whilst coding a new development, the MPI compatibility has to be taken in account
738(see \path{./src/LBC/lib_mpp.F90}) and should be tested.
739By default, the $x$-$z$ part of the decomposition is chosen to be as square as possible.
740However, this may be overriden by specifying the number of sub-domains in latitude and longitude in
741the \texttt{nammpp} section of the namelist file.
742
743\section{Features to be avoided}
744
745The code must follow the current standards of FORTRAN and ANSI C.
746In particular, the code should not produce any WARNING at compiling phase, so that
747users can be easily alerted of potential bugs when some appear in their new developments.
748Below is a list of features to avoid:
749\begin{itemize}
750\item
751  \forcode{COMMON} block
752  (use the declaration part of \forcode{MODULE} instead)
753\item
754  \forcode{EQUIVALENCE}
755  (use \forcode{POINTER} or derived data type instead to form data structure)
756\item
757  Assigned and computed \forcode{GOTO}
758  (use the \forcode{CASE} construct instead)
759\item
760  Arithmetic \forcode{IF} statement
761  (use the block \forcode{IF}, \forcode{ELSE}, \forcode{ELSEIF}, \forcode{ENDIF} or
763\item
764  Labelled \forcode{DO} construct
765  (use unlabelled \forcode{END DO} instead)
766\item
767  \forcode{FORMAT} statement
768  (use character parameters or
770\item
771  \forcode{GOTO} and \forcode{CONTINUE} statements
772  (use \forcode{IF}, \forcode{CASE}, \forcode{DO WHILE}, \forcode{EXIT} or \forcode{CYCLE} statements or
773  a contained ?)
774\item
775  \forcode{PAUSE}
776\item
777  \forcode{ENTRY} statement: a sub-program must only have one entry point.
778\item
779  \forcode{RETURN} is obsolete and so not necessary at the end of program units
780\item
781  \forcode{FUNCTION} statement
782\item
783  Avoid functions with side effects.
784  \footnote{
785    First, the code is easier to understand, if you can rely on
786    the rule that functions don't change their arguments.
787    Second, some compilers generate more efficient code for PURE functions
788    (in FORTRAN 95 there are the attributes PURE and ELEMENTAL), because
789    they can store the arguments in different places.
790    This is especially important on massive parallel and as well on vector machines.
791  }
792\item
793  \forcode{DATA} and \forcode{BLOCK DATA}
794  (use initialisers)
795\end{itemize}
796
Note: See TracBrowser for help on using the repository browser.


text:
## Transition matrix for Markov Chain

N black balls and N white balls are placed in two urns so that each urn contains N balls. After each unit of time one ball is selected at random from each urn, and the two balls thus selected are interchanged. Let Xn be the number of white balls in the first urn after n units of time. Determine the transition matrix of the Markov chain X.

It looks as if this should depend on the number of white balls in the first urn in the first place, but apparently this is not true. How do we derive the transition matrix (and show it is the same regardless of the initial set up?)

format: plain


text:
# Note-Taking Software

There are a lot of tasks which are so simple that most programmers think that they can just set out and write their own. One of this is note-taking software. There are a couple products out there, but none are quite perfect. And instead of improving one of the existing ones, it is tempting to just start with their own. In the end, of course, there will be just one additional niche solution that only really works for the programmer but not the next user.

Sometimes there are conflicting requirements. Like you want something that is WYSIWYG or not, should it be in the cloud or private. Yet many other things could be made configurable.

I often take notes when sorting my thoughts. That could be as part of my dissertation, drafting blog posts or comparing products when buying something. And now I am looking for a note-taking software that I can use for my dissertation and in the progress I get a blog post out of that. Guess that checks all the boxes then.

My workflow generally consists of writing structured text and adding screenshots, inline math and code snippets along the way. I will compare a few products that I have tried out for note-taking.

## Products

### GitHub Issues

On GitHub one can track issues that feature Markdown. We as a research group use it for code and also our analysis code is there. Instead of using e-mail chains I prefer to use the GitHub Issues also for discussion. So I have abused them for note-taking as well.

Adding images is super easy via drag-and-drop. They get uploaded, assigned some random file name and the Markdown image code is inserted. Also I can add code snippets easily. However, math support is not available.

Discussion intermediate results with my coworkers is really easy this way. But it does not quite fit for things where I work on myself. Or where I want to spare everyone the details. Some of my documents are somewhat write-only, and having everyone else read them is a waste of time.

### Notes-Up

The only Markdown based note taking application that is packaged for Fedora is Notes-Up. It has Markdown stying and one can insert images via the context menu. They get stored internally and I do not have to worry about it.

I also like the interface and how it is structured into notebooks and pages.

My problem with it is that it stores everything in one opaque SQLite database, including the images. This means that one cannot just simply grab a bit of the content and put it elsewhere. One can export as Markdown, but then the images are just gone. One can export to PDF, but it looks quite ugly, rendered with a sans font. At least the paper format is A4.

Also there is no math support. Taking both things together just rule out scientific note-taking with that program.

### Notable

The Notable software is proprietary software at zero cost. It used to be open source, but is not any more. It stores everything as Markdown files. One can add attachments, but including an image in the document needs many steps and one always has to include them with the relative path ../attachment/ to make it work.

Then I think that it did not have math support either.

It might have really nice search features and tagging abilities, but I did not look further into it because the way that image attachments is not how I like it.

The notes service provided by Google is nice because I have it everywhere. It is intended for many small notes and not the larger report-style notes that I want to create. I surely can use Markup there, it just never gets rendered.

### Markdown files on disk

So what I am doing now is just super simple: Having a bunch of Markdown files on disk. This way I can use whatever editor I like (I'm writing this in Marker), switch editors whenever I feel like it.

Image attachments are not automatic, but I just place the images into the same directory as the Markdown file. And to be able to disentagle different notes from each other I just place each note into a separate directory. As the directory name is the title of the note and there is just one Markdown file per directory, I just call it index.md. The directory tree simply looks like this:

Notes
├── 20190910-Thermal State Removal
│   └── index.md
├── 20200521-cA2.09.48 Stride Investigation
│   ├── Bildschirmfoto_20200521-001-11:57RR-Auswahl.png
│   ├── Bildschirmfoto_20200521-001-12:01RR-Auswahl.png
│   ├── Bildschirmfoto_20200521-008-Auswahl.png
│   ├── Bildschirmfoto_20200521-009-Auswahl.png
│   ├── Bildschirmfoto_20200521-010-Auswahl.png
│   ├── Bildschirmfoto_20200521-011-Auswahl.png
│   ├── index.md
│   └── pattern-of-three.png
└── 20200527-Fit Ranges on cA2.09.48
├── Bildschirmfoto_20200527-15:01:46-cc5-Auswahl.png
└── index.md

1. This is the exact same structure that I use with my Nikola blog.

I can search these notes using grep, I can easily take parts and post them on GitHub (having to manually upload the images, though). I can transfer it to my blog without any change. I can use Pandoc to create HTML or PDF representations that use a style of my liking.

So with this I do lack the tagging features that other products have, but I have sufficient flexiblity.

### Joplin

Although Joplin is not available in the Fedora repositories, I still wanted to give it a try because it looks so promising. Fedora Magazine gives installation instructions via a Copr repository.

It organizes notes into notebooks and notes, just like Notes-Up does it. There is also support for subnotebooks if one wants to. It features different editor/viewer layouts and looks quite nice.

In the screenshot you can see a note that I have imported from a Markdown file. As one can see it has imported the resources and gave them new file names. Looking at the storage location, one can see how the files are organized internally. There is an SQLite database for the text and just a bunch of image files in a directory for the attachments.

.config/joplin-desktop/
├── database.sqlite
├── log-database.txt
├── log.txt
├── resources
│   ├── 0201cb0e79504a2eb2dbbe86a8c7e03f.png
│   ├── 08b9967321044c568ac95a8b97e70162.png
│   ├── 3c3bc0f3b07d42a8bc8f7c6baaeabcc8.png
│   ├── 4588241bdd6746e5971f18c3b4c2a8a2.png
│   ├── 48318c1398d844a29940165c8f56e8ac.png
│   ├── 91a9a9c8900a43c18b4f84e71e702c75.png
│   ├── 949e4a3db15c4f2db1c1c0f8410ae38d.png
│   ├── aa311dbb245f42bf884374351ff336ba.png
│   ├── d0f78216da644fddb3be67459d86827f.png
│   ├── d7e677f076fe43d0b49e2df6463d8ec7.png
│   ├── d995468686e547dc9ea86ef7342fc506.png
│   └── e596671aeb28483d9facccbe22286623.png
└── tmp
├── 0490ff23787f12db22752281cf1e783c.css
├── 0e0bbcc8bdd6f998d40e7713def8228a.css
├── 5969ba3480f4296debea17c0689daf5f.css
├── a7043796e0413c96d5f16aa3394553ac.css
└── c6446da69e9e26701d8d96aac114a41b.css

One can then export this as Markdown again and obtains the following structure.

/tmp/export-test/
├── Promotion
│   ├── cA2.09.48 Stride Investigation.md
│   ├── Fit Ranges on cA2.09.48.md
│   └── Thermal State Removal for Three Pions.md
└── _resources
├── 0201cb0e79504a2eb2dbbe86a8c7e03f.png
├── 08b9967321044c568ac95a8b97e70162.png
├── 3c3bc0f3b07d42a8bc8f7c6baaeabcc8.png
├── 4588241bdd6746e5971f18c3b4c2a8a2.png
├── 48318c1398d844a29940165c8f56e8ac.png
├── 91a9a9c8900a43c18b4f84e71e702c75.png
├── 949e4a3db15c4f2db1c1c0f8410ae38d.png
├── aa311dbb245f42bf884374351ff336ba.png
├── d7e677f076fe43d0b49e2df6463d8ec7.png
└── d995468686e547dc9ea86ef7342fc506.png

This is something that one can work with, although the matching between the resources and the documents is not directly clear. This makes sense as a resource could be used in multiple documents and therefore this approach makes more sense if the notes are interpreted in a collected fashion. But one can also export just a single document and then the _resources directory only contains the ones that have been used. Otherwise one could parse the Markdown documents for the filenames that are included in image tags and take them from the resources directory.

PDF generation is not as nice as with Pandoc via LaTeX, but using the export to Markdown feature one could also generate the PDF via Pandoc. The image files compatible with HTML (JPEG, PNG) also properly show up, but PDF images do not show up in either editor or PDF export. To be fair, PDF images also do not work with GitHub Issues or every other Markdown editor. It just works with Pandoc export to LaTeX.

The math support is not full LaTeX. I sometimes use environments like multline which are not Markdown constructs but rather LaTeX that is passed through as-is when I compile the Markdown to LaTeX using Pandoc.

## Joplin vs. Files

I have a really hard time deciding whether I want to use Joplin or plain Markdown files for my notes. The integrated nature of Joplin makes it rather easy to have a repository of notes. Also I can just drag-and-drop my screenshot into the editor and have them automatically managed in the background, like GitHub Issues also does. This is more manual work with plain files.

However, the UNIX philosophy of having everything represented as plain text files also has its appeal. I can switch editors, track the notes individually in my backup snapshots, track them in git and collaborate on a single note. Joplin does support multiple note directories, but it encourages to keep a bunch of notes together in a notebook and possibly multiple notebooks in one directory. I would likely have all my dissertation notes in one thing.

There are certain long-lived documents like my diary. I don't want to submit that to some program which stores the data in a non-standard format. But my dissertation notes only have a half-life of a few weeks to months. Also they are not final documents, they are just notes. I thought that if I was using plain Markdown files for some of the documents, I could just use them for all my Markdown stuff.

The big issue is that I have little projects and they have some notes here and there. It does not make so much sense to have all the notes concentrated in one notebook and other files around elsewhere. I like to have all the project files in one directory. Therefore I think that I will stick with plain Markdown files for my notes and don't have to worry about them turning into fully fledged documents.


text:
# Edit input on previous pages of multipage FormFunction?

Posted 5 years ago
2774 Views
|
0 Replies
|
1 Total Likes
|
 A user moving through a multipage webform might have second thoughts or encounter information on later pages that causes them to want to go back and edit earlier pages. As discussed below, it probably isnt possible for a multipage FormFunction to automatically facilitate such editing unless it has a static layout. In the static layout case, the below code gives the FormFuncton user some access to editing previous page information by cumulatively adding fields for these inputs. Can anyone think of less restrictive conditions, simpler and/or alternative ways to accomplish multipage FormFunction editing?Default FormFunction editingMultiple clicks of the browser back button will allow the user to go back to any previous form page, but as each previous page opens any input that was previously entered will be gone. Furthermore, after going back to the page to be edited, appropriately re-entering the information, and clicking the FormFunction Next button, the user will have to re-enter all information on the page after the edited page, and so on for all subsequent pages.The example in the FormFunction > Examples > Scope > Multipage forms documentation section shows a multipage pure function formspec that programmatically sets the number of fields on second page equal to the integer input on the first page. The possible presence of such multipage dynamic layout would apparently make it difficult, if not impossible, for Mathematica to automatically support paging back and forth through a multipage form in a way that preserves all earlier inputs. However, if the multipage layout is completely static then multipage FormFunction editing should be possible.Simple static layout editingFor a static layout the number of fields (and their input types) on each page is preassigned rather than dependent on user input. But on each page it's still possible to make the user prompt, that is the field label, depend on all previous page inputs: CloudDeploy[ FormFunction[{ FormObject[{ {"A", "A. Given no prior input:"} -> "String"}, AppearanceRules -> <|"ItemLayout" -> "Vertical"|>], FormObject[{ {"A", "A."} -> <|"Interpreter" -> "String", "Input"->#A|>, {"B", "B. Given prior input " <> #A <> ":"} -> "String"}, AppearanceRules -> <|"ItemLayout" -> "Vertical"|>] &, FormObject[{ {"A", "A."} -> <|"Interpreter" -> "String", "Input" -> #A|>, {"B", "B."} -> <|"Interpreter" -> "String", "Input" -> #B|>, {"C", "C. Given prior input " <> #A <> ", " <> #B <> ":"} -> "String"}, AppearanceRules -> <|"ItemLayout" -> "Vertical"|>] &}, Identity], FileNameJoin[{\$CloudRootDirectory,"MultipageFormFunctionStaticLayoutEdit"}]] The first FormFunction page displays the field named A and the string a is entered. The second FormFunction page displays the field named B with a prompt that responds to the input from field A, the string b is entered, and the input for field A is edited to be aa. The third FormFunction page displays the field named C with a prompt that responds to the input from fields A and B, the string c is entered, and the inputs for fields A and B are edited to be aaa and bb. The final FormPage shows that the A, B, and C fields have been correctly assigned their input or last edited values.CommentThe FormFunction parser does not correctly handle a multipage formspec. For example, it presumably should be possible to put labels above fields instead of to their left with the FormFunction option: AppearanceRules -> <|"ItemLayout" -> "Vertical" |> This does not work correctly on the desktop and deployed to the cloud it returns an error. Fortunately theres a workaround, which is employed in the above code. Explicitly specify each FormObject and repetitively include the AppearanceRules option in each FormObject.


text:
# Does Charge Conjugation change the electromagnetic field?

• A
gjj
Is there a difference between the meaning of charge conjugation in Relativistic Quantum Mechanics and its meaning in Quantum Field Theory?

In chapter 4.7.5 of "Thomson Modern Particle Physics" the charge conjugation operator is derived without changing the electromagnetic field Aμ. This approach is also used in other books on relativistic quantum mechanics. Wachter "Relativistic Quantum Mechanics", for instance, defines an "Extended Charge Conjugation" that sets Aμ --> -Aμ, but that's in addition to the usual charge conjugation that makes no change to the fields.

On the other hand when I look at Wikipedia C-symmetry, the statement is made that under charge conjugation every charge is reversed and therefore so are the electromagnetic fields (Aμ --> -Aμ). Wikipedia says "the dynamics would preserve the same form" which I interpret to mean that the motion of the particle would be unaffected by charge conjugation since we've flipped both the charge and the field.

Is charge conjugation defined differently in relativistic quantum mechanics and quantum field theory?

Gold Member
2022 Award
I don't know, how one cannot make ##A^{\mu} \rightarrow -A^{\mu}## under Charge conjugation, if one describes standard electrodynamics, be it classical or quantum. After all electrodynamics is ##C##-invariant (it's also ##P## and ##T## invariant and thus also ##CP## invariant; it's of course ##CPT## invariant anyway, bcause of the Pauli-Lüders theorem). Checking some reasonable textbooks, that's also treated in this way: Weinberg, QT of Fields Vol. 1, Schwartz, QFT and the SM, Duncan, Conceptual framework of QFT, Itzykson/Zuber QFT.

I can imagine how some authors come to the wrong conclusion concerning the C operation on the em. field. This could happen easily when errorneously taking the socalled "relativistic quantum mechanics" (or "first-quantization approach") carelessly literally. Having then defined the C-symmetry operation of Dirac spinor fields (1st quantization!) in the usual way and applying it to the curren ##\bar{\psi} \gamma^{\mu} \psi## leads to the result that the current seems not to change under C and thus to keep C a symmetry of the pseudotheory where electrons and positrons are first-quantized and the electromagnetic field stays unquantized (which in fact very often is a good approximation in non-relativistic QT, the socaled semiclassical approximation), the em. field shouldn't change under C too.

That's of course against our intuition. After all, C is misnomed as "charge conjugation", because its proper definition is that any particle is exchanged by its anti-particle and an antiparticle should sign-flip all its charge-like quantum numbers, including electric charge. That's indeed what comes out of the only consistent relativistic quantum theory we have today, i.e., relativistic QFT! The Dirac field is necessarily to be quantized as fermions, because it's an half-integer field (##s=1/2##), and consequently the proper normal-ordered current operator flips sign under C as it must be. Consequently, to keep QED C-symmetric, also ##A^{\mu}## must flip sign under C. Taking C as charge conjugation, that's also clear from classical electrodynamics since if you flip the sign of all charges, this implies ##\rho \rightarrow -\rho## and ##\vec{j} \rightarrow -\vec{j}##. The em. field is given from these charge-current disribution by the retarded potentials (or Jefimenko equations to directly get the physical fields), which are linear in ##\rho## and ##\vec{j}## and thus also flip sign.

Also if you look on the very fundamental definition of electric charge and the electromagnetic field (in classical physics) via the action of the fields on a test charge, C invariance implies that the field must flip under the C transformation. If you'd only flip the sign of the charge, the Lorentz force ##\vec{F}=q \vec{E} + q \vec{v} \times \vec{B}## (in SI units) would flip its direction either, and you'd get a different trajectory of the charged particle starting with the same initial condition, which would mean C is not a symmetry of electrodynamics.

So there's no good reason, not to flip the em. field under C but it rather contradicts the very well established symmetry of the em. interaction under C. Only the weak interaction violates C (as well as P, C, and CP), as is now proven experimentally for all these types of discrete symmetries. So far, however, synmmetry under CPT still holds (within the accuracy of all experiments), keeping this beautiful prediction of relativistic local microcausal QFT valid.

gjj
Thank you for your answer. I am now clear that in QFT charge conjugation means flipping all the spins and thus also flipping the electric and magnetic fields. Unfortunately, I'm looking at the Feynman-Stueckelberg approach to QED which I realize is not the best approach to QED.

In your second paragraph (the one that starts with "I can imagine ...") you point out how some authors, using this RQM (Feynman-Stueckelberg) approach, could apply charge conjugation and not flip the E&M fields. The reasoning here, as I understand it, is that the charge conjugation operator is applied to a particular Dirac spinor (I think that's what you mean by "C-symmetry operation of Dirac spinor fields" ) rather than to all electrons. Since the electrons that create the electric and magnetic fields are left alone, so are the corresponding fields. This is what I thought those authors who explore the 1st quantization, RQM, Feynman-Stueckelberg approach (Bjorken and Drell, Greiner, Wachter) were doing and if I understand you (although you prefer QFT) this is also your opinion.

In the RQM, Feynman-Stueckelberg approach, the current remains the same after charge conjugation because the charge of the given electron flips as does its 3-momentum. You find this unintuitive, but it sounds something like saying that in a given electric field a positive charge going to the left is like negative charge going to the right.


text:
A square of side 80 cm ,had patterns in circles of diameter 15cm laid out each touching the other .Find the area of the square not

Question

A square of side 80 cm ,had patterns in circles of diameter 15cm laid out each touching the other .Find the area of the square not covered by the circles. plz give answer in fraction not in fraction

in progress 0
1 month 2021-08-16T05:50:00+00:00 2 Answers 0 views 0

1. Step-by-step explanation:

diameter =15

pattern in circle =22/7 (we know that)

therefore,

remaining area = 6400 -22/7×7.5×7.5cm

6223.21cm.

2. Step-by-step explanation:

The required remaining area is 6223.21cm.

Step-by-step explanation:

80× 80⇢ 6400cm

Diameter⇢ 15cm

π⇢22/7

Remaining area ⟹ 6400- 22/ 7

(7.5)^{2}(7.5)

2

Remaining area

⟹6400 − 722×(7.5)^2

6223.21cm

Hence, the required remaining area will be 6223.21cm


text:
# How can i call some function from my DLL?

## Recommended Posts

How can i call some function from my DLL ? lets say the name of the dll is Test.dll and the dll has this function: __declspec (dllexport) bool positive(int num) { if (num>0) return true; return false; } how can i call this function from my other project?

##### Share on other sites
You have to provide a header file along with the library and with that they can see what methods you have defined for your library.

Dave

##### Share on other sites
In this case, you have to include to the caller this header:

__declspec (dllimport) bool positive(int num);

##### Share on other sites
Quote:
It's worth noting that if you go for runtime linking (Which is what using LoadLibrary() and GetProcAddress() is called), then you'll need to export the function with an unmangled name, by using extern "C". E.g.:
extern "C" {__declspec (dllexport) bool positive(int num){   if (num>0)      return true;   return false;}}

##### Share on other sites
and what about classes? how can i make classes in a DLL ?
and how can i call them ?

##### Share on other sites
Quote:
 Original post by lord4nand what about classes? how can i make classes in a DLL ?and how can i call them ?
Using the header and library method again. It's difficult (Pretty much impossible, or at least not worth the effort) to dynamically bind a class. When you export a class, you're really only exporting all of the member functions.

If you create a Win32 DLL project in MSVC, and select "A DLL that exports some symbols", it'll show you an example of a DLL that exports a function, a variable and a class.

##### Share on other sites
ok i exported a class in my DLL
how can i import it into my project ?
THE CLASS IN THE DLL FILE:
class __declspec(dllexport) CJm {public:	CJm();	int Positive(int num); };

##### Share on other sites
Link your EXE to the .lib file your DLL project produced, and include the header file that class is in. You should be using import/export differently though, like how MSVC does:
// In CJm.h:#ifdef MYDLL_EXPORTS#   define MYDLL_EXPORT __declspec(dllexport)#else#   define MYDLL_EXPORT __declspec(dllimport)#endifclass MYDLL_EXPORT CJm {public:	CJm();	int Positive(int num); };

And then define MYDLL_EXPORTS in your DLL project's preprocessor settings. That ensures that when the DLL is built, the class is exported, and when anything else is built, the class is imported.

##### Share on other sites
EDIT:
Nevermind its working.
heres the working code:
#pragma comment( lib, "e:\\jm")class __declspec(dllimport) CJm {public:	CJm(void);};int main(int argc, char* argv[]){	CJm a;	return 0;}[/soruce]

## Create an account

Register a new account

• ### Forum Statistics

• Total Topics
627700
• Total Posts
2978690

• 20
• 14
• 12
• 10
• 12


text:
# How to use RFECV for feature selection and cross validation

I am still very new to machine learning and trying to figure things out myself. I am using SciKit learn and have a data set of tweets with around 20,000 features (n_features=20,000). So far I achieved a precision, recall and f1 score of around 79%. I would like to use RFECV for feature selection and improve the performance of my model. I have read the SciKit learn documentation but am still a bit confused on how to use RFECV.

This is the code I have so far:

from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.naive_bayes import MultinomialNB
from sklearn.cross_validation import StratifiedShuffleSplit
from sklearn.cross_validation import cross_val_score
from sklearn.feature_selection import RFECV
from sklearn import metrics

# cross validation
sss = StratifiedShuffleSplit(y, 5, test_size=0.2, random_state=42)
for train_index, test_index in sss:
docs_train, docs_test = X[train_index], X[test_index]
y_train, y_test = y[train_index], y[test_index]

# feature extraction
count_vect = CountVectorizer(stop_words='English', min_df=3, max_df=0.90, ngram_range=(1,3))
X_CV = count_vect.fit_transform(docs_train)

tfidf_transformer = TfidfTransformer()
X_tfidf = tfidf_transformer.fit_transform(X_CV)

# Create the RFECV object
nb = MultinomialNB(alpha=0.5)

# The "accuracy" scoring is proportional to the number of correct classifications
rfecv = RFECV(estimator=nb, step=1, cv=2, scoring='accuracy')

rfecv.fit(X_tfidf, y_train)
X_rfecv=rfecv.transform(X_tfidf)

print("Optimal number of features : %d" % rfecv.n_features_)

# train classifier
clf = MultinomialNB(alpha=0.5).fit(X_rfecv, y_train)

# test clf on test data

X_test_CV = count_vect.transform(docs_test)
X_test_tfidf = tfidf_transformer.transform(X_test_CV)
X_test_rfecv = rfecv.transform(X_test_tfidf)

y_predicted = clf.predict(X_test_rfecv)

#print the mean accuracy on the given test data and labels

print ("Classifier score is: %s " % rfecv.score(X_test_rfecv,y_test))

Three questions:

1) Is this the correct way to use cross validation and RFECV? I am especially interested to know if I am running any risk of overfitting.

2) The accuracy of my model before and after I implemented RFECV with the above code are almost the same (around 78-79%), which puzzles me. I would expect performance to improve by using RFECV. Anything I might have missed here or could do differently to improve the performance of my model?

3) What other feature selection methods could you recommend me to try? I have tried RFE and SelectKBest so far, but they both haven't given me any improvement in terms of model accuracy.

• Please spell out your acronyms. What is "RFECV"? Be aware the code check is off topic here. You may want to give a brief text summary of what your code does for people who don't use Python. – gung Aug 20 '15 at 5:16


text:
A computer program specifies a sequence of operations to be performed in order to accomplish some task. Often, the operations are deterministic: given a fixed input, the behavior of the program should always be the same for that input. Yet there are many problems for which an efficient and/or elegant solution can be obtained using randomization.

In a randomized program, some operations may be chosen randomly rather than deterministically according to the program’s input. Thus, different executions of the same program with the same input may give different behavior. While the potential unpredictability of randomized programs may seem at odds with program correctness and efficiency, we will see that for many randomized procedures it is possible to argue that undesireable outcomes are incredibly unlikely. In some cases, a randomized solution is so much simpler than a deterministic one that the slight chance of an undesireable outcome is overshadowed by the efficiency and simplicity of the randomized procedure.

The goal of this note is to introduce some of the basic concepts, vocabulary, and notation of probability. This material will serve as the foundation to reason about randomized procedures we will encounter going forward. For simplicity, we focus on discrete (finite) probability.

## Probability Spaces

Perhaps the most familiar examples of randomness we encounter in our everday lives occur in games of chance. In many games, randomness is achieved by rolling dice, flipping coins, or dealing cards from a shuffled deck. Randomness affords a game a level of unpredictability. Yet patterns emerge from these random processes: a coin flipped repeatedly will typically yield an approximately equal number of heads and tails; a poker-player is almost never dealt a royal flush in a game of five-card stud. Probability is the quantitative study of random processes. That is, probability seeks to quantify the likelihood of different outcomes of a random processes.

The basic object of study in probability is a probability space. A (finite) probability space consists of:

1. a sample space space $$\Omega = \{\omega_1, \omega_2, \ldots, \omega_n\}$$ whose elements are called outcomes, and

2. a probability measure $$P$$ that associates a real number $$P(\omega_i)$$—the probability of $$\omega_i$$ to each outome $$\omega_i$$ in $$\Omega$$ satisfying:

• $$0 \leq P(\omega_i) \leq 1$$ for all outcomes $$\omega_i$$, and
• $$P(\omega_1) + P(\omega_2) + \cdots + P(\omega_n) = 1$$.

Example 1. We model the randomness of tossing a (fair) coin. In this case, there are two possible outcomes of a coin toss: heads and tails. We take our sample space to be $$\Omega = \{\mathrm{H},\mathrm{T}\}$$. Since the result of a coin flip is equally likely to heads or tails, we have $$P(H)=P(T)=1/2$$.

Example 2. Rolling a standard (six-sided) die has six outcomes which are equally likely. Thus we take $$\Omega=\{1,2,3,4,5,6\}$$, and $$P(i) = 1/6$$ for $$i = 1,2,\ldots,6$$.

##### Events

An event $$A$$ is a set of outcomes. We can compute the probability that event $$A$$ occurs—denoted $$P(A)$$—by summing the probabilities of the different outcomes in $$A$$.

Example 3. Consider rolling a six-sided die, and let $$A$$ be the event that the outcome is at least $$4$$. That is, $$A = \{4, 5, 6\}$$. We can compute $$P(A)$$ to be the sum of the probabilities of these outcomes. Since there are 3 possible outcomes in $$A$$ and each occurs with probability $$1/6$$, we have $$P(A) = 1/6 + 1/6 + 1/6 = 1/2$$.

Example 4. Consider the process of rolling two dice. The first die can take any value from 1 to 6, and similarly with the second die. Thus, we can represent the outcome of a roll as a pair $$(i, j)$$ where $$i$$ is the outcome of the first die and $$j$$ is the outcome of the second. Thus, we have $$\Omega = \{(1, 1), (1,2), \ldots, (6, 6)\}$$. Note that there are 36 possible outcomes, and all are equally likely. Thus we have $$P((i, j)) = 1 / 36$$ for all outcomes. Consider the event $$A$$ that the values of the dice sum to $$7$$. Notice that $$A$$ contains $$6$$ outcomes: $$A = \{(1, 6), (2, 5), \ldots, (6, 1)\}$$. Thefore, we compute $$P(A) = 6 \cdot (1 / 36) = 1 / 6$$. Now consider the event $$B$$ that the values of the dice sum to $$8$$. Thus, $$B = \{(2, 6), (3, 5), (4, 4), (5, 3), (6, 2)\}$$. Since $$B$$ contains $$5$$ outcomes, each occurring with probability $$1 / 36$$, we have $$P(B) = 5 / 36$$.

Exercise 1. Consider the scenario described in Example 4. Consider the event $$C$$ that the values of the dice sum to at least $$10$$. What is $$P(C)$$?

## Random Variables

Given a probability space $$(\Omega, P)$$, a random variable $$X$$ is a function that associates a (real) numerical value to each outcome $$\omega$$ in $$\Omega$$.

Example 5. Going back to the coin toss example above, we can define a random variable $$X$$ on the coin toss probability space defined by $$C(\mathrm{H}) = 1$$ and $$X(\mathrm{T}) = -1$$. This random variable may arise as a simple game: two players toss a coin and bet on the outcome. If the outcome is heads, player 1 wins one dollar, while if the outcome is tails, player 1 loses one dollar.

Example 6. For the die rolling example, we can define the random variable $$Y$$ by $$Y(i) = i$$. The value of $$Y$$ is simply the value showing on die after it is rolled.

##### Expected Values

Given a random variable $$X$$ on a probability space $$(\Omega, P)$$, the expected value or average of $$X$$ is defined to be

$E(X) = X(\omega_1) P(\omega_1) + X(\omega_2) P(\omega_2) + \cdots + X(\omega_n) P(\omega_n).$

We can denote the expression above more succinctly using summation notation as

$E(X) = \sum_{i = 1}^n X(\omega_i) P(\omega_i).$

The expected value of a random variable quantifies the average value we expect to see in a random variable if we repeat an experiment (e.g. a coin flip or die roll) many times over.

Example 7. Going back to the coin flip example, we can compute

$E(X) = C(H) P(H) + C(T) P(T) = (1) \cdot \frac{1}{2} + (-1) \cdot \frac{1}{2} = 0.$

This tells us that if we repeatedly play the coin flip betting game described above, neither player has an advantage; The players expect to win about as much as they lose.

Example 8. For the die rolling example, we compute

$E(R) = R(1) P(1) + \cdots + R(6) P(1) = 1 \cdot \frac{1}{6} + \cdots + 6 \cdot \frac{1}{6} = 3.5.$

Thus an “average” die roll is $$3.5$$ (even though $$3.5$$ cannot be the outcome of a single die roll).

##### Probability Distributions

Often, when speaking about random variables we omit reference to the underlying probability space. In this case, we speak only of the probability that a random variable $$X$$ takes on various values. We refer to the set of possible values attained by $$X$$ together with their respective probabilities as the probability distribution of $$X$$. More formally, we can define the probability distribution of $$X$$ by

$f(x) = P(X = x).$

The function $$f$$ is known as the probability density function (or PDF) of $$X$$.

For the coin flipping example above, $$X$$ can be defined by the probability distribution

$P(X = 1) = P(X = -1) = 1/2,$

which gives rise to the PDF $$f(1) = f(-1) = 1 / 2$$.

Note that the PDF does not reference the underlying sample space $$\Omega$$. The danger in this view is that if we don’t explicitly define $$X$$ as a function on some probability space, it may make comparison of random variables difficult. To see an example of this, consider the random variable $$S$$ defined on the die roll sample space, $$\Omega = \{1,\ldots, 6\}$$ by

$S(i) = \begin{cases} 1 &\text{ if } i \text{ is even}\\ -1 &\text{ if } i \text{ is odd}. \end{cases}$

Notice that, like our variable $$X$$ defined for coin flips, we have $$P(S = 1) = P(S = -1) = 1/2$$, so in some sense $$X$$ and $$S$$ are “the same.” However, they are defined on different sample spaces: $$X$$ is defined on the sample space of coin flips, while $$S$$ is defined on the sample space of die rolls.

Consider a game where the play is determined by a coin flip and a die roll. For the examples above, the random variable $$X$$ depends only on the outcome of the coin flip, while $$Y$$ and $$S$$ depend only on the outcome of the die roll. Since the outcome of the coin flip has no effect on the outcome of the die roll, the variables $$X$$ and $$Y$$ are independent of one another, as are $$X$$ and $$S$$. However, $$Y$$ and $$S$$ depend on the same outcome (the die roll) so their values may depend on each other. In fact, the value of $$S$$ is completely determined by the value of $$Y$$! So knowing the value of $$Y$$ allows us to determine the value of $$S$$, and knowing the value of $$S$$ tells us something about the value of $$Y$$ (namely whether $$Y$$ is even or odd).

##### Independence

Definition. Suppose $$X$$ and $$Y$$ are random variables (or more generally, functions) defined on the same probability space, $$(\Omega, P)$$. We say that $$X$$ and $$Y$$ are independent if for all possible values $$x$$ of $$X$$ and $$y$$ of $$Y$$ we have

$P(X = x \text{ and } Y = y) = P(X = x) P(Y = y).$

For our examples above with the coin flip and the die roll, $$X$$ and $$Y$$ cannot be said to be independent because they are defined on different probability spaces. The variables $$Y$$ and $$S$$ are both defined on the die roll sample space, so they can be compared. However, they are not independent. For example, we have $$P(Y = 1) = 1/6$$ and $$P(S = 1) = 1/2$$. Since $$S(i) = 1$$ only when $$i$$ is even, we have

$P(Y = 1 \text{ and } S = 1) = 0 \neq \frac{1}{6} \cdot \frac{1}{2}.$

Let $$W$$ be the random variable on the die roll sample space defined by

$W(i) = \begin{cases} 1 & \text{ if } i = 1, 4\\ 2 & \text{ if } i = 2, 5\\ 3 & \text{ if } i = 3, 6. \end{cases}$

We claim that $$W$$ and $$S$$ are independent. This can be verified by brute force calculation. For example, note that we have $$S = 1$$ and $$W = 1$$ only when the outcome of the die roll is 4. Therefore,

$P(S = 1 \text{ and } W = 1) = \frac{1}{6} = P(S = 1) P(W = 1).$

Similar calculations show that similar equalities hold for all possible values of $$S$$ and $$W$$, hence these random variables are independent.

##### Linearity of Expectation

Given two random variables $$X$$ and $$Y$$ defined on the same probability space, we can define their sum $$X + Y$$ and product $$X Y$$.

Proposition. Suppose $$X$$ and $$Y$$ are random variables on the probability space $$(\Omega, P)$$. Then

$E(X + Y) = E(X) + E(Y) \quad\text{and}\quad E(X Y) = E(X) E(Y).$

Proof. For the first equality, by definition we compute

$E(X + Y) = \sum_{x, y} P(X = x \text{ and } Y = y) (x + y).$

Using the fact that $$X$$ and $$Y$$ are independent, we find

\begin{align*} E(X + Y) &= \sum_{x, y} P(X = x \text{ and } Y = y) (x + y)\\ &= \sum_{x, y} P(X = x) P(Y = y) (x + y)\\ &= \sum_{x} P(X = x) x \sum_y P(Y = y) + \sum_y P(Y = y) y \sum_x P(X = x)\\ &= \sum_x P(X = x) x + \sum_y P(Y = y) y\\ &= E(X) + E(Y). \end{align*}

The fourth equality holds because $$P$$ satisfies $$\sum_x P(X = x) = 1$$ and $$\sum_y P(Y = y) = 1$$. Similarly, we compute

\begin{align*} E(X Y) &= \sum_{x, y} P(X = x \text{ and } Y = y) x y\\ &= \sum_{x, y} P(X = x) P(Y = y) x y\\ &= \left(\sum_{x} P(X = x) x\right) \left(\sum_{y} P(Y = y) y\right)\\ &= E(X) E(Y). \end{align*}

These equations give the desired results. $$\Box$$

The equation $$E(X + Y) = E(X) + E(Y)$$ is satisfied even if $$X$$ and $$Y$$ are not independent. This fundamental fact about probability is known as the linearity of expectation. However, in order to have $$E(X Y) = E(X) E(Y)$$, $$X$$ and $$Y$$ must be independent.

Exercise. Prove that $$E(X + Y) = E(X) + E(Y)$$ without assuming that $$X$$ and $$Y$$ are independent.

Exercise. Give an example of random variables $$X$$ and $$Y$$ for which $$E(X Y) \neq E(X) E(Y)$$. (Note that $$X$$ and $$Y$$ cannot be independent.


text:
# A car dealership is trying to determine how much to spend on advertising during the upcoming...

## Question:

A car dealership is trying to determine how much to spend on advertising during the upcoming fiscal year.

Let {eq}N(x) {/eq} be the expected number of cars that will be sold during the year if the dealer spends {eq}x {/eq} thousand dollars on advertising. Market research indicates annual sales will change at a rate of

{eq}\displaystyle\; N'(x) = \frac{30}{\sqrt{1 + 0.2x}} {/eq}

during the upcoming fiscal year.

(a) Determine the expected increase in sales if the annual advertising budget is increased from {eq}$40\textrm{,}000 {/eq} to {eq}$45\textrm{,}000 {/eq}.

(b) Determine the expected increase in sales if the annual advertising budget is increased from {eq}$50\textrm{,}000 {/eq} to {eq}$55\textrm{,}000 {/eq}.

(c) In which of (a) or (b) does the {eq}$5\textrm{,}000 {/eq} increase in annual advertising expenditures lead to a greater increase in auto sales? Explain. (d) Use what you learned from (a) through (c) to determine whether {eq}N(x) {/eq} is concave up or concave down and explain your reasoning. ## Finding Increase in Sales Upon Increasing Advertising Budget The rate of change of sales in a car dealership is given as an explicit function of the number of dollars, in thousands, spent by the car dealership in advertising. Using a definite integral that uses the Fundamental Theorem of Calculus to evaluate, we find the increase in the sales of cars when the advertising amount is increased from a given quantity to another. Then using the same concept we find the increase in car sales for another different increase in the advertising budget. ## Answer and Explanation: (a) The increase in sales in this part will be given by the following definite integral: {eq}\displaystyle Increase = N(45)-N(40)=\int_{40}^{45} N'(x) \; dx = \int_{40}^{45} \frac {30}{\sqrt {1+0.2x}} \; dx \qquad (1) {/eq} The integral in (1) above is evaluated as follows: {eq}\displaystyle \int_{40}^{45} \frac {30}{\sqrt {1+0.2x}} \; dx = \left[ \frac {30}{0.2} \; \frac {(1+0.2x)^{-1/2+1}}{-1/2+1} \right]_{40}^{45} = 300 \left[ (1+0.2(45))^{1/2}-(1+0.2(40))^{1/2} \right] = 48.69 \approx 49. {/eq} The increase in the numbers of sales of cars here is about 49. (b) Just like in part (a), {eq}\displaystyle Increase = N(55)-N(50)=\int_{50}^{55} N'(x) \; dx = \int_{50}^{55} \frac {30}{\sqrt {1+0.2x}} \; dx \qquad (2) {/eq} The integral in (2) above is evaluated as follows: {eq}\displaystyle \int_{50}^{55} \frac {30}{\sqrt {1+0.2x}} \; dx = \left[ \frac {30}{0.2} \; \frac {(1+0.2x)^{-1/2+1}}{-1/2+1} \right]_{50}^{55} = 300 \left[ (1+0.2(55))^{1/2}-(1+0.2(50))^{1/2} \right] = 44.24 \approx 44. {/eq} The increase in the numbers of sales of cars here is about 44. (c) In part (a) there is a greater increase in the number of cars sold when the advertising amount is increased from$40,000 to \$45,000.

(d) It is concave down since the amount of change in the value of N(x) is decreasing as the value of x gets bigger. That means the derivative of N(x) or N'(x) is decreasing with x increasing. This implies the second derivative is negative which indicates downwards concavity. Eventually the change will become zero.