text:
## CryptoDB

### Daniel Escudero

#### Publications

Year
Venue
Title
2021
CRYPTO
We construct the first efficient MPC protocol that only requires black-box access to a non-commutative ring $R$. Previous results in the same setting were efficient only either for a constant number of corruptions or when computing branching programs and formulas. Our techniques are based on a generalization of Shamir's secret sharing to non-commutative rings, which we derive from the work on Reed Solomon codes by Quintin, Barbier and Chabot (\textit{IEEE Transactions on Information Theory, 2013}). When the center of the ring contains a set $A = \{\alpha_0, \ldots, \alpha_n\}$ such that $\forall i \neq j, \alpha_i - \alpha_j \in R^*$, the resulting secret sharing scheme is strongly multiplicative and we can generalize existing constructions over finite fields without much trouble. Most of our work is devoted to the case where the elements of $A$ do not commute with all of $R$, but they just commute with each other. For such rings, the secret sharing scheme cannot be linear on both sides" and furthermore it is not multiplicative. Nevertheless, we are still able to build MPC protocols with a concretely efficient online phase and black-box access to $R$. As an example we consider the ring $\mathcal{M}_{m\times m}(\mathbb{Z}/2^k\mathbb{Z})$, for which when $m > \log(n+1)$, \enote{maybe adapt/simplify the following claim as the comparison requires some nuances} we obtain protocols that require around $\lceil\log(n+1)\rceil/2$ less communication and $2\lceil\log(n+1)\rceil$ less computation than the state of the art protocol based on Circuit Amortization Friendly Encodings (Dalskov, Lee and Soria-Vazquez, \textit{ASIACRYPT 2020}). In this setting with a less commutative" $A$, our black-box preprocessing phase has a less practical complexity of $\poly(n)$. Due to this, we additionally provide specialized, concretely efficient preprocessing protocols for $R = \mathcal{M}_{m\times m}(\mathbb{Z}/2^k\mathbb{Z})$ that exploit the structure of the matrix ring.
2021
ASIACRYPT
In 2016, Guruswami and Wootters showed Shamir's secret-sharing scheme defined over an extension field has a regenerating property. Namely, we can compress each share to an element of the base field by applying a linear form, such that the secret is determined by a linear combination of the compressed shares. Immediately it seemed like an application to improve the complexity of unconditionally secure multiparty computation must be imminent; however, thus far, no result has been published. We present the first application of regenerating codes to MPC, and show that its utility lies in reducing the number of rounds. Concretely, we present a protocol that obliviously evaluates a depth-$d$ arithmetic circuit in $d + O(1)$ rounds, in the amortized setting of parallel evaluations, with $o(n^2)$ ring elements communicated per multiplication. Our protocol makes use of function-dependent preprocessing, and is secure against the maximal adversary corrupting $t < n/2$ parties. All existing approaches in this setting have complexity $\Omega(n^2)$. Moreover, we extend some of the theory on regenerating codes to Galois rings. It was already known that the repair property of MDS codes over fields can be fully characterized in terms of its dual code. We show this characterization extends to linear codes over Galois rings, and use it to show the result of Guruswami and Wootters also holds true for Shamir's scheme over Galois rings.
2021
TCC
In this work we consider information-theoretically secure MPC against an \emph{mixed} adversary who can corrupt $t_p$ parties passively, $t_a$ parties actively, and can make $t_f$ parties fail-stop. With perfect security, it is known that every function can be computed securely if and only if $3t_a + 2t_p + t_f < n$, for statistical security the bound is $2t_a + 2t_p + t_f < n$. These results say that for each given set of parameters $(t_a, t_p, t_f)$ respecting the inequality, there exists a protocol secure against this particular choice of corruption thresholds. In this work we consider a \emph{dynamic} adversary. Here, the goal is a \emph{single} protocol that is secure, no matter which set of corruption thresholds $(t_a, t_p, t_f)$ from a certain class is chosen by the adversary. A dynamic adversary can choose a corruption strategy after seeing the protocol and so is much stronger than a standard adversary. Dynamically secure protocols have been considered before for computational security. Also the information theoretic case has been studied, but only considering non-threshold adversaries, leading to inefficient protocols. We consider threshold dynamic adversaries and information theoretic security. For statistical security we show that efficient dynamic secure function evaluation (SFE) is possible if and only if $2t_a + 2t_p + t_f < n$, but any dynamically secure protocol must use $\Omega(n)$ rounds, even if only fairness is required. Further, general reactive MPC is possible if we assume in addition that $2t_a+2t_f \leq n$, but fair reactive MPC only requires $2t_a + 2t_p + t_f < n$. For perfect security we show that both dynamic SFE and verifiable secret sharing (VSS) are impossible if we only assume $3t_a + 2t_p + t_f < n$ and remain impossible even if we also assume $t_f=0$. In fact even SFE with security with abort is impossible in this case. On the other hand, perfect dynamic SFE with guaranteed output delivery (G.O.D.) is possible when either $t_p = 0$ or $t_a = 0$ i.e. if instead we assume $3t_a+t_f < n$ or $2t_p +t_f < n$. Further, perfect dynamic VSS with G.O.D. is possible under the stronger conditions $3t_a + 3/2t_f \leq n$ or $2t_p + 2t_f \leq n$. These conditions are also sufficient for perfect reactive MPC. On the other hand, because perfect fair VSS only requires $3t_a+2t_p+t_f< n$, perfect reactive MPC is possible whenever perfect SFE is.
2020
CRYPTO
This work introduces novel techniques to improve the translation between arithmetic and binary data types in multi-party computation. To this end, we introduce a new approach to performing these conversions, using what we call \emph{extended doubly-authenticated bits} (edaBits), which correspond to shared integers in the arithmetic domain whose bit decomposition is shared in the binary domain. These can be used to considerably increase the efficiency of non-linear operations such as truncation, secure comparison and bit-decomposition. Our eDaBits are similar to the \emph{daBits} technique introduced by Rotaru et al.~(Indocrypt 2019). However, our main observations are that (1) applications that benefit from daBits can also benefit from edaBits in the same way, and (2) we can generate edaBits directly in a much more efficeint way than computing them directly from a set of DaBits. Technically, the second contribution is much more challenging, and involves a novel cut and choose technique that may be of independent interest, and requires taking advantage of natural tamper-resilient properties of binary circuits that occur in our construction to obtain the best level of efficiency. Finally, we show how our eDaBits can be applied to efficiently implement various non-linear protocols of interest, and we thoroughly analyze their correctness for both signed and unsigned integers. The results of this work can be applied to any corruption threshold, although they seem best suited to dishonest majority protocols such as SPDZ. We implement and benchmark our constructions, and experimentally verify that our technique yield a substantial increase in effiency. Our eDaBits save in communication by a factor that lies between $2$ and $170$ for secure comparisons with respect to a purely arithmetic approach, and between $2$ and $60$ with respect to using daBits. Improvements in throughput per second are more subdued but still as high as a factor of $47$. We also apply our novel machinery to the tasks of biometric matching and convolutional neural networks, obtaining a noticeable improvement as well.
2020
ASIACRYPT
We study information-theoretic multiparty computation (MPC) protocols over rings Z/p^k Z that have good asymptotic communication complexity for a large number of players. An important ingredient for such protocols is arithmetic secret sharing, i.e., linear secret-sharing schemes with multiplicative properties. The standard way to obtain these over fields is with a family of linear codes C, such that C, $C^\perp$ and C^2 are asymptotically good (strongly multiplicative). For our purposes here it suffices if the square code C^2 is not the whole space, i.e., has codimension at least 1 (multiplicative). Our approach is to lift such a family of codes defined over a finite field F to a Galois ring, which is a local ring that has F as its residue field and that contains Z/p^k Z as a subring, and thus enables arithmetic that is compatible with both structures. Although arbitrary lifts preserve the distance and dual distance of a code, as we demonstrate with a counterexample, the multiplicative property is not preserved. We work around this issue by showing a dedicated lift that preserves \emph{self-orthogonality} (as well as distance and dual distance), for p > 2. Self-orthogonal codes are multiplicative, therefore we can use existing results of asymptotically good self-dual codes over fields to obtain arithmetic secret sharing over Galois rings. For p = 2 we obtain multiplicativity by using existing techniques of secret-sharing using both C and $C^\perp$, incurring a constant overhead. As a result, we obtain asymptotically good arithmetic secret-sharing schemes over Galois rings. With these schemes in hand, we extend existing field-based MPC protocols to obtain MPC over Z/p^k Z, in the setting of a submaximal adversary corrupting less than a fraction 1/2 - \varepsilon of the players, where \varepsilon > 0 is arbitrarily small. We consider 3 different corruption models, and obtain O(n) bits communicated per multiplication for both passive security and active security with abort. For full security with guaranteed output delivery we use a preprocessing model and get O(n) bits per multiplication in the online phase and O(n log n) bits per multiplication in the offline phase. Thus, we obtain true linear bit complexities, without the common assumption that the ring size depends on the number of players.
2019
TCC
At CRYPTO 2018, Cramer et al. introduced a secret-sharing based protocol called SPD$\mathbb {Z}_{2^k}$ that allows for secure multiparty computation (MPC) in the dishonest majority setting over the ring of integers modulo $2^k$, thus solving a long-standing open question in MPC about secure computation over rings in this setting. In this paper we study this problem in the information-theoretic scenario. More specifically, we ask the following question: Can we obtain information-theoretic MPC protocols that work over rings with comparable efficiency to corresponding protocols over fields? We answer this question in the affirmative by presenting an efficient protocol for robust Secure Multiparty Computation over $\mathbb {Z}/p^{k}\mathbb {Z}$ (for any prime p and positive integer k) that is perfectly secure against active adversaries corrupting a fraction of at most 1/3 players, and a robust protocol that is statistically secure against an active adversary corrupting a fraction of at most 1/2 players.
2018
CRYPTO
Most multi-party computation protocols allow secure computation of arithmetic circuits over a finite field, such as the integers modulo a prime. In the more natural setting of integer computations modulo $2^{k}$, which are useful for simplifying implementations and applications, no solutions with active security are known unless the majority of the participants are honest.We present a new scheme for information-theoretic MACs that are homomorphic modulo $2^k$, and are as efficient as the well-known standard solutions that are homomorphic over fields. We apply this to construct an MPC protocol for dishonest majority in the preprocessing model that has efficiency comparable to the well-known SPDZ protocol (Damgård et al., CRYPTO 2012), with operations modulo $2^k$ instead of over a field. We also construct a matching preprocessing protocol based on oblivious transfer, which is in the style of the MASCOT protocol (Keller et al., CCS 2016) and almost as efficient.


