text:
Equilibrium temperature and Dulong-Petit law

Homework Statement

A thermally insulated system consists of 1 mole of a diatomic ideal gas at 100K and 2 moles of a solid at 200K that are separated by a rigid insulating wall. Find the equilibrium temperature of the system after the insulating wall is removed, assuming the solid obeys the Dulong-Petit law. (Assume that the container is divided in such a way that there is no change in volume of the substances when the insulating wall is removed)

Homework Equations

c = 3R/M (D-P law)

Qv (gas) = 2.5 * R * $$\Delta$$T
Qp (gas) = 3.5 * R * $$\Delta$$T

c = C/m

c' = C/n

The Attempt at a Solution

I'm not sure how to start this without knowing what the substances are. Since there's no change in volume the changes are isochoric, therefore no work done, and the change in internal energy is equal to the heat added.

Last edited:


text:
# 3D Graphics with OpenGL

## Basic Theory

### 1.  Computer Graphics Hardware

GPU (Graphics Processing Unit)

Modern day computer has dedicated Graphics Processing Unit (GPU) to produce images for the display, with its own graphics memory (or Video RAM or VRAM).

Pixels and Frame

All modern displays are raster-based. A raster is a 2D rectangular grid of pixels (or picture elements). A pixel has two properties: a color and a position. Color is expressed in RGB (Red-Green-Blue) components - typically 8 bits per component or 24 bits per pixel (or true color). The position is expressed in terms of (x, y) coordinates. The origin (0, 0) is located at the top-left corner, with x-axis pointing right and y-axis pointing down. This is different from the conventional 2D Cartesian coordinates, where y-axis is pointing upwards.

The number of color-bits per pixel is called the depth (or precision) of the display. The number of rows by columns of the rectangular grid is called the resolution of the display, which can range from 640x480 (VGA), 800x600 (SVGA), 1024x768 (XGA) to 1920x1080 (FHD), or even higher.

Frame Buffer and Refresh Rate

The color values of the pixels are stored in a special part of graphics memory called frame buffer. The GPU writes the color value into the frame buffer. The display reads the color values from the frame buffer row-by-row, from left-to-right, top-to-bottom, and puts each of the values onto the screen. This is known as raster-scan. The display refreshes its screen several dozen times per second, typically 60Hz for LCD monitors and higher for CRT tubes. This is known as the refresh rate.

A complete screen image is called a frame.

Double Buffering and VSync

While the display is reading from the frame buffer to display the current frame, we might be updating its contents for the next frame (not necessarily in raster-scan manner). This would result in the so-called tearing, in which the screen shows parts of the old frame and parts of the new frame.

This could be resolved by using so-called double buffering. Instead of using a single frame buffer, modern GPU uses two of them: a front buffer and a back buffer. The display reads from the front buffer, while we can write the next frame to the back buffer. When we finish, we signal to GPU to swap the front and back buffer (known as buffer swap or page flip).

Double buffering alone does not solve the entire problem, as the buffer swap might occur at an inappropriate time, for example, while the display is in the middle of displaying the old frame. This is resolved via the so-called vertical synchronization (or VSync) at the end of the raster-scan. When we signal to the GPU to do a buffer swap, the GPU will wait till the next VSync to perform the actual swap, after the entire current frame is displayed.

The most important point is: When the VSync buffer-swap is enabled, you cannot refresh the display faster than the refresh rate of the display!!! For the LCD/LED displays, the refresh rate is typically locked at 60Hz or 60 frames per second, or 16.7 milliseconds for each frame. Furthermore, if you application refreshes at a fixed rate, the resultant refresh rate is likely to be an integral factor of the display's refresh rate, i.e., 1/2, 1/3, 1/4, etc.

### 2.  3D Graphics Rendering Pipeline

pipeline, in computing terminology, refers to a series of processing stages in which the output from one stage is fed as the input of the next stage, similar to a factory assembly line or water/oil pipe. With massive parallelism, pipeline can greatly improve the overall throughput.

In computer graphics, rendering is the process of producing image on the display from model description.

The 3D Graphics Rendering Pipeline accepts description of 3D objects in terms of vertices of primitives (such as triangle, point, line and quad), and produces the color-value for the pixels on the display.

The 3D graphics rendering pipeline consists of the following main stages:

1. Vertex Processing: Process and transform individual vertices.
2. Rasterization: Convert each primitive (connected vertices) into a set of fragments. A fragment can be treated as a pixel in 3D spaces, which is aligned with the pixel grid, with attributes such as position, color, normal and texture.
3. Fragment Processing: Process individual fragments.
4. Output Merging: Combine the fragments of all primitives (in 3D space) into 2D color-pixel for the display.

In modern GPUs, the vertex processing stage and fragment processing stage are programmable. You can write programs, known as vertex shader and fragment shader to perform your custom transform for vertices and fragments. The shader programs are written in C-like high level languages such as GLSL (OpenGL Shading Language), HLSL (High-Level Shading Language for Microsoft Direct3D), or Cg (C for Graphics by NVIDIA).

On the other hand, the rasterization and output merging stages are not programmable, but configurable - via configuration commands issued to the GPU.

### 3.  Vertices, Primitives, Fragment and Pixels

3.1  3D Graphics Coordinate Systems

OpenGL adopts the Right-Hand Coordinate System (RHS). In the RHS, the x-axis is pointing right, y-axis is pointing up, and z-axis is pointing out of the screen. With your right-hand fingers curving from the x-axis towards the y-axis, the thumb is pointing at the z-axis. RHS is counter-clockwise (CCW). The 3D Cartesian Coordinates is a RHS.

Some graphics software (such as Microsoft Direct3D) use Left-hand System (LHS), where the z-axis is inverted. LHS is clockwise (CW). In this article, we shall adopt the RHS and CCW used in OpenGL.

3.2  Primitives

The inputs to the Graphics Rendering Pipeline are geometric primitives (such as triangle, point, line or quad), which is formed by one or more vertices.

OpenGL supports three classes of geometric primitives: pointsline segments, and closed polygons. They are specified via vertices. Each vertex is associated with its attributes such as the position, color, normal and texture. OpenGL provides 10 primitives as shown. Sphere, 3D box and pyramid are not primitives. They are typically assembled using primitive triangle or quad.

3.3  Vertices

Recall that a primitive is made up of one or more vertices. A vertex, in computer graphics, has these attributes:

1. Position in 3D space V=(xyz): typically expressed in floating point numbers.
2. Color: expressed in RGB (Red-Green-Blue) or RGBA (Red-Green-Blue-Alpha) components. The component values are typically normalized to the range of 0.0 and 1.0 (or 8-bit unsigned integer between 0 and 255). Alpha is used to specify the transparency, with alpha of 0 for totally transparent and alpha of 1 for opaque.
3. Vertex-Normal N=(nxnynz): We are familiar with the concept of surface normal, where the normal vector is perpendicular to the surface. In computer graphics, however, we need to attach a normal vector to each vertex, known as vertex-normal. Normals are used to differentiate the front- and back-face, and for other processing such as lighting. Right-hand rule (or counter-clockwise) is used in OpenGL. The normal is pointing outwards, indicating the outer surface (or front-face).
4. Texture T=(st): In computer graphics, we often wrap a 2D image to an object to make it seen realistic. A vertex could have a 2D texture coordinates (st), which provides a reference point to a 2D texture image.
5. Others.

OpenGL Primitives and Vertices

As an example, the following OpenGL code segment specifies a color-cube, center at the origin.

To create a geometric object or model, we use a pair of glBegin(PrimitiveType) and glEnd() to enclose the vertices that form the model. For primitiveType that ends with 'S' (e.g., GL_QUADS), we can define multiple shapes of the same type.

Each of the 6 faces is a primitive quad (GL_QUAD). We first set the color via glColor3f(red, green, blue). This color would be applied to all subsequent vertices until it is overridden. The 4 vertices of the quad are specified via glVertex3f(x, y, z), in counter-clockwise manner such that the surface-normal is pointing outwards, indicating its front-face. All four vertices has this surface-normal as its vertex-normal.

glBegin(GL_QUADS); // of the color cube

// Top-face
glColor3f(0.0f, 1.0f, 0.0f); // green
glVertex3f(1.0f, 1.0f, -1.0f);
glVertex3f(-1.0f, 1.0f, -1.0f);
glVertex3f(-1.0f, 1.0f, 1.0f);
glVertex3f(1.0f, 1.0f, 1.0f);

// Bottom-face
glColor3f(1.0f, 0.5f, 0.0f); // orange
glVertex3f(1.0f, -1.0f, 1.0f);
glVertex3f(-1.0f, -1.0f, 1.0f);
glVertex3f(-1.0f, -1.0f, -1.0f);
glVertex3f(1.0f, -1.0f, -1.0f);

// Front-face
glColor3f(1.0f, 0.0f, 0.0f); // red
glVertex3f(1.0f, 1.0f, 1.0f);
glVertex3f(-1.0f, 1.0f, 1.0f);
glVertex3f(-1.0f, -1.0f, 1.0f);
glVertex3f(1.0f, -1.0f, 1.0f);

// Back-face
glColor3f(1.0f, 1.0f, 0.0f); // yellow
glVertex3f(1.0f, -1.0f, -1.0f);
glVertex3f(-1.0f, -1.0f, -1.0f);
glVertex3f(-1.0f, 1.0f, -1.0f);
glVertex3f(1.0f, 1.0f, -1.0f);

// Left-face
glColor3f(0.0f, 0.0f, 1.0f); // blue
glVertex3f(-1.0f, 1.0f, 1.0f);
glVertex3f(-1.0f, 1.0f, -1.0f);
glVertex3f(-1.0f, -1.0f, -1.0f);
glVertex3f(-1.0f, -1.0f, 1.0f);

// Right-face
glColor3f(1.0f, 0.0f, 1.0f); // magenta
glVertex3f(1.0f, 1.0f, -1.0f);
glVertex3f(1.0f, 1.0f, 1.0f);
glVertex3f(1.0f, -1.0f, 1.0f);
glVertex3f(1.0f, -1.0f, -1.0f);

glEnd(); // of the color cube

Indexed Vertices

Primitives often share vertices. Instead of repeatedly specifying the vertices, it is more efficient to create an index list of vertices, and use the indexes in specifying the primitives.

For example, the following code fragment specifies a pyramid, which is formed by 5 vertices. We first define 5 vertices in an index array, followed by their respectively color. For each of the 5 faces, we simply provide the vertex index and color index.

float[] vertices = { // 5 vertices of the pyramid in (x,y,z)
-1.0f, -1.0f, -1.0f,  // 0. left-bottom-back
1.0f, -1.0f, -1.0f,  // 1. right-bottom-back
1.0f, -1.0f,  1.0f,  // 2. right-bottom-front
-1.0f, -1.0f,  1.0f,  // 3. left-bottom-front
0.0f,  1.0f,  0.0f   // 4. top
};

