text:
# cf.RegridOperator¶

class cf.RegridOperator(weights=None, row=None, col=None, coord_sys=None, method=None, src_shape=None, dst_shape=None, src_cyclic=None, dst_cyclic=None, src_mask=None, dst_mask=None, src_coords=None, src_bounds=None, start_index=0, src_axes=None, dst_axes=None, dst=None)[source]

Bases: cf.mixin_container.Container, cfdm.abstract.container.Container

A regridding operator between two grids.

Regridding is the process of interpolating from one grid resolution to a different grid resolution.

The regridding operator stores the regridding weights; auxiliary information, such as the grid shapes; the CF metadata for the destination grid; and the source grid coordinates.

Initialization

Parameters
weights: array_like

The 1-d array of regridding weights for locations in the 2-d dense weights matrix. The locations are defined by the row and col parameters.

row, col: array_like, array_like

The 1-d arrays of the row and column indices of the regridding weights in the dense weights matrix, which has J rows and I columns, where J and I are the total number of cells in the destination and source grids respectively. See the start_index parameter.

coord_sys: str

The name of the coordinate system of the source and destination grids. Either 'spherical' or 'Cartesian'.

method: str

The name of the regridding method.

src_shape: sequence of int

The shape of the source grid.

dst_shape: sequence of int

The shape of the destination grid.

src_cyclic: bool

For spherical regridding, specifies whether or not the source grid longitude axis is cyclic.

dst_cyclic: bool

For spherical regridding, specifies whether or not the destination grid longitude axis is cyclic.

src_mask: numpy.ndarray or None, optional

If a numpy.ndarray with shape src_shape then this is the source grid mask that was used during the creation of the weights. If src_mask is a scalar array with value False, then this is equivalent to a source grid mask with shape src_shape entirely populated with False.

If None (the default), then the weights are assumed to have been created assuming no source grid masked cells.

dst_mask: numpy.ndarray or None, optional

A destination grid mask to be applied to the weights matrix, in addition to those destination grid cells that have no non-zero weights. If None (the default) then no additional destination grid cells are masked. If a Boolean numpy array then it must have shape dst_shape, and a value of True signifies a masked destination grid cell.

start_index: int, optional

Specify whether the row and col parameters use 0- or 1-based indexing. By default 0-based indexing is used.

parameters: Deprecated at version 3.14.0

dst: Field or Domain

The definition of the destination grid.

dst_axes: dict or sequence or None, optional

The destination grid axes to be regridded.

src_axes: dict or sequence or None, optional

The source grid axes to be regridded.

Methods

 copy Return a deep copy. dump A full description of the regrid operator. get_parameter Return a regrid operation parameter. parameters Get the CF metadata parameters for the destination grid. todense Return the weights in dense format. tosparse Return the weights in sparse COOrdinate format.

Attributes

 col The 1-d array of the column indices of the regridding weights. coord_sys The name of the regridding coordinate system. dst The definition of the destination grid. dst_axes The destination grid axes to be regridded. dst_cyclic Whether or not the destination grid longitude axis is cyclic. dst_mask A destination grid mask to be applied to the weights matrix. dst_shape The shape of the destination grid. method The name of the regridding method. name The name of the regridding method. row The 1-d array of the row indices of the regridding weights. src_axes The source grid axes to be regridded. src_bounds The bounds of the source grid cells. src_coords The coordinates of the source grid cells. src_cyclic Whether or not the source grid longitude axis is cyclic. src_mask The source grid mask that was applied during the weights creation. src_shape The shape of the source grid. start_index The start index of the row and column indices. weights The 1-d array of the regridding weights.

Methods


text:
Theory Manual Version 3.4
$\newcommand{\lyxlock}{}$
Subsection 2.5.1: Governing Equations Up Chapter 2: Continuum Mechanics Subsection 2.6.1: Governing Equations

## 2.6 Biphasic-Solute Material

A biphasic-solute material is an extension of the biphasic material model that also includes transport and mechano-chemical effects of a neutral solute. Transport of a solute in a porous medium includes diffusion, resulting from gradients in the solute concentration, and convection of the solute by the solvent, as a result of fluid pressure gradients. Mechano-chemical effects describe phenomena such as osmotic pressurization and swelling.
Subsection 2.5.1: Governing Equations Up Chapter 2: Continuum Mechanics Subsection 2.6.1: Governing Equations

format: plain


text:
# Thread: What factors do 4,6,7 have in common

1. ## What factors do 4,6,7 have in common

Hey guys, not sure how to state this problem.

I am given the numbers 4,6, and 7. I am then told to find the common numbers of these 3 numbers from 1 to 400? How do I go about it besides listing all the multiples of 4, 6, and 7, and then finding the similar numbers? Thanks for any suggestions!

2. any common multiples of these three numbers would be a multiple of all three of the numbers. so multiply them

3. ok, so if I multiply them the first multiple would be 4*6*7 = 168. However, 84 is a common multiple of 4,6, and 7, so it seems this doesn't do the trick. Or am I missing something?

4. Originally Posted by spearfish
ok, so if I multiply them the first multiple would be 4*6*7 = 168. However, 84 is a common multiple of 4,6, and 7, so it seems this doesn't do the trick. Or am I missing something?
Since $4 \times 6 \times 7 = 2^2 \times 2 \times 3 \times 7 = 2 \times 2^2 \times 3 \times 7$, any common multiples of $2^2 \times 3 \times 7$ will be a multiple of 4, 6 and 7.

5. Originally Posted by spearfish
ok, so if I multiply them the first multiple would be 4*6*7 = 168. However, 84 is a common multiple of 4,6, and 7, so it seems this doesn't do the trick. Or am I missing something?
84 is the lowest common multiple of 4,6, & 7. Find all the mutliples of 84 between 84 and 400 = your answer.

6. Mr_fantastic,

Do you mind explaining why you chose 2^2 * 3 * 7 as the common factors? For example, why did you leave out the other 2? Or why not 2 * 3 * 7 instead of 2^2 * ... ?

I am just trying to figure out a methodical method to solve these types of problems and it seems your answer fits this, but just help me understand it.

Thanks!

7. Originally Posted by spearfish
Mr_fantastic,

Do you mind explaining why you chose 2^2 * 3 * 7 as the common factors? For example, why did you leave out the other 2? Or why not 2 * 3 * 7 instead of 2^2 * ... ?

I am just trying to figure out a methodical method to solve these types of problems and it seems your answer fits this, but just help me understand it.

Thanks!
OK, here's a better way:

7 is prime. So just get the lowest common multiple of 3 and 4 (which is 12) and then multiply by 7.

Alternatively, 3 is prime so just get the lowest common multiple of 4 and 7 (which is 28) and then multiply by 3.

8. thanks to all for your time and for your explanations mr_fantastic

when factorized $4*6*7 = 2* 2* 2* 3 *7$
he canceled off one of the 2's because in the factorized form u should be able to form each of the original numbers with the least amount of numbers used, in order to get your lowest common multiple

like for $2*2*3*7$ you can form a 4 u can also form a 6 and also a 7 therefore this will give u, ur lowest common multiple which is 84

10. Originally Posted by spearfish
Mr_fantastic,

... why not 2 * 3 * 7 instead of 2^2 * ... ?

Thanks!
Because $4 = 2 \times 2$ and so therefore is not a factor of $2 \times 2 \times 3 \times 7$.

This method is a methodical way to find the lcm of a set of numbers - break them down into their prime factors and form the number you get by taking the highest indices of those primes that you find in those numbers, and multiply it together.

This is the sort of thing you learn formally in an elementary number theory class at Uni level - it's straightforward to understand but rather trickier to prove.

11. Thanks again for the explanation guys! It makes perfect sense now

12. Originally Posted by arze
any common multiples of these three numbers would be a multiple of all three of the numbers. so multiply them
This is incorrect. 4 and 6 have a factor of 2 in common so the "least common multiple" of 4 and 6 is 2*2*3= 12. The "least common multiple" of 4, 6, and 7 is 12*7= 84. All common multiples of 4, 6, and 7 are multiples of 84.


text:
# How much to tessellate?

This topic is 1730 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Ok, I have the current distance based LOD scheme set up in my hull shader. It works pretty well, but has some non-optimal aspects. cp[0], cp[1] and cp[2] are the corners of my triangle patch.

PatchConstants PatchHS(InputPatch<VertexOutput,10> cp, uint patchID : SV_PrimitiveID)
{
PatchConstants pt;

float3 mid0 = lerp(cp[1].PositionWorld,cp[2].PositionWorld,0.5f);
float3 mid1 = lerp(cp[2].PositionWorld,cp[0].PositionWorld,0.5f);
float3 mid2 = lerp(cp[0].PositionWorld,cp[1].PositionWorld,0.5f);

const float dMax = 250.0f;

float d = distance(mid0,vecEye.xyz);
pt.EdgeTess[0] = 12.0f * pow(saturate((dMax - d)/dMax),3);

d = distance(mid1,vecEye.xyz);
pt.EdgeTess[1] = 12.0f * pow(saturate((dMax - d)/dMax),3);

d = distance(mid2,vecEye.xyz);
pt.EdgeTess[2] = 12.0f * pow(saturate((dMax - d)/dMax),3);

d = distance(cp[9].PositionWorld,vecEye.xyz);
pt.InsideTess = 16.0f * pow(saturate((dMax - d)/dMax),2);

return pt;
}

I'm using the midpoint of my triangle patch edges to calculate distance to the camera. Visually, the need for more or less triangles is nowhere near linear in it's relationship to distance, so I am also applying an exponential curve that sort-of, kind-of helps. This scheme is an improvement over simply using fixed tessellation factors, but it seems that it should be possible to come up with something better. The following screenshot shows one of the weaknesses of a distance based scheme.

[attachment=15203:TessFactors.jpg]

You can see a mountain in the foreground and a valley between this mountain and other mountains in the background. The tiles in the valley are both relatively flat and also oblique to the camera so that they need very little tessellation, yet they are being rendered with more triangles than the mountains in the background that could actually use some extra triangles. Wasteful in the former case and sort of ugly in the latter.

Before I tried the distance scheme, I tried to tessellate based on the screen length of the respective patch edges, but I couldn't figure out how to get it working. Such a scheme would be much more efficient and would also preserve water tight stitching since neighbor edges would have the exact same length. Does anybody know how I can calculate that in the hull shader? I tried multiplying my corner vertices by my ProjectionView matrix and then measuring length, but I couldn't figure out what to do with the results of that calculation. How long is a pixel in my world? I have no idea. If an edge goes from one corner of the screen to the other, how long is that? 100? 0.01? I couldnt find a useful context for the distance between my transformed corner control points.

##### Share on other sites

How about preprocessing your control points to indicate where the 'sharp' areas of the heightmap are?  That way you can efficiently put more detail where it will be most needed before you load your control points, and then you can always apply a scaling of that starting point based on the distance from the viewer.