text:
Outlook: AUCKLAND INTERNATIONAL AIRPORT LIMITED is assigned short-term Ba1 & long-term Ba1 estimated rating.
Dominant Strategy : Sell
Time series to forecast n: 10 Jan 2023 for (n+1 year)
Methodology : Statistical Inference (ML)

## Abstract

AUCKLAND INTERNATIONAL AIRPORT LIMITED prediction model is evaluated with Statistical Inference (ML) and Stepwise Regression1,2,3,4 and it is concluded that the AIA stock is predictable in the short/long term. According to price forecasts for (n+1 year) period, the dominant strategy among neural network is: Sell

## Key Points

1. Technical Analysis with Algorithmic Trading
2. Market Outlook
3. Is it better to buy and sell or hold?

## AIA Target Price Prediction Modeling Methodology

We consider AUCKLAND INTERNATIONAL AIRPORT LIMITED Decision Process with Statistical Inference (ML) where A is the set of discrete actions of AIA stock holders, F is the set of discrete states, P : S × F × S → R is the transition probability distribution, R : S × F → R is the reaction function, and γ ∈ [0, 1] is a move factor for expectation.1,2,3,4

F(Stepwise Regression)5,6,7= $\begin{array}{cccc}{p}_{a1}& {p}_{a2}& \dots & {p}_{1n}\\ & ⋮\\ {p}_{j1}& {p}_{j2}& \dots & {p}_{jn}\\ & ⋮\\ {p}_{k1}& {p}_{k2}& \dots & {p}_{kn}\\ & ⋮\\ {p}_{n1}& {p}_{n2}& \dots & {p}_{nn}\end{array}$ X R(Statistical Inference (ML)) X S(n):→ (n+1 year) $\begin{array}{l}\int {r}^{s}\mathrm{rs}\end{array}$

n:Time series to forecast

p:Price signals of AIA stock

j:Nash equilibria (Neural Network)

k:Dominated move

a:Best response for target price

For further technical information as per how our model work we invite you to visit the article below:

How do AC Investment Research machine learning (predictive) algorithms actually work?

## AIA Stock Forecast (Buy or Sell) for (n+1 year)

Sample Set: Neural Network
Stock/Index: AIA AUCKLAND INTERNATIONAL AIRPORT LIMITED
Time series to forecast n: 10 Jan 2023 for (n+1 year)

According to price forecasts for (n+1 year) period, the dominant strategy among neural network is: Sell

X axis: *Likelihood% (The higher the percentage value, the more likely the event will occur.)

Y axis: *Potential Impact% (The higher the percentage value, the more likely the price will deviate.)

Z axis (Grey to Black): *Technical Analysis%

## IFRS Reconciliation Adjustments for AUCKLAND INTERNATIONAL AIRPORT LIMITED

1. The fair value of a financial instrument at initial recognition is normally the transaction price (ie the fair value of the consideration given or received, see also paragraph B5.1.2A and IFRS 13). However, if part of the consideration given or received is for something other than the financial instrument, an entity shall measure the fair value of the financial instrument. For example, the fair value of a long-term loan or receivable that carries no interest can be measured as the present value of all future cash receipts discounted using the prevailing market rate(s) of interest for a similar instrument (similar as to currency, term, type of interest rate and other factors) with a similar credit rating. Any additional amount lent is an expense or a reduction of income unless it qualifies for recognition as some other type of asset.
2. An entity shall assess at the inception of the hedging relationship, and on an ongoing basis, whether a hedging relationship meets the hedge effectiveness requirements. At a minimum, an entity shall perform the ongoing assessment at each reporting date or upon a significant change in the circumstances affecting the hedge effectiveness requirements, whichever comes first. The assessment relates to expectations about hedge effectiveness and is therefore only forward-looking.
3. An entity shall assess separately whether each subgroup meets the requirements in paragraph 6.6.1 to be an eligible hedged item. If any subgroup fails to meet the requirements in paragraph 6.6.1, the entity shall discontinue hedge accounting prospectively for the hedging relationship in its entirety. An entity also shall apply the requirements in paragraphs 6.5.8 and 6.5.11 to account for ineffectiveness related to the hedging relationship in its entirety.
4. An alternative benchmark rate designated as a non-contractually specified risk component that is not separately identifiable (see paragraphs 6.3.7(a) and B6.3.8) at the date it is designated shall be deemed to have met that requirement at that date, if, and only if, the entity reasonably expects the alternative benchmark rate will be separately identifiable within 24 months. The 24-month period applies to each alternative benchmark rate separately and starts from the date the entity designates the alternative benchmark rate as a non-contractually specified risk component for the first time (ie the 24- month period applies on a rate-by-rate basis).

*International Financial Reporting Standards (IFRS) adjustment process involves reviewing the company's financial statements and identifying any differences between the company's current accounting practices and the requirements of the IFRS. If there are any such differences, neural network makes adjustments to financial statements to bring them into compliance with the IFRS.

## Conclusions

AUCKLAND INTERNATIONAL AIRPORT LIMITED is assigned short-term Ba1 & long-term Ba1 estimated rating. AUCKLAND INTERNATIONAL AIRPORT LIMITED prediction model is evaluated with Statistical Inference (ML) and Stepwise Regression1,2,3,4 and it is concluded that the AIA stock is predictable in the short/long term. According to price forecasts for (n+1 year) period, the dominant strategy among neural network is: Sell

### AIA AUCKLAND INTERNATIONAL AIRPORT LIMITED Financial Analysis*

Rating Short-Term Long-Term Senior
Outlook*Ba1Ba1
Income StatementBaa2C
Balance SheetBaa2Baa2
Leverage RatiosBaa2Ba3
Cash FlowBaa2Baa2
Rates of Return and ProfitabilityCaa2Caa2

*Financial analysis is the process of evaluating a company's financial performance and position by neural network. It involves reviewing the company's financial statements, including the balance sheet, income statement, and cash flow statement, as well as other financial reports and documents.
How does neural network examine financial reports and understand financial state of the company?

### Prediction Confidence Score

Trust metric by Neural Network: 77 out of 100 with 513 signals.

## References

1. S. Bhatnagar, H. Prasad, and L. Prashanth. Stochastic recursive algorithms for optimization, volume 434. Springer, 2013
2. Y. Le Tallec. Robust, risk-sensitive, and data-driven control of Markov decision processes. PhD thesis, Massachusetts Institute of Technology, 2007.
3. Schapire RE, Freund Y. 2012. Boosting: Foundations and Algorithms. Cambridge, MA: MIT Press
4. Van der Vaart AW. 2000. Asymptotic Statistics. Cambridge, UK: Cambridge Univ. Press
5. C. Wu and Y. Lin. Minimizing risk models in Markov decision processes with policies depending on target values. Journal of Mathematical Analysis and Applications, 231(1):47–67, 1999
6. Pennington J, Socher R, Manning CD. 2014. GloVe: global vectors for word representation. In Proceedings of the 2014 Conference on Empirical Methods on Natural Language Processing, pp. 1532–43. New York: Assoc. Comput. Linguist.
7. Bastani H, Bayati M. 2015. Online decision-making with high-dimensional covariates. Work. Pap., Univ. Penn./ Stanford Grad. School Bus., Philadelphia/Stanford, CA
Frequently Asked QuestionsQ: What is the prediction methodology for AIA stock?
A: AIA stock prediction methodology: We evaluate the prediction models Statistical Inference (ML) and Stepwise Regression
Q: Is AIA stock a buy or sell?
A: The dominant strategy among neural network is to Sell AIA Stock.
Q: Is AUCKLAND INTERNATIONAL AIRPORT LIMITED stock a good investment?
A: The consensus rating for AUCKLAND INTERNATIONAL AIRPORT LIMITED is Sell and is assigned short-term Ba1 & long-term Ba1 estimated rating.
Q: What is the consensus rating of AIA stock?
A: The consensus rating for AIA is Sell.
Q: What is the prediction period for AIA stock?
A: The prediction period for AIA is (n+1 year)

## People also ask

What are the top stocks to invest in right now?

format: plain


text:
# zbMATH — the first resource for mathematics

Convergence of the finite element method applied to an anisotropic phase-field model. (English) Zbl 1155.74404
Summary: We formulate a finite element method for the computation of solutions to an anisotropic phase-field model for a binary alloy. Convergence is proved in the $$H^1$$-norm. The convergence result holds for anisotropy below a certain threshold value. We present some numerical experiments verifying the theoretical results. For anisotropy below the threshold value we observe optimal order convergence, whereas in the case where the anisotropy is strong the numerical solution to the phase-field equation does not converge.

##### MSC:
 74S05 Finite element methods applied to problems in solid mechanics 74E10 Anisotropy in solid mechanics 65M60 Finite element, Rayleigh-Ritz and Galerkin methods for initial value and initial-boundary value problems involving PDEs 65M12 Stability and convergence of numerical methods for initial value and initial-boundary value problems involving PDEs 65M15 Error bounds for initial value and initial-boundary value problems involving PDEs
ALBERT
Full Text:
##### References:
 [1] Burman, E.; Rappaz, J., Existence of solutions to an anisotropic phase-field model, Math. Methods Appl. Sci., 26, 13, 1137-1160, (2003) · Zbl 1032.35053 [2] Chen, X.; Elliott, C. M.; Gardiner, A.; Zhao, J. J., Convergence of numerical solutions to the Allen-Cahn equation, Appl. Anal., 69, 1-2, 47-56, (1998) · Zbl 0992.65096 [3] Chen, Z.; Hoffmann, K.-H., An error estimate for a finite-element scheme for a phase field model, IMA J. Numer. Anal., 14, 2, 243-255, (1994) · Zbl 0801.65091 [4] Dacorogna, B., Direct methods in the calculus of variations, 78, (1989), Springer-Verlag, Berlin · Zbl 0703.49001 [5] Feng, X.; Prohl, A., Analysis of a fully discrete finite element method for the phase field model and approximation of its sharp interface limits, Math. Comp., 73, 246, 541-567 (electronic), (2004) · Zbl 1115.76049 [6] Kessler, D., Modeling, mathematical and numerical study of a solutal phase-field model, (2001) [7] Kessler, D.; Krüger, O.; Scheid, J. F., Modeling, mathematical and numerical study of a solutal phase-field model, (1998) [8] Kessler, D.; Scheid, J.-F., A priori error estimates of a finite-element method for an isothermal phase-field model related to the solidification process of a binary alloy, IMA J. Numer. Anal., 22, 2, 281-305, (2002) · Zbl 1001.76057 [9] Kobayashi, R., A numerical approach to three-dimensional dendritic solidification, Experiment. Math., 3, 1, 59-81, (1994) · Zbl 0811.65126 [10] Rappaz, J.; Scheid, J. F., Existence of solutions to a phase-field model for the isothermal solidification process of a binary alloy, Math. Methods Appl. Sci., 23, 6, 491-513, (2000) · Zbl 0964.35026 [11] Schmidt, A.; Siebert, K. G., ALBERT—software for scientific computations and applications, Acta Math. Univ. Comenian. (N.S.), 70, 1, 105-122, (2000) · Zbl 0993.65134 [12] Warren, J. A.; Boettinger, W. J., Prediction of dendritic growth and microsegregation patterns in a binary alloy using the phase-field model, Acta Metall., 43, 689-703, (1995)
