Process calculated structures
438582
def proc(ctx, files):
    ''''''

    def calc_reader(fn, verb):
        if verb:
            echo('Reading: {:<60s}\r'.format(fn), nl=False, err=True)
        return ase.io.read(fn)

    action = ctx.parent.params['action']
    systems = [calc_reader(calc, verbose) for calc in files]
    if verbose :
        echo('', err=True)
    if action == 'cij':
        cij = elastic.get_elastic_tensor(systems[0], systems=systems[1:])
        msv = cij[1][3].max()
        eps = 1e-4
        if verbose:
            echo('Cij solution\n'+30*'-')
            echo(' Solution rank: {:2d}{}'.format(
                    cij[1][2],
                    ' (undetermined)' if cij[1][2] < len(cij[0]) else ''))
            if cij[1][2] == len(cij[0]):
                echo(' Square of residuals: {:7.2g}'.format(cij[1][1]))
            echo(' Relative singular values:')
            for sv in cij[1][3]/msv:
                echo('{:7.4f}{}'.format(
                        sv, '* ' if (sv) < eps else '  '), nl=False)
            echo('\n\nElastic tensor (GPa):')
            for dsc in elastic.elastic.get_cij_order(systems[0]):
                echo('{: >7s}  '.format(dsc), nl=False)
            echo('\n'+30*'-')
        for c, sv in zip(cij[0], cij[1][3]/msv):
            echo('{:7.2f}{}'.format(
                    c/ase.units.GPa, '* ' if sv < eps else '  '), nl=False)
        echo()
    elif action == 'eos':
        eos = elastic.get_BM_EOS(systems[0], systems=systems[1:])
        eos[1] /= ase.units.GPa
        if verbose:
            echo('# %7s (A^3)  %7s (GPa)   %7s' % ("V0", "B0", "B0'"))
        echo('    %7.2f        %7.2f        %7.2f' % tuple(eos))
113327
function process(node) {
          var children, i, l, lastContentEditable, hasContentEditableState;

          // Node has a contentEditable value
          if (node.nodeType === 1 && getContentEditable(node)) {
            lastContentEditable = contentEditable;
            contentEditable = getContentEditable(node) === "true";
            hasContentEditableState = true; // We don't want to wrap the container only it's children
          }

          // Grab the children first since the nodelist might be changed
          children = grep(node.childNodes);

          // Process current node
          if (contentEditable && !hasContentEditableState) {
            for (i = 0, l = formatList.length; i < l; i++) {
              if (removeFormat(formatList[i], vars, node, node)) {
                break;
              }
            }
          }

          // Process the children
          if (format.deep) {
            if (children.length) {
              for (i = 0, l = children.length; i < l; i++) {
                process(children[i]);
              }

              if (hasContentEditableState) {
                contentEditable = lastContentEditable; // Restore last contentEditable state from stack
              }
            }
          }
        }
