/// <summary>
        /// Use binary search to find all Isotopic Peaks we want to consider when looking for the cross-links shifts.
        /// </summary>
        /// <param name="completePeakList">The complete list of Isotopic Peaks that we will use for searching.</param>
        /// <param name="minimumMz">The minimum m/z value to consider.</param>
        /// <param name="scanLc">The LC Scan to consider.</param>
        /// <param name="scanIms">The IMS Scan to consider.</param>
        /// <returns>All peaks that are in the given LC Scan and IMS Scan and m/z >= thegiven m/z of the Feature.</returns>
        public static List<IPeak> FindCandidatePeaks(List<IsotopicPeak> completePeakList, double minimumMz, int scanLc, int scanIms)
        {
            // Set up Peak Comparer to use for binary search later on
            AnonymousComparer<IsotopicPeak> peakComparer = new AnonymousComparer<IsotopicPeak>((x, y) => x.ScanLc != y.ScanLc ? x.ScanLc.CompareTo(y.ScanLc) : x.ScanIms != y.ScanIms ? x.ScanIms.CompareTo(y.ScanIms) : x.Mz.CompareTo(y.Mz));

            IsotopicPeak lowPeak = new IsotopicPeak {ScanLc = scanLc, ScanIms = scanIms, Mz = minimumMz, Intensity = 1};
            IsotopicPeak highPeak = new IsotopicPeak { ScanLc = scanLc, ScanIms = scanIms + 1, Mz = 0, Intensity = 1 };

            int lowPeakPosition = completePeakList.BinarySearch(lowPeak, peakComparer);
            int highPeakPosition = completePeakList.BinarySearch(highPeak, peakComparer);

            lowPeakPosition = lowPeakPosition < 0 ? ~lowPeakPosition : lowPeakPosition;
            highPeakPosition = highPeakPosition < 0 ? ~highPeakPosition : highPeakPosition;

            List<IPeak> candidatePeaks = new List<IPeak>();

            for (int j = lowPeakPosition; j < highPeakPosition; j++)
            {
                IsotopicPeak peak = completePeakList[j];
                MSPeak msPeak = new MSPeak(peak.Mz, peak.Intensity, 0.05f, 1);
                candidatePeaks.Add(msPeak);
            }

            return candidatePeaks;
        }
Ejemplo n.º 2
0
        protected virtual CouponUsageRecordJobArgument GetJobArgumentsForCouponUsageRecord(CustomerOrder order)
        {
            var           objectId      = order.Id;
            IHasDiscounts hasDiscounts  = order;
            var           customerId    = order.CustomerId;
            var           customerName  = order.CustomerName;
            var           usageComparer = AnonymousComparer.Create((PromotionUsage x) => string.Join(":", x.PromotionId, x.CouponCode, x.ObjectId));
            var           result        = hasDiscounts.GetFlatObjectsListWithInterface <IHasDiscounts>()
                                          .Where(x => x.Discounts != null)
                                          .SelectMany(x => x.Discounts)
                                          .Where(x => !string.IsNullOrEmpty(x.Coupon))
                                          .Select(x => new PromotionUsage
            {
                CouponCode  = x.Coupon,
                PromotionId = x.PromotionId,
                ObjectId    = objectId,
                ObjectType  = hasDiscounts.GetType().Name,
                UserId      = customerId,
                UserName    = customerName
            })
                                          .Distinct(usageComparer);

            return(new CouponUsageRecordJobArgument()
            {
                OrderId = objectId, PromotionUsages = result.ToArray()
            });
        }
Ejemplo n.º 3
0
 public CouponUsageRecordHandler(IPromotionUsageService usageService, IPromotionUsageSearchService promotionUsageSearchService, IPromotionService promotionService)
 {
     _usageService = usageService;
     _promotionUsageSearchService = promotionUsageSearchService;
     EqualityComparer             = AnonymousComparer.Create((PromotionUsage x) => string.Join(":", x.PromotionId, x.CouponCode, x.ObjectId));
     _promotionService            = promotionService;
 }