float[] colors = {  // Colors of the 5 vertices in RGBA
0.0f, 0.0f, 1.0f, 1.0f,  // 0. blue
0.0f, 1.0f, 0.0f, 1.0f,  // 1. green
0.0f, 0.0f, 1.0f, 1.0f,  // 2. blue
0.0f, 1.0f, 0.0f, 1.0f,  // 3. green
1.0f, 0.0f, 0.0f, 1.0f   // 4. red
};

byte[] indices = { // Vertex indices of the 4 Triangles
2, 4, 3,   // front face (CCW)
1, 4, 2,   // right face
0, 4, 1,   // back face
4, 0, 3    // left face
};

// Transfer the arrays to vertex-buffer, color-buffer and index-buffer.
// Draw the primitives (triangle) from the index buffer

3.4  Pixel vs. Fragment

Pixels refers to the dots on the display, which are aligned in a 2-dimensional grid of a certain rows and columns corresponding to the display's resolution. A pixel is 2-dimensional, with a (xy) position and a RGB color value (there is no alpha value for pixels). The purpose of the Graphics Rendering Pipeline is to produce the color-value for all the pixels for displaying on the screen, given the input primitives.

In order to produce the grid-aligned pixels for the display, the rasterizer of the graphics rendering pipeline, as its name implied, takes each input primitive and perform raster-scan to produce a set of grid-aligned fragments enclosed within the primitive. A fragment is 3-dimensional, with a (xyz) position. The (xy) are aligned with the 2D pixel-grid. The z-value (not grid-aligned) denotes its depth. The z-values are needed to capture the relative depth of various primitives, so that the occluded objects can be discarded (or the alpha channel of transparent objects processed) in the output-merging stage.

Fragments are produced via interpolation of the vertices. Hence, a fragment has all the vertex's attributes such as color, fragment-normal and texture coordinates.

In modern GPU, vertex processing and fragment processing are programmable. The programs are called vertex shader and fragment shader.

(Direct3D uses the term "pixel" for "fragment".)

### 4.  Vertex Processing

4.1  Coordinates Transformation

The process used to produce a 3D scene on the display in Computer Graphics is like taking a photograph with a camera. It involves four transformations:

1. Arrange the objects (or models, or avatar) in the world (Model Transformation or World transformation).
2. Position and orientation the camera (View transformation).
3. Select a camera lens (wide angle, normal or telescopic), adjust the focus length and zoom factor to set the camera's field of view (Projection transformation).
4. Print the photo on a selected area of the paper (Viewport transformation) - in rasterization stage

A transform converts a vertex V from one space (or coordinate system) to another space V'. In computer graphics, transform is carried by multiplying the vector with a transformation matrix, i.e., V' = M V.

4.2  Model Transform (or Local Transform, or World Transform)

Each object (or model or avatar) in a 3D scene is typically drawn in its own coordinate system, known as its model space (or local space, or object space). As we assemble the objects, we need to transform the vertices from their local spaces to the world space, which is common to all the objects. This is known as the world transform. The world transform consists of a series of scaling (scale the object to match the dimensions of the world), rotation (align the axes), and translation (move the origin).

Rotation and scaling belong to a class of transformation called linear transformation (by definition, a linear transformation preserves vector addition and scalar multiplication). Linear transform and translation form the so-called affine transformation. Under an affine transformation, a straight line remains a straight line and ratios of distances between points are preserved.

In OpenGL, a vertex V at (xyz) is represented as a 3x1 column vector:

Other systems, such as Direct3D, use a row vector to represent a vertex.

Scaling

3D scaling can be represented in a 3x3 matrix:

where αxαy and αz represent the scaling factors in xy and z direction, respectively. If all the factors are the same, it is called uniform scaling.

We can obtain the transformed result V' of vertex V via matrix multiplication, as follows:

Rotation

3D rotation operates about an axis of rotation (2D rotation operates about a center of rotation). 3D Rotations about the xy and z axes for an angle θ (measured in counter-clockwise manner) can be represented in the following 3x3 matrices:

The rotational angles about xy and z axes, denoted as θxθy and θz, are known as Euler angles, which can be used to specify any arbitrary orientation of an object. The combined transform is called Euler transform.

[TODO] Link to Proof and illustration

Translation

Translation does not belong to linear transform, but can be modeled via a vector addition, as follows:

Fortunately, we can represent translation using a 4x4 matrices and obtain the transformed result via matrix multiplication, if the vertices are represented in the so-called 4-component homogeneous coordinates (xyz, 1), with an additional forth w-component of 1. We shall describe the significance of the w-component later in projection transform. In general, if the w-component is not equal to 1, then (xyzw) corresponds to Cartesian coordinates of (x/wy/wz/w). If w=0, it represents a vector, instead of a point (or vertex).

Using the 4-component homogeneous coordinates, translation can be represented in a 4x4 matrix, as follows:

The transformed vertex V' can again be computed via matrix multiplication:

Summary of Affine Transformations

We rewrite the scaling and rotation into 4x4 matrices using the homogenous coordinates.

Successive Transforms

A series of successive affine transforms (T1T2T3, ...) operating on a vertex V can be computed via concatenated matrix multiplications V' = ...T3T2T1V. The matrices can be combined before applying to the vertex because matrix multiplication is associative, i.e., T3 (T2 (TV) ) = T3T2T1 ) V.

Example

[TODO]

Transformation of Vertex-Normal

Recall that a vector has a vertex-normal, in addition to (xyz) position and color.

Suppose that M is a transform matrix, it can be applied to vertex-normal only if the transforms does not include non-uniform scaling. Otherwise, the transformed normal will not be orthogonal to the surface. For non-uniform scaling, we could use (M-1)T as the transform matrix, which ensure that the transformed normal remains orthogonal.

[TODO] Diagram and more

4.3  View Transform

After the world transform, all the objects are assembled into the world space. We shall now place the camera to capture the view.

Positioning the Camera

In 3D graphics, we position the camera onto the world space by specifying three view parameters: EYE, AT and UP, in world space.

1. The point EYE (exeyez) defines the location of the camera.
2. The vector AT (axayaz) denotes the direction where the camera is aiming at, usually at the center of the world or an object.
3. The vector UP (uxuyuz) denotes the upward orientation of the camera roughly. UP is typically coincided with the y-axis of the world space. UP is roughly orthogonal to AT, but not necessary. As UP and AT define a plane, we can construct an orthogonal vector to AT in the camera space.

Notice that the 9 values actually produce 6 degrees of freedom to position and orientate the camera, i.e., 3 of them are not independent.

OpenGL

In OpenGL, we can use the GLU function gluLookAt() to position the camera:

void gluLookAt(GLdouble xEye, GLdouble yEye, GLdouble zEye,
GLdouble xAt, GLdouble yAt, GLdouble zAt,
GLdouble xUp, GLdouble yUp, GLdouble zUp)

The default settings of gluLookAt() is:

gluLookAt(0.0, 0.0, 0.0, 0.0, 0.0, -100.0, 0.0, 1.0, 0.0)

That is, the camera is positioned at the origin (0, 0, 0), aimed into the screen (negative z-axis), and faced upwards (positive y-axis). To use the default settings, you have to place the objects at negative z-values.

Computing the Camera Coordinates

From EYE, AT and UP, we first form the coordinate (xcyczc) for the camera, relative to the world space. We fix zc to be the opposite of AT, i.e., AT is pointing at the -zc. We can obtain the direction of xc by taking the cross-product of AT and UP. Finally, we get the direction of yc by taking the cross-product of xc and zc. Take note that UP is roughly, but not necessarily, orthogonal to AT.

Transforming from World Space to Camera Space

Now, the world space is represented by standard orthonormal bases (e1, e2, e3), where e1=(1, 0, 0), e2=(0, 1, 0) and e3=(0, 0, 1), with origin at O=(0, 0, 0). The camera space has orthonormal bases (xcyczc) with origin at EYE=(exeyez).

It is much more convenience to express all the coordinates in the camera space. This is done via view transform.

The view transform consists of two operations: a translation (for moving EYE to the origin), followed by a rotation (to axis the axes):

The View Matrix

We can combine the two operations into one single View Matrix:

Model-View Transform

In Computer Graphics, moving the objects relative to a fixed camera (Model transform), and moving the camera relative to a fixed object (View transform) produce the same image, and therefore are equivalent. OpenGL, therefore, manages the Model transform and View transform in the same manner on a so-called Model-View matrix. Projection transformation (in the next section) is managed via a Projection matrix.

4.4  Projection Transform - Perspective Projection

