Beispiel #1
1
        private void ribbonButton49_Click(object sender, EventArgs e)
        {
            if (ellipsePrimitive == null)
            {
                GeoPoint pos = new GeoPoint();
                pos.x = 116.3;
                pos.y = 39.9;
                pos.srs = m_earthMap.getSRS();

                Linear radiusMajor = new Linear();
                radiusMajor.set( 250, UnitsType.UNIT_MILES );

                Linear radiusMinor = new Linear();
                radiusMinor.set( 100, UnitsType.UNIT_MILES );

                Angular rotationAngle = new Angular();
                rotationAngle.set( 0, UnitsType.UNIT_DEGREES );

                Angular arcStart = new Angular();
                arcStart.set( 45.0, UnitsType.UNIT_DEGREES );

                Angular arcEnd = new Angular();
                arcEnd.set( 360.0 - 45.0, UnitsType.UNIT_DEGREES );

                ellipsePrimitive = new EllipsePrimitive();
                ellipsePrimitive.setPosition( pos );
                ellipsePrimitive.setRadiusMajor( radiusMajor );
                ellipsePrimitive.setRadiusMinor(radiusMinor);
                ellipsePrimitive.setRotationAngle(rotationAngle);
                ellipsePrimitive.setArcStart(arcStart);
                ellipsePrimitive.setArcEnd(arcEnd);
                ellipsePrimitive.setPie(true);
                m_earthRoot.addChild( ellipsePrimitive);
            }
        }
Beispiel #2
1
        private void ribbonButton55_Click(object sender, EventArgs e)
        {
            if (circle == null)
            {
                GeoPoint pos = new GeoPoint();
                pos.x = 116.3;
                pos.y = 39.9;
                pos.srs = m_earthMap.getSRS();

                Linear linear = new Linear();
                linear.set( 300, UnitsType.UNIT_KILOMETERS );

                Angular angularStart = new Angular();
                angularStart.set(-45.0, UnitsType.UNIT_DEGREES);

                Angular angularEnd = new Angular();
                angularEnd.set( 45.0, UnitsType.UNIT_DEGREES );

                circle = new Circle();
                circle.setPosition( pos );
                circle.setRadius( linear );
                circle.setArcStart( angularStart );
                circle.setArcEnd( angularEnd );
                circle.setPie( true );
                m_earthRoot.addChild( circle );
            }
        }
  public void test_basic_deferred_animation()
  {
    this.TearDownAnimations();
    AnimationManager.Default.Configure(Streams.STREAM_0, AnimationStreamType.DEFER, 1);

    var blank = this.SpawnBlank();
    var anim = new MoveTo(new Vector3(1, 1, 1));
    var curve = new Linear(1f);

    var blank2 = this.SpawnBlank();
    var anim2 = new MoveTo(new Vector3(1, 1, 1));
    var curve2 = new Linear(1f);

    int events = 0;
    AnimationManager.Default.Add(Streams.STREAM_0, anim, curve, blank);
    AnimationManager.Default.Add(Streams.STREAM_0, anim2, curve2, blank2);
    AnimationManager.Default.AddEventHandler((ep) => { events += 1; });

    var timer = AnimationHandler.Default;

    // Step
    AnimationHandler.Default.Update(1.0f);
    Assert(events == 1);

    // Step
    AnimationHandler.Default.Update(1.0f);

    Assert(events == 2);

    // Teardown
    TearDownAnimations();
  }
  public void test_basic_working_animation()
  {
    this.TearDownAnimations();
    AnimationManager.Default.Configure(Streams.STREAM_0, AnimationStreamType.REJECT, 1);

    var blank = this.SpawnBlank();
    var anim = new MoveTo(new Vector3(1, 1, 1));
    var curve = new Linear(1f);

    int events = 0;
    AnimationManager.Default.Add(Streams.STREAM_0, anim, curve, blank);
    AnimationManager.Default.AddEventHandler((ep) => { events += 1; });

    // Step
    AnimationHandler.Default.Update(0.5f);
    Assert(events == 0);

    // Step
    AnimationHandler.Default.Update(0.5f);
    Assert(events == 1);

    // Teardown
    TearDownAnimations();
  }
Beispiel #5
0
        public void RunTest()
        {
            Accord.Math.Random.Generator.Seed = 0;

            // Sample data
            //   The following is a simple auto association function
            //   in which each input correspond to its own class. This
            //   problem should be easily solved using a Linear kernel.

            // Sample input data
            double[][] inputs =
            {
                new double[] { 0, 0 },
                new double[] { 0, 1 },
                new double[] { 1, 0 },
                new double[] { 1, 1 },
            };

            // Outputs for each of the inputs
            int[][] outputs =
            {
                //       and   or   nand   xor
                new[] { -1, -1, +1, +1 },
                new[] { -1, +1, +1, -1 },
                new[] { -1, +1, +1, -1 },
                new[] { +1, +1, -1, +1 },
            };

            // Create a new Linear kernel
            IKernel linear = new Linear();

            // Create a new Multi-class Support Vector Machine for one input,
            //  using the linear kernel and four disjoint classes.
            var machine = new MultilabelSupportVectorMachine(inputs: 2, kernel: linear, classes: 4);

            // Create the Multi-class learning algorithm for the machine
            var teacher = new MultilabelSupportVectorLearning(machine, inputs, outputs);

            // Configure the learning algorithm to use SMO to train the
            //  underlying SVMs in each of the binary class subproblems.
            teacher.Algorithm = (svm, classInputs, classOutputs, i, j) =>
                                new SequentialMinimalOptimization(svm, classInputs, classOutputs)
            {
                // Create a hard SVM
                Complexity = 10000.0
            };

            // Run the learning algorithm
            double error = teacher.Run();

            // only xor is not learnable by
            // a hard-margin linear machine

            bool[][] pred  = machine.Decide(inputs);
            bool[][] train = Classes.Decide(outputs);

            var and = pred.GetColumn(0);

            Assert.IsTrue(and.IsEqual(train.GetColumn(0)));

            var or = pred.GetColumn(1);

            Assert.IsTrue(or.IsEqual(train.GetColumn(1)));

            var nand = pred.GetColumn(2);

            Assert.IsTrue(nand.IsEqual(train.GetColumn(2)));

            var xor = pred.GetColumn(3);

            Assert.IsFalse(xor.IsEqual(train.GetColumn(3)));


            Assert.AreEqual(2 / 16.0, error);
        }