1305267
private void doPrecalculateProcess() {
		if (discreteProcess != null && discreteProcess.length != 0) {
			return;
		}

		final int numberOfPaths			= this.getNumberOfPaths();
		final int numberOfFactors		= this.getNumberOfFactors();
		final int numberOfComponents	= this.getNumberOfComponents();

		// Allocate Memory
		discreteProcess			= new RandomVariable[getTimeDiscretization().getNumberOfTimeSteps() + 1][getNumberOfComponents()];
		discreteProcessWeights	= new RandomVariable[getTimeDiscretization().getNumberOfTimeSteps() + 1];

		// Set initial Monte-Carlo weights
		discreteProcessWeights[0] = stochasticDriver.getRandomVariableForConstant(1.0 / numberOfPaths);

		// Set initial value
		RandomVariable[] initialState = getInitialState();
		final RandomVariable[] currentState = new RandomVariable[numberOfComponents];
		for (int componentIndex = 0; componentIndex < numberOfComponents; componentIndex++) {
			currentState[componentIndex] = initialState[componentIndex];
			discreteProcess[0][componentIndex] = applyStateSpaceTransform(componentIndex, currentState[componentIndex]);
		}

		/*
		 * Evolve the process using an Euler scheme.
		 * The evolution is performed multi-threadded.
		 * Each component of the vector runs in its own thread.
		 */
		executor = Executors.newCachedThreadPool();

		// Evolve process
		for (int timeIndex2 = 1; timeIndex2 < getTimeDiscretization().getNumberOfTimeSteps()+1; timeIndex2++) {
			final int timeIndex = timeIndex2;
			// Generate process from timeIndex-1 to timeIndex
			final double deltaT = getTime(timeIndex) - getTime(timeIndex - 1);

			// Fetch drift vector
			final RandomVariable[] drift;
			try {
				drift = getDrift(timeIndex - 1, discreteProcess[timeIndex - 1], null);
			}
			catch(Exception e) {
				throw new RuntimeException("Drift calculaton failed at time index " + timeIndex + " (time=" + getTime(timeIndex - 1) + ") . See cause of this exception for details.", e);
			}

			// Fetch brownianIncrement vector
			final RandomVariable[] brownianIncrement	= stochasticDriver.getIncrement(timeIndex - 1);

			// Calculate new realization
			ArrayList<Future<RandomVariable>> discreteProcessAtCurrentTimeIndex = new ArrayList<>(numberOfComponents);
			for (int componentIndex2 = 0; componentIndex2 < numberOfComponents; componentIndex2++) {
				final int componentIndex = componentIndex2;

				final RandomVariable	driftOfComponent	= drift[componentIndex];

				// Check if the component process has stopped to evolve
				if (driftOfComponent == null) {
					discreteProcessAtCurrentTimeIndex.add(componentIndex, null);
					continue;
				}

				Callable<RandomVariable> worker = new  Callable<RandomVariable>() {
					@Override
					public RandomVariable call() {
						if(scheme == Scheme.EULER_FUNCTIONAL) {
							currentState[componentIndex] = applyStateSpaceTransformInverse(componentIndex, discreteProcess[timeIndex - 1][componentIndex]);
						}

						RandomVariable[]	factorLoadings		= getFactorLoading(timeIndex - 1, componentIndex, discreteProcess[timeIndex - 1]);

						// Check if the component process has stopped to evolve
						if (factorLoadings == null) {
							return null;
						}

						// Apply drift
						if(driftOfComponent != null) {
							currentState[componentIndex] = currentState[componentIndex].addProduct(driftOfComponent, deltaT);
						}

						// Apply diffusion
						currentState[componentIndex] = currentState[componentIndex].addSumProduct(factorLoadings, brownianIncrement);

						// Transform the state space to the value space and return it.
						return applyStateSpaceTransform(componentIndex, currentState[componentIndex]).cache();
					}
				};


				/*
				 * Optional multi-threadding (asyncronous calculation of the components)
				 */
				Future<RandomVariable> result = null;
				try {
					if(isUseMultiThreadding) {
						result = executor.submit(worker);
					} else {
						result = new FutureWrapper<>(worker.call());
					}
				} catch (Exception e) {
					throw new RuntimeException("Euler step failed at time index " + timeIndex + " (time=" + getTime(timeIndex) + "). See cause of this exception for details.", e);
				}

				// The following line will add the result of the calculation to the vector discreteProcessAtCurrentTimeIndex
				discreteProcessAtCurrentTimeIndex.add(componentIndex, result);
			}

			// Fetch results and move to discreteProcess[timeIndex]
			for (int componentIndex = 0; componentIndex < numberOfComponents; componentIndex++) {
				try {
					Future<RandomVariable> discreteProcessAtCurrentTimeIndexAndComponent = discreteProcessAtCurrentTimeIndex.get(componentIndex);
					if(discreteProcessAtCurrentTimeIndexAndComponent != null) {
						discreteProcess[timeIndex][componentIndex] = discreteProcessAtCurrentTimeIndexAndComponent.get().cache();
					} else {
						discreteProcess[timeIndex][componentIndex] = discreteProcess[timeIndex-1][componentIndex];
					}
				} catch (InterruptedException e) {
					throw new RuntimeException("Euler step failed at time index " + timeIndex + " (time=" + getTime(timeIndex) + "). See cause of this exception for details.", e);
				} catch (ExecutionException e) {
					throw new RuntimeException("Euler step failed at time index " + timeIndex + " (time=" + getTime(timeIndex) + "). See cause of this exception for details.", e);
				}
			}

			if (scheme == Scheme.PREDICTOR_CORRECTOR) {
				// Apply corrector step to realizations at next time step

				RandomVariable[] driftWithPredictor = getDrift(timeIndex - 1, discreteProcess[timeIndex], null);

				for (int componentIndex = 0; componentIndex < getNumberOfComponents(); componentIndex++) {
					RandomVariable driftWithPredictorOfComponent		= driftWithPredictor[componentIndex];
					RandomVariable driftWithoutPredictorOfComponent	= drift[componentIndex];

					if (driftWithPredictorOfComponent == null || driftWithoutPredictorOfComponent == null) {
						continue;
					}

					// Calculated the predictor corrector drift adjustment
					RandomVariable driftAdjustment = driftWithPredictorOfComponent.sub(driftWithoutPredictorOfComponent).div(2.0).mult(deltaT);

					// Add drift adjustment
					currentState[componentIndex] = currentState[componentIndex].add(driftAdjustment);

					// Re-apply state space transform
					discreteProcess[timeIndex][componentIndex] = applyStateSpaceTransform(componentIndex, currentState[componentIndex]);
				} // End for(componentIndex)
			} // End if(scheme == Scheme.PREDICTOR_CORRECTOR)

			// Set Monte-Carlo weights
			discreteProcessWeights[timeIndex] = discreteProcessWeights[timeIndex - 1];
		} // End for(timeIndex)

		try {
			executor.shutdown();
		}
		catch(SecurityException e) {
			// @TODO Improve exception handling here
		}
	}
