public ProteinSpectrumMatchSet[][] GroupAcrossRuns(List<ProteinSpectrumMatchSet>[] prsmGroup, INodeComparer<ProteinSpectrumMatchSet> prsmGroupComparer)
        {
            var nDataset = prsmGroup.Length;
            var prsmSet = new NodeSet<ProteinSpectrumMatchSet>() { };

            for (var i = 0; i < nDataset; i++)
            {
                var groupedPrsms = prsmGroup[i];
                if (groupedPrsms == null) continue;
                prsmSet.AddRange(groupedPrsms);
            }

            var alignedPrsms = prsmSet.ConnnectedComponents(prsmGroupComparer);
            var alignedResult = new ProteinSpectrumMatchSet[alignedPrsms.Count][];
            for (var i = 0; i < alignedResult.Length; i++) alignedResult[i] = new ProteinSpectrumMatchSet[nDataset];
            
            for(var i = 0; i < alignedPrsms.Count; i++)
            {
                foreach (var set in alignedPrsms[i])
                {
                    if (alignedResult[i][set.DataId] != null)
                    {
                        alignedResult[i][set.DataId].Merge(set);
                        //Console.WriteLine("[{4}] {0}-{1}...{2}-{3}", set.MinScanNum, set.MaxScanNum, alignedResult[i][set.DataId].MinScanNum, alignedResult[i][set.DataId].MaxScanNum, set.DataId);    
                    }
                    else
                    {
                        alignedResult[i][set.DataId] = set;    
                    }
                }
            }
            return alignedResult;
        }
 public List<ProteinSpectrumMatchSet> GroupingByPrsm(int dataid, IEnumerable<ProteinSpectrumMatch> matches, INodeComparer<ProteinSpectrumMatch> prsmComparer)
 {
     var prsmSet = new NodeSet<ProteinSpectrumMatch>(){};
     prsmSet.AddRange(matches);
     var groupList = prsmSet.ConnnectedComponents(prsmComparer);
     return groupList.Select(@group => new ProteinSpectrumMatchSet(dataid, @group)).ToList();
 }
Ejemplo n.º 3
0
        public byte[] GetMove(byte[] initialState, int moveCount)
        {
            NodeSet nodeSet = new NodeSet();

            for (int i = 0; i < initialState.Length; i++)
            {
                applyAvailableMoves(initialState, i, moveCount, nodeSet);
            }

            return initialState;
        }
Ejemplo n.º 4
0
        // Constructor //
        public NeuralNetwork(string Name, NodeLinkMaster Links, NodeSet Nodes, ResponseNodeSet Responses, NeuralRule Rule, Matrix Data)
        {

            // Set values //
            this._Links = Links;
            this._Nodes = Nodes;
            this._Responses = Responses;
            this._Rule = Rule;
            this._Data = Data;
            this._name = Name;

            // Initialize //
            this.Initialize();
            
        }
Ejemplo n.º 5
0
        void handlePawn(byte[] state, int position, int moveCount, NodeSet nodeSet)
        {
            // for opening move, player can move two spaces
            if (moveCount == 0)
            {
                movePieceIfConstraintMet(state, position, 0, 2, Pieces.Empty, nodeSet);
            }

            movePieceIfConstraintMet(state, position, 0, 1, Pieces.Empty, nodeSet);

            // opponent to the left
            movePieceIfConstraintMet(state, position, -1, 1, new byte[] { Pieces.Pawn, Pieces.Castle, Pieces.Rook, Pieces.Bishop, Pieces.Queen }, nodeSet);

            // opponent to the right
            movePieceIfConstraintMet(state, position, -1, 1, new byte[] { Pieces.Pawn, Pieces.Castle, Pieces.Rook, Pieces.Bishop, Pieces.Queen }, nodeSet);
        }
Ejemplo n.º 6
0
 public NodeServer(Network network, ProtocolVersion version = ProtocolVersion.PROTOCOL_VERSION,
     int internalPort = -1)
 {
     AdvertizeMyself = true;
     internalPort = internalPort == -1 ? network.DefaultPort : internalPort;
     _LocalEndpoint = new IPEndPoint(IPAddress.Parse("0.0.0.0").MapToIPv6(), internalPort);
     _Network = network;
     _ExternalEndpoint = new IPEndPoint(_LocalEndpoint.Address, Network.DefaultPort);
     _Version = version;
     var listener = new EventLoopMessageListener<IncomingMessage>(ProcessMessage);
     _MessageProducer.AddMessageListener(listener);
     OwnResource(listener);
     RegisterPeerTableRepository(_PeerTable);
     _Nodes = new NodeSet();
     _Nodes.MessageProducer.AddMessageListener(listener);
     _Trace = new TraceCorrelation(NodeServerTrace.Trace, "Node server listening on " + LocalEndpoint);
 }
Ejemplo n.º 7
0
        /// <summary>
        /// Adds the resultant state of a piece move if a contraint is met
        /// </summary>
        bool movePieceIfConstraintMet(byte[] state, int position, int dx, int dy, byte pieceMatch, NodeSet nodeSet)
        {
            var tx = (position % 8 + dx);
            var ty = (position / 8) + dy;

            if ((tx < 0) || (tx >= 8) || (ty < 0) || (ty >= 8))
            {
                return false;
            }

            // todo: check self or other player
            if (state[ty * 8 + tx] != pieceMatch)
            {
                return false;
            }

            nodeSet.AddNode(
                state,
                new int[2] { position, ty * 8 + tx },
                new byte[2] { Pieces.Empty, state[position] });

            return true;
        }
Ejemplo n.º 8
0
        public static IEnumerable <Node> Parse(params String[] paths)
        {
            var roots = new NodeSet();

            foreach (var path in paths)
            {
                var  pathSplit = path.Split('\\');
                Node current   = null;
                foreach (var pathElement in pathSplit)
                {
                    var currentRoots = (current == null) ? roots : current.Children;
                    if (currentRoots.Contains(pathElement))
                    {
                        current = currentRoots[pathElement];
                    }
                    else
                    {
                        current = new Node(pathElement);
                        currentRoots.Add(current);
                    }
                }
            }
            return(roots);
        }
Ejemplo n.º 9
0
        void applyAvailableMoves(byte[] state, int position, int moveCount, NodeSet nodeSet)
        {
            switch (state[position])
            {
                case Pieces.Pawn:
                    handlePawn(state, position, moveCount, nodeSet);
                    break;

                case Pieces.Castle:
                    break;

                case Pieces.Rook:
                    break;

                case Pieces.Bishop:
                    break;

                case Pieces.King:
                    break;

                case Pieces.Queen:
                    break;
            }
        }
        public void TestGenericType <T>(int testBufferSize, T testValue)
            where T : struct
        {
            using (var set = new NodeSet())
            {
                var output = set.Create <GenericOutput <T> >();
                var input  = set.Create <GenericInput <T> >();

                set.SetBufferSize(output, GenericOutput <T> .KernelPorts.Output, Buffer <T> .SizeRequest(testBufferSize));
                set.Connect(output, GenericOutput <T> .KernelPorts.Output, input, GenericInput <T> .KernelPorts.Input);

                set.SendMessage(output, GenericOutput <T> .SimulationPorts.Input, testValue);

                var value = set.CreateGraphValue(input, GenericInput <T> .KernelPorts.Output);

                set.Update();
                set.DataGraph.SyncAnyRendering();

                Assert.AreEqual(testValue, set.GetValueBlocking(value));

                set.ReleaseGraphValue(value);
                set.Destroy(input, output);
            }
        }