Beispiel #6
0
        public static void Run()
        {
            Stopwatch sw = new Stopwatch();

            NdArray inputArrayCpu = new NdArray(Initializer.GetRealArray(INPUT_SIZE));
            NdArray inputArrayGpu = new NdArray(Initializer.GetRealArray(INPUT_SIZE));

            //Linear
            Linear linear = new Linear(INPUT_SIZE, OUTPUT_SIZE);

            Console.WriteLine("◆" + linear.Name);

            sw.Restart();
            NdArray[] gradArrayCpu = linear.Forward(inputArrayCpu);
            sw.Stop();
            Console.WriteLine("Forward [Cpu] : " + (sw.ElapsedTicks / (Stopwatch.Frequency / (1000L * 1000L))).ToString("n0") + "μs");

            gradArrayCpu[0].Grad = gradArrayCpu[0].Data; //DataをGradとして使用

            sw.Restart();
            linear.Backward(gradArrayCpu);
            sw.Stop();
            Console.WriteLine("Backward[Cpu] : " + (sw.ElapsedTicks / (Stopwatch.Frequency / (1000L * 1000L))).ToString("n0") + "μs");

            if (linear.SetGpuEnable(true))
            {
                sw.Restart();
                NdArray[] gradArrayGpu = linear.Forward(inputArrayGpu);
                sw.Stop();
                Console.WriteLine("Forward [Gpu] : " + (sw.ElapsedTicks / (Stopwatch.Frequency / (1000L * 1000L))).ToString("n0") + "μs");

                gradArrayGpu[0].Grad = gradArrayGpu[0].Data;

                sw.Restart();
                linear.Backward(gradArrayGpu);
                sw.Stop();
                Console.WriteLine("Backward[Gpu] : " + (sw.ElapsedTicks / (Stopwatch.Frequency / (1000L * 1000L))).ToString("n0") + "μs");
            }


            //Tanh
            TanhActivation tanh = new TanhActivation();

            Console.WriteLine("\n◆" + tanh.Name);

            sw.Restart();
            gradArrayCpu = tanh.Forward(inputArrayCpu);
            sw.Stop();
            Console.WriteLine("Forward [Cpu] : " + (sw.ElapsedTicks / (Stopwatch.Frequency / (1000L * 1000L))).ToString("n0") + "μs");

            gradArrayCpu[0].Grad = gradArrayCpu[0].Data;

            sw.Restart();
            tanh.Backward(gradArrayCpu);
            sw.Stop();
            Console.WriteLine("Backward[Cpu] : " + (sw.ElapsedTicks / (Stopwatch.Frequency / (1000L * 1000L))).ToString("n0") + "μs");

            if (tanh.SetGpuEnable(true))
            {
                sw.Restart();
                NdArray[] gradArrayGpu = tanh.Forward(inputArrayGpu);
                sw.Stop();
                Console.WriteLine("Forward [Gpu] : " + (sw.ElapsedTicks / (Stopwatch.Frequency / (1000L * 1000L))).ToString("n0") + "μs");

                gradArrayGpu[0].Grad = gradArrayGpu[0].Data;

                sw.Restart();
                tanh.Backward(gradArrayGpu);
                sw.Stop();
                Console.WriteLine("Backward[Gpu] : " + (sw.ElapsedTicks / (Stopwatch.Frequency / (1000L * 1000L))).ToString("n0") + "μs");
            }


            //Sigmoid
            Sigmoid sigmoid = new Sigmoid();

            Console.WriteLine("\n◆" + sigmoid.Name);

            sw.Restart();
            gradArrayCpu = sigmoid.Forward(inputArrayCpu);
            sw.Stop();
            Console.WriteLine("Forward [Cpu] : " + (sw.ElapsedTicks / (Stopwatch.Frequency / (1000L * 1000L))).ToString("n0") + "μs");

            gradArrayCpu[0].Grad = gradArrayCpu[0].Data;

            sw.Restart();
            sigmoid.Backward(gradArrayCpu);
            sw.Stop();
            Console.WriteLine("Backward[Cpu] : " + (sw.ElapsedTicks / (Stopwatch.Frequency / (1000L * 1000L))).ToString("n0") + "μs");

            if (sigmoid.SetGpuEnable(true))
            {
                sw.Restart();
                NdArray[] gradArrayGpu = sigmoid.Forward(inputArrayGpu);
                sw.Stop();
                Console.WriteLine("Forward [Gpu] : " + (sw.ElapsedTicks / (Stopwatch.Frequency / (1000L * 1000L))).ToString("n0") + "μs");

                gradArrayGpu[0].Grad = gradArrayGpu[0].Data;

                sw.Restart();
                sigmoid.Backward(gradArrayGpu);
                sw.Stop();
                Console.WriteLine("Backward[Gpu] : " + (sw.ElapsedTicks / (Stopwatch.Frequency / (1000L * 1000L))).ToString("n0") + "μs");
            }


            //ReLU
            ReLU relu = new ReLU();

            Console.WriteLine("\n◆" + relu.Name);

            sw.Restart();
            gradArrayCpu = relu.Forward(inputArrayCpu);
            sw.Stop();
            Console.WriteLine("Forward [Cpu] : " + (sw.ElapsedTicks / (Stopwatch.Frequency / (1000L * 1000L))).ToString("n0") + "μs");

            gradArrayCpu[0].Grad = gradArrayCpu[0].Data;

            sw.Restart();
            relu.Backward(gradArrayCpu);
            sw.Stop();
            Console.WriteLine("Backward[Cpu] : " + (sw.ElapsedTicks / (Stopwatch.Frequency / (1000L * 1000L))).ToString("n0") + "μs");

            if (relu.SetGpuEnable(true))
            {
                sw.Restart();
                NdArray[] gradArrayGpu = relu.Forward(inputArrayGpu);
                sw.Stop();
                Console.WriteLine("Forward [Gpu] : " + (sw.ElapsedTicks / (Stopwatch.Frequency / (1000L * 1000L))).ToString("n0") + "μs");

                gradArrayGpu[0].Grad = gradArrayGpu[0].Data;

                sw.Restart();
                relu.Backward(gradArrayGpu);
                sw.Stop();
                Console.WriteLine("Backward[Gpu] : " + (sw.ElapsedTicks / (Stopwatch.Frequency / (1000L * 1000L))).ToString("n0") + "μs");
            }


            //LeakyReLU
            LeakyReLU leakyRelu = new LeakyReLU();

            Console.WriteLine("\n◆" + leakyRelu.Name);

            sw.Restart();
            gradArrayCpu = leakyRelu.Forward(inputArrayCpu);
            sw.Stop();
            Console.WriteLine("Forward [Cpu] : " + (sw.ElapsedTicks / (Stopwatch.Frequency / (1000L * 1000L))).ToString("n0") + "μs");

            gradArrayCpu[0].Grad = gradArrayCpu[0].Data;

            sw.Restart();
            leakyRelu.Backward(gradArrayCpu);
            sw.Stop();

            Console.WriteLine("Backward[Cpu] : " + (sw.ElapsedTicks / (Stopwatch.Frequency / (1000L * 1000L))).ToString("n0") + "μs");

            if (leakyRelu.SetGpuEnable(true))
            {
                sw.Restart();
                NdArray[] gradArrayGpu = leakyRelu.Forward(inputArrayGpu);
                sw.Stop();
                Console.WriteLine("Forward [Gpu] : " + (sw.ElapsedTicks / (Stopwatch.Frequency / (1000L * 1000L))).ToString("n0") + "μs");

                gradArrayGpu[0].Grad = gradArrayGpu[0].Data;

                sw.Restart();
                leakyRelu.Backward(gradArrayGpu);
                sw.Stop();
                Console.WriteLine("Backward[Gpu] : " + (sw.ElapsedTicks / (Stopwatch.Frequency / (1000L * 1000L))).ToString("n0") + "μs");
            }


            NdArray inputImageArrayGpu = new NdArray(Initializer.GetRealArray(3 * 256 * 256 * 5), new[] { 3, 256, 256 }, 5);
            NdArray inputImageArrayCpu = new NdArray(Initializer.GetRealArray(3 * 256 * 256 * 5), new[] { 3, 256, 256 }, 5);


            //MaxPooling
            MaxPooling maxPooling = new MaxPooling(3);

            Console.WriteLine("\n◆" + maxPooling.Name);

            sw.Restart();
            NdArray[] gradImageArrayCpu = maxPooling.Forward(inputImageArrayCpu);
            sw.Stop();
            Console.WriteLine("Forward [Cpu] : " + (sw.ElapsedTicks / (Stopwatch.Frequency / (1000L * 1000L))).ToString("n0") + "μs");

            gradImageArrayCpu[0].Grad = gradImageArrayCpu[0].Data;

            sw.Restart();
            maxPooling.Backward(gradImageArrayCpu);
            sw.Stop();
            Console.WriteLine("Backward[Cpu] : " + (sw.ElapsedTicks / (Stopwatch.Frequency / (1000L * 1000L))).ToString("n0") + "μs");

            if (maxPooling.SetGpuEnable(true))
            {
                sw.Restart();
                maxPooling.Forward(inputImageArrayGpu);
                sw.Stop();
                Console.WriteLine("Forward [Gpu] : " + (sw.ElapsedTicks / (Stopwatch.Frequency / (1000L * 1000L))).ToString("n0") + "μs");

                //メモリ転送のみのため実装がない
                Console.WriteLine("Backward[Gpu] : None");
            }


            //Conv2D
            Convolution2D conv2d = new Convolution2D(3, 3, 3);

            Console.WriteLine("\n◆" + conv2d.Name);

            sw.Restart();
            gradImageArrayCpu = conv2d.Forward(inputImageArrayCpu);
            sw.Stop();
            Console.WriteLine("Forward [Cpu] : " + (sw.ElapsedTicks / (Stopwatch.Frequency / (1000L * 1000L))).ToString("n0") + "μs");

            gradImageArrayCpu[0].Grad = gradImageArrayCpu[0].Data;

            sw.Restart();
            conv2d.Backward(gradImageArrayCpu);
            sw.Stop();
            Console.WriteLine("Backward[Cpu] : " + (sw.ElapsedTicks / (Stopwatch.Frequency / (1000L * 1000L))).ToString("n0") + "μs");

            if (conv2d.SetGpuEnable(true))
            {
                sw.Restart();
                NdArray[] gradImageArrayGpu = conv2d.Forward(inputImageArrayGpu);
                sw.Stop();
                Console.WriteLine("Forward [Gpu] : " + (sw.ElapsedTicks / (Stopwatch.Frequency / (1000L * 1000L))).ToString("n0") + "μs");

                gradImageArrayGpu[0].Grad = gradImageArrayGpu[0].Data;

                sw.Restart();
                conv2d.Backward(gradImageArrayGpu);
                sw.Stop();
                Console.WriteLine("Backward[Gpu] : " + (sw.ElapsedTicks / (Stopwatch.Frequency / (1000L * 1000L))).ToString("n0") + "μs");
            }


            //Deconv2D
            Deconvolution2D deconv2d = new Deconvolution2D(3, 3, 3);

            Console.WriteLine("\n◆" + deconv2d.Name);

            sw.Restart();
            gradImageArrayCpu = deconv2d.Forward(inputImageArrayCpu);
            sw.Stop();
            Console.WriteLine("Forward [Cpu] : " + (sw.ElapsedTicks / (Stopwatch.Frequency / (1000L * 1000L))).ToString("n0") + "μs");

            gradImageArrayCpu[0].Grad = gradImageArrayCpu[0].Data;

            sw.Restart();
            deconv2d.Backward(gradImageArrayCpu);
            sw.Stop();
            Console.WriteLine("Backward[Cpu] : " + (sw.ElapsedTicks / (Stopwatch.Frequency / (1000L * 1000L))).ToString("n0") + "μs");

            if (deconv2d.SetGpuEnable(true))
            {
                sw.Restart();
                NdArray[] gradImageArrayGpu = deconv2d.Forward(inputImageArrayGpu);
                sw.Stop();
                Console.WriteLine("Forward [Gpu] : " + (sw.ElapsedTicks / (Stopwatch.Frequency / (1000L * 1000L))).ToString("n0") + "μs");

                gradImageArrayGpu[0].Grad = gradImageArrayGpu[0].Data;

                sw.Restart();
                deconv2d.Backward(gradImageArrayGpu);
                sw.Stop();
                Console.WriteLine("Backward[Gpu] : " + (sw.ElapsedTicks / (Stopwatch.Frequency / (1000L * 1000L))).ToString("n0") + "μs");
            }

            //Dropout
            Dropout dropout = new Dropout();

            Console.WriteLine("\n◆" + dropout.Name);

            sw.Restart();
            gradArrayCpu = dropout.Forward(inputArrayCpu);
            sw.Stop();
            Console.WriteLine("Forward [Cpu] : " + (sw.ElapsedTicks / (Stopwatch.Frequency / (1000L * 1000L))).ToString("n0") + "μs");

            gradArrayCpu[0].Grad = gradArrayCpu[0].Data;

            sw.Restart();
            dropout.Backward(gradArrayCpu);
            sw.Stop();
            Console.WriteLine("Backward[Cpu] : " + (sw.ElapsedTicks / (Stopwatch.Frequency / (1000L * 1000L))).ToString("n0") + "μs");

            if (dropout.SetGpuEnable(true))
            {
                sw.Restart();
                NdArray[] gradArrayGpu = dropout.Forward(inputArrayGpu);
                sw.Stop();
                Console.WriteLine("Forward [Gpu] : " + (sw.ElapsedTicks / (Stopwatch.Frequency / (1000L * 1000L))).ToString("n0") + "μs");

                gradArrayGpu[0].Grad = gradArrayGpu[0].Data;

                sw.Restart();
                dropout.Backward(gradArrayGpu);
                sw.Stop();
                Console.WriteLine("Backward[Gpu] : " + (sw.ElapsedTicks / (Stopwatch.Frequency / (1000L * 1000L))).ToString("n0") + "μs");
            }
        }
        static void Main(string[] args)
        {
            List <int> numbers = csvReader.ReadCSV(@"F:\Visual Studio Solutions\AlgorithmsSort-Search\unsorted_numbers.csv");

            DateTime pre;
            DateTime post;

            //INSERTION SORT
            pre = System.DateTime.Now;
            List <int> insertionSorted = Insertion.Sort(numbers);

            post = System.DateTime.Now;
            TimeSpan insertionTime = post - pre;

            //SHELL SORT
            pre = System.DateTime.Now;
            List <int> shellSorted = Shell.Sort(numbers);

            post = System.DateTime.Now;
            TimeSpan shellTime = post - pre;

            Console.WriteLine("Sort time in milliseconds:");
            Console.WriteLine($"insertionSorted: { insertionTime.TotalMilliseconds}");
            Console.WriteLine($"shellSorted: { shellTime.TotalMilliseconds}");

            int[] numsToSearch = new int[]
            {
                insertionSorted[0],
                insertionSorted[1500],
                insertionSorted[3000],
                insertionSorted[4500],
                insertionSorted[6000],
                insertionSorted[7500],
                insertionSorted[9000],
                insertionSorted[10500],
                insertionSorted[12000],
                insertionSorted[13500],
                insertionSorted.Last(),
            };


            //LINEAR SEACRHING(sorted)
            Console.WriteLine("\nLinear Searching(sorted):");
            pre = System.DateTime.Now;
            foreach (int num in numsToSearch)
            {
                int?LinearIndex = Linear.Search(insertionSorted, num);
                Console.WriteLine($"num {num} found at index {LinearIndex}");
            }
            post = System.DateTime.Now;
            TimeSpan linearSortedTime = post - pre;

            Console.WriteLine($"Linear search time(milliseconds): {linearSortedTime.TotalMilliseconds}");

            //LINEAR SEACRHING(unsorted)
            Console.WriteLine("\nLinear Searching(unsorted):");
            pre = System.DateTime.Now;
            foreach (int num in numsToSearch)
            {
                int?LinearIndex = Linear.Search(numbers, num);
                Console.WriteLine($"num {num} found at index {LinearIndex}");
            }
            post = System.DateTime.Now;
            TimeSpan linearUnsortedTime = post - pre;

            Console.WriteLine($"Linear search time(milliseconds): {linearUnsortedTime.TotalMilliseconds}");

            //BINARY SEARCH
            Console.WriteLine("\nBinary Searching:");
            pre = System.DateTime.Now;
            foreach (int num in numsToSearch)
            {
                int?BinaryIndex = Binary.Search(insertionSorted, num);
                Console.WriteLine($"num {num} found at index {BinaryIndex}");
            }
            post = System.DateTime.Now;
            TimeSpan binaryTime = post - pre;

            Console.WriteLine($"Binary search time(milliseconds): {binaryTime.TotalMilliseconds}");

            //SEARCHING A LIST OF 1 to 10,000,000
            List <int> TestList = Enumerable.Range(0, 10000000).ToList();

            numsToSearch = new int[]
            {
                insertionSorted[0],
                insertionSorted[1500],
                insertionSorted[3000],
                insertionSorted[4500],
                insertionSorted[6000],
                insertionSorted[7500],
                insertionSorted[9000],
                insertionSorted[10500],
                insertionSorted[12000],
                insertionSorted[13500],
                insertionSorted.Last(),
                TestList.Last(),
                9999283,
                12345678,
                10,
                0,
                568
            };

            Console.WriteLine("\nSEARCHING A LIST OF 1 to 10,000,000");

            //LINEAR SEACRHING(sorted)
            Console.WriteLine("\nLinear Searching(sorted):");
            pre = System.DateTime.Now;
            foreach (int num in numsToSearch)
            {
                int?LinearIndex = Linear.Search(TestList, num);
                Console.WriteLine($"num {num} found at index {LinearIndex}");
            }
            post             = System.DateTime.Now;
            linearSortedTime = post - pre;
            Console.WriteLine($"Linear search time(milliseconds): {linearSortedTime.TotalMilliseconds}");

            //BINARY SEARCH
            Console.WriteLine("\nBinary Searching:");
            pre = System.DateTime.Now;
            foreach (int num in numsToSearch)
            {
                int?BinaryIndex = Binary.Search(TestList, num);
                Console.WriteLine($"num {num} found at index {BinaryIndex}");
            }
            post       = System.DateTime.Now;
            binaryTime = post - pre;
            Console.WriteLine($"Binary search time(milliseconds): {binaryTime.TotalMilliseconds}");

            Console.ReadLine();
        }
Beispiel #8
0
 public DefaultDensityCurve(DateVector dates, DoubleVector densities, DayCounter dayCounter, Calendar calendar, Linear i) : this(NQuantLibcPINVOKE.new_DefaultDensityCurve__SWIG_0(DateVector.getCPtr(dates), DoubleVector.getCPtr(densities), DayCounter.getCPtr(dayCounter), Calendar.getCPtr(calendar), Linear.getCPtr(i)), true) {
   if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
 }
Beispiel #9
0
 internal static global::System.Runtime.InteropServices.HandleRef getCPtr(Linear obj) {
   return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr;
 }