This reference list is based on information provided by the publisher or from digital mathematics libraries. Its items are heuristically matched to zbMATH identifiers and may contain data conversion errors. It attempts to reflect the references listed in the original paper as accurately as possible without claiming the completeness or perfect precision of the matching.


text:
# Unity - Renderer "raycasts" from top down?

I'm trying to have objects in a game be selectable only from a top down orthographic camera view. I think having physics colliders might be overkill for that - especially because this only needs to be in 2D and not 3D. Is there another method that might be better, such as something like a renderer "raycasts", but perhaps even more performant as it is just from the orthographic 2D top down view

If you build your "top down" view on the XY plane, you can use 2D colliders and Physics2D.OverlapPoint.

This is about as efficient as you will get. A 2D collider is using exactly the same math you'd need to write in your C# code to test for a hit anyway. And if you're using Kinematic bodies on a physics layer that doesn't interact with anything, they won't burn any cycles on unneeded collision detection and resolution.

• is there a way to automatically create 2D colliders from the top down for 3D meshes?
– ina
Dec 18 '20 at 1:16
• You could write a script to do it reasonably easily. Project all the triangles and make a polygon collider out of their perimeter. Dec 18 '20 at 1:19
• Or you could use GetComponent<Renderer>().bounds which gets you the bounding box of the object as its used for culling calculations and create a BoxCollider2D out of it. Dec 18 '20 at 9:12

you can use quadtree algorithm to detect which object under the mouse position

you can use octree algorithm in 3d space

• Why would you do that when Unity already provides that for you? Dec 18 '20 at 9:10
• some people like inventing the sledgehammer even though it is now commodity that's basically free
– ina
Dec 18 '20 at 23:51
• Some times you dont need whole physics features with heavy calculations Dec 19 '20 at 22:14
• Im using ECS and i had to use this algorithm for nearby object detection Dec 19 '20 at 22:15


text:
# Real Sequence As Rational Function in e^-jw

1. Feb 15, 2005

### dduardo

Staff Emeritus
How do I convert a piece wise function like this:

y[n]=