298458
def apply_to_structure(self, structure):
        
        def_struct = structure.copy()
        old_latt = def_struct.lattice.matrix
        new_latt = np.transpose(np.dot(self, np.transpose(old_latt)))
        def_struct.lattice = Lattice(new_latt)
        return def_struct
1144376
def preprocess(self):
        '''
        
        '''
        self.processed_tables = []
        self.flags_by_table = []
        self.units_by_table = []
        for worksheet, rtable in enumerate(self.raw_tables):
            ptable, flags, units = self.preprocess_worksheet(rtable, worksheet)
            self.processed_tables.append(ptable)
            self.flags_by_table.append(flags)
            self.units_by_table.append(units)

        return self.processed_tables
561028
def process_values(self):
        """"""

        if self.padding>0:
            channels = np.zeros((self.vals.shape[0], self.vals.shape[1]+self.padding))
            channels[:, 0:self.vals.shape[0]] = self.vals
        else:
            channels = self.vals
        vals_mat = self.skel.to_xyz(channels.flatten())
        self.vals = np.zeros_like(vals_mat)
        # Flip the Y and Z axes
        self.vals[:, 0] = vals_mat[:, 0].copy()
        self.vals[:, 1] = vals_mat[:, 2].copy()
        self.vals[:, 2] = vals_mat[:, 1].copy()
972962
function computeNodeValues(nodes) {
    zrUtil.each(nodes, function (node) {
        var value1 = sum(node.outEdges, getEdgeValue);
        var value2 = sum(node.inEdges, getEdgeValue);
        var value = Math.max(value1, value2);
        node.setLayout({value: value}, true);
    });
}
574485
@Override
	public void process() {
		locations.reset();
		descriptions.reset();

		// see if the cell array needs to grow for this image.  Recycle data when growing
		growCellArray(derivX.width, derivX.height);

		computeCellHistograms();

		int cellRowMax = (cellRows - (cellsPerBlockY -1));
		int cellColMax = (cellCols - (cellsPerBlockX -1));

		for (int i = 0; i < cellRowMax; i += stepBlock) {
			for (int j = 0; j < cellColMax; j += stepBlock) {
				computeDescriptor(i,j);
			}
		}

	}
