text:
# If we add a constant (say, d) for all data values, how this will affect the geometric mean? Give an example.

Question
Data distributions
If we add a constant (say, d) for all data values, how this will affect the geometric mean? Give an example.

2021-02-04

Geometric mean of a data distribution $$\displaystyle{a}_{{1}},{a}_{{2}},{a}_{{3}},..,{a}_{{n}}$$ is $$n^{th}$$ square root of product of all data points and is calculated using the below mentioned formula $$\displaystyle{G}{M}={\sqrt[{{n}}]{{{a}_{{1}}\cdot{a}_{{2}}\cdot\ldots\cdot{a}_{{n}}}}}={\left({x}_{{1}}\cdot{x}_{{2}}\cdot\ldots\cdot{x}_{{n}}\right)}^{{\frac{{1}}{{n}}}}$$
When a constant d is added to all data values, the product of all numbers will increase, so the geometric mean of the data distribution also increases by adding a constant to all values.
Let us consider an example data distribution 2,4,8,16,32
The geometric mean is calculated as shown below
$$\displaystyle{G}{M}={\sqrt[{{n}}]{{{a}_{{1}}\cdot{a}_{{2}}\cdot\ldots\cdot{a}_{{n}}}}}$$
$$\displaystyle={\sqrt[{{5}}]{{{2}\cdot{4}\cdot{8}\cdot{16}\cdot{32}}}}$$
$$\displaystyle={\sqrt[{{5}}]{{{32768}}}}$$
$$=8$$
If we add a constant 2 to all data points then the data distribution will be 4 ,6 ,10, 18, 34. The geometric mean is calculated as shown below:
$$\displaystyle{G}{M}={\sqrt[{{n}}]{{{a}_{{1}}\cdot{a}_{{2}}\cdot\ldots\cdot{a}_{{n}}}}}$$
$$\displaystyle={\sqrt[{{5}}]{{{4}\cdot{6}\cdot{10}\cdot{18}\cdot{34}}}}$$
$$\displaystyle={\sqrt[{{5}}]{{{146880}}}}$$
$$=10.7992$$
Here it is clearly shown that adding a constant to all data values increases the geometric mean of the data distribution.

### Relevant Questions

We will now add support for register-memory ALU operations to the classic five-stage RISC pipeline. To offset this increase in complexity, all memory addressing will be restricted to register indirect (i.e., all addresses are simply a value held in a register; no offset or displacement may be added to the register value). For example, the register-memory instruction add x4, x5, (x1) means add the contents of register x5 to the contents of the memory location with address equal to the value in register x1 and put the sum in register x4. Register-register ALU operations are unchanged. The following items apply to the integer RISC pipeline:
a. List a rearranged order of the five traditional stages of the RISC pipeline that will support register-memory operations implemented exclusively by register indirect addressing.
b. Describe what new forwarding paths are needed for the rearranged pipeline by stating the source, destination, and information transferred on each needed new path.
c. For the reordered stages of the RISC pipeline, what new data hazards are created by this addressing mode? Give an instruction sequence illustrating each new hazard.
d. List all of the ways that the RISC pipeline with register-memory ALU operations can have a different instruction count for a given program than the original RISC pipeline. Give a pair of specific instruction sequences, one for the original pipeline and one for the rearranged pipeline, to illustrate each way.
Hint for (d): Give a pair of instruction sequences where the RISC pipeline has “more” instructions than the reg-mem architecture. Also give a pair of instruction sequences where the RISC pipeline has “fewer” instructions than the reg-mem architecture.

A random sample of $$n_1 = 14$$ winter days in Denver gave a sample mean pollution index $$x_1 = 43$$.
Previous studies show that $$\sigma_1 = 19$$.
For Englewood (a suburb of Denver), a random sample of $$n_2 = 12$$ winter days gave a sample mean pollution index of $$x_2 = 37$$.
Previous studies show that $$\sigma_2 = 13$$.
Assume the pollution index is normally distributed in both Englewood and Denver.
(a) State the null and alternate hypotheses.
$$H_0:\mu_1=\mu_2.\mu_1>\mu_2$$
$$H_0:\mu_1<\mu_2.\mu_1=\mu_2$$
$$H_0:\mu_1=\mu_2.\mu_1<\mu_2$$
$$H_0:\mu_1=\mu_2.\mu_1\neq\mu_2$$
(b) What sampling distribution will you use? What assumptions are you making? NKS The Student's t. We assume that both population distributions are approximately normal with known standard deviations.
The standard normal. We assume that both population distributions are approximately normal with unknown standard deviations.
The standard normal. We assume that both population distributions are approximately normal with known standard deviations.
The Student's t. We assume that both population distributions are approximately normal with unknown standard deviations.
(c) What is the value of the sample test statistic? Compute the corresponding z or t value as appropriate.
(Test the difference $$\mu_1 - \mu_2$$. Round your answer to two decimal places.) NKS (d) Find (or estimate) the P-value. (Round your answer to four decimal places.)
(e) Based on your answers in parts (i)−(iii), will you reject or fail to reject the null hypothesis? Are the data statistically significant at level \alpha?
At the $$\alpha = 0.01$$ level, we fail to reject the null hypothesis and conclude the data are not statistically significant.
At the $$\alpha = 0.01$$ level, we reject the null hypothesis and conclude the data are statistically significant.
At the $$\alpha = 0.01$$ level, we fail to reject the null hypothesis and conclude the data are statistically significant.
At the $$\alpha = 0.01$$ level, we reject the null hypothesis and conclude the data are not statistically significant.
(f) Interpret your conclusion in the context of the application.
Reject the null hypothesis, there is insufficient evidence that there is a difference in mean pollution index for Englewood and Denver.
Reject the null hypothesis, there is sufficient evidence that there is a difference in mean pollution index for Englewood and Denver.
Fail to reject the null hypothesis, there is insufficient evidence that there is a difference in mean pollution index for Englewood and Denver.
Fail to reject the null hypothesis, there is sufficient evidence that there is a difference in mean pollution index for Englewood and Denver. (g) Find a 99% confidence interval for
$$\mu_1 - \mu_2$$.
(Round your answers to two decimal places.)
lower limit
upper limit
(h) Explain the meaning of the confidence interval in the context of the problem.
Because the interval contains only positive numbers, this indicates that at the 99% confidence level, the mean population pollution index for Englewood is greater than that of Denver.
Because the interval contains both positive and negative numbers, this indicates that at the 99% confidence level, we can not say that the mean population pollution index for Englewood is different than that of Denver.
Because the interval contains both positive and negative numbers, this indicates that at the 99% confidence level, the mean population pollution index for Englewood is greater than that of Denver.
Because the interval contains only negative numbers, this indicates that at the 99% confidence level, the mean population pollution index for Englewood is less than that of Denver.
1. The standard error of the estimate is the same at all points along the regression line because we assumed that A. The observed values of y are normally distributed around each estimated value of y-hat. B. The variance of the distributions around each possible value of y-hat is the same. C. All available data were taken into account when the regression line was calculated. D. The regression line minimized the sum of the squared errors. E. None of the above.
The table below shows the number of people for three different race groups who were shot by police that were either armed or unarmed. These values are very close to the exact numbers. They have been changed slightly for each student to get a unique problem.
Suspect was Armed:
Black - 543
White - 1176
Hispanic - 378
Total - 2097
Suspect was unarmed:
Black - 60
White - 67
Hispanic - 38
Total - 165
Total:
Black - 603
White - 1243
Hispanic - 416
Total - 2262
Give your answer as a decimal to at least three decimal places.
a) What percent are Black?
b) What percent are Unarmed?
c) In order for two variables to be Independent of each other, the P $$(A and B) = P(A) \cdot P(B) P(A and B) = P(A) \cdot P(B).$$
This just means that the percentage of times that both things happen equals the individual percentages multiplied together (Only if they are Independent of each other).
Therefore, if a person's race is independent of whether they were killed being unarmed then the percentage of black people that are killed while being unarmed should equal the percentage of blacks times the percentage of Unarmed. Let's check this. Multiply your answer to part a (percentage of blacks) by your answer to part b (percentage of unarmed).
Remember, the previous answer is only correct if the variables are Independent.
d) Now let's get the real percent that are Black and Unarmed by using the table?
If answer c is "significantly different" than answer d, then that means that there could be a different percentage of unarmed people being shot based on race. We will check this out later in the course.
Let's compare the percentage of unarmed shot for each race.
e) What percent are White and Unarmed?
f) What percent are Hispanic and Unarmed?
If you compare answers d, e and f it shows the highest percentage of unarmed people being shot is most likely white.
Why is that?
This is because there are more white people in the United States than any other race and therefore there are likely to be more white people in the table. Since there are more white people in the table, there most likely would be more white and unarmed people shot by police than any other race. This pulls the percentage of white and unarmed up. In addition, there most likely would be more white and armed shot by police. All the percentages for white people would be higher, because there are more white people. For example, the table contains very few Hispanic people, and the percentage of people in the table that were Hispanic and unarmed is the lowest percentage.
Think of it this way. If you went to a college that was 90% female and 10% male, then females would most likely have the highest percentage of A grades. They would also most likely have the highest percentage of B, C, D and F grades
The correct way to compare is "conditional probability". Conditional probability is getting the probability of something happening, given we are dealing with just the people in a particular group.
g) What percent of blacks shot and killed by police were unarmed?
h) What percent of whites shot and killed by police were unarmed?
i) What percent of Hispanics shot and killed by police were unarmed?
You can see by the answers to part g and h, that the percentage of blacks that were unarmed and killed by police is approximately twice that of whites that were unarmed and killed by police.
j) Why do you believe this is happening?
Do a search on the internet for reasons why blacks are more likely to be killed by police. Read a few articles on the topic. Write your response using the articles as references. Give the websites used in your response. Your answer should be several sentences long with at least one website listed. This part of this problem will be graded after the due date.
The bulk density of soil is defined as the mass of dry solidsper unit bulk volume. A high bulk density implies a compact soilwith few pores. Bulk density is an important factor in influencing root development, seedling emergence, and aeration. Let X denotethe bulk density of Pima clay loam. Studies show that X is normally distributed with $$\displaystyle\mu={1.5}$$ and $$\displaystyle\sigma={0.2}\frac{{g}}{{c}}{m}^{{3}}$$.
(a) What is thedensity for X? Sketch a graph of the density function. Indicate onthis graph the probability that X lies between 1.1 and 1.9. Findthis probability.
(b) Find the probability that arandomly selected sample of Pima clay loam will have bulk densityless than $$\displaystyle{0.9}\frac{{g}}{{c}}{m}^{{3}}$$.
(c) Would you be surprised if a randomly selected sample of this type of soil has a bulkdensity in excess of $$\displaystyle{2.0}\frac{{g}}{{c}}{m}^{{3}}$$? Explain, based on theprobability of this occurring.
(d) What point has the property that only 10% of the soil samples have bulk density this high orhigher?
(e) What is the moment generating function for X?
The following is an 8051 instruction: CJNE A, # 'Q' ,AHEAD
a) what is the opcode for this instruction?
b) how many bytes long is this instruction?
c) explain the purpose of each byte of this instruction.
d) how many machine cycles are required to execute this instruction?
e) If an 8051 is operating from a 10 MHz crystal, how longdoes this instruction take to execute?
1. Find each of the requested values for a population with a mean of $$? = 40$$, and a standard deviation of $$? = 8$$ A. What is the z-score corresponding to $$X = 52?$$ B. What is the X value corresponding to $$z = - 0.50?$$ C. If all of the scores in the population are transformed into z-scores, what will be the values for the mean and standard deviation for the complete set of z-scores? D. What is the z-score corresponding to a sample mean of $$M=42$$ for a sample of $$n = 4$$ scores? E. What is the z-scores corresponding to a sample mean of $$M= 42$$ for a sample of $$n = 6$$ scores? 2. True or false: a. All normal distributions are symmetrical b. All normal distributions have a mean of 1.0 c. All normal distributions have a standard deviation of 1.0 d. The total area under the curve of all normal distributions is equal to 1 3. Interpret the location, direction, and distance (near or far) of the following zscores: $$a. -2.00 b. 1.25 c. 3.50 d. -0.34$$ 4. You are part of a trivia team and have tracked your team’s performance since you started playing, so you know that your scores are normally distributed with $$\mu = 78$$ and $$\sigma = 12$$. Recently, a new person joined the team, and you think the scores have gotten better. Use hypothesis testing to see if the average score has improved based on the following 8 weeks’ worth of score data: $$82, 74, 62, 68, 79, 94, 90, 81, 80$$. 5. You get hired as a server at a local restaurant, and the manager tells you that servers’ tips are $42 on average but vary about $$12 (\mu = 42, \sigma = 12)$$. You decide to track your tips to see if you make a different amount, but because this is your first job as a server, you don’t know if you will make more or less in tips. After working 16 shifts, you find that your average nightly amount is$44.50 from tips. Test for a difference between this value and the population mean at the $$\alpha = 0.05$$ level of significance.