{1 -N<=n<=N
{0 otherwise

to something like this:

p0+p1e^(-jw)+...+pMe^(-jwM)
------------------------------
d0+d1e^(-jw)+...+dNe^(-jwN)

Basically, what formula do I need to use to calculate the coeffients?

 I'm trying to use the matlab function FREQZ, but requires the formula to be in the above format.

Last edited: Feb 15, 2005
2. Feb 15, 2005

### learningphysics

Well, that looks the frequency response of a discrete time system.

I might be wrong, but I'd first get the z-transform of your sequence:

z^N + z^(N-1) + z^(N-2) + .....+ 1 + z^(-1) + z^(-2) + ....z^(-(N-1))+z^(-N)

then plug in z=e^(jwdt)

dt is the time between samples.

e^(jwdtN) + e^(jwdt(N-1)) + .....+ 1 + e^(-jwdt) + e(-jwdt2) + .... e^(-jwdtN)

So that would be your numerator, and the denominator is just 1. Is that form acceptable?

Last edited: Feb 15, 2005


text:
# Comparison of Some Exact and Perturbative Results for a Supersymmetric SU($N_c$) Gauge Theory

Bidragets oversatte titel: Comparison of Some Exact and Perturbative Results for a Supersymmetric SU($N_c$) Gauge Theory

Thomas Ryttov, Robert Shrock

Publikation: Bidrag til tidsskriftTidsskriftartikelForskningpeer review

## Abstrakt

We consider vectorial, asymptotically free ${\cal N}=1$ supersymmetric SU($N_c$) gauge theories with $N_f$ copies of massless chiral super fields in various representations and study how perturbative predictions for the lower boundary of the infrared conformal phase, as a function of $N_f$, compare with exact results. We make use of two-loop and three-loop calculations of the beta function and anomalous dimension of the quadratic chiral super field operator product for this purpose. The specific chiral superfield contents that we consider are $N_f$ copies of (i) $F+\bar F$, (ii) $Adj$, (iii) $S_2+\bar S_2$, and (iv) $A_2 + \bar A_2$, where $F$, $Adj$, $S_2$, and $A_2$ denote, respectively, the fundamental, adjoint, and symmetric and antisymmetric rank-2 tensor representations. We find that perturbative results slightly overestimate the value of $N_{f,cr}$ relative to the respective exact results for these representations, i.e., slightly underestimate the interval in $N_f$ for which the theory has infrared conformal behavior. Our results provide a measure of how closely perturbative calculations reproduce exact results for these theories.
Bidragets oversatte titel Comparison of Some Exact and Perturbative Results for a Supersymmetric SU($N_c$) Gauge Theory Engelsk Physical Review D 2470-0010 https://doi.org/10.1103/PhysRevD.85.076009 Udgivet - 2012

### Bibliografisk note

16 pages, 3 figures


text:
# Show that the series converges. \sum_{n=1}^\infty\frac{n!^n}{n^{n^2}}

Show that the series converges.
$\sum _{n=1}^{\mathrm{\infty }}\frac{n{!}^{n}}{{n}^{{n}^{2}}}$
You can still ask an expert for help

• Questions are typically answered in as fast as 30 minutes

Solve your problem for the price of one coffee

• Math expert for every subject
• Pay only if we can solve it

Paul Mitchell
Since by the Stirling approximation
$n\mathrm{ln}n!-{n}^{2}\mathrm{ln}\in n\left(n\mathrm{ln}-n+o\left(n\right)\right)-{n}^{2}\mathrm{ln}n=-{n}^{2}\left(1-o\left(1\right)\right)$,,
we have a superexponentially decaying upper bound on the n-th term, so the series converges.
###### Not exactly what you’re looking for?
alkaholikd9
karton

If you don't want to use Stirling the simpler is to go for AM-GM inequality followed by rough majoration
$\left(n!{\right)}^{\frac{1}{n}}\le \frac{1}{n}×\frac{n\left(n+1\right)}{2}=\frac{n+1}{2}\le \frac{2n}{3}$
for n large enough.
The term of your series is then to be compared to $\left(\frac{2}{3}{\right)}^{{n}^{2}}$


text:
# Method of solution

Calculation at serviceability limit state starts with a calculation of moments and deflections using uncracked stiffness with load factors for total load. The analyses are performed using load combinations as described in Analysis.

Using the moment values the beam will be checked in the serviceability limit state for cracking and new stiffness values are decided at 20 section per span. A new analysis is performed using the new stiffness’s and new moments and deflection values are being calculated. The cracked calculation is repeated if necessary, see below.

The same calculation steps will be used in calculation of long term loading although here factors for long term load will be used. In long term analysis a section, which was cracked due to moments of total load, will also be considered cracked for long term moment regardless of this moment size.

# Cracking

## Cracking width calculation

The crack width wk may be calculated from:

• wk = Sr,maxsm - εcm)

where:

• Sr,max is the maximum crack spacing
• εsm is the mean strain in the reinforcement
• εcm is the mean strain in the concrete between cracks

εsm - εcm may be calculated from:

• εsm - εcm = [σs - kt fct,eff / ρp,eff (1 + αe ρp,eff)] / Es  0,6 σs / Es

where:

• σs is the stress in the tension reinforcement assuming cracked section
• αe is the ratio Es / Ecm
• fct,eff is the mean value of the tensile strength of the concrete when the first crack occur
• fct,eff = fctm
• ρp,eff = (As + ξ12 Ap') / Ac,eff
• Ap' is the area of pre or post-tensioned tendons within Ac,eff
• Ac,eff is the effective area of concrete as calculated below
• ξ1 is the adjusted ratio of bond strength as calculated below
• kt is a factor dependent on the duration of the load

Effective area of concrete Ac,eff

Ac,eff is the effective area of concrete of depth hc,ef,

where

• hc,ef is the lesser of:
• 2,5 (h - d)
• (h - x) / 3
• h / 2

## Adjusted ratio of bond strength

ξ1 is the adjusted ratio of bond strength taking into account the different diameters of prestressing and reinforcing steel:

• ξ1 = (ξ øs / øp)0,5

where:

• ξ is the ratio of bond strength according to the below table
• øs is the largest bar diameter
• øp is equivalent diameter of prestressing steel

## Crack spacing Sr,max

For bonded reinforcement with spacing  5(c + ø/2) the crack spacing is calculated as:

• Sr,max = kc + k1 k2 kø/ ρp,eff

where:

• ø is the bar diameter in mm. If more than one bar size is present an average bar size øeq should be used,
• øeq = (n1 ø12 + n2 ø22) / (n1 ø1 + n2 ø2)
• c is the cover to the longitudinal reinforcement,
• k1 = 0,8 for high bond bars, 1,6 for plain bars (e.g. prestressing tendons),
• k2 = 0,5 for bending, 1,0 for pure tension,
• k3 = 3,4
• k4 = 0,425
• ρp,eff as above.

For not bonded reinforcement or reinforcement with spacing > 5 (c + ø / 2) the crack spacing is calculated as:

• Sr,max = 1,3 (h - x)

where:

• x is the neutral axis depth

The crack spacing should be calculated in the direction of the principle tensile stress as:

• Sr,max = 1 / (cos θ / Sr,max,y + sin θ / Sr,max,z)
• θ is the angle between the reinforcement in the y-direction and the direction of the principal tensile stress,
• Sr,max,y and Sr,max,z are the crack spacing’s calculated in the y and z directions respectively.

# Deflections

The calculation of the deflection of the beam is done iteratively and begins with that the average curvature is calculated using un-cracked cross-section in 20 sections per span. The calculation is performed under short term conditions using total load respectively under long-term conditions using long term load.

Using the moment values the beam will be checked for cracking and new effective stiffness values are decided at 20 sections per span using the curvatures. A new analysis is performed using the new stiffness’s and new moments and deflection values are being calculated. The cracked calculation is repeated until stiffness values are stabilized in such a way that the difference in deflection between two consecutive calculations is less then the user defined percentage of the first calculation. The calculation is also terminated when the user defined number of iteration steps is reached.

In long term calculation a section, which was cracked due to moments of total load, will also be considered cracked for long term moment regardless of this moment size.

# Effective stiffness

Calculation of curvature is normally done using the relation:

ψ = - M / EI

where:

• ψ is the curvature
• M is the moment
• E is the modulus of elasticity
• I is the moment of inertia.

In un-cracked state under short term condition:

E = Ec,ef

and I is moment of inertia of the composed section, i.e. concrete section adjusted for reinforcement according to:

• I = Ic + α Is

where:

• Ic is moment of inertia for concrete section with reference to centre-of-gravity of composed section,
• Is is moment of inertia of reinforcement with reference to centre-of-gravity of composed section,
• α is the quotation Es / Ec,ef

At cracked analysis consideration must be taken to un-cracked parts of the beam between the cracks and under long term conditions also curvature changes due to creep and shrinking must be considered.

It is however recognized from geometry that:

• ψ = (εt - εb) / H

where:

• εt is strain in top of section
• εb is strain in bottom of section
• H is section height.

Thus by calculating the strains in section it is easy to calculate the curvature generally. We get:

• EIeff = M / ψ

and observe that this equation can be used if the curvature ψ is calculated using strains which include effects of cracking, creeping and shrinkage. Furthermore, if we mix un cracked and cracked calculation results using crack coefficient ζ we get:

• ψ = ψcracked + (1-ζ)  ψuncracked

where:

• ζ is a distribution coefficient.
• ζ = 1 - β (σsr / σs)2
or for flexure:
• ζ = 1 - β (Mcr / M)2

All parameters are according to the crack width calculation described above:

• ζ is zero for the un-cracked condition,
• β is a coefficient taking account of the influence of the duration of the loading or of repeated loading on the average strain,
• σs is the stress in the tension reinforcement calculated on the basis of a cracked section
• σsr is the stress in the tension reinforcement calculated on the basis of a cracked section under the loading causing first cracking

Creep

Creep effects are considered by reducing the modulus of elasticity:

• Ec,eff = Ecm / (1 + φ)

where:

• φ is the creep coefficient.

Shrinkage

Effects of shrinkage are considered as:

• 1 / rcs = εcs αe S / I

where:

• 1 / rcs is the curvature due to shrinkage
• εcs is the free shrinkage strain
• αe is the effective modular ratio Es / Ec,eff
• S is the first moment of area of both the top and bottom reinforcement about the center of gravity of the section
• I is the moment of inertia


text:
# KrakenDev

Here's to the crazy ones. The misfits. The troublemakers. The Swifters.

Viewing entries tagged
dependency injection

# Defeating the Anti-Pattern Bully 💥 Part 1 - Singletons

In this inaugural post on my anti-pattern series, Defeating the Anti-Pattern Bully, I talk about singletons. Many blogs out there discourage the use of singletons and for the most part, I agree. However, that doesn't mean that they don't have their merits. Here, I'll show you where you should probably use them and why so many people say you shouldn't.


text:
Question: Explain the operation of Hartley oscillator and state its application.
0

Subject: Computer Engineering

Topic: Electronic Circuits and Communication Fundamentals

Difficulty: Medium / High

 modified 12 months ago  • written 12 months ago by Sayali Bagwe • 2.2k
0

Hartley Oscillator:

Operation:

$R_1,R_2$ and $R_C→$ Resistances for biasing of transistors.

$C_{c1}$ and $C_{c2}→$ Coupling capacitors $C_C→$ bypasses $R_e$. The feedback circuit is formed by components $L_1,L_2$ and $L_s$

The amp is $C_e$ configuration, Hence it provides 180 degree phase shift between its i/p / o/p . The feedback circuit provides an additional 180 degree phase shift to satisfy the condition for the + ve feedback.

The frequency. of oscillation: EQUATION

$(L_1+L_2 )→$ Equivalent inductances. EQUATION

Non-considered mutual inductances between $L_1$ and $L_2$ . Inductors $L_1$ and $L_2$ (in practice) are wound on the same core so we can’t neglect the mutual inductance M present between them. So, considering mutual inductance, eq ind. $L_{eq}$ is $L_1+L_2+2M$

The oscillator frequency. can be varied by varying the capacitor EQUATION. The frequency variation over a wide range can be easily obtained.

• Easy to tune
• It can operate over a wide frequency. range typically from few Hz to several MHz.
• Easy to change the frequency. by means of a variable capacitor.


text:
# Math Help - Conditinal Probability with numbers selected at random

1. ## Conditinal Probability with numbers selected at random

Suppose that three numbers are selected one by one, at random, and without replacement from the set of numbers {1, 2, 3, ... n}. What is the probability that the third number falls between the first two if the first is smaller than the second?

The book tells me that the answer is 1/3, but that isn't much help towards how to find the answer.

2. Hello, Zennie!

$\text{Suppose that three numbers are selected randomly without replacement}$
$\text{from the set of numbers }\{1,\,2,\,3,\,\hdots\, n\}.$

$\text{What is the probability that the third number falls between the first two}$
$\text{if the first is smaller than the second?}$

$\text{The book answer is: }\frac{1}{3}$

Let the three numbers be: . $a,\,b,\,c$

There are $3! = 6$ permutations of the three numbers:
. . $abc,\:acb,\:bac,\:bca,\:cab,\:cba$ . (in increasing order)

"The first is less than the second": . $a < b$
. . There are three cases: . $abc,\:acb,\:cab$

In only one case, $\,c$ is between $\,a$ and $\,b$: . $acb$

Therefore, the probability is: . $\dfrac{1}{3}$

3. Wow, thanks a lot. That's so much more simple than I was expecting. I probably wouldn't have thought about it that way.

4. It is not such a tough question. Try using this hint:
Pick three number (in order) - x1,x2,x3 from {1,2,3,.....,n}
What is the Prob(x1<x2<x3)? [You don't need any calculation - think symmetry !!]


text:
×
INTELLIGENT WORK FORUMS
FOR ENGINEERING PROFESSIONALS

Log In

#### Come Join Us!

Are you an
Engineering professional?
Join Eng-Tips Forums!
• Talk With Other Members
• Be Notified Of Responses
To Your Posts
• Keyword Search
• One-Click Access To Your
Favorite Forums
• Automated Signatures
On Your Posts
• Best Of All, It's Free!
• Students Click Here

*Eng-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

#### Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Students Click Here

# Best way to contol flow

 Forum Search FAQs Links MVPs

## Best way to contol flow

(OP)
In a paper mill I am working in, they are using recirc lines to control pressure and thus flow to a process.  They use process line pressure to open and close a recirc valve, diverting flow back to a holding tank which provides for a pump's suction.  The end result is that the pump is always at a constant flow, with only a portion of the flow going to the process.  These recirc lines typically divert up to 20% of the flow through the pump!  The TDH for these applications is high (100 psig), therefore, VFDs on the pump do not appear to be feasible.  Will putting a control valve on the pump discharge to control flow be more energy efficient than current practice?  What suggestions do you hve?

### RE: Best way to contol flow

These are centrifugal type pumps?  If they are, they should save energy, you can easily determine how much and the  by looking at your pump curve.  Some pump Hp curves are pretty flat.

The other thing to consider is the fluid, is there some reason they wanted to keep a constant flow in the pipe, keep solids entrained, etc?  20% recirc doesn't seem enough for this to me but I would consider it.  Are there any other issues with this process that they would want to have designed the recycle this way?

100 psi dP is not that high of a differential pressure, VFDs might be an option but would be more expensive than a valve.

### RE: Best way to contol flow

The VFD will save more energy than a valve!  Much more on a centrifugal than a PD pump for this example.

With a VFD you can rough estimate the savings with "10% reduction on pump speed will give 20%reduction in power consumption" (centrifugal pumps).

As TD2K warned about solids suspention or other hydraulic considerations, if this is a standard pumping application, this is a VFD no brainer.

### RE: Best way to contol flow

No doubt a vfd is always the most energy efficient solution, but cost-benefit would need evaluation.

If you restrict yourself to comparing throttling of a recirc path to throttling of the main flow, I don't think the comparison is as simple as you suggest. For one thing, you may not save energy by throttling on main discharge... there is still an energy loss, and depending on where you are on the pump curve you may need more input power as you close the main flow discharge valve (if to the right of the peak of BHP vs flow curve).

Another thing to consider is that centrifugal pumps don't like to be operated under too restricted flow (far to the left of BEP).  That can cause vibration and problems which will decrease pump life.

Just a few thoughts without much specifics. Hopefully others can add more.

### RE: Best way to contol flow

(OP)
I have looked at a VFD application.  The system pressure is such that the minimum pump speed must be 70 to 80% just to overcome the minimum head requirements.  That is why I am looking at a control valve application.

### RE: Best way to contol flow

Bottom line is you need to look closely at that BHP vs flow curve to determine which option (recirc control or main-discharge throttling) consumes less energy.  Possibly fairly flat as TD2K says in which case you don't gain much energy either way.  Typically there is a peak somewhere in the operating range, so the answer to which strategy saves you energy depends partly on which side of the peak you're on.

My inclination would be to leave it alone unless you have identified clear-cut/substantial energy savings AND have looked carefully at possible implications (vibration at lower flows, range of expected operating conditions etc).

### RE: Best way to contol flow

Consider the following three example situations:

1) Typical horizontal split case pump, 2500 GPM at 100 PSI, 81%Eff, recirculating 20% flow, BHP (brake HP) will be about 185 HP.

2) Same pump, 2000 GPM (80%), 79% Eff, discharge control valve set for 100 PSI to system, BHP will be about 153 HP.

3) Same pump on a VFD, 2000 to 2500 GPM, 100 PSI, operates 24/7, 100%flow/5%time, 90%flow/50%time, 80%flow/45%time, $0.10 kWh. Should save about 198,000 kWh /$19,000 per year over the control valve application.  In this example the installed cost of a 200 HP VFD would be paid for in about 14 months.