557861
protected void updateFormulas() {
        CTCalcChain calculationChain = getCalculationChain();
        int formulaCount = processInnerFormulas(calculationChain);
        processOuterFormulas(formulaCount, calculationChain);
    }
1280137
public function process()
    {
        parent::process();

        foreach ($this->columns as $column) {
            $column->process();
        }

        foreach ($this->spanning_columns as $column) {
            $column->process();
        }

        foreach ($this->extra_rows as $row) {
            $row->process();
        }

        // this is part of the old selection API
        if ($this->hasColumn('checkbox')) {
            $items = $this->getColumn('checkbox');
            $this->checked_items = $items->getItems();
        }
    }
422481
@Override
    public void preProcess(@NonNull MultiDataSet toPreProcess) {
        int numFeatures = toPreProcess.numFeatureArrays();
        int numLabels = toPreProcess.numLabelsArrays();

        for (int i = 0; i < numFeatures; i++) {
            strategy.preProcess(toPreProcess.getFeatures(i), toPreProcess.getFeaturesMaskArray(i), getFeatureStats(i));
        }
        if (isFitLabel()) {
            for (int i = 0; i < numLabels; i++) {
                strategy.preProcess(toPreProcess.getLabels(i), toPreProcess.getLabelsMaskArray(i), getLabelStats(i));
            }
        }
    }
60868
def process(self, obj, pk_set=None, action=None, update_fields=None, **kwargs):
        """"""
        build_kwargs = self._get_build_kwargs(obj, pk_set, action, update_fields, **kwargs)

        if build_kwargs:
            self.index.build(**build_kwargs)
627934
def ParallelCalculate(cls,syslst,properties=['energy'],system_changes=all_changes):
        '''
        
        '''
        print('Launching:',end=' ')
        sys.stdout.flush()
        for n,s in enumerate(syslst):
            try :
                s.calc.block=False
                s.calc.calculate(atoms=s,properties=properties,system_changes=system_changes)
            except CalcNotReadyError:
                s.calc.block=True
            print(n+1, end=' ')
            sys.stdout.flush()
        print()
        print('     Done:', end=' ')
        sys.stdout.flush()
        for n,s in enumerate(syslst):
            s.calc.read_results()
            print( n+1, end=' ')
            sys.stdout.flush()
        print()
        return syslst
