Esempio n. 1
0
        public static FunctionTerm Polynomial(IEnumerable <FunctionTerm> basis, int dimension)
        {
            if (basis == null)
            {
                throw new ArgumentNullException("basis");
            }
            if (dimension < 0)
            {
                throw new ArgumentOutOfRangeException("dimension");
            }

            ValueTerm variable = Variable("x");
            IEnumerable <ValueTerm> coefficients =
                (
                    from index in Enumerable.Range(0, basis.Count())
                    select Variable(string.Format("c_{0}", index), dimension)
                )
                .ToArray();
            IEnumerable <ValueTerm> parameters = Enumerables.Concatenate(Enumerables.Create(variable), coefficients);

            if (!basis.Any())
            {
                return(Constant(Enumerable.Repeat(0.0, dimension)).Abstract(parameters));
            }

            IEnumerable <ValueTerm> basisValues = basis.Select(basisFunction => basisFunction.Apply(variable));

            return(Sum(Enumerable.Zip(basisValues, coefficients, Scaling)).Abstract(parameters));
        }
Esempio n. 2
0
        public static ValueTerm IntegrateTrapezoid(FunctionTerm function, OrderedRange <double> bounds, int segmentCount)
        {
            if (segmentCount < 1)
            {
                throw new ArgumentOutOfRangeException("segmentCount");
            }

            ValueTerm segmentWidth = Terms.Constant(bounds.Length() / segmentCount);

            IEnumerable <ValueTerm> values =
                (
                    from segmentPosition in Scalars.GetIntermediateValuesSymmetric(bounds.Start, bounds.End, segmentCount)
                    select function.Apply(Terms.Constant(segmentPosition))
                )
                .ToArray();

            return(Terms.Product
                   (
                       segmentWidth,
                       Terms.Sum
                       (
                           Enumerables.Concatenate
                           (
                               Enumerables.Create(Terms.Product(Terms.Constant(0.5), values.First())),
                               values.Skip(1).SkipLast(1),
                               Enumerables.Create(Terms.Product(Terms.Constant(0.5), values.Last()))
                           )
                       )
                   ));
        }
Esempio n. 3
0
        // polynomial
        public static FunctionTerm Polynomial(int dimension, int degree)
        {
            if (dimension < 0)
            {
                throw new ArgumentOutOfRangeException("dimension");
            }
            if (degree < 0)
            {
                throw new ArgumentOutOfRangeException("degree");
            }

            Variable variable = new Variable(1, "x");
            IEnumerable <Variable> coefficients =
                (
                    from index in Enumerable.Range(0, degree)
                    select new Variable(dimension, string.Format("c{0}", index))
                )
                .ToArray();

            return(Sum
                   (
                       from index in Enumerable.Range(0, degree)
                       let power = Exponentiation(variable, Constant(index))
                                   let parameter = coefficients.ElementAt(index)
                                                   select Scaling(power, parameter)
                   )
                   .Abstract(Enumerables.Concatenate(Enumerables.Create(variable), coefficients)));
        }
Esempio n. 4
0
        void RebuildSegmentComponents()
        {
            IEnumerable <PositionedControlComponent> orderedSpecificationComponents =
                (
                    from specificationComponent in SpecificationComponents
                    orderby specificationComponent.Position ascending
                    select specificationComponent
                )
                .ToArray();

            segmentComponents.Clear();

            IEnumerable <PositionedControlComponent> segmentDelimitingComponents = Enumerables.Concatenate
                                                                                   (
                Enumerables.Create(curveStartComponent),
                orderedSpecificationComponents,
                Enumerables.Create(curveEndComponent)
                                                                                   );

            foreach (Tuple <PositionedControlComponent, PositionedControlComponent> segmentDelimitingComponentRange in segmentDelimitingComponents.GetRanges())
            {
                SegmentComponent segmentComponent = new SegmentComponent(this, this, segmentDelimitingComponentRange.Item1, segmentDelimitingComponentRange.Item2);

                segmentComponent.InsertLength         += InsertLength;
                segmentComponent.SpecificationChanged += SpecificationChanged;
                segmentComponent.AddSpecification     += AddSpecification;
                segmentComponent.SelectionChanged     += SelectionChanged;

                segmentComponents.Add(segmentComponent);
            }
        }