Example of "no brainer".

### RE: Best way to contol flow

Correct me if I am worng, but isn't picking the correct pump the most efficient choice?  VFD's are in themselves verry inefficient devices when compared to across the line operation of a motor.

BobPE

### RE: Best way to contol flow

Bob - It is true that lowering the pump capacity can be a more efficient solution IF the pump has capacity beyond the maximum demand ever anticipated.  (not always true if demand is varying).

One way of reducing pump capacity/power consumption in the case where pumps are oversized compared to the maximum demand is to trim the impeller. Also sometimes a stage can be removed. There was some discussion in another thread about overfiling and underfiling... one increases capacity and one decreases... I forget which.

### RE: Best way to contol flow

I should also mention that even if pump is oversized compared to maximum demand, a vfd may still save energy (compared to throttling or recirculating) if demand is varying.

### RE: Best way to contol flow

With VFD if we reduce the speed(by 20%) to get 20% less flow the head raising capacity of pump reduces by 36% at that flow. So you have to go for higher speeds rather. What is the design head of the pump? As Bob correctly suggested, istead of going for a VFD better look at pump if you have to go for constant flow rates. Trimming of the impeller is an alternative. Underfiling increases flow by 1 to 2% but I never knew anything about overfiling.

Have you checked Cycle Stop Valves?

You can control the discharge valve and there is no harm for 20% reduction in flow.

Regards,

### RE: Best way to contol flow

Using a VFD is not typically a "no brainer".  Often the installation is much more expensive that a valve...yielding a poor return on your investment (yes, after including the energy savings).  You have to look at everything, including all the "goodies" that your Operations department may insist on.  Do you have cabinet space in your substation?  Do you need to be able to control the speed from the sub as well as from the control center?  What do you do if the VFD fails (as far as control strategy goes)?

Also, as pointed out, the process is what is important here.  If you have a flow to speed cascade, yet the VFD doesn't allow the pump to develop enough head at the reduced rate, then it simply won't work.

By the way, I believe that we don't use the term Variable Frequency Drive (VFD) anymore.  They are now designated as Adjustable Speed Drives (ASD's).

I really like ASD's (especially for replacing adjustable pitch control on fin-fans)...but you do have to do your homework and apply them properly.

Good luck!

Regards,

Bob

### RE: Best way to contol flow

(OP)
Thanks to everyone who responded.  I will check the pump BHP to flow curve prior to proceeding with a recommendation.  I don't think we can change impeller or motor size since the recirc flow is typically ~20% of process flow, however, but the recirc valve varies from 0 - 100 % open.  We need the full range of flow.  Again, thanks for your suggestions.

### RE: Best way to contol flow

ORTNVOL

One thing I've been through that sounds similar was circulating fluid at a metal plant.  They wanted flow on demand not seconds later.  In the case they had I calculated ramp time going from 40 to 60 hertz and that was over 35 seconds.  A VFD is a limited bus.  Both pump and  motor inertia as well as fluid viscosity need to be considered.  If you require instant fluid I would recommend that you avoid VFD's.

David

### RE: Best way to contol flow

ORTNVOL

A couple other thoughts:

If you restrict (choke) the discharge you may need to consider water hammer when the valve opens.

When you choke the flow below the pumps BEP the pumps efficiency will go down.  Most of this inefficiency will be converted to heat.  The added heat may cause problems for your pump seals, but more important it may cause bugs or bacteria to form in your pipe system.  The system could operate for months or years before it becomes an operational problem, but it could be very expensive to repair when it does.  We did this in the metal plant I sited in a previous reply.

In a responce from "electricpete" he stated that at low flow the pump could vibrate.  For some pumps this is a fact, but you should check with the pump manufacture about that.  If the pump has adequate thrust protection you should not have a problem.  My pumps don't have this problem, but we design for such contingencies.

You said at times you need to go to 0 flow.  Your pump won't be able to do that.  You need to check with the pump manufacture and find out the absolute min flow for that pump.

This may not answer your question, but I hope it helps anyway.

David

### RE: Best way to contol flow

My opinion is that most advices here are correct. I am myself a VFD person, however they do have some limitations.
If you need an instant correction of pressure, the inertia of your control system will be lowest with the recirculation valve.
If you need to save energy, at the expense of some ripples, and delay at pressure response, a VFD might work. I think that if your VFD has a PID control input, which you feed with a downstream pressure measure, the VFD will know the speed needed to get the get the required pressure.
Pressure changes with the second power with speed, and
Power curves are flat for the same speed, but I think they change with the third power of speed.
For the same capacity flow, pressure will be directly proportional to power, assuming a constant efficiency.
I have 3 80HP VFD working on an aggressive environment (Hcl vapors), 24h/7d for the last 8 years, with no problems so far. For security purposes they need a backup at the warehouse, as any other valve or device, however to replace it could be faster than changing a damaged control valve (no spills too). I have already installed more than 60 units, and I had to replace only 2, due to mechanical misuse (they broke the cases).
sancat

#### Red Flag This Post

Please let us know here why this post is inappropriate. Reasons such as off-topic, duplicates, flames, illegal, vulgar, or students posting their homework.

#### Red Flag Submitted

Thank you for helping keep Eng-Tips Forums free from inappropriate posts.
The Eng-Tips staff will check this out and take appropriate action.

### Reply To This Thread

#### Posting in the Eng-Tips forums is a member-only feature.

Click Here to join Eng-Tips and talk with other members! Already a Member? Login

#### Resources

White Paper - How ESI is Helping Move New Medical Device Product to Market Quicker & More Cost Effic
Early Supplier Involvement has long been a strategy employed by manufacturers to produce innovative products. Now, it almost seems like a necessity. Because decisions made in the design phase can positively affect product quality and costs, this can help add value to OEM bottom lines. This white paper will discuss many facets of ESI, including why itâ€™s so valuable today, what challenges limit the benefits of ESI, how cost is impacted, and more. Download Now

Close Box

# Join Eng-Tips® Today!

Join your peers on the Internet's largest technical engineering professional community.
It's easy to join and it's free.

Here's Why Members Love Eng-Tips Forums:

• Talk To Other Members
• Notification Of Responses To Questions
• Favorite Forums One Click Access
• Keyword Search Of All Posts, And More...

Register now while it's still free!

Already a member? Close this window and log in.


text:
# How do you find the value of the discriminant and state the type of solutions given -x^2-9=6x?

Nov 15, 2017

Solution: $x = - 3$

#### Explanation:

$- {x}^{2} - 9 = 6 x \mathmr{and} - {x}^{2} - 6 x - 9 = 0$

Comparing with standard quadratic equation $a {x}^{2} + b x + c = 0$

$a = - 1 , b = - 6 , c = - 9$ Discriminant $D = {b}^{2} - 4 a c$ or

$D = 36 - 36 = 0$ If discriminant positive, we get two real solutions,

if it is zero we get just one solution, and if it is negative we get

complex solutions. Discriminant is zero , so it has one root .

Quadratic formula: $x = \frac{- b \pm \sqrt{D}}{2 a}$or

$x = \frac{6 \pm \sqrt{0}}{- 2} = - 3$

Solution: $x = - 3$ [Ans]


text:
# pRF Tutorial

This tutorial shows you how to run a pRF analysis (see Dumoulin and Wandell (2008) for details - also Kay, Naselaris, Prenger and Gallant (2008)) with mrTools. The basic idea of a pRF analysis is to fit a “population receptive field” to each voxel. This is usually based on stimuli similar to a typical retinotopy experiment (rotating wedges, rings and moving bars). The responses to these stimuli are predicted by a very simple gaussian receptive field model. The gaussian RF has parameters of x,y position and standard deviation (receptive field size). Then for any given gaussian RF one can generate a model time series by simply multiplying the gaussian by the stimulus time-point by time-point and taking the sum across space. This gives a time series (i.e. the response of the receptive field to the stimulus). Convolving this with a standard hemodynamic function (or in some cases a parameterized one with fit parameters that one can adjust) produces a model time series. Then one finds the RF parameters that produces a model time series that most closely matches the actually measured time series for a voxel. This then is taken as the best population RF for that voxel. By doing this you can get the usual information that you get from a retinotopy experiment (the eccentricity and polar angle for the RF of each voxel), but also as a bonus the receptive field size as well. Plus you are not restricted to stimuli that produce a response that is sinusoidally modulated in time (like wedges and rings). You can in principle use any stimulus that causes response modulation (like bars or white noise).

You should have already run the retinotopy tutorial before going through this tutorial.

## Overview

2. The stimuli used in the experiment
3. Do the classic retinotopy as a reference
4. Average and concatenate appropriate scans
5. Run pRF analysis on V1 bars
6. Examining output of pRF analysis
7. Constrained search
8. Prefit
9. Fitting hemodynamic response function
10. Running a full analysis on V1

You can download the tutorial files from:

Note that this is a rather big file, approximately 300MB.

The files are provided as a tar/zip file. In Mac OS X you should be able to just click to open the files in the Finder. Otherwise, you can go to a terminal and do:

gunzip pRFTutorial.tar.gz
tar xvf pRFTutorial.tar

We provide you with a set of 10 functional scans, an inplane anatomy file, a flat map of the left occipital cortex and an inflated left occipital surface.

The functional scans include 4 rotating wedge runs (2 CW and 2 CCW rotations) and 2 expanding and contracting ring runs (1 expanding and 1 contracting). Each run is 168 volumes long (a volume was acquired every 1.54 seconds). The first 8 volumes will be thrown out to allow hemodynamic response and longitudinal magnetization to reach steady state for the correlation analysis, but for the pRF analysis all volumes may be kept. The data has already been motion compensated (since this step takes quite a bit of time to run).

From here, all the directions will be for commands to run under Matlab. It is assumed that you have properly set up mrTools using the directions under Getting Started.

Note that if you want to run this on your own subjects, you will need to run the stimulus program mglRetinotopy.

## 2. Stimuli and analysis

The visual stimuli are the familiar ones from retinotopy which are CW and CCW rotating 90 degree wedges and expanding and contracting rings. But, typically we also run bars stimuli in which a bar sweeps across the visual field in 8 different directions (its important that they sweep both forwards and backwards so that receptive field size and hemodynamic response width are not confounded. Also, we typically run the bars in a pseudo-random order but keep the same order fixed across repeated scans and average all of the data together). Another important point is that it is useful to turn off the stimulus (go to gray) for a cycle every now and then. This probes for very large receptive fields which may not be modulated by stimuli that move within the receptive field. The bars stimuli look something like this (note that the subject typically is fixating in the center on a fixation cross - not depicted - while doing a straight-forward fixation task):