About the screen space length - you need to project the vertices (as you did), then divide the result by its w-value.  This will put you in clip space, which is in the ranges of [-1,1] for x and y and [0,1] for z.  Then you just need to remap the x and y coordinates to your screen size (i.e. render target height and width).  Finally, you can take the length of the vector between the two points to find out the screen space distance between them in pixels...

That seems like a lot of steps, so you may want to find something that approximates this somehow.  For example, you can just directly use the clip space representation, which will give you a roughly proportional distance that doesn't depend directly on the screen resolution.

##### Share on other sites

Thanks for the reply Jason. I did my best to implement your screen space method, and it almost works except I have one or two bugs that seem impossible. It's one of those times I really wish I could debug my shader. Here is my new hull shader:

PatchConstants PatchHS(InputPatch<VertexOutput,10> cp, uint patchID : SV_PrimitiveID)
{
PatchConstants pt;

float4 corner0 = mul(float4(cp[0].PositionWorld,1.0f),ViewProjection);
float4 corner1 = mul(float4(cp[1].PositionWorld,1.0f),ViewProjection);
float4 corner2 = mul(float4(cp[2].PositionWorld,1.0f),ViewProjection);

corner0 = corner0/(corner0.w + 0.00001f);
corner1 = corner1/(corner1.w + 0.00001f);
corner2 = corner2/(corner2.w + 0.00001f);

const float dMax = 1.5f;

float d0 = abs(distance(corner1.xy,corner2.xy));
pt.EdgeTess[0] = 64.0f * saturate(d0/dMax);

float d1 = abs(distance(corner2.xy,corner0.xy));
pt.EdgeTess[1] = 64.0f * saturate(d1/dMax);

float d2 = abs(distance(corner0.xy,corner1.xy));
pt.EdgeTess[2] = 64.0f * saturate(d2/dMax);

float d3 = min(d0,min(d1,d2));
pt.InsideTess = 64.0f * saturate(d3/dMax);

return pt;
}

I have two problems that I can see in the following screen shot that are probably related somehow. The most obvious problem is that no matter how much space a triangle takes up on screen, my inside tess factor is computing to 2 or less even though I'm clearly trying to use the smallest edge length for the calculation. The second problem I am having is that I can see that the bottom and left sides of the triangles are matching up with their neighbor, but the right side is not! How can only one side not match up? If I switched them there should be two sides not matching up. It would seem that my d2 value is bad or NaN or something, but I can't imagine why that would be, also it seems to almost be right, while NaN values usually jump out at you.

[attachment=15215:TessProb.png]

I almost wonder if my code is being optimized away or something. Here is a picture of the resulting gaps. You can see they are only on the one diagonal.

[attachment=15217:TessProb2.jpg]

##### Share on other sites

So, do you have multiple LODs at the same time on screen ?

if so, did you consider you have to connect them via some intermediary patch that has High detail on one side and low on the other one ? Hunting for those bugs is no fun, though...

##### Share on other sites

So, do you have multiple LODs at the same time on screen ?

if so, did you consider you have to connect them via some intermediary patch that has High detail on one side and low on the other one ? Hunting for those bugs is no fun, though...

LOD in this sense only applies to the edge. There is no problem for each edge to have a different tess factor as long as they line up with their neighbors. There's no need for an  intermediary patch.

On another note, when I simply use pt.EdgeTess[2] = 4.0, the gaps go away and the opposing triangles line up on all sides. That means that for some reason, the distance calculation is giving different results going backwards or forwards, e.i. the distance from corner0 to corner1 is different than the distance from corner1 to corner0. I can't imagine how it ends up that way. For the other edges everything lines up!

##### Share on other sites

And that's why God invented the Breakpoint

Seriously, if the code works in 80% of the cases, it is you who has to figure out why remaining 20% doesn't.