1062955
function processChildren()
    {
        // process the loop body
        $children            = eZTemplateNodeTool::extractFunctionNodeChildren( $this->Node );
        $transformedChildren = eZTemplateCompiler::processNodeTransformationNodes( $this->Tpl, $this->Node, $children, $this->PrivateData );

        $childrenNodes = array();
        $delimiter = null;

        if ( is_array( $transformedChildren ) )
        {
            foreach ( $transformedChildren as $child )
            {
                if ( $child[0] == eZTemplate::NODE_FUNCTION ) // check child type
                {
                    $childFunctionName = $child[2];
                    if ( $childFunctionName == 'delimiter' )
                    {
                        // save delimiter for it to be processed below
                        $delimiter = $child;
                        continue;
                    }
                    elseif ( $childFunctionName == 'break' )
                    {
                        $childrenNodes[] = eZTemplateNodeTool::createCodePieceNode( "break;\n" );
                        continue;
                    }
                    elseif ( $childFunctionName == 'continue' )
                    {
                        $childrenNodes[] = eZTemplateNodeTool::createCodePieceNode( "continue;\n" );
                        continue;
                    }
                    elseif ( $childFunctionName == 'skip' )
                    {
                        $childrenNodes[] = eZTemplateNodeTool::createCodePieceNode( "\$skipDelimiter = true;\ncontinue;\n" );
                        continue;
                    }
                }

                $childrenNodes[] = $child;
            }
        }

        if ( $delimiter ) // if delimiter is specified
        {
            $delimiterNodes = eZTemplateNodeTool::extractNodes( $children,
                                                    array( 'match' => array( 'type' => 'equal',
                                                                             'matches' => array( array( 'match-keys' => array( 0 ),
                                                                                                       'match-with' => eZTemplate::NODE_FUNCTION ),
                                                                                                 array( 'match-keys' => array( 2 ),
                                                                                                        'match-with' => 'delimiter' ) ) ) ) );
            $delimiterNode = false;
            if ( count( $delimiterNodes ) > 0 )
                $delimiterNode = $delimiterNodes[0];

            $delimiterChildren = eZTemplateNodeTool::extractFunctionNodeChildren( $delimiterNode );
            $delimiterParameters = eZTemplateNodeTool::extractFunctionNodeParameters( $delimiterNode );

            $checkModulo = array();
            $checkModuloEnd = array();
            $delemiterModuloValue = array();
            if ( isset( $delimiterParameters['modulo'] ) )
            {
                switch ( $this->Name )
                {
                    case 'foreach':
                    {
                        $delimiterModulo = $delimiterParameters['modulo'];
                        $delimiterModulo = eZTemplateCompiler::processElementTransformationList( $this->Tpl, $delimiterModulo, $delimiterModulo, $this->PrivateData );
                        // Get unique index
                        $currentIndex = "\$fe_i_$this->UniqID";

                        if ( eZTemplateNodeTool::isConstantElement( $delimiterModulo ) )
                        {
                            $moduloValue = (int)eZTemplateNodeTool::elementConstantValue( $delimiterModulo );
                            $matchCode = "( ( $currentIndex ) % $moduloValue ) == 0";
                        }
                        else
                        {
                            $delemiterModuloValue[] = eZTemplateNodeTool::createVariableNode( false, $delimiterModulo, eZTemplateNodeTool::extractFunctionNodePlacement( $this->Node ),
                                                                                        array( 'spacing' => 0 ), 'moduloValue' );
                            $matchCode = "( ( $currentIndex ) % \$moduloValue ) == 0";
                        }
                        $checkModulo[] = eZTemplateNodeTool::createCodePieceNode( "if ( $matchCode ) // Check modulo\n{" );
                        $checkModulo[] = eZTemplateNodeTool::createSpacingIncreaseNode( 4 );

                        $checkModuloEnd[] = eZTemplateNodeTool::createSpacingDecreaseNode( 4 );
                        $checkModuloEnd[] = eZTemplateNodeTool::createCodePieceNode( "}\n" );
                    }
                }
            }
            $delimiterNodes = array();
            $delimiterNodes[] = eZTemplateNodeTool::createCodePieceNode( "if ( \$skipDelimiter )\n" .
                                                                         "    \$skipDelimiter = false;\n" .
                                                                         "else\n" .
                                                                         "{ // delimiter begins" );
            $delimiterNodes[] = eZTemplateNodeTool::createSpacingIncreaseNode();
            if ( is_array( $delimiter[1] ) ) // if delimiter has children
            {
                // If modulo is specified
                $delimiterNodes = array_merge( $delimiterNodes, $checkModulo );

                foreach ( $delimiter[1] as $delimiterChild )
                    $delimiterNodes[] = $delimiterChild;

                // Set end of checking for modulo
                $delimiterNodes = array_merge( $delimiterNodes, $checkModuloEnd );
            }

            $delimiterNodes[] = eZTemplateNodeTool::createSpacingDecreaseNode();
            $delimiterNodes[] = eZTemplateNodeTool::createCodePieceNode( "} // delimiter ends\n" );

            // we place its code right before other loop children,
            // if delemiter and modulo are specified and value of modulo is not static
            // $delemiterModuloValue is initialization of variable
            // we should place initialization of moduloValue before checking for delimiter
            $childrenNodes = array_merge( $delemiterModuloValue, $delimiterNodes, $childrenNodes );
        }

        $this->NewNodes = array_merge( $this->NewNodes, $childrenNodes );
    }
