コード例 #1
0
 private static IEnumerable <KeyValuePair <IntVector3, Vector3> > VertexSymmetryGroup(string symmetryType, IntVector3 key, Vector3 position)
 {
     foreach (Symmetry symmetry in Symmetry.SymmetryGroup(symmetryType))
     {
         yield return(new KeyValuePair <IntVector3, Vector3>(symmetry.Apply(key), symmetry.Apply(position)));
     }
 }
コード例 #2
0
    public static IEnumerable <Symmetry> SymmetryGroup(string symmetryType)
    {
        ParseSymmetryType(symmetryType, out bool shouldRotate, out bool shouldReverse, out bool shouldFlipX, out bool shouldFlipY, out bool shouldFlipZ, out bool positiveOnly, out bool negativeOnly);

        for (int r = 0; r < (shouldRotate ? 3 : 1); r++)
        {
            for (int x = shouldFlipX ? -1 : 1; x <= 1; x += 2)
            {
                for (int y = shouldFlipY ? -1 : 1; y <= 1; y += 2)
                {
                    for (int z = shouldFlipZ ? -1 : 1; z <= 1; z += 2)
                    {
                        for (int t = 0; t < (shouldReverse ? 2 : 1); t++)
                        {
                            var result = new Symmetry(new IntVector3(x, y, z), r, t > 0 ? true : false);
                            if ((positiveOnly && result.isNegative) || (negativeOnly && !result.isNegative))
                            {
                                continue;
                            }
                            yield return(result);
                        }
                    }
                }
            }
        }
    }
コード例 #3
0
    public static RenderGeometry CreateCuboctahedronGeometry(float size, float ratio)
    {
        if (ratio <= 0)
        {
            return(CreateTetrahedronGeometry(size, 1));
        }
        if (ratio >= 1)
        {
            RenderGeometry result = CreateTetrahedronGeometry(size, 1);
            result.ApplyRotation(Quaternion.AngleAxis(90, Vector3.up));
            return(result);
        }

        RenderGeometry geometry = new RenderGeometry();

        var corners = new Dictionary <IntVector3, Vertex>();

        foreach (var symmetry in Symmetry.SymmetryGroup("110"))
        {
            IntVector3 key      = symmetry.Apply(Key(1, 1, 0));
            Vector3    position = symmetry.Apply(Vec(1, 1, (1 - ratio * 2) * (symmetry.isNegative ? -1 : 1)) * (size / 2));
            corners[key] = geometry.CreateVertex(position);
        }
        foreach (IntVector3[] keys in Combine(
                     FaceSymmetryGroup("100", Key(1, 0, -1), Key(1, 1, 0), Key(1, 0, 1), Key(1, -1, 0)),
                     FaceSymmetryGroup("111", Key(1, 1, 0), Key(0, 1, 1), Key(1, 0, 1))))
        {
            geometry.CreateFace(keys.Select(key => corners[key]).ToArray());
        }
        return(geometry);
    }
コード例 #4
0
    public override async Task OnClick(BaseTreeNode node_, Symmetry.Carbon.Client.ICarbonClient cc_)
    {
      var frm = new UserBbgListEditor();
      try
      {
        frm.Create(
          listName_: node_.Text,
          currentTickers_: UserBbgLists.Instance.GetCurrentTickersForList(node_.Text));


        var result = frm.DisplayInShowFormDialog(string.Format("Edit bbg list '{0}'", node_.Text), null);

        if (result == System.Windows.Forms.DialogResult.Cancel) return;

        var listname = frm.ListName;
        var tickers = frm.Tickers;

        await UserBbgLists.Instance.UpdateList(
          listName_: frm.ListName,
          tickersAndFields_: frm.Tickers.Select(ticker => Tuple.Create(ticker, "LAST_PRICE")),
          cc_: cc_);
      }
      finally
      {
        frm.Dispose();
      }
    }
コード例 #5
0
ファイル: GenericChess.cs プロジェクト: ColinSuess/ChessVFork
        // *** CONSTRUCTION *** //

        #region Constructor
        public GenericChess
            (int nFiles,                            // number of files on the board
            int nRanks,                             // number of ranks on the board
            Symmetry symmetry) :                    // symmetry determining board mirroring/rotation
            base(2, nFiles, nRanks, symmetry)
        {
        }
コード例 #6
0
 public void SetSymmetries(Symmetry symmetries, bool value)
 {
     if ((symmetries & Symmetry.ClockwiseNinety) != 0)
     {
         ClockwiseNinety = value;
     }
     if ((symmetries & Symmetry.ClockwiseOneEighty) != 0)
     {
         ClockwiseOneEighty = value;
     }
     if ((symmetries & Symmetry.ClockwiseTwoSeventy) != 0)
     {
         ClockwiseTwoSeventy = value;
     }
     if ((symmetries & Symmetry.FlipAcrossBottomLeftToTopRight) != 0)
     {
         FlipAcrossBottomLeftToTopRight = value;
     }
     if ((symmetries & Symmetry.FlipAcrossHorizontal) != 0)
     {
         FlipAcrossHorizontal = value;
     }
     if ((symmetries & Symmetry.FlipAcrossTopRightToBottomRight) != 0)
     {
         FlipAcrossTopLeftToBottomRight = value;
     }
     if ((symmetries & Symmetry.FlipAcrossVertical) != 0)
     {
         FlipAcrossVertical = value;
     }
     if ((symmetries & Symmetry.Identity) != 0)
     {
         Identity = value;
     }
 }
コード例 #7
0
        private List <Vector2> GenerateSymmetry(List <Vector2> vertices, Symmetry symmetry, float pivot, bool avoidDuplicates = true)
        {
            var symmetricVertices = new List <Vector2>();

            switch (symmetry)
            {
            case Symmetry.Vertical:
                var initialX = vertices[vertices.Count - 1];

                for (var i = vertices.Count - 2; i >= 0; i--)
                {
                    var position = vertices[i];

                    // We want to avoid duplicates
                    if (avoidDuplicates && Math.Abs(position.X - initialX.X) < 0f)
                    {
                        continue;
                    }

                    position.X = (pivot * 2) - position.X;
                    symmetricVertices.Add(position);
                }
                break;

            case Symmetry.Horizontal:
                // TODO: Horizontal symmetry
                break;
            }

            return(symmetricVertices);
        }