Beispiel #10
0
        public void WeightsTest1()
        {
            var dataset = yinyang;

            double[][] inputs = dataset.Submatrix(null, 0, 1).ToArray();
            int[]      labels = dataset.GetColumn(2).ToInt32();

            Accord.Math.Tools.SetupGenerator(0);

            var kernel = new Linear(1);

            {
                var machine = new KernelSupportVectorMachine(kernel, inputs[0].Length);
                var smo     = new SequentialMinimalOptimization(machine, inputs, labels);

                smo.Complexity     = 1.0;
                smo.PositiveWeight = 1;
                smo.NegativeWeight = 1;
                smo.Tolerance      = 0.001;

                double error = smo.Run();

                int[] actual = new int[labels.Length];
                for (int i = 0; i < actual.Length; i++)
                {
                    actual[i] = Math.Sign(machine.Compute(inputs[i]));
                }

                ConfusionMatrix matrix = new ConfusionMatrix(actual, labels);

                Assert.AreEqual(43, matrix.TruePositives); // both classes are
                Assert.AreEqual(43, matrix.TrueNegatives); // well equilibrated
                Assert.AreEqual(7, matrix.FalseNegatives);
                Assert.AreEqual(7, matrix.FalsePositives);

                Assert.AreEqual(1.0, smo.Complexity);
                Assert.AreEqual(1.0, smo.WeightRatio);
                Assert.AreEqual(1.0, smo.NegativeWeight);
                Assert.AreEqual(1.0, smo.PositiveWeight);
                Assert.AreEqual(0.14, error);
                Assert.AreEqual(0.001, smo.Tolerance);
                Assert.AreEqual(31, machine.SupportVectors.Length);
            }

            {
                var machine = new KernelSupportVectorMachine(kernel, inputs[0].Length);
                var smo     = new SequentialMinimalOptimization(machine, inputs, labels);

                smo.Complexity     = 1;
                smo.PositiveWeight = 100;
                smo.NegativeWeight = 1;
                smo.Tolerance      = 0.001;

                double error = smo.Run();

                int[] actual = new int[labels.Length];
                for (int i = 0; i < actual.Length; i++)
                {
                    actual[i] = Math.Sign(machine.Compute(inputs[i]));
                }

                ConfusionMatrix matrix = new ConfusionMatrix(actual, labels);

                Assert.AreEqual(50, matrix.TruePositives); // has more importance
                Assert.AreEqual(23, matrix.TrueNegatives);
                Assert.AreEqual(0, matrix.FalseNegatives); // has more importance
                Assert.AreEqual(27, matrix.FalsePositives);

                Assert.AreEqual(1.0, smo.Complexity);
                Assert.AreEqual(100, smo.WeightRatio);
                Assert.AreEqual(1.0, smo.NegativeWeight);
                Assert.AreEqual(100, smo.PositiveWeight);
                Assert.AreEqual(0.001, smo.Tolerance);
                Assert.AreEqual(0.27, error);
                Assert.AreEqual(41, machine.SupportVectors.Length);
            }

            {
                var machine = new KernelSupportVectorMachine(kernel, inputs[0].Length);
                var smo     = new SequentialMinimalOptimization(machine, inputs, labels);

                smo.Complexity     = 1;
                smo.PositiveWeight = 1;
                smo.NegativeWeight = 100;
                smo.Tolerance      = 0.001;

                double error = smo.Run();

                int[] actual = new int[labels.Length];
                for (int i = 0; i < actual.Length; i++)
                {
                    actual[i] = Math.Sign(machine.Compute(inputs[i]));
                }

                var matrix = new ConfusionMatrix(actual, labels);

                Assert.AreEqual(25, matrix.TruePositives);
                Assert.AreEqual(50, matrix.TrueNegatives); // has more importance
                Assert.AreEqual(25, matrix.FalseNegatives);
                Assert.AreEqual(0, matrix.FalsePositives); // has more importance

                Assert.AreEqual(1.0, smo.Complexity);
                Assert.AreEqual(0.01, smo.WeightRatio);
                Assert.AreEqual(100, smo.NegativeWeight);
                Assert.AreEqual(1.0, smo.PositiveWeight);
                Assert.AreEqual(0.25, error);
                Assert.AreEqual(0.001, smo.Tolerance);
                Assert.AreEqual(40, machine.SupportVectors.Length);
            }
        }
Beispiel #11
0
        /// <summary>
        /// The main entry point for the program
        /// </summary>
        public static void Main()
        {
            try
            {
                #region Exploratory Data Analysis Explanation

                /*
                 *  John Tukey coined the term Exploratory Data Analysis in his seminal book of the same name.  There really is not a prescribed way to do an EDA.
                 *  Tools I use for EDA include Microsoft Excel, plots and visual inspection of the data.  Without creating an early bias, gut feelings do play a role in a good EDA.
                 *  Some objectives of EDA are to:
                 *      •	Identify the types of data in the dataset
                 *      •	Examine the statistical properties of the data
                 *      •	Look for invalid data (may need Domain or Subject Matter experts)
                 *      •	Understand the provenance of the data
                 *      •	Aide in the selection of appropriate statistical tools and techniques
                 *
                 *  For our diabetes dataset, notice that there is both quantitative and qualitative data.  Note that the result or outcome variable (which indicates if the person has
                 *  diabetes) is nominal data with only two states.  This is called dichotomous or binary categorical data which rules out some machine learning algorithms and directs
                 *  us to others.
                 */
                #endregion
                // Because of time constraints, the loading of the DataTables and EDA is complete.
                XmlConfigurator.Configure();

                Logger.Info("Exploratory Data Analysis");

                FileInfo  fi       = new FileInfo("training.csv");
                DataTable training = DataTableCsvConvertor.GetDataTableFromCsv(fi);

                fi = new FileInfo("test.csv");
                DataTable test = DataTableCsvConvertor.GetDataTableFromCsv(fi);

                // Print out the first few table rows.
                Head.PrintHead(training);

                //Logger.Info(string.Empty);
                //BasicStatistics.BasicStats(training); // For most EDA's Basic Descriptive statistics are important, but this outputs a lot of information

                #region Data Imputation & Cleanup Explanation

                /*
                 *  Keep in mind that Machine Learning algorithms operate on numerical data only, something will have to be done with the data is text or NULL.  Also predictor
                 *  variables(aka features or columns of data) that do not vary will not be predictive and may need to be removed.  Due to time constraints the EDA, ETL (Extract, Transform and Load)
                 *  and data cleaning is already completed in the solution.  For this analysis, the HeartRate column because it is all NULL and remove any rows of data that contain NULLs.
                 */
                #endregion
                // Delete any columns that are not needed.
                training.Columns.Remove("HeartRate");
                test.Columns.Remove("HeartRate");

                // How to handle rows containing missing or NA data - data imputation or deletion?
                training = DataImputation.RemoveMissing(training);
                test     = DataImputation.RemoveMissing(test);

                Codification codebook      = new Codification(training);
                int          outputClasses = 2;

                string[] inputColumns =
                {
                    "Gender", "YearOfBirth", "SmokingEffectiveYear", "NISTcode", "Height", "Weight", "BMI", "SystolicBP", "DiastolicBP", "RespiratoryRate", "Temperature"
                };

                string outputColumn = "DMIndicator";

                // Translate our training data into integer symbols using our codebook:
                DataTable  symbols = codebook.Apply(training);
                double[][] inputs  = symbols.ToArray(inputColumns);
                int[]      outputs = Matrix.ToArray <int>(training, outputColumn);


                #region Decision Tree Overview

                /*
                 *  Decision Trees are very powerful, especially with a binary classification model, and are somewhat resistant to over-fitting the data.
                 *  Additionally, they are intuitive to explain to stakeholders.
                 */
                #endregion
                Logger.Info(string.Empty);
                Logger.Info("Decision Tree");

                DecisionVariable[] attributes =
                {
                    new DecisionVariable("Gender",                                             2), // 2 possible values (Male, Female)
                    new DecisionVariable("YearOfBirth",          DecisionVariableKind.Continuous),
                    new DecisionVariable("SmokingEffectiveYear", DecisionVariableKind.Continuous),
                    new DecisionVariable("NISTcode",             DecisionVariableKind.Continuous),
                    new DecisionVariable("Height",               DecisionVariableKind.Continuous),
                    new DecisionVariable("Weight",               DecisionVariableKind.Continuous),
                    new DecisionVariable("BMI",                  DecisionVariableKind.Continuous),
                    new DecisionVariable("SystolicBP",           DecisionVariableKind.Continuous),
                    new DecisionVariable("DiastolicBP",          DecisionVariableKind.Continuous),
                    new DecisionVariable("RespiratoryRate",      DecisionVariableKind.Continuous),
                    new DecisionVariable("Temperature",          DecisionVariableKind.Continuous)
                };

                DecisionTree tree = new DecisionTree(attributes, outputClasses);

                C45Learning c45learning = new C45Learning(tree);

                // Learn the training instances!
                c45learning.Run(inputs, outputs);

                // The next two lines are optional to save the model into IL for future use.
                // Convert to an expression tree
                var expression = tree.ToExpression();
                // Compiles the expression to IL
                var func = expression.Compile();

                #region Evaluation Explanation

                /*
                 *  To evaluate the model, now use each row of the test dataset to predict the output variable (DMIndicator) using the DecisionTree’s compute method passing in the same
                 *  variables that were used to train the model.  Store the test dataset’s value of DMIndicator and the predicted value in a DataTable and integer collection for future
                 *  validation of the model.
                 */
                #endregion
                Evaluator.Evaluate(test, tree);

                #region Validation Explanation

                /*
                 *  There are many ways to validate models, but we will use a confusion matrix because it is intuitive and a very accepted way to validate binary classification models.
                 *  Most conveniently the Accord.Net has a ConfusionMatrix class to create this matrix for you.  Passing in the collection of integers of predicted and actual values
                 *  stored earlier to the ConfusionMatrix class and output the matrix and accuracy.
                 */
                #endregion
                Validator.Validate(test, tree);


                #region Support Vector Machine Overview

                /*
                 *  Support Vector Machines are powerful classification machine learning algorithms with very few knobs to turn.  The kernel of the SVM can be exchanged to use
                 *  a number of different mathematical algorithms including polynomials, neural networks and Gaussian functions.
                 */
                #endregion
                Logger.Info(string.Empty);
                Logger.Info("Support Vector Machine");

                // Add SVM code here
                IKernel kernel = new Linear();

                // Create the Multi-class Support Vector Machine using the selected Kernel
                int inputDimension = inputs[0].Length;
                var ksvm           = new MulticlassSupportVectorMachine(inputDimension, kernel, outputClasses);

                // Create the learning algorithm using the machine and the training data
                var ml = new MulticlassSupportVectorLearning(ksvm, inputs, outputs)
                {
                    Algorithm = (svm, classInputs, classOutputs, i, j) =>
                    {
                        return(new SequentialMinimalOptimization(svm, classInputs, classOutputs)
                        {
                            CacheSize = 0
                        });
                    }
                };

                double svmError = ml.Run();

                #region Evaluation Explanation

                /*
                 *  To evaluate the model, now use each row of the test dataset to predict the output variable (DMIndicator) using the DecisionTree’s compute method passing in the same
                 *  variables that were used to train the model.  Store the test dataset’s value of DMIndicator and the predicted value in a DataTable and integer collection for future
                 *  validation of the model.
                 */
                #endregion
                Evaluator.Evaluate(test, ksvm);

                #region Validation Explanation

                /*
                 *  There are many ways to validate models, but we will use a confusion matrix because it is intuitive and a very accepted way to validate binary classification models.
                 *  Most conveniently the Accord.Net has a ConfusionMatrix class to create this matrix for you.  Passing in the collection of integers of predicted and actual values
                 *  stored earlier to the ConfusionMatrix class and output the matrix and accuracy.
                 */
                #endregion
                Validator.Validate(test, ksvm);
            }
            catch (Exception ex)
            {
                Logger.Error(ex.ToString());
            }
        }
Beispiel #12
0
        private void ribbonButton47_Click(object sender, EventArgs e)
        {
            if (rectanglePrimitive == null)
            {
                rectanglePrimitive = new RectanglePrimitive();
                GeoPoint pos = new GeoPoint();
                pos.x = 116.3;
                pos.y = 39.9;
                pos.srs = m_earthMap.getSRS();
                Linear linear = new Linear();
                linear.set( 1000, UnitsType.UNIT_KILOMETERS );

                rectanglePrimitive.setPosition( pos );
                rectanglePrimitive.setHeight( linear );
                rectanglePrimitive.setWidth(linear);

                m_earthRoot.addChild( rectanglePrimitive );
            }
        }
Beispiel #13
0
        public void GivenWeUseALinearRetryStrategy(int periodicityInSeconds, int maxRetries)
        {
            var strategy = new Linear(TimeSpan.FromSeconds(periodicityInSeconds), maxRetries);

            ScenarioContext.Current.Set(strategy, RetryStrategy);
        }
Beispiel #14
0
 public PiecewiseLinearZero(int settlementDays, Calendar calendar, RateHelperVector instruments, DayCounter dayCounter, QuoteHandleVector jumps, DateVector jumpDates, double accuracy, Linear i) : this(NQuantLibcPINVOKE.new_PiecewiseLinearZero__SWIG_5(settlementDays, Calendar.getCPtr(calendar), RateHelperVector.getCPtr(instruments), DayCounter.getCPtr(dayCounter), QuoteHandleVector.getCPtr(jumps), DateVector.getCPtr(jumpDates), accuracy, Linear.getCPtr(i)), true) {
   if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
 }
        public void SerializeTest1()
        {
            double[][] inputs =
            {
                new double[] { 1, 4, 2, 0, 1 },
                new double[] { 1, 3, 2, 0, 1 },
                new double[] { 3, 0, 1, 1, 1 },
                new double[] { 3, 0, 1, 0, 1 },
                new double[] { 0, 5, 5, 5, 5 },
                new double[] { 1, 5, 5, 5, 5 },
                new double[] { 1, 0, 0, 0, 0 },
                new double[] { 1, 0, 0, 0, 0 },
            };

            int[] outputs =
            {
                0, 0,
                1, 1,
                2, 2,
                3, 3,
            };

            IKernel kernel = new Linear();
            var     msvm   = new MulticlassSupportVectorMachine(5, kernel, 4);
            var     smo    = new MulticlassSupportVectorLearning(msvm, inputs, outputs);

            smo.Algorithm = (svm, classInputs, classOutputs, i, j) =>
                            new SequentialMinimalOptimization(svm, classInputs, classOutputs);

            double expected = smo.Run();


            MemoryStream stream = new MemoryStream();

            // Save the machines
            msvm.Save(stream);

            // Rewind
            stream.Seek(0, SeekOrigin.Begin);

            // Reload the machines
            var target = MulticlassSupportVectorMachine.Load(stream);

            double actual;

            int count = 0; // Compute errors

            for (int i = 0; i < inputs.Length; i++)
            {
                double y = target.Compute(inputs[i]);
                if (y != outputs[i])
                {
                    count++;
                }
            }

            actual = (double)count / inputs.Length;


            Assert.AreEqual(expected, actual);

            Assert.AreEqual(msvm.Inputs, target.Inputs);
            Assert.AreEqual(msvm.Classes, target.Classes);
            for (int i = 0; i < msvm.Machines.Length; i++)
            {
                for (int j = 0; j < msvm.Machines.Length; j++)
                {
                    var a = msvm[i, j];
                    var b = target[i, j];

                    if (i != j)
                    {
                        Assert.IsTrue(a.SupportVectors.IsEqual(b.SupportVectors));
                    }
                    else
                    {
                        Assert.IsNull(a);
                        Assert.IsNull(b);
                    }
                }
            }
        }