The pRF analysis is basically very simple. We hypothesize that each voxel has a gaussian shaped receptive field (the combined receptive field of the population of neurons which contribute to the response of the voxel). We then want to fit the parameters of this gaussian (x, y and standard deviation) such that the predicted response of the receptive field to the stimuli we presented best matches the actual measured time series. We make predicted responses, like the following:

What you see in the above is a small receptive field in the top right with the stimulus running over it in different directions. The black trace below is the time-point by time-point multiplication of the stimulus and the receptive field summed over all of space (it is the predicted response of the receptive field). That gets convolved with a hemodynamic response function to make the predicted BOLD response in red.

If you move the receptive field to a different location, it predicts a different time series:

So, to fit a voxels response we change the position and standard deviation of the receptive field until the predicted response (red) best matches (in a least-squares sense) the actual time series for the voxel (note the lag in the BOLD response compared to the black trace).

Here is an example of a fit as it proceeds to change the receptive field position and size to best match the predicted time series (red) to the measured time series for the voxel (black):

## 3. Retinotopy analysis

We start by doing a quick retinotopy analysis. This will be used as a reference. We will be using the pRF and GLM_v2 plugins (GLM_V2 provides some better user interface items). Make sure these are installed by doing:

>> mlrPlugin

and selecting from the dialog GLM_V2 and pRF. Note that if you have a mrLoadRet going already, you will need to restart it to have these settings take effect.

Now, go ahead and start mrTools by cd'ing into the experiment directory and running:

>> mrLoadRet([])

The scans are all labelled and you should be able to do this analysis w/out looking at the cheat sheet below. Note that the best shift used for these scans was -2. So, go ahead and average together appropriate scans with the correct shift and flip and then run the correlation analysis!

Cheat sheet

If all went well, your retinotopy should look something like this:

Now you should draw ROIs for V1, V2, V3 and V3a (hV4 is a bit broken up in this particular scan). Again you should be able to do this based on what you learned in the Retinotopy tutorial. For our version check the following:

Cheat sheet

## 4. Average and concatenate

In the next steps you will average and concatenate scans for the pRF analysis. Note that this is different from what you do with the retinotopy analysis in which you shift and flip and do other tricks to account for the hemodynamic lag. For pRF analysis you are going to fit a model of the response which has the hemodynamic response lag as part of it. So you don't want to adjust the timing of the scans at all. This is important. If your scan timing is not correct relative to the stimulus all bets are off. In particular, you do not want to shift or reverse scans in averages. The code does handle junkFrames appropriately, but we are going to turn those off too. Remember that if you remove frames then your model has to know you did this otherwise it will associate the wrong stimulus with the response. So, here goes, let's make averages of like scans without any messing with the scans.

1. Turn off junk frames in the Raw group: You do this by going to the Raw group (Select from the group dropdown on the top left) and selecting Edit/Group/Edit Group and then go through and set Junk frames to 0 for each scan. This should automatically set the numFrames to 168. Click ok.
2. Average together the CCW scans (note that you do not want to include CW and CCW scans together since they had very different stimuli with different responses). Go to averageTSeries, include scan 1 and scan 5. Make sure that shift is 0 and reverse in *not* clicked. Make the same type of averages for CW (scans 2 and 6), Expanding (scan 3), Contracting (scan 4) and Bars (scans 7-10). You should end up with 5 new scans in your averages groups. Note that for Expanding and Contracting you will only have one scan - that's ok. This is just so that you have all the scans averaged as needed in the Averages group.
3. Check your work. Go To the Averages group. You should have a total of 7 scans now. Check the Edit/Scan/Info (⌘I) on each one of the scans that you just made to make sure that they are the average of the correct scans and that they do not have shift or reverse set. Also they should have no totalJunkedFrames or junkFrames and have a total of 168 volumes.

## 5. Run pRF analysis on V1 bars

First make a very small ROI for testing. You can make the ROI anywhere, but inside V1 where the retinotopy produced good results would be a good place to start and for the sake of following through on the tutorial you may want to get a similar set of voxels as is shown below:

Now, from the Analysis menu select pRF. You should see a dialog box like this:

This sets the options for the pRF analysis. The help menu should give explanations for the options, so we will just cover a few things here that are essential to know. The pRF analysis needs to know the stimulus that was presented during the scan. The code retrieves this from the stim file. You can take a look at what it computes as the stimulus by clicking the Display stimulus button. For example, let's look at the stimulus for the 7th scan in Averages (the average of the bar stimulus scans). Set dispStimScan to 7 and click Display stimulus and you should see this (this may not work on a non-mac computer):

What you are looking at is the stimulus with different cuts through a volume with axis x and y (image dimensions) and t (time in Z dimension). So, if you click the Z button you should see what the stimulus looks like animated volume by volume. Note that for our calculations we consider the stimulus to be changing at the same rate as the data acquisition. That is, the stimulus changes position each volume. We are ignoring all of the sliding bars that you see in the stimulus shown above. A more sophisticated analysis might try to take into account every frame of the stimulus and use all of that to generate a pRF model, but here we just think of everything happening within the bar as contrast changes that stimulates a pRF and therefore the stimulus image is just showing areas in white where there was high image contrast and black where there was no image contrast. Click Close to close the stimulus view.

Next, lets take a look at the model hemodynamic response function. Click Display HDR:

You can change parameters of this function by changing the parameters (timelag, tau and exponent). It is simply a gamma function commonly used as a simple hemodynamic response function. If you want an hemodynamic response function that has a negative undershoot, click on diffOfGamma and display again. Usually you don't need to adjust this function, but if you have different assumptions about what a “canonical” hemodynamic response function is you can change parameters to get what you want. Note that the basic fit uses this common hemodynamic function shape and convolves it with the model response time series, you can also fit a hemodynamic function at the same time as fitting the receptive field. This is set by changing the rfType to “gaussian-hdr”. But, for now, let's stick with the basics. We'll get back to more advanced fitting in a little bit.

So, now let's run it. Make sure that “restrict” has the ROI you just created (otherwise it may take a very long time to compute - if you make a mistake and it is running too long, your only option is to hit ctrl-C in the command window, which will crash you out to the debugger, but won't have any other bad side effects). Click OK. Then select Scan 7 (the bars stimuli scan) from the dialog that pops up. At this point you may get a pop-up with the following:

Basically, the algorithm work much faster if you use the parallel toolbox. By clicking Yes (this option may not be available if you do not have access to the parallel toolbox), it will start a number of threads each on a different processor of your machine. This speeds up things since on each processor you can be fitting a different voxel simultaneously. So, generally it is worth saying Yes to this dialog. Note that there appears to be some issue as of this writing (6/18/2013, Mac OS 10.8) with java and the parallel toolbox (the program will crash in matlabpool) that can be fixed by a patch.

It should now be fitting the time series. This can take some time depending on how big the ROI is that you made. You can check the progress in the matlab window.

## 6. Examining output of pRF analysis

When processing is finished, there should be 4 new overlays loaded (r2, polarAngle, eccentricity and rfHalfWidth). Switch to scan 7 and you should see an r2 map that looks something like this (note that if you click on a voxel within an ROI you may get a different plot - summary of the whole ROI - so either Hide all the ROIs (menu at left) or click on a voxel outside the ROI):

This shows the amount of variance accounted for by the model fit. You can examine the fit by interrogating voxels with the pRFPlot interrogator. To do so, make sure the interrogators are running (Plots/Interrogate Overlay) and make sure that the interrogator pRFPlot is selected in the bottom left of the screen. You may want to make sure that you hide your ROI viewing since clicking on a voxel within the ROI will bring up a different display which shows the fits of all the voxels as explained below. Now go click on a voxel. For example, if you click on the voxel [12 30 22] you should see the following:

What you are looking at is the data in black with the model fit in red. The top right shows the model hemodynamic response function used (which should be the same for all voxels since we did not fit its parameters for this fit). Below that on the blue background is a display of the fitted RF. It appears on the right side of the screen which is a good sanity check since this is the left visual cortex. If you drag your mouse over the time series the gray bar should move. The gray bar is simply depicting the time window being displayed in the black/red images below. What those images are showing is the stimulus at that time (gray bar) with respect to the receptive field for that voxel (red).

Now let's go back and look at the various other overlays. If you click on the polarAngle overlay you should see the following:

Note that you see a nice gradation as receptive fields are going from the lower right visual quadrant in green to the upper right visual quadrant in blue - just as is expected for the retinotopic ogranization of V1. You should click on individual voxels in green and in blue and be able to see in the interrogator window that the receptive fields are moving as expected. For example here is one from the green region which is more dorsal in V1 and thus responds to the lower visual field:

And here is one from the blue area which is more ventral and thus responds to the upper visual field:

Next click on the eccentricity overlay and you should see the following:

Again a nice gradation as expected from retinotopy. Lighter colors are more eccentric. If you click on voxels at various positions you should see the eccentricity of the RFs.

Finally, we can look at the rfHalfWidth. This is the size of the RF and is actually the std of the gaussian used to fit the receptive field. The map should look something like this:

Its a bit noisier in the sense that there isn't as clear a gradation as for eccentricity, but if you squint there is a tendency for RFs that are bigger (lighter colored) to be more eccentric as expected from the known physiology. Note that there are some voxels that are black suggesting very small RFs. These are likely not real but one failure mode of the algorithm. Clicking on one of them (e.g. [10 29 23]) you can see what happened:

What happened is that the algorithm found that it could make the RF really really small and then account for a few time points in the time series (the red spikes you see). Basically what is going on is that for a tiny RF the response are very infrequent and so the algorithm can fit noisy single points in the data. Note that the variance accounted for by this fit is not as good as other voxels, so you can go set the Clipping Overlay r2 to have a minimum of 0.4 (make sure to have “Clip across overlays” checked, then click on the r2 in the Clipping overlays and set the min field), then you will see that all these black voxels are thresholded out:

Next we will try and refit the population RF using different options for the fitting parameters to better understand what is going on.

We will explore how to set constraints on the search. For example, the voxels with rfHalfWidth very small are unlikely to be real, so it would be nice to set a constraint on the algorithm to avoid it finding such a small RF.