Once the camera is positioned and oriented, we need to decide what it can see (analogous to choosing the camera's field of view by adjusting the focus length and zoom factor), and how the objects are projected onto the screen. This is done by selecting a projection mode (perspective or orthographic) and specifying a viewing volume or clipping volume. Objects outside the clipping volume are clipped out of the scene and cannot be seen.

View Frustum in Perspective View

The camera has a limited field of view, which exhibits a view frustum (truncated pyramid), and is specified by four parameters: fovy, aspect, zNear and zFar.

1. Fovy: specify the total vertical angle of view in degrees.
2. Aspect: the ratio of width vs. height. For a particular z, we can get the height from the fovy, and then get the width from the aspect.
3. zNear; the near plane.
4. zFar: the far plane.

The camera space (xcyczc) is renamed to the familiar (xyz) for convenience.

The projection with view frustum is known as perspective projection, where objects nearer to the COP (Center of Projection) appear larger than objects further to the COP of the same size.

An object outside the view frustum is not visible to the camera. It does not contribute to the final image and shall be discarded to improve the performance. This is known as view-frustum culling. If an object partially overlaps with the view frustum, it will be clipped in the later stage.

OpenGL

In OpenGL, there are two functions for choosing the perspective projection and setting its clipping volume:

1. More commonly-used GLU function gluPerspective():
void gluPerspective(GLdouble fovy, GLdouble aspectRatio, GLdouble zNear, GLdouble zFar)
// fovy is the angle between the bottom and top of the projectors;
// aspectRatio is the ratio of width and height of the front (and also back) clipping plane;
// zNear and zFar specify the front and back clipping planes.
2. Core GL function glFrustum():
void glFrustum(GLdouble xLeft, GLdouble xRight, GLdouble yBottom, GLdouble yTop, GLdouble zNear, GLdouble zFar)
// xLeft, xRight, yBottom and yTop specifies the front clipping plane.
// zNear and zFar specify the positions of the front and back clipping planes.

Clipping-Volume Cuboid

Next, we shall apply a so-called projection matrix to transform the view-frustum into a axis-aligned cuboid clipping-volume of 2x2x1 centered on the near plane, as illustrated. The near plane has z=0, whereas the far plane has z=-1. The planes have dimension of 2x2, with range from -1 to +1.

The Perspective Projection Matrix

The projection matrix is given by:

Take note that the last row of the matrix is no longer [0 0 0 1]. With input vertex of (x, y, z, 1), the resultant w-component would not be 1. We need to normalize the resultant homogeneous coordinates (x, y, z, w) to (x/w, y/w, z/w, 1) to obtain position in 3D space. (It is amazing that homogeneous coordinates can be used for translation, as well as the perspective projection.)

The final step is to flip the z-axis, so that the near plane is still located at z=0, but the far plane is flipped and located at z=1 (instead of z=-1). In other words, the larger the z, the further is the object. To perform flipping, we can simply negate the third row of the projection matrix.

After the flip, the coordinate system is no longer a Right-Hand System (RHS), but becomes a Left-hand System (LHS).

OpenGL's Model-View Matrix and Projection Matrix

OpenGL manages the transforms via two matrices: a model-view matrix (GL_MODELVIEW for handling model and view transforms) and a projection matrix (GL_PROJECTION for handling projection transform). These two matrices can be manipulated independently.

We need to first select the matrix for manipulation via:

void glMatrixMode(GLenum matrix)    // Select matrix for manipulating, e.g., GL_PROJECTION, GL_MODELVIEW.

We can reset the currently selected matrix via:

void glLoadIdentity()

We can save the value of the currently selected matrix onto the stack and restore it back via:

void glPushMatrix()
void glPopMatrix()

Push and pop use a stack and operate in a last-in-first-out manner, and can be nested.

4.5  Projection Transform - Orthographic Projection

Besides the commonly-used perspective projection, there is another so-called orthographic projection (or parallel projection), which is a special case where the camera is placed very far away from the world (analogous to using telescopic lens). The view volume for orthographic projection is a parallelepiped (instead of a frustum in perspective projection).

OpenGL

In OpenGL, we can use glOrtho() function to choose the orthographic projection mode and specify its clipping volume:

void glOrtho(GLdouble xLeft, GLdouble xRight, GLdouble yBottom, GLdouble yTop, GLdouble zNear, GLdouble zFar)

For 2D graphics, we can use gluOrtho2D() (GLU function instead of GL) to choose 2D orthographic projection and set its clipping area:

void gluOrtho2D(GLdouble xLeft, GLdouble xRight, GLdouble yBottom, GLdouble yTop)

The default 3D projection in OpenGL is the orthographic (instead of perspective) with parameters (-1.0, 1.0, -1.0, 1.0, -1.0, 1.0), i.e., a cube with sides of 2.0, centered at origin.

[TODO] Transform matrix

4.6  Outputs of the Vertex Processing Stage

Each vertex is transformed and positioned in the clipping-volume cuboid space, together with their vertex-normal. The x and y coordinates (in the range of -1 to +1) represent its position on the screen, and the z value (in the range of 0 to 1) represents its depth, i.e., how far away from the near plane.

The vertex processing stage transform individual vertices. The relationships between vertices (i.e., primitives) are not considered in this stage.

### 5.  Rasterization

In the previous vertex processing stage, the vertices, which is usually represented in a float value, are not necessarily aligned with the pixel-grid of the display. The relationship of vertices, in term of primitives, are also not considered.

In this rasterization stage, each primitive (such as triangle, quad, point and line), which is defined by one or more vertices, are raster-scan to obtain a set of fragments enclosed within the primitive. Fragments can be treated as 3D pixels, which are aligned with the pixel-grid. The 2D pixels have a position and a RGB color value. The 3D fragments, which are interpolated from the vertices, have the same set of attributes as the vertices, such as position, color, normal, texture.

The substages of rasterization include viewport transform, clipping, perspective division, back-face culling, and scan conversion. The rasterizer is not programmable, but configurable via the directives.

5.1  Viewport Transform

Viewport

Viewport is a rectangular display area on the application window, which is measured in screen's coordinates (in pixels, with origin at the top-left corner). A viewport defines the size and shape of the display area to map the projected scene captured by the camera onto the application window. It may or may not occupy the entire screen.

In 3D graphics, a viewport is 3-dimensional to support z-ordering, which is needed for situations such as ordering of overlapping windows.

OpenGL

In OpenGL, by default, the viewport is set to cover the entire application window. We can use the glViewport() function to choose a smaller area (e.g., for split-screen or multi-screen application).

void glViewport(GLint xTopLeft, GLint yTopLeft, GLsizei width, GLsizei height)

We can also set the z-range of viewport via glDepthRange():

glDepthRange(GLint minZ, GLint maxZ)

Viewport Transform

Our final transform, viewport transform, maps the clipping-volume (2x2x1 cuboid) to the 3D viewport, as illustrated.

Viewport transform is made up of a series of reflection (of y-axis), scaling (of x, y and z axes), and translation (of the origin from the center of the near plane of clipping volume to the top-left corner of the 3D viewport). The viewport transform matrix is given by:

If the viewport cover the entire screen, minX=minY=minZ=0w=screenWidth and h=screenHeight.

Aspect Ratios of Viewport and Projection Plane

It is obvious that if the aspect ratio of the viewport (set via glViewport()) and the projection plane (set via gluPerspective()glOrtho()) are not the same, the shapes will be distorted. Hence, it is important to use the same aspect ratio for the viewport and the projection plane.

The glViewport() command should be included in reshaped() handler, so as to re-size the viewport whenever the window is re-sized. It is important that the aspect ratio of the projection plane is re-configure to match the viewport's aspect ratio, in order not to distort the shapes. In other words, glViewport() and gluPerpective()/glOrtho() should be issued together.

For example,

// Callback when the OpenGL's window is re-sized.
void reshape(GLsizei width, GLsizei height) {  // GLsizei for non-negative integer
if (height == 0) height = 1;                        // To prevent divide by 0
GLfloat aspect = (GLfloat)width / (GLfloat)height; // Compute aspect ratio

// Set the viewport (display area on the window) to cover the whole application window
glViewport(0, 0, width, height);

// Adjust the aspect ratio of projection's clipping volume to match the viewport
glMatrixMode(GL_PROJECTION);   // Select Projection matrix
glLoadIdentity();              // Reset the Projection matrix

// Either "perspective projection" or "orthographic projection", NOT both

// 3D Perspective Projection (fovy, aspect, zNear, zFar), relative to camera's eye position
gluPerspective(45.0, aspect, 0.1, 100.0);

// OR

// 3D Orthographic Projection (xLeft, xRight, yBottom, yTop, zNear, zFar),
// relative to camera's eye position.
if (width <= height) {
glOrtho(-1.0, 1.0, -1.0 / aspect, 1.0 / aspect, -1.0, 1.0);  // aspect <= 1
} else {
glOrtho(-1.0 * aspect, 1.0 * aspect, -1.0, 1.0, -1.0, 1.0);  // aspect > 1
}

// Reset the Model-View matrix
glMatrixMode(GL_MODELVIEW);
}

5.2  Back-Face Culling

While view frustum culling discard objects outside the view frustum, back-face culling discard primitives which is not facing the camera.

Back face can be declared based on the normal vector and the vector connecting the surface and the camera.

Back-face culling shall not be enabled if the object is transparent and alpha blending is enabled.

OpenGL

In OpenGL, face culling is disabled by default, and both front-face and back-faces are rendered. We can use function glCullFace() to specify whether the back-face (GL_BACK) or front-face (GL_FRONT) or both (GL_FRONT_AND_BACK) shall be culled.

### 6.  Fragment Processing

After rasterization, we have a set of fragments for each primitive. A fragment has a position, which is aligned to the pixel-grid. It has a depth, color, normal and texture coordinates, which are interpolated from the vertices.

The fragment processing focuses on the texture and lighting, which has the greatest impact on the quality of the final image. We shall discussed texture and lighting in details in later sections.

The operations involved in the fragment processor are:

1. The first operation in fragment processing is texturing.
2. Next, primary and secondary colors are combined, and fog calculation may be applied.
3. The optional scissor test, alpha test, stencil test, and depth-buffer test are carried out, if enabled.
4. Then, the optional blending, dithering, logical operation, and bitmasking may be performed.

### 7.  Output Merging

7.1  Z-Buffer and Hidden-Surface Removal

z-buffer (or depth-buffer) can be used to remove hidden surfaces (surfaces blocked by other surfaces and cannot be seen from the camera). The z-buffer of the screen is initialized to 1 (farthest) and color-buffer initialized to the background color. For each fragment (of each primitive) processed, its z-value is checked against the buffer value. If its z-value is smaller than the z-buffer, its color and z-value are copied into the buffer. Otherwise, this fragment is occluded by another object and discarded. The fragments can be processed in any order, in this algorithm.

OpenGL

In OpenGL, to use z-buffer for hidden-surface removal via depth testing, we need to:

1. Request for z-buffer via glutInitDisplayMode():
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH);     // GLUT_DEPTH to request for depth-buffer
2. Enable depth testing on z-buffer:
glEnable(GL_DEPTH_TEST);
3. Clear the z-buffer (to 1 denoting the farthest) and the color buffer (to the background color):
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);  // Clear color and depth buffers

7.2  Alpha-Blending

Hidden-surface removal works only if the front object is totally opaque. In computer graphics, a fragment is not necessarily opaque, and could contain an alpha value specifying its degree of transparency. The alpha is typically normalized to the range of [0, 1], with 0 denotes totally transparent and 1 denotes totally opaque. If the fragment is not totally opaque, then part of its background object could show through, which is known as alpha blending. Alpha-blending and hidden-surface removal are mutually exclusive.

The simplest blending equation is as follows:

c = αscs + (1 - αs)cd

where cs is the source color, αs is the source alpha, cd is the destination (background) color. The 3 color channels RGB are applied independently.

For this blending equation, the order of placing the fragment is important. The fragments must be sorted from back-to-front, with the largest z-value processed first. Also, the destination alpha value is not used.

There are many other blending equations to achieve different effects.

OpenGL

In OpenGL, to perform alpha blending, we need to enable blending and disable depth-test (which performs hidden-surface removal). For example,

if (blendingEnabled) {
glEnable(GL_BLEND);        // Enable blending
glDisable(GL_DEPTH_TEST);  // Need to disable depth testing
} else {
glDisable(GL_BLEND);
glEnable(GL_DEPTH_TEST);
}

Source and Destination Blending Factors

In OpenGL, the glBlendFunc() function can be used to specify the so-called source and destination blending factors:

void glBlendFunc(GLenum sourceBlendingFactor, GLenum destinationBlendingFactor)

Suppose that a new object (called source) is to be blended with the existing objects in the color buffer (called destination). The source's color is (RsGsBsAs), and the destination's color is (RdGdBdAd). The source and destination color values will be weighted with respective to the source blending factor and destination blending factor and combined to produce the resultant value. Each of the RGB components will be computed independently.

For example, suppose the source blending factor for G component is p and the destination blending factor for G component is q, the resultant G component is p×Gs + q×Gd.

There are many choices of the blending factors. For example, a popular choice is:

glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

where each component of the source is weighted by source's alpha value (As), and each component of the destination is weighted by 1-As. In this case, if the original color component's value is within [0.0, 1.0], the resultant value is guaranteed to be within this range. The drawback is that the final color depends on the order of rendering if many surfaces are added one after another (because the destination alpha value is not considered).

Another example of blending factors is:

glBlendFunc(GL_SRC_ALPHA, GL_ONE);

where each component of source is weighted by source's alpha value (As), and each component of the destination is weight by 1. The value may overflow/underflow. But the final color does not depends on the order of rendering when many objects are added.

Other values for the blending factors include GL_ZEROGL_ONEGL_SRC_COLORGL_ONE_MINUS_SRC_COLORGL_DST_COLORGL_ONE_MINUS_DST_COLORGL_SRC_ALPHAGL_ONE_MINUS_SRC_ALPHAGL_DST_ALPHAGL_ONE_MINUS_DST_ALPHAGL_CONSTANT_COLORGL_ONE_MINUS_CONSTANT_COLORGL_CONSTANT_ALPHA, and GL_ONE_MINUS_CONSTANT_ALPHA.

The default for source blending factor is GL_ONE, and the default for destination blending factor is GL_ZERO. That is, opaque (totally non-transparent) surfaces.

The computations also explain why depth-testing shall be disabled when alpha-blending is enabled. This is because the final color will be determined by blending between source and destination colors for translucent surfaces, instead of relative depth (the color of the nearer surface) for opaque surfaces.

### 8.  Lighting

Lighting refers to the handling of interactions between the light sources and the objects in the 3D scene. Lighting is one of the most important factor in producing a realistic scene.

The color that we see in the real world is the result of the interaction between the light sources and the color material surfaces. In other words, three parties are involved: viewer, light sources, and the material. When light (of a certain spectrum) from a light source strikes a surface, some gets absorbed, some is reflected or scattered. The angle of reflection depends on the angle of incidence and the surface normal. The amount of scatterness depends on the smoothness and the material of the surface. The reflected light also spans a certain color spectrum, which depends on the color spectrum of the incident light and the absorption property of the material. The strength of the reflected light depends on the position and distance of the light source and the viewer, as well as the material. The reflected light may strike other surfaces, and some is absorbed and some is reflected again. The color that we perceived about a surface is the reflected light hitting our eye. In a 2D photograph or painting, objects appear to be three-dimensional due to some small variations in colors, known as shades.

The are two classes of lighting models:

1. Local illumination: consider only the direct lightings. The color of the surface depends on the reflectance properties of the surface and the direct lightings.
2. Global illumination: in real world, objects received indirect lighting reflected from other objects and the environment. The global illumination model consider indirect lightings reflected from other objects in the scene. Global illumination model is complex and compute intensive.

8.1  Phong Lighting Model for Light-Material Interaction

Phong lighting model is a local illumination model, which is compute inexpensive and extensively used especially in the earlier days. It considers four types of lightings: diffuse, specular, ambient and emissive.

Consider a fragment P on a surface, four vectors are used: the light source L, the viewer V, the fragment-normal N, and the perfect reflector R. The perfect reflector R can be computed from the surface normal N and the incidence light L, according to Newton's law which states that the angle of incidence is equals to the angle of reflection.

Diffuse Light

Diffuse light models distant directional light source (such as the sun light). The reflected light is scattered equally in all directions, and appears the same to all viewers regardless of their positions, i.e., independent of viewer vector V. The strength of incident light depends on the angle between the light source L and the normal N, i.e., the dot product between L and N.

The resultant color can be computed as follows:

The strength of the incident light is max(LN, 0). We use the max function to discard the negative number, i.e., the angle is more than 90 degree. Suppose the light source has color sdiff, and the fragment has diffusion reflectance of mdiff, the resultant color c is:

cdiff = max(LN, 0) sdiff mdiff

where the RGB component of the color are computed independently.

Specular Light

The reflected light is concentrated along the direction of perfect reflector R. What a viewer sees depends on the angle (cosine) between V and R.

The resultant color due to specular reflection is given by:

cspec = max(RV, 0)sh sspec mspec

the sh is known as the shininess factor. As sh increases, the light cone becomes narrower (because RV ≤ 1), the highlighted spot becomes smaller.

Ambient Light

A constant amount of light applied to every point of the scene. The resultant color is:

camb =samb mamb

Emissive Light

Some surfaces may emit light. The resultant color is cem = mem

Resultant Color

The resultant color is the sum of the contribution in all the four components:

cfinal =cdiff + cspec + camb + cem

8.2  OpenGL's Lighting and Material

OpenGL provides point sources (omni-directional), spotlights (directional with cone-shaped), and ambient light (a constant factor). Light source may be located at a fixed position or infinitely far away. Each source has separate ambient, diffuse, and specular components. Each source has RGB components. The lighting calculation is performed on each of the components independently (local illumination without considering the indirect lighting). Materials are modeled in the same manner. Each type of material has a separate ambient, diffuse, and specular components, with parameters specifying the fraction that is reflected for each corresponding component of the light sources. Material may also have a emissive component.

In OpenGL, you need to enable the lighting state, and each of the light sources, identified via GL_LIGHT0 to GL_LIGHTn.

glEnable(GL_LIGHTING);  // Enable lighting
glEnable(GL_LIGHT0);    // Enable light source 0
glEnable(GL_LIGHT1);    // Enable light source 1

Once lighting is enable, color assigned by glColor() are no longer used. Instead, the color depends on the light-material interaction and the viewer's position.

You can use glLight() to define a light source (GL_LIGHT0 to GL_LIGHTn):

void glLight[if](GLenum lightSourceID, GLenum parameterName, type parameterValue);
void glLight[if]v(GLenum lightSourceID, GLenum parameterName, type *parameterValue);
// lightSourceID: ID for the light source, GL_LIGHT0 to GL_LIGHTn.
// parameterName: such as GL_AMBIENT, GL_DIFFUSE, GL_SPECULAR, GL_POSITION.
// parameterValue: values of the parameter.

The default for GL_POSITION is (0, 0, 1) relative to camera coordinates, so it is behind the default camera position (0, 0, 0).

GL_LIGHT0 is special, with default value of white (1, 1, 1) for the GL_AMBIENTGL_DIFFUSEGL_SPECULAR components. You can enable GL_LIGHT0 right away by using its default settings. For other light IDs (GL_LIGHT1 to GL_LIGHTn), the default is black (0, 0, 0) for GL_AMBIENTGL_DIFFUSEGL_SPECULAR.

Material

Similar to light source, a material has reflectivity parameters for specular (GL_SPECULAR), diffuse (GL_DIFFUSE) and ambient (GL_AMBIENT) components (for each of the RGBA color components), which specifies the fraction of light reflected. A surface may also emit light (GL_EMISSION). A surface has a shininess parameter (GL_SHININESS) - the higher the value, the more concentration of reflected-light in the small area around the perfect reflector and the surface appears to be shinier. Furthermore, a surface has two faces: front and back, that may have the same or different parameters.

You can use glMaterial() function to specify these parameters for the front (GL_FRONT), back (GL_BACK), or both (GL_FRONT_AND_BACK) surfaces. The front face is determined by the surface normal (implicitly defined by the vertices with right-hand rule, or glNormal() function).

void glMaterial[if](GLenum face, GLenum parameterName, type parameterValue)
void glMaterial[if]v(GLenum face, GLenum parameterName, type *parameterValues)
// face: GL_FRONT, GL_BACK, GL_FRONT_AND_BACK.
// parameterName: GL_DIFFUSE, GL_SPECULAR, GL_AMBIENT, GL_AMBIENT_AND_DIFFUSE, GL_EMISSION, GL_SHININESS.

The default material has a gray surface (under white light), with a small amount of ambient reflection (0.2, 0.2, 0.2, 1.0), high diffuse reflection (0.8, 0.8, 0.8, 1.0), and no specular reflection (0.0, 0.0, 0.0, 1.0).

[TODO]

8.4  Global Illumination Model

[TODO]

### 9.  Texture

In computer graphics, we often overlay (or paste or wrap) images, called textures, over the graphical objects to make them realistic.

An texture is typically a 2D image. Each element of the texture is called a texel (texture element), similar to pixel (picture element). The 2D texture coordinate (st) is typically normalized to [0.0, 1.0], with origin at the top-left corner, s-axis pointing right and t-axis pointing down. (Need to confirm whether this is true in OpenGL)

9.1  Texture Wrapping

Although the 2D texture coordinates is normalized to [0.0, 1.0], we can configure the behavior if the coordinates are outside the range.

The typical solutions are:

1. Clamp the texture coordinates to [0.0, 1.0] and ignore those outside this range.
2. Wrap (or repeat) the texture along the s- or t-axis, or both. You may set to "mirror" mode so that the textures are continuous.

In OpenGL, we use function glTexParameter() to configure the wrapping behavior for the s and t axes (GL_TEXTURE_WRAP_S and GL_TEXTURE_WRAP_T) individually. Two modes are supported: GL_REPEAT (repeat the texture pattern) and GL_CLAMP (do not repeat, but clamp to 0.0 to 1.0).

glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);  // Repeat the pattern
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);   // Clamped to 0.0 or 1.0
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);

9.2  Texture Filtering

In general, the resolution of the texture image is different from the displayed fragment (or pixel). If the resolution of the texture image is smaller, we need to perform so-called magnification to magnify the texture image to match the display. On the other hand, if the resolution of texture image is larger, we perform minification.

Magnification

The commonly used methods are:

1. Nearest Point Filtering: the texture color-value of the fragment is taken from the nearest texel. This filter leads to "blockiness" as many fragments are using the same texel.
2. Bilinear Interpolation: the texture color-value of the fragment is formed via bilinear interpolation of the four nearest texels. This yields smoother result.

Minification

Minification is needed if the resolution of the texture image is larger than the fragment. Again, you can use the "nearest-point sampling" or "bilinear interpolation" methods.

However, these sampling methods often to the so-called "aliasing artefact", due the low sampling frequency compared with the signal. For example, a far-away object in perspective projection will look strange due to its high signal frequency.

[TODO] diagarm on aliasing artefact

Minmaping

A better approach for performing minification is called minmaping (miniature maps), where lower resolutions of the texture image are created. For example, suppose the original image is 64x64 (Level 0), we can create lower resolution images at 32x32, 16x16, 8x8, 4x4, 2x2, 1x1. The highest resolution is referred to as level 0; the next is level 1; and so on. We can then use the nearest matched-resolution texture image; or perform linear interpolation between the two nearest matched-resolution texture images.

OpenGL Texture Filtering

In OpenGL, you can set the filter for magnification and minification independently.

// Nearest Point Sampling - fast but visual artifacts
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
// 2x2 linear averaging - slower but smoother
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