text:
## University COVID-19 update

### Questions about buildings and services? Visit the list of Modified Services.

Please note: The University of Waterloo is closed for all events until further notice.

# Tutte Colloquium - Anurag Anshu

Friday, May 31, 2019 — 3:30 PM EDT

Title: Quantum Log-Approximate-Rank Conjecture is also False

 Speaker: Anurag Anshu Affiliation: Institute for Quantum Computing - University of Waterloo Room: MC 5501

Abstract:

In a recent breakthrough result, Chattopadhyay, Mande and Sherif [ECCC TR18-17] showed an exponential separation between the log approximate rank and randomized communication complexity of a total function f', hence refuting the log approximate rank conjecture of Lee and Shraibman [2009]. We provide an alternate proof of their randomized communication complexity lower bound using the information complexity approach. Using the intuition developed there, we derive a polynomially-related quantum communication complexity lower bound using the quantum information complexity approach, thus providing an exponential separation between the log approximate rank and quantum communication complexity of f'. Previously, the best known separation between these two measures was (almost) quadratic, due to Anshu, Ben-David, Garg, Jain, Kothari and Lee [CCC, 2017]. This settles one of the main question left open by Chattopadhyay, Mande and Sherif, and refutes the quantum log approximate rank conjecture of Lee and Shraibman [2009]. Along the way, we develop a Shearer-type protocol embedding for product input distributions that might be of independent interest.

Joint work with Naresh Good Boddu and Dave Touchette (https://arxiv.org/abs/1811.10525)

Location
MC - Mathematics & Computer Building
5501
200 University Avenue West

Waterloo, ON N2L 3G1

### November 2020

S M T W T F S
1
3
4
7
8
10
11
14
15
17
18
21
22
24
25
26
27
28
29
1
2
3
4
5
1. 2020 (116)
1. December (2)
2. November (12)
3. October (12)
4. September (12)
5. August (11)
6. July (17)
7. June (11)
8. May (6)
9. March (11)
10. February (11)
11. January (11)
2. 2019 (167)
1. December (5)
2. November (15)
3. October (18)
4. September (15)
5. August (9)
6. July (17)
7. June (18)
8. May (16)
9. April (9)
10. March (24)
11. February (13)
12. January (8)
3. 2018 (136)
4. 2017 (103)
5. 2016 (137)
6. 2015 (136)
7. 2014 (88)
8. 2013 (48)
9. 2012 (39)
10. 2011 (36)
11. 2010 (40)
12. 2009 (40)
13. 2008 (39)
14. 2007 (15)

format: plain


text:
Question
Students in a lab group are given a plastic cube with a hollow cube-shaped space in the middle that fills about half the volume of the cube. The index of refraction of the plastic is known. The hollow space is filled with a gas, and the students are asked to collect the data needed to find the index of refraction of the gas. What information would you need to collect, and how would you use this information in order to deduce the index of refraction of the gas in the cube?
data needed: $\textrm{l}, \theta_1,$\Delta d$,$\textrm{n}_c$. Solve the formula shown in the video numerically for$\Delta d\$.
Solution Video

# OpenStax College Physics Solution, Chapter 25, Problem 9 (Test Prep for AP® Courses) (5:51)

View sample solution
Video Transcript
This is College Physics Answers with Shaun Dychko. We're given a plastic cube with a known index of refraction we’ll call n subscript c for Cube and it has a known height we’ll call that l. And inside of it is a cube full of gas with an unknown index of refraction n subscript g and this Cuban side has a height which is half that of the outer Cube. So we'll call this inner Cube l over two for its height and we're going to have a ray of light that goes at a known angle of incidence will call it Theta one here and then we'll figure out by how much this Ray is displaced here compared to if the cube was not there compared to this straight line that would go here if the gas was not present to displace the ray. So we're going to measure Delta d , Theta one , index refraction of the cube and the cubes height and knowing that we'll be able to figure out the index of refraction of the gas. So how we're going to do that is first consider this picture where we have in the plastic compared to this point here, the beam will get displaced distance d1 by the time it gets to the top of the gas Cube. And then in the gas is going to get displaced an amount d2. And then in the plastic again, it's going to get displaced an amount d3 here. And so this leg of the triangle is l over four, that's the distance here and that first triangle above the gas Cube and then within the gas Cube, we have a distance of l over two. And then in the plastic again, we have a distance l over four. And so we're going to compare this total distance of d1 plus d2 plus d3 with the distance, if you had no gas ng for no gas and so, you know, it's going to go add an incident angle Theta One have the entire distance l the tire height of the plastic Cube and we can figure out dng by saying that the tangent of this angle Theta One is the opposite over the adjacent. And so that's d no gas divided by l and we'll multiply both sides by l . To solve for distance of with no gas l times Tan Theta One And then we're going to take the difference between that and the total distance when there is gas. So we have these portions d1 and d3 within the plastic and those parts are straightforward to calculate and in each case is going to be Theta One is going to be the opposite d1 or d3 and then tangent of that is going to be that horizontal displacement divided by l over four. And so d1 is l over four times Tan Theta One and now this part for calculating d2 is a bit more involved. So this triangle has faded two here. This is an angle of refraction when it goes through the into the gas and we know that from Snell's law that the index refraction of the cube times sine Theta One is going to equal the index of refraction of the gas times sine Theta two . And we can solve for Theta two by dividing both sides by ng. And then taking the inverse sine of both sides. So Theta two inverse sine of nc sine Theta One over ng and that is something that we can plug into the tangent. So we're going to go d2 is l over two times tangent of Theta two . But Theta two is all of this and so that's where that comes from. So the total with the gas is D1 plus d2 plus d3 , butd3 equals d1 . Because once this beam returns back to the same plastic material of the cube, it's going to return to the same angle here Theta One that is started with up here. And so d3 down here is going to equal d1 up there. And so that's two d1 plus d2 and so that's two times l over four times Tan Theta One plus l over two times Tan of inverse sine nc sine Theta One over ng and this Delta d that we can measure is going to be the difference between the distance with no gas l times Tan Theta One minus all of this. And then we can factor out the l over two here and we get Delta d then is l over two times tan Theta One minus tan of the inverse sine of nc times sine of Theta One over ng. Now this formula we really hard to I don't think you can solve it analytically, you need to use a spreadsheet and solve this numerically to figure out what ng if you keep plugging in different possible possibilities for ng what ng would give you the Delta d that you measure given all these other things that you've also measured and so we solve this numerically and the data we need is the height of the cube, the incident angle, the displacement of the beam with no gas compared to with gas, and the index of refraction of the cube material.


text:
Universe mass

Main Question or Discussion Point

This is my equation for the Universe mass based upon the Lambda-CDM model parameters and the Hubble Space Telescope (HST) and WMAP observational parameters in SI units.

Observable Universe mass composition:
$$H_0 = 2.32987690448613 \cdot 10^{- 18} \; \text{s}^{- 1}$$ - Hubble parameter (WMAP)
$$\Omega_b = 0.00444$$ - Baryon density
$$\Omega_{dm} = (\Omega_m - \Omega_b) = 0.2216$$ - dark matter density
$$dN_s = 10^{22}$$ - HST observable stellar number
$$dV_s = 3.3871 \cdot 10^{78} \; \text{m}^3 \; \; \; (4 \cdot 10^{30} \; \text{ly}^3)$$ - HST observable stellar volume
$$M_{\odot} = 1.9891 \cdot 10^{30} \; \text{kg}$$ - solar mass

Observable Universe mass:
$$\boxed{M_u = \frac{4 \pi M_{\odot}}{3 \Omega_b} \left( \frac{dN_s}{dV_s} \right) \left( \frac{c}{H_0} \right)^3}$$

$$\boxed{M_u = 1.18029735794067 \cdot 10^{55} \; \text{kg}}$$

Gravitationally observable dark matter mass:
$$\boxed{M_{dm} = \frac{4 \pi M_{\odot}}{3} \left( \frac{\Omega_{dm}}{\Omega_b} \right) \left( \frac{dN_s}{dV_s} \right) \left( \frac{c}{H_0} \right)^3}$$

$$\boxed{M_{dm} = 2.61553894519654 \cdot 10^{54}}$$

Hubble critical mass:
$$\boxed{M_c = \frac{c^3}{2 G H_0}}$$
$$\boxed{M_c = 8.66352589042757 \cdot 10^{52} \; \text{kg}}$$

Reference:
"[URL [Broken] law - Wikipedia[/URL]
http://en.wikipedia.org/wiki/Lambda-CDM_model" [Broken]
http://en.wikipedia.org/wiki/Universe" [Broken]
http://en.wikipedia.org/wiki/Observable_universe" [Broken]
http://en.wikipedia.org/wiki/Dark_matter" [Broken]

Last edited by a moderator:

Correction, the Baryon density listed in post #1 is the stellar Baryon density, not the total Baryon density.

The stellar Baryon density ranges between:
$$\Omega_s = \int_{0.004}^{0.005}$$

Last edited:

$$\Omega_s = 0.005$$ - stellar Baryon density

Observable Universe mass:
$$\boxed{M_u = \frac{4 \pi M_{\odot}}{3 \Omega_s} \left( \frac{dN_s}{dV_s} \right) \left( \frac{c}{H_0} \right)^3}$$

$$\boxed{M_u = 1.04810405385132 \cdot 10^{55} \; \text{kg}}$$

Gravitationally observable dark matter mass:
$$\boxed{M_{dm} = \frac{4 \pi M_{\odot}}{3} \left( \frac{\Omega_{dm}}{\Omega_s} \right) \left( \frac{dN_s}{dV_s} \right) \left( \frac{c}{H_0} \right)^3}$$

$$\boxed{M_{dm} = 2.32259858333452 \cdot 10^{54} \; \text{kg}}$$

Hubble critical mass:
$$\boxed{M_c = \frac{c^3}{2 G H_0}}$$

$$\boxed{M_c = 8.66352589042757 \cdot 10^{52} \; \text{kg}}$$

Observable Universe mass greater than or equal to Hubble critical mass:
$$\boxed{M_u \geq M_c}$$

$$\boxed{\frac{4 \pi M_{\odot}}{3 \Omega_s} \left( \frac{dN_s}{dV_s} \right) \left( \frac{c}{H_0} \right)^3 \geq \frac{c^3}{2 G H_0}}$$

Observable Universe mass equivalent to Hubble critical mass:
$$\boxed{M_u = M_c}$$

$$\frac{4 \pi M_{\odot}}{3 \Omega_s} \left( \frac{dN_s}{dV_s} \right) \left( \frac{c}{H_0} \right)^3 = \frac{c^3}{2 G H_0}$$

Observable critical stellar Baryon density:
$$\boxed{\Omega_s = \frac{8 \pi G M_{\odot}}{3 H_0^2} \left( \frac{dN_s}{dV_s} \right)}$$

$$\boxed{\Omega_s = 0.604894627838177}$$

Total matter density:
$$\Omega_m = 0.266$$

According to my calculations, the observable Universe mass is greater than the Hubble critical mass.

What exactly are the cosmological theoretical implications for this criteria?

Last edited:

Observable stellar Baryon critical density:
$$\Omega_s = 0.604894627838177$$

Observable cosmological critical density:
$$\Omega_{\Lambda} = 0.7$$

Reference:
http://en.wikipedia.org/wiki/Lambda-CDM_model" [Broken]

Last edited by a moderator:
malawi_glenn
Homework Helper
Why don't you google 'Hubble critical mass' and publish 'your' results in an article?

Why don't you google 'Hubble critical mass' and publish 'your' results in an article?
All my equations require proofreading by a peer review, prior to any publication.

According to my calculations, the observable Universe mass is greater than the Hubble critical mass.

What exactly are the theoretical cosmological implications for this criteria?

Are my equations and calculations correct?

Last edited:


text:
# Not include listing in list of listing

I would not add to list of listing some of my listings. For example I import my matlab file through \lstinputlisting. What command I should use to not add that code to list of listing?

Option nolol, see "5.7 Captions" of listings' documentation.

• should be nolol (?)... please show how to use it – m13r Dec 1 '16 at 11:45
• @m13r Answer is updated to the current listings 2015/06/04 Version 1.6. – Heiko Oberdiek Dec 6 '16 at 16:54

If I understand you right, you want a special listing not listed in the list of listings. Just use the option nolol for \lstinputlisting. I used a fictive file Test.pas. Please change to what you need.

A short MWE:

\documentclass{article}
\usepackage{listings}

\begin{document}
\lstlistoflistings                                % Table of listings
\lstinputlisting[language=Pascal]{Test.pas}       % listed!
\lstinputlisting[language=Pascal,nolol]{Test.pas} % not listed!
\end{document}


text:
1. May 10, 2013

### Shploop

Hi, I am interested in building a very primitive phased array radar for short ranges(1m to 100m).
I thought it's possible to use a simple 2.4GHz RF ASK transmitter, and by just sending a single '1' bit I could generate a pulse and then use a simple RF receiver for that frequency and analyze the time it took the pulse to return to find range and the frequency shift(doppler) to find the velocity of the object I am tracking.

My problems are:
1)I want this to be as cheap as possible(the RF transmitters/receivers are cheap). This way I get a very simple way to generate a 2.4GHz pulse without building a whole circuit with oscillators etc... but the problem is that I need to send a very small pulse to make this work for such a short range, in the order of nano-seconds.