Beispiel #16
0
 public ZeroCurve(DateVector dates, DoubleVector yields, DayCounter dayCounter, Calendar calendar, Linear i, Compounding compounding, Frequency frequency) : this(NQuantLibcPINVOKE.new_ZeroCurve__SWIG_0(DateVector.getCPtr(dates), DoubleVector.getCPtr(yields), DayCounter.getCPtr(dayCounter), Calendar.getCPtr(calendar), Linear.getCPtr(i), (int)compounding, (int)frequency), true) {
   if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
 }
Beispiel #17
0
 public Block(Function parent, Linear linear) : base(parent, null, linear)
 {
     containerType = ContainerTypes.Block;
 }
Beispiel #18
0
 public ZeroCurve(DateVector dates, DoubleVector yields, DayCounter dayCounter, Calendar calendar, Linear i) : this(NQuantLibcPINVOKE.new_ZeroCurve__SWIG_2(DateVector.getCPtr(dates), DoubleVector.getCPtr(yields), DayCounter.getCPtr(dayCounter), Calendar.getCPtr(calendar), Linear.getCPtr(i)), true) {
   if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
 }
 /**
  * Three names that identify in order a linear display unit, an area display
  * unit, and an angular display unit.
  *
  * @param l
  * @param s
  * @param a
  */
 virtual public void SetDisplayUnits(Linear l, Square s, Angular a) {
     PdfArray arr = new PdfArray();
     arr.Add(DecodeUnits.Decode(l));
     arr.Add(DecodeUnits.Decode(s));
     arr.Add(DecodeUnits.Decode(a));
     base.Put(PdfName.PDU, arr);
 }
        public void ClassifyTest()
        {
            // Create some sample input data instances. This is the same
            // data used in the Gutierrez-Osuna's example available on:
            // http://research.cs.tamu.edu/prism/lectures/pr/pr_l10.pdf

            double[][] inputs =
            {
                // Class 0
                new double[] {  4,  1 },
                new double[] {  2,  4 },
                new double[] {  2,  3 },
                new double[] {  3,  6 },
                new double[] {  4,  4 },

                // Class 1
                new double[] {  9, 10 },
                new double[] {  6,  8 },
                new double[] {  9,  5 },
                new double[] {  8,  7 },
                new double[] { 10,  8 }
            };

            int[] output =
            {
                0, 0, 0, 0, 0, // The first five are from class 0
                1, 1, 1, 1, 1  // The last five are from class 1
            };

            // Now we can chose a kernel function to
            // use, such as a linear kernel function.
            IKernel kernel = new Linear();

            // Then, we will create a KDA using this linear kernel.
            var kda = new KernelDiscriminantAnalysis(inputs, output, kernel);

            kda.Compute(); // Compute the analysis


            // Now we can project the data into KDA space:
            double[][] projection = kda.Transform(inputs);

            double[][] classifierProjection = kda.Classifier.First.Transform(inputs);
            Assert.IsTrue(projection.IsEqual(classifierProjection));

            // Or perform classification using:
            int[] results = kda.Classify(inputs);

            string str = projection.ToCSharp();

            double[][] expected = new double[][] {
                new double[] { 80.7607049998409, -5.30485371541545E-06, 6.61304584781419E-06, 4.52807990036774E-06, -3.44409628150189E-06, 3.69094504515388E-06, -1.33641000168438E-05, -0.000132874977040842, -0.000261921590627878, 1.22137997452386 },
                new double[] { 67.6629612351861, 6.80622743409742E-06, -8.48466262226566E-06, -5.80961187779394E-06, 4.4188405141643E-06, -4.73555212510135E-06, 1.71463925084936E-05, 0.000170481102685471, 0.000336050342774286, -1.5670535522193 },
                new double[] { 59.8679301679674, 4.10375477777336E-06, -5.11575246520124E-06, -3.50285421113483E-06, 2.66430090034575E-06, -2.85525936627451E-06, 1.03382660725515E-05, 0.00010279007663172, 0.000202618589039361, -0.944841112367518 },
                new double[] { 101.494441852779, 1.02093411395998E-05, -1.27269939227403E-05, -8.71441780958548E-06, 6.62826077091339E-06, -7.10332818965043E-06, 2.57195887591877E-05, 0.000255721654028207, 0.000504075514164981, -2.35058032832894 },
                new double[] { 104.145798201497, 2.80256425000402E-06, -3.49368461627364E-06, -2.39219308895144E-06, 1.81952256639306E-06, -1.94993321933623E-06, 7.06027928387698E-06, 7.01981011275166E-05, 0.000138373670580449, -0.645257345031474 },
                new double[] { 242.123077020588, 9.00824221261587E-06, -1.12297005614437E-05, -7.689192102589E-06, 5.84846541151762E-06, -6.26764250277745E-06, 2.26937548148953E-05, 0.000225636753569347, 0.000444772512580016, -2.07404146617259 },
                new double[] { 171.808759436683, 9.60879168943052E-06, -1.19783472456447E-05, -8.2018049702981E-06, 6.23836308744075E-06, -6.68548535731617E-06, 2.42066717959233E-05, 0.000240679203812988, 0.000474424013376051, -2.21231089725078 },
                new double[] { 203.147921684494, -4.5041210583463E-06, 5.61485022387842E-06, 3.8445962076139E-06, -2.92423269243614E-06, 3.13382127359318E-06, -1.13468773577097E-05, -0.000112818376692303, -0.000222386256126583, 1.03702073308629 },
                new double[] { 200.496565335776, 2.90265583302585E-06, -3.61845908969372E-06, -2.47762852723099E-06, 1.88450551963371E-06, -2.01957368695105E-06, 7.31243213181187E-06, 7.27051762225983E-05, 0.000143315587422421, -0.668302250211177 },
                new double[] { 244.774433369306, 1.60146531058558E-06, -1.99639123366069E-06, -1.36696743169296E-06, 1.0397271781315E-06, -1.11424755644407E-06, 4.03444536090092E-06, 4.01132006970784E-05, 7.90706689741683E-05, -0.368718482875124 }
            };

            Assert.IsTrue(expected.IsEqual(projection, 1e-6));

            // Test the classify method
            for (int i = 0; i < 5; i++)
            {
                int actual = results[i];
                Assert.AreEqual(0, actual);
            }

            for (int i = 5; i < 10; i++)
            {
                int actual = results[i];
                Assert.AreEqual(1, actual);
            }
        }
Beispiel #21
0
 public static bool IsMetric(Linear t)
 {
     return(t > 0 && (int)t < 50);     // based on enum above
 }
Beispiel #22
0
        private void btn_AddItem_Click(object sender, EventArgs e)
        {
            //if (IsNewItemValid())
            //{
            using (SqlConnection conn = new SqlConnection("Data Source=DESKTOP-Q1K44I8\\SA;Initial Catalog=barcode;Integrated Security=True"))
            {
                for (int i = 0; i < 5; i++)
                {
                    using (SqlCommand Itemcmd = new SqlCommand("dbo.InsertItem", conn))
                    {
                        Itemcmd.CommandType = CommandType.StoredProcedure;

                        //Itemcmd.CommandText = "begin transaction insert into Table_Item with (TABLOCK, HOLDLOCK) (ItemName, ItemWeight, ItemBarcode) values (@ItemName, @ItemWeight, @ItemBarcode) waitfor delay '00:00:01' commit transaction ";

                        Itemcmd.Parameters.AddWithValue("@ItemName", txtBox_NewItemName.Text     = "JWen" + (i + 1));
                        Itemcmd.Parameters.AddWithValue("@ItemWeight", txtBox_NewItemWeight.Text = "100");
                        //Itemcmd.Parameters.AddWithValue("@ItemBarcode", "BAR_" + (i+1));
                        //Itemcmd.Parameters.AddWithValue("@ItemBarcode", "BAR_" + GenerateBarcode());

                        try
                        {
                            conn.Open();
                            Itemcmd.ExecuteNonQuery();
                            //MessageBox.Show("Create New Item Done");
                        }

                        catch
                        {
                            MessageBox.Show("Create New Item Failed");
                        }
                        finally
                        {
                            conn.Close();
                        }
                    }

                    using (SqlCommand Barcodecmd = new SqlCommand())
                    {
                        Barcodecmd.Connection  = conn;
                        Barcodecmd.CommandType = CommandType.Text;
                        Barcodecmd.CommandText = "select ItemBarcode from tblItem order by ItemCode DESC";

                        try
                        {
                            conn.Open();

                            using (SqlDataReader read = Barcodecmd.ExecuteReader())
                            {
                                read.Read();
                                //latestbarcode = read.GetInt32(0) + 1;

                                // Create linear barcode object
                                Linear barcode = new Linear();
                                // Set barcode symbology type to Code-128
                                barcode.Type = BarcodeType.CODE128;
                                // Set barcode data to encode
                                barcode.Data = read["ItemBarcode"].ToString();
                                // Set barcode bar width (X dimension) in pixel
                                barcode.X = 1;
                                // Set barcode bar height (Y dimension) in pixel
                                barcode.Y = 60;
                                // Draw & print generated barcode to png image file
                                barcode.drawBarcode("C:/Users/Jwen/Desktop/Item_" + barcode.Data + ".jpg");
                            }
                            //MessageBox.Show("Create New Barcode Done");
                        }
                        catch
                        {
                            MessageBox.Show("Create New Barcode Failed");
                        }
                        finally
                        {
                            conn.Close();
                        }
                    }

                    txtBox_NewItemName.Clear();
                    txtBox_NewItemWeight.Clear();
                }
            }
        }
 /// <summary>
 /// Gets the degrees of freedom when fitting the regression.
 /// </summary>
 ///
 public double GetDegreesOfFreedom(int numberOfSamples)
 {
     return(Linear.GetDegreesOfFreedom(numberOfSamples));
 }
 public PiecewiseLinearForward(Date referenceDate, RateHelperVector instruments, DayCounter dayCounter, QuoteHandleVector jumps, DateVector jumpDates, double accuracy, Linear i) : this(NQuantLibcPINVOKE.new_PiecewiseLinearForward__SWIG_0(Date.getCPtr(referenceDate), RateHelperVector.getCPtr(instruments), DayCounter.getCPtr(dayCounter), QuoteHandleVector.getCPtr(jumps), DateVector.getCPtr(jumpDates), accuracy, Linear.getCPtr(i)), true)
 {
     if (NQuantLibcPINVOKE.SWIGPendingException.Pending)
     {
         throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
     }
 }
 public PiecewiseYoYInflation(Date referenceDate, Calendar calendar, DayCounter dayCounter, Period lag, Frequency frequency, bool indexIsInterpolated, double baseRate, YieldTermStructureHandle nominalTS, YoYHelperVector instruments, double accuracy, Linear i) : this(NQuantLibcPINVOKE.new_PiecewiseYoYInflation__SWIG_0(Date.getCPtr(referenceDate), Calendar.getCPtr(calendar), DayCounter.getCPtr(dayCounter), Period.getCPtr(lag), (int)frequency, indexIsInterpolated, baseRate, YieldTermStructureHandle.getCPtr(nominalTS), YoYHelperVector.getCPtr(instruments), accuracy, Linear.getCPtr(i)), true)
 {
     if (NQuantLibcPINVOKE.SWIGPendingException.Pending)
     {
         throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
     }
 }
Beispiel #26
0
        private int trcg(double delta, double[] g, double[] s, double[] r)
        {
            int    n   = fun_obj.get_nr_variable();
            double one = 1;

            double[] d = new double[n];
            double[] Hd = new double[n];
            double   rTr, rnewTrnew, cgtol;


            for (int i = 0; i < n; i++)
            {
                s[i] = 0;
                r[i] = -g[i];
                d[i] = r[i];
            }
            cgtol = 0.1 * euclideanNorm(g);


            int cg_iter = 0;

            rTr = dot(r, r);


            while (true)
            {
                if (euclideanNorm(r) <= cgtol)
                {
                    break;
                }
                cg_iter++;
                fun_obj.Hv(d, Hd);


                double alpha = rTr / dot(d, Hd);
                daxpy(alpha, d, s);
                if (euclideanNorm(s) > delta)
                {
                    Linear.info("cg reaches trust region boundary");
                    alpha = -alpha;
                    daxpy(alpha, d, s);


                    double std = dot(s, d);
                    double sts = dot(s, s);
                    double dtd = dot(d, d);
                    double dsq = delta * delta;
                    double rad = Math.Sqrt(std * std + dtd * (dsq - sts));
                    if (std >= 0)
                    {
                        alpha = (dsq - sts) / (std + rad);
                    }
                    else
                    {
                        alpha = (rad - std) / dtd;
                    }
                    daxpy(alpha, d, s);
                    alpha = -alpha;
                    daxpy(alpha, Hd, r);
                    break;
                }
                alpha = -alpha;
                daxpy(alpha, Hd, r);
                rnewTrnew = dot(r, r);
                double beta = rnewTrnew / rTr;
                scale(beta, d);
                daxpy(one, r, d);
                rTr = rnewTrnew;
            }


            return(cg_iter);
        }