Ejemplo n.º 4
0
        public override void Patch(OperationEntity operation)
        {
            base.Patch(operation);

            var target = operation as PaymentInEntity;

            if (target == null)
            {
                throw new ArgumentException(@"operation argument must be of type PaymentInEntity", nameof(operation));
            }

            target.Amount                = Amount;
            target.Price                 = Price;
            target.PriceWithTax          = PriceWithTax;
            target.DiscountAmount        = DiscountAmount;
            target.DiscountAmountWithTax = DiscountAmountWithTax;
            target.TaxType               = TaxType;
            target.TaxPercentRate        = TaxPercentRate;
            target.TaxTotal              = TaxTotal;
            target.Total                 = Total;
            target.TotalWithTax          = TotalWithTax;

            target.CustomerId       = CustomerId;
            target.CustomerName     = CustomerName;
            target.OrganizationId   = OrganizationId;
            target.OrganizationName = OrganizationName;
            target.GatewayCode      = GatewayCode;
            target.Purpose          = Purpose;
            target.OuterId          = OuterId;
            target.Status           = Status;
            target.AuthorizedDate   = AuthorizedDate;
            target.CapturedDate     = CapturedDate;
            target.VoidedDate       = VoidedDate;
            target.IsCancelled      = IsCancelled;
            target.CancelledDate    = CancelledDate;
            target.CancelReason     = CancelReason;
            target.Sum = Sum;

            if (!Addresses.IsNullCollection())
            {
                Addresses.Patch(target.Addresses, (sourceAddress, targetAddress) => sourceAddress.Patch(targetAddress));
            }

            if (!TaxDetails.IsNullCollection())
            {
                var taxDetailComparer = AnonymousComparer.Create((TaxDetailEntity x) => x.Name);
                TaxDetails.Patch(target.TaxDetails, taxDetailComparer, (sourceTaxDetail, targetTaxDetail) => sourceTaxDetail.Patch(targetTaxDetail));
            }

            if (!Discounts.IsNullCollection())
            {
                var discountComparer = AnonymousComparer.Create((DiscountEntity x) => x.PromotionId);
                Discounts.Patch(target.Discounts, discountComparer, (sourceDiscount, targetDiscount) => sourceDiscount.Patch(targetDiscount));
            }

            if (!Transactions.IsNullCollection())
            {
                Transactions.Patch(target.Transactions, (sourceTran, targetTran) => sourceTran.Patch(targetTran));
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Patch changes
        /// </summary>
        /// <param name="source"></param>
        /// <param name="target"></param>
        public static void Patch(this dataModel.Property source, dataModel.Property target)
        {
            if (target == null)
            {
                throw new ArgumentNullException("target");
            }

            var patchInjectionPolicy = new PatchInjection <dataModel.Property>(x => x.PropertyValueType, x => x.IsEnum, x => x.IsMultiValue, x => x.IsLocaleDependant,
                                                                               x => x.IsRequired, x => x.TargetType, x => x.Name);

            target.InjectFrom(patchInjectionPolicy, source);


            //Attributes patch
            if (!source.PropertyAttributes.IsNullCollection())
            {
                var attributeComparer = AnonymousComparer.Create((dataModel.PropertyAttribute x) => x.IsTransient() ?  x.PropertyAttributeName : x.Id);
                source.PropertyAttributes.Patch(target.PropertyAttributes, attributeComparer, (sourceAsset, targetAsset) => sourceAsset.Patch(targetAsset));
            }
            //Property dict values
            if (!source.DictionaryValues.IsNullCollection())
            {
                source.DictionaryValues.Patch(target.DictionaryValues, (sourcePropValue, targetPropValue) => sourcePropValue.Patch(targetPropValue));
            }
        }
Ejemplo n.º 6
0
        public virtual void Patch(DynamicContentPublishingGroupEntity target)
        {
            if (target == null)
            {
                throw new ArgumentNullException(nameof(target));
            }

            target.Description = Description;
            target.Name        = Name;
            target.Priority    = Priority;
            target.IsActive    = IsActive;
            target.StoreId     = StoreId;
            target.StartDate   = StartDate;
            target.EndDate     = EndDate;
            target.PredicateVisualTreeSerialized = PredicateVisualTreeSerialized;

            if (!ContentItems.IsNullCollection())
            {
                var itemComparer = AnonymousComparer.Create((PublishingGroupContentItemEntity x) => x.DynamicContentItemId);
                ContentItems.Patch(target.ContentItems, itemComparer, (sourceProperty, targetProperty) => { sourceProperty.Patch(targetProperty); });
            }

            if (!ContentPlaces.IsNullCollection())
            {
                var itemComparer = AnonymousComparer.Create((PublishingGroupContentPlaceEntity x) => x.DynamicContentPlaceId);
                ContentPlaces.Patch(target.ContentPlaces, itemComparer, (sourceProperty, targetProperty) => { sourceProperty.Patch(targetProperty); });
            }
        }
Ejemplo n.º 7
0
        public void Patch(QuoteItemEntity target)
        {
            if (target == null)
            {
                throw new ArgumentNullException("target");
            }

            var _ = this;

            target.ListPrice  = _.ListPrice;
            target.SalePrice  = _.SalePrice;
            target.TaxType    = _.TaxType;
            target.ImageUrl   = _.ImageUrl;
            target.ProductId  = _.ProductId;
            target.Comment    = _.Comment;
            target.CatalogId  = _.CatalogId;
            target.CategoryId = _.CategoryId;
            target.Currency   = _.Currency;
            target.Name       = _.Name;
            target.Sku        = _.Sku;

            if (!ProposalPrices.IsNullCollection())
            {
                var tierPriceComparer = AnonymousComparer.Create((TierPriceEntity x) => x.Quantity + "-" + x.Price);
                ProposalPrices.Patch(target.ProposalPrices, tierPriceComparer, (sourceTierPrice, targetTierPrice) => { });
            }
        }
Ejemplo n.º 8
0
        public virtual void Patch(PropertyEntity target)
        {
            target.PropertyValueType = this.PropertyValueType;
            target.IsEnum            = this.IsEnum;
            target.IsMultiValue      = this.IsMultiValue;
            target.IsLocaleDependant = this.IsLocaleDependant;
            target.IsRequired        = this.IsRequired;
            target.TargetType        = this.TargetType;
            target.Name = this.Name;

            if (!this.PropertyAttributes.IsNullCollection())
            {
                var attributeComparer = AnonymousComparer.Create((PropertyAttributeEntity x) => x.IsTransient() ? x.PropertyAttributeName : x.Id);
                this.PropertyAttributes.Patch(target.PropertyAttributes, attributeComparer, (sourceAsset, targetAsset) => sourceAsset.Patch(targetAsset));
            }
            if (!this.DictionaryValues.IsNullCollection())
            {
                this.DictionaryValues.Patch(target.DictionaryValues, (sourcePropValue, targetPropValue) => sourcePropValue.Patch(targetPropValue));
            }
            if (!this.DisplayNames.IsNullCollection())
            {
                var displayNamesComparer = AnonymousComparer.Create((PropertyDisplayNameEntity x) => $"{x.Name}-{x.Locale}");
                this.DisplayNames.Patch(target.DisplayNames, displayNamesComparer, (sourceDisplayName, targetDisplayName) => sourceDisplayName.Patch(targetDisplayName));
            }

            if (!this.ValidationRules.IsNullCollection())
            {
                this.ValidationRules.Patch(target.ValidationRules, (sourceRule, targetRule) => sourceRule.Patch(targetRule));
            }
        }
Ejemplo n.º 9
0
        public virtual void Patch(MemberDataEntity target)
        {
            var patchInjection = new PatchInjection <MemberDataEntity>(x => x.Name);

            target.InjectFrom(patchInjection, this);

            if (!this.Phones.IsNullCollection())
            {
                var phoneComparer = AnonymousComparer.Create((PhoneDataEntity x) => x.Number);
                this.Phones.Patch(target.Phones, phoneComparer, (sourcePhone, targetPhone) => targetPhone.Number = sourcePhone.Number);
            }

            if (!this.Emails.IsNullCollection())
            {
                var addressComparer = AnonymousComparer.Create((EmailDataEntity x) => x.Address);
                this.Emails.Patch(target.Emails, addressComparer, (sourceEmail, targetEmail) => targetEmail.Address = sourceEmail.Address);
            }

            if (!this.Addresses.IsNullCollection())
            {
                this.Addresses.Patch(target.Addresses, new AddressDataEntityComparer(), (sourceAddress, targetAddress) => sourceAddress.Patch(targetAddress));
            }

            if (!this.Notes.IsNullCollection())
            {
                var noteComparer = AnonymousComparer.Create((NoteDataEntity x) => x.Id ?? x.Body);
                this.Notes.Patch(target.Notes, noteComparer, (sourceNote, targetNote) => sourceNote.Patch(targetNote));
            }

            if (!this.MemberRelations.IsNullCollection())
            {
                var relationComparer = AnonymousComparer.Create((MemberRelationDataEntity x) => x.AncestorId);
                this.MemberRelations.Patch(target.MemberRelations, relationComparer, (sourceRel, targetRel) => { /*Nothing todo*/ });
            }
        }
        /// <summary>
        /// Executes the cross-link search for LC-IMS-TOF data.
        /// </summary>
        /// <param name="settings">Settings object to control parameters for cross-linking.</param>
        /// <param name="proteinSequenceEnumerable">IEnumerable of protein sequences, as a .NET Bio ISequence object.</param>
        /// <param name="featureList">List of LC-IMS-MS Features, as LcImsMsFeature.</param>
        /// <param name="peakList">List of Isotopic Peaks, as IsotopicPeak.</param>
        /// <returns>An enumerable of CrossLinkResult objects.</returns>
        public static IList<CrossLinkResult> Execute(
            CrossLinkSettings settings,
            IEnumerable<ISequence> proteinSequenceEnumerable,
            List<LcImsMsFeature> featureList,
            List<IsotopicPeak> peakList)
        {
            var massToleranceBase = settings.MassTolerance;
            var maxMissedCleavages = settings.MaxMissedCleavages;
            var digestionRule = settings.TrypticType;

            CrossLinkUtil.StaticDeltaMass = settings.StaticDeltaMass;
            CrossLinkUtil.UseC13 = settings.UseC13;
            CrossLinkUtil.UseN15 = settings.UseN15;

            Console.WriteLine();
            Console.WriteLine("Mass Tolerance:          " + massToleranceBase + " ppm");
            Console.WriteLine("Max missed cleavages:    " + maxMissedCleavages);
            Console.WriteLine("Digestion rule:          " + settings.TrypticType );
            Console.WriteLine("Delta mass uses C13:     " + settings.UseC13);
            Console.WriteLine("Delta mass uses N15:     " + settings.UseN15);
            Console.WriteLine("Static delta mass addon: " + settings.StaticDeltaMass + " Da");

            // Used for finding Isotopic Profiles in the data
                var msFeatureFinder = new BasicTFF();

            var crossLinkList = new List<CrossLink>();
            var lastProgress = DateTime.UtcNow;
            var proteinsProcessed = 0;

            // Create CrossLink objects from all of the protein sequences
            foreach (var proteinSequence in proteinSequenceEnumerable)
            {
                var proteinSequenceString = new string(proteinSequence.Select((a => (char)a)).ToArray());
                var proteinId = proteinSequence.ID;

                // Get a List of Peptides from the Protein Sequence
                var peptideList = SequenceUtil.DigestProtein(proteinSequenceString, digestionRule, maxMissedCleavages);

                // Find all possible cross links from the peptide list
                var crossLinkEnumerable = CrossLinkUtil.GenerateTheoreticalCrossLinks(peptideList, proteinSequenceString, proteinId);
                crossLinkList.AddRange(crossLinkEnumerable);

                proteinsProcessed++;
                if (DateTime.UtcNow.Subtract(lastProgress).TotalSeconds >= 15)
                {
                    lastProgress = DateTime.UtcNow;
                    Console.WriteLine("Creating cross linked peptide list; " + proteinsProcessed + " proteins processed");
                }

            }

            Console.WriteLine("Sorting cross-linked peptides");

            // Sort the CrossLinks by mass so that the results are ordered in a friendly way
            IEnumerable<CrossLink> orderedCrossLinkEnumerable = crossLinkList.OrderBy(x => x.Mass);

            // Sort Feature by mass so we can use binary search
            featureList = featureList.OrderBy(x => x.MassMonoisotopic).ToList();

            // Set up a Feature Comparer and Peak Comparer to use for binary search later on
            var featureComparer = new AnonymousComparer<LcImsMsFeature>((x, y) => x.MassMonoisotopic.CompareTo(y.MassMonoisotopic));
            var peakComparer = new AnonymousComparer<IsotopicPeak>((x, y) => x.ScanLc != y.ScanLc ? x.ScanLc.CompareTo(y.ScanLc) : x.ScanIms != y.ScanIms ? x.ScanIms.CompareTo(y.ScanIms) : x.Mz.CompareTo(y.Mz));

            // Sort the Isotopic Peaks by LC Scan, IMS Scan, and m/z to set them up for binary search later on
            peakList.Sort(peakComparer);

            var crossLinkResultList = new List<CrossLinkResult>();
            var totalCandidatePeptides = crossLinkList.Count;

            Console.WriteLine("Searching isotopic data vs. " + totalCandidatePeptides.ToString("#,##0") + " candidate cross-linked peptides");
            lastProgress = DateTime.UtcNow;
            var crosslinkCandidatesProcessed = 0;

            // Search the data for the existence of cross-links
            foreach (var crossLink in orderedCrossLinkEnumerable)
            {
                // Calculate mass tolerance to use for binary search
                var massTolerance = massToleranceBase * crossLink.Mass / GeneralConstants.PPM_DIVISOR;

                var lowFeature = new LcImsMsFeature { MassMonoisotopic = crossLink.Mass - massTolerance };
                var highFeature = new LcImsMsFeature { MassMonoisotopic = crossLink.Mass + massTolerance };

                var lowFeaturePosition = featureList.BinarySearch(lowFeature, featureComparer);
                var highFeaturePosition = featureList.BinarySearch(highFeature, featureComparer);

                lowFeaturePosition = lowFeaturePosition < 0 ? ~lowFeaturePosition : lowFeaturePosition;
                highFeaturePosition = highFeaturePosition < 0 ? ~highFeaturePosition : highFeaturePosition;

                // Iterate over all LC-IMS-MS Features that match the Unmodified cross-link mass
                for (var i = lowFeaturePosition; i < highFeaturePosition; i++)
                {
                    var feature = featureList[i];

                    // Search for a mass shift in each of the LC Scans the unmodified cross-link mass was found
                    for (var currentScanLc = feature.ScanLcStart; currentScanLc <= feature.ScanLcEnd; currentScanLc++)
                    {
                        var crossLinkResult = new CrossLinkResult(crossLink, feature, currentScanLc);

                        var candidatePeaks = PeakUtil.FindCandidatePeaks(peakList, feature.MzMonoisotopic, currentScanLc, feature.ScanImsRep);
                        var massShiftList = crossLink.MassShiftList;
                        var shiftedMassList = new List<double>();

                        // Calculate the shifted mass values that we want to search for
                        switch (massShiftList.Count)
                        {
                            case 1:
                                {
                                    var firstNewMass = feature.MassMonoisotopic + massShiftList[0];
                                    shiftedMassList.Add(firstNewMass);
                                }
                                break;
                            case 2:
                                {
                                    var firstNewMass = feature.MassMonoisotopic + massShiftList[0];
                                    var secondNewMass = feature.MassMonoisotopic + massShiftList[1];
                                    var thirdNewMass = feature.MassMonoisotopic + massShiftList[0] + massShiftList[1];

                                    shiftedMassList.Add(firstNewMass);
                                    shiftedMassList.Add(secondNewMass);
                                    shiftedMassList.Add(thirdNewMass);
                                }
                                break;
                        }

                        // Search for shifted mass values in Isotopic Peaks
                        foreach (var shiftedMass in shiftedMassList)
                        {
                            var shiftedMz = (shiftedMass / feature.ChargeState) + GeneralConstants.MASS_OF_PROTON;

                            // Create theoretical Isotopic Peaks that will later form a theoretical Isotopic Profile
                            var theoreticalPeakList = new List<MSPeak> { new MSPeak { XValue = shiftedMz, Height = 1 } };
                            for (double k = 1; k < 4; k++)
                            {
                                theoreticalPeakList.Add(new MSPeak { XValue = shiftedMz + (k * 1.003 / feature.ChargeState), Height = (float)(1.0 - (k / 4)) });
                                theoreticalPeakList.Add(new MSPeak { XValue = shiftedMz - (k * 1.003 / feature.ChargeState), Height = (float)(1.0 - (k / 4)) });
                            }

                            // Sort peaks by m/z
                            var sortPeaksQuery = from peak in theoreticalPeakList
                                                 orderby peak.XValue
                                                 select peak;

                            // Create a theoretical Isotopic Profile for DeconTools to search for
                            var isotopicProfile = new IsotopicProfile
                            {
                                MonoIsotopicMass = shiftedMass,
                                MonoPeakMZ = shiftedMz,
                                ChargeState = feature.ChargeState,
                                Peaklist = sortPeaksQuery.ToList()
                            };

                            // Search for the theoretical Isotopic Profile
                            var foundProfile = msFeatureFinder.FindMSFeature(candidatePeaks, isotopicProfile, massToleranceBase, false);

                            /*
                             * It is possible that the set mono pass of the previous theoretical distribution was the right-most peak of the actual distribution
                             * If so, we should be able to shift the theoretical distribution over to the left and find the actual distribution
                             */
                            if (foundProfile == null)
                            {
                                foreach (var msPeak in sortPeaksQuery)
                                {
                                    msPeak.XValue -= (1.003 / feature.ChargeState);
                                }

                                isotopicProfile = new IsotopicProfile
                                {
                                    MonoIsotopicMass = shiftedMass - 1.003,
                                    MonoPeakMZ = shiftedMz - (1.003 / feature.ChargeState),
                                    ChargeState = feature.ChargeState,
                                    Peaklist = sortPeaksQuery.ToList()
                                };

                                foundProfile = msFeatureFinder.FindMSFeature(candidatePeaks, isotopicProfile, massToleranceBase, false);
                            }

                            // Add to results, even if we did not find it.
                            var didFindProfile = foundProfile != null;
                            crossLinkResult.MassShiftResults.KvpList.Add(new KeyValuePair<double, bool>(shiftedMass, didFindProfile));
                        }

                        crossLinkResultList.Add(crossLinkResult);
                    }
                }

                crosslinkCandidatesProcessed++;
                if (DateTime.UtcNow.Subtract(lastProgress).TotalSeconds >= 10)
                {
                    lastProgress = DateTime.UtcNow;
                    var percentComplete = crosslinkCandidatesProcessed / (double)totalCandidatePeptides * 100;

                    Console.WriteLine("Searching isotopic data; " + percentComplete.ToString("0.0") + "% complete");
                }

            }

            return crossLinkResultList;
        }