2)Phase shifters are expensive, although I think I can make variable phase shifter with an all-pass filter.

3)I have little knowledge of antennas(I think a dipole will fit my needs).
and If I am correct, in phased array I need to use the same antenna for RX and TX so I also need some RF switch or Circulator to isolate my RX circuit from the TX circuit so I won't fry it.

4)I need to use minimal amount of array elements to lower cost but still get a decent resolution(like detecting a 20cm(diameter) object.

5)I want to find both range and velocity of an object so I can track it as long as it is in range.

I know all these requirement are insane and if I do make this radar it's going to be nothing like I expect, so if you think this is impossible please stop me before I waste my time :).
But if you have solutions for my problems I would be glad to hear.

Basic diagram of project:

Last edited: May 10, 2013
2. May 10, 2013

### techtribes

you will need a very high prf to do short distances.

3. May 10, 2013

### techtribes

i would say over 30Khz

4. May 10, 2013

### Shploop

Do you mean pulse repetition frequency when you say PRF?
well the 2.4GHz module has a 2MBPS speed so 30KHz PRF is possible but others problems appear, I need to switch the antenna array between transmit and receive quickly enough to receive the echo of an object from such a close range.

Any basic guidelines on short range phased array from an expert in the field :) ?

5. May 10, 2013

### techtribes

You have a transmit frequency which you have established is 2.4 GHz. The prf is separate to the transmit frequency. The prf is how many times you pulse the 2.4 ghz so if your prf is 30Khz that would be pulsing the 2.4 Ghz 30,000 times a second.

6. May 10, 2013

### techtribes

2.4 is way to high

7. May 10, 2013

### techtribes

i would say 80Mhz with a prf of 30Khz

8. May 10, 2013

### sophiecentaur

If you want an interesting project, on which you could learn an awful lot, then go ahead. Otoh, if you want Radar then you may be better to buy a unit for a few hundred quid. There are a lot of non-DIY parts needed, each of which would cost more to buy individually (it's a bit like trying to build a £10k car from available spare parts - it could cost you ten times that much.)
Radar needs a high power transmitter (MWs peak) to give any chance of a significant reflection from a target. That means you need to protect the receiver from the transmitted pulse (proprietary switch I think). The pulse needs to be very short (20cm corresponds to about 1ns) so you would need a magnetron ( which everyone uses for simple radar, afaik)
PRF is not a problem. It's a problem for long distances, when there can be confusion about which pulse you are looking at. You could send pulses once and hour if you wanted to. More frequent just means you improve your signal to noise ratio.
If you use a low frequency (like the suggested "80MHz") the echo from a 20cm target would be far too weak..
What's wrong with a rotating / reciprocating antenna? Phased array is another can of worms for you to tackle. If you need help from an "expert" it means that it will probably be too hard for you. Hardware would cost a lot at 2.4GHz, I think. What angular resolution do you need?
If the target you are tracking could have a transponder on board, life could be a lot easier.
Perhaps giving us a clue about the application details / required spec would help.

9. May 10, 2013

A true phased array is going to be difficult; maybe a simple time of arrival system with two antennas would be simpler. Also if the target is biologic the return signal from a target 20 cm is going to be very low as the absorption will be high. Metal would be less of a problem at 2.4 GHz. Do the path loss calculations to see what kind of signal will return for our target. Using a simple UWB chirp and a simple, fast detector should work if you keep your pulse width under 1 ns. CW-FM might work for you but detecting the Doppler down in the noise is always a problem. See patent US 7551703 to understand how to achieve sub mm resolution with an uwb system you can build for under 50$US. It is a very clever design but the devil is in the details to hit .1 inches at 300 feet. For somebody very skilled and experienced this is a 500 man hour problem. That looks to be a real commitment. Cram 10. May 10, 2013 ### Bobbywhy I cannot know what your level of expertise is regarding phased array radar from your post. If you are just starting out, I’d recommend this to get you launched: http://www.radartutorial.eu/06.antennas/an14.en.html From MIT’s Lincoln Laboratory, here’s a great overview of Phased Array Radar basics, including the new F-35’s airborne fire control radar set. http://www.ofcm.gov/mpar-symposium/2009/presentations/workshop/W1_Herd%20Basics.pdf [Broken] For specifics on F-35 radar, you might start here: http://www.northropgrumman.com/Capabilities/ANAPG81AESARadar/Pages/default.aspx Here’s a course you could take if you can be in Cambridge, Massachusetts this June and have$3,800. to spend:
BUILD A SMALL PHASED ARRAY RADAR SENSOR
Date: June 24-28, 2013 | Tuition: \$3,800 |
COURSE SUMMARY
MIT Professional Education is offering a unique course in the design, fabrication, and testing of a laptop-based digital phased array radar sensor capable of ground moving target imaging (GMTI).

Lots of info and pictures from last year’s MIT program for same project:
http://www.glcharvat.com/Dr._Gregory_L._Charvat_Projects/IAP_phased_array.html

If these sites do not satisfy your quest, I agree with sophiecentaur: give a detailed equipment specification for each desired function. You could work up a cost estimate once you have a clear set of requirements. Better yet, your questions could be addressed here on P.F. in a more utilitarian manner. If you think this will be “cheap” you may find that it will not be.

You’ve said you want to detect a 20 cm (diameter) object. Would that be a baseball, or a metal disc or what? Every material object has a “radar cross-section”. It is roughly the target’s “reflectivity”, so you would need to know this in advance to choose your transmitted power requirement and also, your receiver sensitivity. Other considerations to examine would be what factors determine your transmitting frequency, if and when you will vary the PRF (pulse repetition frequency) at various range bins, the scheme for and resolution of target doppler measurement, beam steering control algorithm for angle tracking (phase shifters), transmitter PW (pulse width) determination for close-in targets (this from basic radar: What factors determine the minimum range?), method for and accuracy required for target range measurement, operator controls, display functions, etc. As for “duplexing”, that is, using the same antenna for both receiving and transmitting, I can tell you that few, if any phased array radars utilize this scheme. Normally there is a plethora of individual receiving and transmitting modules.

The easiest way to create a technical equipment specification is to acquire a real-world example and model yours on it. Often they contain a functional block diagram of the system and a dedicated detailed description of the performance characteristics desired for each block.

Note: just read Cram2000’s comments, posted while I was writing the above. All that he said makes good sense.

Last edited by a moderator: May 6, 2017
11. May 11, 2013

### Shploop

Thanks for all your replies, I am focusing the phased array idea because it's something that's not been done so much before and I can explore different ways to do it and not just copy someone design because it's not as interesting.

techtribes, I choose 2.4ghz because it is available and phased array radars I know use 10GHz or even more. It's a relatively high frequency for these simple RF modules, so I'll get more resolution than a 434MHz RF receiver which is also widely available(higher frequency has smaller wavelength - can't detect and object that is smaller than your wavelength).

Bobbywhy, I already read all these articles(although not thoroughly)and when I mean a 'cheap' radar I meant cheaper than MIT's radar. That radar is really cool but they don't specify any electronics about it and I am not in USA to take that course...

I want to use circuits I make or simple circuits you can buy and connect them so they perform a new function and maybe use new approaches to old problems instead of just buying ready made components that do a certain function and in the process to learn how it all works.

cram thanks for the patent reference, I took a look but it's complex to add something like this to an already complex system.

I've seen real-world examples and they are way too complex and way to expensive.

Lets start simple, if I have these requirements:
*)It needs to be phased array and not SAR/rotating dish.

*)I want to detect both range and doppler.

*)small amount of elements (about 5-12 elements) in the array.

*)Use a 2.4GHz module something like this(use only to transmit):
nRF24L01 module
Other simple replacements will gladly be accepted

*)use an all-pass filter with a digitally controlled variable resistor for variable phase shift:
example of the circuit
Other simple replacements will gladly be accepted

*)range of maximum 30m(minimum 1m) and able to detect 20cm diameter ball(has the same cross section from every angle) - the ball is lets say made of plastic or leather, if too difficult lets say it has metallic surface.

*)can be same antennas transmit or receive or some transmit while others receive(in a way that won't damage the receiver).

I thought about using multiple wi-fi antenna modules like in MIT's project but can't think of a way to change the phase between these modules as I know they work with ASK/FSK/etc and phase has less meaning them and it will be difficult to synchronize phase between these modules to get the "phased array" beam-steering.

by the way, I found a method that might help me - FM ranging as described here:

also found this:
Intro to phased array - I am in interested in the "Passive" phase array as I think it is cheaper and easier to build.

Last edited: May 11, 2013
12. May 11, 2013

### AlephZero

If you are looking at using the Doppler effect, you might think about a laser device instead of radar. That would take the complications of GHz transmitters and receivers out of the design problem and let you start by solving the signal processing problems. A device using a low power (legal) laser pointer as a transmitter should work OK at range of a few meters.

Google for "laser doppler vibrometer" to get some ideas.

13. May 11, 2013

### techtribes

My understanding is you want to detect the velocity and rough direction of an object using a phased antenna. Doing this will also give you a rough position like a ground to air ILS. Using two antenna will give you x and y space telemetry, Z of course would be the planes altimeter. I still say a low frequency at a high amplitude with a high PRF because there will be interference assuming your using it around buildings and trees. And also if the antenna are close to the radio propagation.

14. May 11, 2013

### techtribes

Of course ILS uses two radio frequencies instead of a phased antenna. but the same thing applies as the plane will use two antenna tuned to both frequencies to plot its position. You want to read phase difference in one frequency. Which won’t be that good.

15. May 11, 2013

### Shploop

Well my main requirement is that the radar is NOT a rotating dish because of it's scanning speed limitations, so phased array is the way to go...
I have never thought of using waves in the near-visible/visible part of the spectrum and I know IR light is used to detect range but I don't know if it is used to detect doppler and I need it to be agile enough to detect and track a moving object without mechanical steering...

And I plan on using it in a less cluttered space(like and open field) and directed mostly at the sky, let's say to track something like a football(not really going to track footballs...)

16. May 11, 2013

### marcusl

Strongly suggest you learn something about a) radar, b) antennas, c) phased arrays, d) microwave electronics and e) digital signal processing before starting this project. Based on your postings, your current state of knowledge is not up to the job in these areas. To give just a single example, your 1 ns pulse requires a 1 GHz bandwidth for all system components (transmitter, antenna, receiver, sampler and processor) making this an extremely challenging and sophisticated system.