Beispiel #27
0
 public dataPrepDiscriminantAnalysis()
 {
     kernel = new Linear();
 }
Beispiel #28
0
        public void tron(double[] w)
        {
            // Parameters for updating the iterates.
            double eta0 = 1e-4, eta1 = 0.25, eta2 = 0.75;


            // Parameters for updating the trust region size delta.
            double sigma1 = 0.25, sigma2 = 0.5, sigma3 = 4;


            int    n = fun_obj.get_nr_variable();
            int    i, cg_iter;
            double delta, snorm, one = 1.0;
            double alpha, f, fnew, prered, actred, gs;
            int    search = 1, iter = 1;

            double[] s     = new double[n];
            double[] r     = new double[n];
            double[] w_new = new double[n];
            double[] g     = new double[n];


            for (i = 0; i < n; i++)
            {
                w[i] = 0;
            }


            f = fun_obj.fun(w);
            fun_obj.grad(w, g);
            delta = euclideanNorm(g);
            double gnorm1 = delta;
            double gnorm  = gnorm1;


            if (gnorm <= eps * gnorm1)
            {
                search = 0;
            }


            iter = 1;


            while (iter <= max_iter && search != 0)
            {
                cg_iter = trcg(delta, g, s, r);


                Array.Copy(w, 0, w_new, 0, n);
                daxpy(one, s, w_new);


                gs     = dot(g, s);
                prered = -0.5 * (gs - dot(s, r));
                fnew   = fun_obj.fun(w_new);


                // Compute the actual reduction.
                actred = f - fnew;


                // On the first iteration, adjust the initial step bound.
                snorm = euclideanNorm(s);
                if (iter == 1)
                {
                    delta = Math.Min(delta, snorm);
                }


                // Compute prediction alpha*snorm of the step.
                if (fnew - f - gs <= 0)
                {
                    alpha = sigma3;
                }
                else
                {
                    alpha = Math.Max(sigma1, -0.5 * (gs / (fnew - f - gs)));
                }


                // Update the trust region bound according to the ratio of actual to
                // predicted reduction.
                if (actred < eta0 * prered)
                {
                    delta = Math.Min(Math.Max(alpha, sigma1) * snorm, sigma2 * delta);
                }
                else if (actred < eta1 * prered)
                {
                    delta = Math.Max(sigma1 * delta, Math.Min(alpha * snorm, sigma2 * delta));
                }
                else if (actred < eta2 * prered)
                {
                    delta = Math.Max(sigma1 * delta, Math.Min(alpha * snorm, sigma3 * delta));
                }
                else
                {
                    delta = Math.Max(delta, Math.Min(alpha * snorm, sigma3 * delta));
                }


                Linear.info("iter {0} act {1} pre {2} delta {3} f {4} |g| {5} CG {6}", iter, actred, prered, delta, f, gnorm, cg_iter);


                if (actred > eta0 * prered)
                {
                    iter++;
                    Array.Copy(w_new, 0, w, 0, n);
                    f = fnew;
                    fun_obj.grad(w, g);


                    gnorm = euclideanNorm(g);
                    if (gnorm <= eps * gnorm1)
                    {
                        break;
                    }
                }
                if (f < -1.0e+32)
                {
                    Linear.info("WARNING: f < -1.0e+32");
                    break;
                }
                if (Math.Abs(actred) <= 0 && prered <= 0)
                {
                    Linear.info("WARNING: actred and prered <= 0");
                    break;
                }
                if (Math.Abs(actred) <= 1.0e-12 * Math.Abs(f) && Math.Abs(prered) <= 1.0e-12 * Math.Abs(f))
                {
                    Linear.info("WARNING: actred and prered too small");
                    break;
                }
            }
        }
Beispiel #29
0
        internal override void Paint(object drawingContext)
        {
            //if (_painted) return;

            Style ps = null;

            if (_priceStyleType != _chartPanel._chartX._priceStyle || _seriesTypeType != _seriesType)
            {
                if (_chartPanel._chartX._priceStyle != PriceStyleEnum.psStandard)
                {
                    switch (_chartPanel._chartX._priceStyle)
                    {
                    case PriceStyleEnum.psKagi:
                        ps = new Kagi(this);
                        break;

                    case PriceStyleEnum.psCandleVolume:
                    case PriceStyleEnum.psEquiVolume:
                    case PriceStyleEnum.psEquiVolumeShadow:
                        ps = new EquiVolume(this);
                        break;

                    case PriceStyleEnum.psPointAndFigure:
                        ps = new PointAndFigure(this);
                        break;

                    case PriceStyleEnum.psRenko:
                        ps = new Renko(this);
                        break;

                    case PriceStyleEnum.psThreeLineBreak:
                        ps = new ThreeLineBreak(this);
                        break;

                    case PriceStyleEnum.psHeikinAshi:
                        ps = new HeikinAshi(this);
                        break;
                    }
                }
                else
                {
                    switch (_seriesType)
                    {
                    case SeriesTypeEnum.stCandleChart:
                        ps = new Candles(this);
                        break;

                    case SeriesTypeEnum.stStockBarChartHLC:
                    case SeriesTypeEnum.stStockBarChart:
                        ps = new PriceStyles.Stock(this);
                        break;

                    case SeriesTypeEnum.stLineChart:
                        ps = new Linear(this);
                        break;
                    }
                }
                if (_priceStyle != null)
                {
                    _priceStyle.RemovePaint();
                }
            }

            if (_darvasBoxes != null)
            {
                _darvasBoxes.RemovePaint();
            }

            if (_chartPanel._chartX._priceStyle == PriceStyleEnum.psStandard || _chartPanel._chartX._priceStyle == PriceStyleEnum.psHeikinAshi)
            {
                if (_darvasBoxes == null)
                {
                    _darvasBoxes = new DarvasBoxes(this);
                }

                _darvasBoxes.SetSeriesStock(this);
                if (_chartPanel._chartX._darwasBoxes)
                {
                    _darvasBoxes.Paint();
                }
            }

            if (_priceStyle != null || ps != null)
            {
                (ps ?? _priceStyle).SetStockSeries(this);
                Style psToPaint = ps ?? _priceStyle;
                bool  res;
                if (psToPaint is Candles && drawingContext != null)
                {
                    res = psToPaint.Paint(drawingContext);
                }
                else
                {
                    res = psToPaint.Paint();
                }
                //if (!(ps ?? _priceStyle).Paint()) return;
                if (!res)
                {
                    return;
                }
            }

            if (Selected)
            {
                ShowSelection();
            }

            if (ps == null)
            {
                return;
            }

            _priceStyle     = ps;
            _priceStyleType = _chartPanel._chartX._priceStyle;
            _seriesTypeType = _seriesType;
        }
Beispiel #30
0
        public static void Run()
        {
            //Weightを分割の前と後で揃える
            Real[,] testWeightValues =
            {
                { -0.02690255,  0.08830735, -0.02041466,  -0.0431439, -0.07749002 },
                { -0.06963444, -0.03971611,   0.0597842,  0.08824182, -0.06649109 },
                { -0.04966073, -0.04697048, -0.02235234, -0.09396666,    0.073189 },
                {  0.06563969,  0.04446745, -0.07192299,  0.06784364,  0.09575776 },
                {  0.05012317, -0.08874852, -0.05977172, -0.05910181, -0.06009106 },
                { -0.05200623, -0.09679124,  0.02159978, -0.08058041, -0.01340541 },
                {  -0.0254951,  0.09963084,  0.00936683, -0.08179696,  0.09604459 },
                {  -0.0732494,  0.07253634,  0.05981455, -0.01007657, -0.02992892 },
                { -0.06818873, -0.02579817,  0.06767359, -0.03379837, -0.04880046 },
                { -0.06429326, -0.08964688,  -0.0960066, -0.00286683, -0.05761427 },
                {  -0.0454098,  0.07809167, -0.05030088, -0.02533244, -0.02322736 },
                { -0.00866754, -0.03614252,  0.05237325,  0.06478979, -0.03599609 },
                { -0.01789357, -0.04479434, -0.05765592,  0.03237658, -0.06403019 },
                { -0.02421552,  0.05533903, -0.08627617,    0.094624,  0.03319318 },
                {  0.02328842, -0.08234859, -0.07979888,  0.01439688, -0.03267198 },
                { -0.07128382,  0.08531934,  0.07180037,  0.04772871, -0.08938966 },
                {  0.09431138,  0.02094762,  0.04443646,  0.07653841,  0.02028433 },
                {  0.01844446, -0.08441339,  0.01957355,  0.04430714, -0.03080243 },
                {  -0.0261334, -0.03794889, -0.00638074,  0.07278767, -0.02165155 },
                {  0.08390063, -0.03253863,   0.0311571,  0.08088892, -0.07267931 }
            };

            Real[][,] testJaggWeightValues =
            {
                new Real[, ] {
                    { -0.02690255,0.08830735, -0.02041466, -0.0431439, -0.07749002 },
                    { -0.06963444,-0.03971611, 0.0597842, 0.08824182, -0.06649109 },
                    { -0.04966073,-0.04697048, -0.02235234, -0.09396666, 0.073189 },
                    { 0.06563969,0.04446745, -0.07192299, 0.06784364, 0.09575776 },
                    { 0.05012317,         -0.08874852, -0.05977172, -0.05910181, -0.06009106 }
                },
                new Real[, ] {
                    { -0.05200623,-0.09679124, 0.02159978, -0.08058041, -0.01340541 },
                    { -0.0254951,0.09963084, 0.00936683, -0.08179696, 0.09604459 },
                    { -0.0732494,0.07253634, 0.05981455, -0.01007657, -0.02992892 },
                    { -0.06818873,-0.02579817, 0.06767359, -0.03379837, -0.04880046 },
                    { -0.06429326,         -0.08964688, -0.0960066, -0.00286683, -0.05761427 }
                },
                new Real[, ] {
                    { -0.0454098,0.07809167, -0.05030088, -0.02533244, -0.02322736 },
                    { -0.00866754,-0.03614252, 0.05237325, 0.06478979, -0.03599609 },
                    { -0.01789357,-0.04479434, -0.05765592, 0.03237658, -0.06403019 },
                    { -0.02421552,0.05533903, -0.08627617, 0.094624, 0.03319318 },
                    { 0.02328842,         -0.08234859, -0.07979888, 0.01439688, -0.03267198 }
                },
                new Real[, ] {
                    { -0.07128382,0.08531934, 0.07180037, 0.04772871, -0.08938966 },
                    { 0.09431138,0.02094762, 0.04443646, 0.07653841, 0.02028433 },
                    { 0.01844446,-0.08441339, 0.01957355, 0.04430714, -0.03080243 },
                    { -0.0261334,-0.03794889, -0.00638074, 0.07278767, -0.02165155 },
                    { 0.08390063, -0.03253863, 0.0311571, 0.08088892, -0.07267931 }
                }
            };

            Linear l0 = new Linear(5, 20, initialW: testWeightValues, name: "l0");

            Linear l1 = new Linear(5, 5, initialW: testJaggWeightValues[0], name: "l1");
            Linear l2 = new Linear(5, 5, initialW: testJaggWeightValues[1], name: "l2");
            Linear l3 = new Linear(5, 5, initialW: testJaggWeightValues[2], name: "l3");
            Linear l4 = new Linear(5, 5, initialW: testJaggWeightValues[3], name: "l4");

            //FunctionにOptimizerを設定
            l0.SetOptimizer(new SGD());

            //OptimiserにFunctionを登録
            SGD sgd = new SGD();

            l1.SetOptimizer(sgd);
            l2.SetOptimizer(sgd);
            l3.SetOptimizer(sgd);
            l4.SetOptimizer(sgd);


            //入力は同値だがGradが加算されてしまうため分ける
            Real[]  testValue        = { 0.01618112, -0.08296648, -0.05545357, 0.00389254, -0.05727582 };
            NdArray testInputValuesA = new NdArray(testValue);
            NdArray testInputValuesB = new NdArray(testValue);

            Console.WriteLine("l0 for");
            NdArray l0Result = l0.Forward(testInputValuesA)[0];

            Console.WriteLine(l0Result);

            Console.WriteLine("\nl1 for");
            NdArray l1Result = l1.Forward(testInputValuesB)[0];

            Console.WriteLine(l1Result);

            Console.WriteLine("\nl2 for");
            NdArray l2Result = l2.Forward(testInputValuesB)[0];

            Console.WriteLine(l2Result);

            Console.WriteLine("\nl3 for");
            NdArray l3Result = l3.Forward(testInputValuesB)[0];

            Console.WriteLine(l3Result);

            Console.WriteLine("\nl4 for");
            NdArray l4Result = l4.Forward(testInputValuesB)[0];

            Console.WriteLine(l4Result);

            Console.WriteLine();

            //適当なGrad値をでっち上げる
            l0Result.Grad = new Real[]
            {
                -2.42022760e-02, 5.02482988e-04, 2.52015481e-04, 8.08797951e-04, -7.19293347e-03,
                1.40045900e-04, 7.09874439e-05, 2.07651625e-04, 3.80124636e-02, -8.87162634e-04,
                -4.64874669e-04, -1.40792923e-03, -4.12280299e-02, -3.36557830e-04, -1.50323089e-04,
                -4.70047118e-04, 3.61101292e-02, -7.12957408e-04, -3.63163825e-04, -1.12809543e-03
            };

            l1Result.Grad = new Real[] { -2.42022760e-02, 5.02482988e-04, 2.52015481e-04, 8.08797951e-04, -7.19293347e-03 };
            l2Result.Grad = new Real[] { 1.40045900e-04, 7.09874439e-05, 2.07651625e-04, 3.80124636e-02, -8.87162634e-04 };
            l3Result.Grad = new Real[] { -4.64874669e-04, -1.40792923e-03, -4.12280299e-02, -3.36557830e-04, -1.50323089e-04 };
            l4Result.Grad = new Real[] { -4.70047118e-04, 3.61101292e-02, -7.12957408e-04, -3.63163825e-04, -1.12809543e-03 };


            //Backwardを実行
            l0.Backward(l0Result);

            l1.Backward(l1Result);
            l2.Backward(l2Result);
            l3.Backward(l3Result);
            l4.Backward(l4Result);

            Console.WriteLine("\nl0 back");
            Console.WriteLine(testInputValuesA.ToString("Grad"));

            Console.WriteLine("\nl1-l4 sum back");
            Console.WriteLine(testInputValuesB.ToString("Grad"));

            l0.Update();  //書式が変則的だがl0はSGDを内包しているため
            sgd.Update(); //こちらはOptimizerに関数を登録して使用している

            Console.WriteLine("\nl0 Weight");
            Console.WriteLine(l0.Weight);

            Console.WriteLine("\nl1 Weight");
            Console.WriteLine(l1.Weight);

            Console.WriteLine("\nl0 Bias");
            Console.WriteLine(l0.Bias);

            Console.WriteLine("\nl1 Bias");
            Console.WriteLine(l1.Bias);
        }