To do this you can recompute the fits for specific voxels - in particular, choose a voxel that came up black in the pRF analysis rfHalfWidth map. What you need to do is make sure that input focus is on the mrLoadRet window (click on the title bar for instance). Now using the interrogator function, you should click on a voxel while holding the shift key down. (Note that this may not work on a non-Apple machine - if clicking on an individual voxel while shift is held down does not work, then just re-run the whole pRF analysis from the Analysis menu).

Make sure you keep the shift key down until you see the pRF options dialog box come up:

We can now set the constraints so that we don't allow fits with tiny receptive fields. To do this, we have to use the levenberg-marquardt algorithm instead of nelder-mead. This is because levenberg-marquardt is a non-linear minimization algorithm which takes constraints, but nelder-mead simplex method is an unconstrained search. Note that the default is to use nelder-mead because it doesn't seem to get stuck in local minimum as much as levenberg-marquardt. If you want to learn more about these algorithms books like “Numerical Recipes” are a standard reference. So, first we set the algorithm to levenberg-marquaredt. Next unclick “defaultConstraints”. Also click “quickPrefit” (more about that in a minute) and click “OK”. You should see the following constraints dialog come up.

You can set constraints on any of the parameters, but for this case, let's just set the minrfWidth to 0.5 to keep from fitting a very small RF. Set that and click OK. After a minute you should see a window appear in which you can see the progress of the fitting algorithm (it should up-date from time to time with the RF moving around and the red model responses changing).

In this case, it settled on an RF slightly larger than the minimum (0.76) and still seems to have got the right location for the voxel (compare the x,y position with neighboring voxels in the map).

You may want to refit a few voxels and see how changing the constraints in various ways changes the fit that you get.

## 8. Prefit

When doing nonlinear fits, the starting point of the algorithm often has a large impact on the optimal fit achieved. For example, if the initial estimate of the RF that you give the algorithm is very far away from ideal, the algorithm can get lost in the error space and stuck in a local minimum with parameters far from the global optimal. If you could tell the algorithm where to start - like that you should start in the contralateral visual field for instance, you could do better.

The way we deal with this problem is by computing a grid of model receptive fields at many different locations in the visual field with many different receptive field sizes. We then do a quick test - what we call “prefit” - to see which of these model responses is most highly correlated with the actual voxels responses. By choosing that RFs parameters as the starting point we could do a better fit.

But, how many model receptive fields to calculate? The more you calculate the longer the algorithm takes, but the better the starting estimate. So, there are a few options that you can play with here. Shift-click on a voxel to bring up the pRF parameters dialog box. quickPrefit only computes a small number of model responses. This is useful for testing things out quickly, but the problem is that you may not have sampled the space of RFs very well and so the algorithm later will get stuck in a local minimum. We note that this is particularly true with lavenberg-marquardt which seems to not move very far from the initial starting point. This is why we default to using the nelder-mead even though it cannot do constrained searches.

The other option to note is the “prefitOnly” option. What this does is compute the best RF just based on the prefit (no nonlinear search). It just matches the best model response with the voxel response and reports that as the fit. It is very quick and dirty and can give a pretty good idea of whether things are working or not, but the results will be quantized to only the RF locations and sizes that were computed.

## 9. Fitting hemodynamic response function

Up to now we have been using a “canonical” hemodynamic response function. In some cases you may want to relax this assumption and actually try to fit the hemodynamic response. Note that when you do this there are more parameters in the model and lots of opportunities to get stuck in local minimum, so the fit gets harder to do. Nonetheless we can try to estimate the hemodynamic response function at the same time. Shift-click on a voxel with very high r2 like [10 31 20]. Now, in the options dialog box, change the rfModel to “gaussian-hdr”. Keep everything else with the default values - in particular, probably best not to do a quickfit since we need good starting parameters. You should see a window like this:

You can watch as the algorithm adjusts both the RF location and the shape of the hemodynamic response function to find the best fit. Here is in example of it doing the fit with the hemodynamic response:

## 10. Running a full analysis on V1

Ok. Now we are ready to try a bigger ROI for a more real test. To do this, we are going to now concatenate all of our various stimulus types together so that we can use all of the data that we have.

So, go to Analysis/Concatenate Time Series and concatenate scans 3-7 (make sure not to concatenate the scans 1 and 2 which were the ones used to make the standard retinotopy and have the response time series shifted and reversed). You can use the standard options for filtering and the like on the concatenate dialog box. The scans you select should look like this:

Now, switch to the Concatenation group and select Analysis/pRF. Let's do a quick and dirty prefit only to see what things look like. Click “prefitOnly” and “quickPrefit” and make sure that the restrict ROI selected is for your V1 ROI.

This may take some time to run. Works best if you are using the parallel toolbox and you have lots of free processors! After some time it should complete and you get a rough polarAngle map that should look something like this:

And the eccentricity map should look like this:

Looks reasonable! If you have the processing power and the time to wait, you can try a real fit. Just run pRF from the analysis menu again, but this time use all the default options and click OK. Wait some time and you should get maps that look like the following. Things look generally smoother and cleaner with the exception of a few voxels here and there that are not fit well:

r2 map:

Polar angle:

Eccentricity:

and rfHalfWidth:

If you click on a voxel (say [10 31 21] that has been well fit with the interrogator, then you should see that it is using the full time course across many experiments and doing a pretty good job of fitting all the data (compare red model curve to data in black). Notice that the overall r2 for this voxel is accounting for 80% of the variance. In individual scans within the cocnat (second row of title), we see that it is account from 85% to 93%.

Finally, if you have the V1 ROI showing and click a voxel within the ROI:

You can examine all the RFs within the ROI together. You should see a figure like the following:

Left shows all the RFs drawn on to the visual field - they all are in the contralateral (right) visual field and look like they do a reasonably good job of tiling that space. The plot of RF half width (std of gaussian receptive field) against eccentricity shows a nice linear relationship which is also what we expect in V1.

-jg.


text:
• # Organizing Code Files in C and C++

General and Gameplay Programming

# Introduction

While many simple programs fit into a single C or CPP source file, any serious project is going to need splitting up into several source files in order to be manageable. However, many beginning programmers may not realize what the point of this is - especially since some may have tried it themselves and run into so many problems that they decided it wasn't worth the effort. This article should explain why to do it, and how to do it properly. Where necessary, I give a brief explanation of how compilers and linkers work to help understand why you have to do things in a certain way.

## Terminology

In this article, I will call standard C and C++ files (usually with the .C or .CPP extension) "source files". This will be to distinguish them from "header files" (usually with the .H or .HPP extension). This terminology is also used by Visual C++ and most books. Note that the difference is purely conceptual - they are both just text files with code inside them. However, as the rest of the article will show, this difference in the way you treat source and header files is very important.

# Why split code into several files?

The first question some novice programmers ask when they see a directory full of separate code files is, "why isn't it all just in one file?" To them, they just don't see the point of scattering the code about. Splitting any reasonably-sized project up buys you some advantages, the most significant of which are the following:
• Speed up compilation - most compilers work on a file at a time. So if all your 10000 lines of code is in one file, and you change one line, then you have to recompile 10000 lines of code. On the other hand, if your 10000 lines of code are spread evenly across 10 files, then changing one line will only require 1000 lines of code to be recompiled. The 9000 lines in the other 9 files will not need recompiling. (Linking time is unaffected.) [nbsp]
• Increase organization - Splitting your code along logical lines will make it easier for you (and any other programmers on the project) to find functions, variables, struct/class declarations, and so on. Even with the ability to jump directly to a given identifier that is provided in many editors and development environments (such as Microsoft Visual C++), there will always be times when you need to scan the code manually to look for something. Just as splitting the code up reduces the amount of code you need to recompile, it also reduces the amount of code you need to read in order to find something. Imagine that you need to find a fix you made to the sound code a few weeks ago. If you have one large file called GAME.C, that's potentially a lot of searching. If you have several small files called GRAPHICS.C, MAINLOOP.C, SOUND.C, and INPUT.C, you know where to look, cutting your browsing time by 3/4. [nbsp]
• Facilitate code reuse - If your code is carefully split up into sections that operate largely independently of each other, this lets you use that code in another project, saving you a lot of rewriting later. There is a lot more to writing reusable code than just using a logical file organization, but without such an organization it is very difficult to know which parts of the code work together and which do not. Therefore putting subsystems and classes in a single file or carefully delineated set of files will help you later if you try to use that code in another project. [nbsp]
• Share code between projects - The principle here is the same as with the reuse issue. By carefully separating code into certain files, you make it possible for multiple projects to use some of the same code files without duplicating them. The benefit of sharing a code file between projects rather than just using copy-and-paste is that any bug fixes you make to that file or files from one project will affect the other project, so both projects can be sure of using the most up-to-date version. [nbsp]
• Split coding responsibilities among programmers - For really large projects, this is perhaps the main reason for separating code into multiple files. It isn't practical for more than one person to be making changes to a single file at any given time. Therefore you would need to use multiple files so that each programmer can be working on a separate part of the code without affecting the file that the other programmers are editing. Of course, there still have to be checks that 2 programmers don't try altering the same file; configuration management systems and version control systems such as CVS or MS SourceSafe help you here. All of the above can be considered to be aspects of modularity, a key element of both structured and object-oriented design.

# How to do it: The Basics

By now you're probably convinced that there are benefits to splitting up your project into several smaller files. So, how would you go about it? Although some of the decisions you make will be reasonably arbitrary, there are some basic rules that you should follow to ensure that it all works. Firstly, look at how you would split your code into sections. Often this is by splitting it into separate subsystems, or 'modules', such as sound, music, graphics, file handling, etc. Create new files with meaningful filenames so that you know at a glance what kind of code is in them. Then move all the code that belongs to that module into that file. Sometimes you don't have clear module - some would say this should send out warnings about the quality of your design! There may still be other criteria you use for splitting up code, such as the structures it operates upon. (Often "general purpose" functions can be split into string-handling and number-handling, for example.) And occasionally a module could be split into two or more files, because it might make sense to do so on logical grounds. Once you have split it up in this way into separate source files, the next stage is to consider what will go into the header files. On a very simple level, code that you usually put at the top of the source file is a prime candidate for moving into a separate header file. This is presumably why they got termed 'header' files, after all. This code to go in a header usually includes some or all of the following:
• class and struct definitions
• typedefs
• function prototypes
• global variables (but see below)
• constants
• #defined macros

# Potential Pitfalls

The rules given above are fairly vague and merely serve as a starting point for organizing your code. In simple cases, you can produce completely working programs by following those guidelines. However there are some more details that have to be accounted for, and it is often these details that cause novice programmers so much grief when they first start splitting their code up into header files and normal files. In my experience, there are four basic errors that people encounter when they first enter the murky world of user-defined header files.
1. The source files no longer compile as they can't find the functions or variables that they need. (This often manifests itself in the form of something similar to "error C2065: 'MyStruct' : undeclared identifier" in Visual C++, although this can produce any number of different error messages depending on exactly what you are trying to reference.) [nbsp]
2. Cyclic dependencies, where headers appear to need to #include each other to work as intended. A Sprite may contain a pointer to the Creature it represents, and a Creature may contain a pointer to the Sprite it uses. No matter how you do this, either Creature or Sprite must be declared first in the code, and that implies that it won't work since the other type isn't declared yet. [nbsp]
3. Duplicate definitions where a class or identifier is included twice in a source file. This is a compile time error and usually arises when multiple header files include one other header file, leading to that header being included twice when you compile a source file that uses them. (In MSVC, this might look something like "error C2011: 'MyStruct' : 'struct' type redefinition.) [nbsp]
4. Duplicate instances of objects within the code that compiled fine. This is a linking error, often difficult to understand. (In MSVC, you might see something like "error LNK2005: "int myGlobal" (?myGlobal@@3HA) already defined in myotherfile.obj".)
So how do we fix these issues?

# Fixing Problem 1

Luckily, these issues are easy to fix, and even easier to avoid once you understand them. The first error, where a source file refuses to compile because one of the identifiers was undeclared, is easy to resolve. Simply #include the file that contains the definition of the identifier you need. If your header files are organized logically and named well, this should be easy. If you need to use the Sprite struct, then you probably need to #include "sprite.h" in every file that does so. One mistake that programmers often make is to assume that a file is #included simply because another header #includes it for itself.
Example: /* Header1.h */ #include "header2.h" class ClassOne { ... }; /* Header2.h */ class ClassTwo { ... }; /* File1.cpp */ #include "Header1.h" ClassOne myClassOne_instance; ClassTwo myClassTwo_instance;
In this case, File1.cpp will compile fine, as including Header1.h has indirectly #included Header2.h, meaning that File1.cpp has access to the Class2 class. But what happens if, at a later date, someone realises that Header1.h doesn't actually need to #include Header2.h? They can remove that #include line, and suddenly File1.cpp will break the next time you try to compile it. The key here, is to explicitly #include any header files that you need for a given source file to compile. You should never rely on header files indirectly including extra headers for you, as that may change. The 'extra' #includes also serve as documentation, by demonstrating what other code this file is dependent on. So don't try and leave them out if you know you need that header included somehow.

# Fixing Problem 2

Cyclic (or two-way) dependencies are a common problem in software engineering. Many constructs involve a two-way link of some sort, and this implies that both classes or structures know about each other. Often this ends up looking like this:
/* Parent.h */ #include "child.h" class Parent { Child* theChild; }; /* Child.h */ #include "parent.h" class Child { Parent* theParent; };
Given that one of these has to be compiled first, you need some way to break the cycle. In this case, it's actually quite trivial. The Parent struct doesn't actually need to know the details of the Child class, as it only stores a pointer to one. Pointers are pretty much the same no matter what they point to, therefore you don't need to the definition of the structure or class in order to store a pointer to an instance of that structure or class. So the #include line is not needed. However, simply taking it out will give you an "undeclared identifier" error when it encounters the word 'Child', so you need to let the compiler know that Child is a class or class that you wish to point to. This is done with a forward declaration, taking the form of a class or class definition without a body. Example:
/* Parent.h */ class Child; /* Forward declaration of Child; */ class Parent { Child* theChild; };
Notice how the #include line is replaced by the forward declaration. This has allowed you to break the dependency between Parent.h and Child.h. Additionally, it will speed up compilation as you are reading in one less header file. In this case, the same procedure can (and should) be followed in Child.h by forward declaring "class Parent;" As long as you are only referring to a pointer and not the actual type itself, you don't need to #include the full definition. In 99% of cases, this can be applied to one or both sides of a cycle to remove the need to #include one header from another, eliminating the cyclic dependency. Of course, in the source files, it's quite likely that there will be functions that apply to Parent that will manipulate the Child also, or vice versa. Therefore, it is probably necessary to #include both parent.h and child.h in parent.c and child.c.

# Fixing Problem 3

Duplicate definitions at compile time imply that a header ended up being included more than once for a given source file. This leads to a class or struct being defined twice, causing an error. The first thing you should do is ensure that, for each source file, you only include the headers that you need. This will aid compilation speed since the compiler is not reading and compiling headers that serve no purpose for this file. Sadly, this is rarely enough, since some headers will include other headers. Let's revisit an example from earlier, slightly modified:
/* Header1.h */ #include "header3.h" class ClassOne { ... }; /* Header2.h */ #include "header3.h" class ClassTwo { ... }; /* File1.cpp */ #include "Header1.h" #include "Header2.h" ClassOne myClassOne_instance; ClassTwo myClassTwo_instance;

For the purposes of compilation, File1.cpp ends up containing copies of Header1.h and Header2.h, both of which include their own copies of Header3.h. The resulting file, with all headers expanded inline into your original file, is known as a translation unit. Due to this inline expansion, anything declared in Header3.h is going to appear twice in this translation unit, causing an error. So, what do you do? You can't do without Header1.h or Header2.h, since you need to access the structures declared within them So you need some way of ensuring that, no matter what, Header3.h is not going to appear twice in your File1.cpp translation unit when it gets compiled. This is where inclusion guards come in. If you looked at stdlib.h earlier, you may have noticed lines near the top similar to the following:
#ifndef _INC_STDLIB #define _INC_STDLIB
And at the bottom of the file, something like:
#endif /* _INC_STDLIB */
This is what is known as an inclusion guard. In plain English, it says "if we haven't defined the symbol "_INC_STDLIB" yet, then define it and continue. Otherwise, skip to the #endif." This is a similar concept to writing the following code to get something to run once:
static bool done = false; if (!done) { /* Do something */ done = true; }
This ensures that the 'do something' only ever happens once. The same principle goes for the inclusion guards. During compilation of File1.cpp, the first time any file asks to #include stdlib.h, it reaches the #ifndef line and continues because "_INC_STDLIB" is not yet defined. The very next line defines that symbol and carries on reading in stdlib.h. If there is another "#include " during the compilation of File1.cpp, it will read to the #ifndef check and then skip to the #endif at the end of the file. This is because everything between the #ifndef and the #endif is only executed if "_INC_STDLIB" is not defined; and it got defined the first time we included it. This way, it is ensured that the definitions within stdlib.h are only ever included once by putting them within this #ifndef / #endif pair. This is trivial to apply to your own projects. At the start of every header file you write, put the following:
#ifndef INC_FILENAME_H #define INC_FILENAME_H
Note that the symbol (in this case, "INC_FILENAME_H") needs to be unique across your project. This is why it is a good idea to incorporate the filename into the symbol. Don't add an underscore at the start like stdlib.h does, as identifiers prefixed with an underscore are supposed to be reserved for "the implementation" (ie. the compiler, the standard libraries, and so on). Then add the #endif /* INC_FILENAME_H */ at the end of the file. The comment is not necessary, but will help you remember what that #endif is there for. If you use Microsoft Visual C++, you may have also noticed 3 lines in stdlib.h similar to:
#if _MSC_VER > 1000 #pragma once #endif
Other compilers may have code similar to this. This effectively achieves the same thing as the inclusion guards, without having to worry about filenames, or adding the #endif at the bottom of the file, by saying that "for this translation unit, only include this file once". However, remember that this is not portable. Most compilers don't support the #pragma once directive, so it's a good habit to use the standard inclusion guard mechanism anyway, even if you do use #pragma once. With inclusion guards in all your headers, there should be no way for any given header's contents to end up included more than once in any translation unit, meaning you should get no more compile-time redefinition errors. So that's compile-time redefinition fixed. But what about the link-time duplicate definition problems?

# Fixing Problem 4

When the linker comes to create an executable (or library) from your code, it takes all the object (.obj or .o) files, one per translation unit, and puts them together. The linker's main job is to resolve identifiers (basically, variables or functions names) to machine addresses in the file. This is what links the various object files together. The problem arises when the linker finds two or more instances of that identifier in the object files, as then it cannot determine which is the 'correct' one to use. The identifier should be unique to avoid any such ambiguity. So how come the compiler doesn't see an identifier as being duplicated, yet the linker does? Imagine the following code:
/* Header.h */ #ifndef INC_HEADER_H #define INC_HEADER_H int my_global; #endif /* INC_HEADER_H */ /* code1.cpp */ #include "header1.h" void DoSomething() { ++my_global; } /* code2.cpp */ #include "header1.h" void DoSomethingElse() { --my_global; }
This first gets compiled into two object files, probably called code1.obj and code2.obj. Remember that a translation unit contains full copies of all the headers included by the file you are compiling. Finally, the object files are combined to produce the final file. Here's a visual depiction of the way these files (and their contents) are combined:

extern int my_global;
The 'extern' specifier is like telling the compiler to wait until link time to resolve the 'connection'. And for a function, you just put the function prototype:
int SomeFunction(int parameter);

# Conclusion

If done properly, organizing your files this way can speed your development without hindering you at all or introducing any extra problems. Although it seems like there is a lot to consider when doing so, it becomes second nature in no time. Just remember these key points:
• Split your code up along logical module divisions
• The the interface into the header files and the implementation in the source files
• Use forward declarations wherever possible to reduce dependencies
• Don't put code in the headers that might adversely affect source files that include it Good luck!

Report Article

## User Feedback

What a great article!! Thanks so much to Ben and all those who revised later on..

##### Share on other sites
The best tutorial about this subject(and the only I thinkq many books don't cover this). Thanks helped me a lot.

##### Share on other sites

Thanks, this helped me a lot

##### Share on other sites

Great and very helpful article. Only one thing you left unexplained, that's part of the One Definition Rule(ODR). Some things, like types, templates, and extern inline functions, can be defined in more than one translation unit. For a given entity, each definition must be the same. Non-extern objects and functions in different translation units are different entities, even if their names and types are the same. Again, I think this is the best article on this topic one can found on the net. Congratulations.

##### Share on other sites

Agreed, a very nice article, sums it up nicely!