We can use a single image and ask OpenGL to produce the lower-resolution images via command gluBuild2DMipmaps() (in place of glTexImage2d()).

int gluBuild2DMipmaps(GLenum target, GLint internalFormat, GLsizei width, GLsizei height,
GLenum imageDataFormat, GLenum imageDataType, const void *imageData)

We can then specify the mipmapping filter is to be used via:

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);                // MAG filter is linear
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST); // MIN filter is mipmap

Furthermore, in perspective projection, the fast texture interpolating scheme may not handle the distortion caused by the perspective projection. The following command can be used to ask the renderer to produce a better texture image, in the expense of processing speed.

glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);

Link to OpenGL/Computer Graphics References and Resources

format: plain


text:
# Counterexample of a theorem for characteristic function.

Let $$X$$ be an $$\mathbb R$$-valued random variable and let $$f(t)$$ be his characteristic function. If $$f$$ is derivable up to order $$k$$ in $$t=0$$ , where $$k$$ is even, then $$X$$ has a finite $$k$$-th expectation.

I ask for a counterexample where $$k$$ is not even.

• Welcome to MSE. Please read this text about how to ask a good question. – José Carlos Santos Feb 1 at 9:52
• Have a look at this. – drhab Feb 1 at 10:01
• drhab can you give me an hint to prove that the characteristics function is derivable in 0 ? – Dario La Torre Feb 1 at 10:55


text:
# Essentials¶

## Introduction¶

The Julia standard library contains a range of functions and macros appropriate for performing scientific and numerical computing, but is also as broad as those of many general purpose programming languages. Additional functionality is available from a growing collection of available packages. Functions are grouped by topic below.

Some general notes:

• Except for functions in built-in modules (Pkg, Collections, Graphics, Test and Profile), all functions documented here are directly available for use in programs.
• To use module functions, use import Module to import the module, and Module.fn(x) to use the functions.
• Alternatively, using Module will import all exported Module functions into the current namespace.
• By convention, function names ending with an exclamation point (!) modify their arguments. Some functions have both modifying (e.g., sort!) and non-modifying (sort) versions.

## Getting Around¶

exit([code])

Quit (or control-D at the prompt). The default exit code is zero, indicating that the processes completed successfully.

quit()

Quit the program indicating that the processes completed succesfully. This function calls exit(0) (see exit()).

atexit(f)

Register a zero-argument function to be called at exit.

isinteractive() → Bool

Determine whether Julia is running an interactive session.

whos([Module,] [pattern::Regex])

Print information about global variables in a module, optionally restricted to those matching pattern.

edit(file::String[, line])

Edit a file optionally providing a line number to edit at. Returns to the julia prompt when you quit the editor.

edit(function[, types])

Edit the definition of a function, optionally specifying a tuple of types to indicate which method to edit.

@edit()

Evaluates the arguments to the function call, determines their types, and calls the edit function on the resulting expression

less(file::String[, line])

Show a file using the default pager, optionally providing a starting line number. Returns to the julia prompt when you quit the pager.

less(function[, types])

Show the definition of a function using the default pager, optionally specifying a tuple of types to indicate which method to see.

@less()

Evaluates the arguments to the function call, determines their types, and calls the less function on the resulting expression

clipboard(x)

Send a printed form of x to the operating system clipboard (“copy”).

clipboard() → String

Return a string with the contents of the operating system clipboard (“paste”).

require(file::String...)

Load source files once, in the context of the Main module, on every active node, searching standard locations for files. require is considered a top-level operation, so it sets the current include path but does not use it to search for files (see help for include). This function is typically used to load library code, and is implicitly called by using to load packages.

When searching for files, require first looks in the current working directory, then looks for package code under Pkg.dir(), then tries paths in the global array LOAD_PATH.

Like require, except forces loading of files regardless of whether they have been loaded before. Typically used when interactively developing libraries.

include(path::String)

Evaluate the contents of a source file in the current context. During including, a task-local include path is set to the directory containing the file. Nested calls to include will search relative to that path. All paths refer to files on node 1 when running in parallel, and files will be fetched from node 1. This function is typically used to load source interactively, or to combine files in packages that are broken into multiple source files.

include_string(code::String)

Like include, except reads code from the given string rather than from a file. Since there is no file path involved, no path processing or fetching from node 1 is done.

help(name)

Get help for a function. name can be an object or a string.

apropos(string)

Search documentation for functions related to string.

which(f, types)

Return the method of f (a Method object) that will be called for arguments with the given types.

@which()

Evaluates the arguments to the function call, determines their types, and calls the which function on the resulting expression

methods(f[, types])

Show all methods of f with their argument types.

If types is specified, an array of methods whose types match is returned.

methodswith(typ[, showparents])

Return an array of methods with an argument of type typ. If optional showparents is true, also return arguments with a parent type of typ, excluding type Any.

@show()

Show an expression and result, returning the result

versioninfo([verbose::Bool])

Print information about the version of Julia in use. If the verbose argument is true, detailed system information is shown as well.

workspace()

Replace the top-level module (Main) with a new one, providing a clean workspace. The previous Main module is made available as LastMain. A previously-loaded package can be accessed using a statement such as using LastMain.Package.

This function should only be used interactively.

## All Objects¶

is(x, y) → Bool
===(x, y) → Bool
(x, y) → Bool

Determine whether x and y are identical, in the sense that no program could distinguish them. Compares mutable objects by address in memory, and compares immutable objects (such as numbers) by contents at the bit level. This function is sometimes called egal.

isa(x, type) → Bool

Determine whether x is of the given type.

isequal(x, y)

Similar to ==, except treats all floating-point NaN values as equal to each other, and treats -0.0 as unequal to 0.0. For values that are not floating-point, isequal calls == (so that if you define a == method for a new type you automatically get isequal).

isequal is the comparison function used by hash tables (Dict). isequal(x,y) must imply that hash(x) == hash(y).

This typically means that if you define your own == function then you must define a corresponding hash (and vice versa). Collections typically implement isequal by calling isequal recursively on all contents.

Scalar types generally do not need to implement isequal separate from ==, unless they represent floating-point numbers amenable to a more efficient implementation than that provided as a generic fallback (based on isnan, signbit, and ==).

isless(x, y)

Test whether x is less than y, according to a canonical total order. Values that are normally unordered, such as NaN, are ordered in an arbitrary but consistent fashion. This is the default comparison used by sort. Non-numeric types with a canonical total order should implement this function. Numeric types only need to implement it if they have special values such as NaN.

ifelse(condition::Bool, x, y)

Return x if condition is true, otherwise return y. This differs from ? or if in that it is an ordinary function, so all the arguments are evaluated first.

lexcmp(x, y)

Compare x and y lexicographically and return -1, 0, or 1 depending on whether x is less than, equal to, or greater than y, respectively. This function should be defined for lexicographically comparable types, and lexless will call lexcmp by default.

lexless(x, y)

Determine whether x is lexicographically less than y.

typeof(x)

Get the concrete type of x.

tuple(xs...)

Construct a tuple of the given objects.

ntuple(n, f::Function)

Create a tuple of length n, computing each element as f(i), where i is the index of the element.

object_id(x)

Get a unique integer id for x. object_id(x)==object_id(y) if and only if is(x,y).

hash(x[, h])

Compute an integer hash code such that isequal(x,y) implies hash(x)==hash(y). The optional second argument h is a hash code to be mixed with the result.

New types should implement the 2-argument form, typically by calling the 2-argument hash method recursively in order to mix hashes of the contents with each other (and with h). Typically, any type that implements hash should also implement its own == (hence isequal) to guarantee the property mentioned above.

finalizer(x, function)

Register a function f(x) to be called when there are no program-accessible references to x. The behavior of this function is unpredictable if x is of a bits type.

copy(x)

Create a shallow copy of x: the outer structure is copied, but not all internal values. For example, copying an array produces a new array with identically-same elements as the original.

deepcopy(x)

Create a deep copy of x: everything is copied recursively, resulting in a fully independent object. For example, deep-copying an array produces a new array whose elements are deep copies of the original elements. Calling deepcopy on an object should generally have the same effect as serializing and then deserializing it.

As a special case, functions can only be actually deep-copied if they are anonymous, otherwise they are just copied. The difference is only relevant in the case of closures, i.e. functions which may contain hidden internal references.

While it isn’t normally necessary, user-defined types can override the default deepcopy behavior by defining a specialized version of the function deepcopy_internal(x::T, dict::ObjectIdDict) (which shouldn’t otherwise be used), where T is the type to be specialized for, and dict keeps track of objects copied so far within the recursion. Within the definition, deepcopy_internal should be used in place of deepcopy, and the dict variable should be updated as appropriate before returning.

isdefined([object, ]index | symbol)

Tests whether an assignable location is defined. The arguments can be an array and index, a composite object and field name (as a symbol), or a module and a symbol. With a single symbol argument, tests whether a global variable with that name is defined in current_module().

convert(type, x)

Try to convert x to the given type. Conversions from floating point to integer, rational to integer, and complex to real will raise an InexactError if x cannot be represented exactly in the new type.

promote(xs...)

Convert all arguments to their common promotion type (if any), and return them all (as a tuple).

oftype(x, y)

Convert y to the type of x.

widen(type | x)

If the argument is a type, return a “larger” type (for numeric types, this will be a type with at least as much range and precision as the argument, and usually more). Otherwise the argument x is converted to widen(typeof(x)).

julia> widen(Int32)
Int64

julia> widen(1.5f0)
1.5

identity(x)

The identity function. Returns its argument.

## Types¶

super(T::DataType)

Return the supertype of DataType T

issubtype(type1, type2)

True if and only if all values of type1 are also of type2. Can also be written using the <: infix operator as type1 <: type2.

<:(T1, T2)

Subtype operator, equivalent to issubtype(T1,T2).

subtypes(T::DataType)

Return a list of immediate subtypes of DataType T. Note that all currently loaded subtypes are included, including those not visible in the current module.

subtypetree(T::DataType)

Return a nested list of all subtypes of DataType T. Note that all currently loaded subtypes are included, including those not visible in the current module.

typemin(type)

The lowest value representable by the given (real) numeric type.

typemax(type)

The highest value representable by the given (real) numeric type.

realmin(type)

The smallest in absolute value non-subnormal value representable by the given floating-point type

realmax(type)

The highest finite value representable by the given floating-point type

maxintfloat(type)

The largest integer losslessly representable by the given floating-point type

sizeof(type)

Size, in bytes, of the canonical binary representation of the given type, if any.

eps([type])

The distance between 1.0 and the next larger representable floating-point value of type. Only floating-point types are sensible arguments. If type is omitted, then eps(Float64) is returned.

eps(x)

The distance between x and the next larger representable floating-point value of the same type as x.

promote_type(type1, type2)