Bobbywhy gave you a good list. Here are other suggestions:
• Stimson, Intro to Airborne Radar (2nd ed.) A gentle but very thorough introduction to radar with many diagrams and pictures.
• Antenna books by Kraus or Balanis cover antenna and phased array basics
• Mailloux, Phased Array Handbook gives nitty gritty details of phased array design
• Oppenheim and Schafer, Discrete Signal Processing or any one of dozens of similar texts to learn DSP

Last edited: May 11, 2013
17. May 12, 2013

### Shploop

Thanks for the books list, I was looking for some recommendations on good books on the subject, I have a book about Antennas I just started reading "Antenna theory".

Well my whole idea was to make something known from different components - kind of a "hack" that 2.4ghz module for different purpose but I guess it's too complex to do it without a big budget and an MIT course...

Thank you all for your replies.


text:
# nLab associative quasigroup

Contents

### Context

#### Algebra

higher algebra

universal algebra

## Theorems

group theory

### Cohomology and Extensions

#### Representation theory

representation theory

geometric representation theory

# Contents

## Definitions

A (left/right/two-sided) associative quasigroup is a (left/right/two-sided) quasigroup $(G, \cdot,\backslash,/)$ where $a \cdot (b \cdot c) = (a \cdot b) \cdot c$ for all $a$, $b$, and $c$ in $G$.

In every associative quasigroup $G$, $a/a = b\backslash b$ for every $a$ and $b$ in $G$. This is because for every $a$ and $b$ in $G$, $b \cdot a = b \cdot (a/a) \cdot a = b \cdot (b\backslash b) \cdot a$. Left dividing both sides by $b$ and right dividing both sides by $a$ results in $a/a = b\backslash b$. This means in particular that $a/a = a\backslash a$, which means that every associative quasigroup is a possibly empty loop. Thus, an associative quasigroup is a associative possibly empty loop, or a possibly empty group. In particular, there is an additional definition of an associative quasigroup in terms of the left and right divisions alone, without any semigroup operation at all:

A left associative quasigroup is a set $G$ with a binary operation $(-)\backslash(-):G \times G \to G$ (a magma) such that:

• For all $a$ and $b$ in $G$, $a\backslash a=b\backslash b$
• For all $a$ in $G$, $(a\backslash (a\backslash a))\backslash (a\backslash a)=a$
• For all $a$, $b$, and $c$ in $G$, $(a\backslash b)\backslash c= b\backslash ((a\backslash (a\backslash a))\backslash c)$.

For any element $a$ in $G$, the element $a\backslash a$ is called a right identity element, and the element $a\backslash (a\backslash a)$ is called the right inverse element of $a$. For all elements $a$ and $b$ in $G$, left multiplication of $a$ and $b$ is defined as $(a\backslash (a\backslash a))\backslash b$.

A right associative quasigroup is a set $G$ with a binary operation $(-)/(-):G \times G \to G$ such that:

• For all $a$ and $b$ in $G$, $a/a=b/b$
• For all $a$ in $G$, $(a/a)/((a/a)/a)=a$
• for all $a$, $b$, and $c$ in $G$, $a/(b/c)=(a/((c/c)/c)/b$

For any element $a$ in a $G$, the element $a/a$ is called a left identity element, and the element $(a/a)/a$ is called the left inverse element of $a$. For all elements $a$ and $b$, right multiplication of $a$ and $b$ is defined as $a/((b/b)/b)$.

An associative quasigroup is a possibly empty left and right group as defined above such that the following are true:

• left and right identity elements are equal (i.e. $a/a = a \backslash a$) for all $a$ in $G$

• left and right inverse elements are equal (i.e. $(a/a)/a = a\backslash (a\backslash a)$) for all $a$ in $G$

• left and right multiplications are equal (i.e. $a/((b/b)/b) = (a\backslash (a\backslash a))\backslash b$) for all $a$ and $b$ in $G$.

This definition first appeared on the heap article and is due to Toby Bartels.

## Pseudo-torsors

Every left associative quasigroup $G$ has a pseudo-torsor $t_G:G^3 \to G$ defined as $t_G(x,y,z) = x \cdot (y \backslash z)$. Every right associative quasigroup $H$ has a pseudo-torsor $t_H:H^3 \to H$ defined as $t_H(x,y,z) = (x / y) \cdot z$. This means every associative quasigroup has two pseudo-torsors. If the (left or right) associative quasigroup is inhabited, then those pseudo-torsors are actually torsors or heaps.

## Category of associative quasigroups

An associative quasigroup homomorphism is a semigroup homomorphism between associative quasigroups that preserves left and right quotients. Associative quasigroup homomorphisms are the morphisms in the category of associative quasigroups $AssocQuasiGrp$.

As the category of associative quasigroups is a concrete category, there is a forgetful functor $U:AssocQuasiGrp \to Set$. $U$ has a left adjoint, the free associative quasigroup functor $F:Set \to AssocQuasiGrp$.

The empty associative quasigroup $0$ whose underlying set is the empty set is the initial associative quasigroup, and is strictly initial. The trivial associative quasigroup $1$ whose underlying set is the singleton is the terminal associative quasigroup.

The direct product $G \times H$ of associative quasigroups $G$ and $H$ is the cartesian product of sets $U(G) \times U(H)$ with an associative quasigroup structure defined componentwise by

$(g_1, h_1) \cdot_{G \times H} (g_2, h_2) = (g_1 \cdot_G g_2, h_1 \cdot_H h_2)$
$(g_1, h_1) /_{G \times H} (g_2, h_2) = (g_1 /_G g_2, h_1 /_H h_2)$
$(g_1, h_1) \backslash_{G \times H} (g_2, h_2) = (g_1 \backslash_G g_2, h_1 \backslash_H h_2)$

for all $(g_1, h_1), (g_2, h_2) \in U(G) \times U(H)$, with product projections $p_G: G \times H \to G$ $p_H: G \times H \to H$ where $p_G(g, h) = g$ and $p_H(g,h) = h$ for all $(g,h)\in G \times H$ The direct product of associative quasigroups is thus the cartesian product in $AssocQuasiGrp$. The endofunctor $P(G) = G \times 1$ is the identity functor on $AssocQuasiGrp$ while the endofunctor $P(G) = G \times 0$ is a constant functor that sends every associative quasigroup to $0$.

An associative subquasigroup of an associative quasigroup $G$ is an associative quasigroup $H$ with an associative quasigroup monomorphism

$H \hookrightarrow G \,.$

The empty associative is the initial associative subquasigroup of $G$.

Let $G$ and $H$ be associative quasigroups and let $f:G \to H$ be an associative quasigroup homomorphism. Then given an element $h \in H$, there is an associative subquasigroup

$i: I \hookrightarrow G \,.$

such that $g \in I$ if and only if $f(g) = h$. $I$ is called the fiber of $f$ over $h$.

Because $AssocQuasiGrp$ has a terminal object, cartesian products, and fibers, it is a finitely complete category.

Every associative quasigroup $G$ and associative subquasigroup $H \hookrightarrow G$ has a set of left ideals $G H$ in $G$ and a set of right ideals $H G$ in $G$.

## Examples

• Every group is an associative quasigroup.

• The empty associative quasigroup is an associative quasigroup that is not a group.

## References

Last revised on August 4, 2022 at 04:50:54. See the history of this page for a list of all contributions to it.


text:
# Does this month start on a Monday?

June 2020 is a month in which June 1st corresponds to Monday, June 2nd corresponds to Tuesday, ... June 7th corresponds to Sunday. For reference, here's the cal of June 2020.

      June 2020
Su Mo Tu We Th Fr Sa
1  2  3  4  5  6
7  8  9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30

Given a year and a month in the format [year, month], output two distinct values that tell whether this month starts on a Monday.

## Test cases

[2020,6] -> True
[2021,2] -> True
[1929,4] -> True

[1969,1] -> False
[1997,5] -> False
[2060,1] -> False

## Specification

• The input can be in any format you prefer for your answer, e.g. numeric list, numeric tuple, etc. It doesn't have to be taken in this rigid format (it's JSON by the way).
• However, making the input a Date object is a loophole here. You shouldn't make the input a Date object.
• The month in the input doesn't have to be 1-indexed - it can also be 0-indexed.
• You need to support all years after 1582 (the start of the Proleptic Gregorian calendar), up to the year 9999.
• Is this asking, in less jargony terms, "does the given month start on a Monday"? The question is kind of hard to parse – pppery Jun 14 '20 at 1:20
• I suggest scrapping the entire challenge text and replacing it with: Given a year and a month, answer whether the given month begins with a Monday in the given year. – Adám Jun 14 '20 at 1:49
• @MitchellSpector Unless anything specific is stated, you can assume that default I/O rules apply. (And the format used happens to be JSON, a very well-supported standard.) – Adám Jun 14 '20 at 2:15
• I asked because the challenge specifically says "in the format [year, month]". That implies to me a rigid input format (how else would a rigid input format be expressed?). I agree with what I think is your implication that the challenge would be better with the usual default I/O rules. I think OP should clarify this. @Adám – Mitchell Spector Jun 14 '20 at 2:18
• How large a year range do we have to support? For instance, certain hundred years skip the leap day, and year -1 coming directly before year 1 doesn't work well with some number types. – SE - stop firing the good guys Jun 14 '20 at 12:22

# Japt-!, 6 5 bytes

ÓÐN e

Try it

ÓÐN e     :Implicit input of integers U=y and V=m
Ð        :Create date object from
N       :  The array of inputs [U,V] with the date defaulting to the 1st
e     :0-indexed day of the week
Ó         :Decrement
:Implicit output of Boolean negation

• Looks like our "Try it" link shows that your solution does not produce the correct results. – Thomas Jun 17 '20 at 5:32
• Depends on your locale, @Thomas. – Shaggy Jun 18 '20 at 13:57

# Ruby, 26 24 bytes

->d{Time.gm(*d).monday?}

Try it online!

You'll never guess what this does.

Edit: -2 bytes from Dingus.

# Excel, 44 342319 18 bytes