Ejemplo n.º 11
0
                protected override void ComputeValues(NodeSet NS, int j0, int Len, MultidimensionalArray output)
                {
                    LevelSet LevSet = (LevelSet)(this.m_owner.GetLevSet());

                    var BasisHessian = LevSet.Basis.Evaluate2ndDeriv(NS);

                    Debug.Assert(output.GetLength(0) == Len);
                    int N = LevSet.Basis.Length;

                    Debug.Assert(BasisHessian.GetLength(1) == N);
                    int D = this.m_owner.m_owner.GridDat.SpatialDimension;

                    Debug.Assert(D == BasisHessian.GetLength(2));
                    Debug.Assert(D == BasisHessian.GetLength(3));
                    Debug.Assert(D == output.GetLength(2));
                    Debug.Assert(D == output.GetLength(3));
                    int K = output.GetLength(1); // No of nodes

                    Debug.Assert(K == BasisHessian.GetLength(0));

                    var Coordinates = ((MultidimensionalArray)LevSet.Coordinates).ExtractSubArrayShallow(new int[] { j0, 0 }, new int[] { j0 + Len - 1, N - 1 });

                    output.Multiply(1.0, BasisHessian, Coordinates, 0.0, "jkdr", "kndr", "jn");
                }
Ejemplo n.º 12
0
        public void EvaluateGradient(int j0, int Len, NodeSet NS, MultidimensionalArray result)
        {
            MultidimensionalArray nodes = GetGlobalNodes(j0, Len, NS);
            int noOfNodes = nodes.GetLength(1);

            for (int i = 0; i < Len; i++)
            {
                for (int j = 0; j < noOfNodes; j++)
                {
                    double x = nodes[i, j, 0];
                    double y = nodes[i, j, 1];

                    double theta = Math.Atan2(y, x);
                    double r     = Math.Sqrt(x * x + y * y);
                    //if (r < 0.001) {
                    //    result[i, j, 0] = 0.0;
                    //    result[i, j, 1] = 0.0;
                    //} else {
                    result[i, j, 0] = -2.5 * Math.Sin(5.0 * theta) * (theta - x * y / r / r) - x / r;
                    result[i, j, 1] = 2.5 * Math.Sin(5.0 * theta) * y * y / r / r - y / r;
                    //}
                }
            }
        }
Ejemplo n.º 13
0
        public void EvaluateGradient(int j0, int Len, NodeSet Ns, MultidimensionalArray result)
        {
            MultidimensionalArray nodes = GetGlobalNodes(j0, Len, Ns);
            int noOfNodes = nodes.GetLength(1);

            double aSquare = xMajor * xMajor / 4.0;
            double bSquare = yMajor * yMajor / 4.0;
            double cSquare = zMajor * zMajor / 4.0;

            for (int i = 0; i < Len; i++)
            {
                for (int j = 0; j < noOfNodes; j++)
                {
                    double x = nodes[i, j, 0];
                    double y = nodes[i, j, 1];
                    double z = nodes[i, j, 2];

                    double d = Math.Sqrt(x * x / aSquare + y * y / bSquare + z * z / cSquare);
                    result[i, j, 0] = -x / aSquare / d;
                    result[i, j, 1] = -y / bSquare / d;
                    result[i, j, 2] = -z / cSquare / d;
                }
            }
        }
Ejemplo n.º 14
0
        public void EvaluateTotalCurvature(int j0, int Len, NodeSet Ns, MultidimensionalArray result)
        {
            MultidimensionalArray nodes = GetGlobalNodes(j0, Len, Ns);
            int noOfNodes = nodes.GetLength(1);

            for (int i = 0; i < Len; i++)
            {
                for (int j = 0; j < noOfNodes; j++)
                {
                    double x = nodes[i, j, 0];
                    double y = nodes[i, j, 1];

                    double norm = Math.Sqrt(x * x + y * y);

                    // Small perturbation at the singularity
                    if (norm == 0)
                    {
                        norm = 1e-15;
                    }

                    result[i, j] = -1 / norm;
                }
            }
        }
Ejemplo n.º 15
0
        private static bool cmpQueryQueryE(Operator.Op op, object val1, object val2)
        {
            bool    flag = op == Operator.Op.EQ;
            NodeSet set  = new NodeSet(val1);
            NodeSet set2 = new NodeSet(val2);

            while (set.MoveNext())
            {
                if (!set2.MoveNext())
                {
                    return(false);
                }
                string str = set.Value;
                do
                {
                    if ((str == set2.Value) == flag)
                    {
                        return(true);
                    }
                }while (set2.MoveNext());
                set2.Reset();
            }
            return(false);
        }
Ejemplo n.º 16
0
        void Start()
        {
            using (var set = new NodeSet())
            {
                var writer = set.Create <MyWriter>();
                var reader = set.Create <MyReader>();

                set.Connect(writer, MyWriter.KernelPorts.OutputBuffer, reader, MyReader.KernelPorts.InputBuffer);

                /*
                 * You'll notice we haven't declared the size of the array anywhere yet.
                 * This is done in the simulation (or externally), by transferring a size request in the SetBufferSize() API
                 * on the node set.
                 */
                set.SetBufferSize(writer, MyWriter.KernelPorts.OutputBuffer, Buffer <float> .SizeRequest(50));

                set.Update();

                /*
                 * Buffer memory is otherwise managed by the node set, so we don't have to worry about cleaning that up.
                 */
                set.Destroy(writer, reader);
            }
        }