Determine a type big enough to hold values of each argument type without loss, whenever possible. In some cases, where no type exists to which both types can be promoted losslessly, some loss is tolerated; for example, promote_type(Int64,Float64) returns Float64 even though strictly, not all Int64 values can be represented exactly as Float64 values.

promote_rule(type1, type2)

Specifies what type should be used by promote when given values of types type1 and type2. This function should not be called directly, but should have definitions added to it for new types as appropriate.

getfield(value, name::Symbol)

Extract a named field from a value of composite type. The syntax a.b calls getfield(a, :b), and the syntax a.(b) calls getfield(a, b).

setfield!(value, name::Symbol, x)

Assign x to a named field in value of composite type. The syntax a.b = c calls setfield!(a, :b, c), and the syntax a.(b) = c calls setfield!(a, b, c).

fieldoffsets(type)

The byte offset of each field of a type relative to the data start. For example, we could use it in the following manner to summarize information about a struct type:

julia> structinfo(T) = [zip(fieldoffsets(T),names(T),T.types)...];

julia> structinfo(StatStruct)
12-element Array{(Int64,Symbol,DataType),1}:
(0,:device,Uint64)
(8,:inode,Uint64)
(16,:mode,Uint64)
(32,:uid,Uint64)
(40,:gid,Uint64)
(48,:rdev,Uint64)
(56,:size,Int64)
(64,:blksize,Int64)
(72,:blocks,Int64)
(80,:mtime,Float64)
(88,:ctime,Float64)

fieldtype(value, name::Symbol)

Determine the declared type of a named field in a value of composite type.

isimmutable(v)

True if value v is immutable. See Immutable Composite Types for a discussion of immutability. Note that this function works on values, so if you give it a type, it will tell you that a value of DataType is mutable.

isbits(T)

True if T is a “plain data” type, meaning it is immutable and contains no references to other values. Typical examples are numeric types such as Uint8, Float64, and Complex{Float64}.

julia> isbits(Complex{Float64})
true

julia> isbits(Complex)
false

isleaftype(T)

Determine whether T is a concrete type that can have instances, meaning its only subtypes are itself and None (but T itself is not None).

typejoin(T, S)

Compute a type that contains both T and S.

typeintersect(T, S)

Compute a type that contains the intersection of T and S. Usually this will be the smallest such type or one close to it.

## Generic Functions¶

apply(f, x...)

Accepts a function and several arguments, each of which must be iterable. The elements generated by all the arguments are appended into a single list, which is then passed to f as its argument list.

julia> function f(x, y) # Define a function f
x + y
end;

julia> apply(f, [1 2]) # Apply f with 1 and 2 as arguments
3

apply is called to implement the ... argument splicing syntax, and is usually not called directly: apply(f,x) === f(x...)

method_exists(f, tuple) → Bool

Determine whether the given generic function has a method matching the given tuple of argument types.

julia> method_exists(length, (Array,))
true

applicable(f, args...) → Bool

Determine whether the given generic function has a method applicable to the given arguments.

julia> function f(x, y)
x + y
end;

julia> applicable(f, 1)
false

julia> applicable(f, 1, 2)
true

invoke(f, (types...), args...)

Invoke a method for the given generic function matching the specified types (as a tuple), on the specified arguments. The arguments must be compatible with the specified types. This allows invoking a method other than the most specific matching method, which is useful when the behavior of a more general definition is explicitly needed (often as part of the implementation of a more specific method of the same function).

|>(x, f)

Applies a function to the preceding argument. This allows for easy function chaining.

julia> [1:5] |> x->x.^2 |> sum |> inv
0.01818181818181818

## Syntax¶

eval([m::Module, ]expr::Expr)

Evaluate an expression in the given module and return the result. Every module (except those defined with baremodule) has its own 1-argument definition of eval, which evaluates expressions in that module.

@eval()

Evaluate an expression and return the value.

evalfile(path::String)

Load the file using include, evaluate all expressions, and return the value of the last one.

esc(e::ANY)

Only valid in the context of an Expr returned from a macro. Prevents the macro hygiene pass from turning embedded variables into gensym variables. See the Non-Standard String Literals section of the Metaprogramming chapter of the manual for more details and examples.

gensym([tag])

Generates a symbol which will not conflict with other variable names.

@gensym()

Generates a gensym symbol for a variable. For example, @gensym x y is transformed into x = gensym("x"); y = gensym("y").

parse(str, start; greedy=true, raise=true)

Parse the expression string and return an expression (which could later be passed to eval for execution). Start is the index of the first character to start parsing. If greedy is true (default), parse will try to consume as much input as it can; otherwise, it will stop as soon as it has parsed a valid expression. Incomplete but otherwise syntactically valid expressions will return Expr(:incomplete, "(error message)"). If raise is true (default), syntax errors other than incomplete expressions will raise an error. If raise is false, parse will return an expression that will raise an error upon evaluation.

parse(str; raise=true)

Parse the whole string greedily, returning a single expression. An error is thrown if there are additional characters after the first expression. If raise is true (default), syntax errors will raise an error; otherwise, parse will return an expression that will raise an error upon evaluation.

## System¶

run(command)

Run a command object, constructed with backticks. Throws an error if anything goes wrong, including the process exiting with a non-zero status.

spawn(command)

Run a command object asynchronously, returning the resulting Process object.

DevNull

Used in a stream redirect to discard all data written to it. Essentially equivalent to /dev/null on Unix or NUL on Windows. Usage: run(cat test.txt |> DevNull)

success(command)

Run a command object, constructed with backticks, and tell whether it was successful (exited with a code of 0). An exception is raised if the process cannot be started.

process_running(p::Process)

Determine whether a process is currently running.

process_exited(p::Process)

Determine whether a process has exited.

kill(p::Process, signum=SIGTERM)

Send a signal to a process. The default is to terminate the process.

open(command, mode::String="r", stdio=DevNull)

Start running command asynchronously, and return a tuple (stream,process). If mode is "r", then stream reads from the process’s standard output and stdio optionally specifies the process’s standard input stream. If mode is "w", then stream writes to the process’s standard input and stdio optionally specifies the process’s standard output stream.

open(f::Function, command, mode::String="r", stdio=DevNull)

Similar to open(command, mode, stdio), but calls f(stream) on the resulting read or write stream, then closes the stream and waits for the process to complete. Returns the value returned by f.

Starts running a command asynchronously, and returns a tuple (stdout,stdin,process) of the output stream and input stream of the process, and the process object itself.

ignorestatus(command)

Mark a command object so that running it will not throw an error if the result code is non-zero.

detach(command)

Mark a command object so that it will be run in a new process group, allowing it to outlive the julia process, and not have Ctrl-C interrupts passed to it.

setenv(command, env; dir=working_dir)

Set environment variables to use when running the given command. env is either a dictionary mapping strings to strings, or an array of strings of the form "var=val".

The dir keyword argument can be used to specify a working directory for the command.

|>(command, command)
|>(command, filename)
|>(filename, command)

Redirect operator. Used for piping the output of a process into another (first form) or to redirect the standard output/input of a command to/from a file (second and third forms).

Examples:
• run(ls |> grep xyz)
• run(ls |> "out.txt")
• run("out.txt" |> grep xyz)
>>(command, filename)

Redirect standard output of a process, appending to the destination file.

.>(command, filename)

Redirect the standard error stream of a process.

gethostname() → String

Get the local machine’s host name.

Get the IP address of the local machine, as a string of the form “x.x.x.x”.

getpid() → Int32

Get julia’s process ID.

time([t::TmStruct])

Get the system time in seconds since the epoch, with fairly high (typically, microsecond) resolution. When passed a TmStruct, converts it to a number of seconds since the epoch.

time_ns()

Get the time in nanoseconds. The time corresponding to 0 is undefined, and wraps every 5.8 years.

strftime([format, ]time)

Convert time, given as a number of seconds since the epoch or a TmStruct, to a formatted string using the given format. Supported formats are the same as those in the standard C library.

strptime([format, ]timestr)

Parse a formatted time string into a TmStruct giving the seconds, minute, hour, date, etc. Supported formats are the same as those in the standard C library. On some platforms, timezones will not be parsed correctly. If the result of this function will be passed to time to convert it to seconds since the epoch, the isdst field should be filled in manually. Setting it to -1 will tell the C library to use the current system settings to determine the timezone.

TmStruct([seconds])

Convert a number of seconds since the epoch to broken-down format, with fields sec, min, hour, mday, month, year, wday, yday, and isdst.

tic()

Set a timer to be read by the next call to toc() or toq(). The macro call @time expr can also be used to time evaluation.

toc()

Print and return the time elapsed since the last tic().

toq()

Return, but do not print, the time elapsed since the last tic().

@time()

A macro to execute an expression, printing the time it took to execute and the total number of bytes its execution caused to be allocated, before returning the value of the expression.

@elapsed()

A macro to evaluate an expression, discarding the resulting value, instead returning the number of seconds it took to execute as a floating-point number.

@allocated()

A macro to evaluate an expression, discarding the resulting value, instead returning the total number of bytes allocated during evaluation of the expression.

EnvHash() → EnvHash

A singleton of this type provides a hash table interface to environment variables.

ENV

Reference to the singleton EnvHash, providing a dictionary interface to system environment variables.

@unix()

Given @unix? a : b, do a on Unix systems (including Linux and OS X) and b elsewhere. See documentation for Handling Platform Variations in the Calling C and Fortran Code section of the manual.

@osx()

Given @osx? a : b, do a on OS X and b elsewhere. See documentation for Handling Platform Variations in the Calling C and Fortran Code section of the manual.

@linux()

Given @linux? a : b, do a on Linux and b elsewhere. See documentation for Handling Platform Variations in the Calling C and Fortran Code section of the manual.

@windows()

Given @windows? a : b, do a on Windows and b elsewhere. See documentation for Handling Platform Variations in the Calling C and Fortran Code section of the manual.

## Errors¶

error(message::String)

Raise an error with the given message

throw(e)

Throw an object as an exception

rethrow([e])

Throw an object without changing the current exception backtrace. The default argument is the current exception (if called within a catch block).

backtrace()

Get a backtrace object for the current program point.

catch_backtrace()

Get the backtrace of the current exception, for use within catch blocks.

assert(cond[, text])

Raise an error if cond is false. Also available as the macro @assert expr.

@assert()

Raise an error if cond is false. Preferred syntax for writing assertions.

ArgumentError

The parameters given to a function call are not valid.

BoundsError

An indexing operation into an array tried to access an out-of-bounds element.

EOFError

No more data was available to read from a file or stream.

ErrorException

Generic error type. The error message, in the .msg field, may provide more specific details.

KeyError

An indexing operation into an Associative (Dict) or Set like object tried to access or delete a non-existent element.

An error occurred while including, requiring, or using a file. The error specifics should be available in the .error field.

MethodError

A method with the required type signature does not exist in the given generic function.

ParseError

The expression passed to the parse function could not be interpreted as a valid Julia expression.

ProcessExitedException