Esempio n. 5
0
        public void Write(BinaryWriter writer)
        {
            writer.Write(Encoding.ASCII.GetBytes("ID3"));

            writer.Write(majorVersion);
            writer.Write(minorVersion);

            writer.Write(BitField.FromBits(Enumerables.Create(unsynchronisation, extendedHeader, experimental, false, false, false, false, false)).Bytes.Single());

            BitField dataLength = BitField.FromValue(DataLength, 28);

            dataLength = BitField.FromBits
                         (
                Enumerables.Concatenate
                (
                    Enumerables.Create(false),
                    dataLength[0, 7].Bits,
                    Enumerables.Create(false),
                    dataLength[7, 14].Bits,
                    Enumerables.Create(false),
                    dataLength[14, 21].Bits,
                    Enumerables.Create(false),
                    dataLength[21, 28].Bits
                )
                         );
            writer.Write(dataLength.Bytes.ToArray());

            foreach (ID3v2Frame frame in frames)
            {
                frame.Write(writer);
            }
        }
Esempio n. 6
0
        public virtual void Write(BinaryWriter writer)
        {
            BitField header = BitField.FromBits
                              (
                Enumerables.Concatenate
                (
                    BitField.FromValue(0x07FF, 11).Bits,
                    BitField.FromValue((int)version, 2).Bits,
                    BitField.FromValue((int)layer, 2).Bits,
                    Enumerables.Create(!hasErrorProtection),
                    BitField.FromValue(bitRateID, 4).Bits,
                    BitField.FromValue(sampleRateID, 2).Bits,
                    Enumerables.Create(hasPadding),
                    Enumerables.Create(privateBit),
                    BitField.FromValue((int)channelMode, 2).Bits,
                    BitField.FromValue((int)joinID, 2).Bits,
                    Enumerables.Create(isCopyrighted),
                    Enumerables.Create(isOriginal),
                    BitField.FromValue((int)emphasis, 2).Bits
                )
                              );

            writer.Write(header.Bytes.ToArray());

            if (hasErrorProtection)
            {
                writer.Write(checksum);
            }
        }
Esempio n. 7
0
        public IEnumerable <XElement> GetSvgPaths()
        {
            Kurve.Curves.Curve curve = optimizer.GetCurve(specification);

            IEnumerable <string> curveCommands = Enumerables.Concatenate
                                                 (
                Enumerables.Create(Svg.MoveTo(curve.GetPoint(0))),
                from positions in Scalars.GetIntermediateValuesSymmetric(0, 1, SegmentCount + 1).GetRanges()
                let controlPoint1 = curve.GetPoint(positions.Item1) + (1.0 / (3 * SegmentCount)) * curve.GetVelocity(positions.Item1)
                                    let controlPoint2 = curve.GetPoint(positions.Item2) - (1.0 / (3 * SegmentCount)) * curve.GetVelocity(positions.Item2)
                                                        let point2 = curve.GetPoint(positions.Item2)
                                                                     select Svg.CurveTo(controlPoint1, controlPoint2, point2)
                                                 );

            yield return(Svg.PathShape(curveCommands, null, Colors.Black, 2));

            IEnumerable <string> curvatureMarkersCommands =
                (
                    from positions in Scalars.GetIntermediateValuesSymmetric(0, 1, SegmentCount + 1).GetRanges()
                    let position = Enumerables.Average(positions.Item1, positions.Item2)
                                   let curvatureVector = CurvatureMarkersFactor * curve.GetCurvature(position) * curve.GetNormalVector(position)
                                                         select Svg.Line(curve.GetPoint(position), curve.GetPoint(position) + curvatureVector)
                );

            yield return(Svg.PathShape(curvatureMarkersCommands, null, Colors.Blue, 0.5));

            foreach (PointCurveSpecification pointCurveSpecification in specification.BasicSpecification.CurveSpecifications.OfType <PointCurveSpecification>())
            {
                Vector2Double point = curve.GetPoint(pointCurveSpecification.Position);

                yield return(Svg.CircleShape(point, 10, Colors.Red, null, 0));
            }
            foreach (DirectionCurveSpecification directionCurveSpecification in specification.BasicSpecification.CurveSpecifications.OfType <DirectionCurveSpecification>())
            {
                Vector2Double directionVector = curve.GetDirectionVector(directionCurveSpecification.Position);
                Vector2Double start           = curve.GetPoint(directionCurveSpecification.Position) - 1000 * directionVector;
                Vector2Double end             = curve.GetPoint(directionCurveSpecification.Position) + 1000 * directionVector;

                yield return(Svg.LineShape(start, end, null, Colors.Green, 2));
            }
            foreach (CurvatureCurveSpecification curvatureCurveSpecification in specification.BasicSpecification.CurveSpecifications.OfType <CurvatureCurveSpecification>())
            {
                if (curvatureCurveSpecification.Curvature == 0)
                {
                    Vector2Double directionVector = curve.GetDirectionVector(curvatureCurveSpecification.Position);
                    Vector2Double start           = curve.GetPoint(curvatureCurveSpecification.Position) - 1000 * directionVector;
                    Vector2Double end             = curve.GetPoint(curvatureCurveSpecification.Position) + 1000 * directionVector;

                    yield return(Svg.LineShape(start, end, null, Colors.Blue, 2));
                }
                else
                {
                    Vector2Double center = curve.GetPoint(curvatureCurveSpecification.Position) - (1.0 / curvatureCurveSpecification.Curvature) * curve.GetNormalVector(curvatureCurveSpecification.Position);
                    double        radius = 1.0 / curvatureCurveSpecification.Curvature.Absolute();

                    yield return(Svg.CircleShape(center, radius, null, Colors.Blue, 2));
                }
            }
        }