Ejemplo n.º 17
0
        MultidimensionalArray StokesAnsatzRHS(Basis TestBasis, CellBoundaryQuadratureScheme cellBndSchme, CellMask _mask, int order)
        {
            var GridDat = this.tracker.GridDat;
            CellBoundaryQuadrature <CellBoundaryQuadRule> qBnd = null;

            int N = TestBasis.Length;
            int D = GridDat.SpatialDimension;
            MultidimensionalArray RHS = MultidimensionalArray.Create(D, N, _mask.NoOfItemsLocally);

            double[] CellN       = new double[D]; // cell normal
            double[] SurfN       = new double[D]; // level-set normal
            double[] OutwardTang = new double[D]; // level-set tangent, outward of cell

            if (D != 2)
            {
                throw new NotSupportedException("Currently only supported for spatial dimension of 2.");
            }

            //MultidimensionalArray Nudes = null;
            int jSgrd = 0;

            qBnd = CellBoundaryQuadrature <CellBoundaryQuadRule> .GetQuadrature(new int[] { D, N },
                                                                                GridDat, cellBndSchme.Compile(GridDat, order),
                                                                                delegate(int i0, int Length, CellBoundaryQuadRule NS, MultidimensionalArray EvalResult) { // Evaluate
                //MultidimensionalArray BasisValues = TestBasis.Evaluate(0);                 // reference
                //var LSNormals = LsTrk.GetLevelSetReferenceNormals(iLevSet, 0, i0, Length); // reference
                MultidimensionalArray BasisValues = TestBasis.CellEval(NS.Nodes, i0, Length);                   // physical
                MultidimensionalArray LSNormals   = this.LevelSetData.GetLevelSetNormals(NS.Nodes, i0, Length); // physical

                for (int i = 0; i < Length; i++)                                                                // loop over cells
                //if(i0 + i == 1) {
                //    EvalResult.ExtractSubArrayShallow(i, -1, -1, -1).Clear();
                //    continue;
                //}

                {
                    CellBoundaryQuadRule cR = qBnd.CurrentRule;
                    int[] NodesPerEdge      = cR.NumbersOfNodesPerFace;
                    var Kref      = cR.RefElement;
                    int NoOfFaces = Kref.NoOfFaces;
                    int iNode     = 0;

                    Debug.Assert(NoOfFaces == NodesPerEdge.Length);
                    for (int e = 0; e < NoOfFaces; e++)       // loop over the faces of the cell

                    {
                        if (NodesPerEdge[e] <= 0)
                        {
                            continue;
                        }

                        // reference:
                        //for (int d = 0; d < D; d++) {
                        //    CellN[d] = Kref.FaceNormals[e, d];
                        //}
                        // ~~~~

                        // physical:
                        var FaceNodes   = new NodeSet(Kref, cR.Nodes.ExtractSubArrayShallow(new int[] { iNode, 0 }, new int[] { iNode + NodesPerEdge[e] - 1, D - 1 }));
                        var FaceNormals = MultidimensionalArray.Create(NodesPerEdge[e], D);
                        GridDat.Edges.GetNormalsForCell(FaceNodes, i0, e, FaceNormals);
                        // ~~~~

                        for (int _n = 0; _n < NodesPerEdge[e]; _n++)       // loop over nodes in one edge
                        {
                            for (int d = 0; d < D; d++)
                            {
                                SurfN[d] = LSNormals[i, iNode, d];
                                CellN[d] = FaceNormals[_n, d];     // physical
                            }
                            tangente(SurfN, CellN, OutwardTang);

                            for (int n = 0; n < N; n++)                                                     // loop over Test polynomials (the same as the basis polynomials)
                            {
                                for (int d = 0; d < D; d++)                                                 // loop over spatial direction
                                {
                                    EvalResult[i, iNode, d, n] = BasisValues[i, iNode, n] * OutwardTang[d]; // physical
                                    //EvalResult[i, iNode, d, n] = BasisValues[iNode, n]*OutwardTang[d]; // reference
                                }
                            }

                            iNode++;
                        }
                    }
                    Debug.Assert(iNode == EvalResult.GetLength(1));
                }
            },
                                                                                delegate(int i0, int Length, MultidimensionalArray ResultsOfIntegration) { // SaveIntegrationResults
                for (int i = 0; i < Length; i++)
                {
                    var ResPart   = RHS.ExtractSubArrayShallow(new int[] { 0, 0, jSgrd }, new int[] { D - 1, N - 1, jSgrd - 1 });
                    int NoOfFaces = ResultsOfIntegration.GetLength(1);

                    for (int e = 0; e < NoOfFaces; e++)
                    {
                        var ip = ResultsOfIntegration.ExtractSubArrayShallow(new int[] { i, e, 0, 0 }, new int[] { i - 1, e - 1, D - 1, N - 1 });
                        ResPart.Acc(1.0, ip);
                    }
                    jSgrd++;
                }
            },
                                                                                cs : CoordinateSystem.Physical);

            qBnd.Execute();

            var ret = RHS.ResizeShallow(N * D, _mask.NoOfItemsLocally);

            return(ret);
        }
Ejemplo n.º 18
0
        protected MultidimensionalArray GaußAnsatzRHS(DivergenceFreeBasis TestBasis, CellBoundaryQuadratureScheme cellBndScheme, CellMask _mask, int order)
        {
            var _Context = this.tracker.GridDat;
            int D        = this.tracker.GridDat.Grid.SpatialDimension;
            int N        = TestBasis.Count;
            var coordSys = CoordinateSystem.Reference;
            var LsTrk    = this.tracker;
            int Nrhs     = _mask.NoOfItemsLocally;

            Debug.Assert(N % D == 0);
            N /= D;
            MultidimensionalArray RHS = MultidimensionalArray.Create(N, Nrhs);

            var splx      = this.Kref;
            int NoOfFaces = splx.NoOfFaces;
            //var normals = _Context.GridDat.Normals;
            CellBoundaryQuadrature <CellBoundaryQuadRule> qBnd = null;

            int jSgrd = 0;

            qBnd = CellBoundaryQuadrature <CellBoundaryQuadRule> .GetQuadrature(new int[] { N },
                                                                                _Context, cellBndScheme.Compile(_Context, order),
                                                                                delegate(int i0, int Length, CellBoundaryQuadRule QR, MultidimensionalArray EvalResult) { // Evaluate
                NodeSet Nodes = QR.Nodes;
                MultidimensionalArray BasisValues;
                if (coordSys == CoordinateSystem.Physical)
                {
                    //BasisValues = TestBasis.CellEval(Nodes, i0, Length);
                    throw new NotImplementedException("todo");
                }
                else if (coordSys == CoordinateSystem.Reference)
                {
                    BasisValues = TestBasis.Values.GetValues(Nodes);
                }
                else
                {
                    throw new NotImplementedException();
                }

                for (int i = 0; i < Length; i++)       // loop over cells

                {
                    CellBoundaryQuadRule cR = qBnd.CurrentRule;
                    int[] NodesPerEdge      = cR.NumbersOfNodesPerFace;
                    Debug.Assert(object.ReferenceEquals(splx, cR.RefElement));

                    int iNode = 0;

                    Debug.Assert(NoOfFaces == NodesPerEdge.Length);
                    for (int e = 0; e < NoOfFaces; e++)              // loop over the faces of the cell
                    {
                        for (int _n = 0; _n < NodesPerEdge[e]; _n++) // loop over nodes in one edge
                        {
                            for (int n = 0; n < N; n++)              // loop over Test polynomials (the same as the basis polynomials)
                            {
                                double acc = 0;
                                for (int d = 0; d < D; d++)       // loop over spatial directions

                                {
                                    if (coordSys == CoordinateSystem.Physical)
                                    {
                                        throw new NotImplementedException("todo");
                                        //int q = _Context.GridDat.LocalCellIndexToEdges[i+i0, e];
                                        //int iEdge = Math.Abs(q) - 1;
                                        //double Nsign = Math.Sign(q);
                                        //double Nd = normals[iEdge, d];
                                        //EvalResult[i, iNode, n, d] = BasisValues[i, iNode, n]*Nd*Nsign;
                                    }
                                    else
                                    {
                                        Debug.Assert(coordSys == CoordinateSystem.Reference);
                                        double Nd = splx.FaceNormals[e, d];
                                        //Debug.Assert(Nd == normals[iEdge, d]*Nsign);
                                        acc += BasisValues[iNode, n *D + d] * Nd;
                                    }
                                }
                                EvalResult[i, iNode, n] = acc;
                            }

                            iNode++;
                        }
                    }
                    Debug.Assert(iNode == EvalResult.GetLength(1));
                }
            },
                                                                                delegate(int i0, int Length, MultidimensionalArray ResultsOfIntegration) { // SaveIntegrationResults
                for (int i = 0; i < Length; i++)
                {
                    var ResPart = RHS.ExtractSubArrayShallow(new int[] { 0, jSgrd }, new int[] { N - 1, jSgrd - 1 });

                    for (int e = 0; e < NoOfFaces; e++)
                    {
                        var ip = ResultsOfIntegration.ExtractSubArrayShallow(new int[] { i, e, 0 }, new int[] { i - 1, e - 1, N - 1 });
                        ResPart.Acc(1.0, ip);
                    }
                    jSgrd++;
                }
            },
                                                                                cs : coordSys);

            qBnd.Execute();


            return(RHS);
        }