Beispiel #31
0
        public void serialize_reload_new_version()
        {
            double[][] inputs =
            {
                new double[] { 1, 4, 2, 0, 1 },
                new double[] { 1, 3, 2, 0, 1 },
                new double[] { 3, 0, 1, 1, 1 },
                new double[] { 3, 0, 1, 0, 1 },
                new double[] { 0, 5, 5, 5, 5 },
                new double[] { 1, 5, 5, 5, 5 },
                new double[] { 1, 0, 0, 0, 0 },
                new double[] { 1, 0, 0, 0, 0 },
            };

            int[] outputs =
            {
                0, 0,
                1, 1,
                2, 2,
                3, 3,
            };

            IKernel kernel = new Linear();
            var     msvm   = new MultilabelSupportVectorMachine(5, kernel, 4);
            var     smo    = new MultilabelSupportVectorLearning(msvm, inputs, outputs);

            smo.Algorithm = (svm, classInputs, classOutputs, i, j) =>
                            new SequentialMinimalOptimization(svm, classInputs, classOutputs)
            {
                Complexity = 1
            };

            double expected = smo.Run();


            // Save the machines

            var bytes = msvm.Save();

            // Reload the machines
            var target = Serializer.Load <MultilabelSupportVectorMachine>(bytes);

            double actual;

            int count = 0; // Compute errors

            for (int i = 0; i < inputs.Length; i++)
            {
                double[] responses;
                target.Compute(inputs[i], out responses);
                int y; responses.Max(out y);
                if (y != outputs[i])
                {
                    count++;
                }
            }

            actual = (double)count / inputs.Length;


            Assert.AreEqual(expected, actual);

            Assert.AreEqual(msvm.Inputs, target.Inputs);
            Assert.AreEqual(msvm.Classes, target.Classes);
            for (int i = 0; i < msvm.Machines.Length; i++)
            {
                var a = msvm[i];
                var b = target[i];

                Assert.AreEqual(a.Threshold, b.Threshold);
                Assert.AreEqual(a.NumberOfInputs, b.NumberOfInputs);
                Assert.AreEqual(a.NumberOfOutputs, b.NumberOfOutputs);
                Assert.IsTrue(a.Weights.IsEqual(b.Weights));

                Assert.IsTrue(a.SupportVectors.IsEqual(b.SupportVectors));
            }
        }
Beispiel #32
0
        public Sequential CreateSequential(JToken model)
        {
            var seq = new Sequential(controller);

            var layers = model.SelectToken("config").Children();

            foreach (var layer in layers)
            {
                var layerType = layer.SelectToken("class_name");
                switch (layerType.Value <String>())
                {
                case "Linear":
                    // weight float tensor
                    var weightData   = layer.SelectToken("config.weights.data").ToObject <float[]>();
                    var weightShape  = layer.SelectToken("config.weights.shape").ToObject <int[]>();
                    var weightTensor = controller.floatTensorFactory.Create(_data: weightData, _shape: weightShape, _autograd: true);

                    // bias float tensor

                    Linear linear = null;
                    if (layer.SelectToken("config.bias") == null)
                    {
                        var biasData   = layer.SelectToken("config.bias.data").ToObject <float[]>();
                        var biasShape  = layer.SelectToken("config.bias.shape").ToObject <int[]>();
                        var biasTensor = controller.floatTensorFactory.Create(_data: biasData, _shape: biasShape, _autograd: true);

                        var input  = layer.SelectToken("config.input").ToObject <int>();
                        var output = layer.SelectToken("config.output").ToObject <int>();

                        linear = new Linear(controller, input: input, output: output, weights: weightTensor, bias: biasTensor);
                    }
                    else
                    {
                        var input  = layer.SelectToken("config.input").ToObject <int>();
                        var output = layer.SelectToken("config.output").ToObject <int>();

                        linear = new Linear(controller, input: input, output: output, weights: weightTensor);
                    }

                    seq.AddLayer(linear);
                    break;

                case "ReLU":
                    seq.AddLayer(new ReLU(controller));
                    break;

                case "Log":
                    seq.AddLayer(new OpenMined.Syft.Layer.Log(controller));
                    break;

                case "Dropout":
                    var rate    = layer.SelectToken("config.rate").ToObject <float>();
                    var dropout = new Dropout(controller, rate);
                    seq.AddLayer(dropout);
                    break;

                case "Softmax":
                    var dim = layer.SelectToken("config.dim").ToObject <int>();
                    seq.AddLayer(new Softmax(controller, dim));
                    break;

                case "Sigmoid":
                    seq.AddLayer(new Sigmoid(controller));
                    break;
                }
            }

            return(seq);
        }
Beispiel #33
0
 public PiecewiseZeroInflation(Date referenceDate, Calendar calendar, DayCounter dayCounter, Period lag, Frequency frequency, bool indexIsInterpolated, double baseRate, YieldTermStructureHandle nominalTS, ZeroHelperVector instruments, double accuracy, Linear i) : this(NQuantLibcPINVOKE.new_PiecewiseZeroInflation__SWIG_0(Date.getCPtr(referenceDate), Calendar.getCPtr(calendar), DayCounter.getCPtr(dayCounter), Period.getCPtr(lag), (int)frequency, indexIsInterpolated, baseRate, YieldTermStructureHandle.getCPtr(nominalTS), ZeroHelperVector.getCPtr(instruments), accuracy, Linear.getCPtr(i)), true) {
   if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
 }
Beispiel #34
0
        public override void Train(EEGRecord record)
        {
            if (!EEGRecordStorage.IsRecordValid(record))
            {
                throw new InvalidRecordException();
            }
            List <double[]> outputInput = record.FeatureVectorsOutputInput;

            double[,] inputs = null;
            int[] outputs = null;
            Converters.Convert(outputInput, ref inputs, ref outputs);

            //output classes must be consecutive: 1,2,3 ...
            _lda = new LinearDiscriminantAnalysis(inputs, outputs);

            if (this.Progress != null)
            {
                this.Progress(10);
            }

            // Compute the analysis
            _lda.Compute();

            if (this.Progress != null)
            {
                this.Progress(35);
            }

            double[,] projection = _lda.Transform(inputs);

            // convert for NN format
            double[][] input2  = null;
            int[]      output2 = null;
            Converters.Convert(projection, outputs, ref input2, ref output2);

            int dimensions   = projection.GetLength(1);
            int output_count = outputs.Max();

            // Create a new Linear kernel
            IKernel kernel = new Linear();

            // Create a new Multi-class Support Vector Machine with one input,
            //  using the linear kernel and for four disjoint classes.
            _machine = new MulticlassSupportVectorMachine(dimensions, kernel, output_count);

            // Create the Multi-class learning algorithm for the machine
            var teacher = new MulticlassSupportVectorLearning(_machine, input2, output2);

            // Configure the learning algorithm to use SMO to train the
            //  underlying SVMs in each of the binary class subproblems.
            teacher.Algorithm = (svm, classInputs, classOutputs, i, j) =>
                                new SequentialMinimalOptimization(svm, classInputs, classOutputs);

            // Run the learning algorithm
            double error = teacher.Run();

            if (this.Progress != null)
            {
                this.Progress(100);
            }
        }