Esempio n. 8
0
 public static IEnumerable <double> ToWaveletData(WaveletCollection waveletCollection)
 {
     return(Enumerables.Concatenate
            (
                Enumerables.Create(waveletCollection.smoothingCoefficient),
                from level in waveletCollection.decomposition
                from item in level
                select item
            )
            .ToArray());
 }
Esempio n. 9
0
        public override FunctionTerm Substitute(Variable variable, ValueTerm substitute)
        {
            if (variables.Contains(variable))
            {
                return(this);
            }

            IEnumerable <Variable> newVariables = FindUnusedVariables
                                                  (
                variables,
                Enumerables.Concatenate
                (
                    GetFreeVariables(),
                    Enumerables.Create(variable),
                    substitute.GetFreeVariables()
                )
                                                  );
            ValueTerm newTerm = term.Substitute(variables, newVariables);

            return(new Abstraction(newVariables, newTerm.Substitute(variable, substitute)));
        }
Esempio n. 10
0
        OptimizationProblem(OptimizationSegments optimizationSegments, IEnumerable <CurveSpecification> curveSpecifications)
        {
            if (optimizationSegments == null)
            {
                throw new ArgumentNullException("segmentManager");
            }
            if (curveSpecifications == null)
            {
                throw new ArgumentNullException("curveSpecifications");
            }

            this.optimizationSegments = optimizationSegments;
            this.curveSpecifications  = curveSpecifications;

            this.curveLength = Terms.Variable("curveLength");

            this.pointSpecificationTemplates =
                (
                    from pointSpecificationIndex in Enumerable.Range(0, curveSpecifications.Count(curveSpecification => curveSpecification is PointCurveSpecification))
                    select SpecificationTemplate.CreatePointSpecificationTemplate(optimizationSegments.Segments, pointSpecificationIndex)
                )
                .ToArray();
            this.directionSpecificationTemplates =
                (
                    from directionSpecificationIndex in Enumerable.Range(0, curveSpecifications.Count(curveSpecification => curveSpecification is DirectionCurveSpecification))
                    select SpecificationTemplate.CreateDirectionSpecificationTemplate(optimizationSegments.Segments, curveLength, directionSpecificationIndex)
                )
                .ToArray();
            this.curvatureSpecificationTemplates =
                (
                    from curvatureSpecificationIndex in Enumerable.Range(0, curveSpecifications.Count(curveSpecification => curveSpecification is CurvatureCurveSpecification))
                    select SpecificationTemplate.CreateCurvatureSpecificationTemplate(optimizationSegments.Segments, curveLength, curvatureSpecificationIndex)
                )
                .ToArray();

            IEnumerable <ValueTerm> variables = optimizationSegments.Parameters;

            ValueTerm segmentLength = Terms.Quotient(curveLength, Terms.Constant(optimizationSegments.Segments.Count()));

            ValueTerm speedError = Terms.Sum
                                   (
                from segment in optimizationSegments.Segments
                let position                                                                                                             = Terms.Variable("t")
                                                                   let curve                                                             = segment.LocalCurve
                                                                                                       let speed                         = curve.Speed.Apply(position)
                                                                                                                               let error = Terms.Square(Terms.Difference(speed, segmentLength))
                                                                                                                                           select Terms.IntegrateTrapezoid(error.Abstract(position), new OrderedRange <double>(0, 1), 100)
                                   );

            ValueTerm fairnessError = Terms.Sum
                                      (
                from segment in optimizationSegments.Segments
                let position                                                          = Terms.Variable("t")
                                                      let curve                       = segment.LocalCurve
                                                                             let jerk = curve.Jerk.Apply(position)
                                                                                        let normal                         = Terms.Normal(curve.Velocity.Apply(position))
                                                                                                                 let error = Terms.Square(Terms.DotProduct(jerk, normal))
                                                                                                                             select Terms.IntegrateTrapezoid(error.Abstract(position), new OrderedRange <double>(0, 1), 100)
                                      );

//			ValueTerm pointSpecificationError = Terms.Sum
//			(
//				Enumerables.Concatenate
//				(
//					Enumerables.Create(Terms.Constant(0)),
//					from specificationTemplate in Enumerables.Concatenate(pointSpecificationTemplates)
//					select Terms.NormSquared
//					(
//						Terms.Difference
//						(
//							specificationTemplate.Constraint.Item,
//				            Terms.Vector(specificationTemplate.Constraint.Ranges.Select(range => range.Start))
//						)
//					)
//				)
//			);
//			ValueTerm directionSpecificationError = Terms.Sum
//			(
//				Enumerables.Concatenate
//				(
//					Enumerables.Create(Terms.Constant(0)),
//					from specificationTemplate in Enumerables.Concatenate(directionSpecificationTemplates)
//					select Terms.NormSquared
//					(
//						Terms.Difference
//						(
//							specificationTemplate.Constraint.Item,
//				            Terms.Vector(specificationTemplate.Constraint.Ranges.Select(range => range.Start))
//						)
//					)
//				)
//			);
//			ValueTerm curvatureSpecificationError = Terms.Sum
//			(
//				Enumerables.Concatenate
//				(
//					Enumerables.Create(Terms.Constant(0)),
//					from specificationTemplate in Enumerables.Concatenate(curvatureSpecificationTemplates)
//					select Terms.NormSquared
//					(
//						Terms.Difference
//						(
//							specificationTemplate.Constraint.Item,
//				            Terms.Vector(specificationTemplate.Constraint.Ranges.Select(range => range.Start))
//						)
//					)
//				)
//			);

            ValueTerm objectiveValue = Terms.Sum
                                       (
                Terms.Product(Terms.Exponentiation(segmentLength, Terms.Constant(-2)), Terms.Constant(100000.0), speedError),
                Terms.Product(Terms.Exponentiation(segmentLength, Terms.Constant(-4)), Terms.Constant(1), fairnessError)
//				Terms.Product(Terms.Exponentiation(segmentLength, Terms.Constant(0)), Terms.Constant(0.1), pointSpecificationError),
//				Terms.Product(Terms.Exponentiation(segmentLength, Terms.Constant(1)), Terms.Constant(10), directionSpecificationError),
//				Terms.Product(Terms.Exponentiation(segmentLength, Terms.Constant(2)), Terms.Constant(100), curvatureSpecificationError)
                                       )
                                       .Simplify();

            IEnumerable <Constraint <ValueTerm> > constraintValues =
                (
                    Enumerables.Concatenate
                    (
                        from pointSpecificationTemplate in pointSpecificationTemplates
                        select pointSpecificationTemplate.Constraint,
                        from directionSpecificationTemplate in directionSpecificationTemplates
                        select directionSpecificationTemplate.Constraint,
                        from curvatureSpecificationTemplate in curvatureSpecificationTemplates
                        select curvatureSpecificationTemplate.Constraint,

                        from segmentIndex in Enumerable.Range(0, optimizationSegments.Segments.Count() - 1)
                        let segment0CurvePoint = optimizationSegments.Segments.ElementAt(segmentIndex + 0).LocalCurve.Point
                                                 let segment1CurvePoint = optimizationSegments.Segments.ElementAt(segmentIndex + 1).LocalCurve.Point
                                                                          select Constraints.CreateEquality
                                                                          (
                            segment0CurvePoint.Apply(Terms.Constant(1)),
                            segment1CurvePoint.Apply(Terms.Constant(0))
                                                                          ),

                        from segmentIndex in Enumerable.Range(0, optimizationSegments.Segments.Count() - 1)
                        let segment0CurveVelocity = optimizationSegments.Segments.ElementAt(segmentIndex + 0).LocalCurve.Velocity
                                                    let segment1CurveVelocity = optimizationSegments.Segments.ElementAt(segmentIndex + 1).LocalCurve.Velocity
                                                                                select Constraints.CreateEquality
                                                                                (
                            segment0CurveVelocity.Apply(Terms.Constant(1)),
                            segment1CurveVelocity.Apply(Terms.Constant(0))
                                                                                ),

                        from segmentIndex in Enumerable.Range(0, optimizationSegments.Segments.Count() - 1)
                        let segment0CurveAcceleration = optimizationSegments.Segments.ElementAt(segmentIndex + 0).LocalCurve.Acceleration
                                                        let segment1CurveAcceleration = optimizationSegments.Segments.ElementAt(segmentIndex + 1).LocalCurve.Acceleration
                                                                                        select Constraints.CreateEquality
                                                                                        (
                            segment0CurveAcceleration.Apply(Terms.Constant(1)),
                            segment1CurveAcceleration.Apply(Terms.Constant(0))
                                                                                        )
                    )
                )
                .ToArray();

            Constraint <ValueTerm> constraint = Constraints.Merge(constraintValues);

            FunctionTerm objectiveFunction  = objectiveValue.Abstract(variables);
            FunctionTerm constraintFunction = constraint.Item.Abstract(variables);

            this.problem = IpoptProblem.Create(objectiveFunction, constraintFunction, constraint.Ranges);
        }