After a client Julia process has exited, further attempts to reference the dead child will throw this exception.

SystemError

A system call failed with an error code (in the errno global variable).

TypeError

A type assertion failure, or calling an intrinsic function with an incorrect argument type.

## Events¶

Timer(f::Function)

Create a timer to call the given callback function. The callback is passed one argument, the timer object itself. The timer can be started and stopped with start_timer and stop_timer.

start_timer(t::Timer, delay, repeat)

Start invoking the callback for a Timer after the specified initial delay, and then repeating with the given interval. Times are in seconds. If repeat is 0, the timer is only triggered once.

stop_timer(t::Timer)

Stop invoking the callback for a timer.

## Reflection¶

module_name(m::Module) → Symbol

Get the name of a module as a symbol.

module_parent(m::Module) → Module

Get a module’s enclosing module. Main is its own parent.

current_module() → Module

Get the dynamically current module, which is the module code is currently being read from. In general, this is not the same as the module containing the call to this function.

fullname(m::Module)

Get the fully-qualified name of a module as a tuple of symbols. For example, fullname(Base.Pkg) gives (:Base,:Pkg), and fullname(Main) gives ().

names(x::Module[, all=false[, imported=false]])

Get an array of the names exported by a module, with optionally more module globals according to the additional parameters.

names(x::DataType)

Get an array of the fields of a data type.

isconst([m::Module, ]s::Symbol) → Bool

Determine whether a global is declared const in a given module. The default module argument is current_module().

isgeneric(f::Function) → Bool

Determine whether a function is generic.

function_name(f::Function) → Symbol

Get the name of a generic function as a symbol, or :anonymous.

function_module(f::Function, types) → Module

Determine the module containing a given definition of a generic function.

functionloc(f::Function, types)

Returns a tuple (filename,line) giving the location of a method definition.

functionlocs(f::Function, types)

Returns an array of the results of functionloc for all matching definitions.

## Internals¶

gc()

Perform garbage collection. This should not generally be used.

gc_disable()

Disable garbage collection. This should be used only with extreme caution, as it can cause memory use to grow without bound.

gc_enable()

Re-enable garbage collection after calling gc_disable.

macroexpand(x)

Takes the expression x and returns an equivalent expression with all macros removed (expanded).

expand(x)

Takes the expression x and returns an equivalent expression in lowered form

code_lowered(f, types)

Returns an array of lowered ASTs for the methods matching the given generic function and type signature.

@code_lowered()

Evaluates the arguments to the function call, determines their types, and calls the code_lowered function on the resulting expression

code_typed(f, types)

Returns an array of lowered and type-inferred ASTs for the methods matching the given generic function and type signature.

@code_typed()

Evaluates the arguments to the function call, determines their types, and calls the code_typed function on the resulting expression

code_llvm(f, types)

Prints the LLVM bitcodes generated for running the method matching the given generic function and type signature to STDOUT.

@code_llvm()

Evaluates the arguments to the function call, determines their types, and calls the code_llvm function on the resulting expression

code_native(f, types)

Prints the native assembly instructions generated for running the method matching the given generic function and type signature to STDOUT.

@code_native()

Evaluates the arguments to the function call, determines their types, and calls the code_native function on the resulting expression

precompile(f, args::(Any..., ))

Compile the given function f for the argument tuple (of types) args, but do not execute it.


text:
The second Yamabe invariant with singularities
Annales mathématiques Blaise Pascal, Volume 19 (2012) no. 1, pp. 147-176.

Let $\left(M,g\right)$ be a compact Riemannian manifold of dimension $n\ge 3$.We suppose that $g$ is a metric in the Sobolev space ${H}_{2}^{p}\left(M,{T}^{*}M\otimes {T}^{*}M\right)$ with $p>\frac{n}{2}$ and there exist a point $\phantom{\rule{4pt}{0ex}}P\in M$ and $\delta >0$ such that $g$ is smooth in the ball $\phantom{\rule{4pt}{0ex}}{B}_{p}\left(\delta \right)$. We define the second Yamabe invariant with singularities as the infimum of the second eigenvalue of the singular Yamabe operator over a generalized class of conformal metrics to $g$ and of volume $1$. We show that this operator is attained by a generalized metric, we deduce nodal solutions to a Yamabe type equation with singularities.

DOI: 10.5802/ambp.308
Classification: 58J05
Keywords: Second Yamabe invariant, singularities, Critical Sobolev growth.
Mohammed Benalili 1; Hichem Boughazi 1