コード例 #8
0
        public void PaintPart(IPartScript part, bool flag, int MaterialLevel, int MaterialID, bool paintSymmetricParts)
        {
            if (MaterialLevel == -1)
            {
                for (int i = 0; i < part.Data.MaterialIds.Count; i++)
                {
                    if (part.Data.MaterialIds[i] != MaterialID)
                    {
                        part.PartMaterialScript.SetMaterial(MaterialID, i); flag = true;
                    }
                }
            }
            else if (part.Data.MaterialIds[MaterialLevel] != MaterialID)
            {
                part.PartMaterialScript.SetMaterial(MaterialID, MaterialLevel); flag = true;
            }

            if (paintSymmetricParts)
            {
                foreach (IPartScript item in Symmetry.EnumerateSymmetricPartScripts(part))
                {
                    PaintPart(item, flag, MaterialLevel, MaterialID, false);
                }
            }

            if (flag)
            {
                foreach (PartModifierData modifier in part.Data.Modifiers)
                {
                    ((IDesignerPartModifierData)modifier).DesignerPartProperties.OnPartMaterialsChanged();
                }
            }
        }
コード例 #9
0
ファイル: Generic10x9.cs プロジェクト: ColinSuess/ChessVFork
        // *** CONSTRUCTION *** //

        public Generic10x9
            (Symmetry symmetry) :
            base
                (/* num files = */ 10,
                /* symmetry = */ symmetry)
        {
        }
コード例 #10
0
        // *** CONSTRUCTION *** //

        public Generic9x8
            (Symmetry symmetry) :
            base
                (/* num files = */ 9,
                /* symmetry = */ symmetry)
        {
        }
コード例 #11
0
ファイル: Generic11x8.cs プロジェクト: ColinSuess/ChessVFork
        // *** CONSTRUCTION *** //

        public Generic11x8
            (Symmetry symmetry) :
            base
                (/* num files = */ 11,
                /* symmetry = */ symmetry)
        {
        }
コード例 #12
0
 private static IEnumerable <IntVector3[]> FaceSymmetryGroup(string symmetryType, params IntVector3[] vertexKeys)
 {
     foreach (Symmetry symmetry in Symmetry.SymmetryGroup(symmetryType))
     {
         yield return(symmetry.Apply(vertexKeys));
     }
 }
コード例 #13
0
ファイル: Generic12x12.cs プロジェクト: ColinSuess/ChessVFork
        // *** CONSTRUCTION *** //

        public Generic12x12
            (Symmetry symmetry) :
            base
                (/* num files = */ 12,
                /* symmetry = */ symmetry)
        {
        }
コード例 #14
0
ファイル: BbgLists.cs プロジェクト: heimanhon/researchwork
    public async Task UpdateList(IList<SeriesConfig> list_, Symmetry.Carbon.Client.ICarbonClient client_)
    {
      // deliberately blank!

      // this provider will not be used to populate anything in the 'main' / 'shared' derived series tree, but will
      // be used to extract series from bloomberg for the lists they are set up by the user directly

    }