Esempio n. 11
0
        public ID3v2Tag(BinaryReader reader)
        {
            string identifier = Encoding.ASCII.GetString(reader.ReadBytes(3));

            if (identifier != "ID3")
            {
                throw new InvalidDataException(string.Format("Wrong identifier '{0}', should be 'ID3'.", identifier));
            }

            this.majorVersion = reader.ReadByte();
            this.minorVersion = reader.ReadByte();

            if (majorVersion != 3)
            {
                throw new NotImplementedException();
            }

            BitField flags = BitField.FromBytes(reader.ReadBytes(1));

            if (flags[3, 8].Value != 0)
            {
                throw new InvalidDataException(string.Format("Found non-used but set flags '{0}'.", flags));
            }

            this.unsynchronisation = flags[0];
            this.extendedHeader    = flags[1];
            this.experimental      = flags[2];

            if (unsynchronisation || extendedHeader || experimental)
            {
                throw new NotImplementedException();
            }

            BitField dataLength = BitField.FromBytes(reader.ReadBytes(4));

            if (dataLength[0] || dataLength[8] || dataLength[16] || dataLength[24])
            {
                throw new InvalidDataException(string.Format("Found wrongly set bits in the length field '{0}'.", dataLength));
            }
            dataLength = BitField.FromBits
                         (
                Enumerables.Concatenate
                (
                    dataLength[1, 8].Bits,
                    dataLength[9, 16].Bits,
                    dataLength[17, 24].Bits,
                    dataLength[25, 32].Bits
                )
                         );

            if (reader.BaseStream.Position + dataLength.Value > reader.BaseStream.Length)
            {
                throw new InvalidDataException("Invalid frame data length.");
            }

            long framesEndPosition = reader.BaseStream.Position + dataLength.Value;

            this.frames = ReadFrames(reader, framesEndPosition).ToArray();

            if (reader.BaseStream.Position != framesEndPosition)
            {
                reader.ReadBytes((int)(framesEndPosition - reader.BaseStream.Position));
            }
        }