1 Université Aboubekr Belkaïd Faculty of Sciences Dept. of Math. B.P. 119 Tlemcen, Algeria
@article{AMBP_2012__19_1_147_0,
author = {Mohammed Benalili and Hichem Boughazi},
title = {The second {Yamabe} invariant with singularities},
journal = {Annales math\'ematiques Blaise Pascal},
pages = {147--176},
publisher = {Annales math\'ematiques Blaise Pascal},
volume = {19},
number = {1},
year = {2012},
doi = {10.5802/ambp.308},
mrnumber = {2978317},
zbl = {1256.58005},
language = {en},
url = {https://ambp.centre-mersenne.org/articles/10.5802/ambp.308/}
}
TY  - JOUR
AU  - Mohammed Benalili
AU  - Hichem Boughazi
TI  - The second Yamabe invariant with singularities
JO  - Annales mathématiques Blaise Pascal
PY  - 2012
DA  - 2012///
SP  - 147
EP  - 176
VL  - 19
IS  - 1
PB  - Annales mathématiques Blaise Pascal
UR  - https://ambp.centre-mersenne.org/articles/10.5802/ambp.308/
UR  - https://www.ams.org/mathscinet-getitem?mr=2978317
UR  - https://zbmath.org/?q=an%3A1256.58005
UR  - https://doi.org/10.5802/ambp.308
DO  - 10.5802/ambp.308
LA  - en
ID  - AMBP_2012__19_1_147_0
ER  -
%0 Journal Article
%A Mohammed Benalili
%A Hichem Boughazi
%T The second Yamabe invariant with singularities
%J Annales mathématiques Blaise Pascal
%D 2012
%P 147-176
%V 19
%N 1
%I Annales mathématiques Blaise Pascal
%U https://doi.org/10.5802/ambp.308
%R 10.5802/ambp.308
%G en
%F AMBP_2012__19_1_147_0
Mohammed Benalili; Hichem Boughazi. The second Yamabe invariant with singularities. Annales mathématiques Blaise Pascal, Volume 19 (2012) no. 1, pp. 147-176. doi : 10.5802/ambp.308. https://ambp.centre-mersenne.org/articles/10.5802/ambp.308/

[1] B. Ammann; E. Humbert The second Yamabe invariant, J. Funct. Anal., Volume 235 (2006) no. 2, pp. 377-412 | DOI | MR

[2] Thierry Aubin Équations différentielles non linéaires et problème de Yamabe concernant la courbure scalaire, J. Math. Pures Appl. (9), Volume 55 (1976) no. 3, pp. 269-296 | MR | Zbl

[3] Mohammed Benalili; Hichem Boughazi On the second Paneitz-Branson invariant, Houston J. Math., Volume 36 (2010) no. 2, pp. 393-420 | MR

[4] Haïm Brézis; Elliott Lieb A relation between pointwise convergence of functions and convergence of functionals, Proc. Amer. Math. Soc., Volume 88 (1983) no. 3, pp. 486-490 | DOI | MR | Zbl

[5] Emmanuel Hebey Introductions à l’analyse sur les variétés, Courant Lecture Notes in Mathematics, 5, Diderot Éditeur, Arts et sciences, Paris, 1997

[6] Farid Madani Le problème de Yamabe avec singularités, Bull. Sci. Math., Volume 132 (2008) no. 7, pp. 575-591 | DOI | MR

[7] R. Schoen; S.-T. Yau Conformally flat manifolds, Kleinian groups and scalar curvature, Invent. Math., Volume 92 (1988) no. 1, pp. 47-71 | DOI | MR | Zbl

[8] Richard Schoen Conformal deformation of a Riemannian metric to constant scalar curvature, J. Differential Geom., Volume 20 (1984) no. 2, pp. 479-495 http://projecteuclid.org/getRecord?id=euclid.jdg/1214439291 | MR | Zbl

[9] Neil S. Trudinger Remarks concerning the conformal deformation of Riemannian structures on compact manifolds, Ann. Scuola Norm. Sup. Pisa (3), Volume 22 (1968), pp. 265-274 | Numdam | MR | Zbl

Cited by Sources:


text:
# titlesec: How to get current chapter number when using [hang]

I'm using the titlesec package so my chapter heading looks like:

1. METHODOLOGY

According to this package documentation, I must use [hang] to get the chapter number and title in the same line. However, I cannot get the number to appear (only the chapter label is displayed).

This is my code:

\documentclass{book}
\usepackage{lipsum}
\usepackage{titlesec}

\titleformat{\chapter}[hang]{\normalfont\bfseries\huge\uppercase}{\thechapter. }{15pt}{}

\begin{document}

\chapter{Methodology}
\lipsum[2]

\chapter{Results}

\lipsum[2]

\end{document}

Do you see anything wrong with it?

• Welcome to TeX.SE. Please provide a compilable document, not such fragments only!
– user31729
Feb 11 '17 at 19:10
• You also can use the [block] style. This is not exactly the same if the chapter title spreads over several lines. That said, \thechapter in your code yields the chapter number. Feb 11 '17 at 19:32
• Where does \justifyheading come from? Feb 11 '17 at 19:43
• Because I'm using the following command to right-aligned: \newcommand*{\justifyheading}{\raggedleft}
– heb
Feb 11 '17 at 19:44
• \uppercase is always wrong; in that position it's very wrong. Feb 11 '17 at 20:34

There is nothing wrong, apart from \uppercase that should never be used.

\documentclass{book}
\usepackage{lipsum}
\usepackage{titlesec}

\titleformat{\chapter}[hang]
{\normalfont\bfseries\huge\raggedright}
{\thechapter. }
{15pt}
{\MakeUppercase}

\begin{document}

\chapter{Methodology}
\lipsum[2]

\chapter{Results}

\lipsum[2]

\end{document}

If you don't get the chapter number, you probably have an outdated version of titlesec, see titlesec: loss of section numbering with the new update (2016/03/15)

@Bernard gave me the answer: by changing [hang] to [block], \thechapter worked!


text:
# Prime numbers as knots: Alexander polynomial

A naive and idle number theory question from a topologist (but not a knot theorist):

I have heard it said (and this came up recently at MO) that there is a fruitful analogy between Spec $\mathbb Z$ and the $3$-sphere. I gather that from an etale point of view the former is $3$-dimensional and simply connected; from the same point of view the subschemes Spec $\mathbb Z/p$ are $1$-dimensional and very much like circles; and the Legendre symbols for two odd primes that figure in quadratic reciprocity are said to be analogous to linking numbers of knots. So, prompted by a recent MO question, I started thinking:

The abelianized fundamental group of the complement of Spec $\mathbb Z/p$ (the group of $p$-adic units) is not terribly different from the abelianized fundamental group of a knot complement (an infinite cyclic group). For nontrivial knots, there is a lot more to the fundamental group of a knot complement than its abelianization. The next little bit, the abelianization of the commutator subgroup (or $H_1$ of the infinite cyclic cover) has an action of that infinite cyclic group, and I recall that the Alexander polynomial of the knot may be created out of this action.

So there must be some analogue of that in number theory, right? Like, some construction involving ideal class groups or idele class groups of $p$-power cyclotomic fields can be interpreted as the Alexander polynomial of a prime number?

-
Short answer: The group of ideles is the group of units of the ring of adeles, so the group of ideles is a multiplicative thing and the group of adeles is an additive thing. The ideles map onto the ideals. I am guessing that "adeles" was coined after "ideles", with "ad-" indicating "additive". Who wants to tell the true story? –  Tom Goodwillie Jul 10 '10 at 0:37
Tom, your guess is basically correct, but I heard that Weil (who coined the name "adeles" to replace the previous "valuation vectors") also intended it as a kind of joke, since adele is a French girl's name too. Then it stuck. –  BCnrd Jul 10 '10 at 1:45
Tom, ideles were invented by Chevalley around 1940 for his non-analytic development of class field theory (all priori work required analytic input at some point), and I believe he gave them the name "ideles" because of how they were used to unify generalized ideal class groups into quotients of a single structure. However, due to the application in class field theory, he gave them a topology with far fewer open sets than the one now used. That they were units of a ring was only recognized later (presumably quite soon), since the context for their invention had no need for it. –  BCnrd Jul 10 '10 at 3:48
I would have given a substantial answer to this question if I were not so lazy. Instead, let me point to the papers: Coates, John; Fukaya, Takako; Kato, Kazuya; Sujatha, Ramdorai; Venjakob, Otmar The $\rm GL_2$ main conjecture for elliptic curves without complex multiplication. Publ. Math. Inst. Hautes Études Sci. No. 101 (2005), 163--208; Fukaya, Takako; Kato, Kazuya A formulation of conjectures on $p$-adic zeta functions in noncommutative Iwasawa theory. Proceedings of the St. Petersburg Mathematical Society. Vol. XII, 1--85, Amer. Math. Soc. Transl. Ser. 2, 219; cont. –  Minhyong Kim Jul 11 '10 at 6:15
mathematik.uni-regensburg.de/preprints/Forschergruppe/… These illustrate how homotopy-theoretic the incarnations have become. In brief, the current view is that the Iwasawa polynomial=p-adic L-function should be viewed as a path in K-theory space. –  Minhyong Kim Jul 11 '10 at 6:18


text:
Le Séminaire de Combinatoire Enumérative et Analytique, rebaptisé Séminaire Philippe Flajolet le 7 avril 2011, a pour objectif de couvrir un large spectre de recherche en combinatoire, et est ouvert à tous les chercheurs et étudiants intéressés.

Il se tient un jeudi tous les deux mois à l'ENSCP où à l'IHP, plus de détails ici.
Attention, le séminaire du jeudi 1 décembre aura exceptionnellement lieu à l'Université Paris 7, dans la Halle aux farines, en salle 580F

Traditionnellement, après chaque exposé, un volontaire se charge de rédiger une petite synthèse des résultats présentés. Voir la page des archives.

Les séances de l'année 2016-2017 sont fixées au: 29 septembre 2016, 1er decembre 2016, 2 février 2017, 30 mars 2017, 1er juin 2017.

###### Prochaine séance: 1er décembre 2016. Attention, le séminaire aura exceptionnellement lieu à l'Université Paris 7, dans la Halle aux farines, en salle 580F
• 10h30 - 11h30: Christina Goldschmidt (Oxford),
Parking on a tree,
.

Consider the following particle system. We are given a uniform random rooted tree on vertices labelled by $[n]=\{1,2,...,n\}$, with edges directed towards the root. Each node of the tree has space for a single particle (we think of them as cars). A number $m \le n$ of cars arrives one by one, and car $i$ wishes to park at node $S_i$, $1 \le i \le m$, where $S_1, S_2, \ldots, S_m$ are i.i.d. uniform random variables on $[n]$. If a car arrives at a space which is already occupied, it follows the unique path oriented towards the root until the first time it encounters an empty space, in which case it parks there; otherwise, it leaves the tree. Let $A_{n,m}$ denote the event that all $m$ cars find spaces in the tree. Lackner and Panholzer proved (via analytic combinatorics methods) that there is a phase transition in this model. Set $m = [\alpha n]$. Then if $\alpha \le 1/2$, $P(A_{n,[\alpha n]}) \to \sqrt{1-2\alpha}/(1-\alpha)$, whereas if $\alpha > 1/2$ we have $P(A_{n,[\alpha n]}) \to 0$. (In fact, they proved more precise asymptotics in $n$ for $\alpha \ge 1/2$.) In this talk, I will give a probabilistic explanation for this phenomenon, and an alternative proof via the objective method.
Based on joint work in progress with Michal Przykucki (Oxford).

• 13h45 - 14h45: Jean-Christophe Novelli (LIGM, Marne-la-Vallée),
Promenade autour de l'inversion de Lagrange,
.

Cet exposé présentera des travaux récents ayant tous des liens profonds avec l'inversion de Lagrange, notamment des calculs dans les opérades dendriformes, des résultats sur les probabilités libres et encore d'autres composantes de la combinatoire algébrique et bijective.
Travaux en commun avec Matthieu Josuat-Vergès, Frédéric Menous et Jean-Yves Thibon.

• 14h45 - 15h45: Guillem Perarnau (Birmingham),
A switching approach to random graphs with a fixed degree sequence,
.

For a fixed degree sequence $D=(d_1,...,d_n)$, let $G(D)$ be a uniformly chosen (simple) graph on $\{1,...,n\}$ where the vertex $i$ has degree $d_i$. The study of $G(D)$ is of special interest in order to model real-world networks that can be described by their degree sequence, such as scale-free networks. While many aspects of $G(D)$ have been extensively studied, most of the obtained results only hold provided that the degree sequence $D$ satisfies some technical conditions. In this talk we will introduce a new approach (based on the switching method) that allows us to study the random graph $G(D)$ imposing no conditions on $D$. Most notably, this approach provides a new criterion on the existence of a giant component in $G(D)$. Moreover, this method is also useful to determine whether there exists a percolation threshold in $G(D)$.
The first part of this talk is joint work with F. Joos, D. Rautenbach and B. Reed, and the second part, with N. Fountoulakis and F. Joos.

• 16h00: Pause café


text:
# Change syntax from other programs to mathematica syntax

Is there a good way to transform syntax from other computer algebra systems or from latex to mathematica syntax?

-
I think this would be a better question, and attract more useful answers, if it were more specific. Eg: "How do I convert TeX to Mathematica syntax", "How do I convert Excel formulas to Mathematica", etc... –  Brett Champion Jan 18 '12 at 16:29
@BrettChampion Maybe. Personally, I am interested in Latex, maple and sage, and the answers correspond to my intention. I would prefer to discus this on meta. This is the private beta after all, I can reformulate, partition or delete my question also tomorrow, there is no hurry. –  Phira Jan 18 '12 at 17:26
Meta thread here: meta.mathematica.stackexchange.com/questions/42/… –  Phira Jan 18 '12 at 17:33
What you're asking for is essentially machine translation applied to programming languages. –  Mike Bantegui Jan 19 '12 at 2:19

There is support for TeX files built in to the Import function. For example:

NotebookPut[Import["http://www.math.wisc.edu/computing/tex/sample.tex"]]

Will load the sample TeX file located at that URL into a Mathematica notebook. You can of course replace the URL with a path to a file on your computer.

The TeX file is imported with "structure" intact (I suppose we'd expect this from Mathematica), so you can play around with how exactly it is formatted.

As for other computer algebra systems, it would surprise me if there was an easy way to translate syntax in general--but you can use StringReplace for simple syntax modifications, as in this example:

ToExpression[StringReplace["Sin(x)+Cos(y)", {"(" -> "[", ")" -> "]"}]]

-

Yes, there is, but it is not particularly simple. Generally, you will have to get somewhere a grammar of the language of interest, and write a parser, which would transform the program given in that languages (as a string) into some Mathematica expression representing the AST (Abstract Syntax Tree) of that program. For this stage, you will need familiarity with some lower-level language (in practice, C or Java), and parser generators with bindings for that languages (Flex/Bison for C and say ANTLR for Java). With some effort, you can then import the program as a Mathematica expression, into Mathematica, using MathLink or LibraryLink if you choose C and J/Link for Java.

The second part you can do in Mathematica. The good news is that replacement rules are very well suited for programming code transformations. One of the biggest problems you will face at this stage is premature evaluation of pieces of code you generate, which you will have to prevent. Some discussion of one simple way of how to do this can be found here.

As of now, however, this is a non-trivial undertaking. We may hope that some day there will be Mathematica bindings for things like Flex/Bison, so that the first part could be done entirely in Mathematica. We may also hope that some better / more powerful ways /libraries will emerge which will facilitate easier generation of Mathematica code.

-

This is a practical workaround which I've used in the past to transfer even huge expressions from other systems:

What I often do in practice is create a TraditionalForm input cell, and paste the expression there. The biggest difference between Mathematica and other systems is that Mathematica uses f[x] while most others use f(x). f(x) is interpreted correctly in TraditionalForm, and the rest of the editing can be done manually (party on the string input, and partly by Replaceing the resulting function)

If it is only an expression (not a program) that you need to convert, this often works very well in practice.

-

Other people have answered for TeX, since that functionality is present in Mathematica. They have also given tips for semi-manually making the translation.

One way would be to use Sage as an intermediate. Sage has interfaces to most of the major computer algebra systems out there. See: http://www.sagemath.org/doc/reference/interfaces.html

Here's an example of going from Maxima to Mathematica

sage: a = maxima('(sin(%e^x) + sqrt(2))^5'); a
(sin(%e^x)+sqrt(2))^5
sage: mathematica(a)
(Sqrt[2] + Sin[E^x])^5

This could be done from within Mathematica by calling Sage from the Mathematica frontend. One neat way of doing this might be to use a new input style that evaluates in Sage, see e.g., WReach's "Mathematica tool bag" post.

-
There was some recent discussion about this on the sage-devel group: Mathematica/Magma/Sage dictionaries –  Simon Jan 18 '12 at 11:24

An excellent book into the subject is Language Implementation Patterns by Terence Parr ( prof. and lead developer of ANTLR ). Part IV of the book covers the topic you are interested in: "Translating and Generating Languages".

http://pragprog.com/book/tpdsl/language-implementation-patterns

-