コード例 #15
0
ファイル: OmegaChess.cs プロジェクト: ColinSuess/ChessVFork
        // *** INITIALIZATION *** //

        #region CreateBoard
        public override Board CreateBoard(int nPlayers, int nFiles, int nRanks, Symmetry symmetry)
        {
            Board board = new Board(12, 12);

            board.SetFileNotation(new char[] { ' ', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', ' ' });
            board.SetRankNotation(new string[] { " ", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", " " });
            return(board);
        }
コード例 #16
0
 public PsyiaControllerSettings(PsyiaControllerSettings copyTarget)
 {
     ControllerSymmetry    = copyTarget.ControllerSymmetry;
     ControllerModels      = copyTarget.ControllerModels;
     ControllerDistance    = copyTarget.ControllerDistance;
     ControllerDistanceVis = copyTarget.ControllerDistanceVis;
     ControllerHaptics     = copyTarget.ControllerHaptics;
 }
コード例 #17
0
 private void Updates()
 {
     Symmetry.SynchronizePartModifiers(Script.PartScript);
     materialShellListMaking();
     UpdateValue();
     Script.UpdateTank();
     Script.PartScript.CraftScript.RaiseDesignerCraftStructureChangedEvent();
 }
コード例 #18
0
        void OnMultiplicityChanged()
        {
            Symmetry Sym = new Symmetry(Value);

            Sym.Multiplicity = (int)Multiplicity;

            Value = Sym.ToString();
        }
コード例 #19
0
    public InvoiceSpreadLine(DateTime date_, FutureBondLookup.BondFutureConversion contractBondSpecifics,
      Symmetry.Data.Enums.KnownCurve curve_)
    {
      Date = date_;

      if (contractBondSpecifics == null) return;

      {
        ContractTicker = contractBondSpecifics.ContractTicker;
        ContractDelivery = contractBondSpecifics.DeliveryDate;
        ConversionFactor = contractBondSpecifics.ConversionFactor;
        FutureSettlePrice = contractBondSpecifics.FuturePrices.ValueOnExactDate(Date);
      }

      if (contractBondSpecifics.Bond == null) return;

      CTDBond = contractBondSpecifics.Bond.DisplayName;


      {
        ConvertedBondPrice = FutureSettlePrice*ConversionFactor;
      }

      if (FutureSettlePrice == 0d) return;


      {
        BondYield = BondSpreadRetriever.GetSpreads(
          bondType_:
            OTBondHelper.InferOTBondFromIsin(contractBondSpecifics.Bond.SymmetryCode,
              contractBondSpecifics.Bond.Maturity.Value),
          curveType_: CurveMappings.GetMapping(curve_).SwapCurve,
          maturity_: DateConversions.ToNodaLocalDate(contractBondSpecifics.Bond.Maturity.Value),
          issueDate_: DateConversions.ToNodaLocalDate(contractBondSpecifics.Bond.IssueDate.Value),
          firstCouponDate_: DateConversions.ToNodaLocalDate(contractBondSpecifics.Bond.IssueDate.Value),
          priceValue_: ConvertedBondPrice.Value/100d,
          priceType_: Symmetry.Data.Enums.QuoteValueType.Price,
          asOf_: Date,
          client_: CarbonDataSource.GetPersistedInstance(),
          coupon_: contractBondSpecifics.Bond.Coupon/100d
          ).Spreads.Yield;
      }

      var p = CurvePointCalculator.CalculateMMS(
        curve_: curve_,
        valueDAte_: Date.AddHours(23),
        startDate_: ContractDelivery.Value,
        endDate_: contractBondSpecifics.Bond.Maturity.Value,
        client_: CarbonDataSource.GetPersistedInstance());

      if (p == null)
        return;

      SwapYield = p.Price;

      InvoiceSpread = 10000d*(SwapYield - BondYield);
    }
コード例 #20
0
        void OnValueChanged()
        {
            Symmetry Sym = new Symmetry(Value);

            Multiplicity = Sym.Multiplicity;
            ComboGroups.SelectedIndex = (int)Sym.Type;

            ValueChanged?.Invoke(this, new DependencyPropertyChangedEventArgs(ValueProperty, Value, Value));
        }
コード例 #21
0
 /// <summary>
 /// Called when the part modifier data is initialized in the designer scene.
 /// </summary>
 /// <param name="d">The designer part properties.</param>
 protected override void OnDesignerInitialization(IDesignerPartPropertiesModifierInterface d)
 {
     base.OnDesignerInitialization(d);
     d.OnActivated(() => Symmetry.ExecuteOnSymmetricPartModifiers(this, true, x => x.PropertiesOpen   = true));
     d.OnDeactivated(() => Symmetry.ExecuteOnSymmetricPartModifiers(this, true, x => x.PropertiesOpen = false));
     d.OnPropertyChanged(() => this.emissionAngle, (x, y) => { Symmetry.SynchronizePartModifiers(this.Part.PartScript); Symmetry.ExecuteOnSymmetricPartModifiers(this, true, (z) => z.Script?.SetEmissionAngle(x)); });
     d.OnPropertyChanged(() => this.emissionRate, (x, y) => { Symmetry.SynchronizePartModifiers(this.Part.PartScript); Symmetry.ExecuteOnSymmetricPartModifiers(this, true, (z) => z.Script?.SetEmissionRate(x)); });
     d.OnPropertyChanged(() => this.emissionVelocity, (x, y) => { Symmetry.SynchronizePartModifiers(this.Part.PartScript); Symmetry.ExecuteOnSymmetricPartModifiers(this, true, (z) => z.Script?.SetEmissionVelocity(x)); });
 }
コード例 #22
0
    public static OTBond GetBond(Symmetry.Data.FIBond bond_)
    {
      if (bond_.Market == null)
        throw new Exception(string.Format("Market not set on bond {0} so cannot determine suitable OTBond number"));

      OTBond otBond;

      switch (bond_.Market)
      {
        case "UST":
        case "T":
        case "USTSTR":
          otBond = bond_.FI.Maturity.Value.Day > 25 ? OTBond.US_EOM : OTBond.US_MID;
          break;
        case "BKO":
        case "DBR":
        case "OBL":
          otBond = OTBond.Germany;
          break;
        case "FRTR":
          otBond = OTBond.France;
          break;
        case "BTPS":
          otBond = OTBond.Italy;
          break;
        case "SPGB":
          otBond = OTBond.Spain;
          break;
        case "UKT":
          otBond = OTBond.UK;
          break;
        case "NETHER":
          otBond = OTBond.Netherlands;
          break;
        case "BGB":
          otBond = OTBond.Belgium;
          break;
        case "PGB":
        case "PORTB":
          otBond = OTBond.Portugal;
          break;
        case "IRISH":
        case "IRTB":
          otBond = OTBond.Ireland;
          break;
        case "JGB":
          otBond = OTBond.Japan;
           break;
        case "CAN":
          otBond = OTBond.Canada;
          break;
        default:
          throw new Exception("Unable to calculate OT bond type for unknown market " + bond_.Market);
      }
      return otBond;
    }
コード例 #23
0
        protected virtual void MakeSymBoundary(string bn)
        {
            Boundary sym = new Symmetry(bn);

            U.BoundaryField.AddBoundary(sym);
            p.BoundaryField.AddBoundary(sym);
            k.BoundaryField.AddBoundary(sym);
            epsilon.BoundaryField.AddBoundary(sym);
            nut.BoundaryField.AddBoundary(sym);
        }
コード例 #24
0
        /// <summary>
        /// Create a maze gen rotator with the given symmetries enabled.
        /// </summary>
        public static MazeGenRotator GetRotator(Symmetry symmetries)
        {
            if (symmetries == Symmetry.None)
            {
                throw new System.ArgumentException("Rotator must have at least one symmetry enabled.");
            }

            var rotator = CreateInstance <MazeGenRotator>();

            rotator.SetSymmetries(symmetries, true);
            return(rotator);
        }
コード例 #25
0
 /*
  *      public void UpdateScale()
  *      {
  *          base.Script.UpdateScale();
  *      }
  */
 protected override void OnDesignerInitialization(IDesignerPartPropertiesModifierInterface d)
 {
     d.OnValueLabelRequested(() => _length, (float x) => x.ToString("0.00") + "m");
     d.OnValueLabelRequested(() => _force, (float x) => Units.GetForceString(x));
     d.OnValueLabelRequested(() => _acceleration, (float x) => Units.GetAccelerationString(x));
     d.OnValueLabelRequested(() => _velocity, (float x) => Units.GetVelocityString(x));
     d.OnPropertyChanged(() => _length, (x, y) =>
     {
         Symmetry.SynchronizePartModifiers(base.Part.PartScript);
         base.Part.PartScript.CraftScript.RaiseDesignerCraftStructureChangedEvent();
     });
 }
コード例 #26
0
        /*
         * Flipping vectors for symmetry
         * */
        private static Vector3 Symmetrize(Vector3 v, Symmetry symmetry)
        {
            switch (symmetry)
            {
            case Symmetry.X: return(new Vector3(-v.x, v.y, v.z));

            case Symmetry.Y: return(new Vector3(v.x, -v.y, v.z));

            case Symmetry.Z: return(new Vector3(v.x, v.y, -v.z));

            default: return(v);
            }
        }
コード例 #27
0
 public static BondSpreadResult GetSpreads(Symmetry.Data.FIBond bond_, QuoteValueType priceType_, double priceValue_, SwapCurveType curveType_, DateTime asOf_, CarbonClient client_, ThrowBehavior behavior_ = ThrowBehavior.DontThrow)
 {
   return GetSpreads(
     bondType_: OTBondHelper.GetBond(bond_),
     maturity_:bond_.FI.Maturity.Value.ToNodaLocalDate(),
     issueDate_:bond_.IssueDate.Value.ToNodaLocalDate(),
     firstCouponDate_: bond_.Coupon==0 ? bond_.IssueDate.Value.ToNodaLocalDate() : bond_.FirstCouponDate.Value.ToNodaLocalDate(),
     priceType_:priceType_,
     priceValue_:priceValue_,
     coupon_: Convert.ToDouble(bond_.Coupon)/100d,
     pricingSetup_: CurveMappings.GetMapping(curveType_),
     asOf_: asOf_,
     client_: client_,
     behavior_: behavior_);
 }
コード例 #28
0
    public override async Task OnClick(BaseTreeNode node_, Symmetry.Carbon.Client.ICarbonClient cc_)
    {
      var leaf = node_ as TreeNode_Leaf;

      var series = await SeriesList.Instance.Retrieve(leaf.Config, cc_);

      if (series != null && series.Series != null)
      {
        var chart = new PeriodLineChart.PeriodLineChart();
        chart.Create();
        chart.SetValues(series, PeriodLineChart.TimePeriod.YearOne);
        chart.DisplayInShowForm(node_.Text);
      }
      
    }
コード例 #29
0
 private void Update()
 {
 #if UNITY_EDITOR
     if (_symmetry != _lastSymmetry)
     {
         _lastSymmetry = _symmetry;
         DoSymmetry(_h1, ref _h2, ref _dirty2);
     }
 #endif
     if (transform.hasChanged)
     {
         _dirty1 = _dirty2 = true;
         transform.hasChanged = false;
         parent.dirty         = true;
     }
 }
コード例 #30
0
        private void DeselectAllParts()
        {
            if (_selectedParts.Count > 0)
            {
                foreach (IPartScript part in _selectedParts)
                {
                    _partHighlighter.RemovePartHighlight(part);
                    foreach (IPartScript SymmetricPart in Symmetry.EnumerateSymmetricPartScripts(part))
                    {
                        _partHighlighter.RemovePartHighlight(SymmetricPart);
                    }
                }

                _selectedParts = new List <IPartScript> ();
                Debug.Log("Deselected All Parts ");
            }
        }
コード例 #31
0
        private void ComboGroups_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            SymmetryTypes SymType = Symmetry.ParseType((string)ComboGroups.SelectedItem);

            SliderMultiplicity.Visibility = Symmetry.HasMultiplicity(SymType) ? Visibility.Visible : Visibility.Collapsed;
            if (SymType == SymmetryTypes.In || SymType == SymmetryTypes.InH)
            {
                SliderMultiplicity.MaxValue = 5;
                Multiplicity = Math.Min(5, Multiplicity);
            }
            else
            {
                SliderMultiplicity.MaxValue = 99;
            }

            Value = new Symmetry(SymType, (int)Multiplicity).ToString();
        }
コード例 #32
0
    private static RenderGeometry CreateCubeGeometryInternal(Vector3 size, Func <int, SurfaceComponentGeometry> surfaceGenerator)
    {
        StructureGeometry structure = new StructureGeometry();

        var corners = new Dictionary <IntVector3, Vertex>();

        foreach (var keyAndPosition in VertexSymmetryGroup("111", Key(1, 1, 1), Vector3.one))
        {
            corners[keyAndPosition.Key] = structure.CreateVertex(keyAndPosition.Value.Times(size / 2));
        }
        foreach (Symmetry symmetry in Symmetry.SymmetryGroup("100"))
        {
            Vertex[] verts = symmetry.Apply(Key(1, -1, -1), Key(1, 1, -1), Key(1, 1, 1), Key(1, -1, 1)).Select(key => corners[key]).ToArray();
            structure.CreateFace(surfaceGenerator.Invoke(symmetry.rotation), true, verts);
        }
        return(structure.Build());
    }
コード例 #33
0
    public void CreateSymObject()
    {
        creating = true;
        GameObject symGO = new GameObject();

        symGO.name             = name + " Symmetry";
        symGO.transform.parent = transform.parent;
        transform.parent       = symGO.transform;

        Symmetry sym = symGO.AddComponent <Symmetry>();

        sym.a = transform;
        DestroyImmediate(this);

#if UNITY_EDITOR
        UnityEditor.Selection.activeObject = symGO;
#endif
    }
コード例 #34
0
        internal double[,] CalculateVscomeValue()
        {
            double symmetryValue = 0;
            double vorivValue    = 0;

            double[,] vscome = new double[orientationField.GetLength(0), orientationField.GetLength(1)];

            for (int u = 0; u < orientationField.GetLength(0); u++)
            {
                for (int v = 0; v < orientationField.GetLength(1); v++)
                {
                    symmetryValue = Symmetry.CalculateSymmetry(u, v, orientationField.GetLength(0) * orientationField.GetLength(1), filteredField);
                    vorivValue    = VORIV.CalculateVoriv(u, v, orientationField);
                    vscome[u, v]  = (vorivValue + symmetryValue) / 2;
                }
            }

            return(vscome);
        }
コード例 #35
0
        /// <summary>
        /// Returns the number of possible distinct orientations for a tile.
        /// <para>An orientation is a combination of rotations and reflections.</para>
        /// </summary>
        /// <param name="symmetry"></param>
        /// <returns></returns>
        public static uint NumberOfPossibleOrientations(Symmetry symmetry)
        {
            switch (symmetry)
            {
            case Symmetry.X:
                return(1);

            case Symmetry.I:
            case Symmetry.Backslash:
                return(2);

            case Symmetry.T:
            case Symmetry.L:
                return(4);

            default:
                return(8);
            }
        }
コード例 #36
0
        private void UpdatePartHighlight()
        {
            if (_SelectedParts.Count > 0)
            {
                _PartHighlighter.HighlightColor = new Color(0f, 1f, 0f, 1f);

                foreach (IPartScript part in _SelectedParts)
                {
                    _PartHighlighter.AddPartHighlight(part);
                    foreach (IPartScript SymmetricPart in Symmetry.EnumerateSymmetricPartScripts(part))
                    {
                        _PartHighlighter.AddPartHighlight(SymmetricPart);
                    }
                }
            }
            else
            {
                _PartHighlighter.HighlightColor = _Designer.CraftScript.RootPart.Data.ThemeData.Theme.PartStateColors.Highlighted;
            }
        }
コード例 #37
0
 public async Task<TimeSeries.SeriesExtractResult> GetSelectedSeries(Symmetry.Carbon.Client.ICarbonClient cc_)
 {
   return await m_retriever.GetSeries();
 }
コード例 #38
0
    public static void GetFutureQuotesFromBloomberg (
      Symmetry.Data.Enums.InstrumentType instrumentType_,
      DateTime valueDate_,
      Symmetry.Data.Enums.QuoteValueType priceType_ = Symmetry.Data.Enums.QuoteValueType.Price,
      string targetMarketSnap_ = "CLOSE",
      string targetQuoteSource_ = "SYM",
      string bbgField_="PX_SETTLE",
      Func<FI, bool> shouldInclude_ = null,
      bool checkDataBase_=true
  )
    {
      try
      {
        var dc = SymmetryDataSource.ReadWrite();
        if(checkDataBase_) checkDatabase(dc);

        var targetQS = QuoteHelpers.GetQuoteSource(targetQuoteSource_, dc);
        var targetMS = QuoteHelpers.GetOrCreateMarketSnap(targetMarketSnap_, valueDate_, dc);

        foreach (var fi in dc.FIs.Where(x => x.InstrumentType == instrumentType_).ToArray())
        {
          if (shouldInclude_ != null && shouldInclude_(fi) == false)
            continue;

          var hist = BbgTalk.HistoryRequester.GetHistory(valueDate_, fi.SymmetryCode, bbgField_, false);

          if (hist == null || !hist.HasDate(valueDate_))
          {
            Logger.Error(
              string.Format("Could not pull value for {0} from bloomberg for date {1}", fi.SymmetryCode, valueDate_),
              typeof (SymmetryTSCopyQuote));
            continue;
          }

          var sourceValue = hist.ValueOnExactDate(valueDate_);
          
          {
            Logger.Info(string.Format("{0} {1} Bbg => {2}.{3}  Value={4}",
              valueDate_.ToString("dd-MMM-yyyy"),
              fi.SymmetryCode,
              targetQuoteSource_,
              targetMarketSnap_,
              sourceValue
              ), typeof(SymmetryTSCopyQuote));

            QuoteHelpers.SaveQuote(targetMS, targetQS.QuoteSourceID, fi.FIID, priceType_, Convert.ToDecimal(sourceValue),
              DateTime.Now, dc, ThrowBehavior.DontThrow, true);
          }
        }

        dc.SaveChanges();
      }
      catch (Exception ex_)
      {
        Logger.Error("Error copying quotes", typeof(TEst), ex_);
      }
    }
コード例 #39
0
    public static void CopyQuotes(
      Symmetry.Data.Enums.InstrumentType instrumentType_,
      DateTime valueDate_,
      Symmetry.Data.Enums.QuoteValueType priceType_ = Symmetry.Data.Enums.QuoteValueType.Price,
      string sourceMarketSnap_ = "MLP",
      string sourceQuoteSource_ = "MLP",
      string targetMarketSnap_ = "CLOSE",
      string targetQuoteSource_ = "SYM",
      Func<FI,bool> shouldInclude_ =null,
      bool checkDataBase_=true
      )
    {
      try
      {
        var dc = SymmetryDataSource.ReadWrite();
        if(checkDataBase_) checkDatabase(dc);

        var sourceQS = QuoteHelpers.GetQuoteSource(sourceQuoteSource_, dc);
        var sourceMS = QuoteHelpers.GetMarketSnap(sourceMarketSnap_, valueDate_, dc);

        var targetQS = QuoteHelpers.GetQuoteSource(targetQuoteSource_, dc);
        var targetMS = QuoteHelpers.GetOrCreateMarketSnap(targetMarketSnap_, valueDate_, dc);

        foreach (var fi in dc.FIs.Where(x => x.InstrumentType == instrumentType_).ToArray())
        {
          if (shouldInclude_ != null && shouldInclude_(fi) == false)
            continue;

          var sourceValue = QuoteHelpers.GetQuoteValue(sourceMS.MarketSnapID, sourceQS.QuoteSourceID, fi.FIID,
            priceType_, dc, ThrowBehavior.DontThrow);


          if (sourceValue.HasValue)
          {
            Logger.Info(string.Format("{6} {0} {1}.{2} => {3}.{4}  Value={5}",
              fi.SymmetryCode,
              sourceQuoteSource_,
              sourceMarketSnap_,
              targetQuoteSource_,
              targetMarketSnap_,
              sourceValue.Value,
              valueDate_.ToString("dd-MMM-yyyy")), typeof (SymmetryTSCopyQuote));

            QuoteHelpers.SaveQuote(targetMS, targetQS.QuoteSourceID, fi.FIID, priceType_, sourceValue.Value,
              DateTime.Now, dc, ThrowBehavior.DontThrow, true);
          }
        }

        dc.SaveChanges();
      }
      catch (Exception ex_)
      {
        Logger.Error("Error copying quotes", typeof(TEst), ex_);
      }
    }
コード例 #40
0
    public static List<InvoiceSpreadLine> GetInvoiceSpreadsLines(string futureStart_, Symmetry.Data.Enums.KnownCurve curve_, int contractOffset_ = 0)
    {
      Logger.Debug(
        string.Format("Starting to generate invoice spreads for future={0}, curve={1}, offset={2}", futureStart_, curve_,
          contractOffset_), typeof(Generator));

      var returnList = new List<InvoiceSpreadLine>();

      var startDate = new DateTime(2010, 6, 1);

      var contractList = GetList(futureStart_: futureStart_);

      while (startDate < DateTime.Today)
      {
        var subList = contractList.Where(x => x.LastTrade >= startDate).ToArray();

        if (subList.Length == 0)
        {
          Logger.Error(string.Format("No contract found for date={0}", startDate.ToString("dd-MMM-yyyy")),
            typeof(Generator));
          continue;
        }

        var item = new InvoiceSpreadLine(
          date_: startDate,
          contractBondSpecifics: subList[contractOffset_],
          curve_: curve_);

        returnList.Add(item);

        startDate = MyCalendar.NextWeekDay(startDate);
      }

      return returnList;
    }
コード例 #41
0
 public async Task<DatedDataCollectionGen<double>> Extract(SeriesConfig line_, Symmetry.Carbon.Client.ICarbonClient cc_, bool forceRefresh_ = false)
 {
   var tickerAndField = GetTickerAndFieldFromConfig(line_);
   return BbgTalk.HistoryRequester.GetHistory(new DateTime(2000, 1, 1), tickerAndField.Item1, tickerAndField.Item2,
     BbgTalk.RefreshOption.RefreshIfOlderThanToday);
 }
コード例 #42
0
 public static Mapping GetMapping(Symmetry.Data.Enums.KnownCurve curve_)
 {
   return _mappings.First(x => x.ForecastCurve == curve_);
 }
コード例 #43
0
 public static Mapping GetMapping(Symmetry.Data.Enums.SwapCurveType swapCurveType_)
 {
   return _mappings.First(x => x.SwapCurve == swapCurveType_);
 }
 /*
  * Flipping vectors for symmetry
  * */
 private static Vector3 Symmetrize(Vector3 v, Symmetry symmetry)
 {
     switch(symmetry) {
     case Symmetry.X: return new Vector3(-v.x, v.y, v.z);
     case Symmetry.Y: return new Vector3(v.x, -v.y, v.z);
     case Symmetry.Z: return new Vector3(v.x, v.y, -v.z);
     default: return v;
     }
 }
        public void OnSceneGUI()
        {
            GUI.changed = false;

            // Set defaultLocalRotation so that the initial local rotation will be the zero point for the rotation limit
            if (!Application.isPlaying) script.defaultLocalRotation = script.transform.localRotation;
            if (script.axis == Vector3.zero) return;

            // Quick Editing Tools
            Handles.BeginGUI();
            GUILayout.BeginArea(new Rect(10, UnityEngine.Screen.height - 180, 550, 130), "Rotation Limit Polygonal", "Window");

            // Cloning values from another RotationLimitPolygonal
            EditorGUILayout.BeginHorizontal();
            if (Inspector.Button("Clone From", "Make this rotation limit identical to another", script, GUILayout.Width(220))) CloneLimit();
            clone = (RotationLimitPolygonal)EditorGUILayout.ObjectField("", clone, typeof(RotationLimitPolygonal), true);
            EditorGUILayout.EndHorizontal();

            // Symmetry
            symmetry = (Symmetry)EditorGUILayout.EnumPopup("Symmetry", symmetry, GUILayout.Width(220));

            // Flipping
            EditorGUILayout.BeginHorizontal();
            if (Inspector.Button("Flip X", "Flip points along local X axis", script, GUILayout.Width(100))) FlipLimit(0);
            if (Inspector.Button("Flip Y", "Flip points along local Y axis", script, GUILayout.Width(100))) FlipLimit(1);
            if (Inspector.Button("Flip Z", "Flip points along local Z axis", script, GUILayout.Width(100))) FlipLimit(2);
            GUILayout.Label("Flip everything along axis");
            EditorGUILayout.EndHorizontal();

            // Rotating
            EditorGUILayout.BeginHorizontal();
            if (Inspector.Button("Rotate X", "Rotate points along X axis by Degrees", script, GUILayout.Width(100))) RotatePoints(degrees, Vector3.right);
            if (Inspector.Button("Rotate Y", "Rotate points along Y axis by Degrees", script, GUILayout.Width(100))) RotatePoints(degrees, Vector3.up);
            if (Inspector.Button("Rotate Z", "Rotate points along Z axis by Degrees", script, GUILayout.Width(100))) RotatePoints(degrees, Vector3.forward);

            degrees = EditorGUILayout.FloatField("Degrees", degrees, GUILayout.Width(200));
            EditorGUILayout.EndHorizontal();

            // Smooth/Optimize
            EditorGUILayout.BeginHorizontal();
            if (Inspector.Button("Smooth", "Double the points", script)) Smooth();
            if (Inspector.Button("Optimize", "Delete every second point", script)) Optimize();
            EditorGUILayout.EndHorizontal();

            GUILayout.EndArea();
            Handles.EndGUI();

            // Rebuild reach cones
            script.BuildReachCones();

            // Draw a white transparent sphere
            DrawRotationSphere(script.transform.position);

            // Draw Axis
            DrawArrow(script.transform.position, Direction(script.axis), colorDefault, "Axis", 0.02f);

            // Display limit points
            for (int i = 0; i < script.points.Length; i++) {
                Color color = GetColor(i); // Paint the point in green or red if it belongs to an invalid reach cone

                Handles.color = color;
                GUI.color = color;

                // Line from the center to the point and the label
                Handles.DrawLine(script.transform.position, script.transform.position + Direction(script.points[i].point));
                Handles.Label(script.transform.position + Direction(script.points[i].point + new Vector3(-0.02f, 0, 0)), " " + i.ToString());

                // Selecting points
                Handles.color = colorHandles;
                if (Handles.Button(script.transform.position + Direction(script.points[i].point), script.transform.rotation, 0.02f, 0.02f, Handles.DotCap)) {
                    selectedPoint = i;
                }

                Handles.color = Color.white;
                GUI.color = Color.white;

                // Limit point GUI
                if (i == selectedPoint) {
                    Handles.BeginGUI();

                    GUILayout.BeginArea(new Rect(UnityEngine.Screen.width - 240, UnityEngine.Screen.height - 180, 230, 130), "Limit Point " + i.ToString(), "Window");

                    if (Inspector.Button("Delete", "Delete this point", script)) {
                        if (script.points.Length > 3) {
                            // Using the deletePoint index here because we dont want to delete points from the array that we are iterating
                            deletePoint = i;
                        } else if (!Warning.logged) script.LogWarning("Polygonal Rotation Limit should have at least 3 limit points");
                    }
                    if (Inspector.Button("Add Point", "Add a new point next to this one", script)) {
                        addPoint = i;
                    }

                    // Store point for undo
                    Vector3 oldPoint = script.points[i].point;

                    // Manual input for the point position
                    Inspector.AddVector3(ref script.points[i].point, "Point", script, GUILayout.Width(210));

                    EditorGUILayout.Space();

                    // Tangent weight
                    Inspector.AddFloat(ref script.points[i].tangentWeight, "Tangent Weight", "Weight of this point's tangent. Used in smoothing.", script, -Mathf.Infinity, Mathf.Infinity, GUILayout.Width(150));

                    GUILayout.EndArea();

                    Handles.EndGUI();

                    // Moving Points
                    Vector3 pointWorld = Handles.PositionHandle(script.transform.position + Direction(script.points[i].point), Quaternion.identity);
                    Vector3 newPoint = InverseDirection(pointWorld - script.transform.position);
                    if (newPoint != script.points[i].point) {
                        if (!Application.isPlaying) Undo.RecordObject(script, "Move Limit Point");
                        script.points[i].point = newPoint;
                    }

                    // Symmetry
                    if (symmetry != Symmetry.Off && script.points.Length > 3 && oldPoint != script.points[i].point) {
                        RotationLimitPolygonal.LimitPoint symmetryPoint = GetClosestPoint(Symmetrize(oldPoint, symmetry));
                        if (symmetryPoint != script.points[i]) {
                            symmetryPoint.point = Symmetrize(script.points[i].point, symmetry);
                        }
                    }
                }

                // Normalize the point
                script.points[i].point = script.points[i].point.normalized;
            }

            // Display smoothed polygon
            for (int i = 0; i < script.P.Length; i++) {
                Color color = GetColor(i);

                // Smoothed triangles are transparent
                Handles.color = new Color(color.r, color.g, color.b, 0.25f);
                Handles.DrawLine(script.transform.position, script.transform.position + Direction(script.P[i]));

                Handles.color = color;

                if (i < script.P.Length - 1) Handles.DrawLine(script.transform.position + Direction(script.P[i]), script.transform.position + Direction(script.P[i + 1]));
                else Handles.DrawLine(script.transform.position + Direction(script.P[i]), script.transform.position + Direction(script.P[0]));

                Handles.color = Color.white;
            }

            // Deleting points
            if (deletePoint != -1) {
                DeletePoint(deletePoint);
                selectedPoint = -1;
                deletePoint = -1;
            }

            // Adding points
            if (addPoint != -1) {
                AddPoint(addPoint);
                addPoint = -1;
            }

            if (GUI.changed) EditorUtility.SetDirty(script);
        }
コード例 #46
0
    /// <summary>
    /// Calculate the bondspreads for the given bond over the given swap curve
    /// </summary>
    /// <param name="bond_"></param>
    /// <param name="priceType_">either yield or price</param>
    /// <param name="priceValue_">if price, then pass 100.3 rather than 1.003</param>
    /// <param name="curveType_">the swap curve</param>
    /// <param name="country_">JB's country definitions</param>
    /// <param name="asOf_">the date of the price. will determine the date of the curves that are used</param>
    /// <param name="client_">carbon client to get holidays</param>
    /// <param name="quoteSource_">mlp/sym</param>
    /// <param name="snapCode_">mlp/nyk/ldn</param>
    /// <param name="behavior_">whether you want exceptions to be swallowed or not</param>
    /// <returns></returns>
    public static async Task<BondSpreadResult> GetSpreads(
      Symmetry.Data.FIBond bond_, 
      QuoteValueType priceType_, 
      double priceValue_, 
      SwapCurveType curveType_,
      BondAnalytics.Country country_,
      DateTime asOf_, 
      CarbonClient client_,
      string quoteSource_,
      string snapCode_,
      ThrowBehavior behavior_ = ThrowBehavior.DontThrow)
    {
      try
      {
        var mapping = CurveMappings.GetMapping(curveType_);

        var settleDate = await client_.RollDateAsync(
          date: asOf_.Date.ToNodaLocalDate(),
          count: country_.SettleDateDays(),
          unit: DateUnit.Bd,
          convention: BusinessDayConvention.Following,
          calendar: country_.OTHolidayCode());

        var holidays = CalendarRetriever.GetCalendar(country_.OTHolidayCode(), client_).ToList();

        var startDate = bond_.EffectiveDate.Value;

        var firstCpnDate = bond_.Coupon==0 ? bond_.IssueDate.Value : bond_.FirstCouponDate.Value;

        var maturity = bond_.FI.Maturity;

        var coupon = Convert.ToDouble(bond_.Coupon);

        // get the persisted discount curves for the fixed and floating legs
        var discCurve = SObjectManager.Instance().LoadSObject<DiscountCurve>(new Moniker()
        {
          Close = snapCode_,
          Source = quoteSource_,
          Name = KnownCurveHelpers.GetKnownCurveCode(mapping.DiscountCurve),
          Type = "discountcurve",
          Date = asOf_.Date
        });

        if (discCurve == null)
        {
          SLog.log.ErrorFormat("Could not load {0} discount curve from database for {1}", mapping.DiscountCurve, asOf_.Date);
          return null;
        }

        var fcstCurve = SObjectManager.Instance().LoadSObject<DiscountCurve>(new Moniker()
        {
          Close = snapCode_,
          Source = quoteSource_,
          Name = KnownCurveHelpers.GetKnownCurveCode(mapping.ForecastCurve),
          Type = "discountcurve",
          Date = asOf_.Date
        });

        if (fcstCurve == null)
        {
          SLog.log.ErrorFormat("Could not load {0} discount curve from database for {1}", mapping.ForecastCurve, asOf_.Date);
          return null;
        }

        double price=0, yield=0;

        switch (priceType_)
        {
          case QuoteValueType.Price:
            price = priceValue_;

            yield = BondAnalytics.SolveYield(
              country: country_,
              settleDate: settleDate.ToDateTime(),
              cleanPrice: price,
              startDate: startDate,
              firstCpnDate: firstCpnDate,
              maturityDate: maturity.Value,
              coupon: coupon,
              freq: country_.BondFreq())[0];

            break;
          case QuoteValueType.Yield:
            yield = priceValue_;
            price = BondAnalytics.PriceFromYield(
              country: country_,
              settleDate: settleDate.ToDateTime(),
              yield: priceValue_,
              startDate: startDate,
              firstCpnDate: firstCpnDate,
              maturityDate: maturity.Value,
              coupon: coupon,
              freq: country_.BondFreq())[0];
              break;
        }

        var mms = BondAnalytics.CalcMMS(
          startDate: settleDate.ToDateTime(),
          maturityDate: maturity.Value,
          dctType: mapping.DayCountType,
          fixedFreq: (long) mapping.FixedFreq,
          floatFreq: (long) mapping.FloatFreq,
          discCurveDates: discCurve.AsDoubleArray().SliceColumn(0).Select(DateTime.FromOADate).ToArray(),
          discDfs: discCurve.AsDoubleArray().SliceColumn(1),
          fcstCurveDates: fcstCurve.AsDoubleArray().SliceColumn(0).Select(DateTime.FromOADate).ToArray(),
          fcstDfs: fcstCurve.AsDoubleArray().SliceColumn(1),
          holidays: holidays,
          stubExpiries: null,
          stubTenors: null,
          stubValues: null,
          fixingTenors: null,
          fixings: null,
          firstCpnDate: firstCpnDate
          );

        var truespread = BondAnalytics.SolveZSpread(
          country: country_,
          settleDate: settleDate.ToDateTime(),
          cleanPrice: price,
          startDate: startDate,
          firstCpnDate: firstCpnDate,
          maturityDate: maturity.Value,
          coupon: coupon,
          freq: country_.BondFreq(),
          curveDates: fcstCurve.AsDoubleArray().SliceColumn(0).Select(DateTime.FromOADate).ToArray(),
          dfs: fcstCurve.AsDoubleArray().SliceColumn(1),
          holidays: holidays);

        return new BondSpreadResult
        {
          Price = price,
          Spreads = new BondSpread
          {
            Yield=yield,
            MMS=mms,
            TrueSpread=truespread * -1d,
            Spread = mms-yield,
          }
        };
      }
      catch (Exception ex_)
      {
        Exceptions.Rethrow("Error calculating bondspread", behavior_, ex_);
        return null;
      }
    }
コード例 #47
0
        private List<Vector2> GenerateSymmetry(List<Vector2> vertices, Symmetry symmetry, float pivot, bool avoidDuplicates = true)
        {
            var symmetricVertices = new List<Vector2>();

            switch (symmetry)
            {
                case Symmetry.Vertical:
                    var initialX = vertices[vertices.Count - 1];

                    for (var i = vertices.Count - 2; i >= 0; i--)
                    {
                        var position = vertices[i];

                        // We want to avoid duplicates
                        if (avoidDuplicates && Math.Abs(position.X - initialX.X) < 0f)
                            continue;

                        position.X = (pivot * 2) - position.X;
                        symmetricVertices.Add(position);
                    }
                    break;
                case Symmetry.Horizontal:
                    // TODO: Horizontal symmetry
                    break;
            }

            return symmetricVertices;
        }
コード例 #48
0
 public InvoiceSpreadConfig(Symmetry.Data.Enums.KnownCurve curve_, string future_, int series_)
 {
   Curve = curve_;
   Future = future_;
   Series = series_;
 }
コード例 #49
0
 public override async Task OnClick(BaseTreeNode node_, Symmetry.Carbon.Client.ICarbonClient cc_)
 {
   SeriesList.Instance.ClearCache();
   await SeriesList.Instance.GetConfigList(cc_,forceRefresh_:true);
 }