Beispiel #35
0
 internal static global::System.Runtime.InteropServices.HandleRef getCPtr(Linear obj)
 {
     return((obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr);
 }
Beispiel #36
0
        public void TestLinear()
        {
            Linear linear  = new Linear(2, 3);
            Linear linear2 = new Linear(3, 3);

            linear.Weight.Data = new R[] {
                1, 2, 3,
                4, 5, 6
            };
            linear.Bias.Data = new R[] {
                0.0, 0.0, 0.0
            };

            Tensor inTensor = new Tensor(
                new R[] {
                0.1, 0.3,
                2.0, 1.0,
            },
                new List <int>()
            {
                2, 2
            }
                );

            R[] expectSecond = new R[] {
                1.3, 1.7, 2.1,
                6, 9, 12
            };

            R[] expectLinearGrad = new R[] {
                1.0, 1.0, 1.0,
                1.0, 1.0, 1.0
            };

            R[] expectBiasGrad = new R[] {
                2.0, 2.0, 2.0
            };

            R[] expectWeightGrad = new R[] {
                2.1, 2.1, 2.1,
                1.3, 1.3, 1.3
            };

            R[] expectInputGrad = new R[] {
                6, 15,
                6, 15
            };

            Tensor secondTensor = (linear as IFunction).Forward(inTensor);
            Tensor resultTensor = F.Sum(secondTensor);

            resultTensor.Grad = new R[] { 1.0 };
            resultTensor.UseCount++;
            resultTensor.Backward();

            this._CheckArrayEqual(resultTensor.Data, new R[] { 32.1 }, "TestLinearOut");
            this._CheckArrayEqual(secondTensor.Data, expectSecond, "TestLinearSecondData");
            this._CheckArrayEqual(secondTensor.Grad, expectLinearGrad, "Test");
            this._CheckArrayEqual(linear.Weight.Grad, expectWeightGrad, "TestLinearWeightGrad");
            this._CheckArrayEqual(linear.Bias.Grad, expectBiasGrad, "TestLinearBiasGrad");
            this._CheckArrayEqual(inTensor.Grad, expectInputGrad, "TestLinearInputGrad");
        }
Beispiel #37
0
 public PiecewiseLinearZero(int settlementDays, Calendar calendar, RateHelperVector instruments, DayCounter dayCounter, QuoteHandleVector jumps, DateVector jumpDates, double accuracy, Linear i) : this(NQuantLibcPINVOKE.new_PiecewiseLinearZero__SWIG_5(settlementDays, Calendar.getCPtr(calendar), RateHelperVector.getCPtr(instruments), DayCounter.getCPtr(dayCounter), QuoteHandleVector.getCPtr(jumps), DateVector.getCPtr(jumpDates), accuracy, Linear.getCPtr(i)), true)
 {
     if (NQuantLibcPINVOKE.SWIGPendingException.Pending)
     {
         throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
     }
 }
Beispiel #38
0
 /**
  * @see #setWeights(double[], int[])
  */
 public double[] getWeights()
 {
     return(Linear.copyOf(weight, weight.Length));
 }
        public void ClassifyTest()
        {
            // Create some sample input data instances. This is the same
            // data used in the Gutierrez-Osuna's example available on:
            // http://research.cs.tamu.edu/prism/lectures/pr/pr_l10.pdf

            double[][] inputs =
            {
                // Class 0
                new double[] {  4,  1 },
                new double[] {  2,  4 },
                new double[] {  2,  3 },
                new double[] {  3,  6 },
                new double[] {  4,  4 },

                // Class 1
                new double[] {  9, 10 },
                new double[] {  6,  8 },
                new double[] {  9,  5 },
                new double[] {  8,  7 },
                new double[] { 10,  8 }
            };

            int[] output =
            {
                0, 0, 0, 0, 0, // The first five are from class 0
                1, 1, 1, 1, 1  // The last five are from class 1
            };

            // Now we can chose a kernel function to
            // use, such as a linear kernel function.
            IKernel kernel = new Linear();

            // Then, we will create a KDA using this linear kernel.
            var kda = new KernelDiscriminantAnalysis(inputs, output, kernel);

            kda.Compute(); // Compute the analysis


            // Now we can project the data into KDA space:
            double[][] projection = kda.Transform(inputs);

            // Or perform classification using:
            int[] results = kda.Classify(inputs);


            // Test the classify method
            for (int i = 0; i < 5; i++)
            {
                int expected = 0;
                int actual   = results[i];
                Assert.AreEqual(expected, actual);
            }

            for (int i = 5; i < 10; i++)
            {
                int expected = 1;
                int actual   = results[i];
                Assert.AreEqual(expected, actual);
            }
        }
Beispiel #40
0
 /**
  * @see #setWeights(double[], int[])
  */
 public int[] getWeightLabels()
 {
     return(Linear.copyOf(weightLabel, weightLabel.Length));
 }
Beispiel #41
0
        ////////////////////////////////////////////////////////////////////////////////////////////////////
        /// <summary>   Sets the parameters. </summary>
        ///
        /// <param name="func">         The function. </param>
        /// <param name="modelData">    Information describing the model. </param>
        ////////////////////////////////////////////////////////////////////////////////////////////////////

        static void SetParams(Function func, NpzDictionary modelData)
        {
            if (func is Linear)
            {
                Linear linear = (Linear)func;

                Array.Copy(Real.GetArray(modelData[func.Name + "/W.npy"]), linear.Weight.Data, linear.Weight.Data.Length);

                if (!linear.NoBias)
                {
                    Array.Copy(Real.GetArray(modelData[func.Name + "/b.npy"]), linear.Bias.Data, linear.Bias.Data.Length);
                }
            }
            else if (func is Convolution2D)
            {
                Convolution2D conv2D = (Convolution2D)func;

                Array.Copy(Real.GetArray(modelData[func.Name + "/W.npy"]), conv2D.Weight.Data, conv2D.Weight.Data.Length);

                if (!conv2D.NoBias)
                {
                    Array.Copy(Real.GetArray(modelData[func.Name + "/b.npy"]), conv2D.Bias.Data, conv2D.Bias.Data.Length);
                }
            }
            else if (func is Deconvolution2D)
            {
                Deconvolution2D deconv2D = (Deconvolution2D)func;

                Array.Copy(Real.GetArray(modelData[func.Name + "/W.npy"]), deconv2D.Weight.Data, deconv2D.Weight.Data.Length);

                if (!deconv2D.NoBias)
                {
                    Array.Copy(Real.GetArray(modelData[func.Name + "/b.npy"]), deconv2D.Bias.Data, deconv2D.Bias.Data.Length);
                }
            }
            else if (func is EmbedID)
            {
                EmbedID embed = (EmbedID)func;

                Array.Copy(Real.GetArray(modelData[func.Name + "/W.npy"]), embed.Weight.Data, embed.Weight.Data.Length);
            }
            else if (func is BatchNormalization)
            {
                BatchNormalization bn = (BatchNormalization)func;

                Array.Copy(Real.GetArray(modelData[func.Name + "/beta.npy"]), bn.Beta.Data, bn.Beta.Data.Length);
                Array.Copy(Real.GetArray(modelData[func.Name + "/gamma.npy"]), bn.Gamma.Data, bn.Gamma.Data.Length);

                if (bn.IsTrain)
                {
                    if (modelData.ContainsKey(func.Name + "/avg_mean.npy"))
                    {
                        Array.Copy(Real.GetArray(modelData[func.Name + "/avg_mean.npy"]), bn.AvgMean.Data, bn.AvgMean.Data.Length);
                    }
                    if (modelData.ContainsKey(func.Name + "/avg_var.npy"))
                    {
                        Array.Copy(Real.GetArray(modelData[func.Name + "/avg_var.npy"]), bn.AvgVar.Data, bn.AvgVar.Data.Length);
                    }
                }
            }
            else if (func is MultiplyScale)
            {
                MultiplyScale scale = (MultiplyScale)func;

                Array.Copy(Real.GetArray(modelData[func.Name + "/W.npy"]), scale.Weight.Data, scale.Weight.Data.Length);

                if (scale.BiasTerm)
                {
                    Array.Copy(Real.GetArray(modelData[func.Name + "/bias/b.npy"]), scale.Bias.Data, scale.Bias.Data.Length);
                }
            }
        }
Beispiel #42
0
        private void ImprimirPagina1(PrintPageEventArgs e)
        {
            var dtEncabezado = _dts.Tables[0];
            //var dtDetalle = _dts.Tables[1];
            var dtDetalle = _detalle;
            var dtBancos  = _dts.Tables[2];
            var dtPremios = _dts.Tables[3];
            //var dtSaldosAsesora = _dts.Tables[7];
            //var dtSaldoAFavor = _dts.Tables[7];
            //var dtSaldoPendiente = _dts.Tables[8];

            Int32 numSAldoAfavor    = 0;
            Int32 numSaldoPendiente = 0;
            Int32 totalpagar        = 0;

            //if (dtSaldosAsesora.Rows.Count > 0)
            //{
            //    numSAldoAfavor = Convert.ToInt32(dtSaldosAsesora.Rows[0]["curSaldoAfavor"]);
            //    numSaldoPendiente = Convert.ToInt32(dtSaldosAsesora.Rows[0]["curSaldoEnContra"]);
            //}



            //strTipo=4 Productos Agotados
            //strTipo=5 Cambios Surtidos
            //strTipo=6 Cambios Agotados
            //strTipo=
            var dtOtros = _dts.Tables[4];

            //string rutaImagen = Properties.Settings.Default.Carpeta_Imagen.Trim();


            Image logo  = Properties.Resources.Logo_Dolce_1;
            Image logo1 = Properties.Resources.Logo_Dolce;
            //Image logo = Image.FromFile(string.Format("{0}Logo_Dolce.jpg", rutaImagen));


            int fontsize           = 8;
            var xbrushes           = Brushes.Black;
            var fueteTitulo        = new Font("Tahoma", 9, FontStyle.Bold);
            var fuenteNormal       = new Font("Tahoma", fontsize);
            var fuentepequeña      = new Font("Tahoma", 5, FontStyle.Bold);
            var fuenteDetalle      = new Font("Tahoma", 7, FontStyle.Bold);
            var fuentecolilla      = new Font("Tahoma", 8, FontStyle.Bold);
            var fuentelistaDetalle = new Font("Arial", 8);
            var fuenteBancos       = new Font("Arial", 5);

            e.Graphics.DrawImage(logo, 10, 10);

            //Paginacion
            e.Graphics.DrawString(string.Format("Pagina {0} de {1}", _numPagina, _totalPaginas), new Font("Arial", 7, FontStyle.Bold), xbrushes, 700, 10);
            //Fin Paginacion

            //Datos del Encabezado

            //e.Graphics.DrawString("D O L C E",new Font("Arial",10,FontStyle.Bold),xbrushes,80,20);
            //e.Graphics.DrawString("Un mundo de moda.", new Font("Arial", 10,FontStyle.Bold), xbrushes, 80, 40);

            e.Graphics.DrawString(dtEncabezado.Rows[0]["nombreempresa"].ToString(), fueteTitulo, xbrushes, 250, 25);
            e.Graphics.DrawString(string.Format("Nit:{0}", dtEncabezado.Rows[0]["nitempresa"]), fueteTitulo, xbrushes, 250, 40);
            e.Graphics.DrawString(dtEncabezado.Rows[0]["ventadirecta"].ToString(), fueteTitulo, xbrushes, 250, 55);
            e.Graphics.DrawString(dtEncabezado.Rows[0]["regimen"].ToString(), fuentepequeña, xbrushes, 250, 75);
            //e.Graphics.DrawString(dtEncabezado.Rows[0]["contribuyentes"].ToString(), fuentepequeña, xbrushes, 250, 75);
            //e.Graphics.DrawString(dtEncabezado.Rows[0]["resolucionGC"].ToString(), fuentepequeña, xbrushes, 250, 90);

            e.Graphics.DrawString("FACTURA DE VENTA No", fueteTitulo, xbrushes, 470, 20);
            e.Graphics.DrawString(
                string.Format("{0}-{1}", dtEncabezado.Rows[0]["Prefijo"].ToString().Trim(),
                              dtEncabezado.Rows[0]["numFactura"].ToString().Trim()), fueteTitulo, xbrushes, 650, 20);
            e.Graphics.DrawString("PEDIDO No", fueteTitulo, xbrushes, 470, 35);
            e.Graphics.DrawString(dtEncabezado.Rows[0]["numPedido"].ToString(), fueteTitulo, xbrushes, 650, 35);
            e.Graphics.DrawString("FECHA FACTURA", fueteTitulo, xbrushes, 470, 50);
            e.Graphics.DrawString(Convert.ToDateTime(dtEncabezado.Rows[0]["fechafactura"]).Date.ToShortDateString(), fueteTitulo,
                                  xbrushes, 650, 50);
            e.Graphics.DrawString("FECHA VENCIMIENTO", fueteTitulo, xbrushes, 470, 65);
            e.Graphics.DrawString(Convert.ToDateTime(dtEncabezado.Rows[0]["fechavence"]).Date.ToShortDateString(), fueteTitulo,
                                  xbrushes, 650, 65);

            e.Graphics.DrawString("CAMPAÑA", fueteTitulo, xbrushes, 750, 50);
            e.Graphics.DrawString(dtEncabezado.Rows[0]["strCampaña"].ToString().Trim(), fueteTitulo, xbrushes, 750, 65);

            //Datos del Cliente


            e.Graphics.FillRectangle(Brushes.LightGray, 10, 90, 830, 70);

            e.Graphics.DrawString("Cliente", fueteTitulo, xbrushes, 20, 95);
            e.Graphics.DrawString(dtEncabezado.Rows[0]["Asesora"].ToString().Trim(), fuenteNormal, xbrushes, 80, 95);
            e.Graphics.DrawString("Cedula", fueteTitulo, xbrushes, 20, 110);
            e.Graphics.DrawString(dtEncabezado.Rows[0]["cedula"].ToString().Trim(), new Font("Tahoma", 10, FontStyle.Bold), xbrushes, 80, 110);
            e.Graphics.DrawString("Zona", fueteTitulo, xbrushes, 20, 125);
            e.Graphics.DrawString(dtEncabezado.Rows[0]["Zona"].ToString().Trim(), fuenteNormal, xbrushes, 80, 125);
            e.Graphics.DrawString("Seccion", fueteTitulo, xbrushes, 20, 140);
            e.Graphics.DrawString(dtEncabezado.Rows[0]["Seccion"].ToString().Trim(), fuenteNormal, xbrushes, 80, 140);
            e.Graphics.DrawString("Telefono", fueteTitulo, xbrushes, 270, 110);
            e.Graphics.DrawString(dtEncabezado.Rows[0]["telefono"].ToString().Trim(), fuenteNormal, xbrushes, 370, 110);
            e.Graphics.DrawString("Direccion", fueteTitulo, xbrushes, 270, 125);
            e.Graphics.DrawString(dtEncabezado.Rows[0]["direccion"].ToString().Trim(), fuenteNormal, xbrushes, 370, 125);
            e.Graphics.DrawString("Ciudad/Barrio", fueteTitulo, xbrushes, 270, 140);
            e.Graphics.DrawString(
                string.Format("{0}/{1}", dtEncabezado.Rows[0]["ciudad"].ToString().Trim(),
                              dtEncabezado.Rows[0]["barrio"].ToString().Trim()), fuenteNormal, xbrushes, 370, 140);
            e.Graphics.DrawString("Directora", fueteTitulo, xbrushes, 580, 95);
            e.Graphics.DrawString(dtEncabezado.Rows[0]["directora"].ToString().Trim(), fuenteNormal, xbrushes, 650, 95);
            e.Graphics.DrawString("Celular", fueteTitulo, xbrushes, 580, 110);
            e.Graphics.DrawString(dtEncabezado.Rows[0]["celulardirectora"].ToString().Trim(), fuenteNormal, xbrushes, 650, 110);
            e.Graphics.DrawString("Telefono", fueteTitulo, xbrushes, 580, 125);
            e.Graphics.DrawString(dtEncabezado.Rows[0]["telefonodirectora"].ToString().Trim(), fuenteNormal, xbrushes, 650, 125);

            //Fin Datos del Cliente

            //Encabezado Columnas

            e.Graphics.FillRectangle(Brushes.LightGray, 10, 170, 830, 15);

            e.Graphics.DrawString("CODIGO", fuenteDetalle, xbrushes, 20, 172);
            e.Graphics.DrawString("DESCRIPCION", fuenteDetalle, xbrushes, 210, 172);
            e.Graphics.DrawString("CANTIDAD", fuenteDetalle, xbrushes, 430, 172);
            e.Graphics.DrawString("VALOR UNITARIO", fuenteDetalle, xbrushes, 560, 172);
            e.Graphics.DrawString("VALOR TOTAL", fuenteDetalle, xbrushes, 730, 172);

            //Fin Encabezado Columnas

            //Lineas verticales del Detalle

            var pen = new Pen(Color.LightGray, 1)
            {
                DashStyle = DashStyle.Dot
            };

            e.Graphics.DrawLine(pen, 90, 180, 90, 650);
            e.Graphics.DrawLine(pen, 400, 180, 400, 650);
            e.Graphics.DrawLine(pen, 520, 180, 520, 650);
            e.Graphics.DrawLine(pen, 700, 180, 700, 650);
            //Fin Lineas verticales del Detalle

            //Linea Final Del Detalle

            e.Graphics.DrawLine(pen, 10, 650, 830, 650);

            //Fin de Linea Final Detalle

            //Detalle de Productos

            int conteo = 185;
            int linea  = 186;

            //for (int i = 0; i < 42; i++)
            //{
            //    e.Graphics.DrawString("0000", fuentelistaDetalle, xbrushes, 20, conteo);
            //    e.Graphics.DrawString("SHOR CONTROL SBELTA REF 5946", fuentelistaDetalle, xbrushes, 95,
            //        conteo);
            //    e.Graphics.DrawString("1", fuentelistaDetalle, xbrushes, 450, conteo);
            //    e.Graphics.DrawString("$ 1.500",
            //        fuentelistaDetalle, xbrushes, 550, conteo);
            //    e.Graphics.DrawString("$ 1.500", fuentelistaDetalle,
            //        xbrushes, 720, conteo);

            //    conteo = conteo + 11;

            //    linea = linea + 11;

            //    e.Graphics.DrawLine(pen, 10, linea, 830, linea);
            //}

            for (int i = 0; i < dtDetalle.Rows.Count; i++)
            {
                e.Graphics.DrawString(dtDetalle.Rows[i]["codigo"].ToString().Trim(), fuentelistaDetalle, xbrushes, 20, conteo);
                e.Graphics.DrawString(dtDetalle.Rows[i]["descripcion"].ToString().Trim(), fuentelistaDetalle, xbrushes, 95,
                                      conteo);
                e.Graphics.DrawString(dtDetalle.Rows[i]["cantidad"].ToString().Trim(), fuentelistaDetalle, xbrushes, 450, conteo);
                e.Graphics.DrawString(string.Format("$ {0:##,##}", Convert.ToInt64(dtDetalle.Rows[i]["valorunitario"])),
                                      fuentelistaDetalle, xbrushes, 550, conteo);
                e.Graphics.DrawString(string.Format("$ {0:##,##}", dtDetalle.Rows[i]["valortotal"]), fuentelistaDetalle,
                                      xbrushes, 720, conteo);

                conteo = conteo + 11;

                linea = linea + 11;

                e.Graphics.DrawLine(pen, 10, linea, 830, linea);
            }


            //Fin Detalle de Productos

            //Observacion

            e.Graphics.DrawString("OBSERVACION", fueteTitulo, xbrushes, 20, 745);
            e.Graphics.DrawString(dtEncabezado.Rows[0]["Observacion2"].ToString().Trim(), fuenteNormal, xbrushes, 20, 765);


            //Fin Observacion

            //Total Factura

            if (_numPagina == _totalPaginas)
            {
                Int32 totalFactura = Convert.ToInt32(dtEncabezado.Rows[0]["totalapagar"]);

                e.Graphics.FillRectangle(Brushes.LightGray, 550, 655, 280, 125);
                e.Graphics.DrawString("TOTAL VALOR FACTURA", fueteTitulo, xbrushes, 555, 655);
                e.Graphics.DrawString(string.Format("$ {0:##,##}", Convert.ToInt64(dtEncabezado.Rows[0]["totalapagar"])),
                                      fueteTitulo, xbrushes, 730, 655);
                e.Graphics.DrawString("ESTA FACTURA INCLUYE IVA POR", new Font("Arial", 7), xbrushes, 555, 675);
                e.Graphics.DrawString(string.Format("$ {0:##,##}", Convert.ToInt64(dtEncabezado.Rows[0]["totaliva"])),
                                      new Font("Arial", 8, FontStyle.Bold), xbrushes, 730, 675);
                //Fin Total Factura

                e.Graphics.DrawLine(new Pen(Brushes.Black)
                {
                    DashStyle = DashStyle.Dot
                }, 553, 690, 825, 690);

                //Saldos a favor o encontra de la Asesora

                e.Graphics.DrawString("Saldo Pendiente", new Font("Arial", 10, FontStyle.Bold), xbrushes, 555, 700);
                e.Graphics.DrawString(string.Format("$ {0:##,##}", numSaldoPendiente), new Font("Arial", 8), xbrushes, 730, 700);

                e.Graphics.DrawString("Saldo a Favor", new Font("Arial", 10, FontStyle.Bold), xbrushes, 555, 725);
                e.Graphics.DrawString(string.Format("$ {0:##,##}", numSAldoAfavor), new Font("Arial", 8), xbrushes, 730, 725);

                e.Graphics.DrawLine(new Pen(Brushes.Black)
                {
                    DashStyle = DashStyle.Dot
                }, 553, 745, 825, 745);

                totalpagar = (totalFactura + numSaldoPendiente) - numSAldoAfavor;

                e.Graphics.DrawString("TOTAL A PAGAR", fueteTitulo, xbrushes, 555, 750);
                e.Graphics.DrawString(string.Format("$ {0:##,##}", totalpagar), fueteTitulo, xbrushes, 730, 750);


                //Fin Saldos
            }

            //Cuadro de Dialogo Pie de Pagina
            e.Graphics.DrawRectangle(Pens.Black, 10, 785, 819, 25);
            e.Graphics.DrawString(dtEncabezado.Rows[0]["Observacion"].ToString().Trim(), new Font("Arial", 6), xbrushes, 20, 787);
            e.Graphics.DrawString(dtEncabezado.Rows[0]["resolucion"].ToString().Trim(), new Font("Arial", 6), xbrushes, 20, 797);

            //Fin Cuadro de Dialogo

            //Colilla de Pago Izquierda
            e.Graphics.DrawImage(logo1, 10, 820);
            e.Graphics.DrawString(dtEncabezado.Rows[0]["nombreempresa"].ToString().Trim(), fuentecolilla, xbrushes, 100, 820);
            e.Graphics.DrawString(string.Format("Nit:{0}", dtEncabezado.Rows[0]["nitempresa"]).ToString().Trim(), fuentecolilla,
                                  xbrushes, 100, 835);
            e.Graphics.DrawString(dtEncabezado.Rows[0]["ventadirecta"].ToString().Trim(), fuentecolilla, xbrushes, 100, 850);
            e.Graphics.DrawString("DOLCE", new Font("Tahoma", 12, FontStyle.Bold), xbrushes, 10, 870);
            e.Graphics.DrawString("¡UN MUNDO DE MODA!", new Font("Tahoma", 9, FontStyle.Bold), xbrushes, 10, 885);


            e.Graphics.DrawString("CUENTAS BANCARIAS", fuentecolilla, xbrushes, 10, 900);

            int conteoBanco = 900;

            for (int i = 0; i < dtBancos.Rows.Count; i++)
            {
                conteoBanco = conteoBanco + 12;
                e.Graphics.DrawString(dtBancos.Rows[i]["nombre"].ToString().Trim(), fuenteBancos, xbrushes, 10, conteoBanco);
                conteoBanco = conteoBanco + 12;
                e.Graphics.DrawString(dtBancos.Rows[i]["descripcion"].ToString().Trim(), fuenteBancos, xbrushes, 10, conteoBanco);
            }

            e.Graphics.DrawString("-COPIA BANCO-", fuentecolilla, xbrushes, 300, 820);

            e.Graphics.FillRectangle(Brushes.LightGray, 230, 850, 170, 40);

            e.Graphics.DrawString(dtEncabezado.Rows[0]["Asesora"].ToString().Trim(), fuentepequeña, xbrushes, 230, 850);
            e.Graphics.DrawString(string.Format("CEDULA {0}", dtEncabezado.Rows[0]["cedula"].ToString().Trim()),
                                  new Font("Arial", 5), xbrushes, 230, 860);
            e.Graphics.DrawString(string.Format("ZONA {0}", dtEncabezado.Rows[0]["Zona"].ToString().Trim()),
                                  new Font("Arial", 5), xbrushes, 230, 870);
            e.Graphics.DrawString("VALOR:", fueteTitulo, xbrushes, 270, 875);
            e.Graphics.DrawString(string.Format("$ {0:##,##}", totalpagar),
                                  fueteTitulo, xbrushes, 320, 875);
            e.Graphics.DrawString(
                string.Format("FECHA VENCIMIENTO {0}",
                              Convert.ToDateTime(dtEncabezado.Rows[0]["fechavence"]).Date.ToShortDateString()), new Font("Arial", 5),
                xbrushes, 270, 870);

            //Fin Colilla de Pago

            //Codigo de Barras

            e.Graphics.DrawString(dtEncabezado.Rows[0]["referenciabanco"].ToString().Trim(), fuentepequeña, xbrushes, 10, 960);
            //e.Graphics.DrawString(string.Format("*{0}*", dtEncabezado.Rows[0]["codbarras"].ToString().Trim()), new Font("Code128", 8), xbrushes, 10, 1010);


            var code128 = new Linear
            {
                Type        = BarcodeType.CODE128,
                Data        = dtEncabezado.Rows[0]["codbarras"].ToString().Trim(),
                LeftMargin  = 0,
                RightMargin = 0
            };

            code128.drawBarcode("D:/Prueba.jpg");

            Image codbarras = Image.FromFile("D:/Prueba.jpg");


            e.Graphics.DrawImage(codbarras, 5, 970);
            e.Graphics.DrawImage(codbarras, 405, 970);

            //Fin Codigo de Barras

            //Colilla de Pago Derecha

            e.Graphics.DrawImage(logo1, 410, 820);
            e.Graphics.DrawString(dtEncabezado.Rows[0]["nombreempresa"].ToString().Trim(), fuentecolilla, xbrushes, 510, 820);
            e.Graphics.DrawString(string.Format("Nit:{0}", dtEncabezado.Rows[0]["nitempresa"]).ToString().Trim(), fuentecolilla,
                                  xbrushes, 510, 835);
            e.Graphics.DrawString(dtEncabezado.Rows[0]["ventadirecta"].ToString().Trim(), fuentecolilla, xbrushes, 510, 850);

            e.Graphics.DrawString("DOLCE", new Font("Tahoma", 12, FontStyle.Bold), xbrushes, 410, 870);
            e.Graphics.DrawString("¡UN MUNDO DE MODA!", new Font("Tahoma", 9, FontStyle.Bold), xbrushes, 410, 885);

            e.Graphics.DrawString("CUENTAS BANCARIAS", fuentecolilla, xbrushes, 410, 900);

            conteoBanco = 900;
            for (int i = 0; i < dtBancos.Rows.Count; i++)
            {
                conteoBanco = conteoBanco + 12;
                e.Graphics.DrawString(dtBancos.Rows[i]["nombre"].ToString().Trim(), fuenteBancos, xbrushes, 410, conteoBanco);
                conteoBanco = conteoBanco + 12;
                e.Graphics.DrawString(dtBancos.Rows[i]["descripcion"].ToString().Trim(), fuenteBancos, xbrushes, 410,
                                      conteoBanco);
            }

            e.Graphics.DrawString("-COPIA DOLCE-", fuentecolilla, xbrushes, 710, 820);

            e.Graphics.FillRectangle(Brushes.LightGray, 650, 850, 170, 40);

            e.Graphics.DrawString(dtEncabezado.Rows[0]["Asesora"].ToString().Trim(), fuentepequeña, xbrushes, 650, 850);
            e.Graphics.DrawString(string.Format("CEDULA {0}", dtEncabezado.Rows[0]["cedula"].ToString().Trim()),
                                  new Font("Arial", 5), xbrushes, 650, 860);
            e.Graphics.DrawString(string.Format("ZONA {0}", dtEncabezado.Rows[0]["Zona"].ToString().Trim()),
                                  new Font("Arial", 5), xbrushes, 650, 870);
            e.Graphics.DrawString("VALOR:", fueteTitulo, xbrushes, 670, 875);
            e.Graphics.DrawString(string.Format("$ {0:##,##}", totalpagar),
                                  fueteTitulo, xbrushes, 720, 875);
            e.Graphics.DrawString(
                string.Format("FECHA VENCIMIENTO {0}",
                              Convert.ToDateTime(dtEncabezado.Rows[0]["fechavence"]).Date.ToShortDateString()), new Font("Arial", 5),
                xbrushes, 690, 870);

            e.Graphics.DrawString(dtEncabezado.Rows[0]["referenciabanco"].ToString().Trim(), fuentepequeña, xbrushes, 410, 960);

            //Fin Colilla de Pago
        }
Beispiel #43
0
 public static PdfName Decode(Linear l)
 {
     switch (l) {
         case Linear.INTERNATIONAL_FOOT:
             return new PdfName("FT");
         case Linear.INTERNATIONAL_MILE:
             return new PdfName("MI");
         case Linear.INTERNATIONAL_NAUTICAL_MILE:
             return new PdfName("NM");
         case Linear.KILOMETER:
             return new PdfName("KM");
         case Linear.METER:
             return new PdfName("M");
         case Linear.US_SURVEY_FOOT:
             return new PdfName("USFT");
         default:
             return null;
     }
 }
Beispiel #44
0
 public PiecewiseLinearForward(Date referenceDate, RateHelperVector instruments, DayCounter dayCounter, QuoteHandleVector jumps, DateVector jumpDates, double accuracy, Linear i) : this(NQuantLibcPINVOKE.new_PiecewiseLinearForward__SWIG_0(Date.getCPtr(referenceDate), RateHelperVector.getCPtr(instruments), DayCounter.getCPtr(dayCounter), QuoteHandleVector.getCPtr(jumps), DateVector.getCPtr(jumpDates), accuracy, Linear.getCPtr(i)), true) {
   if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
 }