If, for some reason, you cannot debug the shader, use colors of vertices to determine the computed results (e.g. assing a color for each range of the values -> Black (0-63), Red (64-127), Green (128-191), Blue (192-223), White (224-255).

Also, you could use a texture as an output from the pixel shader, if the method above does not yield the desired results.

##### Share on other sites

I went ahead and lowered the max tessellation from 64 to 12 in order to make the problem more obvious. Another thing that is really stumping me is that the inside tessellation result makes no sense at all, even with the problem on edge 2.

[attachment=15220:TessProb3.jpg]

I used this code to change it, and it works much more as intended: (Note that changed d0,d1 etc. to dist0, dist1 in case I was using some register name by accident)

	float dist3 = min(dist0,min(dist1,dist2));
//	pt.InsideTess = 12.0f * saturate(dist3/dMax);
pt.InsideTess = min(pt.EdgeTess[0],min(pt.EdgeTess[1],pt.EdgeTess[2]));

But I can't imagine why this line would give a different result than the line commented out line! The edge factors are calculated the same way as the inside factor! If the bad edge is wrong but close to the others, why would the inside edge be zeroed out when I am using the same distance? The inside factor should match one of the three edges, and the commented out line it matches none of them.

Edited by cephalo

##### Share on other sites

Here is another observation that I did not expect. On the triangle patch in the center of the image, even though the edge nearest to the camera is nearly twice as long as the other two edges, all the edges appear to have the same tess factor! I know I can set them independently, so the three edges must be calculating to the same clip space length. That also explains why one edge is not lining up with its neighbor. It looks like my clip space calculations are wrong, because the distance between the edge points are always the same which is not the case.

Actually this consequence is visible in the above example as well. All of the edges of a single triangle have the same tess factor. What am I doing wrong?

EDIT: wrong again actually. Only the 1 and 2 edges are always the same, the 0 edge appears to be independent. I have no idea what's going on.

[attachment=15221:TessProb4.jpg]

Edited by cephalo

##### Share on other sites

Very interesting problem...  Can you post your declarations for the tessellation factor structure (PatchConstants) and your input control point structure (VertexOutput)?  I'm curious to see how they are declared.  Also, have you tried to run the program with the reference device instead of the hardware device?  I recall when I was working on tessellation a while back that there is huge variability from driver to driver, and you may find that the issue is something to do with a problem in that area...

I will go back through my notes on tessellation and see if I can find anything related to similar issues, and I'll post here if I am able to find anything.

EDIT: One other thing - can you post the attributes of your tessellation setup as well?  For example, the domain, partitioning, etc...  I would also like to take a look at those if possible.

Edited by Jason Z

##### Share on other sites

At work we used to do something very similar to what's described in this presentation, back when we were planning on using a lot of tessellation. It seemed to work well enough, although it was never battle-tested in a production setting.

##### Share on other sites

Here are the requested structures:

struct VertexOutput
{
float3 PositionWorld    : POSITION;
float2 MainTexCoord        : TEXCOORD;
};

struct PatchConstants
{
float EdgeTess[3]    : SV_TessFactor;
float InsideTess    : SV_InsideTessFactor;

};
struct HullOut
{
float3 PositionWorld	: POSITION;
float2 MainTexCoord		: TEXCOORD;
};

[domain("tri")]
[partitioning("fractional_even")]
[outputtopology("triangle_cw")]
[outputcontrolpoints(10)]
[patchconstantfunc("PatchHS")]
HullOut HS(InputPatch<VertexOutput,10> p, uint i : SV_OutputControlPointID, uint patchId : SV_PrimitiveID)
{
HullOut hout;

hout = p;

return hout;
}

I've never used the ref device. I'm not even sure exactly what that is. I'd almost give my left foot to peek into my variables in the shader, (but not \$500!). I think its one of those things that seems to be partially working, but is really not working at all except in creating an illusion of working.

Edited by cephalo

##### Share on other sites

Ok, that stuff all looks fine, and your calculation looks fine to me too.  If you think that there is a low level fundamental problem, then I would recommend to temporarily modify your drawing routine to only render a single control patch, and then you can work on that directly before moving on to the large scale issue.

Next I would suggest getting the tessellation to respond directly to your changes.  So start out with manually setting the tessellation factors, then switch back to your calculated value with the max factor set to something simple like 4.

Similarly, I would set your inside tessellation factor manually first to ensure that it is changeable/controllable, and then make it a function that can't end up with a zero value.  For example, take your saturated result and use that as the interpolant to the lerp function, and use two positive values for the min and max tessellation factor.  It seems that there is some values going to zero, and that is cooking your inside tessellation factor.

##### Share on other sites

Yeah, I've been playing around with it a lot today. Anytime I do anything differently, it works fine. For example I set edge[0] to 4.0, edge[1] to 6.0 and edge[2] to 8.0 and I got what you would expect with no mismatched edges. I can set the inside tess factor to anything and it works fine.

The only thing I changed from my original distance based hull shader is the bit that I displayed. I wonder if there is something wrong with my ProjectionView matrix that for some reason I didn't notice before, or if there is some automatic fix in later stages that eliminates whatever problem it might have.

##### Share on other sites

Did you try the lerp function to ensure you don't end up with zero as a tessellation factor?  Also, did you isolate down to a single triangle patch in your rendering?  I think both of those can give you more confidence in your code.

Also, since you are working from within the patch constant function, it can be difficult to output an appropriate diagnostic information.  If your manual setting of the tessellation factors works, then try using if / then statements to test the data in the patch constant function.  For example, you could do something like this:

PatchConstants PatchHS(InputPatch<VertexOutput,10> cp, uint patchID : SV_PrimitiveID)
{
PatchConstants pt;

float4 corner0 = mul(float4(cp[0].PositionWorld,1.0f),ViewProjection);
float4 corner1 = mul(float4(cp[1].PositionWorld,1.0f),ViewProjection);
float4 corner2 = mul(float4(cp[2].PositionWorld,1.0f),ViewProjection);

corner0 = corner0/(corner0.w + 0.00001f);
corner1 = corner1/(corner1.w + 0.00001f);
corner2 = corner2/(corner2.w + 0.00001f);

const float dMax = 1.5f;

float d0 = abs(distance(corner1.xy,corner2.xy));
pt.EdgeTess[0] = 64.0f * saturate(d0/dMax);

float d1 = abs(distance(corner2.xy,corner0.xy));
pt.EdgeTess[1] = 64.0f * saturate(d1/dMax);

float d2 = abs(distance(corner0.xy,corner1.xy));
pt.EdgeTess[2] = 64.0f * saturate(d2/dMax);

float d3 = min(d0,min(d1,d2));
if ( d3 < 2.0 )
pt.InsideTess = 2.0;
else
pt.InsideTess = 4.0;

return pt;
}

That should give you some way to interrogate different values within that function.

##### Share on other sites

Ok, I'd like to report on the first couple of experiments for today. I flipped my dist1 and dist2 values to see what would happen, and interestingly this did not change the bad edge. Even with the values swapped the bad edge is still edge 2.

PatchConstants PatchHS(InputPatch<VertexOutput,10> cp, uint patchID : SV_PrimitiveID)
{
PatchConstants pt;

float4 corner0 = mul(float4(cp[0].PositionWorld,1.0f),ViewProjection);
float4 corner1 = mul(float4(cp[1].PositionWorld,1.0f),ViewProjection);
float4 corner2 = mul(float4(cp[2].PositionWorld,1.0f),ViewProjection);

corner0 = corner0/(corner0.w + 0.00001f);
corner1 = corner1/(corner1.w + 0.00001f);
corner2 = corner2/(corner2.w + 0.00001f);

const float dMax = 1.5f;

float dist0 = distance(corner1.xy,corner2.xy);
float dist1 = distance(corner2.xy,corner0.xy);
float dist2 = distance(corner0.xy,corner1.xy);

pt.EdgeTess[0] = 12.0f * saturate(dist0/dMax);
//	pt.EdgeTess[0] = 4.0;

pt.EdgeTess[1] = 12.0f * saturate(dist2/dMax);
//	pt.EdgeTess[1] = 6.0;

pt.EdgeTess[2] = 12.0f * saturate(dist1/dMax);
//	pt.EdgeTess[2] = 8.0;

float dist3 = min(dist0,min(dist1,dist2));
pt.InsideTess = 12.0f * saturate(dist3/dMax);
//	pt.InsideTess = min(pt.EdgeTess[0],min(pt.EdgeTess[1],pt.EdgeTess[2]));

return pt;
}

[attachment=15227:TessProb5.jpg]

I also did a test to see if dist1 and dist2 are equal, and they are not equal. Floating point numbers are rarely equal, but I still wanted to test for it.

##### Share on other sites

Ok, here is the most interesting experiment yet. See the following code: When I comment out the 'saturate' line and put a specific tess factor in an edge, it works fine for edge[0] and edge[2], but when I do the exact same thing for edge[1], I get a compiler exception!

Also, when I comment out all the 'saturate' lines and put in all fixed values, all the edges display as defined and the inside tess factor calculation begins to work as I intended!

Can I deduce from this that there is a compiler bug that I have to work around somehow? I giggle at myself for saying that, because whenever I accuse 'the system' of being broken, it's always my fault and I don't remember a time in my life where that wasn't the case.

Anyway, the following code does not compile! Edit: I tried turning off optimization with ShaderFlags None, OptimizationLevel0 and Debug and changing the shader flags does not allow compilation.

PatchConstants PatchHS(InputPatch<VertexOutput,10> cp, uint patchID : SV_PrimitiveID)
{
PatchConstants pt;

float4 corner0 = mul(float4(cp[0].PositionWorld,1.0f),ViewProjection);
float4 corner1 = mul(float4(cp[1].PositionWorld,1.0f),ViewProjection);
float4 corner2 = mul(float4(cp[2].PositionWorld,1.0f),ViewProjection);

corner0 = corner0/(corner0.w + 0.00001f);
corner1 = corner1/(corner1.w + 0.00001f);
corner2 = corner2/(corner2.w + 0.00001f);

const float dMax = 1.5f;

float dist0 = distance(corner1.xy,corner2.xy);
float dist1 = distance(corner2.xy,corner0.xy);
float dist2 = distance(corner0.xy,corner1.xy);

pt.EdgeTess[0] = 12.0f * saturate(dist0/dMax);
//	pt.EdgeTess[0] = 4.0f;

//	pt.EdgeTess[1] = 12.0f * saturate(dist1/dMax);
pt.EdgeTess[1] = 4.0f;

pt.EdgeTess[2] = 12.0f * saturate(dist2/dMax);
//	pt.EdgeTess[2] = 0.01;

float dist3 = min(dist0,min(dist1,dist2));
pt.InsideTess = 12.0f * saturate(dist3/dMax);
//	pt.InsideTess = min(pt.EdgeTess[0],min(pt.EdgeTess[1],pt.EdgeTess[2]));

return pt;
}

EDIT2: I'm going to post the whole shader if anyone would like to confirm this on their machine:

#define p300 0
#define p030 1
#define p003 2
#define p210 3
#define p201 4
#define p120 5
#define p021 6
#define p012 7
#define p102 8
#define p111 9

cbuffer PerFrameBuffer : register(b0)
{
//float4x4 World; This is just the identity matrix, so not needed
float4x4 ViewProjection;
float4 vecEye;
float4 LightDirection;
float4 LightColor;
};

struct VertexOutput
{
float3 PositionWorld	: POSITION;
float2 MainTexCoord		: TEXCOORD;
};

struct PatchConstants
{
float EdgeTess[3]	: SV_TessFactor;
float InsideTess	: SV_InsideTessFactor;

};

PatchConstants PatchHS(InputPatch<VertexOutput,10> cp, uint patchID : SV_PrimitiveID)
{
PatchConstants pt;

float4 corner0 = mul(float4(cp[0].PositionWorld,1.0f),ViewProjection);
float4 corner1 = mul(float4(cp[1].PositionWorld,1.0f),ViewProjection);
float4 corner2 = mul(float4(cp[2].PositionWorld,1.0f),ViewProjection);

corner0 = corner0/(corner0.w + 0.00001f);
corner1 = corner1/(corner1.w + 0.00001f);
corner2 = corner2/(corner2.w + 0.00001f);

const float dMax = 1.5f;

float dist0 = distance(corner1.xy,corner2.xy);
float dist1 = distance(corner2.xy,corner0.xy);
float dist2 = distance(corner0.xy,corner1.xy);

pt.EdgeTess[0] = 12.0f * saturate(dist0/dMax);
//	pt.EdgeTess[0] = 4.0f;

//	pt.EdgeTess[1] = 12.0f * saturate(dist1/dMax);
pt.EdgeTess[1] = 4.0f;

pt.EdgeTess[2] = 12.0f * saturate(dist2/dMax);
//	pt.EdgeTess[2] = 0.01;

float dist3 = min(dist0,min(dist1,dist2));
pt.InsideTess = 12.0f * saturate(dist3/dMax);
//	pt.InsideTess = min(pt.EdgeTess[0],min(pt.EdgeTess[1],pt.EdgeTess[2]));

return pt;
}

struct HullOut
{
float3 PositionWorld	: POSITION;
float2 MainTexCoord		: TEXCOORD;
};

[domain("tri")]
[partitioning("fractional_even")]
[outputtopology("triangle_cw")]
[outputcontrolpoints(10)]
[patchconstantfunc("PatchHS")]
HullOut HS(InputPatch<VertexOutput,10> p, uint i : SV_OutputControlPointID, uint patchId : SV_PrimitiveID)
{
HullOut hout;

hout = p;

return hout;
}

Edited by cephalo

##### Share on other sites
June 2010 SDK compiler (version 9.29.952.3111) ? Yeah, same result here.

I should have mentioned earlier that this compiler has troubles with tesselation. You were more "lucky" to trigger a compiler crash. I only found out the hard way: Compiled but produced some funny results.

With the compiler coming with the Windows 8 SDK, version 9.30.960.8229, your shader compiles fine.

##### Share on other sites

June 2010 SDK compiler (version 9.29.952.3111) ? Yeah, same result here.

I should have mentioned earlier that this compiler has troubles with tesselation. You were more "lucky" to trigger a compiler crash. I only found out the hard way: Compiled but produced some funny results.

With the compiler coming with the Windows 8 SDK, version 9.30.960.8229, your shader compiles fine.

How do I check which compiler I am using? What files are involved? I do have the June 2010 SDK because I needed PIX, but I thought I also have the Windows 8 SDK as well. I have no idea what's compiling my shader code. I wonder if the new compiler will allow my code to work properly.

##### Share on other sites
The command line compiler dumps its version when calling fxc /?. Compiling through the runtime is done through D3DCompile (or rather the SharpDX/SlimDX managed version thereof). The June 2010 SDK then uses the d3dcompiler_43.dll (the File Version actually is the compiler version), the Windows 8 SDK the d3dcompiler_44.dll.Hmmm, I'm currently digging the docs if one can grab that version through shader reflection.

Anyway: If you write your compiled binaries to a file (shader.fxo, see below) then fxc can grab the assembly from them with

The version is at the second line in shader.asm.

Edit: Ok, there is a Version field in ShaderDescription, but even the docs are enigmatic here. The field Creator, a string, is more informative:

Microsoft (R) HLSL Shader Compiler 9.30.960.8229

Edit2: Yeah, forget about that Version field, it does not change when switching compilers. My bet it's rather shader type (VS, HS, etc). Edited by unbird

##### Share on other sites

Ok, I installed the Windows 8 SDK on my home computer, and doing a search tells me that I have about 100 versions of this dll on my computer. The highest number goes up to d3dcompiler_46.dll. The one in my new SDK is 9.30.9200.20546. My SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile method is still using 9.29.952.3111 according the Creator field. How do I coax SharpDX to use the new shader compiler?

##### Share on other sites

I'm not sure how to get SharpDX to do it, but in general the first instance of a DLL that can be found either in the application's directory or the path will get loaded.  So I would start out with putting it into your executable directory and see if that works for you.

Even for the native C++ side I have to copy that DLL to the executable folder, so it isn't a problem limited to SharpDX.

##### Share on other sites

You might be able to just directly call D3DCompile from that DLL using p/invoke.

##### Share on other sites
An alternative is to use the command line compiler (that's how I checked your shader), i.e. generate binaries offline and load them in your app.

fxc.exe /E HS /T hs_5_0 /Fo hs.fxo /Fx hs.asm hs.hlsl

Hmmm, can't seem to force SlimDX to load the newer DLL with that copy trick. I hope your thread in the SharpDX forum will reveal something.

##### Share on other sites
Hmm, I'm not having much luck with the command line compiler. Here is my result.

C:\Users\rjm\Documents\Visual Studio 2012\Projects\HexMapDemo\HexMapDemo\bin\Deb
ug\Content\Effects\HexVertTri_HS.fx(1,1): error X3000: Illegal character in shad
er file

Here is the exact command I used:
C:\Users\rjm\Documents\Visual Studio 2012\Projects\HexMapDemo\HexMapDemo\bin\Deb
ug\Content\Effects>fxc /E HS /T hs_5_0 /Fo HexVertTri_HS.fxo /Fx HexVertTri_HS.a
sm HexVertTri_HS.fx

EDIT: Ooh, just got a reply from xoofx over at SharpDX. I'm going to try to change over my SharpDX build. Hopefully that will make everything as easy as before.
Edited by cephalo

##### Share on other sites

Ok, I have that squared away and I'm back in business! My algorithm works great, I just have to tweak it so that both low detail and high detail aren't so quick to appear. I can handle that.

After this I'll need to see some performance info of some kind, so I need to print text. I'll open a new thread for that. My research on that topic has given me some conflicting info.


text:
# How to delay execution of execute() function in an Addon?

I have the following code:

bl_info = {
"name": "Align select verts to abs pos",
"category": "Mesh",
}

import bpy
import bmesh

class MeshAlignVerts(bpy.types.Operator):
bl_idname = "mesh.align_verts"
bl_label = "Align verts pos"
bl_options = {'REGISTER', 'UNDO'}

x_pos = bpy.props.FloatProperty(name="X",description="X axis",default=0.0)
y_pos = bpy.props.FloatProperty(name="Y",description="Y axis",default=0.0)
z_pos = bpy.props.FloatProperty(name="Z",description="Z axis",default=0.0)

chosen_axis = bpy.props.EnumProperty(items=(('X','X','Align along X axis'),('Y','Y','Align along Y axis'),('Z','Z','Align along Z axis')),name="Choose Axis")

def execute(self,context):
print (self.chosen_axis)
self.update_indiv_vert_pos(context)
print ("Executed script")
return {'FINISHED'}

# update individual verts
def update_indiv_vert_pos(self,context):
mesh=bmesh.from_edit_mesh(context.object.data)
sel_verts = []
for v in mesh.verts:
if v.select:
sel_verts.append(v)
# TODO: Add logic to move points along custom defined transform orientation
#   bpy.context.space_data.transform_orientation = 'GLOBAL'
for v in sel_verts:
if self.chosen_axis == 'X':
v.co.x = self.x_pos
if self.chosen_axis == 'Y':
v.co.y = self.y_pos
if self.chosen_axis == 'Z':
v.co.z = self.z_pos

def register():
bpy.utils.register_class(MeshAlignVerts)

def unregister():
bpy.utils.unregister_class(MeshAlignVerts)

if __name__ == "__main__":
register()

I want to either add a button which when pressed will call the function in execute. Or at least wait for the user to specify values for the Float properties and then choose an axis which then calls the function in execute()

How can I achieve this ?

This question looks similar to Addon: run execute() only when button is clicked

I have read that but am not able to get any sufficiently useful info from the responses there can someone please guide me on what to do ?

Also what are the other possible alternatives to delaying execution of the execute function for this script ?

Normally you can let Blender's layout system draw the properties, but when you want to have an action button on an Operator UI, you have to specify the whole interface. You might even consider writing a bit of Panel code instead of trying to do it all in the Operator.

But if you do want to stick with the Operator only you could augment your current Operator code with.

• an unlocked property (boolean),
• an explicit draw() function,
• replace your current execute() function with something that checks if the unlocked property was set to True yet.

code:

unlocked = bpy.props.BoolProperty()

def draw(self, context):
scn = context.scene
l = self.layout
col = l.column()

col.prop(self, 'x_pos')
col.prop(self, 'y_pos')
col.prop(self, 'z_pos')
col.prop(self, 'chosen_axis')
col.operator('mesh.align_verts', text='Mesh Align').unlocked = True

def execute(self,context):
print (self.chosen_axis)
if self.unlocked:
self.update_indiv_vert_pos(context)
print ("Executed script")
return {'FINISHED'}

I would not not use an Operator as a replacement for a proper UI panel.

• Should "col.operator('mesh.align_verts', text='Mesh Align').unlocked = True" be set to False if I do not want the execute function to be run the first time when the operator is called from the menu. So that only the second time when the button is actually clicked action is taken ? Nov 27 '15 at 10:42
• Was unsure if the line 'col.operator('mesh.align_verts', text='Mesh Align').unlocked = True' would immediately call the execute function having the 'unlocked' property set to True rather than on button press. Nov 27 '15 at 10:52
• Yep. That line has no effect on the value of unlocked until you press the button. Nov 27 '15 at 10:55


text:
# Understanding parameters of beta family in brms

Hi there,

I’m quite new to brms and especially to handling the beta distribution, so I hope my issue is not too low-level:

I want to fit a Bayesian model with a response variable distributed between 0 and 1 (with zero inflation), so I decided for the zero inflated beta family in brms.

``````    fit <- brm(formula = y ~ 1,
data = data,
``````

But along the way, some unclarities have emerged:

1. When learning more about the beta distribution, it turned out that there seem to be two different ways for its parameterization: (a) mu/mean and phi/precision parameter, or (b) a and b with a = mu*phi and b = (1−mu)*phi. I’m not entirely sure which parameterization is used in brms.

2. I’m struggling with interpreting the posteriors because of the logit/log transformation in the beta model. Do I understand it correctly: The posterior estimates for “Intercept”/“phi” are in logit/log scale, hence need to be converted into probability scale for interpretation?

`````` estimate.Intercept <- posterior_summary(as.data.frame(fit)\$b_Intercept)[1]
a <- exp(estimate.Intercept) / (1 + exp(estimate.Intercept) )

estimate.phi <- posterior_summary(as.data.frame(fit)\$phi)[1] #phi
b <- exp(estimate.phi)
``````

And when transformed, those two are the parameters needed to define the shape of the beta distribution? So, basically dbeta(x, a, b) returns the curve of my predicitve posterior distribution?

Thanks a lot!

1 Like

Hi,

in almost all cases, `brms` parametrizes the distributions so that the main predictor corresponds to the mean, so it uses the `mu` / `phi` parametrization.

Also, you can often gain insight into how stuff is implemented in `brms` by inspecting the generated Stan code via `make_stancode`

Yes, the parameter estimates from `brms` are before applying the inverse-link functions (you can inspect the default link functions at the help page for `brmsfamily`). However, to get accurate transformations, you generally need to work with individual samples and take summaries (e.g. mean) as the last step in the process. So a better way to compute estimate of `a` and `b` would be: for each sample, compute a value for `a` and `b` and then compute the mean of `a` and mean of `b` from those samples (this willl generally give somewhat different results than the method you’ve shown).

Also note, that you can use `posterior_linpred`, `posterior_epred` and `prepare_predictions` to simplify most of the common tasks.

Best of luck with your model!

2 Likes

Hi @Rigaldo, I found two perspectives helpful when interpreting beta parameters:

1. The logit scale tells you if your effect is positive, negative or uncertain. This in itself can be interesting but often times we would like to know how big an effect is as well. Here we have the problem that you can’t interpret the parameters on their own. Due to the nonlinearity of the link function, the effect of your parameter is influenced by the rest of the model.
2. This is where the `conditional_effects()` function can be very handy. It shows you the effect you are looking for for your average sample. While it again doesn’t show the complete picture, as the effect looks different for data points further away from the mean, it gives you a quick look at the outcome scale.

I have also written a small introduction for how to interpret such effects here (Page 11, Introduction of result section) maybe that is helpful as well.

If you want to see (so visuals, not numbers) your posterior, `pp_check()` is also a very useful tool. It shows you what your posterior looks like on the outcome scale.

4 Likes

Hi @Rigaldo
You are correct that the parameters are shown to you on the logit scale, which means that to understand them a bit more easily it is helpful to convert them back to the probability scale (e.g., with the function, plogis). The beta scale is parameterised as mean/mu and phi (phi is the spread of the data around the mean, a bit like a standard deviation for the normal distribution). To plot this type of beta distribution and understand it better, you can use the prop (dprop, rprop) etc. function from the package extradistr (PropBeta: Beta distribution of proportions in extraDistr: Additional Univariate and Multivariate Distributions). The usual beta function in R is not using the same parameterisation.

Below are some plots I previously made to understand the meaning of different mu and phi values that you may find useful (ignore the SD dots, they relate to a prior I had set on the parameter).

It looks like you also have a zero inflation think going on, so you would need to factor in whatever the effect of that is when you are trying to understand your results.

1 Like

Thanks a lot to all of you @scholz , @martinmodrak , @JimBob ! All of your hints are very useful and make things a lot more understandable.

1 Like

Hi, just a short follow-up question: when assigning prior distributions for parameters (e.g. mu intercept), do I define those in the outcome scale or in the logit-transformed-scale?

edit: It strongly assume that this has to take place in log(it) scale too, but a short confirmation would be great.

1 Like

The priors for model coefficients (intercept, fixed/varying effects, …) are always on the scale where the model is linear, i.e. on the logit-transformed scale in this case. Priors for auxiliary parameters (e.g. `phi` in this model, `sigma` for normal-distributed models) is usually directly on the non-transformed parameters.

1 Like

Is this also the case if I want to predict phi?

The formula for my zero-inflated beta-model is:

``````bf(FL ~ 1 + YC,
phi ~ 1 + YC,
zi ~ 1 + access)
``````

So, I have to give priors for the intercepts for phi and zi in non-transformed scale?

This was a thing I wanted left out to avoid confusion, but probably shouldn’t have: If you don’t predict the parameters, you give priors for them on non-transformed scale. When you predict them, the predictors become linear coefficients as any other and work on the transformed scale - the transformations are specified by the `link_XX` parameters of the families (and you can change them if you need).

So notably you would have:

``````# Prior on untransformed sigma
brm(y ~ x, data = dd, family = "gaussian",
prior = prior(normal(0,5), class = "sigma"))

# Prior on log-sigma (as there are no other predictors for sigma)
brm(bf(y ~ x, sigma ~ 1), data = dd, family = "gaussian",
prior = prior(normal(0,5), class = "Intercept", dpar = "sigma"))
``````

When in doubt you can always use `make_stancode` to see what’s happening. (I just did that to verify my understanding is correct)

Thanks!

Just to be sure: The two defined priors for sigma in your example are quite different, arent they?

1 Like

Yes, those would imply very different prior distributions of the data.

1 Like


text:
Price–earnings ratio

The price-earnings ratio, also known as P/E ratio, P/E, or PER, is the ratio of a company's share (stock) price to the company's earnings per share. The ratio is used for valuing companies and to find out whether they are overvalued or undervalued.

${\displaystyle P/E={\frac {\text{Share Price}}{\text{Earnings per Share}}}}$

As an example, if share A is trading at $24 and the earnings per share for the most recent 12-month period is$3, then share A has a P/E ratio of 24/3 or 8. Put another way, the purchaser of the share is investing \$8 for every dollar of earnings. Companies with losses (negative earnings) or no profit have an undefined P/E ratio (usually shown as "not applicable" or "N/A"); sometimes, however, a negative P/E ratio may be shown.

Versions

There are multiple versions of the P/E ratio, depending on whether earnings are projected or realized, and the type of earnings.

• "Trailing P/E" uses the weighted average number of common shares in issue divided by the net income for the most recent 12-month period. This is the most common meaning of "P/E" if no other qualifier is specified. Monthly earnings data for individual companies are not available, and in any case usually fluctuate seasonally, so the previous four quarterly earnings reports are used and earnings per share are updated quarterly. Note, each company chooses its own financial year so the timing of updates varies from one to another.
• "Trailing P/E from continued operations" uses operating earnings, which exclude earnings from discontinued operations, extraordinary items (e.g. one-off windfalls and write-downs), and accounting changes.
• "Forward P/E": Instead of net income, this uses estimated net earnings over next 12 months. Estimates are typically derived as the mean of those published by a select group of analysts (selection criteria are rarely cited).

Some people mistakenly use the formula market capitalization / net income to calculate the P/E ratio. This formula often gives the same answer as market price / earnings per share, but if new capital has been issued it gives the wrong answer, as market capitalization = market price × current number of shares whereas earnings per share= net income / weighted average number of shares.

Variations on the standard trailing and forward P/E ratios are common. Generally, alternative P/E measures substitute different measures of earnings, such as rolling averages over longer periods of time (to attempt to "smooth" volatile or cyclical earnings, for example),[2] or "corrected" earnings figures that exclude certain extraordinary events or one-off gains or losses. The definitions may not be standardized. For companies that are loss-making, or whose earnings are expected to change dramatically, a "primary" P/E can be used instead, based on the earnings projections made for the next years to which a discount calculation is applied.

Interpretation

As the ratio of a stock (share price) to a flow (earnings per share), the P/E ratio has the units of time. It can be interpreted as the amount of time over which the company would need to sustain its current earnings in order to make enough money to pay back the current share price.[3] While the P/E ratio can in principle be given in terms of any time unit, in practice it is essentially always implicitly reported in years, with the unit of "years" rarely indicated explicitly. (This is the convention followed in this article.)

The price/earnings ratio (PER) is the most widely used method for determining whether shares are "correctly" valued in relation to one another. But the PER does not in itself indicate whether the share is a bargain. The PER depends on the market’s perception of the risk and future growth in earnings. A company with a low PER indicates that the market perceives it as higher risk or lower growth or both as compared to a company with a higher PER. The PER of a listed company’s share is the result of the collective perception of the market as to how risky the company is and what its earnings growth prospects are in relation to that of other companies. Investors use the PER to compare their own perception of the risk and growth of a company against the market’s collective perception of the risk and growth as reflected in the current PER. If investors believe that their perception is superior to that of the market, they can make the decision to buy or sell accordingly.[4]

Historical P/E ratios for the U.S. stock market

Since 1900, the average P/E ratio for the S&P 500 index has ranged from 4.78 in Dec 1920 to 44.20 in Dec 1999.[5] However, except for some brief periods, during 1920–1990 the market P/E ratio was mostly between 10 and 20.[6]

The average P/E of the market varies in relation with, among other factors, expected growth of earnings, expected stability of earnings, expected inflation, and yields of competing investments. For example, when U.S. treasury bonds yield high returns, investors pay less for a given earnings per share and P/E's fall.

The average U.S. equity P/E ratio from 1900 to 2005 is 14 (or 16, depending on whether the geometric mean or the arithmetic mean, respectively, is used to average).

Jeremy Siegel has suggested that the average P/E ratio of about 15 [7] (or earnings yield of about 6.6%) arises due to the long term returns for stocks of about 6.8%. In Stocks for the Long Run, (2002 edition) he had argued that with favorable developments like the lower capital gains tax rates and transaction costs, P/E ratio in "low twenties" is sustainable, despite being higher than the historic average.

Set out below are the recent year end values of the S&P 500 index and the associated P/E as reported.[8] For a list of recent contractions (recessions) and expansions see U.S. Business Cycle Expansions and Contractions.

Date Index P/E EPS growth % Comment
2018-03-312640.8722.88
2017-12-312673.6124.33
2016-12-312238.8323.68
2015-12-312043.9423.62
2014-12-312058.9020.12
2013-12-311848.3618.45
2012-12-311426.1916.49
2011-12-311257.6014.46
2010-12-311257.6416.26
2009-12-311115.1021.88
2008-12-31903.2560.70
2007-12-311468.3622.191.4
2006-12-311418.3017.4014.7
2005-12-311248.2917.8513.0
2004-12-311211.9220.7023.8
2003-12-311111.9222.8118.8
2002-12-31879.8231.8918.5
2001-12-311148.0846.50−30.82001 contraction resulting in P/E peak
2000-12-311320.2826.418.6Dot-com bubble burst: 10 March 2000
1999-12-311469.2530.5016.7
1998-12-311229.2332.600.6
1997-12-31970.4324.438.3
1996-12-31740.7419.137.3
1995-12-31615.9318.1418.7
1994-12-31459.2715.0118.0Low P/E due to high recent earnings growth.
1993-12-31466.4521.3128.9
1992-12-31435.7122.828.1
1991-12-31417.0926.12−14.8
1990-12-31330.2215.47−6.9July 1990 – March 1991 contraction.
1989-12-31353.4015.45.
1988-12-31277.7211.69.Bottom (Black Monday was 19 Oct 1987)

Note that at the height of the Dot-com bubble P/E had risen to 32. The collapse in earnings caused P/E to rise to 46.50 in 2001. It has declined to a more sustainable region of 17. Its decline in recent years has been due to higher earnings growth.

The P/E ratio of a company is a major focus for many managers. They are usually paid in company stock or options on their company's stock (a form of payment that is supposed to align the interests of management with the interests of other stock holders). The stock price can increase in one of two ways: either through improved earnings or through an improved multiple that the market assigns to those earnings. In turn, the primary drivers for multiples such as the P/E ratio is through higher and more sustained earnings growth rates.

Consequently, managers have strong incentives to boost earnings per share, even in the short term, and/or improve long term growth rates. This can influence business decisions in several ways:

• If a company wants to acquire companies with a higher P/E ratio than its own, it usually prefers paying in cash or debt rather than in stock. Though in theory the method of payment makes no difference to value, doing it this way offsets or avoids earnings dilution (see accretion/dilution analysis).
• Conversely, companies with higher P/E ratios than their targets are more tempted to use their stock to pay for acquisitions.
• Companies with high P/E ratios but volatile earnings may be tempted to find ways to smooth earnings and diversify risk—this is the theory behind building conglomerates.
• Conversely, companies with low P/E ratios may be tempted to acquire small high growth businesses in an effort to "rebrand" their portfolio of activities and burnish their image as growth stocks and thus obtain a higher PE rating.
• Companies try to smooth earnings, for example by "slush fund accounting" (hiding excess earnings in good years to cover for losses in lean years). Such measures are designed to create the image that the company always slowly but steadily increases profits, with the goal to increase the P/E ratio.
• Companies with low P/E ratios are usually more open to leveraging their balance sheet. As seen above, this mechanically lowers the P/E ratio, which means the company looks cheaper than it did before leverage, and also improves earnings growth rates. Both of these factors help drive up the share price.
• Strictly speaking, the ratio is measured in years, since the price is measured in dollars and earnings are measured in dollars per year. Therefore, the ratio demonstrates how many years it takes to cover the price, if earnings stay the same.


text:
# Complex conductance. Active and reactive power

Complex conductance $Y$ is the value, reverse to the complex resistance $Z$, where $Y=\frac{1}{Z}=y{e}^{–j\phi }$. Complex conductance is measured with .

Ohm Law’s using the conductivity concept is $I=U*Y$. The current can be presented like $I={I}_{a}+{I}_{r}$ where ${I}_{a}$ is an active consistent of current and ${I}_{r}$  is a reactive consistent.

The module of complex resistance .

Here the z parameter is a hypotenuse, $X$ and $R$ are the sides of the triangle. The resistance triangle shows the relation between the active and reactive resistances. So active and reactive conductances are also related to each other with the triangle model,  $y=\sqrt{{g}^{2}+{b}^{2}}$.

In accordance with the first of Kirchhoff’s Laws, the sum of all the currents of the node is equal to 0, i.e.,.

We can represent each current in a complex form so  .

So it does mean that  .

Let’s consider the second Kirchhoff Law regarding the example of the circuit containing the EMF element, resistor, inductance and capacitance. So .

The sums on the both sides of the equation can be replaced with:

This is a short form of the second Kirchhoff Law.

Note, that all the potentials of the AC circuit are complex numbers. Every element of the circuit has its complex potential. These potentials can be drawn on a plane, and the aggregate of all complex potentials on the plane are called a topographic diagram.

Active power of the electric circuit element is the average value of an instantaneous  power value over the period of time T :

Let’s consider the current as $i={I}_{m}sin\omega t$ and $u={U}_{m}\mathrm{sin}\left(\omega t+\phi \right)$, then $P=\frac{1}{T}{\int }_{T}^{}i*u*dt=\frac{{I}_{m}{U}_{m}}{2}\mathrm{cos}\phi$.

The active power is the heat dissipating in the element with the resistance  in the unit of time, where${U}_{m}sin\left(\omega t+\phi \right)=R{I}_{m}sin\omega t$.

It is measured with Watts (Wt). The reactive power $Q$ of the piece of electric circuit is equal to the potential of the circuit element multiplied by the current of the piece of circuit and the sinus of angle between the potential and current, so $Q=U*I\mathrm{sin}\phi$.

It is measures with $Volt*Ampere$ reactive. Let’s consider in detail what is reactive power in a piece of electric circuit in series with connected resistance $R$, capacitance $C$ and inductance $L$.

So we can see that reactive power consists of a static part and a dynamic part. The static part is organised at the beginning of the electric circuit excitation process and does not change any further. The dynamic part changes during the electric circuit process excitation.

The average reactive energy of the piece of electric circuit per the quarter of the period is${W}_{av}=\frac{4}{T}{\int }_{–\frac{T}{8}}^{\frac{T}{8}}{W}_{me}dt=\frac{2}{\pi \omega }Q$.

This does mean that the  load and generating elements exchange the energy twice per period. The total power $S=U*I$, the active, reactive and total energies are connected by the relation ${S}^{2}={P}^{2}+{Q}^{2}$ where $P$ and $Q$ are catheters and $S$ is hypotenuse.

Let’s consider the complex statement $\stackrel{˙}{A}=A{e}^{j{\phi }_{A}}=Acos{\phi }_{A}+jAsin{\phi }_{A}$,  and conjugated complex number ${A}^{*}=A{e}^{–j{\phi }_{A}}=Acos{\phi }_{A}–jAsin{\phi }_{A}.$

Let’s consider voltage at the electric circuit $U=U{e}^{j{\phi }_{u}}$ , current $I=I{e}^{j{\phi }_{i}}$ The power $S=U{I}^{*}=UI{e}^{j\left({\phi }_{u}–{\phi }_{i}\right)}=UIcos\phi +jUIsin\phi =P+jQ$. Here $P=Re\left\{U{I}^{*}\right\}$ is an active power, $S=Im\left\{U{I}^{*}\right\}$ is a reactive power.


text:
## Numerical methods for higher order Sturm-Liouville problems.(English)Zbl 0970.65087

The authors review some efficient numerical methods for certain classes of linear selfadjoint and non-selfadjoint eigenvalue problems, respectively, where they concentrate on methods treated in their own work. For a class of $$2m$$th-order selfadjoint problems, the numerical schemes yield approximations to eigensolutions and to the counting function $$N(\lambda)$$ as well. For a class of non-selfadjoint problems exhibiting the so-called Birkhoff regularity, the numerical code can find eigenvalues $$\lambda$$ in a rectangular, left half plane, or vertical strip. Numerical results are presented.

### MSC:

 65L15 Numerical solution of eigenvalue problems involving ordinary differential equations 34L16 Numerical approximation of eigenvalues and of other parts of the spectrum of ordinary differential operators 34B24 Sturm-Liouville theory

SLEUTH; aicm
Full Text:

### References:

 [1] Atkinson, F., Discrete and continuous boundary problems, (1964), Academic Press New York · Zbl 0117.05806 [2] Birkhoff, G.D., On the asymptotic character of the solutions of certain linear differential equations containing a parameter, Trans. AMS, 9, 219-223, (1908) [3] Birkhoff, G.D., Boundary value problems and expansion problems of ordinary differential equations, Trans. AMS, 9, 373-395, (1908) · JFM 39.0386.02 [4] Blanes, S.; Casas, F.; Oteo, J.A.; Ros, J., Magnus and fer expansions for matrix differential equations: the convergence problem, J. phys. A: math. gen., 31, 259-268, (1998) · Zbl 0946.34014 [5] Chandrasekhar, S., On characteristic value problems in high order differential equations which arise in studies on hydrodynamic and hydromagnetic stability, in Proceedings of the symposium on special topics in applied mathematics, Amer. math. monthly, 61, 2, 32-45, (1955) · Zbl 0056.08303 [6] E.B. Davies, Pseudospectra: the harmonic oscillator and complex resonances. Preprint, Department of Mathematics, King’s College London, 1998. [7] Dieci, L.; Russell, R.D.; Van Vleck, E.S., Unitary integrators and applications to continuous orthonormalization techniques, SIAM J. numer. anal., 31, 261-281, (1994) · Zbl 0815.65096 [8] Drazin, P.G.; Reid, W.H., Hydrodynamic stability, (1981), Cambridge University Press Cambridge · Zbl 0449.76027 [9] C.I. Gheorghiu, I.S. Pop, A modified Chebyshev-tau method for a hydrodynamic stability problem. Approximation and Optimization: Proceedings of the International Conference on Approximation and Optimization (Romania) - ICAOR, Cluj-Napoca, July 29-August 1, 1996. Vol. II, 1997, pp. 119-126. · Zbl 0888.76065 [10] Gohberg, I.C.; Krein, M.G., Introduction to the theory of linear nonselfadjoint operators, Trans. math. monographs, 18, (1969) · Zbl 0181.13504 [11] L. Greenberg, A. Prüfer method for calculating eigenvalues of selfadjoint systems of ordinary differential equations, Parts 1 and 2, University of Maryland Technical Report TR91-24, 1991. [12] Greenberg, L., An oscillation method for fourth-order selfadjoint two-point boundary value problems with nonlinear eigenvalues, SIAM J. math. anal., 22, 1021-1042, (1991) · Zbl 0728.65077 [13] Greenberg, L.; Marletta, M., Oscillation theory and numerical solution of fourth order Sturm-Liouville problems, IMA J. numer. anal., 15, 319-356, (1995) · Zbl 0832.65087 [14] Greenberg, L.; Marletta, M., The code SLEUTH for solving fourth order Sturm-Liouville problems, ACM trans. math. software, 23, 453-493, (1997) · Zbl 0912.65073 [15] Greenberg, L.; Marletta, M., Oscillation theory and numerical solution of sixth order Sturm-Liouville problems, SIAM J. numer. anal., 35, 2070-2098, (1998) · Zbl 0916.34030 [16] L. Greenberg, M. Marletta, Numerical solution of nonselfadjoint Sturm-Liouville problems and related systems, SIAM J. Numer. Anal., submitted. · Zbl 1001.34020 [17] Iserles, A.; Nørsett, S.P., On the solution of linear differential equations in Lie groups, Philos. trans. roy. soc. London, A 357, 983-1019, (1999) · Zbl 0958.65080 [18] Kravanja, P.; Sakurai, T.; Van Barel, M., On locating clusters of zeros of analytic functions, report TW280, dept. of computer science, (1998), Katholieke Universiteit Leuven Belgium · Zbl 0948.65051 [19] Magnus, W., On the exponential solution of differential equations for a linear operator, Comm. pure appl. math., 7, 649-673, (1954) · Zbl 0056.34102 [20] Maple, C.R.; Marletta, M., Algorithms and software for selfadjoint ODE eigenproblems, () · Zbl 0910.65060 [21] Marletta, M., Numerical solution of eigenvalue problems for Hamiltonian systems, Adv. comput. math., 2, 155-184, (1994) · Zbl 0833.65083 [22] Naimark, M.A., Linear differential operators, vol. 1, (1968), Ungar New York · Zbl 0227.34020 [23] Orszag, S.A., Accurate solution of the Orr-Sommerfeld stability equation, J. fluid mech., 50, 689-703, (1971) · Zbl 0237.76027 [24] Reid, W.T., Sturmian theory for ordinary differential equations, (1980), Springer New York · Zbl 0459.34001 [25] Roseau, M., Vibrations in mechanical systems, (1987), Springer Berlin [26] Straughan, B.; Walker, D.W., Two very accurate and efficient methods for computing eigenvalues and eigenfunctions in porous convection problems, J. comput. phys., 127, 128-141, (1996) · Zbl 0858.76064 [27] Trefethen, L.N., Pseudospectra of linear operators, SIAM rev., 39, 383-406, (1997) · Zbl 0896.15006 [28] Ying, X.; Katz, I.N., A reliable argument principle algorithm to find the number of zeros of an analytic function in a bounded domain, Numer. math., 53, 143-163, (1988) · Zbl 0628.65015
This reference list is based on information provided by the publisher or from digital mathematics libraries. Its items are heuristically matched to zbMATH identifiers and may contain data conversion errors. It attempts to reflect the references listed in the original paper as accurately as possible without claiming the completeness or perfect precision of the matching.


text:
# For what?

I’ve previously deployed my game engine to macOS successfully with GLFW and macOS’s “vanilla” version OpenGL 4.1 library, everything was nice and sweet (and of course naive) at that time, and every few weeks I would port new changes from Windows side to it in an accumulating way. But as I started to use some C++17 new features, yep I mean <filesystem>, which Apple still didn’t give us a certain answer (I’ve heard about Xcode 10.2 update that there is something new with Apple Clang that somehow <experimental/filesystem> is just there, but later I’ll talk about it separately), and targeting OpenGL version to almost latest 4.5 for quite few new features, I have to deprecate macOS for some moments because, why not?

So the frustrated feeling always tangles around when I started to think about macOS until one day I realized maybe I should just forget about Apple Clang, it’s not the only fruit on the tree. Then I tested the LLVM/Clang package provided by Homebrew (since I use GCC on Linux, it’s better to have another compiler/linker choice on macOS for a wider test scenario), and of course, it works.

But the problem related to OpenGL is still quite unsolvable, and when I heard about macOS 10.14 would deprecate OpenGL officially, there is really a moment I was thinking maybe it’s time to say bye-bye to macOS. I wanted to use Metal, but I really didn’t figure out how to integrate a Swift written module into C++. Then, I threw the idea about the macOS porting to a dusty corner as same as how Apple did with OpenGL decades ago.

And recently I removed the engine’s dependency on GLFW, because I need to use Qt as the editor framework, then choose a design with the native window handling is better and more flexible. After 2 or 3 days refactoring, I successfully decoupled the entire window event system with GLFW, and plugged into Qt smoothly (ignore the annoying QtNativeEvent). Then I have to do the same thing for Linux (currently means Ubuntu), I need to write a native window event system for user input and display there too.

# Then how?

And then macOS became a far more impossible direction, previously GLFW wrapped the platform window for me, now without it what should I do there? But GLFW provides a C++ API, while standard macOS application is often written in Objective-C, then it should have some bridging method to do this. So I googled a little bit and see a weird thing called, Objective-C++.

If you googled that name as same as me, then you should have a brief understanding about how to connect Objective C to C++, we just need to configure something on the build pipeline then we could build an Objective C source file mixed with C++ code together. In practice just simply rename your Objective-C source file’s extension from .m to .mm, and then the build toolchain would consider it as an Objective-C++ file, and it would try to compile it with a mixed interpretation (Or you could change to recognize the file explicitly as an Objective-C++ file in your Xcode IDE).

Then I started to work on a native Cocoa window and, why not get some Metal? But I want to integrate them into my current architecture, not to alter something to fit them. So basically I need a bidirectional communication solution between the C++ engine code and the Objective-C code. Use Objective-C++ could only solve the problem on Objective-C side, it’s always impossible to put any Objective-C language-set-only code in C++ file directly.

Luckily this kind of bridging hooking attaching mapping snapping problem should be common because I’ve found some nice example and article easily about how to deal with it. The basic idea is using inheritance to encapsulate the Objective-C object into a C++ object, and provide some virtual functions as the interface. Then it just becomes a solvable problem, I just need to wrap the window handle into an Objective-C++ class which inherits from a C++ class, and pass the handle or pointer of it to C++ side in runtime.

This is how an Objective-C++ header file looks like, it contains an Objective-C++ class declaration, while it looks just as same as a 100% pure C++ class who inherits from an engine’s abstract bridge class (the private member pointers are Objective-C object pointers, I would explain why it is here later):

#define NO_ANY_OBJECTIVE_C_SXXT_HERE
class MacWindowSystemBridgeImpl : public MacWindowSystemBridge
{
public:
explicit MacWindowSystemBridgeImpl(MacWindowDelegate* macWindowDelegate, MetalDelegate* metalDelegate);
~MacWindowSystemBridgeImpl();

bool setup(unsigned int sizeX, unsigned int sizeY) override;
bool initialize() override;
bool update() override;
bool terminate() override;

ObjectStatus getStatus() override;
private:
ObjectStatus m_objectStatus = ObjectStatus::SHUTDOWN;
MacWindowDelegate* m_macWindowDelegate = nullptr;
MetalDelegate* m_metalDelegate = nullptr;
};

And the .mm source file is mixed with the C++ function declaration and Objective-C implementation, “bridging” happens here:

// Personally I feel O-C is interesting to write painful to read
bool MacWindowSystemBridgeImpl::setup(unsigned int sizeX, unsigned int sizeY) {
NSRect frame = NSMakeRect(0, 0, sizeX, sizeY);

[m_macWindowDelegate initWithContentRect:frame
backing:NSBackingStoreBuffered
defer:NO];

return true;
}
// And so on...

And it’s quite a shame to talk about, I finally knew Metal support Objective-C at that time as late as I started to search about the window solution. But it’s quite an additional inspire for me because all the barrier on macOS porting seems would disappear. Now the Objective-C side objects are created in such a way:

// The main entry
int main(int argc, const char * argv[]) {
[NSApplication sharedApplication];
AppDelegate* appDelegate = [[AppDelegate alloc] init];
[NSApp setDelegate:appDelegate];
[NSApp run];
return 0;
}

//......
//......
//......
// the AppDelegate initialization, allocate the Objective-C objects

- (id)init
{
m_macWindowDelegate = [MacWindowDelegate alloc];
m_metalDelegate = [MetalDelegate alloc];

// Allocate Objective-C++ bridge implementation class instances, the simple new operator allocation is quite enough, just remember to delete them in dtor

m_macWindowSystemBridge = new MacWindowSystemBridgeImpl(m_macWindowDelegate, m_metalDelegate);
m_metalRenderingSystemBridge = new MTRenderingSystemBridgeImpl(m_macWindowDelegate, m_metalDelegate);

// Start the engine c++ code
// Pass the bridge instance pointers to the engine
const char* l_args = "-renderer 4 -mode 0";
if (!InnoApplication::setup(m_macWindowSystemBridge, m_metalRenderingSystemBridge, (char*)l_args))
{
return 0;
}
if (!InnoApplication::initialize())
{
return 0;
}

// the classic while-loop for update
[NSTimer scheduledTimerWithTimeInterval:0.000001 target:self selector:@selector(drawLoop:) userInfo:nil repeats:YES];

return self;
}

And now I’ve implemented a bridge (or you could call it as “Adapter Pattern” or “Adopter Pattern” or something else, I’m really bad at remembering those design patterns name) for these communications. Native window and Metal Objective-C objects are created by the Objective-C application entry, and then use them to construct Objective-C++ classes, and pass the pointer as pure C++ classes to the engine’s runtime, everything was so perfect!

## Devils in the details???

And of course, there are some disadvantages. The first thing which needs extra care about is the memory, since Objective-C object has a so-called ARC some sort of memory management stuff, for to safely maintain the lifecycle of them, I would never pass any Objective-C object pointer directly to C++ code in case someone would delete it accidentally. Instead, it is better to use a std::shared_ptr (or std::make_shared<T> directly) to wrap the Objective-C object we created to pass it to C++ object, or better, never inform C++ side anything about Objective-C like my example.

And furthermore, as you may find, I actually add another indirection in between a C++ declaration and an Objective-C implementation. Because if you just pass your Objective-C++ object by a safer std::shared_ptr to C++, you would still occur some weird problems because the object is not always “there” in memory! Maybe its reference count is reset to 0 at a moment and then was deleted, I didn’t dig into the reason so deeply, as the solution what I’ve figured out, that I would choose to use an Objective-C++ object as the bridge like the original design, but it doesn’t implement any Objective object-related features by itself directly, instead it just owns a pure Objective object’s reference (I use pointer actually), and dispatch all the invocation to that object.

Another not so bad “side-effect” when I removed the dependency on GLFW is, I could enjoy all the latest C++ features without worry about anything. Because now the platform entry module is compiled by Apple Clang, and the engine module is compiled by LLVM/Clang, just link the entry module with the engine module I would have a fully functional application, a kill two birds with one stone!

So now the final solution looks like this:

The further possible burden would relate to the indirection cost and the code redundancy, in this kind of design if you want any interactions in between, you may have to write lots of wrapper functions, and it quite reminds me of a similar thing which everybody used at least for a while when they were learning 3D programming, da, GLAD/GLEW/GLBLABLA these OpenGL function loader:).


text:
# Field extension

If $K$ and $L$ are fields and $K\subseteq L$, then $L/K$ is said to be a field extension. We sometimes say that $L$ is a field extension of $K$.

If $L/K$ is a field extension, then $L$ may be thought of as a vector space over $K$. The dimension of this vector space is called the degree of the extension, and is denoted by $[L:K]$.

Given three fields $K\subseteq L\subseteq M$, then, if the degrees of the extensions $M/L$, $L/K$ and $M/K$, are finite, then are related by the tower law: $$[M:K] = [M:L]\cdot[L:M]$$


text:
## Groupoïdes d’holonomie et classifiants.(French)Zbl 0562.57012

Structure transverse des feuilletages, Toulouse 1982, Astérisque 116, 70-97 (1984).
[For the entire collection see Zbl 0534.00014.]
This paper, a very good summary of the different types of groupoids associated with a foliation, was written by the inventor of some of these structures. This is a review article and certainly does the job. First, he explains the holonomy groupoid or graph, G of a foliation. Then, he defines the holonomy groupoid $$\Gamma_ T$$ of a complete transversal T of the foliation. These groupoids are looked at in terms of different geometric structures put on the foliation. Also discussed is the problem of relating the pseudogroup of transformations of a manifold to the graph of a foliation on a compact manifold.
The classifying space BG of G is defined and invariants of the transverse structure are examined. Cohomology with $$\Gamma$$-coefficients and $$\Gamma$$-principal bundles are also looked at. A review of Milnor’s construction of classifying spaces is given in terms of holonomy groupoids. The author also interprets Steenrod’s work on bundles via groupoids. The paper concludes with a discussion of V-manifolds, their relationship with holonomy groupoids, and their classifying spaces.
Reviewer: I.S.Moskowitz

### MSC:

 57R30 Foliations in differential topology; geometric theory 20L05 Groupoids (i.e. small categories in which all morphisms are isomorphisms) 53C12 Foliations (differential geometric aspects) 55R35 Classifying spaces of groups and $$H$$-spaces in algebraic topology

Zbl 0534.00014


text:
# Localization of the nerve problem by nerve conduction test

Given that we know the affected root and dermatome, can the nerve conduction test be used to localize the site of the nerve problem? I mean can it tell the distance of the pathology compressing on the nerve from the skin surface?

## Answers and Replies

Evo
Mentor
Given that we know the affected root and dermatome, can the nerve conduction test be used to localize the site of the nerve problem? I mean can it tell the distance of the pathology compressing on the nerve from the skin surface?
Please post at least one study in a peer reviewed journal where this is discussed so that we do not have to guess what you mean. Thank you.

And members, please do not post guesses, let the OP post what he means.

Last edited:
Please post at least one study in a peer reviewed journal where this is discussed so that we do no have to guess what you mean. Thank you.

And members, please do not post guesses, let the OP post what he means.
I asked a specific question and I dont have any reference for the answer which why I asked the question. If you have a specific answer (yes or no) just post it.

Evo
Mentor
I asked a specific question and I dont have any reference for the answer which why I asked the question. If you have a specific answer (yes or no) just post it.
No, you need to post a suitable reference for the question you are asking. Which nerve conduction test, there is more than one. It is for you to tell us exactly what you are asking, it is not for us to guess.

I have agreed to the following post.

Last edited:
I am interested to know if a signal processing technique can tell the location of the nerve impingement or compression from processing the nerve conduction test (NCT) signal. MRI sometimes fails to answer where the exact site of the compression along the nerve is.


text:
• Docs »
• External Files

# External Files¶

## Input Files¶

Typically, a user will find it most convenient to generate the BROOD query using the graphical interface. Even if one wants to run BROOD on a cluster or other machine where it isn’t convenient to use the graphical interface, the graphical interface can be used to generate the necessary input and then BROOD can be executed on a different machine after moving the input files. BROOD requires one input file, a query fragment file. With a default installation, the BROOD application can search either one of the default fragment database or a user-generated database (see Database preparation).

### Query Files¶

The entire query is encapsulated into a single query file, typically generated in the GUI. When generated, the GUI names the file brood_1_query.oeb.gz where the 1 is replaced with the next appropriate integer to maintain unique file names. This BROOD query includes the original molecule, the fragment that the user has chosen to replace, the user-edited description of the shape, chemistry and electrostatics of the query. In addition, if the query includes protein structures either for bump-check or selectivity-check, these too will be encapsulated in the query file.

BROOD carries out a 3D search, and a 3D search is required for the search and is usually included in the query file. The BROOD GUI can take either a 2D or a 3D query file. If the original input is 2D, a 3D structure will be generated in the GUI and used during the search.

### Fragment Database¶

As mentioned in the theory section, BROOD comes with a pregenerated, multiconformer fragment database. This database is made from fragments of known molecules that contain 1-15 heavy atoms and 1-3 attachment sites.

BROOD can also search user-generated fragment files. Details on how to create a custom database are included in a later chapter (see Database preparation).

### Example Fragment Files¶

The database file used for BROOD searches is in a highly optimized format with many pre-calculated properties and a complex structure intended to minimize disk access during the time-critical search. These database files can be generated by the CHOMP program included with your BROOD distribution. By default, CHOMP will generate fragments from complete molecules. On the other hand, if a user has their own fragment files they would like to search, these can be loaded directly into the CHOMP program and used to generate a searchable database.

In this case input database fragment for bioisostere searching must be a molecular fragment with one or more “attachment points”. An attachment point represents a bond from the fragment to the rest of the molecule. Inside OEChem, this is represented as a bond to an atom with atomic number 0 (termed a “Dummy Atom”). If it is necessary to uniquely distinguish these dummy atoms, Map Indices can be used via the OEAtomBase::SetMapIdx() and OEAtomBase::GetMapIdx() api.

The input fragment does not need to have 3D coordinates (they can, optionally, be generated on-the-fly). This makes SMILES and 2D SDF file formats the most convenient for query fragment input. On the other hand, the fragment database should contain 3D coordinates with multiple conformers per fragment. In the examples below, a simple amide fragment with generic (amide) and uniquely labeled (amideR) dummy atoms are shown.

SMILES format:

*C(=O)N* amide
[*:1]C(=O)N[*:2] amideR

SDF format:

amide
-OEChem-01040614232D

5  4  0     0  0  0  0  0  0999 V2000
0.0000    0.0000    0.0000 *   0  0  0  0  0  0  0  0  0  0  0  0
0.0000    0.0000    0.0000 C   0  0  0  0  0  0  0  0  0  0  0  0
0.0000    0.0000    0.0000 O   0  0  0  0  0  0  0  0  0  0  0  0
0.0000    0.0000    0.0000 N   0  0  0  0  0  0  0  0  0  0  0  0
0.0000    0.0000    0.0000 *   0  0  0  0  0  0  0  0  0  0  0  0
1  2  1  0  0  0  0
2  3  2  0  0  0  0
2  4  1  0  0  0  0
4  5  1  0  0  0  0
M  END

amideR
-OEChem-01040614232D

5  4  0     0  0  0  0  0  0999 V2000
0.0000    0.0000    0.0000 R#  0  0  0  0  0  0  0  0  0  0  0  0
0.0000    0.0000    0.0000 C   0  0  0  0  0  0  0  0  0  0  0  0
0.0000    0.0000    0.0000 O   0  0  0  0  0  0  0  0  0  0  0  0
0.0000    0.0000    0.0000 N   0  0  0  0  0  0  0  0  0  0  0  0
0.0000    0.0000    0.0000 R#  0  0  0  0  0  0  0  0  0  0  0  0
1  2  1  0  0  0  0
2  3  2  0  0  0  0
2  4  1  0  0  0  0
4  5  1  0  0  0  0
M  RGP  2   1   1   5   2
M  END

## Output Files¶

BROOD generates seven output files in addition to the hitlist. All of these files begin with the prefix specified by the -prefix flag, that by default is “brood”. The also include an integer to retain unique file names in the working directory (in this example, we will use the integer “1”). These files include:

1. brood_1.info, the info file
2. brood_1.log, the log file
3. brood_1.param, the param file
4. brood_1.rpt, the report file
5. brood_1.csv, the spreadsheet file

By default, there is one hitlist and the contents of the hitlist will be determined by the command flags.

• brood_1.hitlist.oeb.gz

In post-processing of the search, some fragments are removed from the hitlist. These are preserved in the “removed” file.

• brood_1.removed.oeb.gz

If the -ET flag is used, the hitlist will include molecules electrostatically similar to the query.

Before executing the search, the GUI also writes the encapsulated query into the query file.

• brood_1_query.oeb.gz

### Info File¶

By default, an information file titled brood_1.info is written or updated for every 500 fragments that are processed. Reading this info file allows a user to monitor the progress of the database search while it is occurring and it serves as a record of the performance of that search after the execution is completed. During execution, the GUI uses this file as well as direct communication with the application to keep the user apprised of all information available in the info file.

An example info file is shown below.

*********** Progress Update ***********
Percent of Database Processed    = 100%
Total packets read               = 329
Packets suitable for Processing  = 99
Number of Fragments Overlayed    = 92134
Number of Fragments Eliminated   = 74560
Number of Fragments Processed    = 166694
Number in color hitlist          = 300
Remove for quick search        = 291
Remove protein clashes         = 0
Remove select protein          = 0
Remove duplicates              = 0
Remove unstable bonds          = 0
Remove strained molecules      = 0
Number in final hitlist          = 9
Number of Warnings               = 2
Number of Errors                 = 0
Processed fragments/sec          = 1742
Elapsed Time (sec)               = 95
***************************************

If any warnings or errors are noted in the info file, it is strongly suggested that a user check in the log file to determine the nature of the problem!

### Param File¶

BROOD’s command-line interface can be efficiently run using the -param command line parameter followed by the name of a parameter file. Param files are files that contain one command-line parameter on each line. Every execution of BROOD, including executions started within the GUI, generates a .param file called brood.param. This file contains all of the parameters used by BROOD. Further, this file can be used in subsequent runs with the -param flag either with or without user modifications.

The .param file is particularly useful if you want to use the graphical interface to set up a job, but execute the job on another machine (such as a cluster). The .param file can be moved to a different machine along with the -queryMolecule file it specifies and it can be used to execute exactly the same run as would have been executed from within the graphical interface.

The following is an example of a .param file generated by the GUI (brood_1.param). It can be used to regenerate the run using the command-line below.

This file could be edited or used “as-is” with subsequent runs. In addition, any explicit command-line parameter takes precedent of parameters in the .param file, so this mechanism can be used to execute a series of similar jobs.

prompt> brood -param brood_1.param

prompt> brood -mpi_np 16 -param brood_1.param -prefix brood_mpi1

Listing of brood.param file contents:

#Interface settings

#Execute Options :
-param  /Users/chemist/data/brood_49.param
-input_chunksize  10
-success_chunksize  10
-failure_chunksize  10

#Brood :

#Input :
#-queryFrag (Not set, no default)
-queryMol  /Users/chemist/data/brood_49_query.oeb.gz
-db  /Users/chemist/data/db/chembl17
#-prot (Not set, no default)
#-select (Not set, no default)
#-noqueryprot  false
#-cpddb  none
#-param (Not set, no default)

#Output :
-prefix  brood_49
-dots  true
#-log (Not set, no default)
#-info (Not set, no default)
#-report (Not set, no default)
-format  oeb.gz
-csv  true
-idea  true
-neutralpH  true
-tautomer  true
-hitlistProt  true

#Control parameters :
-quickLook  true
-ringOnly  true
-ET  false
-sdTag  verbose
-checkBond  true
#-maxHit  1000
#-title (Not set, no default)
-attachColor  false
#-attachFrag  true

#-bondOrder  true
-attachmentCutoff  0.78
-shapeCutoff  0.6
-attachmentScale  1.5
-checkGeometry  true
-fromCT  false
-fileChrg  false
-interval  5000
-hitinterval  1000
#-maxFrag  0
-rangeSize  6
-rangeOffset  0

#Property Selection :
-property  false
#-maxMolWt  500.0
#-minMolWt  100.0
#-maxlogp  5.0
#-minlogp  -1.0
#-maxpsa  150
#-minpsa  60
#-maxRotBond  13
#-minRotBond  0
#-maxHvyAtom  35
#-minHvyAtom  7
#-maxLipinskiDon  8
#-minLipinskiDon  1
#-maxLipinskiAcc  11
#-minLipinskiAcc  2

#Synthetic Properties :
#-maxComplexity  1.0
#-minComplexity  0.0
#-maxFreq  100
#-minFreq  1

#Derived Property Selection :
#-maxLipinski  1
#-minLipinski  0
#-maxMartin  1.0
#-minMartin  0.2
#-eganEgg  true
#-veber  false
#-maxFsp3C  1.0
#-minFsp3C  0.3
#-maxAromFJCt  5
#-minAromFJCt  0

prompt> brood -param brood.param

This would result in exactly the same execution as the one which generated the file above.

### Log File¶

The log file contains all of the critical information about the execution in one place. It begins with a copy of the param file and it finishes with the final info file output. In between, it contains all the warnings and errors that might have occurred during execution. The log file gives a user a single place they can check to determine what job was run, if it executed properly and how long it took.

### Report File¶

The report file contains a detailed listing of the similarity scores for every molecule in the database that was sufficiently similar to warrant a 3D overlay. By default, the file is titled brood_1.rpt and contains 1 line for the column titles and 1 line for each molecule in the database (tab separated columns). The report file contains columns for

• database fragment SMILES
• database fragment title
• query SMILES
• number of attachment bonds
• structural rms value
• attachment score
• shape Tanimoto
• color Tanimoto
• combo score (shape + color)
• et attachment score
• et shape Tanimoto
• electrostatic Tanimoto
• et combo score (shape + et)
• a comment regarding the disposition of the fragment (if and why it failed to be scored)

If a particular score was not calculated for any given fragment, “-” will be found in the report file under the corresponding column. Since all the data for a fragment is contained in a single line, there is only one report file regardless of the number or type of the number or type of hitlists generated. This file is in tab separated format and can easily be imported into a spreadsheet program for further analysis of the results.

### Hitlist File¶

As discussed above, a hitlist is generated for each execution of BROOD. All of the hitlists are written in the file format specified by -format, which defaults to gzipped OEB format .oeb.gz. If the -queryMolecule flag is specified, the hitlist will contain complete molecules, otherwise it will contain fragments. The first entry in the hitlist is the query molecule or query fragment. Each subsequent analog molecule (fragment) in the hitlist is oriented in the optimum overlay on the query molecule (fragment). For the “struc” hitlist, this overlay is the optimum overlay of the attachment point atoms. In addition, by default, the similarity scores and physical property data for each molecule (fragment) are attached as SDTags (OEB and SD format only). In the case when the queryMolecule is not specified, but the -ET flag is set, in the hitlist, the attachment vectors of the fragments are replaced by methyl groups. This facilitates easy calculation of electrostatic potentials in data visualization programs such as VIDA.

By default, the hitlist files are written periodically while the search is being carried out (see -hitinterval). This allows a user to examine results at intermediate stages without waiting for the entire search to complete.

If the -queryMolecule flag specified a 2D input molecule, then all of the analog molecules in the hitlist will likewise be in 2D format, though the fragment similarity search will have been carried out in 3D. When using the graphical interface with a 2D input molecule, a 3D molecule is generated prior to processing and the output format will always be 3D.

### Removed File¶

At the end of the primary fragment search, a complete hitlist is generated. In post-processing, the fragments are build into whole molecules and tested for strain, the newly formed bonds are examined for chemical stability, potential duplicates in the hitlist are removed, the new molecules are checked for bumps with the protein environment and against the optional selectivity protein. At any of these stages fragments that are similar according to the primary search criteria may be removed from the hitlist for these secondary criteria. In rare cases, few fragments may remain in the final hitlist and the user may want to examine the removed fragments without needing to re-run the entire search. For this reason, any fragment removed at the post-processing stage is written to the removed hitlist brood_1.removed.oeb.gz.


text:
# The GAMPL Procedure

Subsections:

#### Generalized Linear Models

All probability distributions that the GAMPL procedure fits are members of an exponential family of distributions. For the specification of an exponential family, see the section "Generalized Linear Models Theory" in Chapter 44: The GENMOD Procedure in SAS/STAT 14.1 User's Guide.

Table 7.11 lists and defines some common notation that is used in the context of generalized linear models and generalized additive models.

Table 7.11: Common Notation

Notation

Meaning

Log-likelihood

Penalized log-likelihood

Deviance

Penalized deviance

Response mean

Linear predictor

Dispersion parameter

Column of response variance

Prior weight for each observation

The GAMPL procedure supports the following distributions: binary, binomial, gamma, inverse Gaussian, negative binomial, normal (Gaussian), and Poisson.

For forms of log-likelihood functions for each of the probability distributions, see the section "Log-Likelihood Functions" in Chapter 44: The GENMOD Procedure in SAS/STAT 14.1 User's Guide. For forms of the deviance for each of the probability distributions, see the section "Goodness of Fit" in Chapter 44: The GENMOD Procedure in SAS/STAT 14.1 User's Guide.

Generalized additive models are extensions of generalized linear models (Nelder and Wedderburn 1972). For each observation that has a response and a row vector of the model matrix , both generalized additive models and generalized linear models assume the model additivity

where and is independently distributed in some exponential family. Generalized linear models further assume model linearity by for . Generalized additive models relax the linearity assumption by allowing some smoothing functions to characterize the dependency. The GAMPL procedure constructs the smoothing functions by using thin-plate regression splines. For more information about generalized additive models and other type of smoothing functions, see Chapter 41: The GAM Procedure in SAS/STAT 14.1 User's Guide.

Consider a generalized additive model that has some linear terms with coefficients and p smoothing functions . Each smoothing function can be constructed by thin-plate regression splines with a smoothing parameter . Using the notations described in the section Low-Rank Approximation, you can characterize each smoothing function by

Notice that each smoothing function representation contains a zero-degree polynomial that corresponds to a constant. Having multiple constant terms makes the smoothing functions unidentifiable. The solution is to include a global constant term (that is, the intercept) in the model and enforce the centering constraint to each smoothing function. You can write the constraint as

By using a similar approach as the linear constraint for thin-plate regression splines, you obtain the orthogonal column basis via the QR decomposition of such that . Each smoothing function can be reparameterized as .

Let and . Then the generalized additive model can be represented as . The roughness penalty matrix is represented as a block diagonal matrix:

Then the roughness penalty is measured in the quadratic form .

#### Penalized Likelihood Estimation

Given a fixed vector of smoothing parameters, , you can fit the generalized additive models by the penalized likelihood estimation. In contrast to the maximum likelihood estimation, penalized likelihood estimation obtains an estimate for by maximizing the penalized log likelihood,

Any optimization technique that you can use for maximum likelihood estimation can also be used for penalized likelihood estimation. If first-order derivatives are required for the optimization technique, you can compute the gradient as

If second-order derivatives are required for the optimization technique, you can compute the Hessian as

In the gradient and Hessian forms, and are the corresponding gradient and Hessian, respectively, for the log-likelihood for generalized linear models. For more information about optimization techniques, see the section Choosing an Optimization Technique.