=2=MOD(A3&"-"&A2,7

-11 thanks to Adam and -4 thanks to Shazback

-1 thanks to this

=(TEXT(DATE(A2,A3,1),"ddd")="Mon")

Ensure that the year is placed in cell A2 and the month in A3.

:( Crossed out 44 is still 44.

• =2=MOD(DATE(A2,A3,1),7) – Adám Jun 14 '20 at 2:22
• You removed the final closing parenthesis. While I'm not to comment on the validity of that, what you have now is only 22 bytes. – Adám Jun 14 '20 at 2:43
• Doesn't Google Sheets auto-close parentheses? – Shaggy Jun 14 '20 at 8:24
• 1 byte can be saved by abusing the Date function's default value: =1=mod(date(A2,A3,),7) – Shazback Jun 15 '20 at 10:45
• 24 bytes - but quite readable for a golf: =WEEKDAY(DATE(A2,A3,))=1 – David258 Jun 15 '20 at 15:14

# Bash + GNU utilities, 25 22 19 bytes

date -d$1-1|grep ^M  Try it online! The input is passed as an argument in the format year-month, and the output is the exit code (0 for truthy, 1 for falsey, as usual). • It assumes being run on an english locale. – Amessihel Jun 16 '20 at 0:25 • @Amessihel That's true. Of course, the question was in English, and TIO doesn't even seem to have any non-English locales available. – Mitchell Spector Jun 16 '20 at 1:16 • date -d$1-1 +%u would be more universal and has 15 bytes, but will print numbers 1-7, which is not what OP requested. – pLumo Jun 17 '20 at 7:03
• @pLumo Yes -- in fact, if you check the edit history, my first version worked that way: date +%u -d$1-$2-1|grep 1 was the code. But that's 25 bytes, including the grep at the end to check for the numerical code for Monday, so that it meets OP's specs. codegolf.stackexchange.com/revisions/206071/1 (I could take off 3 bytes with the more liberal input criteria OP provided in response to a question, using $1 instead of $1-$2, but that would still only get down to 22 bytes.) – Mitchell Spector Jun 17 '20 at 16:24 # JavaScript (ES61), 33 26 25 bytes 1: This works in Chrome, Node and Edge Chromium Saved 7 bytes thanks to @Shaggy Saved 1 byte thanks to @l4m2 Using a built-in. Takes input as ([year, month]). a=>/^M/.test(new Date(a))  Try it online! ## How? ### Converting the input to a Date object The Date() constructor expects either: Date(year, month [ , date [ , hours [ , minutes [ , seconds [ , ms ] ] ] ] ])  or: Date(value)  In the first syntax, month must be 0-indexed. In the second syntax, value is coerced to a string (unless it's undefined or it's an object) and parsed as such. Therefore, a 1-indexed month is expected in that case. According to the ECMAScript specification: The function first attempts to parse the format of the String according to the rules (including extended years) called out in Date Time String Format (20.3.1.15). If the String does not conform to that format the function may fall back to any implementation-specific heuristics or implementation-specific date formats. So [2020,6] is turned into "2020,6" and parsed using implementation-specific heuristics which happen to work in V8-based engines when a comma is used as a separator. This also works with several other symbols. ### Regular expression When passed as the argument of /^M/.test(), the Date object is implicitly converted into a string in the following format: "DDD MMM 01 YYYY 00:00:00 GMT[...]"  where: • DDD is the 3-letter abbreviation of the day of the week • MMM is the 3-letter abbreviation of the month • YYYY is the year in numerical format Therefore, the string begins with a "M" iff the day of the week is Monday. # JavaScript (ES6), 62 61 60 bytes Using a formula. Takes input as (year)(month), where month is 0-indexed. y=>m=>(y-=m<2,y+=(y&~3)-3*~~(y/100)>>2)%7=='045204263153'[m]  Try it online! • 26 bytes – Shaggy Jun 14 '20 at 8:14 • @Shaggy Nice. I don't think I've ever seen this trick before. I guess the Date constructor basically accepts any separator between the numbers. – Arnauld Jun 14 '20 at 8:28 • The strangest part of it to me is that the month is now 1-indexed. – Shaggy Jun 14 '20 at 9:19 • @Shaggy I've added an explanation. Please let me know if you think something is inaccurate. – Arnauld Jun 14 '20 at 10:00 • 25 – l4m2 Jun 15 '20 at 8:26 # APL (Dyalog Unicode) 18.0, 9 bytes (SBCS) Anonymous tacit prefix function. 1=7|1⎕DT⊂  Try it online! (uses a model, ∆DT, instead of ⎕DT so it can run using TIO's current version) ⊂ enclose the argument (because we need the date to be a scalar) 1⎕DT convert Date-Time to days since 1899-12-31 (this will "pad" the date to the first of the month) 7| division remainder when divided by 7 1= does one equal that? # Wolfram Language 36 bytes DayName@DateObject@{#,#2,1}==Monday&  examples Naming the function f, to save space and increase clarity. f = DayName@DateObject@{#, #2, 1} == Monday & f[2020, 6] f[2021, 2] f[1929, 4] f[1969, 1] f[1997, 5] f[2060, 1] (*True*) (*True*) (*True*) (*False*) (*False*) (*False*)  # Red, 33 bytes func[b][1 = pick(to now b)+ 1 10]  Try it online! The argument bis a block containing the year and the month. now is function returning the current date and time; to now b converts the input to a date! datatype. The odd thing is that currently Red assigns the missing data (the day of month) 0 by default, but Red being 1-indexed, thus calculates the last day of the previos month instead of the first day of the given month: to now [2020 6] gives 31-May-2020 That's why I add 1 to the resulting date. date! has among its path accessors /weekday, wich can be queried using indexing instead - 10 (tenth item). Too bad I can't use direct indexing using paths /10, because it only works on words (variables) and not on literal / unnamed data. That's why I use pickdate 10. Finally I check if the weekday is 1 (for Monday). # T-SQL, 47 bytes SELECT 1/datepart(w,datefromparts(y,m,7))FROM i  (10 bytes saved thanks to @t-clausen.dk) Assumes the input is in a table i with two columns, y and m. It assumes Sunday is set as the first day of week, which is the default setting. Outputs 1 if the month starts on a Monday, 0 otherwise. datepart(w,datefromparts(y,m,7)), the day of week of the seventh day of the month returns 1 (=Sunday) if the month starts on a Monday, and a higher number otherwise. Since it's an integer, the division is rounded down to zero in the latter case. Demo • nice first answer. I hope to see more SQL answers. This will not work on all servers. It depends on the datefirst setting. SET datefirst 7 would ensure it works – t-clausen.dk Jun 15 '20 at 8:06 • you can save a few bytes: 1/datepart(w,datefromparts(y,m,7)) – t-clausen.dk Jun 15 '20 at 8:33 • Thanks, that's a nice trick. – Glorfindel Jun 15 '20 at 8:51 • Sunday is the default setting for some languages. I know Germany, Denmark, Norway. Sweden and alot of other countries uses different defaults. So you can't release this code for production - but this doesn't matter for Codegolf, as long as your Demo works – t-clausen.dk Jun 15 '20 at 18:09 # 05AB1E, 36 bytes Ð3‹12*+>₂*T÷s3‹Xα©т%D4÷®т÷©4÷®·(O7%Θ  Here we go again. 05AB1E has no date builtins, so everything is done manually. This solution is a derivative of my answer here. Takes both inputs separated, the $$\month\$$ as first input and $$\year\$$ as second. Explanation: The general formula to calculate the Day of the Week manually is: $${\displaystyle h=\left(q+\left\lfloor{\frac{13(m+1)}{5}}\right\rfloor+K+\left\lfloor{\frac{K}{4}}\right\rfloor+\left\lfloor{\frac{J}{4}}\right\rfloor-2J\right){\bmod{7}}}$$ Where for the months March through December: • $$\q\$$ is the $$\day\$$ of the month ([1, 31]) • $$\m\$$ is the 1-indexed $$\month\$$ ([3, 12]) • $$\K\$$ is the year of the century ($$\year \bmod 100\$$) • $$\J\$$ is the 0-indexed century ($$\\left\lfloor {\frac {year}{100}}\right\rfloor\$$) And for the months January and February: • $$\q\$$ is the $$\day\$$ of the month ([1, 31]) • $$\m\$$ is the 1-indexed $$\month + 12\$$ ([13, 14]) • $$\K\$$ is the year of the century for the previous year ($$\(year - 1) \bmod 100\$$) • $$\J\$$ is the 0-indexed century for the previous year ($$\\left\lfloor {\frac {year-1}{100}}\right\rfloor\$$) Resulting in in the day of the week $$\h\$$, where 0 = Saturday, 1 = Sunday, ..., 6 = Friday. Source: Zeller's congruence Since we only care about $$\q=1\$$, we can use that to golf 2 bytes. With the formula above, the result would be $$\2\$$ for Mondays (and thus requiring a leading $ to push both 1 AND the input-month; as well as a trailing 2Q to check if the result equal 2). But if we remove the $$\q+\$$ part, the result would be $$\1\$$ for Mondays (in which case we can use the implicit input-month, removing the $; and also use the ==1 builtin Θ instead of 2Q). Ð # Triplicate the (implicit) input-month 3‹ # Check if the month is below 3 (Jan. / Feb.), # resulting in 1 or 0 for truthy/falsey respectively 12* # Multiply this by 12 (either 0 or 12) + # And add it to the month # This first part was to make Jan. / Feb. 13 and 14 > # Month + 1 ₂* # Multiplied by 26 T÷ # Integer-divided by 10 s3‹ # Check if the month is below 3 again (resulting in 1 / 0) Iα # Take the absolute difference with the second input-year © # Store this potentially modified year in the register т% # mYear modulo-100 D4÷ # mYear modulo-100, integer-divided by 4 ®т÷©4÷ # mYear integer-divided by 100, and then integer-divided by 4 ®·( # mYear integer-divided by 100, doubled, and then made negative O # Take the sum of all values on the stack 7% # And then take modulo-7 to complete the formula, # resulting in 0 for Sunday, and [1, 6] for [Monday, Saturday] Θ # Check if this is equal to 1 (thus a Monday) # (after which the result is output implicitly)  Note that I've also used $$\\left\lfloor{\frac{26(m+1)}{10}}\right\rfloor\$$ instead of $$\\left\lfloor{\frac{13(m+1)}{5}}\right\rfloor\$$, since 05AB1E has a 1-byte builtin for both 26 and 10 (₂ and T respectively), saving a byte on the 13. # Julia 1.0, 39 bytes using Dates x*y=dayofweek(Date(x,y))==1  Try it online! I am posting this seperate from my other answer, since it doesn't use the point-free style, and thus doesn't have the cool side-benifits of also working for year only etc. But it is shorter # Python 2, 56 bytes lambda y,m:date(y,m,1).weekday()<1 from datetime import*  Try it online! # C (gcc), 61 60 59 bytes Saved a byte thanks to ceilingcat!!! Saved a byte thanks to nununoisy!!! f(y,m){y-=m<2;m=(y+y/4-y/100+y/400+"bed=pen+fad."[m])%7<1;}  Try it online! Straight-up calculation that uses 0-based months. • 59 bytes if you use 0-indexed months: Try it online! – nununoisy Jun 15 '20 at 7:22 • @nununoisy Yes of course, was using a byte up in that string just to make it 1-based. Nice one = thank! :D – Noodle9 Jun 15 '20 at 10:06 # Perl 5-MTime::Local -pa, 38 33 bytes Shaved 5 bytes with help from @DomHastings $_=(gmtime timegm 0,0,0,1,@F)=~Mo

Try it online!

Input is space separated: 0-indexed month followed by year.

• Nice, I wasn't getting anything competitive with core functions... You can save a few bytes dropping the / around the regex and using @F instead of <>,$_ too: Try it online! – Dom Hastings Jun 15 '20 at 16:02 # Java (JDK), 35 bytes m->{m.set(5,1);return m.get(7)==2;}  Try it online! ## Explanation The input is taken as a java.util.Calendar. First we modify the calendar to force the first of the month, then we check if that day of week is a Monday. m -> { m.set(Calendar.DAY_OF_MONTH, 1); // DAY_OF_MONTH is the constant 5 return m.get(Calendar.DAY_OF_WEEK) // DAY_OF_WEEK is the constant 7 == Calendar.MONDAY // MONDAY is the constant 2. Don't ask why, no one knows. }  # Retina 0.8.2, 108 bytes \d+$*
^(11? )1
12$*1$1
\G1
13$* (1+)\1{4}1{27,} (?=(1*)\2{399})(?=(1*)\3{3})(1*)(?=\4{99})$1$2$3
^(1{7})*$ Try it online! Link includes speedup ^ so that the included test cases complete within TIO's time limit. Takes 1-indexed month first, then the year. Explanation: \d+$*

Convert to unary.

^(11? )1
12$*1$1

If the month is January or February, then add 12 and subtract 1 from the year.

\G1
13$*  Multiply the month by 13, which begins a form of Zeller's congruence. (1+)\1{4}1{27,} (?=(1*)\2{399})(?=(1*)\3{3})(1*)(?=\4{99})$1$2$3

The month is integer divided by 5, but with 27 subtracted, which allows the calculation to result in Monday = 0. The year is separately divided by both 400 and 4, after which 1% of the year is skipped thus effectively subtracting it. The month calculation, y/400 and y/4 are then added to the remaining (y-y/100). Note that Retina will attempt to match this expression more than once but will always fail because there is only one space in the input. However, these attempts make it very slow, so to optimise this the TIO link includes a leading ^. The code will work without it eventually though.

^(1{7})*$ Test whether the result is a multiple of 7. # Julia 41 bytes (37 characters) using Dates isequal(1)∘dayofweek∘Date  It's fairly rare to find a code-golf that can be answered in point-free style in Julia. An interesting side effect of this, is that if you give this just 1 input it will tell you if the year starts with a Monday. And if you give it 3 inputs it will tell you if a given day is a Monday. # R, 39 bytes strftime(paste0(scan(,''),'-1'),'%u')<2  Try it online! # PHP 7.4, 43 bytes This code creates an anonymous function where you pass the month and year, returning true for monday, and false if the 1st day it isn't on a monday. fn($Y,$M)=>!~-date(N,strtotime("$Y-$M-1"));  An alternative solution could be just this (40 bytes): fn($Y,$M)=>date(N,strtotime("$Y-$M-1"));  Which returns the week day, where 1 is monday, 2 is tuesday .... I don't think this is in the spirit of the question. # Python 3.8, 80 bytes from calendar import Calendar as C f=lambda x:C().monthdayscalendar(*x)[0][0]==1  Try it online! • This can be shorter with from calendar import*. – ovs Jun 15 '20 at 8:04 # T-SQL, 43 bytes PRINT datediff(d,0,concat(@+@y*100,14))%7/6  the expression datediff(d,0,concat(@+@y*100,14))%7  will return 0-6. 6 represent Monday - this is divided by 6(rounding off) Mondays returns 1, other weekdays returns 0 Try it online # brainfuck, 582 bytes ->+++[[>]>,>++++++[<-------->-]<[<++++++++++>-],>++++++[<-------->-]<[<+>-]+[-<+]->-]>>>[->>>>+>+<<<<<]>>>>[<<<<+>>>>-]<+>>>+++<+>+<[->-[>]<<]<[-]<[-<<<<->>>]>[-]>[-]>[-]>[-]>[-]+++>++>+++++>>+++>+++++>+>++++>++++++>++>+++++[-<+]->>>>[>>+>+<<<-]>>[>>>[-<<<<+>>>>]<<[->+<]<[->+<]>-]>>>[-<+<<+>>>]<<<[->>>+<<<]>[[-<+>]>[-<+>]<<<<[->>>>+<<<<]>>-]>>++++++++++[<+++++++>-]<<<<<<<[>>+>>>>--<<<<<<-]>>[-[->>+<]>[<]<]>>[-[->>+<]>[<]<]<<<[->+>>>>+<<<<<]>[-[->>+<]>[<]<]>>[-[->>+<]>[<]<]>>[-<<<<<<<+>>>>>>>]<<<<<<+++++++<<+>[>->+<[>]>[<+>-]<<[<]>-]>[-]+>[[-]<->]<[->+<]>>++++++++[<++++++>-]<.  Try it online! Definitely not the shortest program here, this was more to see if it was possible to do. Expects input in the form of YYYYMM - the month needs to be 1-indexed and 2 characters wide. Outputs 1 if the month starts on Monday, 0 otherwise. This could be shortened by 21 bytes if the output was not ASCII. Ungolfed: -> reference +++[ input 3 sets of 2 numbers [>] find next zero >,>++++++[<-------->-]< input number and sub 48 ascii [<++++++++++>-] mul by 10 ,>++++++[<-------->-] input next number and sub 48 <[<+>-] copy to previous cell +[-<+]- move back to reference >- dec counter ] end input >>> [->>>>+>+<<<<<] copy the month variable for comparison >>>>[<<<<+>>>>-]<+>>>+++<+>+<[->-[>]<<] <[-]<[-< if month is less than 3 <<<->>> decrement the year ]>[-]>[-]>[-]>[-]>[-] clear out comparison cells to store lookup table 0 3 2 5 0 3 5 1 4 6 2 4 +++>++>+++++>>+++>+++++>+>++++>++++++>++>++++ lookup table +[-<+]- move back to reference >>>> move to month [>>+>+<<<-] >>[>>>[-<<<<+>>>>]<<[->+<]<[->+<]>-] access lookup table for month >>>[-<+<<+>>>]<<<[->>>+<<<]> [[-<+>]>[-<+>]<<<<[->>>>+<<<<]>>-] copy table value to result >>++++++++++[<+++++++>-]<<<<<<< add 70 to result to prevent wrap [>>+>>>>--<<<<<<-] >>[-[->>+<]>[<]<] >>[-[->>+<]>[<]<] add century div by 4 <<<[->+>>>>+<<<<<]> add year [-[->>+<]>[<]<] >>[-[->>+<]>[<]<]>> add year div by 4 [-<<<<<<<+>>>>>>>] set up modulo <<<<<<+++++++<<+>[>->+<[>]>[<+>-]<<[<]>-] all modulo 7 >[-]+>[[-]<->]<[->+<]>>++++++++[<++++++>-]<. display result  # Befunge-93, 81 78 bytes &&:2!#v_2->267+**2-55+/\:"d"/02-*\:"d"%\:"d"%4/\"d"/4/++++7%!.@ -1\++55< ^\  Try it online! ## How does it work? This is based on a formula which gives the day of the week given a date: W = (k + floor(2.6m - 0.2) - 2C + Y + floor(Y/4) + floor(C/4)) mod 7  where • k is the day of month, • m is the month of the year, if years start with March (so Mar = 1, Apr = 2, ..., Dec = 10, Jan = 11, Feb = 12). • C is the century of the March adjusted year (so year = year - 1 in January and February). • Y is the year in the century (March adjusted). • W is the weekday, (Sun = 0, ..., Sat = 6). We will be calculating W' = floor((26m - 2)/10) - 2C + Y + floor(Y/4) + floor(C/4)) mod 7  the month will start with a Monday, iff W' == 0. Breaking down the program gives us: && Reads year and month :2!#v_2-> If the month is January or February, subtract 1 from -1\++55< ^\ the year, and add 10 to the month; else, subtract 2 from the month. (Years start in March). 267+**2-55+/ Calculate (2.6 * month - 0.2). \:"d"/02-* -2 * Century (= int (year / 100)) \:"d"% Year in century (year % 100) \:"d"%4/ 4 year leap year cycle adjustment (int ((year % 100) / 4)) \"d"/4/ 400 year leap year cycle adjustment (int (int (year / 100) / 4)) ++++ Sum them all 7% Mod 7. !.@ Negate the result and print it -- if 0 (hence, first day of the month is a Monday), then 1, else (not a Monday) 0.  Edit: Saved three bytes. # Python 3.8 (pre-release), 53 bytes lambda x:date(*x,1).weekday()<1 from datetime import*  Try it online! # Bash + Standard Unix Tools, 17 bytes cal$1|grep ' 6$'  • Input like "06 2020". • Exit Code is 0 if first day of month is Monday and 1 if not. Try it online! In some implementations, additional two bytes are necessary:  cal$1|grep ' 6 *$'  # PowerShell, 28 21 bytes (d$i -U %A)-like'M*'

Try it online!

# Perl 5, 44 bytes

say 1==(gmtime timegm 0,0,0,1,-1+pop,pop)[6]

Try it online!

# Charcoal, 43 bytes

ＮθＮη≧⁻‹η³θ¬﹪Σ⟦θ÷θ⁴±÷θ¹⁰⁰÷θ⁴⁰⁰Ｉ§”)➙⊟-�=.”η⟧⁷