819269
def calc2dcoords(mol):
    
    topology.recognize(mol)
    g = set(i for i, _ in mol.atoms_iter())
    # 1: get nodes in scaffolds
    scaffolds = []
    belongs = {}
    for i, rkeys in enumerate(sorted(mol.scaffolds, key=len)):
        scf = []
        for rkey in rkeys:
            ring = mol.rings[rkey]
            for r in ring:
                belongs[r] = i
            scf.append(ring)
            g -= set(ring)
        scaffolds.append(scf)
    # 2: traverse nodes and scaffolds
    # the node and scaffold graph should be a tree (no cycles)
    f = True
    # print(scaffolds)
    coords = {}
    while g:
        if f and scaffolds:  # largest scaffold is first
            stack = [scaffolds[-1][0][0]]
            f = False
        else:
            stack = [g.pop()]
        pred = {}
        branch = {}
        while stack:
            # print("stack: {}".format(stack))
            tail = stack.pop()
            # print("tail: {}".format(tail))
            if tail in belongs:  # scaffolds
                scf = scaffold_coords(scaffolds[belongs[tail]])
                # print(scf.keys())
                # rotate and translate
                if not coords:
                    coords = scf
                else:
                    u = coords[pred[tail]]
                    v = scf[tail]
                    op = [u[0] + math.cos(u[2]), u[1] + math.sin(u[2])]
                    translate(scf, gm.vector(v[:2], op))
                    rotate(scf, op, gm.rad(u[2] + math.pi - v[2]))
                    coords.update(scf)
                # stack nbrs of scaffold
                for k in scf.keys():
                    pred[k] = None
                    for nbr in mol.neighbors(k):
                        if nbr not in scf.keys():
                            stack.append(nbr)
                            pred[nbr] = k
            else:  # append linker
                if tail not in pred:  # isolated
                    coords[tail] = [0, 0, 0, 1]
                    continue
                p = pred[tail]
                x, y, ang, d = coords[p]
                # TODO: ring configuration
                coords[tail] = [x + math.cos(ang), y + math.sin(ang),
                                ang + d * math.pi / 3, d * -1]
                if p not in branch:
                    coords[p][2] = gm.rad(coords[p][2] + math.pi * 2 / 3 * d)
                    branch[p] = 1
                elif branch[p] == 1:
                    coords[p][2] = gm.rad(coords[p][2] + math.pi * d)
                    branch[p] += 1
                elif branch[p] == 2:
                    coords[p][2] = gm.rad(coords[p][2] + math.pi * 2 / 3 * d)
                    branch[p] += 1
                for nbr in mol.neighbors(tail):
                    if nbr not in pred:
                        stack.append(nbr)
                        pred[nbr] = tail
        g -= set(pred)
    resolve_overlap(coords)
    for i, a in mol.atoms_iter():
        mol.atom(i).coords = coords[i][:2]
222088
def process(ctx, dataset, kwargs):
    ""

    kwargs = parse_kwargs(kwargs)
    data(dataset, **ctx.obj).process(**kwargs)
373493
def _process_rules(self, rules: dict, system: System):
        
        self._source = None # reset the template source
        if not self._shall_proceed(rules):
            return
        self.context.update(rules.get('context', {}))
        self.path = rules.get('path', '')
        self.source = rules.get('source', None)
        self._process_rule(rules.get('system', None), {'system': system})
        for module in system.modules:
            self._process_rule(rules.get('module', None), {'module': module})
            for interface in module.interfaces:
                self._process_rule(rules.get('interface', None), {'interface': interface})
            for struct in module.structs:
                self._process_rule(rules.get('struct', None), {'struct': struct})
            for enum in module.enums:
                self._process_rule(rules.get('enum', None), {'enum': enum})