Ejemplo n.º 19
0
        protected MultidimensionalArray GaußAnsatzMatrix(DivergenceFreeBasis TestBasis, NodeSet SurfQrNodes, int jCell)
        {
            int N = TestBasis.Count;
            int D = this.tracker.GridDat.Grid.SpatialDimension;

            Debug.Assert(N % D == 0);
            N /= D;
            int ksurf = SurfQrNodes.GetLength(0);

            Debug.Assert(SurfQrNodes.Dimension == 2);
            Debug.Assert(SurfQrNodes.GetLength(1) == D);
            int iKref = this.tracker.GridDat.Cells.GetRefElementIndex(jCell);

            MultidimensionalArray EdgMatrix = MultidimensionalArray.Create(N, ksurf);

            // evaluate Basis and Gradient of Basis
            var Phi             = TestBasis.Values.GetValues(SurfQrNodes); // test function, n
            var LevelSetNormals = this.LevelSetData.GetLevelSetReferenceNormals(SurfQrNodes, jCell, 1).ExtractSubArrayShallow(0, -1, -1);

            //metrics = tracker.GetLevelSetNormalReferenceToPhysicalMetrics(this.LevelSetIndex, 0, jCell, 1);

            // multiply
            for (int k = 0; k < ksurf; k++)  // loop over nodes...
            {
                for (int n = 0; n < N; n++)  // loop over basis polynomials...
                {
                    double acc = 0.0;
                    for (int d = 0; d < D; d++) // loop over spatial dimension...
                    {
                        acc += Phi[k, n *D + d] * LevelSetNormals[k, d];
                    }
                    EdgMatrix[n, k] = acc;
                }
            }

            // resize and return:
            return(EdgMatrix);
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Fill the PeerTable with fresh addresses
        /// </summary>
        public void DiscoverPeers(int peerToFind = 990)
        {
            TraceCorrelation traceCorrelation = new TraceCorrelation(NodeServerTrace.Trace, "Discovering nodes");
            List<Task> tasks = new List<Task>();
            using(traceCorrelation.Open())
            {
                while(CountPeerRequired(peerToFind) != 0)
                {
                    NodeServerTrace.PeerTableRemainingPeerToGet(CountPeerRequired(peerToFind));
                    CancellationTokenSource cancellation = new CancellationTokenSource(TimeSpan.FromSeconds(40));
                    var peers = PeerTable.GetActivePeers(1000);
                    if(peers.Length == 0)
                    {
                        PopulateTableWithDNSNodes();
                        PopulateTableWithHardNodes();
                        peers = PeerTable.GetActivePeers(1000);
                    }

                    CancellationTokenSource peerTableFull = new CancellationTokenSource();
                    NodeSet connected = new NodeSet();
                    try
                    {
                        Parallel.ForEach(peers, new ParallelOptions()
                        {
                            MaxDegreeOfParallelism = 5,
                            CancellationToken = peerTableFull.Token,
                        }, p =>
                        {
                            Node n = null;
                            try
                            {
                                n = GetNodeByPeer(p, cancellation.Token);
                                if(n.State < NodeState.HandShaked)
                                {
                                    connected.AddNode(n);
                                    n.VersionHandshake(cancellation.Token);
                                }
                                n.SendMessage(new GetAddrPayload());
                                Thread.Sleep(2000);
                            }
                            catch(Exception)
                            {
                                if(n != null)
                                    n.Disconnect();
                            }
                            if(CountPeerRequired(peerToFind) == 0)
                                peerTableFull.Cancel();
                            else
                                NodeServerTrace.Information("Need " + CountPeerRequired(peerToFind) + " more peers");
                        });
                    }
                    catch(OperationCanceledException)
                    {
                    }
                    finally
                    {
                        connected.DisconnectAll();
                    }
                }
                NodeServerTrace.Trace.TraceInformation("Peer table is now full");
            }
        }
Ejemplo n.º 21
0
 static bool cmpQueryBoolO(Operator.Op op, object val1, object val2) {
     NodeSet n1 = new NodeSet(val1);
     double d1 = n1.MoveNext() ? 1.0 : 0;
     double d2 = NumberFunctions.Number((bool)val2);
     return cmpNumberNumberO(op, d1, d2);
 }
Ejemplo n.º 22
0
        // Render the network //
        public NeuralNetwork Construct()
        {

            // Create the scrubber //
            NeuralDataFactory scrubber = new NeuralDataFactory(this._SourceData, this._XValues, this._YValues, this._Where);

            // Create the data layer //
            this._DataLayer = new NN_Layer(this._DataBias, scrubber.InputKey, scrubber.Columns);

            // Create the prediction layer //
            this._PredictionLayer = new NN_Layer(this._PredictionReducer, this._PredictionActivation, scrubber.OutputKey);

            // Link predictions to last hidden //
            if (this._HiddenLayers.Count == 0)
            {
                NN_Layer.LinkChildren(this._Links, this._PredictionLayer, this._DataLayer);
            }
            else
            {

                // Data -> First.Hidden
                NN_Layer.LinkChildren(this._Links, this._HiddenLayers.First(), this._DataLayer);

                // Last.Hidden -> Predictions //
                NN_Layer.LinkChildren(this._Links, this._PredictionLayer, this._HiddenLayers.Last());

                // Hidden -> Hidden //
                for (int i = 0; i < this._HiddenLayers.Count - 1; i++)
                    NN_Layer.LinkChildren(this._Links, this._HiddenLayers[i + 1], this._HiddenLayers[i]);

            }

            // Build a nodeset //
            NodeSet nodes = new NodeSet(this._Links);

            // Build a response set //
            ResponseNodeSet responses = new ResponseNodeSet(this._Links);

            // Neural rule //
            NeuralRule rule = RuleFactory.Construct(this.DefaultRule, responses);

            // Construct //
            return new NeuralNetwork(this._name, this._Links, nodes, responses, rule, scrubber.ScrubbedData);

        }
Ejemplo n.º 23
0
		private SlashIterator (SlashIterator other) : base (other)
		{
			_iterLeft = (BaseIterator) other._iterLeft.Clone ();
			if (other._iterRight != null)
				_iterRight = (BaseIterator) other._iterRight.Clone ();
			_expr = other._expr;
			if (other._iterList != null)
				_iterList = (SortedList) other._iterList.Clone ();
			_finished = other._finished;
			if (other._nextIterRight != null)
				_nextIterRight = (BaseIterator) other._nextIterRight.Clone ();
		}
Ejemplo n.º 24
0
		public SlashIterator (BaseIterator iter, NodeSet expr) : base (iter.NamespaceManager)
		{
			_iterLeft = iter;
			_expr = expr;
		}
Ejemplo n.º 25
0
		private SimpleSlashIterator (SimpleSlashIterator other)
			: base (other)
		{
			_expr = other._expr;
			_left = (BaseIterator) other._left.Clone ();
			if (other._right != null)
				_right = (BaseIterator) other._right.Clone ();
		}
Ejemplo n.º 26
0
		public SimpleSlashIterator (BaseIterator left, NodeSet expr)
			: base (left.NamespaceManager)
		{
			this._left = left;
			this._expr = expr;
		}
Ejemplo n.º 27
0
		public override Expression Optimize ()
		{
			left = left.Optimize ();
			right = (NodeSet) right.Optimize ();
			// Path A//B is equal to 
			// A/descendant-or-self::node()/child::B, which is
			// equivalent to A/descendant::B. Unlike '//', '/'
			// could be optimized by SimpleSlashIterator.
			NodeTest rnt = right as NodeTest;
			if (rnt != null && rnt.Axis.Axis == Axes.Child) {
				NodeNameTest nameTest = rnt as NodeNameTest;
				if (nameTest != null)
					return new ExprSLASH (left,
						new NodeNameTest (nameTest, Axes.Descendant));
				NodeTypeTest typeTest = rnt as NodeTypeTest;
				if (typeTest != null)
					return new ExprSLASH (left,
						new NodeTypeTest (typeTest, Axes.Descendant));
			}
			return this;
		}
Ejemplo n.º 28
0
		public ExprSLASH2 (Expression left, NodeSet right)
		{
			this.left = left;
			this.right = right;
		}
Ejemplo n.º 29
0
        protected override GridCommons CreateOrLoadGrid()
        {
            // Options
            string dataPath     = @"\\fdyprime\userspace\mueller\Jan\waves\";
            string databasePath = @"e:\bosss_db\GridOfTomorrow\";

            noOfCellsX       = 64;
            noOfNodesPerEdge = 4;
            dgDegree         = 6;

            //noOfCellsX = 85;
            //noOfNodesPerEdge = 4;
            //dgDegree = 6;

            Directory.SetCurrentDirectory(dataPath);
            DatabaseInfo database           = new DatabaseInfo(databasePath);
            string       sessionDescription = "Blafasel";

            // Create the grid
            aspectRatio = 4;
            GridCommons grid = Grid2D.Cartesian2DGrid(
                GenericBlas.Linspace(0.0, 1.0, noOfCellsX + 1),
                GenericBlas.Linspace(-1.5, 2.5, aspectRatio * noOfCellsX + 1),
                CellType.Square_Linear,
                periodicX: true,
                periodicY: false);

            grid.EdgeTagNames.Add(1, "subsonicOutlet");
            grid.EdgeTagNames.Add(2, "supersonicInlet");
            grid.DefineEdgeTags(delegate(double[] x) {
                if (x[1] > 0.0)
                {
                    return(2);
                }
                else
                {
                    return(1);
                }
            });
            gridData = new GridData(grid);

            // Read the values
            MultidimensionalArray rho = ReadVariableValues("rho");
            MultidimensionalArray u   = ReadVariableValues("vx1");
            MultidimensionalArray v   = ReadVariableValues("vx2");
            MultidimensionalArray p   = ReadVariableValues("prs");

            // Assemble node set corresponding to the ordering from Matlab
            double[] nodes1D          = GenericBlas.Linspace(-1.0, 1.0, noOfNodesPerEdge);
            int      noOfNodesPerCell = noOfNodesPerEdge * noOfNodesPerEdge;

            double[,] localNodes = new double[noOfNodesPerCell, gridData.SpatialDimension];
            for (int i = 0; i < noOfNodesPerEdge; i++)
            {
                for (int j = 0; j < noOfNodesPerEdge; j++)
                {
                    int localNodeIndex = i * noOfNodesPerEdge + j;
                    localNodes[localNodeIndex, 0] = nodes1D[i];
                    localNodes[localNodeIndex, 1] = nodes1D[j];
                }
            }
            nodeSet = new NodeSet(gridData.Grid.RefElements[0], localNodes);

            // Interpolate
            //SinglePhaseField[] fields = LeastSquaresInterpolation(rho, u, v, p);
            SinglePhaseField[] fields = SpecFEMInterpolation(rho, u, v, p);

            // Save everything
            database.Controller.DBDriver.SaveGrid(grid);

            SessionInfo session = database.Controller.DBDriver.CreateNewSession(database);

            session.Description = sessionDescription;
            session.Save();

            database.Controller.DBDriver.SaveTimestep(
                0.0, 0, session, gridData, fields);

            return(grid);
        }
Ejemplo n.º 30
0
 double EvaluateAt(S Psi, NodeSet Point)
 {
     return(EvaluateAt(Psi, Point, this.cell));
 }
Ejemplo n.º 31
0
 static bool cmpQueryBoolE(Operator.Op op, object val1, object val2) {
     NodeSet n1 = new NodeSet(val1);
     bool b1 = n1.MoveNext();
     bool b2 = (bool)val2;
     return cmpBoolBoolE(op, b1, b2);
 }
Ejemplo n.º 32
0
 bool HeightDirectionIsSuitable(T arg, S psi, NodeSet Point, int heightDirection, MultidimensionalArray gradient)
 {
     return(HeightDirectionIsSuitable(arg, psi, Point, heightDirection, gradient, this.cell));
 }
Ejemplo n.º 33
0
        /*cmpXslt:*/
        static bool cmpQueryQueryE(Operator.Op op, object val1, object val2) {
            Debug.Assert(op == Operator.Op.EQ || op == Operator.Op.NE);
            bool isEQ = (op == Operator.Op.EQ);

            NodeSet n1 = new NodeSet(val1);
            NodeSet n2 = new NodeSet(val2);

            while (true) {
                if (! n1.MoveNext()) {
                    return false;
                }
                if (! n2.MoveNext()) {
                    return false;
                }

                string str1 = n1.Value;

                do {
                    if ((str1 == n2.Value) == isEQ) {
                        return true;
                    }
                }while (n2.MoveNext());
                n2.Reset();    
            }
        }
Ejemplo n.º 34
0
 double EvaluateBounds(T arg, S psi, NodeSet x_center)
 {
     return(EvaluateBounds(arg, psi, x_center, this.cell));
 }
Ejemplo n.º 35
0
        public NodeSet CreateNodeSet(int size)
        {
            if(size > 1000)
                throw new ArgumentOutOfRangeException("size", "size should be less than 1000");
            TraceCorrelation trace = new TraceCorrelation(NodeServerTrace.Trace, "Creating node set of size " + size);
            NodeSet set = new NodeSet();
            using(trace.Open())
            {
                while(set.Count() < size)
                {
                    var peerToGet = size - set.Count();
                    var activePeers = PeerTable.GetActivePeers(1000);
                    activePeers = activePeers.Where(p => !set.Contains(p.NetworkAddress.Endpoint)).ToArray();
                    if(activePeers.Length < peerToGet)
                    {
                        DiscoverPeers(size);
                        continue;
                    }
                    NodeServerTrace.Information("Need " + peerToGet + " more nodes");

                    BlockingCollection<Node> handshakedNodes = new BlockingCollection<Node>(peerToGet);
                    CancellationTokenSource handshakedFull = new CancellationTokenSource();

                    try
                    {
                        Parallel.ForEach(activePeers,
                            new ParallelOptions()
                            {
                                MaxDegreeOfParallelism = 10,
                                CancellationToken = handshakedFull.Token
                            }, p =>
                        {
                            if(set.Contains(p.NetworkAddress.Endpoint))
                                return;
                            Node node = null;
                            try
                            {
                                node = GetNodeByPeer(p, handshakedFull.Token);
                                node.VersionHandshake(handshakedFull.Token);
                                if(node != null && node.State != NodeState.HandShaked)
                                    node.Disconnect();
                                if(!handshakedNodes.TryAdd(node))
                                {
                                    handshakedFull.Cancel();
                                    node.Disconnect();
                                }
                                else
                                {
                                    var remaining = (size - set.Count() - handshakedNodes.Count);
                                    if(remaining == 0)
                                    {
                                        handshakedFull.Cancel();
                                    }
                                    else
                                        NodeServerTrace.Information("Need " + remaining + " more nodes");
                                }
                            }
                            catch(Exception)
                            {
                                if(node != null)
                                    node.Disconnect();
                            }
                        });
                    }
                    catch(OperationCanceledException)
                    {
                    }
                    set.AddNodes(handshakedNodes.ToArray());
                }
            }
            return set;
        }
Ejemplo n.º 36
0
 protected abstract double EvaluateAt(S Psi, NodeSet Point, int cell);
Ejemplo n.º 37
0
 public Model(EndianBinaryReader er)
 {
     long basepos = er.BaseStream.Position;
     size = er.ReadUInt32();
     ofsSbc = er.ReadUInt32();
     ofsMat = er.ReadUInt32();
     ofsShp = er.ReadUInt32();
     ofsEvpMtx = er.ReadUInt32();
     info = new ModelInfo(er);
     nodes = new NodeSet(er);
     long curpos = er.BaseStream.Position;
     er.BaseStream.Position = ofsSbc + basepos;
     sbc = er.ReadBytes((int)(ofsMat - ofsSbc));
     er.BaseStream.Position = curpos;
     er.BaseStream.Position = ofsMat + basepos;
     materials = new MaterialSet(er);
     er.BaseStream.Position = ofsShp + basepos;
     shapes = new ShapeSet(er);
     if (ofsEvpMtx != size && ofsEvpMtx != 0)
     {
         er.BaseStream.Position = ofsEvpMtx + basepos;
         evpMatrices = new EvpMatrices(er, nodes.dict.numEntry);
     }
     /*long modelset = er.GetMarker("ModelSet");
     er.ClearMarkers();
     curpos = er.BaseStream.Position;
     er.BaseStream.Position = modelset;
     er.SetMarkerOnCurrentOffset("ModelSet");
     er.BaseStream.Position = curpos;*/
 }
Ejemplo n.º 38
0
 protected abstract bool HeightDirectionIsSuitable(T arg, S psi, NodeSet Point, int heightDirection,
                                                   MultidimensionalArray gradient, int cell);
Ejemplo n.º 39
0
        NodeSet ProjectOntoLevset(int jCell, NodeSet Nodes)
        {
            int      D         = Nodes.GetLength(1);
            int      NoOfNodes = Nodes.GetLength(0);
            var      m_Context = this.tracker.GridDat;
            LevelSet LevSet    = (LevelSet)(this.tracker.LevelSets[this.LevelSetIndex]);

            MultidimensionalArray LevSetValues = MultidimensionalArray.Create(1, NoOfNodes);
            MultidimensionalArray LevSetGrad   = MultidimensionalArray.Create(1, NoOfNodes, D);

            MultidimensionalArray x0_i_Local  = MultidimensionalArray.Create(1, NoOfNodes, D);
            MultidimensionalArray x0_i_Global = MultidimensionalArray.Create(1, NoOfNodes, D); // quadrature nodes in global coordinates

            MultidimensionalArray x0_ip1_Local  = MultidimensionalArray.Create(1, NoOfNodes, D);
            MultidimensionalArray x0_ip1_Global = MultidimensionalArray.Create(NoOfNodes, D);

            // set initial value;


            x0_i_Local.SetSubArray(Nodes, 0, -1, -1);

            int NN = NoOfNodes;

            for (int i = 0; i < 10; i++)
            {
                double radiusError = 0;


                int j = jCell;


                LevSet.Evaluate(j, 1, Nodes, LevSetValues, 0, 0.0);
                LevSet.EvaluateGradient(j, 1, Nodes, LevSetGrad);


                m_Context.TransformLocal2Global(new NodeSet(this.Kref, x0_i_Local.ExtractSubArrayShallow(0, -1, -1)), j, 1, x0_i_Global, 0);

                for (int nn = 0; nn < NN; nn++)
                {
                    double sc = 0;
                    for (int d = 0; d < D; d++)
                    {
                        sc += LevSetGrad[0, nn, d].Pow2();
                    }


                    for (int d = 0; d < D; d++)
                    {
                        double xd = x0_i_Global[0, nn, d] - LevSetGrad[0, nn, d] * LevSetValues[0, nn] / sc;
                        x0_ip1_Global[nn, d] = xd;
                    }

                    radiusError += Math.Abs(LevSetValues[0, nn]);
                }

                m_Context.TransformGlobal2Local(x0_ip1_Global, x0_ip1_Local, j, 1, 0);


                // next iter: x0_i <- x0_{i+1}
                x0_i_Local.Set(x0_ip1_Local);
                Nodes = (new NodeSet(this.Kref, x0_i_Local.ExtractSubArrayShallow(0, -1, -1)));
            }

            return(Nodes);
        }
Ejemplo n.º 40
0
 public void AddNode(INode <T> node)
 {
     NodeSet.Add(node);
 }
Ejemplo n.º 41
0
        MultidimensionalArray StokesAnsatzMatrix(Basis TestBasis, NodeSet surfaceNodes, int jCell)
        {
            int N         = TestBasis.Length;
            int NoOfNodes = surfaceNodes.GetLength(0);
            int D         = surfaceNodes.GetLength(1);
            var GridDat   = this.tracker.GridDat;

            Debug.Assert(D == GridDat.SpatialDimension);
            int iKref    = GridDat.Cells.GetRefElementIndex(jCell);
            var scalings = GridDat.Cells.JacobiDet;
            int iLevSet  = this.LevelSetIndex;

            if (!GridDat.Cells.IsCellAffineLinear(jCell))
            {
                throw new NotSupportedException();
            }


            //var Phi = TestBasis.Evaluate(0);              // reference
            //var GradPhi = TestBasis.EvaluateGradient(0);  // reference
            var Phi     = TestBasis.CellEval(surfaceNodes, jCell, 1).ExtractSubArrayShallow(0, -1, -1);              // physical
            var GradPhi = TestBasis.CellEvalGradient(surfaceNodes, jCell, 1).ExtractSubArrayShallow(0, -1, -1, -1);  // physical

            //var LevsetNormal = this.LsTrk.GetLevelSetReferenceNormals(iLevSet, 0, jCell, 1);  // reference
            //var Curvature = this.LsTrk.GetLevelSetReferenceCurvature(iLevSet, 0, jCell, 1);   // reference
            var LevsetNormal = this.LevelSetData.GetLevelSetNormals(surfaceNodes, jCell, 1).ExtractSubArrayShallow(0, -1, -1); // physical
            var Curvature    = MultidimensionalArray.Create(1, NoOfNodes);                                                     // physical

            ((LevelSet)(this.tracker.LevelSets[iLevSet])).EvaluateTotalCurvature(jCell, 1, surfaceNodes, Curvature);           // physical

            var Coeffs = MultidimensionalArray.Create(D, N, NoOfNodes);

            if (D == 2)
            {
                for (int k = 0; k < NoOfNodes; k++)   // loop over nodes
                {
                    double Nx    = LevsetNormal[k, 0];
                    double Ny    = LevsetNormal[k, 1];
                    double kappa = Curvature[0, k];


                    double Prj_11 = 1.0 - Nx * Nx, Prj_12 = -Nx * Ny,
                           Prj_21 = -Ny * Nx, Prj_22 = 1.0 - Ny * Ny;

                    for (int n = 0; n < N; n++)
                    {
                        double Phi_kn     = Phi[k, n];
                        double dPhi_dx_kn = GradPhi[k, n, 0];
                        double dPhi_dy_kn = GradPhi[k, n, 1];

                        Coeffs[0, n, k] = -Phi_kn * kappa * Nx + Prj_11 * dPhi_dx_kn + Prj_12 * dPhi_dy_kn;
                        Coeffs[1, n, k] = -Phi_kn * kappa * Ny + Prj_21 * dPhi_dx_kn + Prj_22 * dPhi_dy_kn;
                    }
                }
            }
            else if (D == 3)
            {
                throw new NotImplementedException("to do.");
            }
            else
            {
                throw new NotSupportedException("Unknown spatial dimension.");
            }

            Coeffs.Scale(scalings[jCell]);  // physical

            return(Coeffs.ResizeShallow(N * D, NoOfNodes));
        }
Ejemplo n.º 42
0
 public bool Contains(INode <T> node)
 {
     return(NodeSet.Contains(node));
 }
Ejemplo n.º 43
0
        //Algorithm 3
        //page: A1006
        protected void SayeRecursion(TreeNode <T> treeNode)
        {
            T arg = treeNode.Value;

            //Assert ... (line 1)
            Debug.Assert(arg.Surface == false || (arg.Dimension > 1 && arg.n == 1));
            //Check treeNode : Prune
            //-----------------------------------------------------------------------------------------------
            // If d = 1 ... (line 2)
            if (arg.Dimension == 1)
            {
                return;
            }
            //Define x_c (line 3)
            NodeSet x_center = arg.GetCellCenter();

            //for i = n downto 1 do (line 4)
            for (int i = arg.n - 1; i >= 0; --i)
            {
                Tuple <S, int> psiAndS = arg.PsiAndS[i];
                S psi_i = psiAndS.Item1;
                //Evaluate bounds on the value of psi_i on U such that sup_(x element U)|psi_i(x) - psi_i(x_c)| <= delta (line 5)
                double delta = EvaluateBounds(arg, psi_i, x_center);
                // if |psi_i(x_c)| >= delta then (line 6)
                if (delta <= Math.Abs(EvaluateAt(psi_i, x_center)))
                {
                    int s_i = psiAndS.Item2;
                    //if s_i * psi_i >= 0 (line 7)
                    if (s_i * EvaluateAt(psi_i, x_center) >= 0)
                    {
                        //Remove ψi from the list and decrement n by one. (line 8)
                        arg.PsiAndS.RemoveAt(i);
                    }
                    else
                    {
                        //The domain of integration is empty; return 0. (line 9,10)
                        arg.Status = SayeArgument <S> .Mode.DomainIsEmpty;
                        return;
                    }
                }
            }
            //if n = 0 then (line 11)
            if (arg.n == 0)
            {
                //If this is a Surface Integral, this Subcell is empty
                if (arg.Surface)
                {
                    arg.Status = SayeArgument <S> .Mode.DomainIsEmpty;
                }
                else
                {
                    //Apply a tensor - product Gaussian quadrature scheme (line 12)
                    arg.Status = SayeArgument <S> .Mode.GaussQuadrature;
                }
                return;
            }

            //Find new subspace
            //-----------------------------------------------------------------------------------------------
            //Set k = argmax_j|d_xj Psi_1(x_c)| and initialize Psi-tilde = empty (line 14)
            S   psi_1       = arg.PsiAndS[0].Item1;
            int k           = FindPromisingHeightDirection(psi_1, x_center);
            T   subspaceArg = DeriveNewArgument(arg);

            //for i = 1 to n do (line 15)
            foreach (Tuple <S, int> psiAndS in arg.PsiAndS)
            {
                S   psi_i = psiAndS.Item1;
                int s_i   = psiAndS.Item2;
                //Evaluate g := gradient(Psi_i(x_c)) (line 16)
                MultidimensionalArray g = Gradient(psi_i, x_center);
                //Determine bounds and check bounds (line 17,18)
                if (HeightDirectionIsSuitable(arg, psi_i, x_center, k, g))
                {
                    //Define Psi_i^L and Psi_i^U (line 19)
                    S[] subPsis = ExtractSubPsis(psi_i, arg, k);
                    S   psi_U   = subPsis[1];
                    S   psi_L   = subPsis[0];
                    //Evaluate signs s_i^L and s_i^U (line 20)
                    int s_U = EvaluateSign(g, k, s_i, arg.Surface, 1);
                    int s_L = EvaluateSign(g, k, s_i, arg.Surface, -1);
                    //Add {Psi_i^L, s_i^L}  and {Psi_i^U, s_i^U} to the collection Psi-tilde (line 21)
                    Tuple <S, int> newPsiAndS_U = new Tuple <S, int>(psi_U, s_U);
                    Tuple <S, int> newPsiAndS_L = new Tuple <S, int>(psi_L, s_L);
                    subspaceArg.PsiAndS.Add(newPsiAndS_U);
                    subspaceArg.PsiAndS.Add(newPsiAndS_L);
                }
                else
                {
                    //The height function direction ek is not suitable for ψi. If already subdivided too
                    //many times, revert to a low - order method(see discussion).Otherwise split U (line 23)
                    if (SubdivideSuitable(arg))
                    {
                        //Subdivide
                        T            siblingArg = Subdivide(arg);
                        TreeNode <T> sibling    = treeNode.AddSibling(siblingArg);
                        //Recalculate
                        SayeRecursion(treeNode);
                        SayeRecursion(sibling);
                    }
                    else
                    {
                        arg.Status = SayeArgument <S> .Mode.LowOrderQuadrature;
                    }
                    return;
                }
            }
            //Define a new integrand (line 24)
            arg.HeightDirection = k;
            //return I(...) (line 25)
            subspaceArg.Surface = false;
            subspaceArg.RemoveDimension(k);
            TreeNode <T> subSpaceNode = treeNode.AddChild(subspaceArg);

            SayeRecursion(subSpaceNode);
        }
Ejemplo n.º 44
0
		public override Expression Optimize ()
		{
			left = left.Optimize ();
			right = (NodeSet) right.Optimize ();
			return this;
		}
Ejemplo n.º 45
0
 int FindPromisingHeightDirection(S psi, NodeSet Point)
 {
     return(FindPromisingHeightDirection(psi, Point, this.cell));
 }
 public override object Clone()
 {
   NodeSet copy = new NodeSet();
   foreach (object o in this) 
   {
     copy.Add(o);
   }
   return copy;
 }
Ejemplo n.º 47
0
 MultidimensionalArray Gradient(S psi, NodeSet Node)
 {
     return(Gradient(psi, Node, this.cell));
 }
        /// <summary>
        /// Exports a node to a nodeset.
        /// </summary>
        public void ExportNode(NodeId nodeId, NodeSet nodeSet)
        {
            lock (m_lock)
            {
                ILocalNode node = GetLocalNode(nodeId) as ILocalNode;

                if (node == null)
                {
                    throw ServiceResultException.Create(StatusCodes.BadNodeIdUnknown, "NodeId ({0}) does not exist.", nodeId);
                }

                ExportNode(node, nodeSet, (node.NodeClass & (NodeClass.Object | NodeClass.Variable)) != 0);
            }
        }
Ejemplo n.º 49
0
 protected abstract MultidimensionalArray Gradient(S psi, NodeSet Node, int Cell);
        /// <summary>
        /// Exports a node to a nodeset.
        /// </summary>
        public void ExportNode(ILocalNode node, NodeSet nodeSet, bool instance)
        {
            lock (m_lock)
            {
                // check if the node has already been added.
                NodeId exportedId = nodeSet.Export(node.NodeId, m_nodes.NamespaceUris);

                if (nodeSet.Contains(exportedId))
                {
                    return;
                }

                // add to nodeset.
                Node nodeToExport = nodeSet.Add(node, m_nodes.NamespaceUris, m_nodes.ServerUris);

                // follow children.
                foreach (ReferenceNode reference in node.References)
                {
                    // export all references.
                    bool export = true;

                    // unless it is a subtype reference.
                    if (m_server.TypeTree.IsTypeOf(reference.ReferenceTypeId, ReferenceTypeIds.HasSubtype))
                    {
                        export = false;
                    }
       
                    if (export)
                    {
                        nodeSet.AddReference(nodeToExport, reference, m_nodes.NamespaceUris, m_nodes.ServerUris);
                    }
                    
                    if (reference.IsInverse || m_server.TypeTree.IsTypeOf(reference.ReferenceTypeId, ReferenceTypeIds.HasSubtype))
                    {
                        nodeSet.AddReference(nodeToExport, reference, m_nodes.NamespaceUris, m_nodes.ServerUris);
                    }

                    if (m_server.TypeTree.IsTypeOf(reference.ReferenceTypeId, ReferenceTypeIds.Aggregates))
                    {
                        if (reference.IsInverse)
                        {
                            continue;
                        }
                        
                        ILocalNode child = GetLocalNode(reference.TargetId) as ILocalNode;

                        if (child != null)
                        {
                            if (instance)
                            {
                                NodeId modellingRule = child.ModellingRule;

                                if (modellingRule != Objects.ModellingRule_Mandatory)
                                {
                                    continue;
                                }
                            }

                            ExportNode(child, nodeSet, instance);
                        }
                    }
                }
            }
        }
Ejemplo n.º 51
0
 protected abstract int FindPromisingHeightDirection(S psi, NodeSet Point, int cell);
Ejemplo n.º 52
0
        /*cmpXslt:*/
        static bool cmpQueryQueryO(Operator.Op op, object val1, object val2) {
            Debug.Assert(
                op == Operator.Op.LT || op == Operator.Op.GT ||
                op == Operator.Op.LE || op == Operator.Op.GE
            );

            NodeSet n1 = new NodeSet(val1);
            NodeSet n2 = new NodeSet(val2);

            while (true) {
                if (!n1.MoveNext()) {
                    return false;
                }
                if (!n2.MoveNext()) {
                    return false;
                }

                double num1 = NumberFunctions.Number(n1.Value);

                do {
                    if (cmpNumberNumber(op, num1, NumberFunctions.Number(n2.Value))) {
                        return true;
                    }
                } while (n2.MoveNext());
                n2.Reset();
            }
        }        
Ejemplo n.º 53
0
 protected abstract double EvaluateBounds(T arg, S psi, NodeSet x_center, int cell);
Ejemplo n.º 54
0
        static bool cmpQueryStringE(Operator.Op op, object val1, object val2) {
            NodeSet n1 = new NodeSet(val1);
            string n2 = (string) val2;

            while (n1.MoveNext()) {
                if (cmpStringStringE(op, n1.Value, n2)) {
                    return true;
                }
            }
            return false;
        }
Ejemplo n.º 55
0
 public INode <T> GetNode(T data)
 {
     return(NodeSet.FindByValue(data));
 }
Ejemplo n.º 56
0
        static bool cmpQueryStringO(Operator.Op op, object val1, object val2) {
            NodeSet n1 = new NodeSet(val1); 
            double n2 = NumberFunctions.Number((string) val2);

            while (n1.MoveNext()) {
                if (cmpNumberNumberO(op, NumberFunctions.Number(n1.Value), n2)) {
                    return true;
                }
            }
            return false;
        }
Ejemplo n.º 57
0
 public bool Contains(T value)
 {
     return(NodeSet.FindByValue(value) != null);
 }
Ejemplo n.º 58
0
        static bool cmpRtfQueryE(Operator.Op op, object val1, object val2) {
            string n1 = Rtf(val1);
            NodeSet n2 = new NodeSet(val2);

            while (n2.MoveNext()) {
                if (cmpStringStringE(op, n1, n2.Value)) {
                    return true;
                }
            }
            return false;
        }
Ejemplo n.º 59
0
        /// <summary>
        /// modifies a matrix <paramref name="Mtx"/> and a right-hand-side <paramref name="rhs"/>
        /// in order to fix the pressure at some reference point
        /// </summary>
        /// <param name="map">row mapping for <paramref name="Mtx"/> as well as <paramref name="rhs"/></param>
        /// <param name="iVar">the index of the pressure variable in the mapping <paramref name="map"/>.</param>
        /// <param name="LsTrk"></param>
        /// <param name="Mtx"></param>
        /// <param name="rhs"></param>
        static public void SetPressureReferencePoint <T>(UnsetteledCoordinateMapping map, int iVar, LevelSetTracker LsTrk, BlockMsrMatrix Mtx, T rhs)
            where T : IList <double>
        {
            using (new FuncTrace()) {
                var GridDat = map.GridDat;

                if (rhs.Count != map.LocalLength)
                {
                    throw new ArgumentException();
                }
                if (!Mtx.RowPartitioning.EqualsPartition(map) || !Mtx.ColPartition.EqualsPartition(map))
                {
                    throw new ArgumentException();
                }

                Basis PressureBasis = (Basis)map.BasisS[iVar];
                int   D             = GridDat.SpatialDimension;

                long GlobalID, GlobalCellIndex;
                bool IsInside, onthisProc;
                GridDat.LocatePoint(new double[D], out GlobalID, out GlobalCellIndex, out IsInside, out onthisProc, LsTrk.Regions.GetCutCellSubGrid().VolumeMask.Complement());

                int iRowGl = -111;
                if (onthisProc)
                {
                    int jCell = (int)GlobalCellIndex - GridDat.CellPartitioning.i0;


                    NodeSet CenterNode = new NodeSet(GridDat.iGeomCells.GetRefElement(jCell), new double[D]);
                    MultidimensionalArray LevSetValues = LsTrk.DataHistories[0].Current.GetLevSetValues(CenterNode, jCell, 1);;


                    MultidimensionalArray CenterNodeGlobal = MultidimensionalArray.Create(1, D);
                    GridDat.TransformLocal2Global(CenterNode, CenterNodeGlobal, jCell);
                    //Console.WriteLine("Pressure Ref Point @( {0:0.###E-00} | {1:0.###E-00} )", CenterNodeGlobal[0,0], CenterNodeGlobal[0,1]);


                    LevelSetSignCode  scode = LevelSetSignCode.ComputeLevelSetBytecode(LevSetValues[0, 0]);
                    ReducedRegionCode rrc;
                    int No   = LsTrk.Regions.GetNoOfSpecies(jCell, out rrc);
                    int iSpc = LsTrk.GetSpeciesIndex(rrc, scode);

                    iRowGl = (int)map.GlobalUniqueCoordinateIndex_FromGlobal(iVar, GlobalCellIndex, 0);
                }
                iRowGl = iRowGl.MPIMax();


                // clear row
                // ---------
                if (onthisProc)
                {
                    // ref. cell is on local MPI process
                    int jCell = (int)GlobalCellIndex - GridDat.CellPartitioning.i0;

                    ReducedRegionCode rrc;
                    int NoOfSpc = LsTrk.Regions.GetNoOfSpecies(jCell, out rrc);

                    // set matrix row to identity
                    Mtx.ClearRow(iRowGl);
                    Mtx.SetDiagonalElement(iRowGl, 1.0);


                    // clear RHS
                    int iRow = iRowGl - Mtx.RowPartitioning.i0;
                    rhs[iRow] = 0;
                }

                // clear column
                // ------------
                {
                    for (int i = Mtx.RowPartitioning.i0; i < Mtx.RowPartitioning.iE; i++)
                    {
                        if (i != iRowGl)
                        {
                            Mtx[i, iRowGl] = 0;
                        }
                    }
                }
            }
        }
Ejemplo n.º 60
0
        static bool cmpRtfQueryO(Operator.Op op, object val1, object val2) {
            double n1 = NumberFunctions.Number(Rtf(val1));
            NodeSet n2 = new NodeSet(val2);

            while (n2.MoveNext()) {
                if (cmpNumberNumberO(op, n1, NumberFunctions.Number(n2.Value))) {
                    return true;
                }
            }
            return false;
        }