Try it online! Link is to verbose version of code. Takes 1-indexed month and outputs a Charcoal boolean, i.e. - for Monday, no output otherwise. Explanation:

ＮθＮη

Input the year and the month.

≧⁻‹η³θ

Decrement the year if the month is January or February.

¬﹪Σ⟦θ÷θ⁴±÷θ¹⁰⁰÷θ⁴⁰⁰Ｉ§”)➙⊟-�=.”η⟧⁷

Calculate the number of leap years and adjust for the month using a cyclic lookup table 403250351462, then output whether the result is zero (mod 7).

# q, 33 32 bytes

accepting the inputs as strings:

{2=mod["d"$"M"$x,".",-2#"0",y]7}

explanation

                     -2#"0",y    /append "0" to 2nd input and take last 2 chars from result
x,".",            /join by "."
"M"$/tok, convert string to month type "d"$                      /cast to date type - returns 1st of month
mod[                      ]7  /date mod 7, 0->sat,1->sun,2->mon,etc
2=                              /check if equal 2

run like:

q){2=mod["d"$"M"$x,".",-2#"0",y]7}["1929";"4"]
1b

# JavaScript, 45 bytes

n=>(''+new Date(n[0]+'-'+n[1]+'-01'))[0]=='M'

Takes input as an array like [2020, 6].

## How it works

Converts the date object to a string then checks if the first character is an M.


text:
# NNabla Python API Demonstration Tutorial¶

Let us import nnabla first, and some additional useful tools.

import nnabla as nn  # Abbreviate as nn for convenience.

import numpy as np
%matplotlib inline
import matplotlib.pyplot as plt

2017-06-26 23:11:00,013 [nnabla][INFO]: Initializing CPU extension...

## NdArray¶

NdArray is a data container of a multi-dimensional array. NdArray is device (e.g. CPU, CUDA) and type (e.g. uint8, float32) agnostic, in which both type and device are implicitly casted or transferred when it is used. Below, you create a NdArray with a shape of (2, 3, 4).

a = nn.NdArray((2, 3, 4))

You can see the values held inside a by the following. The values are not initialized, and are created as float32 by default.

print a.data

[[[ -8.57284198e+09   4.56907377e-41  -8.57284198e+09   4.56907377e-41]
[  0.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+00]
[  0.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+00]]

[[  0.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+00]
[  0.00000000e+00   0.00000000e+00   6.74024561e-43   0.00000000e+00]
[ -8.57256346e+09   4.56907377e-41  -8.57256346e+09   4.56907377e-41]]]

The accessor .data returns a reference to the values of NdArray as numpy.ndarray. You can modify these by using the Numpy API as follows.

print '[Substituting random values]'
a.data = np.random.randn(*a.shape)
print a.data
print '[Slicing]'
a.data[0, :, ::2] = 0
print a.data

[Substituting random values]
[[[-0.44771791  0.37770718  0.13974769 -0.7574079 ]
[-0.69822484  0.72812998  0.65710258  1.39894378]
[ 2.45816112  0.14256425 -0.10612717  0.37355551]]

[[-1.26604652 -1.17278957  0.93183202 -1.35603702]
[-0.37144065 -0.10313081 -0.89111573 -1.47255397]
[ 0.62756163 -0.6097846   1.48144531  0.41393015]]]
[Slicing]
[[[ 0.          0.37770718  0.         -0.7574079 ]
[ 0.          0.72812998  0.          1.39894378]
[ 0.          0.14256425  0.          0.37355551]]

[[-1.26604652 -1.17278957  0.93183202 -1.35603702]
[-0.37144065 -0.10313081 -0.89111573 -1.47255397]
[ 0.62756163 -0.6097846   1.48144531  0.41393015]]]

Note that the above operation is all done in the host device (CPU). NdArray provides more efficient functions in case you want to fill all values with a constant, .zero and .fill. They are lazily evaluated when the data is requested (when neural network computation requests the data, or when numpy array is requested by Python) The filling operation is executed within a specific device (e.g. CUDA GPU), and more efficient if you specify the device setting, which we explain later.

a.fill(1)  # Filling all values with one.
print a.data

[[[ 1.  1.  1.  1.]
[ 1.  1.  1.  1.]
[ 1.  1.  1.  1.]]

[[ 1.  1.  1.  1.]
[ 1.  1.  1.  1.]
[ 1.  1.  1.  1.]]]

You can create an NdArray instance directly from a Numpy array object.

b = nn.NdArray.from_numpy_array(np.ones(a.shape))
print b.data

[[[ 1.  1.  1.  1.]
[ 1.  1.  1.  1.]
[ 1.  1.  1.  1.]]

[[ 1.  1.  1.  1.]
[ 1.  1.  1.  1.]
[ 1.  1.  1.  1.]]]

NdArray is used in Variable class, as well as NNabla’s imperative computation of neural networks. We describe them in the later sections.

## Variable¶

Variable class is used when you construct a neural network. The neural network can be described as a graph in which an edge represents a function (a.k.a operator and layer) which defines operation of a minimum unit of computation, and a node represents a variable which holds input/output values of a function (Function class is explained later). The graph is called “Computation Graph”.

In NNabla, a Variable, a node of a computation graph, holds two NdArrays, one for storing the input or output values of a function during forward propagation (executing computation graph in the forward order), while another for storing the backward error signal (gradient) during backward propagation (executing computation graph in backward order to propagate error signals down to parameters (weights) of neural networks). The first one is called data, the second is grad in NNabla.

The following line creates a Variable instance with a shape of (2, 3, 4). It has data and grad as NdArray. The flag need_grad is used to omit unnecessary gradient computation during backprop if set to False.

x = nn.Variable([2, 3, 4], need_grad=True)
print 'x.data:', x.data

x.data: <NdArray((2, 3, 4)) at 0x7f5e93877120>
x.grad: <NdArray((2, 3, 4)) at 0x7f5e93877120>

You can get the shape by:

x.shape

(2, 3, 4)

Since both data and grad are NdArray, you can get a reference to its values as NdArray with the .data accessor, but also it can be refered by .d or .g property for data and grad respectively.

print 'x.data'
print x.d
x.d = 1.2345  # To avoid NaN
assert np.all(x.d == x.data.data), 'd: {} != {}'.format(x.d, x.data.data)
print x.g
x.g = 1.2345  # To avoid NaN

print 'x.grad (after .zero())'
print x.g

x.data
[[[ -8.57293210e+09   4.56907377e-41  -8.57293210e+09   4.56907377e-41]
[             nan   4.56907377e-41   1.09979112e+27   1.83946147e+25]
[  1.69275966e+22   4.80112800e+30   1.21230330e+25   7.22962302e+31]]

[[  1.10471027e-32   4.63080422e+27   2.44632805e+20   2.87606258e+20]
[  4.46263300e+30   4.62311881e+30   7.65000750e+28   3.01339003e+29]
[  2.08627352e-10   1.03903997e+21   2.46406626e+32   6.74187108e+22]]]
[[[ -8.57288294e+09   4.56907377e-41  -8.57288294e+09   4.56907377e-41]
[             nan   0.00000000e+00   1.09979112e+27   1.83946147e+25]
[  1.69275966e+22   4.80112800e+30   1.21230330e+25   7.22962302e+31]]

[[  1.10471027e-32   4.63080422e+27   2.44632805e+20   2.87606258e+20]
[  4.46263300e+30   4.62311881e+30   7.65000750e+28   3.01339003e+29]
[  2.08627352e-10   1.03903997e+21   2.46406626e+32   6.74187108e+22]]]
[[[ 0.  0.  0.  0.]
[ 0.  0.  0.  0.]
[ 0.  0.  0.  0.]]

[[ 0.  0.  0.  0.]
[ 0.  0.  0.  0.]
[ 0.  0.  0.  0.]]]

Like NdArray, a Variable can also be created from Numpy array(s).

x2 = nn.Variable.from_numpy_array(np.ones((3,)), need_grad=True)
print x2
print x2.d
print x3
print x3.d
print x3.g

<Variable((3,), need_grad=True) at 0x7f5e9387e258>
[ 1.  1.  1.]
[ 1.  1.  1.]
[ 0.  0.  0.]

Besides storing values of a computation graph, pointing a parent edge (function) to trace the computation graph is an important role. Here x doesn’t have any connection. Therefore, the .parent property returns None.

print x.parent

None

## Function¶

A function defines a operation block of a computation graph as we described above. The module nnabla.functions offers various functions (e.g. Convolution, Affine and ReLU). You can see the list of functions available in the API reference guide.

import nnabla.functions as F

As an example, here you will defines a computation graph that computes the element-wise Sigmoid function outputs for the input variable and sums up all values into a scalar. (This is simple enough to explain how it behaves but a meaningless example in the context of neural network training. We will show you a neural network example later.)

sigmoid_output = F.sigmoid(x)
sum_output = F.reduce_sum(sigmoid_output)

The function API in nnabla.functions takes one (or several) Variable(s) and arguments (if any), and returns one (or several) output Variable(s). The .parent points to the function instance which created it. Note that no computation occurs at this time since we just define the graph. (This is the default behavior of NNabla computation graph API. You can also fire actual computation during graph definition which we call “Dynamic mode” (explained later)).

print "sigmoid_output.parent.name:", sigmoid_output.parent.name
print "x:", x
print "sigmoid_output.parent.inputs refers to x:", sigmoid_output.parent.inputs

sigmoid_output.parent.name: Sigmoid
x: <Variable((2, 3, 4), need_grad=True) at 0x7f5e9387e2c0>
sigmoid_output.parent.inputs refers to x: [<Variable((2, 3, 4), need_grad=True) at 0x7f5e935a48d8>]

print "sum_output.parent.name:", sum_output.parent.name
print "sigmoid_output:", sigmoid_output
print "sum_output.parent.inputs refers to sigmoid_output:", sum_output.parent.inputs

sum_output.parent.name: ReduceSum
sigmoid_output: <Variable((2, 3, 4), need_grad=True) at 0x7f5e935a46d0>
sum_output.parent.inputs refers to sigmoid_output: [<Variable((2, 3, 4), need_grad=True) at 0x7f5e935a4940>]

The .forward() at a leaf Variable executes the forward pass computation in the computation graph.

sum_output.forward()
print "CG output:", sum_output.d
print "Reference:", np.sum(1.0 / (1.0 + np.exp(-x.d)))

CG output: 18.5905208588
Reference: 18.5905

The .backward() does the backward propagation through the graph. Here we initialize the grad values as zero before backprop since the NNabla backprop algorithm always accumulates the gradient in the root variables.

x.grad.zero()
sum_output.backward()
print "d sum_o / d sigmoid_o:"
print sigmoid_output.g
print "d sum_o / d x:"
print x.g

d sum_o / d sigmoid_o:
[[[ 1.  1.  1.  1.]
[ 1.  1.  1.  1.]
[ 1.  1.  1.  1.]]

[[ 1.  1.  1.  1.]
[ 1.  1.  1.  1.]
[ 1.  1.  1.  1.]]]
d sum_o / d x:
[[[ 0.17459197  0.17459197  0.17459197  0.17459197]
[ 0.17459197  0.17459197  0.17459197  0.17459197]
[ 0.17459197  0.17459197  0.17459197  0.17459197]]

[[ 0.17459197  0.17459197  0.17459197  0.17459197]
[ 0.17459197  0.17459197  0.17459197  0.17459197]
[ 0.17459197  0.17459197  0.17459197  0.17459197]]]

NNabla is developed by mainly focused on neural network training and inference. Neural networks have parameters to be learned associated with computation blocks such as Convolution, Affine (a.k.a. fully connected, dense etc.). In NNabla, the learnable parameters are also represented as Variable objects. Just like input variables, those parameter variables are also used by passing into Functions. For example, Affine function takes input, weights and biases as inputs.

x = nn.Variable([5, 2])  # Input
w = nn.Variable([2, 3], need_grad=True)  # Weights
b = nn.Variable([3], need_grad=True)  # Biases
affine_out = F.affine(x, w, b)  # Create a graph including only affine

The above example takes an input with B=5 (batchsize) and D=2 (dimensions) and maps it to D’=3 outputs, i.e. (B, D’) output.

You may also notice that here you set need_grad=True only for parameter variables (w and b). The x is a non-parameter variable and the root of computation graph. Therefore, it doesn’t require gradient computation. In this configuration, the gradient computation for x is not executed in the first affine, which will omit the computation of unnecessary backpropagation.

The next block sets data and initializes grad, then applies forward and backward computation.

# Set random input and parameters
x.d = np.random.randn(*x.shape)
w.d = np.random.randn(*w.shape)
b.d = np.random.randn(*b.shape)

# Forward and backward
affine_out.forward()
affine_out.backward()
# Note: Calling backward at non-scalar Variable propagates 1 as error message from all element of outputs. .

You can see that affine_out holds an output of Affine.

print 'F.affine'
print affine_out.d
print 'Reference'
print np.dot(x.d, w.d) + b.d

F.affine
[[-0.12508428  0.78213298 -0.31685624]
[-2.05011082 -0.40075728 -0.22697631]
[-1.75955343  1.1205312  -0.4265328 ]
[-1.03893924 -0.40710089 -0.18724398]
[-2.58731937 -2.25192761  0.00879636]]
Reference
[[-0.12508428  0.78213304 -0.31685624]
[-2.05011082 -0.40075728 -0.22697631]
[-1.75955343  1.1205312  -0.4265328 ]
[-1.03893924 -0.40710089 -0.18724398]
[-2.58731937 -2.25192761  0.00879636]]

The resulting gradients of weights and biases are as follows.

print "dw"
print w.g
print "db"
print b.g

dw
[[ 1.40481603  1.40481603  1.40481603]
[-0.10959685 -0.10959685 -0.10959685]]
db
[ 5.  5.  5.]

The gradient of x is not changed because need_grad is set as False.

print x.g

[[ 0.  0.]
[ 0.  0.]
[ 0.  0.]
[ 0.  0.]
[ 0.  0.]]

## Parametric Function¶

Considering parameters as inputs of Function enhances expressiveness and flexibility of computation graphs. However, to define all parameters for each learnable function is annoying for users to define a neural network. In NNabla, trainable models are usually created by composing functions that have optimizable parameters. These functions are called “Parametric Functions”. The Parametric Function API provides various parametric functions and an interface for composing trainable models.

To use parametric functions, import:

import nnabla.parametric_functions as PF

The function with optimizable parameter can be created as below.

with nn.parameter_scope("affine1"):
c1 = PF.affine(x, 3)

The first line creates a parameter scope. The second line then applies PF.affine - an affine transform - to x, and creates a variable c1 holding that result. The parameters are created and initialized randomly at function call, and registered by a name “affine1” using parameter_scope context. The function nnabla.get_parameters() allows to get the registered parameters.

nn.get_parameters()

OrderedDict([('affine1/affine/W',
('affine1/affine/b',

The name= argument of any PF function creates the equivalent parameter space to the above definition of PF.affine transformation as below. It could save the space of your Python code. The nnabla.parametric_scope is more useful when you group multiple parametric functions such as Convolution-BatchNormalization found in a typical unit of CNNs.

c1 = PF.affine(x, 3, name='affine1')
nn.get_parameters()

OrderedDict([('affine1/affine/W',
('affine1/affine/b',

It is worth noting that the shapes of both outputs and parameter variables (as you can see above) are automatically determined by only providing the output size of affine transformation(in the example above the output size is 3). This helps to create a graph in an easy way.

c1.shape

(5, 3)

Parameter scope can be nested as follows (although a meaningless example).

with nn.parameter_scope('foo'):
h = PF.affine(x, 3)
with nn.parameter_scope('bar'):
h = PF.affine(h, 4)

This creates the following.

nn.get_parameters()

OrderedDict([('affine1/affine/W',
('affine1/affine/b',
('foo/affine/W',
('foo/affine/b',
('foo/bar/affine/W',
('foo/bar/affine/b',

Also, get_parameters() can be used in parameter_scope. For example:

with nn.parameter_scope("foo"):
print nn.get_parameters()

OrderedDict([('affine/W', <Variable((2, 3), need_grad=True) at 0x7f5e915574c8>), ('affine/b', <Variable((3,), need_grad=True) at 0x7f5e91557530>), ('bar/affine/W', <Variable((3, 4), need_grad=True) at 0x7f5e91557600>), ('bar/affine/b', <Variable((4,), need_grad=True) at 0x7f5e91557668>)])

nnabla.clear_parameters() can be used to delete registered parameters under the scope.

with nn.parameter_scope("foo"):
nn.clear_parameters()
print nn.get_parameters()

OrderedDict([('affine1/affine/W', <Variable((2, 3), need_grad=True) at 0x7f5e91557120>), ('affine1/affine/b', <Variable((3,), need_grad=True) at 0x7f5e91557188>)])

## MLP Example For Explanation¶

The following block creates a computation graph to predict one dimensional output from two dimensional inputs by a 2 layer fully connected neural network (multi-layer perceptron).

nn.clear_parameters()
batchsize = 16
x = nn.Variable([batchsize, 2])
with nn.parameter_scope("fc1"):
h = F.tanh(PF.affine(x, 512))
with nn.parameter_scope("fc2"):
y = PF.affine(h, 1)
print "Shapes:", h.shape, y.shape

Shapes: (16, 512) (16, 1)

This will create the following parameter variables.

nn.get_parameters()

OrderedDict([('fc1/affine/W',
('fc1/affine/b',
('fc2/affine/W',
('fc2/affine/b',

As described above, you can execute the forward pass by calling forward method at the terminal variable.

x.d = np.random.randn(*x.shape)  # Set random input
y.forward()
print y.d

[[-0.11192071]
[ 0.01330618]
[-0.09277273]
[ 0.02282887]
[-0.13924919]
[ 0.06651091]
[ 0.00193427]
[-0.04056951]
[-0.01993009]
[ 0.05051719]
[-0.04514493]
[ 0.07883289]
[ 0.03532286]
[-0.00734853]
[ 0.04141491]
[ 0.05428782]]

Training a neural networks needs a loss value to be minimized by gradient descent with backpop. In NNabla, loss function is also a just function, and packaged in the functions module.

# Variable for label
label = nn.Variable([batchsize, 1])
# Set loss
loss = F.reduce_mean(F.squared_error(y, label))

# Execute forward pass.
label.d = np.random.randn(*label.shape)  # Randomly generate labels
loss.forward()
print loss.d

0.605832397938

As you’ve seen above, NNabla backward accumulates the gradients at the root variables. You have to initialize the grad of the parameter variables before backprop (We will show you the easiest way with Solver API).

# Collect all parameter variables and init grad.
for name, param in nn.get_parameters().items():
# Grdients are accumulated to grad of params.
loss.backward()

## Imperative Mode¶

After performing backprop, gradients are held in parameter variable grads. The next block will update the parameters with vanilla gradient descent.

for name, param in nn.get_parameters().items():
F.sub2(param.data, F.mul_scalar(param.grad, 0.001), outputs=[param.data])  # 0.001 as learning rate

The above computation is an example of NNabla’s “Imperative Mode” of execution of neural networks. If any input of a function takes an NdArray, the function computation will be fired immediately, and returns NdArray(s) as output(s). Hence, the “Imperative mode” doesn’t create a computation graph, and can be used like Numpy with device acceleration (if CUDA etc is enabled). Parametric functions can also be used with NdArray input(s). The following block demonstrates a simple imperative execution example.

# A simple example of imperative mode.
xi = nn.NdArray((2, 2))
xi.data = np.arange(4).reshape(2, 2) - 1
yi = F.relu(xi)
print xi.data
print yi.data

[[-1.  0.]
[ 1.  2.]]
[[ 0.  0.]
[ 1.  2.]]

## Solver¶

NNabla provides stochastic gradient descent algorithms to optimize parameters listed in the nnabla.solvers module. The parameter updates demonstrated above can be replaced with this Solver API, which is easier and usually faster.

from nnabla import solvers as S
solver = S.Sgd(lr=0.00001)
solver.set_parameters(nn.get_parameters())

# Set random data
x.d = np.random.randn(*x.shape)
label.d = np.random.randn(*label.shape)

# Forward
loss.forward()

Just call the the following solver method to fill zero grad region, then backprop

solver.zero_grad()
loss.backward()

The following block updates parameters with the Vanilla Sgd rule (equivalent to the imperative example above).

solver.update()

## Toy Problem To Demonstrate Training¶

The following function defines a regression problem which computes the norm of a vector.

def vector2length(x):
# x : [B, 2] where B is number of samples.
return np.sqrt(np.sum(x ** 2, axis=1, keepdims=True))

We visualize this mapping with the contour plot by matplotlib as follows.

# Data for plotting contour on a grid data.
xs = np.linspace(-1, 1, 100)
ys = np.linspace(-1, 1, 100)
grid = np.meshgrid(xs, ys)
X = grid[0].flatten()
Y = grid[1].flatten()

def plot_true():
"""Plotting contour of true mapping from a grid data created above."""
plt.contourf(xs, ys, vector2length(np.hstack([X[:, None], Y[:, None]])).reshape(100, 100))
plt.axis('equal')
plt.colorbar()

plot_true()

We define a deep prediction neural network.

def length_mlp(x):
h = x
for i, hnum in enumerate([4, 8, 4, 2]):
h = F.tanh(PF.affine(h, hnum, name="fc{}".format(i)))
y = PF.affine(h, 1, name='fc')
return y

nn.clear_parameters()
batchsize = 100
x = nn.Variable([batchsize, 2])
y = length_mlp(x)
label = nn.Variable([batchsize, 1])
loss = F.reduce_mean(F.squared_error(y, label))

We created a 5 layers deep MLP using for-loop. Note that only 3 lines of the code pottentially create infinitely deep neural networks. The next block adds helper functions to visialize the learned function.

def predict(inp):
ret = []
for i in range(0, inp.shape[0], x.shape[0]):
xx = inp[i:i + x.shape[0]]
# Imperative execution
xi = nn.NdArray.from_numpy_array(xx)
yi = length_mlp(xi)
ret.append(yi.data.copy())
return np.vstack(ret)

def plot_prediction():
plt.contourf(xs, ys, predict(np.hstack([X[:, None], Y[:, None]])).reshape(100, 100))
plt.colorbar()
plt.axis('equal')

Next we instantiate a solver object as follows. We use Adam optimizer which is one of the most popular SGD algorithm used in the literature.

from nnabla import solvers as S
solver.set_parameters(nn.get_parameters())

The following function generates data from the true system infinitely.

def random_data_provider(n):
x = np.random.uniform(-1, 1, size=(n, 2))
y = vector2length(x)
return x, y

In the next block, we run 2000 training steps (SGD updates).

num_iter = 2000
for i in range(num_iter):
# Sample data and set them to input variables of training.
xx, ll = random_data_provider(batchsize)
x.d = xx
label.d = ll
# Forward propagation given inputs.
loss.backward(clear_buffer=True)
# Apply weight decay and update by Adam rule.
solver.weight_decay(1e-6)
solver.update()
# Just print progress.
if i % 100 == 0 or i == num_iter - 1:
print "Loss@{:4d}: {}".format(i, loss.d)

Loss@   0: 1.41921281815
Loss@ 100: 0.0575609095395
Loss@ 200: 0.0476776212454
Loss@ 300: 0.00250923167914
Loss@ 400: 0.00137762445956
Loss@ 500: 0.00102305703331
Loss@ 600: 0.000931202783249
Loss@ 700: 0.00154988327995
Loss@ 800: 0.00154625205323
Loss@ 900: 0.00146807299461
Loss@1000: 0.000928562716581
Loss@1100: 0.000884895969648
Loss@1200: 0.00086419924628
Loss@1300: 0.000785566866398
Loss@1400: 0.000894531258382
Loss@1500: 0.00105767603964
Loss@1600: 0.000928580528125
Loss@1700: 0.00119259918574
Loss@1800: 0.000793418090325
Loss@1900: 0.000500827969518
Loss@1999: 0.000929419475142

Memory usage optimization: You may notice that, in the above updates, .forward() is called with the clear_no_need_grad= option, and .backward() is called with the clear_buffer= option. Training of neural network in more realistic scenarios usually consumes huge memory due to the nature of backpropagation algorithm, in which all of the forward variable buffer data should be kept in order to compute the gradient of a function. In a naive implementation, we keep all the variable data and grad living until the NdArray objects are not referenced (i.e. the graph is deleted). The clear_* options in .forward() and .backward() enables to save memory consumptions due to that by clearing (erasing) memory of data and grad when it is not referenced by any subsequent computation. (More precisely speaking, it doesn’t free memory actually. We use our memory pool engine by default to avoid memory alloc/free overhead). The unreferenced buffers can be re-used in subequent computation. See the document of Variable for more details. Note that the following loss.forward(clear_buffer=True) clears data of any intermediate variables. If you are interested in intermediate variables for some purposes (e.g. debug, log), you can use the .persistent flag to prevent clearing buffer of a specific Variable like below.

loss.forward(clear_buffer=True)
print "The prediction y is cleared because it's an intermedicate variable."
print y.d.flatten()[:4]  # to save space show only 4 values
y.persistent = True
loss.forward(clear_buffer=True)
print "The prediction y is kept by the persistent flag."
print y.d.flatten()[:4]  # to save space show only 4 value

The prediction y is cleared because it's an intermedicate variable.
[ 0.00010636  0.00016095  0.00029495  0.00013584]
The prediction y is kept by the persistent flag.
[ 1.00525522  0.70511746  0.72825861  0.62030995]

We can confirm the prediction performs fairly well by looking at the following visualization of the ground truth and prediction function.

plt.subplot(121)
plt.title("Ground truth")
plot_true()
plt.subplot(122)
plt.title("Prediction")
plot_prediction()

You can save learned parameters by nnabla.save_parameters and load by nnabla.load_parameters.

path_param = "param-vector2length.h5"
nn.save_parameters(path_param)
# Remove all once
nn.clear_parameters()
nn.get_parameters()

2017-06-26 23:11:07,458 [nnabla][INFO]: Parameter save (hdf5): param-vector2length.h5

OrderedDict()

# Load again
print '\n'.join(map(str, nn.get_parameters().items()))

2017-06-26 23:11:07,624 [nnabla][INFO]: Parameter load (<built-in function format>): param-vector2length.h5

(u'fc0/affine/W', <Variable((2, 4), need_grad=True) at 0x7f5e91569808>)
(u'fc1/affine/W', <Variable((4, 8), need_grad=True) at 0x7f5e91569870>)
(u'fc2/affine/W', <Variable((8, 4), need_grad=True) at 0x7f5e915697a0>)
(u'fc3/affine/W', <Variable((4, 2), need_grad=True) at 0x7f5e915696d0>)
(u'fc/affine/W', <Variable((2, 1), need_grad=True) at 0x7f5e91569598>)

Both save and load functions can also be used in a parameter scope.

with nn.parameter_scope('foo'):
print '\n'.join(map(str, nn.get_parameters().items()))

2017-06-26 23:11:07,747 [nnabla][INFO]: Parameter load (<built-in function format>): param-vector2length.h5

(u'fc0/affine/W', <Variable((2, 4), need_grad=True) at 0x7f5e91569808>)
(u'fc1/affine/W', <Variable((4, 8), need_grad=True) at 0x7f5e91569870>)
(u'fc2/affine/W', <Variable((8, 4), need_grad=True) at 0x7f5e915697a0>)
(u'fc3/affine/W', <Variable((4, 2), need_grad=True) at 0x7f5e915696d0>)
(u'fc/affine/W', <Variable((2, 1), need_grad=True) at 0x7f5e91569598>)

!rm {path_param}  # Clean ups