hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
b86adc8bb3ceb769f8e3cb3848ae2500206d46f0
12,023
cpp
C++
Source/web/WebSearchableFormData.cpp
quanganh2627/bytm-x64-L-w05-2015_external_chromium_org_third_party_WebKit
20e637e67a0c272870ae4d78466a68bcb77af041
[ "BSD-3-Clause" ]
null
null
null
Source/web/WebSearchableFormData.cpp
quanganh2627/bytm-x64-L-w05-2015_external_chromium_org_third_party_WebKit
20e637e67a0c272870ae4d78466a68bcb77af041
[ "BSD-3-Clause" ]
null
null
null
Source/web/WebSearchableFormData.cpp
quanganh2627/bytm-x64-L-w05-2015_external_chromium_org_third_party_WebKit
20e637e67a0c272870ae4d78466a68bcb77af041
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (C) 2009 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "public/web/WebSearchableFormData.h" #include "core/HTMLNames.h" #include "core/dom/Document.h" #include "core/html/FormDataList.h" #include "core/html/HTMLFormControlElement.h" #include "core/html/HTMLFormElement.h" #include "core/html/HTMLInputElement.h" #include "core/html/HTMLOptionElement.h" #include "core/html/HTMLSelectElement.h" #include "platform/network/FormDataBuilder.h" #include "public/web/WebFormElement.h" #include "public/web/WebInputElement.h" #include "wtf/text/TextEncoding.h" using namespace WebCore; using namespace HTMLNames; namespace { // Gets the encoding for the form. void GetFormEncoding(const HTMLFormElement* form, WTF::TextEncoding* encoding) { String str(form->getAttribute(HTMLNames::accept_charsetAttr)); str.replace(',', ' '); Vector<String> charsets; str.split(' ', charsets); for (Vector<String>::const_iterator i(charsets.begin()); i != charsets.end(); ++i) { *encoding = WTF::TextEncoding(*i); if (encoding->isValid()) return; } if (!form->document().loader()) return; *encoding = WTF::TextEncoding(form->document().encoding()); } // Returns true if the submit request results in an HTTP URL. bool IsHTTPFormSubmit(const HTMLFormElement* form) { // FIXME: This function is insane. This is an overly complicated way to get this information. String action(form->action()); // The isNull() check is trying to avoid completeURL returning KURL() when passed a null string. return form->document().completeURL(action.isNull() ? "" : action).protocolIs("http"); } // If the form does not have an activated submit button, the first submit // button is returned. HTMLFormControlElement* GetButtonToActivate(HTMLFormElement* form) { HTMLFormControlElement* firstSubmitButton = 0; const FormAssociatedElement::List& element = form->associatedElements(); for (FormAssociatedElement::List::const_iterator i(element.begin()); i != element.end(); ++i) { if (!(*i)->isFormControlElement()) continue; HTMLFormControlElement* control = toHTMLFormControlElement(*i); if (control->isActivatedSubmit()) { // There's a button that is already activated for submit, return 0. return 0; } if (!firstSubmitButton && control->isSuccessfulSubmitButton()) firstSubmitButton = control; } return firstSubmitButton; } // Returns true if the selected state of all the options matches the default // selected state. bool IsSelectInDefaultState(HTMLSelectElement* select) { const WillBeHeapVector<RawPtrWillBeMember<HTMLElement> >& listItems = select->listItems(); if (select->multiple() || select->size() > 1) { for (WillBeHeapVector<RawPtrWillBeMember<HTMLElement> >::const_iterator i(listItems.begin()); i != listItems.end(); ++i) { if (!(*i)->hasLocalName(HTMLNames::optionTag)) continue; HTMLOptionElement* optionElement = toHTMLOptionElement(*i); if (optionElement->selected() != optionElement->hasAttribute(selectedAttr)) return false; } return true; } // The select is rendered as a combobox (called menulist in WebKit). At // least one item is selected, determine which one. HTMLOptionElement* initialSelected = 0; for (WillBeHeapVector<RawPtrWillBeMember<HTMLElement> >::const_iterator i(listItems.begin()); i != listItems.end(); ++i) { if (!(*i)->hasLocalName(HTMLNames::optionTag)) continue; HTMLOptionElement* optionElement = toHTMLOptionElement(*i); if (optionElement->hasAttribute(selectedAttr)) { // The page specified the option to select. initialSelected = optionElement; break; } if (!initialSelected) initialSelected = optionElement; } return !initialSelected || initialSelected->selected(); } // Returns true if the form element is in its default state, false otherwise. // The default state is the state of the form element on initial load of the // page, and varies depending upon the form element. For example, a checkbox is // in its default state if the checked state matches the state of the checked attribute. bool IsInDefaultState(HTMLFormControlElement* formElement) { ASSERT(formElement); if (isHTMLInputElement(*formElement)) { const HTMLInputElement& inputElement = toHTMLInputElement(*formElement); if (inputElement.isCheckbox() || inputElement.isRadioButton()) return inputElement.checked() == inputElement.hasAttribute(checkedAttr); } else if (isHTMLSelectElement(*formElement)) { return IsSelectInDefaultState(toHTMLSelectElement(formElement)); } return true; } // Look for a suitable search text field in a given HTMLFormElement // Return nothing if one of those items are found: // - A text area field // - A file upload field // - A Password field // - More than one text field HTMLInputElement* findSuitableSearchInputElement(const HTMLFormElement* form) { HTMLInputElement* textElement = 0; const FormAssociatedElement::List& element = form->associatedElements(); for (FormAssociatedElement::List::const_iterator i(element.begin()); i != element.end(); ++i) { if (!(*i)->isFormControlElement()) continue; HTMLFormControlElement* control = toHTMLFormControlElement(*i); if (control->isDisabledFormControl() || control->name().isNull()) continue; if (!IsInDefaultState(control) || isHTMLTextAreaElement(*control)) return 0; if (isHTMLInputElement(*control) && control->willValidate()) { const HTMLInputElement& input = toHTMLInputElement(*control); // Return nothing if a file upload field or a password field are found. if (input.isFileUpload() || input.isPasswordField()) return 0; if (input.isTextField()) { if (textElement) { // The auto-complete bar only knows how to fill in one value. // This form has multiple fields; don't treat it as searchable. return 0; } textElement = toHTMLInputElement(control); } } } return textElement; } // Build a search string based on a given HTMLFormElement and HTMLInputElement // // Search string output example from www.google.com: // "hl=en&source=hp&biw=1085&bih=854&q={searchTerms}&btnG=Google+Search&aq=f&aqi=&aql=&oq=" // // Return false if the provided HTMLInputElement is not found in the form bool buildSearchString(const HTMLFormElement* form, Vector<char>* encodedString, WTF::TextEncoding* encoding, const HTMLInputElement* textElement) { bool isElementFound = false; const FormAssociatedElement::List& elements = form->associatedElements(); for (FormAssociatedElement::List::const_iterator i(elements.begin()); i != elements.end(); ++i) { if (!(*i)->isFormControlElement()) continue; HTMLFormControlElement* control = toHTMLFormControlElement(*i); if (control->isDisabledFormControl() || control->name().isNull()) continue; FormDataList dataList(*encoding); if (!control->appendFormData(dataList, false)) continue; const WillBeHeapVector<FormDataList::Item>& items = dataList.items(); for (WillBeHeapVector<FormDataList::Item>::const_iterator j(items.begin()); j != items.end(); ++j) { if (!encodedString->isEmpty()) encodedString->append('&'); FormDataBuilder::encodeStringAsFormData(*encodedString, j->data()); encodedString->append('='); ++j; if (control == textElement) { encodedString->append("{searchTerms}", 13); isElementFound = true; } else FormDataBuilder::encodeStringAsFormData(*encodedString, j->data()); } } return isElementFound; } } // namespace namespace blink { WebSearchableFormData::WebSearchableFormData(const WebFormElement& form, const WebInputElement& selectedInputElement) { RefPtrWillBeRawPtr<HTMLFormElement> formElement = static_cast<PassRefPtrWillBeRawPtr<HTMLFormElement> >(form); HTMLInputElement* inputElement = static_cast<PassRefPtrWillBeRawPtr<HTMLInputElement> >(selectedInputElement).get(); // Only consider forms that GET data. // Allow HTTPS only when an input element is provided. if (equalIgnoringCase(formElement->getAttribute(methodAttr), "post") || (!IsHTTPFormSubmit(formElement.get()) && !inputElement)) return; Vector<char> encodedString; WTF::TextEncoding encoding; GetFormEncoding(formElement.get(), &encoding); if (!encoding.isValid()) { // Need a valid encoding to encode the form elements. // If the encoding isn't found webkit ends up replacing the params with // empty strings. So, we don't try to do anything here. return; } // Look for a suitable search text field in the form when a // selectedInputElement is not provided. if (!inputElement) { inputElement = findSuitableSearchInputElement(formElement.get()); // Return if no suitable text element has been found. if (!inputElement) return; } HTMLFormControlElement* firstSubmitButton = GetButtonToActivate(formElement.get()); if (firstSubmitButton) { // The form does not have an active submit button, make the first button // active. We need to do this, otherwise the URL will not contain the // name of the submit button. firstSubmitButton->setActivatedSubmit(true); } bool isValidSearchString = buildSearchString(formElement.get(), &encodedString, &encoding, inputElement); if (firstSubmitButton) firstSubmitButton->setActivatedSubmit(false); // Return if the search string is not valid. if (!isValidSearchString) return; String action(formElement->action()); KURL url(formElement->document().completeURL(action.isNull() ? "" : action)); RefPtr<FormData> formData = FormData::create(encodedString); url.setQuery(formData->flattenToString()); m_url = url; m_encoding = String(encoding.name()); } } // namespace blink
40.894558
146
0.684605
[ "vector" ]
b86dd2f025899500bd2375901f80d43633c29717
1,483
cpp
C++
exo/src/body.cpp
btheobald/compa2
aa9d5b966fb4c6a4e836e481d9df1bd297de3140
[ "MIT" ]
2
2016-02-11T20:01:26.000Z
2016-11-30T16:16:02.000Z
exo/src/body.cpp
btheobald/compa2
aa9d5b966fb4c6a4e836e481d9df1bd297de3140
[ "MIT" ]
null
null
null
exo/src/body.cpp
btheobald/compa2
aa9d5b966fb4c6a4e836e481d9df1bd297de3140
[ "MIT" ]
null
null
null
// Interface include #include "body.hpp" body::body() { // Creates a copy of body at pointer } body::body(body* p_b) { // Creates a copy of body at pointer // Copy contents of p_b to this object. *this = *p_b; } body::body(double p_m, double p_r, double p_pX, double p_pY, bool p_fixed) { // Mass m = p_m; // Radius r = p_r; // Position pX = p_pX; pY = p_pY; // Fixed fixed = p_fixed; } body::body(double p_m, double p_r, double p_pX, double p_pY, double p_vX, double p_vY) { // Mass m = p_m; // Radius r = p_r; // Position pX = p_pX; pY = p_pY; // Velocity vX = p_vX; vY = p_vY; } body::body(double p_m, double p_r, double p_pX, double p_pY, double p_vX, double p_vY, float p_color[3]) { // Mass m = p_m; // Radius r = p_r; // Position pX = p_pX; pY = p_pY; // Velocity vX = p_vX; vY = p_vY; // Color color[0] = p_color[0]; color[1] = p_color[1]; color[2] = p_color[2]; } body::~body() { } // Calculation Methods - Requires itteration delta time void body::calcPosition(double p_dt) { // ΔPosition = Velocity * ΔTime if(!fixed) { pX += vX * p_dt; pY += vY * p_dt; } } void body::calcHalfVelocity(double p_dt) { // (1/2)ΔVelocity = Acceleration * ΔTime * 0.5 if(!fixed) { vX += aX * p_dt * 0.5; vY += aY * p_dt * 0.5; } } double body::calcMomentum(int xy) { // p = mv if(xy) { // Y Component return m * vY; } else { // X Component return m * vX; } }
17.244186
106
0.578557
[ "object" ]
b8741bdb4a14d273586f4a986d74f340f3b7d931
111,530
hpp
C++
clicache/src/IRegion.hpp
rhoughton-pivot/geode-native
ab6fe7d996e5ec23832f90663d03f1d66b9f5fbd
[ "Apache-2.0" ]
48
2017-02-08T22:24:07.000Z
2022-02-06T02:47:56.000Z
clicache/src/IRegion.hpp
rhoughton-pivot/geode-native
ab6fe7d996e5ec23832f90663d03f1d66b9f5fbd
[ "Apache-2.0" ]
388
2017-02-13T17:09:45.000Z
2022-03-29T22:18:39.000Z
clicache/src/IRegion.hpp
rhoughton-pivot/geode-native
ab6fe7d996e5ec23832f90663d03f1d66b9f5fbd
[ "Apache-2.0" ]
68
2017-02-09T18:43:15.000Z
2022-03-14T22:59:13.000Z
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include "geode_defs.hpp" #include "begin_native.hpp" #include <geode/DataOutput.hpp> #include "end_native.hpp" #include "ISubscriptionService.hpp" using namespace System; using namespace System::Collections::Generic; namespace Apache { namespace Geode { namespace Client { ref class Cache; ref class CacheStatistics; interface class IRegionService; generic<class TResult> interface class ISelectResults; generic<class TKey, class TValue> ref class RegionEntry; generic<class TKey, class TValue> ref class RegionAttributes; generic<class TKey, class TValue> ref class AttributesMutator; /// <summary> /// Encapsulates a concrete region of cached data. /// Implements generic IDictionary<TKey, TValue> interface class. /// </summary> /// <remarks> /// This class manages subregions and cached data. Each region /// can contain multiple subregions and entries for data. /// Regions provide a hierachical name space /// within the cache. Also, a region can be used to group cached /// objects for management purposes. /// /// Entries managed by the region are key-value pairs. A set of region attributes /// is associated with the region when it is created. /// /// The IRegion interface basically contains two set of APIs: Region management /// APIs and (potentially) distributed operations on entries. Non-distributed /// operations on entries are provided by <c>RegionEntry</c>. /// /// Each <c>Cache</c> defines regions called the root regions. /// User applications can use the root regions to create subregions /// for isolated name spaces and object grouping. /// /// A region's name can be any string, except that it must not contain /// the region name separator, a forward slash (/). /// /// <c>Regions</c> can be referenced by a relative path name from any region /// higher in the hierarchy in <see cref="IRegion.GetSubRegion" />. You can get the relative /// path from the root region with <see cref="IRegion.FullPath" />. The name separator /// is used to concatenate all the region names together from the root, starting /// with the root's subregions. /// </remarks> /// <see cref="RegionAttributes" /> generic<class TKey, class TValue> public interface class IRegion : public System::Collections::Generic::IDictionary<TKey, TValue> { public: /// <summary> /// Gets or sets the element with the specified key. /// </summary> /// <remarks> /// This property provides the ability to access a specific element in the collection /// by using the following syntax: myCollection[key]. /// You can also use the Item property to add new elements by setting the value of a key /// that does not exist in the dictionary; for example, myCollection["myNonexistentKey"] = myValue /// However, if the specified key already exists in the dictionary, /// setting the Item property overwrites the old value. In contrast, /// the Add method does not modify existing elements. /// This property is applicable to local as well as distributed region. /// For local region instance - Puts/Gets a new value into an entry in this region in the local cache only. /// For distributed region instance - Puts/Gets a new value into an entry in this region /// and this operation is propogated to the Geode cache server to which it is connected. /// </remarks> /// <param name="key"> /// The key of the element to get or set. /// </param> /// <param name ="Property Value"> /// The element with the specified key. /// </param> /// <exception cref="IllegalArgumentException"> /// if key is null /// </exception> /// <exception cref="KeyNotFoundException"> /// If given key was not present in the region and if region is not in secure mode, or if Pool /// attached with Region is not in multiusersecure mode. /// </exception> /// <exception cref="EntryNotFoundException"> /// if given key's value is null. /// </exception> /// <exception cref="CacheWriterException"> /// if CacheWriter aborts the operation /// </exception> /// <exception cref="CacheListenerException"> /// if CacheListener throws an exception /// </exception> /// <exception cref="RegionDestroyedException"> /// if region has been destroyed /// </exception> /// <exception cref="CacheServerException"> /// If an exception is received from the Java cache server. /// Only for Native Client regions. /// </exception> /// <exception cref="NotConnectedException"> /// if not connected to the Geode system because the client cannot /// establish usable connections to any of the servers given to it. /// For pools configured with locators, if no locators are available, innerException /// of NotConnectedException is set to NoAvailableLocatorsException. /// </exception> /// <exception cref="TimeoutException"> /// if the operation timed out /// </exception> /// <exception cref="OutOfMemoryException"> /// if there is not enough memory for the value /// </exception> /// <exception cref="CacheLoaderException"> /// if CacheLoader throws an exception /// </exception> /// <exception cref="MessageException"> /// If the message received from server could not be handled. This will /// be the case when an unregistered typeId is received in the reply or /// reply is not well formed. More information can be found in the log. /// </exception> virtual property TValue default[TKey] { TValue get(TKey key); void set(TKey key, TValue value); } /// <summary> /// Returns an enumerator that iterates through the collection of the region entries. /// This operation is performed entirely in local cache. /// </summary> /// <remarks> /// The foreach statement of the C# language (for each in C++)hides the /// complexity of the enumerators. Therefore, using foreach is recommended, /// instead of directly manipulating the enumerator. /// Enumerators can be used to read the data in the collection, /// but they cannot be used to modify the underlying collection. /// Initially, the enumerator is positioned before the first element in the collection. /// At this position, Current is undefined. Therefore, you must call MoveNext to advance /// the enumerator to the first element of the collection before reading the value of Current. /// Current returns the same object until MoveNext is called. MoveNext sets Current to the next element. /// If MoveNext passes the end of the collection, the enumerator is positioned after the last element /// in the collection and MoveNext returns false. When the enumerator is at this position, subsequent /// calls to MoveNext also return false. If the last call to MoveNext returned false, Current is /// undefined. You cannot set Current to the first element of the collection again; you must create /// a new enumerator instance instead. /// The enumerator does not have exclusive access to the collection; therefore, enumerating through a /// collection is intrinsically not a thread-safe procedure. To guarantee thread safety during /// enumeration, you can lock the collection during the entire enumeration. To allow the collection /// to be accessed by multiple threads for reading and writing, you must implement your own /// synchronization. /// Default implementations of collections in the System.Collections.Generic namespace are not /// synchronized. /// For both local & distributed region instances, this operation is restricted to local cache only. /// </remarks> /// <exception cref="InvalidOperationException"> /// if enumerator is before or after the collection and Current method is called on it. /// </exception> /// <returns> /// Type: System.Collections.Generic.IEnumerator<T>. A IEnumerator<T> that /// can be used to iterate through the collection. /// </returns> virtual System::Collections::Generic::IEnumerator<KeyValuePair<TKey,TValue>>^ GetEnumerator(); /// <summary> /// Returns an enumerator that iterates through the collection of the region entries. /// This operation is performed entirely in local cache. /// </summary> /// <remarks> /// The foreach statement of the C# language (for each in C++)hides the /// complexity of the enumerators. Therefore, using foreach is recommended, /// instead of directly manipulating the enumerator. /// Enumerators can be used to read the data in the collection, /// but they cannot be used to modify the underlying collection. /// Initially, the enumerator is positioned before the first element in the collection. /// At this position, Current is undefined. Therefore, you must call MoveNext to advance /// the enumerator to the first element of the collection before reading the value of Current. /// Current returns the same object until MoveNext is called. MoveNext sets Current to the next element. /// If MoveNext passes the end of the collection, the enumerator is positioned after the last element /// in the collection and MoveNext returns false. When the enumerator is at this position, subsequent /// calls to MoveNext also return false. If the last call to MoveNext returned false, Current is /// undefined. You cannot set Current to the first element of the collection again; you must create /// a new enumerator instance instead. /// The enumerator does not have exclusive access to the collection; therefore, enumerating through a /// collection is intrinsically not a thread-safe procedure. To guarantee thread safety during /// enumeration, you can lock the collection during the entire enumeration. To allow the collection /// to be accessed by multiple threads for reading and writing, you must implement your own /// synchronization. /// For both local & distributed region instances, this operation is restricted to local cache only. /// </remarks> /// <exception cref="InvalidOperationException"> /// if enumerator is before or after the collection and Current method is called on it. /// </exception> /// <returns> /// Type: System.Collections.IEnumerator. An IEnumerator object that can be used to iterate /// through the collection. /// </returns> virtual System::Collections::IEnumerator^ GetEnumeratorOld() = System::Collections::IEnumerable::GetEnumerator; /// <summary> /// Determines whether the IDictionary contains an element with the specified key. /// </summary> /// <remarks> /// For local region instance - This only searches in the local cache. /// For distributed region instance - checks to see if the key is present on the server. /// </remarks> /// <param name="key"> /// The key to locate in the IDictionary. /// </param> /// <exception cref="ArgumentNullException"> /// key is a null reference /// </exception> /// <returns> /// true if the IDictionary contains an element with the key; otherwise, false. /// </returns> virtual bool ContainsKey(TKey key); /// <summary> /// Adds an element with the provided key and value to the IDictionary. /// </summary> /// <remark> /// You can also use the Item property to add new elements by setting the value of a key /// that does not exist in the dictionary; for example, myCollection["myNonexistentKey"] = myValue /// However, if the specified key already exists in the dictionary, setting the Item property /// overwrites the old value. In contrast, the Add method does not modify existing elements. /// </remark> /// <remarks> /// <para> /// If remote server put fails throwing back a <c>CacheServerException</c> /// or security exception, then local put is tried to rollback. However, /// if the entry has overflowed/evicted/expired then the rollback is /// aborted since it may be due to a more recent notification or update /// by another thread. /// </para> /// <para> /// For local region instance - creates a new entry in this region with the specified keyvaluepair /// in the local cache only. /// For distributed region instance - The new entry is propogated to the java server to which it is /// connected with. /// </para> /// </remarks> /// <param name="key"> /// The object to use as the key of the element to add. /// </param> /// <param name="value"> /// The object to use as the value of the element to add. /// </param> /// <exception cref="IllegalArgumentException"> /// if key is null /// </exception> /// <exception cref="EntryExistsException"> /// if an entry with this key already exists /// </exception> /// <exception cref="CacheWriterException"> /// if CacheWriter aborts the operation /// </exception> /// <exception cref="CacheListenerException"> /// if CacheListener throws an exception /// </exception> /// <exception cref="CacheServerException"> /// If an exception is received from the Java cache server. /// Only for Native Client regions. /// </exception> /// <exception cref="NotConnectedException"> /// if not connected to a Geode system because the client cannot /// establish usable connections to any of the servers given to it. /// For pools configured with locators, if no locators are available, innerException /// of NotConnectedException is set to NoAvailableLocatorsException. /// </exception> /// <exception cref="RegionDestroyedException"> /// if region has been destroyed /// </exception> /// <exception cref="TimeoutException"> /// if the operation timed out /// </exception> /// <exception cref="OutOfMemoryException"> /// if there is not enough memory for the new entry /// </exception> virtual void Add(TKey key, TValue value); /// <summary> /// Adds an item to the ICollection<T>. /// </summary> /// <remarks> /// <para> /// If remote server put fails throwing back a <c>CacheServerException</c> /// or security exception, then local put is tried to rollback. However, /// if the entry has overflowed/evicted/expired then the rollback is /// aborted since it may be due to a more recent notification or update /// by another thread. /// </para> /// <para> /// For local region instance - creates a new entry in this region with the specified keyvaluepair /// in the local cache only. /// For distributed region instance - The new entry is propogated to the java server to which it is /// connected with. /// </para> /// </remarks> /// <param name="keyValuePair"> /// Type: KeyValuePair<TKey, TValue> The object to add to the ICollection<T>. /// </param> /// <exception cref="IllegalArgumentException"> /// if key is null /// </exception> /// <exception cref="EntryExistsException"> /// if an entry with this key already exists /// </exception> /// <exception cref="CacheWriterException"> /// if CacheWriter aborts the operation /// </exception> /// <exception cref="CacheListenerException"> /// if CacheListener throws an exception /// </exception> /// <exception cref="CacheServerException"> /// If an exception is received from the Java cache server. /// Only for Native Client regions. /// </exception> /// <exception cref="NotConnectedException"> /// if not connected to a Geode system because the client cannot /// establish usable connections to any of the servers given to it. /// For pools configured with locators, if no locators are available, innerException /// of NotConnectedException is set to NoAvailableLocatorsException. /// </exception> /// <exception cref="RegionDestroyedException"> /// if region has been destroyed /// </exception> /// <exception cref="TimeoutException"> /// if the operation timed out /// </exception> /// <exception cref="OutOfMemoryException"> /// if there is not enough memory for the new entry /// </exception> virtual void Add(KeyValuePair<TKey, TValue> keyValuePair); /// <summary> /// Creates a new entry in this region with the specified key and value, /// passing the callback argument to any cache writers and cache listeners /// that are invoked in the operation. /// </summary> /// <remarks> /// <para> /// Updates the <see cref="CacheStatistics.LastAccessedTime" /> and /// <see cref="CacheStatistics.LastModifiedTime" /> for this region /// and the entry. /// </para> /// <para> /// For local region instance - creates a new entry in this region with the specified key and value /// in the local cache only. /// For distributed region instance - The new entry is propogated to the java server to which it is /// connected with. /// </para><para> /// If remote server put fails throwing back a <c>CacheServerException</c> /// or security exception, then local put is tried to rollback. However, /// if the entry has overflowed/evicted/expired then the rollback is /// aborted since it may be due to a more recent notification or update /// by another thread. /// </para> /// </remarks> /// <param name="key"> /// The key for which to create the entry in this region. The object is /// created before the call, and the caller should not deallocate the object. /// </param> /// <param name="value"> /// The value for the new entry, which may be null to indicate that the new /// entry starts as if it had been locally invalidated. /// </param> /// <param name="callbackArg"> /// a custome parameter to pass to the cache writer or cache listener /// </param> /// <exception cref="IllegalArgumentException"> /// if key is null /// </exception> /// <exception cref="EntryExistsException"> /// if an entry with this key already exists /// </exception> /// <exception cref="CacheWriterException"> /// if CacheWriter aborts the operation /// </exception> /// <exception cref="CacheListenerException"> /// if CacheListener throws an exception /// </exception> /// <exception cref="CacheServerException"> /// If an exception is received from the Java cache server. /// Only for Native Client regions. /// </exception> /// <exception cref="NotConnectedException"> /// if not connected to a Geode system because the client cannot /// establish usable connections to any of the servers given to it. /// For pools configured with locators, if no locators are available, innerException /// of NotConnectedException is set to NoAvailableLocatorsException. /// </exception> /// <exception cref="RegionDestroyedException"> /// if region has been destroyed /// </exception> /// <exception cref="TimeoutException"> /// if the operation timed out /// </exception> /// <exception cref="OutOfMemoryException"> /// if there is not enough memory for the new entry /// </exception> /// <seealso cref="Put" /> /// <seealso cref="Get" /> void Add(TKey key, TValue value, Object^ callbackArg); /// <summary> /// Removes the element with the specified key from the IDictionary. /// </summary> /// <remarks> /// For local region instance - removes the entry with the specified key from the local cache only. /// For distributed region instance - remove is propogated to the Geode cache server. /// </remarks> /// <param name="key"> /// The key of the element to remove. /// </param> /// <exception cref="IllegalArgumentException">if key is null</exception> /// <exception cref="EntryNotFoundException"> /// if the entry does not exist in this region locally, applicable only for local region instance. /// </exception> /// <exception cref="CacheServerException"> /// If an exception is received from the Java cache server. /// Only for Native Client regions. /// </exception> /// <exception cref="NotConnectedException"> /// if not connected to the Geode system because the client cannot /// establish usable connections to any of the servers given to it. /// For pools configured with locators, if no locators are available, innerException /// of NotConnectedException is set to NoAvailableLocatorsException. /// </exception> /// <exception cref="TimeoutException"> /// if the operation timed out /// </exception> /// <exception cref="RegionDestroyedException"> /// if this region has been destroyed /// </exception> /// <returns> /// true if the element is successfully removed; otherwise, false. /// This method also returns false if key was not found in the original IDictionary. /// </returns> virtual bool Remove(TKey key); /// <summary> /// Removes the entry with the specified key, passing the callback /// argument to any cache writers that are invoked in the operation. /// </summary> /// <remarks> /// <para> /// Removes not only the value, but also the key and entry /// from this region. /// </para> /// <para> /// For local region instance - removes the value with the specified key in the local cache only. /// For distributed region instance - destroy is propogated to the Geode cache server /// to which it is connected. /// </para> /// <para> /// Does not update any <c>CacheStatistics</c>. /// </para> /// </remarks> /// <param name="key">the key of the entry to destroy</param> /// <param name="callbackArg"> /// a user-defined parameter to pass to cache writers triggered by this method /// </param> /// <exception cref="IllegalArgumentException">if key is null</exception> /// <exception cref="CacheServerException"> /// If an exception is received from the Java cache server. /// Only for Native Client regions. /// </exception> /// <exception cref="NotConnectedException"> /// if not connected to the Geode system because the client cannot /// establish usable connections to any of the servers given to it. /// For pools configured with locators, if no locators are available, innerException /// of NotConnectedException is set to NoAvailableLocatorsException. /// </exception> /// <exception cref="TimeoutException"> /// if the operation timed out /// </exception> /// <exception cref="RegionDestroyedException"> /// if this region has been destroyed /// </exception> /// <seealso cref="Invalidate" /> /// <seealso cref="ICacheListener.AfterDestroy" /> /// <seealso cref="ICacheWriter.BeforeDestroy" /> /// <returns> /// true if the element is successfully removed; otherwise, false. /// This method also returns false if key was not found in the original IDictionary. /// </returns> bool Remove( TKey key, Object^ callbackArg ); /// <summary> /// Gets the value associated with the specified key. /// </summary> /// <remark> /// This method combines the functionality of the ContainsKey method and the Item property. /// If the key is not found, then the value parameter gets the appropriate default value for the value /// type V; for example, zero (0) for integer types, false for Boolean types, and a null reference for /// reference types. /// For local region instance - returns the value with the specified key from the local cache only. /// For distributed region instance - If the value is not present locally then it is requested from /// the java server. If even that is unsuccessful then a local CacheLoader will be invoked /// if there is one. /// </remark> /// <param name="key"> /// The key whose value to get. /// </param> /// <param name="value">When this method returns, the value associated with the specified key, if the key is /// found; otherwise, the default value for the type of the value parameter. /// This parameter is passed uninitialized.</param> /// <exception cref="IllegalArgumentException"> /// if key is null /// </exception> /// <exception cref="CacheLoaderException"> /// if CacheLoader throws an exception /// </exception> /// <exception cref="CacheServerException"> /// If an exception is received from the Java cache server. /// Only for Native Client regions. /// </exception> /// <exception cref="NotConnectedException"> /// if not connected to the Geode system because the client cannot /// establish usable connections to any of the servers given to it. /// For pools configured with locators, if no locators are available, innerException /// of NotConnectedException is set to NoAvailableLocatorsException. /// </exception> /// <exception cref="MessageException"> /// If the message received from server could not be handled. This will /// be the case when an unregistered typeId is received in the reply or /// reply is not well formed. More information can be found in the log. /// </exception> /// <exception cref="TimeoutException"> /// if the operation timed out /// </exception> /// <exception cref="RegionDestroyedException"> /// if this region has been destroyed /// </exception> /// <returns> /// true if the object that implements IDictionary contains an element with the specified key; otherwise, false. /// </returns> virtual bool TryGetValue(TKey key, TValue %value); /// <summary> /// Determines whether the ICollection contains a specific value. /// </summary> /// <remarks> /// <para> /// For local region instance - returns the value with the specified key from the local cache only. /// For distributed region instance - If the value is not present locally then it is requested from /// the java server. If even that is unsuccessful then a local CacheLoader will be invoked /// if there is one. /// </para> /// <para> /// The comparison of the value of the key value pair depends on the Equals function of the TValue class. /// If the Equals function is not overriden in the TValue class the behavior of this function is undefined. Hence, this /// function won't work properly for the .NET types that uses the default implementation of the Equals method, for /// e.g. arrays. /// </para> /// </remarks> /// <param name="keyValuePair"> /// The KeyValuePair structure to locate in the ICollection. /// </param> /// <exception cref="IllegalArgumentException"> /// if key is null /// </exception> /// <exception cref="CacheLoaderException"> /// if CacheLoader throws an exception /// </exception> /// <exception cref="CacheServerException"> /// If an exception is received from the Java cache server. /// Only for Native Client regions. /// </exception> /// <exception cref="NotConnectedException"> /// if not connected to the Geode system because the client cannot /// establish usable connections to any of the servers given to it. /// For pools configured with locators, if no locators are available, innerException /// of NotConnectedException is set to NoAvailableLocatorsException. /// </exception> /// <exception cref="MessageException"> /// If the message received from server could not be handled. This will /// be the case when an unregistered typeId is received in the reply or /// reply is not well formed. More information can be found in the log. /// </exception> /// <exception cref="TimeoutException"> /// if the operation timed out /// </exception> /// <exception cref="RegionDestroyedException"> /// if this region has been destroyed /// </exception> /// <returns> /// true if keyValuePair is found in the ICollection; otherwise, false. /// </returns> virtual bool Contains(KeyValuePair<TKey,TValue> keyValuePair); /// <summary> /// Removes all items from the ICollection<T>. /// remove all entries in the region. /// </summary> /// For local region instance - remove all entries in the local region. /// For distributed region instance - remove all entries in the local region, /// and propagate the operation to server. virtual void Clear(); /// <summary> /// remove all entries in the region. /// For local region instance - remove all entries in the local region. /// For distributed region instance - remove all entries in the local region, /// and propagate the operation to server. /// </summary> /// <param name="callbackArg"> /// argument that is passed to the callback functions /// </param> void Clear(Object^ callbackArg); /// <summary> /// Copies the elements of the ICollection to an Array, starting at a particular Array index. /// This operation copies entries from local region only. /// </summary> /// <param name="toArray"> /// The one-dimensional Array that is the destination of the elements copied from ICollection. /// The Array must have zero-based indexing. /// </param> /// <param name="startIdx"> /// The zero-based index in array at which copying begins. /// </param> /// <exception cref="ArgumentNullException"> /// if toArray is a null reference /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// if startIdx is less than 0. /// </exception> /// <exception cref="ArgumentException"> /// if toArray is multidimensional or The number of elements in the source ICollection is greater than /// the available space from startIdx to the end of the destination array or startIdx is equal to /// or greater than the length of array. /// </exception> virtual void CopyTo(array<KeyValuePair<TKey,TValue>>^ toArray, int startIdx); /// <summary> /// Removes a key and value from the dictionary. /// </summary> /// <remarks> /// <para> /// Remove removes not only the value, but also the key and entry /// from this region. /// </para> /// <para> /// The Remove is propogated to the Geode cache server to which it is connected. /// </para> /// <para> /// Does not update any <c>CacheStatistics</c>. /// </para> /// <para> /// The comparison of the value of the key value pair depends on the Equals function of the TValue class. /// If the Equals function is not overriden in the TValue class the behavior of this function is undefined. Hence, this /// function won't work properly for the .NET types that uses the default implementation of the Equals method, for /// e.g. arrays. /// </para> /// </remarks> /// <param name="keyValuePair">The KeyValuePair structure representing /// the key and value to remove from the Dictionary.</param> /// <exception cref="CacheServerException"> /// If an exception is received from the Java cache server. /// Only for Native Client regions. /// </exception> /// <exception cref="NotConnectedException"> /// if not connected to the Geode system because the client cannot /// establish usable connections to any of the servers given to it. /// For pools configured with locators, if no locators are available, innerException /// of NotConnectedException is set to NoAvailableLocatorsException. /// </exception> /// <exception cref="TimeoutException"> /// if the operation timed out /// </exception> /// <exception cref="RegionDestroyedException"> /// if this region has been destroyed /// </exception> /// <returns>true if the key and value represented by keyValuePair is successfully found and removed; /// otherwise, false. This method returns false if keyValuePair is not found in the ICollection.</returns> /// <returns>true if entry with key and its value are removed otherwise false.</returns> /// <seealso cref="Invalidate" /> /// <seealso cref="ICacheListener.AfterDestroy" /> /// <seealso cref="ICacheWriter.BeforeDestroy" /> virtual bool Remove(KeyValuePair<TKey,TValue> keyValuePair); /// <summary> /// Removes the entry with the specified key and value, passing the callback /// argument to any cache writers that are invoked in the operation. /// </summary> /// <remarks> /// <para> /// Remove removes not only the value, but also the key and entry /// from this region. /// </para> /// <para> /// The Remove is propogated to the Geode cache server to which it is connected. /// </para> /// <para> /// Does not update any <c>CacheStatistics</c>. /// </para> /// </remarks> /// <param name="key">the key of the entry to Remove</param> /// <param name="value">the value of the entry to Remove</param> /// <param name="callbackArg"> the callback for user to pass in, It can also be null</param>. /// <exception cref="IllegalArgumentException">if key is null</exception> /// <exception cref="CacheServerException"> /// If an exception is received from the Java cache server. /// Only for Native Client regions. /// </exception> /// <exception cref="NotConnectedException"> /// if not connected to the Geode system because the client cannot /// establish usable connections to any of the servers given to it. /// For pools configured with locators, if no locators are available, innerException /// of NotConnectedException is set to NoAvailableLocatorsException. /// </exception> /// <exception cref="TimeoutException"> /// if the operation timed out /// </exception> /// <exception cref="RegionDestroyedException"> /// if this region has been destroyed /// </exception> /// <returns>true if entry with key and its value are removed otherwise false.</returns> /// <seealso cref="Invalidate" /> /// <seealso cref="ICacheListener.AfterDestroy" /> /// <seealso cref="ICacheWriter.BeforeDestroy" /> virtual bool Remove(TKey key, TValue value, Object^ callbackArg ); /// <summary> /// Gets the number of elements contained in the ICollection<T>. /// Get the size of region. For native client regions, this will give /// the number of entries in the local cache and not on the servers. /// </summary> /// <returns>number of entries in the region</returns> virtual property int Count { int get(); } /// <summary> /// This property throws NotImplementedException when called by /// both local and distributed region instances. /// </summary> virtual property bool IsReadOnly { bool get(); } /// <summary> /// Gets an ICollection containing the keys of the IDictionary /// Returns all the keys for this region. This includes /// keys for which the entry is invalid. /// For local region instance - gets collection of keys from local cache only. /// For distributed region instance - gets collection of keys from the Geode cache server. /// </summary> /// <returns>collection of keys</returns> /// <remark> /// The order of the keys in the returned ICollection is unspecified, /// but it is guaranteed to be the same order as the corresponding values in the ICollection /// returned by the Values property. /// </remark> /// <exception cref="UnsupportedOperationException"> /// if the member type is not <c>Client</c> /// or region is not a Native Client region. /// </exception> /// <exception cref="CacheServerException"> /// If an exception is received from the Java cache server. /// Only for Native Client regions. /// </exception> /// <exception cref="NotConnectedException"> /// if not connected to the Geode system because the client cannot /// establish usable connections to any of the servers given to it. /// For pools configured with locators, if no locators are available, innerException /// of NotConnectedException is set to NoAvailableLocatorsException. /// </exception> /// <exception cref="MessageException"> /// If the message received from server could not be handled. This will /// be the case when an unregistered typeId is received in the reply or /// reply is not well formed. More information can be found in the log. /// </exception> /// <exception cref="TimeoutException"> /// if there is a timeout getting the keys /// </exception> virtual property System::Collections::Generic::ICollection<TKey>^ Keys { System::Collections::Generic::ICollection<TKey>^ get() ; } /// <summary> /// Gets an ICollection containing the values in the IDictionary. /// Returns all values in the local process for this region. No value is included /// for entries that are invalidated. /// For both local & distributed region instances, this operation is always local only. /// </summary> /// <returns>collection of values</returns> /// <remark> /// The order of the values in the returned ICollection is unspecified, /// but it is guaranteed to be the same order as the corresponding keys in the ICollection /// returned by the Keys property. /// </remark> virtual property System::Collections::Generic::ICollection<TValue>^ Values { System::Collections::Generic::ICollection<TValue>^ get() ; } /// <summary> /// Puts a new value into an entry in this region with the specified key, /// passing the callback argument to any cache writers and cache listeners /// that are invoked in the operation. /// </summary> /// <remarks> /// <para> /// If there is already an entry associated with the specified key in /// this region, the entry's previous value is overwritten. /// The new put value is propogated to the java server to which it is connected. /// Put is intended for very simple caching situations. In general /// it is better to create a <c>ICacheLoader</c> object and allow the /// cache to manage the creation and loading of objects. /// For local region instance - Puts a new value into an entry in this region in the local cache only. /// For distributed region instance - Puts a new value into an entry in this region /// and this operation is propogated to the Geode cache server to which it is connected. /// </para><para> /// Updates the <see cref="CacheStatistics.LastAccessedTime" /> and /// <see cref="CacheStatistics.LastModifiedTime" /> for this region and the entry. /// </para><para> /// If remote server put fails throwing back a <c>CacheServerException</c> /// or security exception, then local put is tried to rollback. However, /// if the entry has overflowed/evicted/expired then the rollback is /// aborted since it may be due to a more recent notification or update /// by another thread. /// </para> /// </remarks> /// <param name="key"> /// a key object associated with the value to be put into this region. /// </param> /// <param name="value">the value to be put into this region</param> /// <param name="callbackArg"> /// argument that is passed to the callback functions /// </param> /// <exception cref="IllegalArgumentException"> /// if key is null /// </exception> /// <exception cref="CacheWriterException"> /// if CacheWriter aborts the operation /// </exception> /// <exception cref="CacheListenerException"> /// if CacheListener throws an exception /// </exception> /// <exception cref="RegionDestroyedException"> /// if region has been destroyed /// </exception> /// <exception cref="CacheServerException"> /// If an exception is received from the Java cache server. /// Only for Native Client regions. /// </exception> /// <exception cref="NotConnectedException"> /// if not connected to the Geode system because the client cannot /// establish usable connections to any of the servers given to it. /// For pools configured with locators, if no locators are available, innerException /// of NotConnectedException is set to NoAvailableLocatorsException. /// </exception> /// <exception cref="TimeoutException"> /// if the operation timed out /// </exception> /// <exception cref="OutOfMemoryException"> /// if there is not enough memory for the value /// </exception> /// <seealso cref="Get" /> /// <seealso cref="Add" /> void Put(TKey key, TValue value, Object^ callbackArg); /// <summary> /// Puts a new value into an entry in this region with the specified key. /// </summary> /// <remarks> /// <para> /// If there is already an entry associated with the specified key in /// this region, the entry's previous value is overwritten. /// The new put value is propogated to the java server to which it is connected. /// Put is intended for very simple caching situations. In general /// it is better to create a <c>ICacheLoader</c> object and allow the /// cache to manage the creation and loading of objects. /// For local region instance - Puts a new value into an entry in this region in the local cache only. /// For distributed region instance - Puts a new value into an entry in this region /// and this operation is propogated to the Geode cache server to which it is connected. /// </para><para> /// Updates the <see cref="CacheStatistics.LastAccessedTime" /> and /// <see cref="CacheStatistics.LastModifiedTime" /> for this region and the entry. /// </para><para> /// If remote server put fails throwing back a <c>CacheServerException</c> /// or security exception, then local put is tried to rollback. However, /// if the entry has overflowed/evicted/expired then the rollback is /// aborted since it may be due to a more recent notification or update /// by another thread. /// </para> /// </remarks> /// <param name="key"> /// a key object associated with the value to be put into this region /// </param> /// <param name="value">the value to be put into this region</param> /// <exception cref="IllegalArgumentException"> /// if key is null /// </exception> /// <exception cref="CacheWriterException"> /// if CacheWriter aborts the operation /// </exception> /// <exception cref="CacheListenerException"> /// if CacheListener throws an exception /// </exception> /// <exception cref="RegionDestroyedException"> /// if region has been destroyed /// </exception> /// <exception cref="CacheServerException"> /// If an exception is received from the Java cache server. /// Only for Native Client regions. /// </exception> /// <exception cref="NotConnectedException"> /// if not connected to the Geode system because the client cannot /// establish usable connections to any of the servers given to it. /// For pools configured with locators, if no locators are available, innerException /// of NotConnectedException is set to NoAvailableLocatorsException. /// </exception> /// <exception cref="TimeoutException"> /// if the operation timed out /// </exception> /// <exception cref="OutOfMemoryException"> /// if there is not enough memory for the value /// </exception> /// <seealso cref="Get" /> /// <seealso cref="Add" /> void Put(TKey key, TValue value); /// <summary> /// Returns the value for the given key, passing the callback argument /// to any cache loaders or that are invoked in the operation. /// </summary> /// <remarks> /// <para> /// For local region instance - returns the value with the specified key from the local cache only. /// For distributed region instance - If the value is not present locally then it is requested from /// the java server. If even that is unsuccessful then a local CacheLoader will be invoked /// if there is one. /// </para> /// <para> /// The value returned by get is not copied, so multi-threaded applications /// should not modify the value directly, but should use the update methods. /// </para><para> /// Updates the <see cref="CacheStatistics.LastAccessedTime" /> /// <see cref="CacheStatistics.HitCount" />, <see cref="CacheStatistics.MissCount" />, /// and <see cref="CacheStatistics.LastModifiedTime" /> (if a new value is loaded) /// for this region and the entry. /// </para> /// </remarks> /// <param name="key"> /// key whose associated value is to be returned -- the key /// object must implement the Equals and GetHashCode methods. /// </param> /// <param name="callbackArg"> /// An argument passed into the CacheLoader if loader is used. /// Has to be Serializable (i.e. implement <c>ISerializable</c>); /// can be null. /// </param> /// <returns> /// value, or null if the value is not found and can't be loaded /// </returns> /// <exception cref="IllegalArgumentException"> /// if key is null /// </exception> /// <exception cref="CacheLoaderException"> /// if CacheLoader throws an exception /// </exception> /// <exception cref="CacheServerException"> /// If an exception is received from the Java cache server. /// Only for Native Client regions. /// </exception> /// <exception cref="NotConnectedException"> /// if not connected to the Geode system because the client cannot /// establish usable connections to any of the servers given to it. /// For pools configured with locators, if no locators are available, innerException /// of NotConnectedException is set to NoAvailableLocatorsException. /// </exception> /// <exception cref="MessageException"> /// If the message received from server could not be handled. This will /// be the case when an unregistered typeId is received in the reply or /// reply is not well formed. More information can be found in the log. /// </exception> /// <exception cref="TimeoutException"> /// if the operation timed out /// </exception> /// <exception cref="RegionDestroyedException"> /// if this region has been destroyed /// </exception> /// <seealso cref="Put" /> TValue Get(TKey key, Object^ callbackArg); /// <summary> /// Returns the value for the given key, passing the callback argument /// to any cache loaders or that are invoked in the operation. /// </summary> /// <remarks> /// <para> /// For local region instance - returns the value with the specified key from the local cache only. /// For distributed region instance - If the value is not present locally then it is requested from /// the java server. If even that is unsuccessful then a local CacheLoader will be invoked /// if there is one. /// </para> /// <para> /// The value returned by get is not copied, so multi-threaded applications /// should not modify the value directly, but should use the update methods. /// </para><para> /// Updates the <see cref="CacheStatistics.LastAccessedTime" /> /// <see cref="CacheStatistics.HitCount" />, <see cref="CacheStatistics.MissCount" />, /// and <see cref="CacheStatistics.LastModifiedTime" /> (if a new value is loaded) /// for this region and the entry. /// </para> /// </remarks> /// <param name="key"> /// key whose associated value is to be returned -- the key /// object must implement the Equals and GetHashCode methods. /// </param> /// <returns> /// value, or null if the value is not found and can't be loaded /// </returns> /// <exception cref="IllegalArgumentException"> /// if key is null /// </exception> /// <exception cref="CacheLoaderException"> /// if CacheLoader throws an exception /// </exception> /// <exception cref="CacheServerException"> /// If an exception is received from the Java cache server. /// Only for Native Client regions. /// </exception> /// <exception cref="NotConnectedException"> /// if not connected to the Geode system because the client cannot /// establish usable connections to any of the servers given to it. /// For pools configured with locators, if no locators are available, innerException /// of NotConnectedException is set to NoAvailableLocatorsException. /// </exception> /// <exception cref="MessageException"> /// If the message received from server could not be handled. This will /// be the case when an unregistered typeId is received in the reply or /// reply is not well formed. More information can be found in the log. /// </exception> /// <exception cref="TimeoutException"> /// if the operation timed out /// </exception> /// <exception cref="RegionDestroyedException"> /// if this region has been destroyed /// </exception> /// <seealso cref="Put" /> TValue Get(TKey key); /// <summary> /// Invalidates this region. /// </summary> /// <remarks> /// <para> /// The invalidation will cascade to all the subregions and cached /// entries. The region /// and the entries in it will still exist. /// For local region instance - invalidates this region without distributing to other caches. /// For distributed region instance - Invalidates this region and this /// operation is propogated to the Geode cache server to which it is connected. /// </para> /// <para> /// To remove all the /// entries and the region, use <see cref="DestroyRegion" />. /// </para><para> /// Does not update any <c>CacheStatistics</c>. /// </para> /// </remarks> /// <exception cref="CacheListenerException"> /// if CacheListener throws an exception; if this occurs some /// subregions may have already been successfully invalidated /// </exception> /// <exception cref="NotConnectedException"> /// if not connected to the Geode system because the client cannot /// establish usable connections to any of the servers given to it. /// For pools configured with locators, if no locators are available, innerException /// of NotConnectedException is set to NoAvailableLocatorsException. /// </exception> /// <exception cref="RegionDestroyedException"> /// if this region has been destroyed /// </exception> /// <seealso cref="DestroyRegion" /> /// <seealso cref="ICacheListener.AfterRegionInvalidate" /> void InvalidateRegion(); /// <summary> /// Invalidates this region. /// </summary> /// <remarks> /// <para> /// The invalidation will cascade to all the subregions and cached /// entries. The region /// and the entries in it will still exist. /// For local region instance - invalidates this region without distributing to other caches. /// For distributed region instance - Invalidates this region and this /// operation is propogated to the Geode cache server to which it is connected. /// </para> /// <para> /// To remove all the /// entries and the region, use <see cref="DestroyRegion" />. /// </para><para> /// Does not update any <c>CacheStatistics</c>. /// </para> /// </remarks> /// <param name="callbackArg"> /// user-defined parameter to pass to callback events triggered by this method /// </param> /// <exception cref="NotConnectedException"> /// if not connected to the Geode system because the client cannot /// establish usable connections to any of the servers given to it. /// For pools configured with locators, if no locators are available, innerException /// of NotConnectedException is set to NoAvailableLocatorsException. /// </exception> /// <exception cref="RegionDestroyedException"> /// if this region has been destroyed /// </exception> /// <exception cref="CacheListenerException"> /// if CacheListener throws an exception; if this occurs some /// subregions may have already been successfully invalidated /// </exception> /// <seealso cref="DestroyRegion" /> /// <seealso cref="ICacheListener.AfterRegionInvalidate" /> void InvalidateRegion(Object^ callbackArg); /// <summary> /// Destroys the whole distributed region and provides a user-defined parameter /// object to any <c>ICacheWriter</c> invoked in the process. /// </summary> /// <remarks> /// <para> /// Destroy cascades to all entries and subregions. After the destroy, /// this region object can not be used any more. Any attempt to use /// this region object will get a <c>RegionDestroyedException</c> /// The region destroy not only destroys the local region but also destroys the /// server region. /// For local region instance - destroys the whole local region only /// For distributed region instance - destroys the whole local region and this /// operation is also propogated to the Geode cache server to which it is connected. /// </para><para> /// Does not update any <c>CacheStatistics</c>. /// </para> /// </remarks> /// <exception cref="CacheWriterException"> /// if a CacheWriter aborts the operation; if this occurs some /// subregions may have already been successfully destroyed. /// </exception> /// <exception cref="CacheListenerException"> /// if CacheListener throws an exception; if this occurs some /// subregions may have already been successfully invalidated /// </exception> /// <exception cref="CacheServerException"> /// If an exception is received from the Java cache server. /// Only for Native Client regions. /// </exception> /// <exception cref="NotConnectedException"> /// if not connected to the Geode system because the client cannot /// establish usable connections to any of the servers given to it. /// For pools configured with locators, if no locators are available, innerException /// of NotConnectedException is set to NoAvailableLocatorsException. /// </exception> /// <exception cref="TimeoutException"> /// if the operation timed out /// </exception> /// <seealso cref="InvalidateRegion" /> void DestroyRegion(); /// <summary> /// Destroys the whole distributed region and provides a user-defined parameter /// object to any <c>ICacheWriter</c> invoked in the process. /// </summary> /// <remarks> /// <para> /// Destroy cascades to all entries and subregions. After the destroy, /// this region object can not be used any more. Any attempt to use /// this region object will get a <c>RegionDestroyedException</c> /// The region destroy not only destroys the local region but also destroys the /// server region. /// For local region instance - destroys the whole local region only /// For distributed region instance - destroys the whole local region and this /// operation is also propogated to the Geode cache server to which it is connected. /// </para><para> /// Does not update any <c>CacheStatistics</c>. /// </para> /// </remarks> /// <param name="callbackArg"> /// a user-defined parameter to pass to callback events triggered by this call /// </param> /// <exception cref="CacheWriterException"> /// if a CacheWriter aborts the operation; if this occurs some /// subregions may have already been successfully destroyed. /// </exception> /// <exception cref="CacheListenerException"> /// if CacheListener throws an exception; if this occurs some /// subregions may have already been successfully invalidated /// </exception> /// <exception cref="CacheServerException"> /// If an exception is received from the Java cache server. /// Only for Native Client regions. /// </exception> /// <exception cref="NotConnectedException"> /// if not connected to the Geode system because the client cannot /// establish usable connections to any of the servers given to it. /// For pools configured with locators, if no locators are available, innerException /// of NotConnectedException is set to NoAvailableLocatorsException. /// </exception> /// <exception cref="TimeoutException"> /// if the operation timed out /// </exception> /// <seealso cref="InvalidateRegion" /> void DestroyRegion(Object^ callbackArg); /// <summary> /// Invalidates the entry with the specified key, /// passing the callback argument /// to any cache /// listeners that are invoked in the operation. /// </summary> /// <remarks> /// <para> /// Invalidate only removes the value from the entry -- the key is kept intact. /// To completely remove the entry, call <see cref="Destroy" />. /// </para> /// <para> /// For both local & distributed region instaces, invalidate is not propogated to the /// Geode cache server to which it is connected. /// </para> /// <para> /// Does not update any <c>CacheStatistics</c>. /// </para> /// </remarks> /// <param name="key">key of the value to be invalidated</param> /// <exception cref="IllegalArgumentException">if key is null</exception> /// <exception cref="EntryNotFoundException"> /// if this entry does not exist in this region locally /// </exception> /// <exception cref="RegionDestroyedException"> /// if the region is destroyed /// </exception> /// <seealso cref="Destroy" /> /// <seealso cref="ICacheListener.AfterInvalidate" /> void Invalidate(TKey key); /// <summary> /// Invalidates the entry with the specified key, /// passing the callback argument /// to any cache /// listeners that are invoked in the operation. /// </summary> /// <remarks> /// <para> /// Invalidate only removes the value from the entry -- the key is kept intact. /// To completely remove the entry, call <see cref="Destroy" />. /// </para> /// <para> /// For both local & distributed region instaces, invalidate is not propogated to the /// Geode cache server to which it is connected. /// </para> /// <para> /// Does not update any <c>CacheStatistics</c>. /// </para> /// </remarks> /// <param name="key">key of the value to be invalidated</param> /// <param name="callbackArg"> /// a user-defined parameter to pass to callback events triggered by this method /// </param> /// <exception cref="IllegalArgumentException">if key is null</exception> /// <exception cref="EntryNotFoundException"> /// if this entry does not exist in this region locally /// </exception> /// <exception cref="RegionDestroyedException"> /// if the region is destroyed /// </exception> /// <seealso cref="Destroy" /> /// <seealso cref="ICacheListener.AfterInvalidate" /> void Invalidate(TKey key, Object^ callbackArg); /// <summary> /// Puts a (IDictionary) generic collection of key/value pairs in this region. /// </summary> /// <remarks> /// <para> /// If there is already an entry associated with any key in the map in /// this region, the entry's previous value is overwritten. /// The new values are propogated to the java server to which it is connected. /// PutAll is intended for speed up large amount of put operation into /// the same region. /// For local region instance - this method is not applicable. /// </para> /// </remarks> /// <param name="map"> /// A map contains entries, i.e. (key, value) pairs. It is generic collection of key/value pairs. /// Value should not be null in any of the entries. /// </param> /// <exception cref="NullPointerException"> /// if any value in the map is null /// </exception> /// <exception cref="RegionDestroyedException"> /// if region has been destroyed /// </exception> /// <exception cref="CacheServerException"> /// If an exception is received from the Java cache server. /// Only for Native Client regions. /// </exception> /// <exception cref="NotConnectedException"> /// if not connected to the Geode system because the client cannot /// establish usable connections to any of the servers given to it. /// For pools configured with locators, if no locators are available, innerException /// of NotConnectedException is set to NoAvailableLocatorsException. /// </exception> /// <exception cref="TimeoutException"> /// if the operation timed out /// </exception> /// <exception cref="OutOfMemoryException"> /// if there is not enough memory for the value /// </exception> /// <exception cref="NotSupportedException"> /// if it is called by local region instance <see cref="Region.GetLocalView" /> /// </exception> /// <seealso cref="Put" /> void PutAll(IDictionary<TKey, TValue>^ map); /// <summary> /// Puts a (IDictionary) generic collection of key/value pairs in this region. /// </summary> /// <remarks> /// <para> /// If there is already an entry associated with any key in the map in /// this region, the entry's previous value is overwritten. /// The new values are propogated to the java server to which it is connected. /// PutAll is intended for speed up large amount of put operation into /// the same region. /// For local region instance - this method is not applicable. /// </para> /// </remarks> /// <param name="map"> /// A map contains entries, i.e. (key, value) pairs. It is generic collection of key/value pairs. /// Value should not be null in any of the entries. /// </param> /// <param name="timeout">The time (in seconds) to wait for the PutAll /// response. It should be less than or equal to 2^31/1000 i.e. 2147483. /// Optional. /// </param> /// <exception cref="IllegalArgumentException"> /// If timeout is more than 2^31/1000 i.e. 2147483. /// </exception> /// <exception cref="NullPointerException"> /// if any value in the map is null /// </exception> /// <exception cref="RegionDestroyedException"> /// if region has been destroyed /// </exception> /// <exception cref="CacheServerException"> /// If an exception is received from the Java cache server. /// Only for Native Client regions. /// </exception> /// <exception cref="NotConnectedException"> /// if not connected to the Geode system because the client cannot /// establish usable connections to any of the servers given to it. /// For pools configured with locators, if no locators are available, innerException /// of NotConnectedException is set to NoAvailableLocatorsException. /// </exception> /// <exception cref="TimeoutException"> /// if the operation timed out /// </exception> /// <exception cref="OutOfMemoryException"> /// if there is not enough memory for the value /// </exception> /// <exception cref="NotSupportedException"> /// if it is called by local region instance <see cref="Region.GetLocalView" /> /// </exception> /// <seealso cref="Put" /> void PutAll(IDictionary<TKey, TValue>^ map, TimeSpan timeout); /// <summary> /// Puts a (IDictionary) generic collection of key/value pairs in this region. /// </summary> /// <remarks> /// <para> /// If there is already an entry associated with any key in the map in /// this region, the entry's previous value is overwritten. /// The new values are propogated to the java server to which it is connected. /// PutAll is intended for speed up large amount of put operation into /// the same region. /// For local region instance - this method is not applicable. /// </para> /// </remarks> /// <param name="map"> /// A map contains entries, i.e. (key, value) pairs. It is generic collection of key/value pairs. /// Value should not be null in any of the entries. /// </param> /// <param name="timeout">The time (in seconds) to wait for the PutAll /// response. It should be less than or equal to 2^31/1000 i.e. 2147483. /// Optional. /// </param> /// <param name="callbackArg"> /// a user-defined parameter to pass to callback events triggered by this method /// </param> /// <exception cref="IllegalArgumentException"> /// If timeout is more than 2^31/1000 i.e. 2147483. /// </exception> /// <exception cref="NullPointerException"> /// if any value in the map is null /// </exception> /// <exception cref="RegionDestroyedException"> /// if region has been destroyed /// </exception> /// <exception cref="CacheServerException"> /// If an exception is received from the Java cache server. /// Only for Native Client regions. /// </exception> /// <exception cref="NotConnectedException"> /// if not connected to the Geode system because the client cannot /// establish usable connections to any of the servers given to it. /// For pools configured with locators, if no locators are available, innerException /// of NotConnectedException is set to NoAvailableLocatorsException. /// </exception> /// <exception cref="TimeoutException"> /// if the operation timed out /// </exception> /// <exception cref="OutOfMemoryException"> /// if there is not enough memory for the value /// </exception> /// <exception cref="NotSupportedException"> /// if it is called by local region instance <see cref="Region.GetLocalView" /> /// </exception> /// <seealso cref="Put" /> void PutAll(IDictionary<TKey, TValue>^ map, TimeSpan timeout, Object^ callbackArg); /// <summary> /// Removes all of the entries for the specified keys from this region. /// The effect of this call is equivalent to that of calling {@link #destroy(Object)} on /// this region once for each key in the specified collection. /// If an entry does not exist that key is skipped; /// EntryNotFoundException is not thrown. /// For local region instance - this method is not applicable. /// Updates the <see cref="CacheStatistics.LastAccessedTime" /> /// and <see cref="CacheStatistics.HitCount" /> and /// <see cref="CacheStatistics.MissCount" /> for this region and the entry. /// </summary> /// <param name="keys">the collection of keys</param> /// <exception cref="IllegalArgumentException"> /// If the collection of keys is null or empty. /// </exception> /// <exception cref="CacheServerException"> /// If an exception is received from the Java cache server while /// processing the request. /// </exception> /// <exception cref="NotConnectedException"> /// if region is not connected to the cache because the client /// cannot establish usable connections to any of the given servers /// For pools configured with locators, if no locators are available, innerException /// of NotConnectedException is set to NoAvailableLocatorsException. /// </exception> /// <exception cref="RegionDestroyedException"> /// If region destroy is pending. /// </exception> /// <exception cref="TimeoutException"> /// if operation timed out. /// </exception> /// <exception cref="UnknownException"> /// For other exceptions. /// </exception> /// <exception cref="NotSupportedException"> /// if it is called by local region instance <see cref="Region.GetLocalView" /> /// </exception> /// <seealso cref="Get"/> void RemoveAll(System::Collections::Generic::ICollection<TKey>^ keys); /// <summary> /// Removes all of the entries for the specified keys from this region. /// The effect of this call is equivalent to that of calling {@link #remove(Object)} on /// this region once for each key in the specified collection. /// If an entry does not exist that key is skipped; /// EntryNotFoundException is not thrown. /// For local region instance - this method is not applicable. /// Updates the <see cref="CacheStatistics.LastAccessedTime" /> /// and <see cref="CacheStatistics.HitCount" /> and /// <see cref="CacheStatistics.MissCount" /> for this region and the entry. /// </summary> /// <param name="keys">the collection of keys</param> /// <param name="callbackArg">an argument that is passed to the callback functions. /// Optional. /// </param> /// <exception cref="IllegalArgumentException"> /// If the collection of keys is null or empty. /// </exception> /// <exception cref="CacheServerException"> /// If an exception is received from the Java cache server while /// processing the request. /// </exception> /// <exception cref="NotConnectedException"> /// if region is not connected to the cache because the client /// cannot establish usable connections to any of the given servers /// For pools configured with locators, if no locators are available, innerException /// of NotConnectedException is set to NoAvailableLocatorsException. /// </exception> /// <exception cref="RegionDestroyedException"> /// If region destroy is pending. /// </exception> /// <exception cref="TimeoutException"> /// if operation timed out. /// </exception> /// <exception cref="UnknownException"> /// For other exceptions. /// </exception> /// <exception cref="NotSupportedException"> /// if it is called by local region instance <see cref="Region.GetLocalView" /> /// </exception> /// <seealso cref="Remove"/> void RemoveAll(System::Collections::Generic::ICollection<TKey>^ keys, Object^ callbackArg); /// <summary> /// Gets values for collection of keys from the local cache or server. /// If value for a key is not present locally then it is requested from the /// java server. The value returned is not copied, so multi-threaded /// applications should not modify the value directly, /// but should use the update methods. /// For local region instance - this method is not applicable. /// Updates the <see cref="CacheStatistics.LastAccessedTime" /> /// and <see cref="CacheStatistics.HitCount" /> and /// <see cref="CacheStatistics.MissCount" /> for this region and the entry. /// </summary> /// <param name="keys">the collection of keys</param> /// <param name="values"> /// output parameter that provides the map of keys to /// respective values; when this is NULL then an /// <c>IllegalArgumentException</c> is thrown. /// </param> /// <param name="exceptions"> /// output parameter that provides the map of keys /// to any exceptions while obtaining the key; ignored if this is NULL /// </param> /// <exception cref="IllegalArgumentException"> /// If the collection of keys is null or empty, /// or <c>values</c> argument is null. /// </exception> /// <exception cref="CacheServerException"> /// If an exception is received from the Java cache server while /// processing the request. /// </exception> /// <exception cref="NotConnectedException"> /// if region is not connected to the cache because the client /// cannot establish usable connections to any of the given servers /// For pools configured with locators, if no locators are available, innerException /// of NotConnectedException is set to NoAvailableLocatorsException. /// </exception> /// <exception cref="RegionDestroyedException"> /// If region destroy is pending. /// </exception> /// <exception cref="TimeoutException"> /// if operation timed out. /// </exception> /// <exception cref="UnknownException"> /// For other exceptions. /// </exception> /// <exception cref="NotSupportedException"> /// if it is called by local region instance <see cref="Region.GetLocalView" /> /// </exception> /// <seealso cref="Get"/> void GetAll(System::Collections::Generic::ICollection<TKey>^ keys, System::Collections::Generic::IDictionary<TKey, TValue>^ values, System::Collections::Generic::IDictionary<TKey, System::Exception^>^ exceptions); /// <summary> /// Gets values for collection of keys from the local cache or server. /// If value for a key is not present locally then it is requested from the /// java server. The value returned is not copied, so multi-threaded /// applications should not modify the value directly, /// but should use the update methods. /// For local region instance - this method is not applicable. /// Updates the <see cref="CacheStatistics.LastAccessedTime" /> /// and <see cref="CacheStatistics.HitCount" /> and /// <see cref="CacheStatistics.MissCount" /> for this region and the entry. /// </summary> /// <param name="keys">the collection of keys</param> /// <param name="values"> /// output parameter that provides the map of keys to /// respective values; ignored if NULL; when this is NULL then at least /// the <c>addToLocalCache</c> parameter should be true and caching /// should be enabled for the region to get values into the region /// otherwise an <c>IllegalArgumentException</c> is thrown. /// </param> /// <param name="exceptions"> /// output parameter that provides the map of keys /// to any exceptions while obtaining the key; ignored if this is NULL /// </param> /// <param name="addToLocalCache"> /// true if the obtained values have also to be added to the local cache /// </param> /// <exception cref="IllegalArgumentException"> /// If the collection of keys is null or empty. Other invalid case is when /// the <c>values</c> parameter is NULL, and either /// <c>addToLocalCache</c> is false or caching is disabled /// for this region. /// </exception> /// <exception cref="CacheServerException"> /// If an exception is received from the Java cache server while /// processing the request. /// </exception> /// <exception cref="NotConnectedException"> /// if region is not connected to the cache because the client /// cannot establish usable connections to any of the given servers /// For pools configured with locators, if no locators are available, innerException /// of NotConnectedException is set to NoAvailableLocatorsException. /// </exception> /// <exception cref="RegionDestroyedException"> /// If region destroy is pending. /// </exception> /// <exception cref="TimeoutException"> /// if operation timed out. /// </exception> /// <exception cref="UnknownException"> /// For other exceptions. /// </exception> /// <exception cref="NotSupportedException"> /// if it is called by local region instance <see cref="Region.GetLocalView" /> /// </exception> /// <seealso cref="Get"/> void GetAll(System::Collections::Generic::ICollection<TKey>^ keys, System::Collections::Generic::IDictionary<TKey, TValue>^ values, System::Collections::Generic::IDictionary<TKey, System::Exception^>^ exceptions, bool addToLocalCache); /// <summary> /// Gets values for collection of keys from the local cache or server. /// If value for a key is not present locally then it is requested from the /// java server. The value returned is not copied, so multi-threaded /// applications should not modify the value directly, /// but should use the update methods. /// For local region instance - this method is not applicable. /// Updates the <see cref="CacheStatistics.LastAccessedTime" /> /// and <see cref="CacheStatistics.HitCount" /> and /// <see cref="CacheStatistics.MissCount" /> for this region and the entry. /// </summary> /// <param name="keys">the collection of keys</param> /// <param name="values"> /// output parameter that provides the map of keys to /// respective values; ignored if NULL; when this is NULL then at least /// the <c>addToLocalCache</c> parameter should be true and caching /// should be enabled for the region to get values into the region /// otherwise an <c>IllegalArgumentException</c> is thrown. /// </param> /// <param name="exceptions"> /// output parameter that provides the map of keys /// to any exceptions while obtaining the key; ignored if this is NULL /// </param> /// <param name="addToLocalCache"> /// true if the obtained values have also to be added to the local cache /// </param> /// <param name="callbackArg"> /// a user-defined parameter to pass to callback events triggered by this method /// </param> /// <exception cref="IllegalArgumentException"> /// If the collection of keys is null or empty. Other invalid case is when /// the <c>values</c> parameter is NULL, and either /// <c>addToLocalCache</c> is false or caching is disabled /// for this region. /// </exception> /// <exception cref="CacheServerException"> /// If an exception is received from the Java cache server while /// processing the request. /// </exception> /// <exception cref="NotConnectedException"> /// if region is not connected to the cache because the client /// cannot establish usable connections to any of the given servers /// For pools configured with locators, if no locators are available, innerException /// of NotConnectedException is set to NoAvailableLocatorsException. /// </exception> /// <exception cref="RegionDestroyedException"> /// If region destroy is pending. /// </exception> /// <exception cref="TimeoutException"> /// if operation timed out. /// </exception> /// <exception cref="UnknownException"> /// For other exceptions. /// </exception> /// <exception cref="NotSupportedException"> /// if it is called by local region instance <see cref="Region.GetLocalView" /> /// </exception> /// <seealso cref="Get"/> void GetAll(System::Collections::Generic::ICollection<TKey>^ keys, System::Collections::Generic::IDictionary<TKey, TValue>^ values, System::Collections::Generic::IDictionary<TKey, System::Exception^>^ exceptions, bool addToLocalCache, Object^ callbackArg); /// <summary> /// Gets the region name. /// </summary> /// <returns> /// region's name /// </returns> property String^ Name { String^ get(); } /// <summary> /// Gets the region's full path, which can be used to get this region object /// with <see cref="Cache.GetRegion" />. /// </summary> /// <returns> /// region's pathname /// </returns> property String^ FullPath { String^ get(); } /// <summary> /// Gets the parent region. /// </summary> /// <returns> /// region's parent, if any, or null if this is a root region /// </returns> /// <exception cref="RegionDestroyedException"> /// if the region has been destroyed /// </exception> property IRegion<TKey, TValue>^ ParentRegion { IRegion<TKey, TValue>^ get(); } /// <summary> /// Returns the attributes for this region, which can be used to create a new /// region with <see cref="Cache.CreateRegion" />. /// </summary> /// <returns> /// region's attributes /// </returns> property RegionAttributes<TKey, TValue>^ Attributes { RegionAttributes<TKey, TValue>^ get(); } /// <summary> /// Return a mutator object for changing a subset of the /// region attributes. /// </summary> /// <returns> /// attribute mutator /// </returns> /// <exception cref="RegionDestroyedException"> /// if the region has been destroyed /// </exception> property AttributesMutator<TKey, TValue>^ AttributesMutator { Apache::Geode::Client::AttributesMutator<TKey, TValue>^ get(); } /// <summary> /// Returns the statistics for this region. /// </summary> /// <returns>the <c>CacheStatistics</c> for this region</returns> /// <exception cref="StatisticsDisabledException"> /// if statistics have been disabled for this region /// </exception> property CacheStatistics^ Statistics { CacheStatistics^ get(); } /// <summary> /// Returns the subregion identified by the path, null if no such subregion. /// </summary> /// <param name="path">path</param> /// <returns>subregion, or null if none</returns> /// <seealso cref="FullPath" /> /// <seealso cref="SubRegions" /> /// <seealso cref="ParentRegion" /> IRegion<TKey, TValue>^ GetSubRegion( String^ path ); /// <summary> /// Creates a subregion with the given name and attributes. /// </summary> /// <param name="subRegionName">new subregion name</param> /// <param name="attributes">subregion attributes</param> /// <returns>new subregion</returns> /// <seealso cref="CreateServerSubRegion" /> IRegion<TKey, TValue>^ CreateSubRegion( String^ subRegionName, RegionAttributes<TKey, TValue>^ attributes ); /// <summary> /// Returns the subregions of this region. /// </summary> /// <param name="recursive">if true, also return all nested subregions</param> /// <returns>collection of regions</returns> /// <exception cref="RegionDestroyedException"> /// this region has already been destroyed /// </exception> System::Collections::Generic::ICollection<IRegion<TKey, TValue>^>^ SubRegions( bool recursive ); /// <summary> /// Return the meta-object RegionEntry for the given key. /// For both local & distributed region instances, this operation happens in local cache only. /// </summary> /// <param name="key">key to use</param> /// <returns>region entry object</returns> /// <exception cref="IllegalArgumentException">key is null</exception> /// <exception cref="RegionDestroyedException"> /// region has been destroyed /// </exception> Client::RegionEntry<TKey, TValue>^ GetEntry( TKey key ); /// <summary> /// Gets the entries in this region. /// For both local & distributed region instances, this operation happens in local cache only. /// </summary> /// <param name="recursive"> /// if true, also return all nested subregion entries /// </param> /// <returns>collection of entries</returns> System::Collections::Generic::ICollection<Client::RegionEntry<TKey, TValue>^>^ GetEntries(bool recursive); /// <summary> /// Gets the RegionService for this region. /// </summary> /// <returns>RegionService</returns> property Apache::Geode::Client::IRegionService^ RegionService { Apache::Geode::Client::IRegionService^ get( ); } /// <summary> /// True if the region contains a value for the given key. /// This only searches in the local cache. /// </summary> /// <remark> /// For both local & distributed region instances this always searches only in local cache. /// </remark> /// <param name="key">key to search for</param> /// <returns>true if value is not null</returns> bool ContainsValueForKey( TKey key ); /// <summary> /// True if this region has been destroyed. /// </summary> /// <returns>true if destroyed</returns> property bool IsDestroyed { bool get(); } /// <summary> /// Reteuns an instance of a Region<TKey, TValue> class that implements /// ISubscriptionService interface /// This method is applicable only on distributed region & not on local region. /// </summary> /// <exception cref="NotSupportedException"> /// if it is called by local region instance <see cref="Region.GetLocalView" /> /// </exception> ISubscriptionService<TKey>^ GetSubscriptionService(); /// <summary> /// Reteuns an instance of a Region<TKey, TValue> class that executes within /// a local scope of a process. /// This method is applicable only on distributed region & not on local region. /// </summary> /// <exception cref="NotSupportedException"> /// if it is called by local region instance <see cref="Region.GetLocalView" /> /// </exception> IRegion<TKey, TValue>^ GetLocalView(); /// <summary> /// Executes the query on the server based on the predicate. /// Valid only for a Native Client region. /// This method is applicable only on distributed region & not on local region. /// </summary> /// <param name="predicate">The query predicate (just the WHERE clause) or the entire query to execute</param> /// <exception cref="IllegalArgumentException"> /// If the predicate is empty. /// </exception> /// <exception cref="IllegalStateException"> /// If some error occurred. /// </exception> /// <exception cref="CacheServerException"> /// If an exception is received from the Java cache server. /// </exception> /// <exception cref="NotConnectedException"> /// if not connected to the Geode system because the client cannot /// establish usable connections to any of the servers given to it. /// For pools configured with locators, if no locators are available, innerException /// of NotConnectedException is set to NoAvailableLocatorsException. /// </exception> /// <exception cref="MessageException"> /// If the message received from server could not be handled. This will /// be the case when an unregistered typeId is received in the reply or /// reply is not well formed. More information can be found in the log. /// </exception> /// <exception cref="QueryException"> /// If some query error occurred at the server. /// </exception> /// <exception cref="TimeoutException"> /// if the operation timed out /// </exception> /// <exception cref="CacheClosedException"> /// if the cache has been closed /// </exception> /// <exception cref="NotSupportedException"> /// if it is called by local region instance <see cref="Region.GetLocalView" /> /// </exception> /// <returns> /// The SelectResults which can either be a ResultSet or a StructSet. /// </returns> generic<class TResult> ISelectResults<TResult>^ Query( String^ predicate ); /// <summary> /// Executes the query on the server based on the predicate. /// Valid only for a Native Client region. /// This method is applicable only on distributed region & not on local region. /// </summary> /// <param name="predicate">The query predicate (just the WHERE clause) or the entire query to execute</param> /// <param name="timeout">The time (in seconds) to wait for the query response, optional</param> /// <exception cref="IllegalArgumentException"> /// If the predicate is empty. /// </exception> /// <exception cref="IllegalStateException"> /// If some error occurred. /// </exception> /// <exception cref="CacheServerException"> /// If an exception is received from the Java cache server. /// </exception> /// <exception cref="NotConnectedException"> /// if not connected to the Geode system because the client cannot /// establish usable connections to any of the servers given to it. /// For pools configured with locators, if no locators are available, innerException /// of NotConnectedException is set to NoAvailableLocatorsException. /// </exception> /// <exception cref="MessageException"> /// If the message received from server could not be handled. This will /// be the case when an unregistered typeId is received in the reply or /// reply is not well formed. More information can be found in the log. /// </exception> /// <exception cref="QueryException"> /// If some query error occurred at the server. /// </exception> /// <exception cref="TimeoutException"> /// if the operation timed out /// </exception> /// <exception cref="CacheClosedException"> /// if the cache has been closed /// </exception> /// <exception cref="NotSupportedException"> /// if it is called by local region instance <see cref="Region.GetLocalView" /> /// </exception> /// <returns> /// The SelectResults which can either be a ResultSet or a StructSet. /// </returns> generic<class TResult> ISelectResults<TResult>^ Query( String^ predicate, TimeSpan timeout ); /// <summary> /// Executes the query on the server based on the predicate /// and returns whether any result exists. /// Valid only for a Native Client region. /// This method is applicable only on distributed region & not on local region. /// </summary> /// <param name="predicate"> /// The query predicate (just the WHERE clause) /// or the entire query to execute /// </param> /// <exception cref="IllegalArgumentException"> /// If the predicate is empty. /// </exception> /// <exception cref="IllegalStateException"> /// If some error occurred. /// </exception> /// <exception cref="CacheServerException"> /// If an exception is received from the Java cache server. /// </exception> /// <exception cref="NotConnectedException"> /// if not connected to the Geode system because the client cannot /// establish usable connections to any of the servers given to it. /// For pools configured with locators, if no locators are available, innerException /// of NotConnectedException is set to NoAvailableLocatorsException. /// </exception> /// <exception cref="MessageException"> /// If the message received from server could not be handled. This will /// be the case when an unregistered typeId is received in the reply or /// reply is not well formed. More information can be found in the log. /// </exception> /// <exception cref="QueryException"> /// If some query error occurred at the server. /// </exception> /// <exception cref="TimeoutException"> /// if the operation timed out /// </exception> /// <exception cref="CacheClosedException"> /// if the cache has been closed /// </exception> /// <exception cref="NotSupportedException"> /// if it is called by local region instance <see cref="Region.GetLocalView" /> /// </exception> /// <returns> /// true if the result size is non-zero, false otherwise. /// </returns> bool ExistsValue( String^ predicate ); /// <summary> /// Executes the query on the server based on the predicate /// and returns whether any result exists. /// Valid only for a Native Client region. /// This method is applicable only on distributed region & not on local region. /// </summary> /// <param name="predicate"> /// The query predicate (just the WHERE clause) /// or the entire query to execute /// </param> /// <param name="timeout"> /// The time (in seconds) to wait for the query response /// </param> /// <exception cref="IllegalArgumentException"> /// If the predicate is empty. /// </exception> /// <exception cref="IllegalStateException"> /// If some error occurred. /// </exception> /// <exception cref="CacheServerException"> /// If an exception is received from the Java cache server. /// </exception> /// <exception cref="NotConnectedException"> /// if not connected to the Geode system because the client cannot /// establish usable connections to any of the servers given to it. /// For pools configured with locators, if no locators are available, innerException /// of NotConnectedException is set to NoAvailableLocatorsException. /// </exception> /// <exception cref="MessageException"> /// If the message received from server could not be handled. This will /// be the case when an unregistered typeId is received in the reply or /// reply is not well formed. More information can be found in the log. /// </exception> /// <exception cref="QueryException"> /// If some query error occurred at the server. /// </exception> /// <exception cref="TimeoutException"> /// if the operation timed out /// </exception> /// <exception cref="CacheClosedException"> /// if the cache has been closed /// </exception> /// <exception cref="NotSupportedException"> /// if it is called by local region instance <see cref="Region.GetLocalView" /> /// </exception> /// <returns> /// true if the result size is non-zero, false otherwise. /// </returns> bool ExistsValue( String^ predicate, TimeSpan timeout ); /// <summary> /// Executes the query on the server based on the predicate /// and returns a single result value. /// Valid only for a Native Client region. /// This method is applicable only on distributed region & not on local region. /// </summary> /// <param name="predicate"> /// The query predicate (just the WHERE clause) /// or the entire query to execute /// </param> /// <exception cref="IllegalArgumentException"> /// If the predicate is empty. /// </exception> /// <exception cref="IllegalStateException"> /// If some error occurred. /// </exception> /// <exception cref="CacheServerException"> /// If an exception is received from the Java cache server. /// </exception> /// <exception cref="NotConnectedException"> /// if not connected to the Geode system because the client cannot /// establish usable connections to any of the servers given to it. /// For pools configured with locators, if no locators are available, innerException /// of NotConnectedException is set to NoAvailableLocatorsException. /// </exception> /// <exception cref="MessageException"> /// If the message received from server could not be handled. This will /// be the case when an unregistered typeId is received in the reply or /// reply is not well formed. More information can be found in the log. /// </exception> /// <exception cref="QueryException"> /// If some query error occurred at the server, /// or more than one result items are available. /// </exception> /// <exception cref="TimeoutException"> /// if the operation timed out /// </exception> /// <exception cref="CacheClosedException"> /// if the cache has been closed /// </exception> /// <exception cref="NotSupportedException"> /// if it is called by local region instance <see cref="Region.GetLocalView" /> /// </exception> /// <returns> /// The single ResultSet or StructSet item, /// or NULL of no results are available. /// </returns> Object^ SelectValue( String^ predicate ); /// <summary> /// Executes the query on the server based on the predicate /// and returns a single result value. /// Valid only for a Native Client region. /// This method is applicable only on distributed region & not on local region. /// </summary> /// <param name="predicate"> /// The query predicate (just the WHERE clause) /// or the entire query to execute /// </param> /// <param name="timeout"> /// The time (in seconds) to wait for the query response /// </param> /// <exception cref="IllegalArgumentException"> /// If the predicate is empty. /// </exception> /// <exception cref="IllegalStateException"> /// If some error occurred. /// </exception> /// <exception cref="CacheServerException"> /// If an exception is received from the Java cache server. /// </exception> /// <exception cref="NotConnectedException"> /// if not connected to the Geode system because the client cannot /// establish usable connections to any of the servers given to it. /// For pools configured with locators, if no locators are available, innerException /// of NotConnectedException is set to NoAvailableLocatorsException. /// </exception> /// <exception cref="MessageException"> /// If the message received from server could not be handled. This will /// be the case when an unregistered typeId is received in the reply or /// reply is not well formed. More information can be found in the log. /// </exception> /// <exception cref="QueryException"> /// If some query error occurred at the server, /// or more than one result items are available. /// </exception> /// <exception cref="TimeoutException"> /// if the operation timed out /// </exception> /// <exception cref="CacheClosedException"> /// if the cache has been closed /// </exception> /// <exception cref="NotSupportedException"> /// if it is called by local region instance <see cref="Region.GetLocalView" /> /// </exception> /// <returns> /// The single ResultSet or StructSet item, /// or NULL of no results are available. /// </returns> Object^ SelectValue( String^ predicate, TimeSpan timeout ); }; } // namespace Client } // namespace Geode } // namespace Apache
50.903697
130
0.58716
[ "object" ]
b87990049c89b5f7b58cd623bd7b7f48152f0241
6,103
cpp
C++
apps/jpegresize/devapp/JpegDecodeDV.cpp
TonyBrewer/OpenHT
63898397de4d303ba514d88b621cc91367ffe2a6
[ "BSD-3-Clause" ]
13
2015-02-26T22:46:18.000Z
2020-03-24T11:53:06.000Z
apps/jpegresize/devapp/JpegDecodeDV.cpp
PacificBiosciences/OpenHT
63898397de4d303ba514d88b621cc91367ffe2a6
[ "BSD-3-Clause" ]
5
2016-02-25T17:08:19.000Z
2018-01-20T15:24:36.000Z
apps/jpegresize/devapp/JpegDecodeDV.cpp
TonyBrewer/OpenHT
63898397de4d303ba514d88b621cc91367ffe2a6
[ "BSD-3-Clause" ]
12
2015-04-13T21:39:54.000Z
2021-01-15T01:00:13.000Z
/* Copyright (c) 2015 Convey Computer Corporation * * This file is part of the OpenHT jpegscale application. * * Use and distribution licensed under the BSD 3-clause license. * See the LICENSE file for the complete license text. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #define _USE_MATH_DEFINES #include <math.h> #include "JpegCommon.h" #include "JpegDecodeDV.h" #include "JpegIdctDV.h" #include "JpegZigZag.h" //LenStats g_lenStats; void jpegDecodeBlkDV( HuffDecDV &huffDec, short (&block)[8][8] ); void jpegDecodeRestartDV( JobInfo * pJobInfo, uint16_t rstIdx ); void jpegIdctBlkDV( JobInfo * pJobInfo, int ci, short (&coefBlock)[8][8], uint8_t (&outBlock)[8][8] ); void jpegWriteBlkDV( JobInfo * pJobInfo, int ci, int mcuRow, int mcuCol, int blkRow, int blkCol, uint8_t (&outBlock)[8][8] ); // Decode jpeg image using parameter from JobInfo int jpegDecBlkCntDV = 0; void jpegDecodeDV( JobInfo * pJobInfo ) { for (int rstIdx = 0; rstIdx < pJobInfo->m_dec.m_rstCnt; rstIdx += 1) // Async fork jpegDecodeRestartDV( pJobInfo, rstIdx ); } void jpegDecodeRestartDV( JobInfo * pJobInfo, uint16_t rstIdx ) { HuffDecDV huffDec( pJobInfo, rstIdx ); short coefBlock[8][8]; uint8_t outBlock[8][8]; int mcuDecodedCnt = 0; int mcuRstCnt = 0; int mcuRow = pJobInfo->m_dec.m_rstInfo[rstIdx].m_mcuRow; int mcuCol = pJobInfo->m_dec.m_rstInfo[rstIdx].m_mcuCol; int rstMcuCntOrig = pJobInfo->m_dec.m_rstMcuCntOrig; if (pJobInfo->m_dec.m_rstInfo[rstIdx].m_firstRstMcuCnt != 0) rstMcuCntOrig = pJobInfo->m_dec.m_rstInfo[rstIdx].m_firstRstMcuCnt; goto restart; for (mcuRow = 0; mcuRow < pJobInfo->m_dec.m_mcuRows; mcuRow += 1) { for (mcuCol = 0; mcuCol < pJobInfo->m_dec.m_mcuCols; mcuCol += 1) { restart: for (int ci = 0; ci < pJobInfo->m_dec.m_compCnt; ci += 1) { huffDec.setCompId( ci ); for (int blkRow = 0; blkRow < pJobInfo->m_dec.m_dcp[ci].m_blkRowsPerMcu; blkRow += 1) { for (int blkCol = 0; blkCol < pJobInfo->m_dec.m_dcp[ci].m_blkColsPerMcu; blkCol += 1) { jpegDecodeBlkDV( huffDec, coefBlock ); jpegIdctBlkDV( pJobInfo, ci, coefBlock, outBlock ); jpegWriteBlkDV( pJobInfo, ci, mcuRow, mcuCol, blkRow, blkCol, outBlock ); jpegDecBlkCntDV += 1; } } } mcuDecodedCnt += 1; mcuRstCnt += 1; if (pJobInfo->m_dec.m_rstMcuCnt > 0 && pJobInfo->m_dec.m_rstMcuCnt == mcuDecodedCnt) return; if (rstMcuCntOrig > 0 && (mcuRstCnt == rstMcuCntOrig)) { huffDec.nextRestart(); rstMcuCntOrig = pJobInfo->m_dec.m_rstMcuCntOrig; mcuRstCnt = 0; } } } huffDec.checkEndOfScan(); } void jpegDecodeBlkDV( HuffDecDV &huffDec, short (&block)[8][8] ) { memset(block, 0, sizeof(short)*64); // find DC value int s = huffDec.getNext(true); if (s != 0) { huffDec.fillBits(); int r = huffDec.getBits(s); s = huffDec.huffExtend(r, s); } if (true /*pJobInfo->m_dec.m_bCurDcNeeded*/) { s += huffDec.getLastDcValueRef(); huffDec.getLastDcValueRef() = s; block[0][0] = s; } // get AC values for (int k = 1; k < 64; k += 1) { s = huffDec.getNext(false); int r = s >> 4; s &= 0xf; #define JPEG_HUFF_DEC_DEBUG 0 #if JPEG_HUFF_DEC_DEBUG == 3 if (jpegDecBlkCntDV <= 8) printf("s=%d, r=%d, k=%d\n", s, r, k); #endif if (s) { k += r; huffDec.fillBits(); if (true /*pJobInfo->m_dec.m_bCurAcNeeded*/) { r = huffDec.getBits(s); s = huffDec.huffExtend(r, s); block[jpegZigZag[k].m_r][jpegZigZag[k].m_c] = s; } else huffDec.dropBits(s); } else { if (r != 15) break; k += 15; } } #if JPEG_HUFF_DEC_DEBUG == 1 if (jpegDecBlkCntDV < 8) printf("D blk=%d ci=%d [%4d %4d %4d %4d %4d %4d %4d %4d]\n", jpegDecBlkCntDV, huffDec.getCompId(), block[0][0], block[0][1], block[0][2], block[0][3], block[0][4], block[0][5], block[0][6], block[0][7]); #endif #if JPEG_HUFF_DEC_DEBUG == 2 if (jpegDecBlkCntDV < 128) { printf("blk=%d ci=%d\n", jpegDecBlkCntDV, huffDec.getCompId()); for (int i = 0; i < 8; i += 1) printf(" [%4d %4d %4d %4d %4d %4d %4d %4d]\n", block[i][0], block[i][1], block[i][2], block[i][3], block[i][4], block[i][5], block[i][6], block[i][7]); fflush(stdout); } if (jpegDecBlkCntDV == 128) exit(0); #endif } void jpegIdctBlkDV( JobInfo * pJobInfo, int ci, short (&coefBlock)[8][8], uint8_t (&outBlock)[8][8] ) { uint8_t * pOutPtrs[8]; for (int i = 0; i < 8; i += 1) pOutPtrs[i] = outBlock[i]; jpegIdctDV ( pJobInfo, ci, coefBlock, pOutPtrs ); #define JPEG_IDCT_DEBUG 0 #if JPEG_IDCT_DEBUG == 1 printf("blk=%d ci=%d [%3d %3d %3d %3d %3d %3d %3d %3d]\n", jpegDecBlkCntDV, ci, outBlock[0][0], outBlock[0][1], outBlock[0][2], outBlock[0][3], outBlock[0][4], outBlock[0][5], outBlock[0][6], outBlock[0][7]); //if (jpegDecBlkCntDV == 128) // exit(0); #endif #if JPEG_IDCT_DEBUG == 2 if (jpegDecBlkCntDV <= 6) { printf("blk=%d ci=%d\n", jpegDecBlkCntDV, ci); for (int i = 0; i < 8; i += 1) printf(" [%3d %3d %3d %3d %3d %3d %3d %3d]\n", outBlock[i][0], outBlock[i][1], outBlock[i][2], outBlock[i][3], outBlock[i][4], outBlock[i][5], outBlock[i][6], outBlock[i][7]); } if (jpegDecBlkCntDV == 16) exit(0); #endif } void jpegWriteBlkDV( JobInfo * pJobInfo, int ci, int mcuRow, int mcuCol, int blkRow, int blkCol, uint8_t (&outBlock)[8][8] ) { // write 8x8 block of 8-bit data to image buffer JobDcp &dcp = pJobInfo->m_dec.m_dcp[ci]; uint64_t row = (mcuRow * pJobInfo->m_dec.m_dcp[ci].m_blkRowsPerMcu + blkRow) * DCTSIZE; uint64_t col = (mcuCol * pJobInfo->m_dec.m_dcp[ci].m_blkColsPerMcu + blkCol) * DCTSIZE; //if (mcuRow < 2) // printf("WriteBlk (ci=%d, mcuRow=%d, mcuCol=%d, blkRow=%d, blkCol=%d) row=%d, col=%d\n", // ci, mcuRow, mcuCol, blkRow, blkCol, row, col); for (uint64_t ri = 0; ri < DCTSIZE; ri += 1) { //if (row + ri >= dcp.m_compRows) // continue; uint64_t imageOffset = (row + ri) * dcp.m_compBufColLines * MEM_LINE_SIZE + col; assert(imageOffset < (uint64_t)(dcp.m_compBufRowBlks * DCTSIZE * dcp.m_compBufColLines * MEM_LINE_SIZE)); *(uint64_t *)(dcp.m_pCompBuf + imageOffset) = *(uint64_t *)outBlock[ri]; } }
29.200957
124
0.64624
[ "3d" ]
b87a235e791fedf45ce0d8f57f06cb757221db44
9,098
hpp
C++
include/sg/core/task.hpp
tillenius/superglue
4f4fe917b4d7a11cb971f349a885bef4e869ae75
[ "0BSD" ]
29
2015-02-13T19:00:56.000Z
2021-09-01T07:33:41.000Z
include/sg/core/task.hpp
tillenius/superglue
4f4fe917b4d7a11cb971f349a885bef4e869ae75
[ "0BSD" ]
1
2020-07-21T08:32:31.000Z
2020-07-29T10:12:12.000Z
include/sg/core/task.hpp
tillenius/superglue
4f4fe917b4d7a11cb971f349a885bef4e869ae75
[ "0BSD" ]
3
2015-02-25T18:05:13.000Z
2015-11-15T14:13:00.000Z
#ifndef SG_TASK_HPP_INCLUDED #define SG_TASK_HPP_INCLUDED #include "sg/core/types.hpp" #include "sg/platform/atomic.hpp" #include <string> #include <stdint.h> namespace sg { template<typename Options> class Access; template<typename Options> class AccessUtil; template<typename Options> class Handle; template<typename Options> class Resource; template<typename Options> class TaskBase; template<typename Options> class TaskExecutor; namespace detail { // ============================================================================ // Option: Global ID for each task // ============================================================================ template<typename Options, typename T = typename Options::TaskId> class Task_GlobalId; template<typename Options> class Task_GlobalId<Options, typename Options::Disable> {}; template<typename Options> class Task_GlobalId<Options, typename Options::Enable> { typedef typename Options::taskid_type taskid_type; private: taskid_type id; public: Task_GlobalId() { static taskid_type global_task_id = 0; id = Atomic::increase_nv(&global_task_id); } taskid_type get_global_id() const { return id; } }; // ============================================================================ // Option Contributions // ============================================================================ template<typename Options, typename T = typename Options::Contributions> class Task_Contributions; template<typename Options> class Task_Contributions<Options, typename Options::Disable> { public: static bool can_run_with_contribs() { return false; } }; template<typename Options> class Task_Contributions<Options, typename Options::Enable> { public: virtual bool can_run_with_contribs() { return false; } }; // ============================================================================ // Option PassTaskExecutor // ============================================================================ template<typename Options, typename T = typename Options::PassTaskExecutor> class Task_PassTaskExecutor; template<typename Options> class Task_PassTaskExecutor<Options, typename Options::Disable> { public: virtual void run() = 0; }; template<typename Options> class Task_PassTaskExecutor<Options, typename Options::Enable> { public: virtual void run(TaskExecutor<Options> &) = 0; }; // ============================================================================ // Option TaskName // ============================================================================ template<typename Options, typename T = typename Options::TaskName> class Task_TaskName; template<typename Options> class Task_TaskName<Options, typename Options::Disable> {}; template<typename Options> class Task_TaskName<Options, typename Options::Enable> { public: virtual std::string get_name() = 0; }; // ============================================================================ // Option Subtasks // ============================================================================ template<typename Options, typename T = typename Options::Subtasks> class Task_Subtasks; template<typename Options> class Task_Subtasks<Options, typename Options::Disable> {}; template<typename Options> class Task_Subtasks<Options, typename Options::Enable> { public: size_t subtask_count; TaskBase<Options> *parent; Task_Subtasks() : subtask_count(0), parent(NULL) {} }; } // namespace detail // ============================================================================ // TaskBaseDefault : Base for tasks without dependencies // ============================================================================ template<typename Options> class TaskBaseDefault : public Options::ReadyListType::ElementData, public detail::Task_PassTaskExecutor<Options>, public detail::Task_GlobalId<Options>, public detail::Task_TaskName<Options>, public detail::Task_Contributions<Options>, public detail::Task_Subtasks<Options> { template<typename, typename> friend class Task_PassThreadId; template<typename, typename> friend class Task_AccessData; protected: size_t num_access; size_t access_idx; Access<Options> *access_ptr; TaskBaseDefault(size_t num_access_, Access<Options> *access_ptr_) : num_access(num_access_), access_idx(0), access_ptr(access_ptr_) {} public: TaskBaseDefault() : num_access(0), access_idx(0), access_ptr(0) {} virtual ~TaskBaseDefault() {} size_t get_num_access() const { return num_access; } Access<Options> *get_access() const { return access_ptr; } Access<Options> &get_access(size_t i) const { return access_ptr[i]; } bool are_dependencies_solved_or_notify() { TaskBase<Options> *this_(static_cast<TaskBase<Options> *>(this)); for (; access_idx < num_access; ++access_idx) { if (!access_ptr[access_idx].get_handle()->is_version_available_or_notify(this_, access_ptr[access_idx].required_version)) { ++access_idx; // We consider this dependency fulfilled now, as it will be when we get the callback. return false; } } return true; } }; // export Options::TaskBaseType as TaskBase (default: TaskBaseDefault<Options>) template<typename Options> class TaskBase : public Options::TaskBaseType {}; // ============================================================================ // TaskDefault : adds depend() // ============================================================================ template<typename Options, typename TaskBaseType, int N = -1> class TaskAccessMixin : public TaskBaseType { Access<Options> access[N]; typedef typename Options::AccessInfoType AccessInfo; typedef typename AccessInfo::Type AccessType; typedef typename Options::version_type version_type; typedef typename Options::lockcount_type lockcount_type; public: TaskAccessMixin() { // If this assignment is done through a constructor, we can save the initial assignment, // but then any user-overloaded TaskBaseDefault() class must forward both constructors. TaskBaseType::access_ptr = &access[0]; } void fulfill(AccessType type, Handle<Options> &handle, version_type version) { Access<Options> &a(access[TaskBaseType::num_access]); a.handle = &handle; a.required_version = version; if (AccessUtil<Options>::needs_lock(type)) a.set_required_quantity(1); Options::LogDAG::add_dependency(static_cast<TaskBaseType *>(this), &handle, version, type); ++TaskBaseType::num_access; } void register_access(AccessType type, Handle<Options> &handle) { fulfill(type, handle, handle.schedule(type)); } void require(Resource<Options> &resource, lockcount_type quantity = 1) { Access<Options> &a(access[TaskBaseType::num_access]); a.handle = &resource; a.required_version = 0; a.set_required_quantity(quantity); //Options::LogDAG::add_dependency(static_cast<TaskBaseType *>(this), &handle, version, type); ++TaskBaseType::num_access; } }; // Specialization for zero dependencies template<typename Options, typename TaskBaseType> class TaskAccessMixin<Options, TaskBaseType, 0> : public TaskBaseType {}; // Specialization for variable number of dependencies template<typename Options, typename TaskBaseType> class TaskAccessMixin<Options, TaskBaseType, -1> : public TaskBaseType { typedef typename Options::AccessInfoType AccessInfo; typedef typename AccessInfo::Type AccessType; typedef typename Types<Options>::template vector_t< Access<Options> >::type access_vector_t; typedef typename Options::version_type version_type; typedef typename Options::lockcount_type lockcount_type; protected: access_vector_t access; public: void fulfill(AccessType type, Handle<Options> &handle, version_type version) { access.push_back(Access<Options>(&handle, version)); Access<Options> &a(access[access.size()-1]); if (AccessUtil<Options>::needs_lock(type)) a.set_required_quantity(1); Options::LogDAG::add_dependency(static_cast<TaskBaseType *>(this), &handle, version, type); ++TaskBaseType::num_access; TaskBase<Options>::access_ptr = &access[0]; // vector may be reallocated at any add } void register_access(AccessType type, Handle<Options> &handle) { fulfill(type, handle, handle.schedule(type)); } void require(Resource<Options> &resource, lockcount_type quantity = 1) { access.push_back(Access<Options>(&resource, 0)); Access<Options> &a(access[access.size()-1]); a.set_required_quantity(quantity); ++TaskBaseType::num_access; TaskBase<Options>::access_ptr = &access[0]; // vector may be reallocated at any add } }; // export "Options::TaskType<>::type" (default: TaskDefault) as type Task template<typename Options, int N = -1> class Task : public Options::template TaskType<N>::type {}; } // namespace sg #endif // SG_TASK_HPP_INCLUDED
38.714894
135
0.639042
[ "vector" ]
b88194965251e1c99a9d36b9c7b701fd4a3607eb
1,345
cpp
C++
codejam/20210410/b.cpp
honux77/algorithm
2ed8cef1fbee7ad96d8f2ae583666d52bd8892ee
[ "MIT" ]
2
2019-02-08T01:23:07.000Z
2020-11-19T12:23:52.000Z
codejam/20210410/b.cpp
honux77/algorithm
2ed8cef1fbee7ad96d8f2ae583666d52bd8892ee
[ "MIT" ]
null
null
null
codejam/20210410/b.cpp
honux77/algorithm
2ed8cef1fbee7ad96d8f2ae583666d52bd8892ee
[ "MIT" ]
null
null
null
#include <stdio.h> #include <string.h> #include <math.h> #include <assert.h> #include <math.h> #include <vector> #include <queue> #include <algorithm> #include <iostream> #include <string> #include <bitset> #include <map> #include <set> #include <tuple> #include <random> #include <functional> #define all(x) (x).begin(), (x).end() #define xx first #define yy second using namespace std; template<typename T, typename Pr = less<T>> using pq = priority_queue<T, vector<T>, Pr>; using i64 = unsigned long long int; using ii = pair<int, int>; using ii64 = pair<i64, i64>; i64 ans; void bts(vector<i64> &v, int k, i64 s, i64 p) { //cout << k << " " << s << " " << p; if (k == v.size()) { if (s == p) ans = max(ans, p); return; } bts(v, k + 1, s + v[k], p); bts(v, k + 1, s, p * v[k]); //bts(v, k + 1, s, p); } i64 solve() { ans = 0; int n; cin >> n; vector<i64> v; for (int i = 0; i < n; i++) { int n1, n2; cin >> n1 >> n2; for (int j = 0; j < n2; j++) v.push_back(n1); } bts(v, 0, 0, 1); return ans; } int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); int t; cin >> t; for (int i = 1; i <= t; i++) { cout << "Case #" << i << ": " << solve() << "\n"; } return 0; }
19.214286
60
0.50632
[ "vector" ]
b881a0bf4e3b125d813fecb73ed9dc94b8c43d47
1,447
hpp
C++
src/input/Input.hpp
Gegel85/IndieStudio
63e58c61416b3c16885d35d75d126e3db5ed3cc8
[ "MIT" ]
null
null
null
src/input/Input.hpp
Gegel85/IndieStudio
63e58c61416b3c16885d35d75d126e3db5ed3cc8
[ "MIT" ]
null
null
null
src/input/Input.hpp
Gegel85/IndieStudio
63e58c61416b3c16885d35d75d126e3db5ed3cc8
[ "MIT" ]
1
2019-06-18T15:53:48.000Z
2019-06-18T15:53:48.000Z
/* ** EPITECH PROJECT, 2018 ** IndieStudio ** File description: ** Input.hpp */ #ifndef INPUT_HPP #define INPUT_HPP #include <iostream> #include <vector> #include <irrlicht/irrlicht.h> #include <irrlicht/Keycodes.h> #include <irrlicht/ILogger.h> #include <irrlicht/irrString.h> #include <irrlicht/IEventReceiver.h> #include "./error/Errors.hpp" namespace Input { enum Action { ACTION_UP, ACTION_RIGHT, ACTION_DOWN, ACTION_LEFT, ACTION_ACTION, ACTION_ULT, NB_OF_ACTIONS, ACTION_JOYSTICK, NO_ACTION }; enum KeysButtonName { BACK_FROM_KEYS_MANAGING = 0, NEXT_FROM_KEYS_MANAGING, P1_UP, P1_DOWN, P1_LEFT, P1_RIGHT, P1_DROP, P1_ULT, P2_UP, P2_DOWN, P2_LEFT, P2_RIGHT, P2_DROP, P2_ULT, P3_UP, P3_DOWN, P3_LEFT, P3_RIGHT, P3_DROP, P3_ULT, P4_UP, P4_DOWN, P4_LEFT, P4_RIGHT, P4_DROP, P4_ULT, P1_INPUT_CHOICE, P2_INPUT_CHOICE, P3_INPUT_CHOICE, P4_INPUT_CHOICE }; class Input { public: virtual std::vector<Action> getActions() = 0; virtual bool isAI() = 0; virtual void resetControl() = 0; virtual std::string getEnumControlString(Action code) = 0; private: }; } #endif
18.316456
66
0.564616
[ "vector" ]
b8866ee37b9d0beacd0fa7ca11f7730bda577751
1,043
hpp
C++
include/Pomdog/Graphics/PipelineStateDescription.hpp
bis83/pomdog
133a9262958d539ae6d93664e6cb2207b5b6c7ff
[ "MIT" ]
null
null
null
include/Pomdog/Graphics/PipelineStateDescription.hpp
bis83/pomdog
133a9262958d539ae6d93664e6cb2207b5b6c7ff
[ "MIT" ]
null
null
null
include/Pomdog/Graphics/PipelineStateDescription.hpp
bis83/pomdog
133a9262958d539ae6d93664e6cb2207b5b6c7ff
[ "MIT" ]
null
null
null
// Copyright (c) 2013-2015 mogemimi. // Distributed under the MIT license. See LICENSE.md file for details. #ifndef POMDOG_PIPELINESTATEDESCRIPTION_E706BE44_HPP #define POMDOG_PIPELINESTATEDESCRIPTION_E706BE44_HPP #include "detail/ForwardDeclarations.hpp" #include "BlendDescription.hpp" #include "DepthStencilDescription.hpp" #include "InputLayoutDescription.hpp" #include "RasterizerDescription.hpp" #include <memory> #include <vector> #include <string> #include <unordered_map> namespace Pomdog { using ConstantBufferBindSlotCollection = std::unordered_map<std::string, int>; struct PipelineStateDescription { ConstantBufferBindSlotCollection ConstantBufferBindSlots; std::shared_ptr<Shader> VertexShader; std::shared_ptr<Shader> PixelShader; InputLayoutDescription InputLayout; BlendDescription BlendState; RasterizerDescription RasterizerState; DepthStencilDescription DepthStencilState; std::uint32_t MultiSampleMask; }; } // namespace Pomdog #endif // POMDOG_PIPELINESTATEDESCRIPTION_E706BE44_HPP
29.8
78
0.813039
[ "vector" ]
b888d99ce83e916bde2272878f9edc2c395eeb76
9,799
hpp
C++
stapl_release/stapl/containers/multiarray/deep_slice.hpp
parasol-ppl/PPL_utils
92728bb89692fda1705a0dee436592d97922a6cb
[ "BSD-3-Clause" ]
null
null
null
stapl_release/stapl/containers/multiarray/deep_slice.hpp
parasol-ppl/PPL_utils
92728bb89692fda1705a0dee436592d97922a6cb
[ "BSD-3-Clause" ]
null
null
null
stapl_release/stapl/containers/multiarray/deep_slice.hpp
parasol-ppl/PPL_utils
92728bb89692fda1705a0dee436592d97922a6cb
[ "BSD-3-Clause" ]
null
null
null
/* // Copyright (c) 2000-2009, Texas Engineering Experiment Station (TEES), a // base_container of the Texas A&M University System. // All rights reserved. // The information and source code contained herein is the exclusive // property of TEES and may not be disclosed, examined or reproduced // in whole or in part without explicit written authorization from TEES. */ #ifndef STAPL_CONTAINERS_MULTIARRAY_DEEP_SLICE_HPP #define STAPL_CONTAINERS_MULTIARRAY_DEEP_SLICE_HPP #include <stapl/utility/tuple.hpp> #include <stapl/utility/pack_ops.hpp> #include <stapl/views/sliced_view.hpp> #include <stapl/containers/type_traits/dimension_traits.hpp> #include <stapl/containers/distribution/base_container_metadata.hpp> #include <stapl/utility/tuple/ensure_tuple.hpp> namespace stapl { namespace detail { ////////////////////////////////////////////////////////////////////// /// @brief Helper functor to compute the last element of a domain based on /// its start and size. /// /// @ptparam T The size type (either tuple or std::size_t) ////////////////////////////////////////////////////////////////////// template<typename T> struct last_of { T operator()(T const& first, T const& size) const { return tuple_ops::transform(first, size, [](std::size_t start, std::size_t sz) { return start + sz - 1; } ); } }; ////////////////////////////////////////////////////////////////////// /// @brief Specialization for std::size_t. ////////////////////////////////////////////////////////////////////// template<> struct last_of<std::size_t> { std::size_t operator()(std::size_t first, std::size_t size) const { return first + size - 1; } }; } // namespace detail template<typename Slices, typename BC, typename Linearizer> struct multiarray_bc_slice; ////////////////////////////////////////////////////////////////////// /// @brief Metafunction to compute whether or not a type is a deep slice. ////////////////////////////////////////////////////////////////////// template<typename T> struct is_deep_slice : std::false_type {}; template<typename... Args> struct is_deep_slice<multiarray_bc_slice<Args...>> : std::true_type {}; ////////////////////////////////////////////////////////////////////// /// @brief A lightweight wrapper around a multiarray base container's /// sequential storage pointer, with some of the dimensions hoisted out. /// /// @tparam Slices All dimensions that are being sliced /// @tparam BC The base container type /// @tparam Linearizer The linearizer that maps from n-d to n-|slices|-d ////////////////////////////////////////////////////////////////////// template<typename Slices, typename BC, typename Linearizer> struct multiarray_bc_slice { using container_type = typename BC::container_type; using iterator = typename container_type::iterator; using accessor_type = typename BC::accessor_type; using reference = typename BC::reference; using const_reference = typename BC::const_reference; using value_type = typename BC::value_type; using traversal_type = typename Linearizer::traversal_type; using loc_dist_metadata = base_container_metadata<multiarray_bc_slice>; /// There are as many dimensions as there are in the index of the new /// Linearizer using dimension_type = std::integral_constant<int, dimension_traits<typename Linearizer::index_type>::type::value >; using domain_type = typename detail::SLICED_view_domain< dimension_type::value, std::size_t >::type; using gid_type = typename domain_type::gid_type; using cid_type = gid_type; private: iterator m_start; Linearizer m_linear_mf; BC* m_ct_ptr; template<typename Index, std::size_t... Indices> reference make_reference_impl(Index const& gid, index_sequence<Indices...>) { return make_reference(stapl::get<Indices>(gid)...); } public: STAPL_USE_MANAGED_ALLOC(multiarray_bc_slice) ////////////////////////////////////////////////////////////////////// /// @brief Create a deep slice. /// /// @param start An iterator to the new start in the sequential storage /// @param linear_mf A new linearization for the reduced dimensionality /// base container /// @param ct_ptr Pointer to the original base_container ////////////////////////////////////////////////////////////////////// multiarray_bc_slice(iterator start, Linearizer const& linear_mf, BC* ct_ptr) : m_start(start), m_linear_mf(linear_mf), m_ct_ptr(ct_ptr) { } multiarray_bc_slice(void) = default; ////////////////////////////////////////////////////////////////////// /// @brief @copybrief multiarray_base_container::local_position ////////////////////////////////////////////////////////////////////// template<typename... Indices> size_t local_position(Indices const&... i) const { return m_linear_mf(i...); } ////////////////////////////////////////////////////////////////////// /// @brief @copybrief multiarray_base_container::make_reference ////////////////////////////////////////////////////////////////////// template<typename... Indices> reference make_reference(Indices const&... i) { return reference(accessor_type(m_ct_ptr, m_start + local_position(i...))); } ////////////////////////////////////////////////////////////////////// /// @brief @copybrief multiarray_base_container::operator() ////////////////////////////////////////////////////////////////////// template<typename... Indices> reference operator()(Indices const&... i) { return make_reference(i...); } ////////////////////////////////////////////////////////////////////// /// @brief @copybrief multiarray_base_container::operator[] /// /// @todo A specialization for gid_type of size_t is needed to eliminate /// the construction of a tuple in this method. ////////////////////////////////////////////////////////////////////// reference operator[](gid_type const& gid) { return make_reference_impl(tuple_ops::ensure_tuple(gid), make_index_sequence<dimension_type::value>()); } reference get_element(gid_type const& gid) { return make_reference_impl(tuple_ops::ensure_tuple(gid), make_index_sequence<dimension_type::value>()); } void set_element(gid_type const& gid, value_type const& value) { make_reference_impl(tuple_ops::ensure_tuple(gid), make_index_sequence<dimension_type::value>()) = value; } ////////////////////////////////////////////////////////////////////// /// @brief Domain of this deep slice. It has the same dimensionality as /// the new linearizer. ////////////////////////////////////////////////////////////////////// domain_type domain() const { auto const first = m_linear_mf.m_original_first; auto const last = detail::last_of<typename domain_type::index_type>()( first, m_linear_mf.m_original_size ); return {first, last, true}; } ////////////////////////////////////////////////////////////////////// /// @brief Number of elements represented by this slice ////////////////////////////////////////////////////////////////////// std::size_t size() const { return this->domain().size(); } ////////////////////////////////////////////////////////////////////// /// @brief @copybrief multiarray_base_container::apply_get ////////////////////////////////////////////////////////////////////// template<typename F> auto apply_get(gid_type const& gid, F&& f) -> decltype(f(std::declval<value_type>())) { value_type& ref = *(m_start + m_linear_mf(gid)); return f(ref); } ////////////////////////////////////////////////////////////////////// /// @brief @copybrief multiarray_base_container::apply_set ////////////////////////////////////////////////////////////////////// template<typename F> void apply_set(gid_type const& gid, F&& f) { value_type& ref = *(m_start + m_linear_mf(gid)); f(ref); } ////////////////////////////////////////////////////////////////////// /// @brief Metafunction to compute the type of a new slice on this deep /// slice. /// /// @tparam Slices The indices to slice on this deep slice /// @tparam Fixed The type of element that will be used to specify the /// fixed values. Typically a tuple of size |Slices|. ////////////////////////////////////////////////////////////////////// template<typename NewSlices, typename Fixed> struct slice_type { using type = typename std::decay< decltype(std::declval< multiarray_bc_slice<NewSlices, BC, decltype(m_linear_mf.template slice<NewSlices>( std::declval<Fixed>()).second ) >> ())>::type; }; ////////////////////////////////////////////////////////////////////// /// @brief Create another deep slice by slicing off dimensions specified /// in NewSlices. /// /// @tparam Slices The indices to slice on this deep slice /// @tparam Fixed The type of element that will be used to specify the /// fixed values. Typically a tuple of size |Slices|. ////////////////////////////////////////////////////////////////////// template<typename NewSlices, typename Fixed> typename slice_type<NewSlices, Fixed>::type slice(Fixed const& fixed) { auto lin_pair = m_linear_mf.template slice<NewSlices>(fixed); using slice_t = multiarray_bc_slice< NewSlices, BC, decltype(lin_pair.second) >; return slice_t(m_start + lin_pair.first, lin_pair.second, m_ct_ptr); } void define_type(typer& t) { stapl_assert(0, "Attempting to pack a deep slice."); } }; // struct multiarray_bc_slice } // namespace stapl #endif // STAPL_CONTAINERS_MULTIARRAY_DEEP_SLICE_HPP
35.248201
78
0.549954
[ "transform" ]
b889cd674936c1f797807ac6a95c5961a4445fdd
8,682
cc
C++
Cloudde/EA_library/DE_CPU.cc
LandBuffalo/Cloudde
e1328b5e4801a8a72f88e52943b36bf834a7c4b3
[ "MIT" ]
null
null
null
Cloudde/EA_library/DE_CPU.cc
LandBuffalo/Cloudde
e1328b5e4801a8a72f88e52943b36bf834a7c4b3
[ "MIT" ]
null
null
null
Cloudde/EA_library/DE_CPU.cc
LandBuffalo/Cloudde
e1328b5e4801a8a72f88e52943b36bf834a7c4b3
[ "MIT" ]
null
null
null
#include "EA_CPU.h" DE_CPU::DE_CPU() { } DE_CPU::~DE_CPU() { } string DE_CPU::GetParameters() { string str; ostringstream temp1, temp2; string parameters = "CR/F="; double CR = DE_info_.CR; temp1<<CR; str=temp1.str(); parameters.append(str); parameters.append("/"); double F = DE_info_.F; temp2<<F; str=temp2.str(); parameters.append(str); if(DE_info_.strategy_ID == 0) parameters.append("_current/1/bin"); else if(DE_info_.strategy_ID == 1) parameters.append("_current/2/bin"); else if(DE_info_.strategy_ID == 2) parameters.append("_current-to-best/1/bin"); else if(DE_info_.strategy_ID == 3) parameters.append("_current-to-best/2/bin"); else if(DE_info_.strategy_ID == 4) parameters.append("_rand/1/bin"); else if(DE_info_.strategy_ID == 5) parameters.append("_rand/2/bin"); else if(DE_info_.strategy_ID == 6) parameters.append("_best/1/bin"); else if(DE_info_.strategy_ID == 7) parameters.append("_best/2/bin"); else if(DE_info_.strategy_ID == 8) parameters.append("_current_to_rand/1/bin"); return parameters; } int DE_CPU::Initilize(ProblemInfo problem_info, int configurations) { EA_CPU::Initilize(problem_info, configurations); if(configurations == 0) { DE_info_.CR = 0.9; DE_info_.F = 0.5; DE_info_.strategy_ID = 4; } if(configurations == 1) { DE_info_.CR = 0.9; DE_info_.F = 0.5; DE_info_.strategy_ID = 4; } if(configurations == 2) { DE_info_.CR = 0.1; DE_info_.F = 0.5; DE_info_.strategy_ID = 6; } if(configurations == 3) { DE_info_.CR = 0.1; DE_info_.F = 0.5; DE_info_.strategy_ID = 6; } return 0; } int DE_CPU::Unitilize() { EA_CPU::Unitilize(); return 0; } int DE_CPU::Reproduce(Population & candidate, Population & population) { Individual best_individual = FindBestIndividual(population); vector<int> r = random_.Permutate(population.size(), 5); double F = DE_info_.F; double CR = DE_info_.CR; for (int i = 0; i < population.size(); i++) { Individual tmp_candidate; double tmp_value = 0; for (int j = 0; j < problem_info_.dim; j++) { switch (DE_info_.strategy_ID) { case 0: tmp_value = population[i].elements[j] + F * (population[r[0]].elements[j] - population[r[1]].elements[j]); break; case 1: tmp_value = population[i].elements[j] + F * (population[r[0]].elements[j] - population[r[1]].elements[j]) + \ + F * (population[r[2]].elements[j] - population[r[3]].elements[j]); break; case 2: tmp_value = population[i].elements[j] + F * (best_individual.elements[j] - population[i].elements[j]) + \ + F * (population[r[0]].elements[j] - population[r[1]].elements[j]); break; case 3: tmp_value = population[i].elements[j] + F * (best_individual.elements[j] - population[i].elements[j]) + \ + F * (population[r[0]].elements[j] - population[r[1]].elements[j]) + F * (population[r[2]].elements[j] - population[r[3]].elements[j]); break; case 4: tmp_value = population[r[0]].elements[j] + F * (population[r[1]].elements[j] - population[r[2]].elements[j]); break; case 5: tmp_value = population[r[0]].elements[j] + F * (population[r[1]].elements[j] - population[r[2]].elements[j]) + \ + F * (population[r[3]].elements[j] - population[r[4]].elements[j]); break; case 6: tmp_value = best_individual.elements[j] + F * (population[r[0]].elements[j] - population[r[1]].elements[j]); break; case 7: tmp_value = best_individual.elements[j] + F * (population[r[0]].elements[j] - population[r[1]].elements[j]) + \ + F * (population[r[2]].elements[j] - population[r[3]].elements[j]); break; case 8: tmp_value = population[i].elements[j] + F * (population[r[0]].elements[j] - population[i].elements[j]) + \ + F * (population[r[1]].elements[j] - population[r[2]].elements[j]) + F * (population[r[3]].elements[j] - population[r[4]].elements[j]); break; default: break; } if (random_.RandDoubleUnif(0, 1) > CR && j != random_.RandIntUnif(0, problem_info_.dim - 1)) tmp_value = population[i].elements[j]; tmp_value = CheckBound(tmp_value, problem_info_.min_bound, problem_info_.max_bound); tmp_candidate.elements.push_back(tmp_value); } tmp_candidate.fitness_value = 0; candidate.push_back(tmp_candidate); } return 0; } int DE_CPU::SelectSurvival(Population & population, Population & candidate) { for(int i = 0; i < population.size(); i++) if(candidate[i].fitness_value < population[i].fitness_value) population[i] = candidate[i]; return 0; } int DE_CPU::Run(Population & population) { Individual best_individual = FindBestIndividual(population); vector<int> r = random_.Permutate(population.size(), 5); double F = DE_info_.F; double CR = DE_info_.CR; for (int i = 0; i < population.size(); i++) { Individual tmp_candidate; double tmp_value = 0; for (int j = 0; j < problem_info_.dim; j++) { switch (DE_info_.strategy_ID) { case 0: tmp_value = population[i].elements[j] + F * (population[r[0]].elements[j] - population[r[1]].elements[j]); break; case 1: tmp_value = population[i].elements[j] + F * (population[r[0]].elements[j] - population[r[1]].elements[j]) + \ + F * (population[r[2]].elements[j] - population[r[3]].elements[j]); break; case 2: tmp_value = population[i].elements[j] + F * (best_individual.elements[j] - population[i].elements[j]) + \ + F * (population[r[0]].elements[j] - population[r[1]].elements[j]); break; case 3: tmp_value = population[i].elements[j] + F * (best_individual.elements[j] - population[i].elements[j]) + \ + F * (population[r[0]].elements[j] - population[r[1]].elements[j]) + F * (population[r[2]].elements[j] - population[r[3]].elements[j]); break; case 4: tmp_value = population[r[0]].elements[j] + F * (population[r[1]].elements[j] - population[r[2]].elements[j]); break; case 5: tmp_value = population[r[0]].elements[j] + F * (population[r[1]].elements[j] - population[r[2]].elements[j]) + \ + F * (population[r[3]].elements[j] - population[r[4]].elements[j]); break; case 6: tmp_value = best_individual.elements[j] + F * (population[r[0]].elements[j] - population[r[1]].elements[j]); break; case 7: tmp_value = best_individual.elements[j] + F * (population[r[0]].elements[j] - population[r[1]].elements[j]) + \ + F * (population[r[2]].elements[j] - population[r[3]].elements[j]); break; case 8: tmp_value = population[i].elements[j] + F * (population[r[0]].elements[j] - population[i].elements[j]) + \ + F * (population[r[1]].elements[j] - population[r[2]].elements[j]) + F * (population[r[3]].elements[j] - population[r[4]].elements[j]); break; default: break; } if (random_.RandDoubleUnif(0, 1) > CR && j != random_.RandIntUnif(0, problem_info_.dim - 1)) tmp_value = population[i].elements[j]; //tmp_value = CheckBound(tmp_value, problem_info_.min_bound, problem_info_.max_bound); tmp_candidate.elements.push_back(tmp_value); } tmp_candidate.fitness_value = cec2014_.EvaluateFitness(tmp_candidate.elements); if(tmp_candidate.fitness_value < population[i].fitness_value) population[i] = tmp_candidate; } return 0; }
38.415929
156
0.541926
[ "vector" ]
b88b24b7ad70c8a9790505d5ffd624b00374948d
4,367
cpp
C++
test_package/test_package_libtooling.cpp
blockspacer/llvm_9_installer
7607a89affe610bf6d1723c2ac43d17fae2a5fed
[ "MIT" ]
null
null
null
test_package/test_package_libtooling.cpp
blockspacer/llvm_9_installer
7607a89affe610bf6d1723c2ac43d17fae2a5fed
[ "MIT" ]
null
null
null
test_package/test_package_libtooling.cpp
blockspacer/llvm_9_installer
7607a89affe610bf6d1723c2ac43d17fae2a5fed
[ "MIT" ]
null
null
null
#if defined(UNDEFINED_SANITIZER) \ || defined(ADRESS_SANITIZER) \ || defined(UNDEFINED_BEHAVIOR_SANITIZER) \ || defined(MEMORY_SANITIZER) \ || defined(THREAD_SANITIZER) #error \"sanitizers not supported with libtooling\" #endif #include <cstdlib> #include <iostream> #include <iterator> #include <exception> #include <string> #include <algorithm> #include <chrono> #include <cmath> #include <memory> #include <vector> // __has_include is currently supported by GCC and Clang. However GCC 4.9 may have issues and // returns 1 for 'defined( __has_include )', while '__has_include' is actually not supported: // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=63662 #if __has_include(<filesystem>) #include <filesystem> #else #include <experimental/filesystem> #endif // __has_include #include <clang/Rewrite/Core/Rewriter.h> #include <clang/ASTMatchers/ASTMatchers.h> #include <clang/AST/ASTContext.h> #include <clang/ASTMatchers/ASTMatchFinder.h> #include <clang/ASTMatchers/ASTMatchersMacros.h> #include <clang/AST/Type.h> #include <clang/Frontend/CompilerInstance.h> #include <clang/Sema/Sema.h> #include <clang/Basic/FileManager.h> #include <clang/Basic/LangOptions.h> #include <clang/Basic/SourceManager.h> #include <clang/Frontend/CompilerInstance.h> #include <clang/Sema/Sema.h> #include <clang/Lex/Lexer.h> #include <clang/Frontend/FrontendAction.h> #include <clang/Frontend/ASTConsumers.h> #include <clang/Frontend/CompilerInstance.h> #include <clang/Tooling/Tooling.h> #include <clang/Rewrite/Core/Rewriter.h> #include <clang/Driver/Options.h> #include <clang/AST/AST.h> #include <clang/AST/ASTContext.h> #include <clang/AST/ASTConsumer.h> #include <clang/AST/RecursiveASTVisitor.h> #include <clang/Frontend/ASTConsumers.h> #include <clang/Frontend/FrontendActions.h> #include <clang/Frontend/CompilerInstance.h> #include <clang/Tooling/CommonOptionsParser.h> #include <clang/Tooling/Tooling.h> #include <clang/Rewrite/Core/Rewriter.h> #include <clang/Frontend/CompilerInstance.h> #include <clang/Sema/Sema.h> #include <clang/Lex/Lexer.h> #include <clang/Frontend/FrontendAction.h> #include <clang/Frontend/ASTConsumers.h> #include <clang/Frontend/CompilerInstance.h> #include <clang/Tooling/Tooling.h> #include <clang/Rewrite/Core/Rewriter.h> #include <clang/Driver/Options.h> #include <clang/AST/AST.h> #include <clang/AST/ASTContext.h> #include <clang/AST/ASTConsumer.h> #include <clang/AST/RecursiveASTVisitor.h> #include <clang/Frontend/ASTConsumers.h> #include <clang/Frontend/FrontendActions.h> #include <clang/Frontend/CompilerInstance.h> #include <clang/Tooling/CommonOptionsParser.h> #include <clang/Tooling/Tooling.h> #include <clang/Rewrite/Core/Rewriter.h> #include <clang/Basic/DiagnosticOptions.h> #include <clang/Frontend/TextDiagnosticPrinter.h> #include <clang/Frontend/CompilerInstance.h> #include <clang/Basic/TargetOptions.h> #include <clang/Basic/TargetInfo.h> #include <clang/Basic/FileManager.h> #include <clang/Basic/SourceManager.h> #include <clang/Lex/Preprocessor.h> #include <clang/Lex/Lexer.h> #include <clang/Basic/Diagnostic.h> #include <clang/AST/RecursiveASTVisitor.h> #include <clang/AST/ASTConsumer.h> #include <clang/Parse/ParseAST.h> #include <clang/Rewrite/Frontend/Rewriters.h> #include <clang/Rewrite/Core/Rewriter.h> #include <llvm/Support/Host.h> #include <llvm/Support/raw_ostream.h> #include <llvm/ADT/IntrusiveRefCntPtr.h> #include <llvm/ADT/StringRef.h> #include <llvm/Support/FileSystem.h> using namespace clang::tooling; using namespace llvm; // Apply a custom category to all command-line options so that they are the // only ones displayed. static cl::OptionCategory MyToolCategory("my-tool options"); // CommonOptionsParser declares HelpMessage with a description of the common // command-line options related to the compilation database and input files. // It's nice to have this help message in all tools. static cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage); // A help message for this specific tool can be added afterwards. static cl::extrahelp MoreHelp("\nMore help text...\n"); int main(int argc, const char **argv) { CommonOptionsParser OptionsParser(argc, argv, MyToolCategory); ClangTool Tool(OptionsParser.getCompilations(), OptionsParser.getSourcePathList()); return Tool.run(newFrontendActionFactory<clang::SyntaxOnlyAction>().get()); }
36.090909
93
0.777422
[ "vector" ]
b88bce99da35864343269e803deef36ab716b4e0
6,738
hpp
C++
include/Buffer.hpp
hidenorly/audioframework
764a164d651f58c6f99a817410aaead228a4d79e
[ "Apache-2.0" ]
null
null
null
include/Buffer.hpp
hidenorly/audioframework
764a164d651f58c6f99a817410aaead228a4d79e
[ "Apache-2.0" ]
null
null
null
include/Buffer.hpp
hidenorly/audioframework
764a164d651f58c6f99a817410aaead228a4d79e
[ "Apache-2.0" ]
null
null
null
/* Copyright (C) 2021 hidenorly Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #ifndef __BUFFER_HPP__ #define __BUFFER_HPP__ #include <vector> #include "AudioFormat.hpp" #include <map> #define __USE_RESERVE__ 1 #define __USE_COPY_WITH_BACKINSERTER__ 1 #define __USE_INSERT__ 0 /* @desc ByteBuffer. Note that this is based on std::vector therefore vector related methods are available such as data(), size(), [] oprators. */ typedef std::vector<uint8_t> ByteBuffer; /* @desc This enables to set/get per-sample and per-channel access */ class AudioSample { protected: AudioFormat mFormat; ByteBuffer mBuf; public: AudioSample(AudioFormat format = AudioFormat()); AudioSample(AudioFormat format, ByteBuffer buf); virtual ~AudioSample(); /* @desc get specifed channel's sample @arg channel: specifying the channel @return specified channel's data. Note that this should be fit to the specified AudioFormat's encoding such as 16bit LPCM data, etc. */ uint8_t* getData(AudioFormat::CH channel); /* @desc set specifed channel's sample @arg channel: specifying the data's channel @arg pData: specified channel's data. Note that this should be fit to the specified AudioFormat's encoding such as 16bit LPCM data, etc. */ void setData(AudioFormat::CH channel, uint8_t* pData); /* @desc get one sample ByteBuffer which includes all of channel data @return ButeBuffer */ ByteBuffer getRawBuffer(); /* @desc get one sample data pointer which includes all of channel data @return the raw bufer pointer. Note that the user must access as the AudioFormat such as encoding, channel but this is just 1 sample. */ uint8_t* getRawBufferPointer(); /* @desc get raw buffer bytes @return number of buffer of current raw buffer */ int getRawBufferSize(); }; /* @desc This enables to handle buffer of both compressed audio data and PCM (non-compressed audio data) */ class IAudioBuffer { protected: AudioFormat mFormat; ByteBuffer mBuf; public: virtual ~IAudioBuffer(); /* @desc get audio data pointer which includes all of channel data @return the raw buffer pointer. Note that the user must access within the size of getRawBuffer().size() */ virtual uint8_t* getRawBufferPointer(void); /* @desc get audio buffer which includes all of channel data @return the ByteBuffer as REFERENCE. To avoid any change for this IAudioBuffer instance, IAudioBuffer tmp; tmp=this->getRawBuffer(); Do IAudioBuffer copiedBuffer = tmp; */ virtual ByteBuffer& getRawBuffer(void); /* @desc get raw buffer bytes @return number of buffer of current raw buffer */ int getRawBufferSize(); /* @desc replace internal raw audio buffer @arg ByteBuffer instance. You must use the same AudioFormat's ByteBuffer. */ virtual void setRawBuffer(ByteBuffer& buf); /* @desc copy the specified data to this instance */ IAudioBuffer& operator=(IAudioBuffer& buf); /* @desc get the instance's AudioFormat @return AudioFormat instance */ virtual AudioFormat getAudioFormat(void); /* @desc check this instance's AudioFormat with the specified IAudioBuffer's format @return true: same format, false: different format */ virtual bool isSameAudioFormat(IAudioBuffer& buf); /* @desc add specified IAudioBuffer's buffer to this instance's buffer's tail @arg IAudioBuffer */ virtual void append(IAudioBuffer& buf); /* @desc change AudioFormat. Usually this might be useful after setrawBuffer if the format is different */ virtual void setAudioFormat( AudioFormat format, bool bForceAndSilent = false ); /* @desc get number of samples which this instance has */ virtual int getNumberOfSamples(void); }; /* @desc This enables to handle PCM (non-compressed audio data) */ class AudioBuffer : public IAudioBuffer { public: AudioBuffer(AudioFormat format, int samples); AudioBuffer(AudioBuffer& buf); AudioBuffer(); virtual ~AudioBuffer(); /* @desc get corresponding time at the format's sampling rate @return usec. number of samples * duration of one sample */ int getWindowSizeUsec(void); /* @desc change AudioFormat. Note that buffer will be cleared if format is different from this instance's current format. */ virtual void setAudioFormat( AudioFormat format, bool bForceAndSilent = false ); /* @desc change buffer's sample size. Specifying smaller then current means cut off the data. Specifying larger than current means adding 0 @arg samples : the number of samples @arg bClear : true : force clear the buffer */ void resize( int samples, bool bClear = true ); /* @desc get specified one sample @arg nOffset : number of sample offset from the beginning of this buffer */ AudioSample getSample(int nOffset); /* @desc replace the sample with specified sample @arg nOffset : number of sample offset from the beginning of this buffer @arg AudioSample : the sample's data which must fit with this instance's format */ void setSample(int nOffset, AudioSample& sample); /* @desc check specified channel mapper is same as this instance's channels @arg mapper: ChannelMapper @return true if e.g. channel is STEREO and ChannelMap is L->L, R->R */ bool isSameChannelMap(AudioFormat::ChannelMapper& mapper); /* @desc Get specified channel's data @arg outAudioFormat: AudioFormat @arg mapper: ChannelMapper as this instance channel to the output buffer's channel @return specified channel map applied AudioBuffer */ AudioBuffer getSelectedChannelData(AudioFormat outAudioFormat, AudioFormat::ChannelMapper& mapper); }; /* @desc This enables to handle compressed audio */ class CompressAudioBuffer : public IAudioBuffer { protected: int mChunkSize; static const int DEFAULT_CHUNK_SIZE = 256; public: CompressAudioBuffer(AudioFormat format = AudioFormat(AudioFormat::ENCODING::COMPRESSED), int nChunkSize = DEFAULT_CHUNK_SIZE); CompressAudioBuffer& operator=(CompressAudioBuffer& buf); /* @desc change AudioFormat. Usually */ virtual void setAudioFormat( AudioFormat format, bool bForceAndSilent = false ); virtual void append(IAudioBuffer& buf); }; #endif /* __BUFFER_HPP__ */
36.421622
176
0.740576
[ "vector" ]
b8a011ef3d3b7feb02376eda9ac5ff463b3aa259
11,530
cpp
C++
Testing/src/ResourceParsingTest.cpp
brunolueders/Cook-Raytracer
9bba5b0af04bd60a89b9de601f0560c819b03c24
[ "MIT" ]
1
2018-10-12T19:12:16.000Z
2018-10-12T19:12:16.000Z
Testing/src/ResourceParsingTest.cpp
brunolueders/Cook-Raytracer
9bba5b0af04bd60a89b9de601f0560c819b03c24
[ "MIT" ]
7
2018-09-03T17:47:58.000Z
2018-09-03T20:17:52.000Z
Testing/src/ResourceParsingTest.cpp
brunolueders/Cook-Raytracer
9bba5b0af04bd60a89b9de601f0560c819b03c24
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "CppUnitTest.h" #include "Scene.hpp" using namespace Microsoft::VisualStudio::CppUnitTestFramework; namespace Testing { TEST_CLASS(ResourceParsing) { public: TEST_METHOD(parse_Colour) { nlohmann::json j = R"("#31ff08")"_json; auto col = cook::ResourceParsing::parse<cook::Colour>(j); Assert::IsTrue(col.closeEnough(cook::Colour{ .192f, 1.f, .031f }, 1e-3f)); j = R"([1.25, 0.5, 0])"_json; col = cook::ResourceParsing::parse<cook::Colour>(j); Assert::IsTrue(col == cook::Colour{ 1.25f, .5f, 0.f }); try { j = R"("445566")"_json; cook::ResourceParsing::parse<cook::Colour>(j); } catch(nlohmann::detail::parse_error&) { return; } Assert::Fail(); } TEST_METHOD(parse_Vec2) { nlohmann::json j = R"([1.25, -4.0])"_json; auto v = cook::ResourceParsing::parse<cook::Vec2>(j); Assert::IsTrue(v == cook::Vec2{ 1.25f, -4.f }); } TEST_METHOD(parse_Vec3) { nlohmann::json j = R"([1.25, -4.0, 2])"_json; auto v = cook::ResourceParsing::parse<cook::Vec3>(j); Assert::IsTrue(v == cook::Vec3{ 1.25f, -4.f, 2.f }); } TEST_METHOD(parse_Transform) { nlohmann::json j = R"({ "position": [10, 10, 10], "rotation": [25, -45, 0], "scale": [20, 0, 50] })"_json; auto t = cook::ResourceParsing::parse<cook::Transform>(j); auto radians = cook::PI180*cook::Vec3{ 25.f, -45.f, 0.f }; Assert::IsTrue(t.position() == cook::Vec3{ 10.f, 10.f, 10.f }); Assert::IsTrue(t.rotation().closeEnough(radians, 1e-4f)); Assert::IsTrue(t.scale() == cook::Vec3{ 20.f, 0.f, 50.f }); } TEST_METHOD(parse_Material) { nlohmann::json j = R"({ "ambient":"#a5a5a5", "diffuse":"#14dd30", "specular":"#6f9a5b", "transmissive":"#bbaaff", "shininess":100.0, "translucency":100.0, "refractive-index":1.25 })"_json; auto mat = cook::ResourceParsing::parse<cook::Material>(j); Assert::IsTrue(mat.ambient().closeEnough(cook::Colour{ .647f, .647f, .647f }, 1e-3f)); Assert::IsTrue(mat.diffuse().closeEnough(cook::Colour{ .078f, .867f, .188f }, 1e-3f)); Assert::IsTrue(mat.specular().closeEnough(cook::Colour{ .435f, .604f, .357f }, 1e-3f)); Assert::IsTrue(mat.transmissive().closeEnough(cook::Colour{ .733f, .667f, 1.f }, 1e-3f)); Assert::IsTrue(mat.shininess() == 100.f); Assert::IsTrue(mat.translucency() == 100.f); Assert::IsTrue(mat.refractiveIndex() == 1.25f); } TEST_METHOD(parse_Vertex) { nlohmann::json j = R"({ "position": [ 100, -25, 15.5 ], "tex-coords": [ 0.25, 0.5 ], "normal": [ 0.25, 0.3, -0.1 ] })"_json; auto v = cook::ResourceParsing::parse<cook::Vertex>(j); Assert::IsTrue(v.position == cook::Vec3{ 100.f, -25.f, 15.5f }); Assert::IsTrue(v.texCoords == cook::Vec2{ .25f, .5f }); Assert::IsTrue(v.normal == cook::Vec3{ .25f, .3f, -.1f }); } TEST_METHOD(parse_Triangle) { nlohmann::json j = R"({ "v0": { "position": [ -1, 1, 1 ], "tex-coords": [ 0, 0 ], "normal": [ 1, 0, 0 ] }, "v1": { "position": [ 1, 1, -1 ], "tex-coords": [ 0, 1 ], "normal": [ 0, 1, 0 ] }, "v2": { "position": [ 1, -1, 1 ], "tex-coords": [ 1, 0 ], "normal": [ 0, 0, 1 ] } })"_json; auto t = cook::ResourceParsing::parse<cook::Triangle>(j); Assert::IsTrue(t.v0().position == cook::Vec3{ -1.f, 1.f, 1.f }); Assert::IsTrue(t.v1().position == cook::Vec3{ 1.f, 1.f, -1.f }); Assert::IsTrue(t.v2().position == cook::Vec3{ 1.f, -1.f, 1.f }); } TEST_METHOD(parse_Mesh) { nlohmann::json j = R"({ "faces": [ { "v0": { "position": [ -1, 1, 1 ], "tex-coords": [ 0, 0 ], "normal": [ 1, 0, 0 ] }, "v1": { "position": [ 1, 1, -1 ], "tex-coords": [ 0, 1 ], "normal": [ 0, 1, 0 ] }, "v2": { "position": [ 1, -1, 1 ], "tex-coords": [ 1, 0 ], "normal": [ 0, 0, 1 ] } }, { "v0": { "position": [ -1, 1, 1 ], "tex-coords": [ 0, 0 ], "normal": [ 1, 0, 0 ] }, "v1": { "position": [ 1, 1, -1 ], "tex-coords": [ 0, 1 ], "normal": [ 0, 1, 0 ] }, "v2": { "position": [ 1, -1, 1 ], "tex-coords": [ 1, 0 ], "normal": [ 0, 0, 1 ] } } ] })"_json; auto m = cook::ResourceParsing::parse<cook::Mesh>(j); Assert::IsTrue(m.triangles().size() == 2); } TEST_METHOD(parse_Light) { nlohmann::json j = R"({ "position": [10, 5, -4], "colour": [1.25, 1.25, 1.25], "radius": 5 })"_json; auto l = cook::ResourceParsing::parse<cook::Light>(j); Assert::IsTrue(l.position() == cook::Vec3{ 10.f, 5.f, -4.f }); Assert::IsTrue(l.colour() == cook::Colour{ 1.25f, 1.25f, 1.25f }); Assert::IsTrue(l.radius() == 5.f); } TEST_METHOD(parse_Camera) { nlohmann::json j = R"({ "position": [ 20, 0, 5 ], "target": [0, 0, 0], "standard-up": [ 0, 1, 0 ], "fov": 60, "far": 200, "focal-length": 100, "aperture": 25 })"_json; auto c = cook::ResourceParsing::parse<cook::Camera>(j); Assert::IsTrue(c.position() == cook::Vec3{ 20.f, 0.f, 5.f }); Assert::IsTrue(c.stdUp() == cook::Vec3::unitY); Assert::IsTrue(cook::closeEnough(c.fov(), 1.0472f, 1e-3f)); Assert::IsTrue(cook::closeEnough(c.near(), 1.7321f, 1e-3f)); Assert::IsTrue(c.far() == 200.f); Assert::IsTrue(c.focalLength() == 100.f); Assert::IsTrue(c.aperture() == 25.f); } TEST_METHOD(MaterialMap_addResources_Multiple) { nlohmann::json j = R"([ { "name":"shiny", "ambient":"#a5a5a5", "diffuse":"#14dd30", "specular":"#6f9a5b", "transmissive":"#bbaaff", "shininess":100.0, "translucency":100.0, "refractive-index":1.25 }, { "name":"wood", "ambient":"#a5a5a5", "diffuse":"#14dd30", "specular":"#6f9a5b", "transmissive":"#bbaaff", "shininess":100.0, "translucency":100.0, "refractive-index":1.25 }, { "name":"copper", "ambient":"#a5a5a5", "diffuse":"#14dd30", "specular":"#6f9a5b", "transmissive":"#bbaaff", "shininess":100.0, "translucency":100.0, "refractive-index":1.25 } ])"_json; cook::MaterialMap map{}; map.addResources(j); Assert::IsTrue(map.get("shiny") != nullptr); Assert::IsTrue(map.get("wood") != nullptr); Assert::IsTrue(map.get("copper") != nullptr); } TEST_METHOD(MaterialMap_addResources_Single) { nlohmann::json j = R"({ "name":"shiny", "ambient":"#a5a5a5", "diffuse":"#14dd30", "specular":"#6f9a5b", "transmissive":"#bbaaff", "shininess":100.0, "translucency":100.0, "refractive-index":1.25 })"_json; cook::MaterialMap map{}; map.addResources(j); Assert::IsTrue(map.get("shiny") != nullptr); } TEST_METHOD(Scene_loadFromStream) { std::istringstream input(std::string(R"({ "ambient-light": [0.1, 0.1, 0.1], "background-colour": "#77ff44", "camera": { "position": [ 20, 0, 5 ], "target": [0, 0, 0], "standard-up": [ 0, 1, 0 ], "fov": 60, "far": 200, "focal-length": 100, "aperture": 25 }, "resources": [{ "type": "material", "data": { "name":"shiny", "ambient":"#a5a5a5", "diffuse":"#14dd30", "specular":"#6f9a5b", "transmissive":"#bbaaff", "shininess":100.0, "translucency":100.0, "refractive-index":1.25 } }], "lights": [{ "position": [10, 5, -4], "colour": [1.25, 1.25, 1.25], "radius": 5 }], "objects": [{ "type": "rectangle", "material": "shiny", "transform": { "position": [10, 10, 10], "rotation": [25, -45, 0], "scale": [20, 0, 50] } }] })")); cook::Scene scene{}; scene.loadFromStream(input, false); Assert::IsTrue(scene.lightCount() == 1); Assert::IsTrue(scene.objectCount() == 1); Assert::IsTrue(scene.materialCount() == 1); } }; }
39.758621
102
0.368864
[ "mesh", "transform" ]
b8a34d9190cb2f4278fcc6f4b7f3a65f36b047a3
9,314
cpp
C++
ElementEngine/enginelib/src/VknPipeline.cpp
lbondi7/Element-2.0
ecba7a5f4402167643984d15b7a1b3bcff951907
[ "MIT" ]
null
null
null
ElementEngine/enginelib/src/VknPipeline.cpp
lbondi7/Element-2.0
ecba7a5f4402167643984d15b7a1b3bcff951907
[ "MIT" ]
null
null
null
ElementEngine/enginelib/src/VknPipeline.cpp
lbondi7/Element-2.0
ecba7a5f4402167643984d15b7a1b3bcff951907
[ "MIT" ]
null
null
null
#include "VknPipeline.h" #include "VkFunctions.h" #include "Device.h" #include "VkInitializers.h" #include "VknResources.h" #include "Resources.h" #include "Locator.h" #include <element/GameSettings.h> #include <stdexcept> Element::VknPipeline::VknPipeline(SwapChain* swapChain, RenderPass* renderPass, const std::string& name, const PipelineData& pipelineInfo) : m_swapChain(swapChain), m_renderPass(renderPass), name(name), m_pipelineData(pipelineInfo) { for (const auto& shaderInfo : m_pipelineData.shaderInfo) { bindingsData.emplace_back( Element::VkInitializers::descriptorSetLayoutBinding( Shader::GetVkShaderStageFlag(shaderInfo.shaderType), Element::VkFunctions::getDescriptorType(shaderInfo.bindObjectType), shaderInfo.binding)); auto shader = Locator::getResource()->shader(shaderInfo.shader, shaderInfo.shaderType); shaderStages.emplace_back(Element::VkInitializers::pipelineShaderStageCreateInfo(shader->GetVkShaderModule(), shader->GetVkShaderStageFlag())); } init(); } Element::VknPipeline::~VknPipeline() { shaderStages.clear(); bindingsData.clear(); } void Element::VknPipeline::init() { createDescriptorSetLayout(); createPipelineLayout(); createVknPipeline(); createDescriptorPool(); } void Element::VknPipeline::destroy() { flush(); auto logicalDevice = Device::getVkDevice(); vkDestroyPipelineLayout(logicalDevice, m_pipelineLayout, nullptr); vkDestroyDescriptorSetLayout(logicalDevice, m_descriptorSetLayout, nullptr); } void Element::VknPipeline::reInitVknPipeline(SwapChain* swapChain, RenderPass* renderPass) { flushed = false; m_swapChain = swapChain; m_renderPass = renderPass; createVknPipeline(); createDescriptorPool(); } void Element::VknPipeline::flush() { if (flushed) return; flushed = true; auto logicalDevice = Device::getVkDevice(); for (auto& pool : m_descriptorPools) { pool = nullptr; } //vkDestroyDescriptorPool(logicalDevice, m_descriptorPool, nullptr); vkDestroyPipeline(logicalDevice, m_vkPipeline, nullptr); m_swapChain = nullptr; m_renderPass = nullptr; } void Element::VknPipeline::bind(VkCommandBuffer vkCommandBuffer) { bound = true; vkCmdBindPipeline(vkCommandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, m_vkPipeline); } void Element::VknPipeline::createPipelineLayout() { auto logicalDevice = Device::getVkDevice(); VkPipelineLayoutCreateInfo pipelineLayoutInfo = Element::VkInitializers::pipelineLayoutCreateInfo(&m_descriptorSetLayout); if (vkCreatePipelineLayout(logicalDevice, &pipelineLayoutInfo, nullptr, &m_pipelineLayout) != VK_SUCCESS) { throw std::runtime_error("failed to create pipeline layout!"); } } void Element::VknPipeline::createDescriptorSetLayout() { VkDescriptorSetLayoutCreateInfo layoutInfo = Element::VkInitializers::descriptorSetLayoutCreateInfo(bindingsData.data(), static_cast<uint32_t>(bindingsData.size())); if (vkCreateDescriptorSetLayout(Device::getVkDevice(), &layoutInfo, nullptr, &m_descriptorSetLayout) != VK_SUCCESS) { throw std::runtime_error("failed to create descriptor set layout!"); } } void Element::VknPipeline::createDescriptorPool() { // uint32_t requireSetInfo = 0; // std::vector<VkDescriptorPoolSize> poolSizes; // for (const auto& binding : bindingsData) // { // auto descriptorCount = static_cast<uint32_t> // (m_swapChain->getImageCount()* // binding.descriptorCount); // poolSizes.emplace_back(Element::VkInitializers::descriptorPoolSizeCreateInfo(binding.descriptorType, // descriptorCount)); // requireSetInfo += descriptorCount; // } // // VkDescriptorPoolCreateInfo poolInfo = // VkInitializers::descriptorPoolCreateInfo(poolSizes.data(), // static_cast<uint32_t>(poolSizes.size()), // requireSetInfo); // // // if (vkCreateDescriptorPool(Device::getVkDevice(), &poolInfo, nullptr, &m_descriptorPool) != VK_SUCCESS) { // throw std::runtime_error("failed to create descriptor pool!"); // } m_descriptorPools.emplace_back( VknResources::get().allocateDescriptorPool(m_pipelineData, m_swapChain->getImageCount())); } Element::PipelineData& Element::VknPipeline::GetPipelineData() { return m_pipelineData; } bool Element::VknPipeline::isBound() { return bound; } void Element::VknPipeline::setBound(bool _bound) { bound = _bound; } const std::string& Element::VknPipeline::getName() { return name; } void Element::VknPipeline::createVknPipeline() { auto logicalDevice = Device::getVkDevice(); const auto& physicalDevice = Device::GetPhysicalDevice()->GetSelectedDevice(); bool depthEnabled = m_pipelineData.depthEnabled; VkPipelineVertexInputStateCreateInfo vertexInputInfo = Element::VkInitializers::pipelineVertexInputCreateInfo(1); auto bindingDescription = Vertex::getBindingDescription(); auto attributeDescriptions = Vertex::getAttributeDescriptions(); vertexInputInfo.vertexAttributeDescriptionCount = static_cast<uint32_t>(attributeDescriptions.size()); vertexInputInfo.pVertexBindingDescriptions = &bindingDescription; vertexInputInfo.pVertexAttributeDescriptions = attributeDescriptions.data(); VkPipelineInputAssemblyStateCreateInfo inputAssembly = VkInitializers::pipelineInputAssemblyCreateInfo(); VkPipelineViewportStateCreateInfo viewportState = VkInitializers::pipelineViewportCreateInfo(nullptr, 1, nullptr, 1); VkPipelineRasterizationStateCreateInfo rasterizer = VkInitializers::pipelineRasterizerCreateInfo(VK_CULL_MODE_BACK_BIT, VK_FRONT_FACE_COUNTER_CLOCKWISE, VK_POLYGON_MODE_FILL, depthEnabled ? VK_FALSE : VK_TRUE); VkPipelineMultisampleStateCreateInfo multisampling = VkInitializers::pipelineMultisamplerCreateInfo(physicalDevice.msaaSamples, VK_FALSE); VkPipelineDepthStencilStateCreateInfo depthStencil = VkInitializers::pipelineDepthStencilCreateInfo(VK_TRUE, VK_TRUE, VK_COMPARE_OP_LESS, VK_FALSE, VK_FALSE); VkPipelineColorBlendAttachmentState colorBlendAttachment = VkInitializers::pipelineColourBlendAttachment(VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT); VkPipelineColorBlendStateCreateInfo colorBlending = VkInitializers::pipelineColourBlendCreateInfo (&colorBlendAttachment, 1, VK_FALSE, VK_LOGIC_OP_COPY); std::vector<VkDynamicState> dynamicStateEnables = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR }; VkPipelineDynamicStateCreateInfo dynamicState = VkInitializers::dynamicStateCreateInfo(dynamicStateEnables); VkGraphicsPipelineCreateInfo pipelineInfo = VkInitializers::graphicsPipelineCreateInfo(); pipelineInfo.stageCount = shaderStages.size(); pipelineInfo.pStages = shaderStages.data(); pipelineInfo.pVertexInputState = &vertexInputInfo; pipelineInfo.pInputAssemblyState = &inputAssembly; pipelineInfo.pViewportState = &viewportState; pipelineInfo.pRasterizationState = &rasterizer; pipelineInfo.pMultisampleState = &multisampling; pipelineInfo.pDepthStencilState = &depthStencil; pipelineInfo.pColorBlendState = &colorBlending; pipelineInfo.pDynamicState = &dynamicState; pipelineInfo.layout = m_pipelineLayout; pipelineInfo.renderPass = m_renderPass->GetVkRenderPass(); pipelineInfo.subpass = 0; pipelineInfo.basePipelineHandle = VK_NULL_HANDLE; if (vkCreateGraphicsPipelines(logicalDevice, VK_NULL_HANDLE, 1, &pipelineInfo, nullptr, &m_vkPipeline) != VK_SUCCESS) { throw std::runtime_error("failed to create graphics pipeline!"); } } VkDescriptorSetLayout Element::VknPipeline::GetVkDescriptorSetLayout() { return m_descriptorSetLayout; } VkPipeline Element::VknPipeline::GetVkPipeline() { return m_vkPipeline; } VkPipelineLayout Element::VknPipeline::GetVkPipelineLayout() { return m_pipelineLayout; } VkDescriptorPool Element::VknPipeline::GetVkDescriptorPool() { return m_descriptorPool; } VkDescriptorPool Element::VknPipeline::allocateDescriptorPool(uint32_t descriptorCount) { for (auto& pool : m_descriptorPools) { if (!pool->isFull(descriptorCount)) return pool->getVkDescriptorPool(); } auto& pool = m_descriptorPools.emplace_back(VknResources::get().allocateDescriptorPool( m_pipelineData, m_swapChain->getImageCount())); return pool->getVkDescriptorPool(); } //const VkDescriptorSetLayout Element::VknPipeline::GetVkDescriptorSetLayout() const //{ // return m_descriptorSetLayout; //} // //const VkPipeline Element::VknPipeline::GetVkPipeline() const //{ // return m_vkPipeline; //} // //const VkPipelineLayout Element::VknPipeline::GetVkPipelineLayout() const //{ // return m_pipelineLayout; //} // //const VkDescriptorPool Element::VknPipeline::GetVkDescriptorPool() const //{ // return m_descriptorPool; //}
36.382813
216
0.732875
[ "vector" ]
b8a59ae9e48756ce90ffac163be3a3c5df1958a5
5,588
cpp
C++
src/descartes_opw_model/descartes_opw_model.cpp
JeroenDM/descartes_opw_model
a07aab932438b866436ce343aeb3405f5dfdec75
[ "Apache-2.0" ]
null
null
null
src/descartes_opw_model/descartes_opw_model.cpp
JeroenDM/descartes_opw_model
a07aab932438b866436ce343aeb3405f5dfdec75
[ "Apache-2.0" ]
null
null
null
src/descartes_opw_model/descartes_opw_model.cpp
JeroenDM/descartes_opw_model
a07aab932438b866436ce343aeb3405f5dfdec75
[ "Apache-2.0" ]
1
2019-12-30T20:10:17.000Z
2019-12-30T20:10:17.000Z
/* * Copyright 2018 Southwest Research Institute * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "descartes_opw_model/descartes_opw_model.h" #include <opw_kinematics/opw_kinematics.h> #include <opw_kinematics/opw_utilities.h> // Compute the 'joint distance' between two poses static double distance(const std::vector<double>& a, const std::vector<double>& b) { double cost = 0.0; for (size_t i = 0; i < a.size(); ++i) cost += std::abs(b[i] - a[i]); return cost; } // Compute the index of the closest joint pose in 'candidates' from 'target' static size_t closestJointPose(const std::vector<double>& target, const std::vector<std::vector<double>>& candidates) { size_t closest = 0; // index into candidates double lowest_cost = std::numeric_limits<double>::max(); for (size_t i = 0; i < candidates.size(); ++i) { assert(target.size() == candidates[i].size()); double c = distance(target, candidates[i]); if (c < lowest_cost) { closest = i; lowest_cost = c; } } return closest; } descartes_opw_model::OPWMoveitStateAdapter::OPWMoveitStateAdapter(const opw_kinematics::Parameters<double> &kin_params, const std::string &kin_base_frame, const std::string &kin_tool_frame) : kin_params_(kin_params) , kin_base_frame_(kin_base_frame) , kin_tool_frame_(kin_tool_frame) { } bool descartes_opw_model::OPWMoveitStateAdapter::initialize(const std::string &robot_description, const std::string &group_name, const std::string &world_frame, const std::string &tcp_frame) { if (!MoveitStateAdapter::initialize(robot_description, group_name, world_frame, tcp_frame)) { return false; } return computeIKFastTransforms(); } bool descartes_opw_model::OPWMoveitStateAdapter::getAllIK(const Eigen::Isometry3d &pose, std::vector<std::vector<double>> &joint_poses) const { joint_poses.clear(); // Transform input pose Eigen::Isometry3d tool_pose = world_to_base_.frame_inv * pose * tool0_to_tip_.frame; std::array<double, 6*8> sols; opw_kinematics::inverse(kin_params_, tool_pose, sols.data()); // Check the output std::vector<double> tmp (6); // temporary storage for API reasons for (int i = 0; i < 8; i++) { double* sol = sols.data() + 6 * i; if (opw_kinematics::isValid(sol)) { opw_kinematics::harmonizeTowardZero(sol); // TODO: make this better... std::copy(sol, sol + 6, tmp.data()); if (isValid(tmp)) { joint_poses.push_back(tmp); } } } return joint_poses.size() > 0; } bool descartes_opw_model::OPWMoveitStateAdapter::getIK(const Eigen::Isometry3d &pose, const std::vector<double> &seed_state, std::vector<double> &joint_pose) const { // Descartes Robot Model interface calls for 'closest' point to seed position std::vector<std::vector<double>> joint_poses; if (!getAllIK(pose, joint_poses)) return false; // Find closest joint pose; getAllIK() does isValid checks already joint_pose = joint_poses[closestJointPose(seed_state, joint_poses)]; return true; } bool descartes_opw_model::OPWMoveitStateAdapter::getFK(const std::vector<double> &joint_pose, Eigen::Isometry3d &pose) const { if (!isValid(joint_pose)) // TODO: Why is this a thing? return false; pose = opw_kinematics::forward<double>(kin_params_, joint_pose.data()); pose = world_to_base_.frame * pose * tool0_to_tip_.frame_inv; return true; } void descartes_opw_model::OPWMoveitStateAdapter::setState(const moveit::core::RobotState &state) { descartes_moveit::MoveitStateAdapter::setState(state); computeIKFastTransforms(); } bool descartes_opw_model::OPWMoveitStateAdapter::computeIKFastTransforms() { // look up the IKFast base and tool frame if (!robot_state_->knowsFrameTransform(kin_base_frame_)) { //logError("IkFastMoveitStateAdapter: Cannot find transformation to frame '%s' in group '%s'.", // kin_base_frame_.c_str(), group_name_.c_str()); return false; } if (!robot_state_->knowsFrameTransform(kin_tool_frame_)) { //logError("IkFastMoveitStateAdapter: Cannot find transformation to frame '%s' in group '%s'.", // kin_tool_frame_.c_str(), group_name_.c_str()); return false; } // calculate frames tool0_to_tip_ = descartes_core::Frame(robot_state_->getFrameTransform(tool_frame_).inverse() * robot_state_->getFrameTransform(kin_tool_frame_)); world_to_base_ = descartes_core::Frame(world_to_root_.frame * robot_state_->getFrameTransform(kin_base_frame_)); return true; }
35.820513
119
0.648533
[ "vector", "model", "transform" ]
b8ac03b0f4a827297fc5a37a008180326a14b34e
9,160
cpp
C++
lib/ast/expression/overload_resolver.cpp
Shachar/practical-sa
01ad8a5d60d2cb09760a38acf229331885dae538
[ "BSL-1.0" ]
1
2018-07-13T18:09:40.000Z
2018-07-13T18:09:40.000Z
lib/ast/expression/overload_resolver.cpp
Shachar/practical-sa
01ad8a5d60d2cb09760a38acf229331885dae538
[ "BSL-1.0" ]
17
2019-03-13T08:51:37.000Z
2020-12-05T18:18:44.000Z
lib/ast/expression/overload_resolver.cpp
Shachar/practical
01ad8a5d60d2cb09760a38acf229331885dae538
[ "BSL-1.0" ]
1
2018-09-25T15:30:50.000Z
2018-09-25T15:30:50.000Z
/* This file is part of the Practical programming langauge. https://github.com/Practical/practical-sa * * To the extent header files enjoy copyright protection, this file is file is copyright (C) 2020 by its authors * You can see the file's authors in the AUTHORS file in the project's home repository. * * This is available under the Boost license. The license's text is available under the LICENSE file in the project's * home directory. */ #include "ast/expression/overload_resolver.h" #include "ast/expression.h" #include <practical/errors.h> namespace AST::ExpressionImpl { void OverloadResolver::resolveOverloads( LookupContext &lookupContext, ExpectedResult expectedResult, const LookupContext::Function::OverloadsContainer &overloads, Weight &weight, Weight weightLimit, ExpressionMetadata &metadata, Slice<const NonTerminals::Expression *const> parserArguments, const Tokenizer::Token *sourceLocation ) { if( expectedResult ) { resolveOverloadsByReturn( lookupContext, expectedResult, overloads, weight, weightLimit, metadata, parserArguments, sourceLocation ); } else { resolveOverloadsByArguments( lookupContext, overloads, weight, weightLimit, metadata, parserArguments, sourceLocation ); } } const FunctionTypeImpl &OverloadResolver::getType() const { ASSERT(definition)<<"Tried to getType from unresolved overloads"; auto functionTypeType = definition->type->getType(); auto functionType = std::get_if<const StaticType::Function *>( &functionTypeType ); ASSERT( functionType )<<"Function's type is not of type Function"; return *downCast(*functionType); } ExpressionId OverloadResolver::codeGen( PracticalSemanticAnalyzer::FunctionGen *functionGen ) const { return definition->codeGen( arguments, definition, functionGen ); } // Private void OverloadResolver::buildActualCall( LookupContext &lookupContext, Weight &weight, Weight weightLimit, const LookupContext::Function::Definition *definition, ExpressionMetadata &metadata, Slice<const NonTerminals::Expression *const> parserArguments ) { auto functionType = std::get<const StaticType::Function *>( definition->type->getType() ); size_t numArguments = functionType->getNumArguments(); ASSERT( numArguments==parserArguments.size() ); arguments.reserve( numArguments ); for( unsigned argumentNum=0; argumentNum<numArguments; ++argumentNum ) { Expression &argument = arguments.emplace_back( *parserArguments[argumentNum] ); Weight additionalWeight; argument.buildAST( lookupContext, ExpectedResult( functionType->getArgumentType(argumentNum) ), additionalWeight, weightLimit ); ASSERT( additionalWeight<=weightLimit ); weight+=additionalWeight; weightLimit-=additionalWeight; } StaticTypeImpl::CPtr returnType = static_cast<const StaticTypeImpl *>( functionType->getReturnType().get() ); if( definition->calcVrp ) { ValueRangeBase::CPtr inputRanges[ numArguments ]; for( unsigned argumentNum=0; argumentNum<numArguments; ++argumentNum ) { inputRanges[argumentNum] = arguments[argumentNum].getValueRange(); } metadata.valueRange = definition->calcVrp( definition->type, Slice( inputRanges, numArguments ) ); } else { metadata.valueRange = returnType->defaultRange(); } metadata.type = std::move(returnType); this->definition = definition; } void OverloadResolver::resolveOverloadsByReturn( LookupContext &lookupContext, ExpectedResult expectedResult, const LookupContext::Function::OverloadsContainer &overloads, Weight &weight, Weight weightLimit, ExpressionMetadata &metadata, Slice<const NonTerminals::Expression *const> parserArguments, const Tokenizer::Token *sourceLocation ) { std::unordered_map< StaticType::CPtr, std::vector< const LookupContext::Function::Definition * > > sortedOverloads; size_t numArguments = parserArguments.size(); for( auto &overload : overloads ) { auto overloadType = std::get<const StaticType::Function *>(overload.second.type->getType()); if( overloadType->getNumArguments() == numArguments ) { sortedOverloads[ overloadType->getReturnType() ].emplace_back( &overload.second ); } } if( sortedOverloads.size()==0 ) { throw NoMatchingOverload( sourceLocation ); } if( sortedOverloads.size()==1 && sortedOverloads.begin()->second.size()==1 ) { // It's the only one that might match. Either it matches or compile error. buildActualCall( lookupContext, weight, weightLimit, *sortedOverloads.begin()->second.begin(), metadata, parserArguments ); return; } auto currentReturnCandidate = sortedOverloads.find( expectedResult.getType() ); if( currentReturnCandidate!=sortedOverloads.end() ) { ASSERT( ! currentReturnCandidate->second.empty() ); if( currentReturnCandidate->second.size()==1 ) { // Only one overload matches the return type exactly buildActualCall( lookupContext, weight, weightLimit, currentReturnCandidate->second[0], metadata, parserArguments ); return; } try { findBestOverloadByArgument( lookupContext, currentReturnCandidate->second, weight, weightLimit, metadata, parserArguments, sourceLocation ); return; } catch( NoMatchingOverload &ex ) { } } ABORT()<<"TODO implement"; /* buildActualCall( lookupContext, expectedResult, weight, weightLimit, preciseResultOverloads[0], metadata, parserArguments ); */ } void OverloadResolver::resolveOverloadsByArguments( LookupContext &lookupContext, const LookupContext::Function::OverloadsContainer &overloads, Weight &weight, Weight weightLimit, ExpressionMetadata &metadata, Slice<const NonTerminals::Expression *const> parserArguments, const Tokenizer::Token *sourceLocation ) { std::vector<const LookupContext::Function::Definition *> relevantOverloads; size_t numArguments = parserArguments.size(); for( auto &overload : overloads ) { auto overloadType = std::get<const StaticType::Function *>(overload.second.type->getType()); if( overloadType->getNumArguments() == numArguments ) { relevantOverloads.emplace_back( &overload.second ); } } if( relevantOverloads.size()==0 ) { throw NoMatchingOverload( sourceLocation ); } if( relevantOverloads.size()==1 ) { // It's the only one that might match. Either it matches or compile error. buildActualCall( lookupContext, weight, weightLimit, relevantOverloads[0], metadata, parserArguments ); return; } findBestOverloadByArgument( lookupContext, relevantOverloads, weight, weightLimit, metadata, parserArguments, sourceLocation ); } void OverloadResolver::findBestOverloadByArgument( LookupContext &lookupContext, Slice< const LookupContext::Function::Definition * > overloads, Weight &weight, Weight weightLimit, ExpressionMetadata &metadata, Slice<const NonTerminals::Expression *const> parserArguments, const Tokenizer::Token *sourceLocation ) { Weight callWeightLimit = weightLimit - weight; Weight bestWeight = Base::NoWeightLimit; OverloadResolver bestOverloader; ExpressionMetadata bestMetadata; std::vector< const LookupContext::Function::Definition * > viableOverloads; for( auto overload : overloads ) { try { OverloadResolver provisoryResolver; Weight callWeight; ExpressionMetadata callMetadata; provisoryResolver.buildActualCall( lookupContext, callWeight, callWeightLimit, overload, callMetadata, parserArguments ); if( callWeight<bestWeight ) { bestWeight = callWeight; callWeightLimit = callWeight; viableOverloads.clear(); bestOverloader = std::move( provisoryResolver ); bestMetadata = std::move( callMetadata ); } viableOverloads.emplace_back( overload ); } catch( NoMatchingOverload &ex ) { } catch( AmbiguousOverloads &ex ) { } catch( CastError &ex ) { } catch( Base::ExpressionTooExpensive &ex ) { } } if( viableOverloads.empty() ) throw NoMatchingOverload( sourceLocation ); if( viableOverloads.size()>1 ) throw AmbiguousOverloads( sourceLocation ); weight += bestWeight; ASSERT( weight<=weightLimit ); (*this) = std::move( bestOverloader ); metadata = std::move( bestMetadata ); } } // namespace AST::ExpressionImpl
37.235772
122
0.668996
[ "vector" ]
b8b0b16873b7974d11c6ce9daa6ebdbcaeb1dc1f
12,735
cpp
C++
Core/Physics/Physics.cpp
marci07iq/SpaceCube
464bc3fa1090bed273bcaa3257aebeacc4e8d3b0
[ "MIT" ]
2
2019-11-05T14:48:34.000Z
2019-11-05T14:49:30.000Z
Core/Physics/Physics.cpp
marci07iq/SpaceCube
464bc3fa1090bed273bcaa3257aebeacc4e8d3b0
[ "MIT" ]
null
null
null
Core/Physics/Physics.cpp
marci07iq/SpaceCube
464bc3fa1090bed273bcaa3257aebeacc4e8d3b0
[ "MIT" ]
null
null
null
#include "../Terrain/WorldLoader.h" const float maxStepSize = 0.5; const float EPSILON = 1e-5; struct movement { mVec3 pos; mpsVec3 vel; }; template<typename T> void sortPairInc(T& a, T& b) { if (a > b) { swap(a, b); } } template<typename T> void sortPairDec(T& a, T& b) { if (a > b) { swap(a, b); } } /*pair<time_type_s, int> getIntersectTime(PhysCube& lhs, PhysCube& rhs, mpsVec3 relVel) { vec3<time_type_s> intersectA = (rhs.nc - lhs.pc) / relVel; vec3<time_type_s> intersectB = (rhs.pc - lhs.nc) / relVel; vec3<time_type_s> intersectStart = vecSwitch(intersectA > intersectB, intersectA, intersectB); vec3<time_type_s> intersectEnd = vecSwitch(intersectA < intersectB, intersectA, intersectB); time_type_s intersectS = intersectStart.x; int lastAxis = 0; if(intersectS < intersectStart.y) { intersectS = intersectStart.y; lastAxis = 1; } if (intersectS < intersectStart.z) { intersectS = intersectStart.z; lastAxis = 2; } time_type_s intersectE = intersectEnd.min(); if (intersectE > intersectS) { return { INFINITY, lastAxis }; } return{ intersectS, lastAxis }; }*/ PhysCube getUnion(PhysCube& lhs, PhysCube& rhs) { PhysCube res; res.nc = vecSwitch(lhs.nc < rhs.nc, lhs.nc, rhs.nc); res.pc = vecSwitch(lhs.pc > rhs.pc, lhs.pc, rhs.pc); return res; } volume_type_mmm getIntersectVol(PhysCube& lhs, PhysCube& rhs) { distance_type_m xIntersect = max<distance_type_m>(0, min(lhs.pc.x, rhs.pc.x) - max(lhs.nc.x, rhs.nc.x)); distance_type_m yIntersect = max<distance_type_m>(0, min(lhs.pc.y, rhs.pc.y) - max(lhs.nc.y, rhs.nc.y)); distance_type_m zIntersect = max<distance_type_m>(0, min(lhs.pc.z, rhs.pc.z) - max(lhs.nc.z, rhs.nc.z)); return xIntersect * yIntersect * zIntersect; } volume_type_mmm getVol(PhysCube& c) { return (c.pc.x-c.nc.x) * (c.pc.y - c.nc.y) * (c.pc.z - c.nc.z); } struct IntersectionData { time_type_s t; int ax; PhysCube cube; }; bool operator<(const IntersectionData& lhs, const IntersectionData& rhs) { return lhs.t < rhs.t; } bool operator>(const IntersectionData& lhs, const IntersectionData& rhs) { return lhs.t > rhs.t; } inline void calculateCollisions(PhysCube& entc, priority_queue_smallest<IntersectionData>& pcubes, mpsVec3& vel, list<PhysCube>& cubes, time_type_s& processTreshold, time_type_s& deltaT) { pcubes = priority_queue_smallest<IntersectionData>(); for (auto&& it : cubes) { vec2<time_type_s> entryTimes; vec2<time_type_s> exitTimes; for (int i = 0; i < 2; i++) { if (vel[i] != 0) { entryTimes[i] = (vel[i] > 0) ? ((it.nc[i] + EPSILON - entc.pc[i]) / vel[i]) : ((it.pc[i] - EPSILON - entc.nc[i]) / vel[i]); exitTimes[i] = (vel[i] > 0) ? ((it.pc[i] - EPSILON - entc.nc[i]) / vel[i]) : ((it.nc[i] + EPSILON - entc.pc[i]) / vel[i]); } else { entryTimes[i] = (max(it.nc[i] + EPSILON, entc.nc[i]) < min(it.pc[i] - EPSILON, entc.pc[i])) ? (-INFINITY) : (INFINITY); exitTimes[i] = (max(it.nc[i] + EPSILON, entc.nc[i]) < min(it.pc[i] - EPSILON, entc.pc[i])) ? (INFINITY) : (-INFINITY); } } if (entryTimes.maxV() < exitTimes.minV()) { int axis = entryTimes.maxI(); time_type_s entry = entryTimes[axis]; if (processTreshold <= entry && entry <= deltaT) { pcubes.push({ entry, (entry < 0) ? -1 : axis, it }); } } } } void tickEntity(Entity* ent, time_type_s deltaT) { //Assumption: deltaT is so small, that an entity entering a PhysCube will not leave it in the same timestep //Guarantee: Even in this case, objects hitting the wall will get stopped. //Assumption: The total amount travelled upwards on stairs is maxStepSize //Guarantee: You just wont be able to go higher //Assumption: Entity height < maxStepSize //Guarantee: Nope. time_type_s stepLength = deltaT; mVec3 newPos = ent->getFeetCenter(); PhysCube entc = ent->getPhysCube(); PhysCube endc = entc; mpsVec3 vel = ent->getVelocity(); getBlock(newPos.x, newPos.y, newPos.z, ent->getDim(), ent->_inWorld); //cout << ent->_friction << endl; vel -= vel * ent->_drag; //cout << vel << endl; vel += (ent->_selfAccel * ent->_friction + G) * deltaT; //cout << vel << endl; //cout << endl; if (!ent->_inWorld) { vel = 0; } mVec3 offset = vel * deltaT; newPos += offset; endc.offset(offset); PhysCube boundry = getUnion(entc, endc); iVec3 iBegBot = { int(floor(boundry.nc.x - EPSILON)),int(floor(boundry.nc.y - EPSILON)) ,int(floor(boundry.nc.z - maxStepSize - EPSILON)) }; iVec3 iBegTop = { int(floor(boundry.pc.x + EPSILON)),int(floor(boundry.pc.y + EPSILON)) ,int(floor(boundry.pc.z + maxStepSize + EPSILON)) }; //mass_type_kg enclosedMass = 0; //float drag = 1; //no restrict list<PhysCube> cubes; //cout << "ET"; for (int i = iBegBot.x; i <= iBegTop.x; i++) { for (int j = iBegBot.y; j <= iBegTop.y; j++) { for (int k = iBegBot.z; k <= iBegTop.z; k++) { bool s = false; BlockPos b[7] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL}; //cout << "S"; b[6] = getBlock(i, j, k, ent->getDim(), s); //cout << "F"; if (s) { for (int l = 0; l < 6; l++) { blockNeighbour(b[6], static_cast<Directions>(l), b[l]); } blockProperties[b[6].b->_ID].getPhysics(b, cubes); } } } } //Order cubes in order of collision time time_type_s processTreshold = -INFINITY; priority_queue_smallest<IntersectionData> pcubes; calculateCollisions(entc, pcubes, vel, cubes, processTreshold, deltaT); distance_type_m lowerHL = min(entc.nc[2], endc.nc[2]); distance_type_m upperHL = max(entc.nc[2], endc.nc[2]) + maxStepSize + EPSILON; //entity height float entcH = entc.pc[2] - entc.nc[2]; bVec2 lockedAxes(false); fVec2 teleportPos; while (pcubes.size()) { auto cube = pcubes.top(); pcubes.pop(); processTreshold = cube.t; if (cube.ax == -1 || !lockedAxes[cube.ax]) { //Merge intervals distance_type_m tempUpper = upperHL; distance_type_m tempLower = lowerHL; distance_type_m newUpper = cube.cube.pc[2]; distance_type_m newLower = cube.cube.nc[2] - entcH; if (lowerHL < newLower && newLower < upperHL) { tempUpper = newLower; } else if (lowerHL < newUpper && newUpper < upperHL) { tempLower = newUpper; } else if (newLower <= lowerHL && upperHL <= newUpper) { tempUpper = newLower; tempLower = newUpper; } if (tempUpper <= tempLower) { if (cube.ax != -1) { lockedAxes[cube.ax] = true; //cout << cube.ax; teleportPos[cube.ax] = (vel[cube.ax] > 0) ? (cube.cube.nc[cube.ax] - (entc.pc[cube.ax] - entc.nc[cube.ax]) / 2.0) : (cube.cube.pc[cube.ax] + (entc.pc[cube.ax] - entc.nc[cube.ax]) / 2.0); vel[cube.ax] = 0; calculateCollisions(entc, pcubes, vel, cubes, processTreshold, deltaT); } } else { //assert(lowerHL <= tempLower); //assert(tempLower <= tempUpper); //assert(tempUpper <= upperHL); lowerHL = tempLower; upperHL = tempUpper; } } } if (lockedAxes[0]) newPos[0] = teleportPos[0]; if (lockedAxes[1]) newPos[1] = teleportPos[1]; newPos[2] = max(lowerHL, min(endc.nc[2], upperHL)); if (abs(newPos[2]-endc.nc[2]) > EPSILON || !ent->_inWorld) { ent->_friction = sVec3(SC_SUBTICK_TIME * 30, SC_SUBTICK_TIME * 30, 1); ent->_drag = sVec3(1 - pow(2, -SC_SUBTICK_TIME / 0.05), 1 - pow(2, -SC_SUBTICK_TIME / 0.05), 1); vel[2] = 0; } else { ent->_friction = sVec3(SC_SUBTICK_TIME / 0.5, SC_SUBTICK_TIME / 0.5, 0); ent->_drag = sVec3(1 - pow(2, -SC_SUBTICK_TIME / 1.0), 1 - pow(2, -SC_SUBTICK_TIME / 1.0), 1 - pow(2, -SC_SUBTICK_TIME / 1.0)); } ent->setPos(newPos); ent->setVel(vel); /*volume_type_mmm fullVol = getVol(entc); for(auto&& it : cubes) { volume_type_mmm interv = getIntersectVol(entc, it); if(interv) { enclosedMass += it.density * interv; drag *= pow(1-it.drag, interv / fullVol); //if even one object has 1 drag, output = 0. } } return {G * (1 - enclosedMass / ent->getMass()), drag};*/ /*vec3<time_type_s> colls = {INFINITY, INFINITY ,INFINITY }; for(auto&& it : cubes) { pair<time_type_s, int> coll = getIntersectTime(entc, it, vel); }*/ //vec3<time_type_s> movTime = vec3<time_type_s>(deltaT); //mpsVec3 nVel = vel; /*for (auto&& it : cubes) { if (getIntersectVol(it, endc) > 0) { vec3<time_type_s> nhitTime = vecSwitch( bVec3(getIntersectVol(it, endcx) > 0, getIntersectVol(it, endcy) > 0, getIntersectVol(it, endcz) > 0), vecSwitch( vel < mpsVec3(0), (it.pc - entc.nc) / vel, vecSwitch( vel > mpsVec3(0), (it.nc - entc.pc) / vel, vec3<time_type_s>(-100000))), vec3<time_type_s>(-0.0)); int lastHit = 0; time_type_s hitTime = nhitTime.x; if (hitTime < nhitTime.y) { hitTime = nhitTime.y; lastHit = 1; } if (hitTime < nhitTime.z) { hitTime = nhitTime.z; lastHit = 2; } cout << hitTime << endl; if (hitTime < movTime[lastHit]) { movTime[lastHit] = hitTime; nVel[lastHit] = 0; cout << lastHit << endl; } } }*/ /* for (auto&& it : cubes) { if(vel.x != 0) { time_type_s newHit = (vel.x < 0) ? (it.pc.x - entc.nc.x) / vel.x : (it.nc.x - entc.pc.x) / vel.x; if (newHit < movTime.x) { movTime.x = newHit; nVel.x = 0; } } if (vel.y != 0) { time_type_s newHit = (vel.y < 0) ? (it.pc.y - entc.nc.y) / vel.y : (it.nc.y - entc.pc.y) / vel.y; if (newHit < movTime.y) { movTime.y = newHit; nVel.y = 0; } } if (vel.z != 0) { time_type_s newHit = (vel.z < 0) ? (it.pc.z - entc.nc.z) / vel.z : (it.nc.z - entc.pc.z) / vel.z; if (newHit < movTime.z) { movTime.z = newHit; nVel.z = 0; } } } */ /*ent->_friction = sVec3(0); mpsVec3 newVel = vel; if (cubes.size() == 0 && !ent->_inWorld) { ent->_friction = sVec3(1); } while (deltaT > 0 && bor(newVel!=mpsVec3(0))) { int blockAxis = -1; time_type_s collideAt = deltaT; for (auto&& it : cubes) { vec3<time_type_s> enterTimes; vec3<time_type_s> exitTimes; for(int ax = 0; ax < 3; ax++) { if (newVel[ax] == 0) { if (max(entc.nc[ax], it.nc[ax]) < min(entc.pc[ax], it.pc[ax])) { enterTimes[ax] = -1e100; exitTimes[ax] = deltaT; } else { break; } } else { if (newVel[ax] < 0) { enterTimes[ax] = (it.pc[ax] - entc.nc[ax]) / newVel[ax]; exitTimes[ax] = (it.nc[ax] - entc.pc[ax]) / newVel[ax]; } else { enterTimes[ax] = (it.nc[ax] - entc.pc[ax]) / newVel[ax]; exitTimes[ax] = (it.pc[ax] - entc.nc[ax]) / newVel[ax]; } } } if (-0.001 < enterTimes.maxV() && enterTimes.maxV() < exitTimes.minV()) { time_type_s lastEnter = enterTimes.x; int lastEnterDir = 0; for (int i = 1; i < 3; i++) { if (lastEnter < enterTimes[i]) { lastEnter = enterTimes[i]; lastEnterDir = i; } } if (lastEnter < collideAt) { collideAt = lastEnter; blockAxis = lastEnterDir; } } } newPos += newVel * collideAt; entc.offset(newVel * collideAt); if (blockAxis != -1) { newVel[blockAxis] = 0; ent->_friction[blockAxis] = 1; } deltaT -= collideAt; } if (ent->_friction[2] > 0) { newVel *= {pow(CONS_E, - 20 * stepLength * abs(newVel.x)), pow(CONS_E, -20 * stepLength * abs(newVel.y)), pow(CONS_E, -0 * stepLength * abs(newVel.z))}; newVel = vecSwitch(newVel < mpsVec3(0.1) & newVel > mpsVec3(-0.1) & bVec3(true, true, false), mpsVec3(0), newVel); } else { newVel *= {pow(CONS_E, - 5 * stepLength * abs(newVel.x)), pow(CONS_E, -5 * stepLength * abs(newVel.y)), pow(CONS_E, -0.01 * stepLength * abs(newVel.z))}; } ent->setPos(newPos); ent->setVel(newVel);*/ } void subtickPhysics() { for (auto&& it : entities) { /*mVec3 posShift = {0,0,0}; mpsVec3 vel = it->getVelocity(); pair<mpssVec3, float> props = getProps(it, posShift); vel *= exp(-tickTime/props.second); posShift = vel * tickTime;*/ //it.second->movPos(it.second->() * tickTime); //it.second->movPos(it.second->_selfAccel * tickTime * 0.02); tickEntity(it.second, SC_SUBTICK_TIME); } }
30.910194
188
0.579191
[ "object" ]
b8b6398b58f2a6625b69583fcfcc905e304c2a45
6,452
cpp
C++
tests/op/test_opendla_op_split.cpp
zhouzy-creator/Tengine
fea5c064da7b8ed0e24212dcc65d30fda3c7477c
[ "Apache-2.0" ]
4,697
2017-12-30T12:15:43.000Z
2022-03-25T08:22:31.000Z
tests/op/test_opendla_op_split.cpp
zhouzy-creator/Tengine
fea5c064da7b8ed0e24212dcc65d30fda3c7477c
[ "Apache-2.0" ]
943
2018-01-02T06:15:00.000Z
2022-03-31T05:32:32.000Z
tests/op/test_opendla_op_split.cpp
zhouzy-creator/Tengine
fea5c064da7b8ed0e24212dcc65d30fda3c7477c
[ "Apache-2.0" ]
1,076
2017-12-30T12:15:46.000Z
2022-03-30T01:28:56.000Z
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * License); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * AS IS BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Copyright (c) 2020, OPEN AI LAB * Author: qtang@openailab.com */ #include "test_op.h" #include "graph/graph.h" #include "graph/node.h" #include "graph/tensor.h" #include "operator/prototype/split_param.h" #include "operator/prototype/eltwise_param.h" extern "C" { #include "vector.h" } float input_scale = 0.062992f; int input_zero_point = 0; float output_scale = 0.062992f; int output_zero_point = 0; int create_test_split_node(graph_t graph, const char* input_name, const char* node_name, int data_type, int layout, int n, int c, int h, int w) { (void)layout; (void)n; (void)c; (void)h; (void)w; /* create the test node */ struct node* test_node = (struct node*)create_graph_node(graph, node_name, "Split"); node_t eltwiseNode = create_graph_node(graph, "eltwise", "Eltwise"); tensor_t input_tensor = get_graph_tensor(graph, input_name); if (NULL == input_tensor) { fprintf(stderr, "create test node failed.\n"); return -1; } /* input tensors of test node */ set_node_input_tensor(test_node, 0, input_tensor); /* output tensors of test node */ tensor_t split_output_tensor0 = create_graph_tensor(graph, "out0", data_type); set_node_output_tensor(test_node, 0, split_output_tensor0, TENSOR_TYPE_VAR); set_tensor_quant_param(split_output_tensor0, &output_scale, &output_zero_point, 1); tensor_t split_output_tensor1 = create_graph_tensor(graph, "out1", data_type); set_node_output_tensor(test_node, 1, split_output_tensor1, TENSOR_TYPE_VAR); set_tensor_quant_param(split_output_tensor1, &output_scale, &output_zero_point, 1); /* set params */ struct split_param* param = (struct split_param*)(struct node*)test_node->op.param_mem; param->axis = 1; param->split_dim = 2; param->split_sizes_ = create_vector(sizeof(int), nullptr); int tmp = 1; push_vector_data(param->split_sizes_, &tmp); push_vector_data(param->split_sizes_, &tmp); /* set params */ struct eltwise_param* eltwise_param = (struct eltwise_param*)((struct node*)eltwiseNode)->op.param_mem; eltwise_param->type = ELT_SUM; set_node_input_tensor(eltwiseNode, 0, split_output_tensor0); set_node_input_tensor(eltwiseNode, 1, split_output_tensor1); tensor_t output_tensor = create_graph_tensor(graph, "eltwise_out", data_type); set_node_output_tensor(eltwiseNode, 0, output_tensor, TENSOR_TYPE_VAR); return 0; } /* * scale = (max - min) / 255 * zero_point = -min / scale * int8 = clip(round(float32 / scale) + zero_point, 0, 255) * float32 = (int8 - zero_point) * scale */ float input_fp32[18] = { 1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, }; float reference_out[9] = { 5.0f, 7.0f, 8.0f, 5.0f, 7.0f, 8.0f, 5.0f, 7.0f, 8.0f, }; float reference_out1[3] = { 4.0f, 5.0f, 6.0f, }; void get_int8_data(float* data_fp32, int8_t* date_i8, int size, float scale, int zero_point) { for (int i = 0; i < size; i++) { int udata = (round)(data_fp32[i] / scale + zero_point); if (udata > 255) udata = 255; else if (udata < 0) udata = 0; date_i8[i] = udata; } } int main(int argc, char* argv[]) { int n = 1, c = 2, h = 3, w = 3; const char* test_node_name = "split"; int data_type = TENGINE_DT_INT8; int layout = TENGINE_LAYOUT_NCHW; // init int ret = test_graph_init(); if (0 != ret) fprintf(stderr, "Tengine init failed.\n"); // create struct graph* ir_graph = (struct graph*)create_opendla_test_graph(test_node_name, data_type, layout, n, c, h, w, &create_test_split_node); if (NULL == ir_graph) return -1; set_log_level(LOG_INFO); dump_graph(ir_graph); // set quantize params struct tensor* input_tensor = (struct tensor*)get_graph_tensor(ir_graph, "input_node"); struct tensor* output_tensor = (struct tensor*)get_graph_tensor(ir_graph, "out0"); // tensor_t weight_tesnor = get_graph_input_tensor(ir_graph, 1, 0); set_tensor_quant_param(input_tensor, &input_scale, &input_zero_point, 1); set_tensor_quant_param(output_tensor, &output_scale, &output_zero_point, 1); // set input data int8_t input_i8[18] = {0}; get_int8_data(input_fp32, input_i8, 18, input_scale, input_zero_point); set_tensor_buffer(input_tensor, input_i8, 18 * sizeof(int8_t)); // graph run ret = test_graph_run(ir_graph); if (0 != ret) { fprintf(stderr, "Run graph error. ERRNO: %d.\n", ret); test_graph_release(ir_graph); return -1; } // get output and dequant int8_t* output_i8 = (int8_t*)output_tensor->data; int output_size = output_tensor->elem_num; get_tensor_quant_param(output_tensor, &output_scale, &output_zero_point, 1); float* output_data = (float*)malloc(output_size * sizeof(float)); for (int i = 0; i < output_size; i++) output_data[i] = ((float)output_i8[i] - (float)output_zero_point) * output_scale; // check the result ret = 0; for (int i = 0; i < output_size; i++) { if (fabsf(output_data[i] - reference_out[i]) > 0.1) { fprintf(stderr, "index:%d, a:%f, b:%f\n", i, output_data[i], reference_out[i]); ret = -1; } } if (ret == 0) fprintf(stderr, "test pass.\n"); else fprintf(stderr, "test failed.\n"); // exit test_graph_release(ir_graph); return ret; }
27.930736
143
0.656696
[ "vector" ]
b8b6a88f5c457756f1e6d1497d1109b5ac673237
19,388
cc
C++
mediapipe/calculators/image/bilateral_filter_calculator.cc
dwayne45/mediapipe
731d2b95363d58f12acb29a6f8435ec33fe548d9
[ "Apache-2.0" ]
2
2019-10-17T13:39:23.000Z
2019-10-17T13:41:19.000Z
mediapipe/calculators/image/bilateral_filter_calculator.cc
shashimanyam/mediapipe
dc9216dc595585d495250d0692afe35985d816ff
[ "Apache-2.0" ]
null
null
null
mediapipe/calculators/image/bilateral_filter_calculator.cc
shashimanyam/mediapipe
dc9216dc595585d495250d0692afe35985d816ff
[ "Apache-2.0" ]
4
2020-07-17T19:56:45.000Z
2021-07-08T11:50:23.000Z
// Copyright 2019 The MediaPipe Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <memory> #include <string> #include "mediapipe/calculators/image/bilateral_filter_calculator.pb.h" #include "mediapipe/framework/calculator_framework.h" #include "mediapipe/framework/calculator_options.pb.h" #include "mediapipe/framework/formats/image_format.pb.h" #include "mediapipe/framework/formats/image_frame.h" #include "mediapipe/framework/formats/image_frame_opencv.h" #include "mediapipe/framework/port/logging.h" #include "mediapipe/framework/port/opencv_core_inc.h" #include "mediapipe/framework/port/opencv_imgproc_inc.h" #include "mediapipe/framework/port/status.h" #include "mediapipe/framework/port/vector.h" #if defined(__ANDROID__) || defined(__EMSCRIPTEN__) #include "mediapipe/gpu/gl_calculator_helper.h" #include "mediapipe/gpu/gl_simple_shaders.h" #include "mediapipe/gpu/shader_util.h" #endif // __ANDROID__ || __EMSCRIPTEN__ namespace mediapipe { namespace { constexpr char kInputFrameTag[] = "IMAGE"; constexpr char kInputGuideTag[] = "GUIDE"; constexpr char kOutputFrameTag[] = "IMAGE"; constexpr char kInputFrameTagGpu[] = "IMAGE_GPU"; constexpr char kInputGuideTagGpu[] = "GUIDE_GPU"; constexpr char kOutputFrameTagGpu[] = "IMAGE_GPU"; enum { ATTRIB_VERTEX, ATTRIB_TEXTURE_POSITION, NUM_ATTRIBUTES }; } // namespace // A calculator for applying a bilateral filter to an image, // with an optional guide image (joint blateral). // // Inputs: // One of the following two IMAGE tags: // IMAGE: ImageFrame containing input image - Grayscale or RGB only. // IMAGE_GPU: GpuBuffer containing input image - Grayscale, RGB or RGBA. // // GUIDE (optional): ImageFrame guide image used to filter IMAGE. (N/A). // GUIDE_GPU (optional): GpuBuffer guide image used to filter IMAGE_GPU. // // Output: // One of the following two tags: // IMAGE: A filtered ImageFrame - Same as input. // IMAGE_GPU: A filtered GpuBuffer - RGBA // // Options: // sigma_space: Pixel radius: use (sigma_space*2+1)x(sigma_space*2+1) window. // This should be set based on output image pixel space. // sigma_color: Color variance: normalized [0-1] color difference allowed. // // Notes: // * When GUIDE is present, the output image is same size as GUIDE image; // otherwise, the output image is same size as input image. // * On GPU the kernel window is subsampled by approximately sqrt(sigma_space) // i.e. the step size is ~sqrt(sigma_space), // prioritizing performance > quality. // * TODO: Add CPU path for joint filter. // class BilateralFilterCalculator : public CalculatorBase { public: BilateralFilterCalculator() = default; ~BilateralFilterCalculator() override = default; static ::mediapipe::Status GetContract(CalculatorContract* cc); // From Calculator. ::mediapipe::Status Open(CalculatorContext* cc) override; ::mediapipe::Status Process(CalculatorContext* cc) override; ::mediapipe::Status Close(CalculatorContext* cc) override; private: ::mediapipe::Status RenderGpu(CalculatorContext* cc); ::mediapipe::Status RenderCpu(CalculatorContext* cc); ::mediapipe::Status GlSetup(CalculatorContext* cc); void GlRender(CalculatorContext* cc); mediapipe::BilateralFilterCalculatorOptions options_; float sigma_color_ = -1.f; float sigma_space_ = -1.f; bool use_gpu_ = false; bool gpu_initialized_ = false; #if defined(__ANDROID__) || defined(__EMSCRIPTEN__) mediapipe::GlCalculatorHelper gpu_helper_; GLuint program_ = 0; GLuint program_joint_ = 0; #endif // __ANDROID__ || __EMSCRIPTEN__ }; REGISTER_CALCULATOR(BilateralFilterCalculator); ::mediapipe::Status BilateralFilterCalculator::GetContract( CalculatorContract* cc) { CHECK_GE(cc->Inputs().NumEntries(), 1); if (cc->Inputs().HasTag(kInputFrameTag) && cc->Inputs().HasTag(kInputFrameTagGpu)) { return ::mediapipe::InternalError("Cannot have multiple input images."); } if (cc->Inputs().HasTag(kInputFrameTagGpu) != cc->Outputs().HasTag(kOutputFrameTagGpu)) { return ::mediapipe::InternalError("GPU output must have GPU input."); } // Input image to filter. #if defined(__ANDROID__) || defined(__EMSCRIPTEN__) if (cc->Inputs().HasTag(kInputFrameTagGpu)) { cc->Inputs().Tag(kInputFrameTagGpu).Set<mediapipe::GpuBuffer>(); } #endif // __ANDROID__ || __EMSCRIPTEN__ if (cc->Inputs().HasTag(kInputFrameTag)) { cc->Inputs().Tag(kInputFrameTag).Set<ImageFrame>(); } // Input guide image mask (optional) if (cc->Inputs().HasTag(kInputGuideTagGpu)) { #if defined(__ANDROID__) || defined(__EMSCRIPTEN__) cc->Inputs().Tag(kInputGuideTagGpu).Set<mediapipe::GpuBuffer>(); #endif // __ANDROID__ || __EMSCRIPTEN__ } if (cc->Inputs().HasTag(kInputGuideTag)) { cc->Inputs().Tag(kInputGuideTag).Set<ImageFrame>(); } // Output image. #if defined(__ANDROID__) || defined(__EMSCRIPTEN__) if (cc->Outputs().HasTag(kOutputFrameTagGpu)) { cc->Outputs().Tag(kOutputFrameTagGpu).Set<mediapipe::GpuBuffer>(); } #endif // __ANDROID__ || __EMSCRIPTEN__ if (cc->Outputs().HasTag(kOutputFrameTag)) { cc->Outputs().Tag(kOutputFrameTag).Set<ImageFrame>(); } #if defined(__ANDROID__) || defined(__EMSCRIPTEN__) RETURN_IF_ERROR(mediapipe::GlCalculatorHelper::UpdateContract(cc)); #endif // __ANDROID__ || __EMSCRIPTEN__ return ::mediapipe::OkStatus(); } ::mediapipe::Status BilateralFilterCalculator::Open(CalculatorContext* cc) { cc->SetOffset(TimestampDiff(0)); options_ = cc->Options<mediapipe::BilateralFilterCalculatorOptions>(); if (cc->Inputs().HasTag(kInputFrameTagGpu) && cc->Outputs().HasTag(kOutputFrameTagGpu)) { #if defined(__ANDROID__) || defined(__EMSCRIPTEN__) use_gpu_ = true; #else RET_CHECK_FAIL() << "GPU processing on non-Android not supported yet."; #endif // __ANDROID__ || __EMSCRIPTEN__ } sigma_color_ = options_.sigma_color(); sigma_space_ = options_.sigma_space(); CHECK_GE(sigma_color_, 0.0); CHECK_GE(sigma_space_, 0.0); if (!use_gpu_) sigma_color_ *= 255.0; if (use_gpu_) { #if defined(__ANDROID__) || defined(__EMSCRIPTEN__) RETURN_IF_ERROR(gpu_helper_.Open(cc)); #endif } return ::mediapipe::OkStatus(); } ::mediapipe::Status BilateralFilterCalculator::Process(CalculatorContext* cc) { if (use_gpu_) { #if defined(__ANDROID__) || defined(__EMSCRIPTEN__) RETURN_IF_ERROR( gpu_helper_.RunInGlContext([this, cc]() -> ::mediapipe::Status { if (!gpu_initialized_) { RETURN_IF_ERROR(GlSetup(cc)); gpu_initialized_ = true; } RETURN_IF_ERROR(RenderGpu(cc)); return ::mediapipe::OkStatus(); })); #endif // __ANDROID__ || __EMSCRIPTEN__ } else { RETURN_IF_ERROR(RenderCpu(cc)); } return ::mediapipe::OkStatus(); } ::mediapipe::Status BilateralFilterCalculator::Close(CalculatorContext* cc) { #if defined(__ANDROID__) || defined(__EMSCRIPTEN__) gpu_helper_.RunInGlContext([this] { if (program_) glDeleteProgram(program_); program_ = 0; if (program_joint_) glDeleteProgram(program_joint_); program_joint_ = 0; }); #endif // __ANDROID__ || __EMSCRIPTEN__ return ::mediapipe::OkStatus(); } ::mediapipe::Status BilateralFilterCalculator::RenderCpu( CalculatorContext* cc) { if (cc->Inputs().Tag(kInputFrameTag).IsEmpty()) { return ::mediapipe::OkStatus(); } const auto& input_frame = cc->Inputs().Tag(kInputFrameTag).Get<ImageFrame>(); auto input_mat = mediapipe::formats::MatView(&input_frame); // Only 1 or 3 channel images supported by OpenCV. if ((input_mat.channels() == 1 || input_mat.channels() == 3)) { return ::mediapipe::InternalError( "CPU filtering supports only 1 or 3 channel input images."); } auto output_frame = absl::make_unique<ImageFrame>( input_frame.Format(), input_mat.cols, input_mat.rows); const bool has_guide_image = cc->Inputs().HasTag(kInputGuideTag) && !cc->Inputs().Tag(kInputGuideTag).IsEmpty(); if (has_guide_image) { // cv::jointBilateralFilter() is in contrib module 'ximgproc'. return ::mediapipe::UnimplementedError( "CPU joint filtering support is not implemented yet."); } else { auto output_mat = mediapipe::formats::MatView(output_frame.get()); // Prefer setting 'd = sigma_space * 2' to match GPU definition of radius. cv::bilateralFilter(input_mat, output_mat, /*d=*/sigma_space_ * 2.0, sigma_color_, sigma_space_); } cc->Outputs() .Tag(kOutputFrameTag) .Add(output_frame.release(), cc->InputTimestamp()); return ::mediapipe::OkStatus(); } ::mediapipe::Status BilateralFilterCalculator::RenderGpu( CalculatorContext* cc) { if (cc->Inputs().Tag(kInputFrameTagGpu).IsEmpty()) { return ::mediapipe::OkStatus(); } #if defined(__ANDROID__) || defined(__EMSCRIPTEN__) const auto& input_frame = cc->Inputs().Tag(kInputFrameTagGpu).Get<mediapipe::GpuBuffer>(); auto input_texture = gpu_helper_.CreateSourceTexture(input_frame); mediapipe::GlTexture output_texture; const bool has_guide_image = cc->Inputs().HasTag(kInputGuideTagGpu) && !cc->Inputs().Tag(kInputGuideTagGpu).IsEmpty(); // Setup textures and Update image in GPU shader. if (has_guide_image) { // joint bilateral filter glUseProgram(program_joint_); const auto& guide_image = cc->Inputs().Tag(kInputGuideTagGpu).Get<mediapipe::GpuBuffer>(); auto guide_texture = gpu_helper_.CreateSourceTexture(guide_image); glUniform2f(glGetUniformLocation(program_joint_, "texel_size_guide"), 1.0 / guide_image.width(), 1.0 / guide_image.height()); output_texture = gpu_helper_.CreateDestinationTexture( guide_image.width(), guide_image.height(), mediapipe::GpuBufferFormat::kBGRA32); gpu_helper_.BindFramebuffer(output_texture); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, input_texture.name()); glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_2D, guide_texture.name()); GlRender(cc); glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_2D, 0); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, 0); guide_texture.Release(); } else { // regular bilateral filter glUseProgram(program_); glUniform2f(glGetUniformLocation(program_, "texel_size"), 1.0 / input_frame.width(), 1.0 / input_frame.height()); output_texture = gpu_helper_.CreateDestinationTexture( input_frame.width(), input_frame.height(), mediapipe::GpuBufferFormat::kBGRA32); gpu_helper_.BindFramebuffer(output_texture); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, input_texture.name()); GlRender(cc); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, 0); } glFlush(); // Send out image as GPU packet. auto output_frame = output_texture.GetFrame<mediapipe::GpuBuffer>(); cc->Outputs() .Tag(kOutputFrameTagGpu) .Add(output_frame.release(), cc->InputTimestamp()); // Cleanup input_texture.Release(); output_texture.Release(); #endif // __ANDROID__ || __EMSCRIPTEN__ return ::mediapipe::OkStatus(); } void BilateralFilterCalculator::GlRender(CalculatorContext* cc) { #if defined(__ANDROID__) || defined(__EMSCRIPTEN__) static const GLfloat square_vertices[] = { -1.0f, -1.0f, // bottom left 1.0f, -1.0f, // bottom right -1.0f, 1.0f, // top left 1.0f, 1.0f, // top right }; static const GLfloat texture_vertices[] = { 0.0f, 0.0f, // bottom left 1.0f, 0.0f, // bottom right 0.0f, 1.0f, // top left 1.0f, 1.0f, // top right }; // vertex storage GLuint vbo[2]; glGenBuffers(2, vbo); GLuint vao; glGenVertexArrays(1, &vao); glBindVertexArray(vao); // vbo 0 glBindBuffer(GL_ARRAY_BUFFER, vbo[0]); glBufferData(GL_ARRAY_BUFFER, 4 * 2 * sizeof(GLfloat), square_vertices, GL_STATIC_DRAW); glEnableVertexAttribArray(ATTRIB_VERTEX); glVertexAttribPointer(ATTRIB_VERTEX, 2, GL_FLOAT, 0, 0, nullptr); // vbo 1 glBindBuffer(GL_ARRAY_BUFFER, vbo[1]); glBufferData(GL_ARRAY_BUFFER, 4 * 2 * sizeof(GLfloat), texture_vertices, GL_STATIC_DRAW); glEnableVertexAttribArray(ATTRIB_TEXTURE_POSITION); glVertexAttribPointer(ATTRIB_TEXTURE_POSITION, 2, GL_FLOAT, 0, 0, nullptr); // draw glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); // cleanup glDisableVertexAttribArray(ATTRIB_VERTEX); glDisableVertexAttribArray(ATTRIB_TEXTURE_POSITION); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); glDeleteVertexArrays(1, &vao); glDeleteBuffers(2, vbo); #endif // __ANDROID__ || __EMSCRIPTEN__ } ::mediapipe::Status BilateralFilterCalculator::GlSetup(CalculatorContext* cc) { #if defined(__ANDROID__) || defined(__EMSCRIPTEN__) const GLint attr_location[NUM_ATTRIBUTES] = { ATTRIB_VERTEX, ATTRIB_TEXTURE_POSITION, }; const GLchar* attr_name[NUM_ATTRIBUTES] = { "position", "texture_coordinate", }; // We bake our sigma values directly into the shader, so the GLSL compiler can // optimize appropriately. std::string sigma_options_string = "const float sigma_space = " + std::to_string(sigma_space_) + "; const float sigma_color = " + std::to_string(sigma_color_) + ";\n"; // Shader to do bilateral filtering on input image based on sigma space/color. // Large kernel sizes are subsampled based on sqrt(sigma_space) window size, // denoted as 'sparsity' below. const std::string frag_src = GLES_VERSION_COMPAT R"( #if __VERSION__ < 130 #define in varying #endif // __VERSION__ < 130 #ifdef GL_ES #define fragColor gl_FragColor precision highp float; #else #define lowp #define mediump #define highp #define texture2D texture out vec4 fragColor; #endif // defined(GL_ES) in vec2 sample_coordinate; uniform sampler2D input_frame; )" + sigma_options_string + R"( uniform vec2 texel_size; const float kSparsityFactor = 0.66; // Higher is more sparse. const float sparsity = max(1.0, sqrt(sigma_space) * kSparsityFactor); const float step = sparsity; const float radius = sigma_space; const float offset = (step > 1.0) ? (step * 0.5) : (0.0); float gaussian(float x, float sigma) { float coeff = -0.5 / (sigma * sigma * 4.0 + 1.0e-6); return exp((x * x) * coeff); } void main() { vec2 center_uv = sample_coordinate; vec3 center_val = texture2D(input_frame, center_uv).rgb; vec3 new_val = vec3(0.0); float space_weight = 0.0; float color_weight = 0.0; float total_weight = 0.0; float sigma_texel = max(texel_size.x, texel_size.y) * sigma_space; // Subsample kernel space. for (float i = -radius+offset; i <= radius; i+=step) { for (float j = -radius+offset; j <= radius; j+=step) { vec2 shift = vec2(j, i) * texel_size; vec2 uv = vec2(center_uv + shift); vec3 val = texture2D(input_frame, uv).rgb; space_weight = gaussian(distance(center_uv, uv), sigma_texel); color_weight = gaussian(distance(center_val, val), sigma_color); total_weight += space_weight * color_weight; new_val += vec3(space_weight * color_weight) * val; } } new_val /= vec3(total_weight); fragColor = vec4(new_val, 1.0); } )"; // Create shader program and set parameters. mediapipe::GlhCreateProgram(mediapipe::kBasicVertexShader, frag_src.c_str(), NUM_ATTRIBUTES, (const GLchar**)&attr_name[0], attr_location, &program_); RET_CHECK(program_) << "Problem initializing the program."; glUseProgram(program_); glUniform1i(glGetUniformLocation(program_, "input_frame"), 1); // Shader to do joint bilateral filtering on input image based on // sigma space/color, and a Guide image. // Large kernel sizes are subsampled based on sqrt(sigma_space) window size, // denoted as 'sparsity' below. const std::string joint_frag_src = GLES_VERSION_COMPAT R"( #if __VERSION__ < 130 #define in varying #endif // __VERSION__ < 130 #ifdef GL_ES #define fragColor gl_FragColor precision highp float; #else #define lowp #define mediump #define highp #define texture2D texture out vec4 fragColor; #endif // defined(GL_ES) in vec2 sample_coordinate; uniform sampler2D input_frame; uniform sampler2D guide_frame; )" + sigma_options_string + R"( uniform vec2 texel_size_guide; // size of guide and resulting filtered image const float kSparsityFactor = 0.66; // Higher is more sparse. const float sparsity = max(1.0, sqrt(sigma_space) * kSparsityFactor); const float step = sparsity; const float radius = sigma_space; const float offset = (step > 1.0) ? (step * 0.5) : (0.0); float gaussian(float x, float sigma) { float coeff = -0.5 / (sigma * sigma * 4.0 + 1.0e-6); return exp((x * x) * coeff); } void main() { vec2 center_uv = sample_coordinate; vec3 center_val = texture2D(guide_frame, center_uv).rgb; vec3 new_val = vec3(0.0); float space_weight = 0.0; float color_weight = 0.0; float total_weight = 0.0; float sigma_texel = max(texel_size_guide.x, texel_size_guide.y) * sigma_space; // Subsample kernel space. for (float i = -radius+offset; i <= radius; i+=step) { for (float j = -radius+offset; j <= radius; j+=step) { vec2 shift = vec2(j, i) * texel_size_guide; vec2 uv = vec2(center_uv + shift); vec3 guide_val = texture2D(guide_frame, uv).rgb; vec3 out_val = texture2D(input_frame, uv).rgb; space_weight = gaussian(distance(center_uv, uv), sigma_texel); color_weight = gaussian(distance(center_val, guide_val), sigma_color); total_weight += space_weight * color_weight; new_val += vec3(space_weight * color_weight) * out_val; } } new_val /= vec3(total_weight); fragColor = vec4(new_val, 1.0); } )"; // Create shader program and set parameters. mediapipe::GlhCreateProgram( mediapipe::kBasicVertexShader, joint_frag_src.c_str(), NUM_ATTRIBUTES, (const GLchar**)&attr_name[0], attr_location, &program_joint_); RET_CHECK(program_joint_) << "Problem initializing the program."; glUseProgram(program_joint_); glUniform1i(glGetUniformLocation(program_joint_, "input_frame"), 1); glUniform1i(glGetUniformLocation(program_joint_, "guide_frame"), 2); #endif // __ANDROID__ || __EMSCRIPTEN__ return ::mediapipe::OkStatus(); } } // namespace mediapipe
34.99639
84
0.691252
[ "vector" ]
b8bc4d6e746b4eb7744589be6f7641431a0cff25
5,729
hpp
C++
include/scalesim/com/mpi/mpi_runner.hpp
asia-lab-sustech/ScaleSim
614869fe9ff2092e6c1f219cbcf44391118517d5
[ "MIT" ]
3
2019-06-26T15:11:26.000Z
2022-03-29T14:38:47.000Z
include/scalesim/com/mpi/mpi_runner.hpp
asia-lab-sustech/ScaleSim
614869fe9ff2092e6c1f219cbcf44391118517d5
[ "MIT" ]
null
null
null
include/scalesim/com/mpi/mpi_runner.hpp
asia-lab-sustech/ScaleSim
614869fe9ff2092e6c1f219cbcf44391118517d5
[ "MIT" ]
3
2019-05-02T12:21:25.000Z
2022-02-16T07:45:07.000Z
/* * mpi_runner.hpp * * Copyright (c) 2015 Masatoshi Hanai * * This software is released under MIT License. * See LICENSE. * */ #ifndef SCALESIM_COM_MPI_MPI_RUNNER_HPP_ #define SCALESIM_COM_MPI_MPI_RUNNER_HPP_ #include <vector> #include <iostream> #include <boost/function.hpp> #include <boost/mpi.hpp> #include <boost/mpi/collectives.hpp> #include <boost/optional.hpp> #include <boost/shared_ptr.hpp> #include <glog/logging.h> #include "scalesim/com/mpi/collection.hpp" #include "scalesim/com/mpi/global_sync.hpp" #include "scalesim/com/mpi/sender_receiver.hpp" #include "scalesim/simulation/sim_obj.hpp" #include "scalesim/util.hpp" namespace scalesim { template<class App> class mpi_thr { typedef boost::shared_ptr<mpi_thr<App> > mpi_thr_ptr; typedef std::vector<boost::mpi::request> requests; private: mpi_thr(): init_(false), loop_active_(false), finish_(false) {}; void operator=(const mpi_thr&); private: bool init_; bool loop_active_; bool finish_; mpi_collection<App> collection_; mpi_sender<App> sender_; mpi_receiver<App> receiver_; boost::thread* thread_; boost::function<void(ev_ptr<App>)> call_back_function_; boost::mpi::environment env_; boost::mpi::communicator comm_world_; public: virtual ~mpi_thr() {}; static mpi_thr<App>* instance() { static mpi_thr<App>* instance_; if (!instance_) { instance_ = new mpi_thr<App>(); } return instance_; }; static void del_instance() { mpi_thr<App>* instance_ = mpi_thr<App>::instance(); if (instance_ != NULL) { delete instance_; instance_ = NULL; } }; void init(const boost::function<void(const ev_ptr<App>&)>& callback_f); void start() { loop_active_ = true; init_ = false; }; void stop() { finish_ = true; loop_active_ = false; }; void finish(); void reset(); int mpi_rank() { return comm_world_.rank(); }; int mpi_size() { return comm_world_.size(); }; void buffer_send_message(int rank, const ev_ptr<App>& event); void barrier(bool& wait_barrier); template<class Obj> void shuffle(bool& wait, std::vector<boost::shared_ptr<const Obj> >& ret, std::vector<boost::shared_ptr<const Obj> >& objs, const parti_ptr& parti); void reduce_sum(bool& wait, long& ret, long val); private: void loop(); private: template<class Obj, class T = void> class shuffle_func { friend class mpi_thr; static void shuffle_impl(bool& wait, std::vector<boost::shared_ptr<const Obj> >& ret, std::vector<boost::shared_ptr<const Obj> >& objs, const parti_ptr& parti); }; template<class T> class shuffle_func<event<App>, T> { friend class mpi_thr; static void shuffle_impl(bool& wait, ev_vec<App>& ret, ev_vec<App>& objs, const parti_ptr& parti) { mpi_thr<App>::instance() ->collection_.wait_shuffle_event(wait, ret, objs, parti); }; }; template<class T> class shuffle_func<what_if<App>, T> { friend class mpi_thr; static void shuffle_impl(bool& wait, std::vector<boost::shared_ptr<const what_if<App> > >& ret, std::vector<boost::shared_ptr<const what_if<App> > >& objs, const parti_ptr& parti) { mpi_thr<App>::instance() ->collection_.wait_shuffle_what_if(wait, ret, objs, parti); }; }; }; template<class App> void mpi_thr<App>::init( const boost::function<void(const ev_ptr<App>&)>& callback_f) { init_ = true; collection_.init(&comm_world_); sender_.init(&comm_world_); receiver_.init(&comm_world_); mpi_gsync<App>::instance()->init(&comm_world_); call_back_function_ = callback_f; thread_ = new boost::thread(boost::bind(&mpi_thr<App>::loop, this)); } template<class App> void mpi_thr<App>::finish() { finish_ = false; thread_->join(); delete thread_; }; template<class App> void mpi_thr<App>::reset() { mpi_gsync<App>::instance()->reset_counter(); sender_.reset(); }; template<class App> void mpi_thr<App>::buffer_send_message(int rank, const ev_ptr<App>& event) { sender_.buffer_sendevent(rank, event); }; template<class App> void mpi_thr<App>::barrier(bool& wait_barrier) { DLOG_ASSERT(!loop_active_) << "Collection cannot be invoked during loop is active. " << "It can be invoked only after start() or after stop()"; collection_.wait_barrier(wait_barrier); }; template<class App> template<class Obj> void mpi_thr<App>::shuffle(bool& wait, std::vector<boost::shared_ptr<const Obj> >& ret, std::vector<boost::shared_ptr<const Obj> >& objs, const parti_ptr& parti) { shuffle_func<Obj>::shuffle_impl(wait, ret, objs, parti); }; template<class App> void mpi_thr<App>::reduce_sum(bool& wait, long& ret, long val) { DLOG_ASSERT(!loop_active_) << "Collection cannot be invoked during loop is active. " << "It can be invoked only after start() or after stop()"; collection_.wait_reduce_sum(wait, ret, val); }; template<class App> void mpi_thr<App>::loop() { while (init_) { /* wait global communication */ collection_.check_collection(); } while (loop_active_) { /* global sync */ mpi_gsync<App>::instance()->check_sync(); /* send and receive */ sender_.async_send(); receiver_.receive(call_back_function_); sender_.check_send(); } while (finish_) { /* wait global communication */ collection_.check_collection(); } }; } /* namespace scalesim */ #endif /* SCALESIM_COM_MPI_MPI_RUNNER_HPP_ */
27.946341
80
0.649852
[ "vector" ]
b8bf0ce7051d4ddf600131711e8c86a0ff462a41
4,177
cpp
C++
tests/test02/threadWorker.cpp
CETONI-Software/3rdparty-QDeferred
662bdc6bc8debf025859ddc59e5dfb8f96b1e5b9
[ "MIT" ]
51
2019-02-11T15:06:22.000Z
2022-03-29T06:52:19.000Z
tests/test02/threadWorker.cpp
CETONI-Software/3rdparty-QDeferred
662bdc6bc8debf025859ddc59e5dfb8f96b1e5b9
[ "MIT" ]
4
2020-10-28T10:20:53.000Z
2022-01-24T08:23:15.000Z
tests/test02/threadWorker.cpp
CETONI-Software/3rdparty-QDeferred
662bdc6bc8debf025859ddc59e5dfb8f96b1e5b9
[ "MIT" ]
12
2019-11-19T19:14:53.000Z
2022-03-29T06:52:20.000Z
#include "threadworker.h" #include <QTimer> #include <QDebug> // THREADWORKEREVENT ------------------------------------------------- ThreadWorkerEvent::ThreadWorkerEvent() : QEvent(QWORKERPROXY_EVENT_TYPE) { // nothing to do here } // THREADWORKER ----------------------------------------------------- ThreadWorker::ThreadWorker() : QObject(nullptr) { } bool ThreadWorker::event(QEvent * ev) { if (ev->type() == QWORKERPROXY_EVENT_TYPE) { // call function static_cast<ThreadWorkerEvent*>(ev)->m_eventFunc(); // return event processed return true; } // Call base implementation (make sure the rest of events are handled) return QObject::event(ev); } // THREADCONTROLLER ----------------------------------------------- ThreadController::ThreadController() { mp_worker = new ThreadWorker; mp_worker->moveToThread(&m_workerThread); QObject::connect(&m_workerThread, &QThread::finished, mp_worker, &QObject::deleteLater); m_workerThread.start(); } ThreadController::~ThreadController() { m_workerThread.quit(); m_workerThread.wait(); } void ThreadController::doWorkOnFirstDeferred(QDefer deferred1, QDeferred<int, double> deferred2) { // exec in thread ThreadWorkerEvent * p_Evt = new ThreadWorkerEvent; p_Evt->m_eventFunc = [deferred1, deferred2]() mutable { // print id auto p_thread = QThread::currentThread(); qDebug() << "[INFO] 1 thread id = " << p_thread; // set done deferred1.done([p_thread]() { qDebug() << "[INFO] DEF1::Callback defined in 1 thread " << p_thread << ", exec in thread " << QThread::currentThread(); }); deferred2.done([p_thread](int i, double d) { Q_UNUSED(i) Q_UNUSED(d) qDebug() << "[INFO] DEF2::Callback defined in 1 thread " << p_thread << ", exec in thread " << QThread::currentThread(); }); QDefer::when(deferred1, deferred2).done([p_thread]() { qDebug() << "[INFO] WHEN::Callback defined in 1 thread " << p_thread << ", exec in thread " << QThread::currentThread(); }); // set resolve timer QTimer::singleShot(1000, [deferred1]() mutable { qDebug() << "[INFO] DEF1::Resolved in 1 thread ********" << QThread::currentThread() << "********"; deferred1.resolve(); }); }; // post event for object with correct thread affinity QCoreApplication::postEvent(mp_worker, p_Evt); } void ThreadController::doWorkOnSecondDeferred(QDefer deferred1, QDeferred<int, double> deferred2) { // exec in thread ThreadWorkerEvent * p_Evt = new ThreadWorkerEvent; p_Evt->m_eventFunc = [deferred1, deferred2]() mutable { // print id auto p_thread = QThread::currentThread(); qDebug() << "[INFO] 2 thread id = " << p_thread; // set done deferred2.done([p_thread](int i, double d) { Q_UNUSED(i) Q_UNUSED(d) qDebug() << "[INFO] DEF2::Callback defined in 2 thread " << p_thread << ", exec in thread " << QThread::currentThread(); }); deferred1.done([p_thread]() { qDebug() << "[INFO] DEF1::Callback defined in 2 thread " << p_thread << ", exec in thread " << QThread::currentThread(); }); QDefer::when(deferred1, deferred2).done([p_thread]() { qDebug() << "[INFO] WHEN::Callback defined in 2 thread " << p_thread << ", exec in thread " << QThread::currentThread(); }); // set resolve timer QTimer::singleShot(1200, [deferred2]() mutable { int iNum = 666; double dNum = 666.666; qDebug() << "[INFO] DEF2::Resolved in 2 thread ********" << QThread::currentThread() << "********"; deferred2.resolve(iNum, dNum); }); }; // post event for object with correct thread affinity QCoreApplication::postEvent(mp_worker, p_Evt); } QDeferred<int> ThreadController::doProgressWork(int delay) { QDeferred<int> retDeferred; // exec in thread ThreadWorkerEvent * p_Evt = new ThreadWorkerEvent; p_Evt->m_eventFunc = [retDeferred, delay]() mutable { // set resolve timer QTimer::singleShot(delay, [retDeferred]() mutable { int iNum = 13; qDebug() << "[INFO] DEF3::Resolved in 2 thread ********" << QThread::currentThread() << "********"; retDeferred.resolve(iNum); }); }; // post event for object with correct thread affinity QCoreApplication::postEvent(mp_worker, p_Evt); // return unresolved deferred return retDeferred; }
32.632813
123
0.652382
[ "object" ]
b8c2d01d0ce127fe8d469030267b0c558db63543
9,161
cpp
C++
src/x86.cpp
raa-eruanna/ProjectPanther
7d703c162b4ede25faa3e99cacacb4fc79fb77da
[ "RSA-MD" ]
2
2018-01-18T21:30:20.000Z
2018-01-19T02:24:46.000Z
src/x86.cpp
raa-eruanna/ProjectPanther
7d703c162b4ede25faa3e99cacacb4fc79fb77da
[ "RSA-MD" ]
null
null
null
src/x86.cpp
raa-eruanna/ProjectPanther
7d703c162b4ede25faa3e99cacacb4fc79fb77da
[ "RSA-MD" ]
null
null
null
/* ** ** **--------------------------------------------------------------------------- ** Copyright 2005-2016 Randy Heit ** Copyright 2005-2016 Christoph Oelckers ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions ** are met: ** ** 1. Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** 2. Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in the ** documentation and/or other materials provided with the distribution. ** 3. The name of the author may not be used to endorse or promote products ** derived from this software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR ** IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES ** OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ** IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, ** INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT ** NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF ** THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **--------------------------------------------------------------------------- ** */ #include "doomtype.h" #include "doomdef.h" #include "x86.h" CPUInfo CPU; #if !defined(__amd64__) && !defined(__i386__) && !defined(_M_IX86) && !defined(_M_X64) void CheckCPUID(CPUInfo *cpu) { memset(cpu, 0, sizeof(*cpu)); cpu->DataL1LineSize = 32; // Assume a 32-byte cache line } void DumpCPUInfo(const CPUInfo *cpu) { } #else #ifdef _MSC_VER #include <intrin.h> #endif #include <mmintrin.h> #include <emmintrin.h> #ifdef __GNUC__ #if defined(__i386__) && defined(__PIC__) // %ebx may by the PIC register. */ #define __cpuid(output, func) \ __asm__ __volatile__("xchgl\t%%ebx, %1\n\t" \ "cpuid\n\t" \ "xchgl\t%%ebx, %1\n\t" \ : "=a" ((output)[0]), "=r" ((output)[1]), "=c" ((output)[2]), "=d" ((output)[3]) \ : "a" (func)); #else #define __cpuid(output, func) __asm__ __volatile__("cpuid" : "=a" ((output)[0]),\ "=b" ((output)[1]), "=c" ((output)[2]), "=d" ((output)[3]) : "a" (func)); #endif #endif void CheckCPUID(CPUInfo *cpu) { int foo[4]; unsigned int maxext; memset(cpu, 0, sizeof(*cpu)); cpu->DataL1LineSize = 32; // Assume a 32-byte cache line #if !defined(_M_IX86) && !defined(__i386__) && !defined(_M_X64) && !defined(__amd64__) return; #else #if defined(_M_IX86) || defined(__i386__) // Old 486s do not have CPUID, so we must test for its presence. // This code is adapted from the samples in AMD's document // entitled "AMD-K6 MMX Processor Multimedia Extensions." #ifndef __GNUC__ __asm { pushfd // save EFLAGS pop eax // store EFLAGS in EAX mov ecx,eax // save in ECX for later testing xor eax,0x00200000 // toggle bit 21 push eax // put to stack popfd // save changed EAX to EFLAGS pushfd // push EFLAGS to TOS pop eax // store EFLAGS in EAX cmp eax,ecx // see if bit 21 has changed jne haveid // if no change, then no CPUID } return; haveid: #else int oldfd, newfd; __asm__ __volatile__("\t" "pushf\n\t" "popl %0\n\t" "movl %0,%1\n\t" "xorl $0x200000,%0\n\t" "pushl %0\n\t" "popf\n\t" "pushf\n\t" "popl %0\n\t" : "=r" (newfd), "=r" (oldfd)); if (oldfd == newfd) { return; } #endif #endif // Get vendor ID __cpuid(foo, 0); cpu->dwVendorID[0] = foo[1]; cpu->dwVendorID[1] = foo[3]; cpu->dwVendorID[2] = foo[2]; if (foo[1] == MAKE_ID('A','u','t','h') && foo[3] == MAKE_ID('e','n','t','i') && foo[2] == MAKE_ID('c','A','M','D')) { cpu->bIsAMD = true; } // Get features flags and other info __cpuid(foo, 1); cpu->FeatureFlags[0] = foo[1]; // Store brand index and other stuff cpu->FeatureFlags[1] = foo[2]; // Store extended feature flags cpu->FeatureFlags[2] = foo[3]; // Store feature flags // If CLFLUSH instruction is supported, get the real cache line size. if (foo[3] & (1 << 19)) { cpu->DataL1LineSize = (foo[1] & 0xFF00) >> (8 - 3); } cpu->Stepping = foo[0] & 0x0F; cpu->Type = (foo[0] & 0x3000) >> 12; // valid on Intel only cpu->Model = (foo[0] & 0xF0) >> 4; cpu->Family = (foo[0] & 0xF00) >> 8; if (cpu->Family == 15) { // Add extended family. cpu->Family += (foo[0] >> 20) & 0xFF; } if (cpu->Family == 6 || cpu->Family == 15) { // Add extended model ID. cpu->Model |= (foo[0] >> 12) & 0xF0; } // Check for extended functions. __cpuid(foo, 0x80000000); maxext = (unsigned int)foo[0]; if (maxext >= 0x80000004) { // Get processor brand string. __cpuid((int *)&cpu->dwCPUString[0], 0x80000002); __cpuid((int *)&cpu->dwCPUString[4], 0x80000003); __cpuid((int *)&cpu->dwCPUString[8], 0x80000004); } if (cpu->bIsAMD) { if (maxext >= 0x80000005) { // Get data L1 cache info. __cpuid(foo, 0x80000005); cpu->AMD_DataL1Info = foo[2]; } if (maxext >= 0x80000001) { // Get AMD-specific feature flags. __cpuid(foo, 0x80000001); cpu->AMDStepping = foo[0] & 0x0F; cpu->AMDModel = (foo[0] & 0xF0) >> 4; cpu->AMDFamily = (foo[0] & 0xF00) >> 8; if (cpu->AMDFamily == 15) { // Add extended model and family. cpu->AMDFamily += (foo[0] >> 20) & 0xFF; cpu->AMDModel |= (foo[0] >> 12) & 0xF0; } cpu->FeatureFlags[3] = foo[3]; // AMD feature flags } } #endif } void DumpCPUInfo(const CPUInfo *cpu) { char cpustring[4*4*3+1]; // Why does Intel right-justify this string (on P4s) // or add extra spaces (on Cores)? const char *f = cpu->CPUString; char *t; // Skip extra whitespace at the beginning. while (*f == ' ') { ++f; } // Copy string to temp buffer, but condense consecutive // spaces to a single space character. for (t = cpustring; *f != '\0'; ++f) { if (*f == ' ' && *(f - 1) == ' ') { continue; } *t++ = *f; } *t = '\0'; if (cpu->VendorID[0] && !batchrun) { Printf("CPU Vendor ID: %s\n", cpu->VendorID); if (cpustring[0]) { Printf(" Name: %s\n", cpustring); } if (cpu->bIsAMD) { Printf(" Family %d (%d), Model %d, Stepping %d\n", cpu->Family, cpu->AMDFamily, cpu->AMDModel, cpu->AMDStepping); } else { Printf(" Family %d, Model %d, Stepping %d\n", cpu->Family, cpu->Model, cpu->Stepping); } Printf(" Features:"); if (cpu->bSSE2) Printf(" SSE2"); if (cpu->bSSE3) Printf(" SSE3"); if (cpu->bSSSE3) Printf(" SSSE3"); if (cpu->bSSE41) Printf(" SSE4.1"); if (cpu->bSSE42) Printf(" SSE4.2"); if (cpu->b3DNow) Printf(" 3DNow!"); if (cpu->b3DNowPlus) Printf(" 3DNow!+"); Printf ("\n"); } } void DoBlending_SSE2(const PalEntry *from, PalEntry *to, int count, int r, int g, int b, int a) { __m128i blendcolor; __m128i blendalpha; __m128i zero; __m128i blending256; __m128i color1; __m128i color2; size_t unaligned; unaligned = ((size_t)from | (size_t)to) & 0xF; #if defined(__amd64__) || defined(_M_X64) int64_t color; blending256 = _mm_set_epi64x(0x10001000100ll, 0x10001000100ll); color = ((int64_t)r << 32) | (g << 16) | b; blendcolor = _mm_set_epi64x(color, color); color = ((int64_t)a << 32) | (a << 16) | a; blendalpha = _mm_set_epi64x(color, color); #else int color; blending256 = _mm_set_epi32(0x100, 0x1000100, 0x100, 0x1000100); color = (g << 16) | b; blendcolor = _mm_set_epi32(r, color, r, color); color = (a << 16) | a; blendalpha = _mm_set_epi32(a, color, a, color); #endif blendcolor = _mm_mullo_epi16(blendcolor, blendalpha); // premultiply blend by alpha blendalpha = _mm_subs_epu16(blending256, blendalpha); // one minus alpha zero = _mm_setzero_si128(); if (unaligned) { for (count >>= 2; count > 0; --count) { color1 = _mm_loadu_si128((__m128i *)from); from += 4; color2 = _mm_unpackhi_epi8(color1, zero); color1 = _mm_unpacklo_epi8(color1, zero); color1 = _mm_mullo_epi16(blendalpha, color1); color2 = _mm_mullo_epi16(blendalpha, color2); color1 = _mm_adds_epu16(blendcolor, color1); color2 = _mm_adds_epu16(blendcolor, color2); color1 = _mm_srli_epi16(color1, 8); color2 = _mm_srli_epi16(color2, 8); _mm_storeu_si128((__m128i *)to, _mm_packus_epi16(color1, color2)); to += 4; } } else { for (count >>= 2; count > 0; --count) { color1 = _mm_load_si128((__m128i *)from); from += 4; color2 = _mm_unpackhi_epi8(color1, zero); color1 = _mm_unpacklo_epi8(color1, zero); color1 = _mm_mullo_epi16(blendalpha, color1); color2 = _mm_mullo_epi16(blendalpha, color2); color1 = _mm_adds_epu16(blendcolor, color1); color2 = _mm_adds_epu16(blendcolor, color2); color1 = _mm_srli_epi16(color1, 8); color2 = _mm_srli_epi16(color2, 8); _mm_store_si128((__m128i *)to, _mm_packus_epi16(color1, color2)); to += 4; } } } #endif
27.264881
95
0.634756
[ "model" ]
fef7204a08b8b87dc9400229b3475dc69ab302e1
26,948
cxx
C++
PWG/Tools/AliMCSpectraWeights.cxx
eciesla/AliPhysics
a9a6dc33c8793ea999348c57cebbce445797e8e4
[ "BSD-3-Clause" ]
null
null
null
PWG/Tools/AliMCSpectraWeights.cxx
eciesla/AliPhysics
a9a6dc33c8793ea999348c57cebbce445797e8e4
[ "BSD-3-Clause" ]
null
null
null
PWG/Tools/AliMCSpectraWeights.cxx
eciesla/AliPhysics
a9a6dc33c8793ea999348c57cebbce445797e8e4
[ "BSD-3-Clause" ]
null
null
null
/*! \file AliMCSpectraWeights.cxx \brief Class for re-weighting particle abundances in MC simulations \author Patrick Huhn \date 25/10/2019 */ #include "AliMCSpectraWeights.h" #include "AliMCEvent.h" #include "AliStack.h" #include "TFile.h" #include "TParticle.h" #include "TParticlePDG.h" ClassImp(AliMCSpectraWeights); AliMCSpectraWeights::AliMCSpectraWeights() : TNamed(), // default constructor fHistMCGenPrimTrackParticle(0), fHistDataFractions(0), fHistMCFractions(0), fHistMCWeights(0), fBinsPt(0), fBinsMultCent(0), fstCollisionSystem("pp"), fNPartTypes(6), fstPartTypes(0), fNCentralities(0), fstCentralities(0), fstFileMCSpectra(""), fstFilePublished(""), fstSavedObjName("fMCSpectraWeights"),fstSavedListName("dNdPt_ParCor"), fUseMultiplicity(kTRUE), fbTaskStatus(0), fFlag(AliMCSpectraWeights::SysFlag::kNominal) { fbTaskStatus = AliMCSpectraWeights::TaskState::kAllEmpty; } // non-default contructor; way to go AliMCSpectraWeights::AliMCSpectraWeights(const char *collisionSystem, const char* name, AliMCSpectraWeights::SysFlag flag) : TNamed(name, name), fHistMCGenPrimTrackParticle(0), fHistDataFractions(0), fHistMCFractions(0), fHistMCWeights(0), fBinsPt(0), fBinsMultCent(0), fstCollisionSystem("pp"), fNPartTypes(6), fstPartTypes(0), fNCentralities(0), fstCentralities(0), fstFileMCSpectra(""), fstFilePublished(""), fstSavedObjName("fMCSpectraWeights"),fstSavedListName("dNdPt_ParCor"), fUseMultiplicity(kTRUE), fbTaskStatus(0), fFlag(flag) { fstCollisionSystem = collisionSystem; fstCollisionSystem.ToLower(); //setting uniform name if(fstCollisionSystem=="pp" || fstCollisionSystem=="p-p") fstCollisionSystem = "pp"; else if(fstCollisionSystem=="ppb" || fstCollisionSystem=="p-pb") fstCollisionSystem="ppb"; else if(fstCollisionSystem=="pbpb" || fstCollisionSystem=="pb-pb") fstCollisionSystem="pbpb"; else if(fstCollisionSystem=="xexe" || fstCollisionSystem=="xe-xe") fstCollisionSystem="xexe"; else fstCollisionSystem="pp"; // set default Binning // pT binning Double_t bins[44] = {0.0, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95, 1.0, 1.1, 1.2, 1.4, 1.6, 1.8, 2.0, 2.2, 2.4, 2.6, 2.8, 3.0, 3.2, 3.6, 4.0, 5.0, 6.0, 8.0, 10.0, 13.0, 20.0, 30.0, 50.0, 80.0, 100.0, 200.0}; fBinsPt = new TArrayD(44, bins); // if(bins) delete bins; // multiplicity binning if (fstCollisionSystem.Contains("pp")) { fNCentralities = 10; fstCentralities = new TString[fNCentralities]; for (int icent = 0; icent < fNCentralities; icent++) { fstCentralities[icent] = Form("%d", icent); } Double_t mulBins[51] = {0}; for (int i = 0; i < 51; ++i) { mulBins[i] = i; } fBinsMultCent = new TArrayD(51, mulBins); // if(mulBins) delete mulBins; } else if (fstCollisionSystem.Contains("ppb")){ Double_t mulBins[301] = {0}; for (int i = 0; i < 301; ++i) { mulBins[i] = i; } fBinsMultCent = new TArrayD(301, mulBins); // if(mulBins) delete mulBins; } else if (fstCollisionSystem.Contains("pbpb")) { Double_t mulBins[201] = {0}; for (int i = 0; i < 201; ++i) { mulBins[i] = i * 25; } fBinsMultCent = new TArrayD(201, mulBins); // if(mulBins) delete mulBins; } else if (fstCollisionSystem.Contains("xexe")) { Double_t mulBins[201] = {0}; for (int i = 0; i < 201; ++i) { mulBins[i] = i * 25; } fBinsMultCent = new TArrayD(201, mulBins); // if(mulBins) delete mulBins; } else { Double_t mulBins[101] = {0}; for (int i = 0; i < 101; ++i) { mulBins[i] = i; } fBinsMultCent = new TArrayD(101, mulBins); // if(mulBins) delete mulBins; } if(!fstCollisionSystem.Contains("pp")) { TString cent[] = {"MB", "c0005", "c0510", "c0010", "c1020", "c2040", "c4060", "c6080"}; fNCentralities = 8; fstCentralities = new TString[fNCentralities]; for (int icent = 0; icent < fNCentralities; icent++) { fstCentralities[icent] = cent[icent]; } } fstPartTypes = new TString[6]; fstPartTypes[AliMCSpectraWeights::ParticleType::kPion] = "Pion"; fstPartTypes[AliMCSpectraWeights::ParticleType::kProtons] = "Proton"; fstPartTypes[AliMCSpectraWeights::ParticleType::kKaon] = "Kaon"; fstPartTypes[AliMCSpectraWeights::ParticleType::kSigmaMinus] = "SigmaMinus"; fstPartTypes[AliMCSpectraWeights::ParticleType::kSigmaPlus] = "SigmaPlus"; fstPartTypes[AliMCSpectraWeights::ParticleType::kRest] = "Rest"; fbTaskStatus = AliMCSpectraWeights::TaskState::kAllEmpty; fstFilePublished = "alien:///alice/cern.ch/user/p/phuhn/AllPublishedFractions.root"; // fstFilePublished = "/home/alidock/particle-composition-correction/data/published/ppMult/ppDataMultFractions.root"; } AliMCSpectraWeights::~AliMCSpectraWeights() { // if (fHistMCGenPrimTrackParticle) // delete fHistMCGenPrimTrackParticle; if (fHistDataFractions) delete fHistDataFractions; if (fHistMCFractions) delete fHistMCFractions; if (fHistMCWeights) delete fHistMCWeights; if (fBinsPt) delete fBinsPt; if (fBinsMultCent) delete fBinsMultCent; if (fstPartTypes) delete fstPartTypes; } void AliMCSpectraWeights::Init() { // Histograms AliMCSpectraWeights::InitHistos(); if (fstFileMCSpectra.Length() > 5) // *.root { // printf("AliMCSpectraWeights:: Opening %s \n", fstFileMCSpectra.Data()); TFile* fInput = TFile::Open(fstFileMCSpectra.Data()); if(fInput) { if (fInput->GetNkeys() != 1) { if(!fstSavedListName.Contains("dNdPt_ParCor")) printf("AliMCSpectraWeights::WARNING: more than 1 list in the streamed file; please specify; using 1st list;\n\n"); } else fstSavedListName = fInput->GetListOfKeys()->At(0)->GetName(); // printf("AliMCSpectraWeights:: Loading %s from list %s\n", fstSavedObjName.Data(), fstSavedListName.Data()); TList *listMC = (TList*)fInput->Get(fstSavedListName); if(!listMC) {printf("AliMCSpectraWeights::ERROR: could not load list in streamed file\n");} else{ fHistMCGenPrimTrackParticle = (THnF*)listMC->FindObject("fHistMCGenPrimTrackParticle"); if(!fHistMCGenPrimTrackParticle) { printf("AliMCSpectraWeights::WARNING: Couln't get fHistMCGenPrimTrackParticle\n" ); AliMCSpectraWeights* inWeights = (AliMCSpectraWeights*)listMC->FindObject(fstSavedObjName.Data()); if(AliMCSpectraWeights::LoadFromAliMCSpectraWeight(inWeights)) fbTaskStatus = AliMCSpectraWeights::TaskState::kMCSpectraObtained; } if(fHistMCGenPrimTrackParticle->GetEntries()>0) fbTaskStatus = AliMCSpectraWeights::TaskState::kMCSpectraObtained; // if(inWeights) delete inWeights; } } // else printf("AliMCSpectraWeights::WARNING: %s can not be loaded\n ", fstFileMCSpectra.Data()); if(fInput) {fInput->Close(); delete fInput;} } // Loading measured fractions if(fbTaskStatus == AliMCSpectraWeights::TaskState::kMCSpectraObtained) { AliMCSpectraWeights::LoadMeasuredFractions(); fbTaskStatus = AliMCSpectraWeights::TaskState::kDataFractionLoaded; } //Calculating weight factors if(fbTaskStatus == AliMCSpectraWeights::TaskState::kDataFractionLoaded) { if(AliMCSpectraWeights::CalculateMCWeights()) { // printf("AliMCSpectraWeights::Calculating MC Weight factors succsessfull\n"); fbTaskStatus = AliMCSpectraWeights::TaskState::kMCWeightCalculated; } // else printf("AliMCSpectraWeights::WARNING Calculating weight factors not succsessfull\n"); } // printf("AliMCSpectraWeights: Status after init: %d\n", // AliMCSpectraWeights::GetTaskStatus()); } void AliMCSpectraWeights::InitHistos() { // Initalizing histograms // histogram charged patricles pt:multcent:type const Int_t iNumberOfParticles = 6; Int_t nBinsTrackParticle[3] = { fBinsPt->GetSize() - 1, fBinsMultCent->GetSize() - 1, iNumberOfParticles}; Double_t minTrackParticle[3] = {fBinsPt->GetAt(0), fBinsMultCent->GetAt(0), 0}; Double_t maxTrackParticle[3] = { fBinsPt->GetAt(fBinsPt->GetSize() - 1), fBinsMultCent->GetAt(fBinsMultCent->GetSize() - 1), iNumberOfParticles}; const Int_t iNumberOfParticlesDATA = 5; Int_t nBinsTrackParticleDATA[3] = {fBinsPt->GetSize() - 1, fBinsMultCent->GetSize() - 1, iNumberOfParticlesDATA}; Double_t minTrackParticleDATA[3] = {fBinsPt->GetAt(0), fBinsMultCent->GetAt(0), 0}; Double_t maxTrackParticleDATA[3] = {fBinsPt->GetAt(fBinsPt->GetSize() - 1), fBinsMultCent->GetAt(fBinsMultCent->GetSize() - 1), iNumberOfParticlesDATA}; Int_t nBinsTrackParticleMC[3] = {fBinsPt->GetSize() - 1, fBinsMultCent->GetSize() - 1, iNumberOfParticles}; Double_t minTrackParticleMC[3] = {fBinsPt->GetAt(0), fBinsMultCent->GetAt(0), 0}; Double_t maxTrackParticleMC[3] = {fBinsPt->GetAt(fBinsPt->GetSize() - 1), fBinsMultCent->GetAt(fBinsMultCent->GetSize() - 1), iNumberOfParticles}; const Int_t iNumberOfParticlesFRACTION = 5; Int_t nBinsTrackParticleFRACTION[3] = {fBinsPt->GetSize() - 1, fBinsMultCent->GetSize() - 1, iNumberOfParticlesFRACTION}; Double_t maxTrackParticleFRACTION[3] = { fBinsPt->GetAt(fBinsPt->GetSize() - 1), static_cast<Double_t>(fBinsMultCent->GetAt(fBinsMultCent->GetSize() - 1)), static_cast<Double_t>(iNumberOfParticlesFRACTION)}; fHistMCGenPrimTrackParticle = new THnF("fHistMCGenPrimTrackParticle", "histogram for charged particle composition", 3, nBinsTrackParticle, minTrackParticle, maxTrackParticle); fHistMCGenPrimTrackParticle->SetBinEdges(0, fBinsPt->GetArray()); fHistMCGenPrimTrackParticle->SetBinEdges(1, fBinsMultCent->GetArray()); fHistMCGenPrimTrackParticle->GetAxis(0)->SetTitle("p_{T} (GeV/c)"); fHistMCGenPrimTrackParticle->GetAxis(1)->SetTitle( "multiplicity or centrality"); fHistMCGenPrimTrackParticle->GetAxis(2)->SetTitle("Particle type"); fHistMCGenPrimTrackParticle->Sumw2(); fHistDataFractions = new THnF( "fHistDataFractions", "DATA fractions histogram", 3, nBinsTrackParticleDATA, minTrackParticleDATA, maxTrackParticleDATA); fHistDataFractions->SetBinEdges(0, fBinsPt->GetArray()); fHistDataFractions->GetAxis(0)->SetTitle("p_{T} (GeV/c)"); fHistMCGenPrimTrackParticle->GetAxis(1)->SetTitle( "multiplicity or centrality"); fHistDataFractions->GetAxis(2)->SetTitle("Particle type"); fHistDataFractions->Sumw2(); fHistMCFractions = new THnF( "fHistMCFractions", "MC fractions histogram", 3, nBinsTrackParticleMC, minTrackParticleMC, maxTrackParticleMC); fHistMCFractions->SetBinEdges(0, fBinsPt->GetArray()); fHistMCFractions->GetAxis(0)->SetTitle("p_{T} (GeV/c)"); fHistMCGenPrimTrackParticle->GetAxis(1)->SetTitle( "multiplicity or centrality"); fHistMCFractions->GetAxis(2)->SetTitle("Particle type"); fHistMCFractions->Sumw2(); fHistMCWeights = new THnF( "fHistMCWeights", "MC weight histogram for charged particle composition", 3, nBinsTrackParticleFRACTION, minTrackParticleDATA, maxTrackParticleFRACTION); fHistMCWeights->SetBinEdges(0, fBinsPt->GetArray()); fHistMCWeights->GetAxis(0)->SetTitle("p_{T} (GeV/c)"); fHistMCGenPrimTrackParticle->GetAxis(1)->SetTitle( "multiplicity or centrality"); fHistMCWeights->GetAxis(2)->SetTitle("Particle type"); fHistMCWeights->Sumw2(); // printf("AliMCSpectraWeights: init histos successful\n"); // works } void AliMCSpectraWeights::LoadMeasuredFractions() { // printf("AliMCSpectraWeights:: Loading %s\n", fstFilePublished.Data()); //TFile *fMeasuredFile = AliDataFile::OpenOADB(fstFilePublished.Data()); TFile *fMeasuredFile = TFile::Open(fstFilePublished.Data(), "OPEN"); if (!fMeasuredFile) { printf( "AliMCSpectraWeights::Error: Could not load measured fractions in %s\n", fstFilePublished.Data()); return; } TString stHistName(""); for (int ipart = 0; ipart < fNPartTypes; ++ipart) { int ibin = ipart; if(fstPartTypes[ipart].Contains("Pion")) ibin = static_cast<int>(AliMCSpectraWeights::ParticleType::kPion); else if(fstPartTypes[ipart].Contains("Proton")) ibin = static_cast<int>(AliMCSpectraWeights::ParticleType::kProtons); else if(fstPartTypes[ipart].Contains("Kaon")) ibin = static_cast<int>(AliMCSpectraWeights::ParticleType::kKaon); else if(fstPartTypes[ipart].Contains("SigmaPlus")) ibin = static_cast<int>(AliMCSpectraWeights::ParticleType::kSigmaPlus); else if(fstPartTypes[ipart].Contains("SigmaMinus")) ibin = static_cast<int>(AliMCSpectraWeights::ParticleType::kSigmaMinus); else continue; for (int icent = 0; icent < fNCentralities; icent++) { TString stFunction("Bylinkin");//TODO define functions with SysFlag TString stSystematic(""); // switch (fFlag) { // case /* value */: // } stHistName = Form("%s%s%s%s%s", fstCollisionSystem.Data(), fstPartTypes[ipart].Data(), fstCentralities[icent].Data(), stFunction.Data(), stSystematic.Data()); // printf("AliMCSpectraWeights:: Loading histogram %s\n", stHistName.Data()); TH1D *hist = (TH1D *)fMeasuredFile->Get(stHistName); if (!hist) { printf("AliMCSpectraWeights::Error: could not find %s \n", stHistName.Data()); continue; } // else printf("AliMCSpectraWeights:: loading successful\n"); // hist-> pt:multcent:type Double_t binEntry[3] = {0.}; binEntry[2] = static_cast<Double_t>(ibin);// particle type if(fUseMultiplicity) binEntry[1] = AliMCSpectraWeights::GetMultFromCent(icent); else binEntry[1] = static_cast<Double_t>(icent); for (int ipt = 0; ipt < hist->GetNbinsX(); ++ipt) { binEntry[0] = hist->GetBinCenter(ipt); if(binEntry[0] < 0) continue; // printf("AliMCSpectraWeights::DEBUG: Writing for particle %lf in %lf cent the momentum %lf the content %lf\n", binEntry[2], binEntry[1], binEntry[0], hist->GetBinContent(ipt)); int ibinHist = fHistDataFractions->GetBin(binEntry); // printf("AliMCSpectraWeights::DEBUG: Writing in bin %d\n", ibinHist); fHistDataFractions->SetBinContent(ibinHist, hist->GetBinContent(ipt)); } delete hist; } } fMeasuredFile->Close(); delete fMeasuredFile; // printf("AliMCSpectraWeights: Load measured fractions finished\n"); } Bool_t AliMCSpectraWeights::LoadFromAliMCSpectraWeight( AliMCSpectraWeights *obj) { // printf("AliMCSpectraWeights::DEBUG: Loading MC histogram from input object\n"); if(!obj) return kFALSE; if(fHistMCGenPrimTrackParticle) delete fHistMCGenPrimTrackParticle; fHistMCGenPrimTrackParticle = (THnF*)((THnF*)obj->GetHistMCGenPrimTrackParticles())->Clone("fHistMCGenPrimTrackParticleLoaded"); if(!fHistMCGenPrimTrackParticle) //printf("AliMCSpectraWeights:: loading successful\n"); {printf("AliMCSpectraWeights::ERROR: problem with loading from object\n"); return kFALSE;} // fHistMCGenPrimTrackParticle->SetName("fHistMCGenPrimTrackParticleLoaded"); // if(!fHistMCGenPrimTrackParticle->GetEntries()>0) {printf("AliMCSpectraWeights::ERROR: loaded hist from object has zero entries\n"); return kFALSE;} // TH1D* pTProjection = (TH1D*)fHistMCGenPrimTrackParticle->Projection(0); // pTProjection->SetName("pTProjection"); // printf("AliMCSpectraWeights:: mean pT: %lf\n", fHistMCGenPrimTrackParticle->Projection(0)->GetMean()); // if(obj) delete obj; return kTRUE; } Bool_t AliMCSpectraWeights::CalcMCFractions(){ if (!fHistMCGenPrimTrackParticle) return kFALSE; for (int icent = 0; icent < fNCentralities; icent++) { float currentMult = AliMCSpectraWeights::GetMultFromCent(icent); float nextMult = 0; float previousMult = 0; float dMultHigh = 0; float dMultLow = 0; if(icent<fBinsMultCent->GetSize()-1) nextMult = AliMCSpectraWeights::GetMultFromCent(icent+1); if(icent>0) previousMult = AliMCSpectraWeights::GetMultFromCent(icent-1); if(icent==0) dMultHigh = fBinsMultCent->GetAt(fBinsMultCent->GetSize() - 1); else dMultHigh = currentMult + (previousMult-currentMult)/2.; if(icent==fBinsMultCent->GetSize()-1) dMultLow = 0.; else dMultLow = currentMult + (currentMult-nextMult)/2.; fHistMCGenPrimTrackParticle->GetAxis(1)->SetRangeUser(dMultLow, dMultHigh); TH1D *h1pTMCAll = (TH1D *)fHistMCGenPrimTrackParticle->Projection(0); if(!h1pTMCAll) {printf("AliMCSpectraWeights::ERROR could not create h1pTMCAll\n"); return kFALSE;} h1pTMCAll->SetName("h1pTMCAll"); for (int ipart = 0; ipart < fNPartTypes; ++ipart) { fHistMCGenPrimTrackParticle->GetAxis(2)->SetRange(ipart+1, ipart+1); TH1D *h1MCFraction = (TH1D *)fHistMCGenPrimTrackParticle->Projection(0); h1MCFraction->SetName("h1MCFraction_tmp"); h1MCFraction->Divide(h1pTMCAll); for (int ipt = 0; ipt < fHistMCFractions->GetAxis(0)->GetNbins(); ++ipt) { Double_t pt = fHistMCFractions->GetAxis(0)->GetBinCenter(ipt); // fHistMCFractions : pt-mult-ipart Double_t binEntry[3] = {pt, currentMult, static_cast<Double_t>(ipart)}; //Write to fHistMCFractions fHistMCFractions->SetBinContent(fHistMCFractions->GetBin(binEntry), h1MCFraction->GetBinContent(h1MCFraction->FindBin(pt))); } delete h1MCFraction; } fHistMCGenPrimTrackParticle->GetAxis(2)->SetRange(0, 0); delete h1pTMCAll; } return kTRUE; } Bool_t AliMCSpectraWeights::CorrectFractionsforRest() { if(!fHistMCGenPrimTrackParticle || !fHistDataFractions) return kFALSE; for (int icent = 0; icent < fNCentralities; icent++) { float currentMult = AliMCSpectraWeights::GetMultFromCent(icent); float nextMult = 0; float previousMult = 0; float dMultHigh = 0; float dMultLow = 0; if(icent<fBinsMultCent->GetSize()-1) nextMult = AliMCSpectraWeights::GetMultFromCent(icent+1); if(icent>0) previousMult = AliMCSpectraWeights::GetMultFromCent(icent-1); if(icent==0) dMultHigh = fBinsMultCent->GetAt(fBinsMultCent->GetSize() - 1); else dMultHigh = currentMult + (previousMult-currentMult)/2.; if(icent==fBinsMultCent->GetSize()-1) dMultLow = 0.; else dMultLow = currentMult + (currentMult-nextMult)/2.; fHistMCGenPrimTrackParticle->GetAxis(1)->SetRangeUser(dMultLow, dMultHigh); TH1D *h1pTMCAll = (TH1D *)fHistMCGenPrimTrackParticle->Projection(0); if(!h1pTMCAll) {printf("AliMCSpectraWeights::ERROR could not create h1pTMCAll\n"); return kFALSE;} h1pTMCAll->SetName("h1pTMCAll"); fHistMCGenPrimTrackParticle->GetAxis(2)->SetRange(1, AliMCSpectraWeights::ParticleType::kRest); TH1D* h1RestCorrFactor = (TH1D*)fHistMCGenPrimTrackParticle->Projection(0); h1RestCorrFactor->SetName("h1RestCorrFactor"); h1RestCorrFactor->Divide(h1pTMCAll); fHistMCGenPrimTrackParticle->GetAxis(2)->SetRange(0, 0); for (int ipart = 0; ipart < fNPartTypes; ++ipart) { if(ipart == AliMCSpectraWeights::ParticleType::kRest) continue; for (int ipt = 0; ipt < fHistDataFractions->GetAxis(0)->GetNbins(); ++ipt) { Double_t pt = fHistDataFractions->GetAxis(0)->GetBinCenter(ipt); // fHistMCFractions : pt-mult-ipart Double_t binEntry[3] = {pt, currentMult, static_cast<Double_t>(ipart)}; double value = fHistDataFractions->GetBinContent(fHistDataFractions->GetBin(binEntry)); fHistDataFractions->SetBinContent(fHistDataFractions->GetBin(binEntry), value*h1RestCorrFactor->GetBinContent(h1RestCorrFactor->FindBin(pt))); } } delete h1pTMCAll; delete h1RestCorrFactor; } return kTRUE; } Bool_t AliMCSpectraWeights::CalculateMCWeights(){ if (!AliMCSpectraWeights::CalcMCFractions()) return kFALSE; if (!AliMCSpectraWeights::CorrectFractionsforRest()) return kFALSE; // correction of rest particles not measured in data fractions (see // AnalysisNote) for (int icent = 0; icent < fNCentralities; icent++) { for (int ipart = 0; ipart < fNPartTypes; ipart++) { if(ipart == AliMCSpectraWeights::ParticleType::kRest) continue; for (int ipt = 0; ipt < fBinsPt->GetSize(); ipt++) { Double_t pt = fHistMCWeights->GetAxis(0)->GetBinCenter(ipt); Double_t binEntry[3] = {pt, AliMCSpectraWeights::GetMultFromCent(icent), static_cast<Double_t>(ipart)}; // Double_t binEntryData[3] = {pt, static_cast<Double_t>(icent), static_cast<Double_t>(ipart)}; Double_t dFractionMC = fHistMCFractions->GetBinContent(fHistMCFractions->GetBin(binEntry)); Double_t dFractionData = fHistDataFractions->GetBinContent(fHistDataFractions->GetBin(binEntry)); if(dFractionMC!=0) fHistMCWeights->SetBinContent(fHistMCWeights->GetBin(binEntry), dFractionData/dFractionMC); } } } return kTRUE; } void AliMCSpectraWeights::CountEventMult() { fMultOrCent=0; double eta = 0.8; if(fstCollisionSystem.Contains("pp")) eta = 0.5; AliStack* fMCStack = fMCEvent->Stack(); for (size_t ipart = 0; ipart < fMCStack->GetNtrack(); ipart++) { TParticle *mcGenParticle = fMCStack->Particle(ipart); if(!fMCStack->IsPhysicalPrimary(ipart)) continue;// secondary rejection if(TMath::Abs(mcGenParticle->GetPDG()->Charge()) < 0.01) continue; // neutral rejection double pEta = mcGenParticle->Eta(); if(TMath::Abs(pEta) > eta) continue; //acceptance cut if(mcGenParticle->Pt() < 0.05) continue; //TODO hard coded low pT cut ++fMultOrCent; } } Double_t AliMCSpectraWeights::GetMCSpectraWeight(TParticle *mcGenParticle, Float_t eventMultiplicityOrCentrality) { Double_t weight = 1; if (!mcGenParticle->GetPDG()) {return 1;} if (TMath::Abs(mcGenParticle->GetPDG()->Charge()) < 0.01) {return 1;} // charge rejection // if (!mcGenParticle->IsPrimary()) {printf("particle not primary\n"); return 1;} Int_t particleType = AliMCSpectraWeights::IdentifyMCParticle(mcGenParticle); if (particleType == AliMCSpectraWeights::ParticleType::kRest) {return 1;} if (fbTaskStatus == AliMCSpectraWeights::TaskState::kMCWeightCalculated) { // rest particles can not be tuned Double_t icent = AliMCSpectraWeights::GetCentFromMult(eventMultiplicityOrCentrality); Double_t pt = mcGenParticle->Pt(); if(pt<0.15) return 1; if(pt>=20) pt=19.9; Double_t binEntry[3] = {pt, AliMCSpectraWeights::GetMultFromCent(icent), static_cast<Double_t>(particleType)}; weight = fHistMCWeights->GetBinContent(fHistMCWeights->GetBin(binEntry)); if(weight==0) weight=1;// printf("AliMCSpectraWeights:: got weight 0; return 1;\n");} // printf("AliMCSpectraWeights:: got weight %lf for pid %d at pt %lf\n", weight, mcGenParticle->GetPdgCode(), binEntry[0]); } //else printf("Status not right\n" ); return weight; } Double_t AliMCSpectraWeights::GetMCSpectraWeight(TParticle *mcGenParticle, AliMCEvent* mcEvent) { if(mcEvent!=fMCEvent) { fMCEvent=mcEvent; AliMCSpectraWeights::CountEventMult(); } return AliMCSpectraWeights::GetMCSpectraWeight(mcGenParticle, fMultOrCent); } void AliMCSpectraWeights::FillMCSpectra(AliMCEvent* mcEvent) { if (fbTaskStatus >= AliMCSpectraWeights::TaskState::kMCSpectraObtained) return; if(mcEvent!=fMCEvent) { fMCEvent=mcEvent; AliMCSpectraWeights::CountEventMult(); } AliStack* MCStack = fMCEvent->Stack(); if (!MCStack) {printf("AliMCSpectraWeights::ERROR: fMCStack not available\n"); return;} for (Int_t iParticle = 0; iParticle < MCStack->GetNtrack(); iParticle++){ TParticle *mcGenParticle = MCStack->Particle(iParticle); if(!mcGenParticle) {printf("AliMCSpectraWeights::ERROR: mcGenParticle not available\n"); continue;} if (!mcGenParticle->GetPDG()) continue; if(!MCStack->IsPhysicalPrimary(iParticle)) continue; float partEta = mcGenParticle->Eta(); if (TMath::Abs(mcGenParticle->GetPDG()->Charge()) < 0.01) continue; if(partEta > 0.8 || partEta < -0.8) continue; // apply same acceptance as in published spectra Int_t particleType = AliMCSpectraWeights::IdentifyMCParticle(mcGenParticle); if(particleType<0) continue; Double_t binEntry[3] = {static_cast<Double_t>(mcGenParticle->Pt()), static_cast<Double_t>(fMultOrCent), static_cast<Double_t>(particleType)}; fHistMCGenPrimTrackParticle->Fill(binEntry); } } /// Function to return Particle ID for Histograms Int_t AliMCSpectraWeights::IdentifyMCParticle(TParticle *mcParticle) { // if(!mcParticle->GetPDG()) return -1; Int_t ipdg = TMath::Abs( mcParticle->GetPdgCode()); // Abs() because antiparticles are negaitve... if (ipdg == 211) return static_cast<Int_t>(AliMCSpectraWeights::ParticleType::kPion); if (ipdg == 321) return static_cast<Int_t>(AliMCSpectraWeights::ParticleType::kKaon); if (ipdg == 2212) return static_cast<Int_t>(AliMCSpectraWeights::ParticleType::kProtons); if (ipdg == 3222) return static_cast<Int_t>(AliMCSpectraWeights::ParticleType::kSigmaPlus); if (ipdg == 3112) return static_cast<Int_t>(AliMCSpectraWeights::ParticleType::kSigmaMinus); // if(ipdg==3334) return AliMCSpectraWeights::ParticleType::kOmegaMinus; // if(ipdg==3312) return AliMCSpectraWeights::ParticleType::kXiMinus; // if(ipdg==11) return AliMCSpectraWeights::ParticleType::kElectron; // if(ipdg==13) return AliMCSpectraWeights::ParticleType::kMuon; //printf("AliMCSpectraWeights:: pdf code of rest particle %d\n", ipdg); return static_cast<Int_t>(AliMCSpectraWeights::ParticleType::kRest); } Double_t AliMCSpectraWeights::GetMultFromCent(int CentBin){ if(fstCollisionSystem.Contains("pp")) { switch (CentBin) { case 0: return 21.3; case 1: return 16.5; case 2: return 13.5; case 3: return 11.5; case 4: return 10.1; case 5: return 8.45; case 6: return 6.72; case 7: return 5.4; case 8: return 3.9; case 9: return 2.26; default: return 0; } } else if(fstCollisionSystem.Contains("ppb"))//TODO include other systems { } else if(fstCollisionSystem.Contains("pbpb")) { } else if(fstCollisionSystem.Contains("xexe")) { } return -1; } Double_t AliMCSpectraWeights::GetCentFromMult(double dMult) { if(fstCollisionSystem.Contains("pp")) { if(dMult > 18) return 0; if(dMult > 14.5) return 1; if(dMult > 12) return 2; if(dMult > 10.9) return 3; if(dMult > 9) return 4; if(dMult > 7) return 5; if(dMult > 5.7) return 6; if(dMult > 4.3) return 7; if(dMult > 3) return 8; if(dMult > 0) return 9; } else if(fstCollisionSystem.Contains("ppb"))//TODO include other systems { } else if(fstCollisionSystem.Contains("pbpb")) { } else if(fstCollisionSystem.Contains("xexe")) { } return -1; }
42.437795
186
0.698197
[ "object" ]
feffb03947d24113ab7283e13ece44757876bf9b
31,474
cc
C++
storage/integration_test/src/integration_test.cc
ehsannas/firebase-cpp-sdk
d002a9db141d9bd590d9c96e8fbe999cdc7ec1f2
[ "Apache-2.0" ]
null
null
null
storage/integration_test/src/integration_test.cc
ehsannas/firebase-cpp-sdk
d002a9db141d9bd590d9c96e8fbe999cdc7ec1f2
[ "Apache-2.0" ]
null
null
null
storage/integration_test/src/integration_test.cc
ehsannas/firebase-cpp-sdk
d002a9db141d9bd590d9c96e8fbe999cdc7ec1f2
[ "Apache-2.0" ]
null
null
null
// Copyright 2019 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <inttypes.h> #include <algorithm> #include <cstdio> #include <cstdlib> #include <cstring> #include <ctime> #include "app_framework.h" // NOLINT #include "firebase/app.h" #include "firebase/auth.h" #include "firebase/internal/platform.h" #include "firebase/storage.h" #include "firebase/util.h" #include "firebase_test_framework.h" // NOLINT // The TO_STRING macro is useful for command line defined strings as the quotes // get stripped. #define TO_STRING_EXPAND(X) #X #define TO_STRING(X) TO_STRING_EXPAND(X) // Path to the Firebase config file to load. #ifdef FIREBASE_CONFIG #define FIREBASE_CONFIG_STRING TO_STRING(FIREBASE_CONFIG) #else #define FIREBASE_CONFIG_STRING "" #endif // FIREBASE_CONFIG namespace firebase_testapp_automated { using app_framework::LogDebug; // You can customize the Storage URL here. const char* kStorageUrl = nullptr; #if FIREBASE_PLATFORM_DESKTOP // Use a larger file on desktop... const int kLargeFileMegabytes = 25; #else // ...and a smaller file on mobile. const int kLargeFileMegabytes = 10; #endif const char kRootNodeName[] = "integration_test_data"; using app_framework::GetCurrentTimeInMicroseconds; using app_framework::PathForResource; using app_framework::ProcessEvents; using firebase_test_framework::FirebaseTest; using testing::ElementsAreArray; class FirebaseStorageTest : public FirebaseTest { public: FirebaseStorageTest(); ~FirebaseStorageTest() override; // Called once before all tests. static void SetUpTestSuite(); // Called once after all tests. static void TearDownTestSuite(); // Called at the start of each test. void SetUp() override; // Called after each test. void TearDown() override; protected: // Initialize Firebase App and Firebase Auth. static void InitializeAppAndAuth(); // Shut down Firebase App and Firebase Auth. static void TerminateAppAndAuth(); // Sign in an anonymous user. static void SignIn(); // Sign out the current user, if applicable. // If this is an anonymous user, deletes the user instead, // to avoid polluting the user list. static void SignOut(); // Initialize Firebase Storage. void InitializeStorage(); // Shut down Firebase Storage. void TerminateStorage(); // Create a unique working folder and return a reference to it. firebase::storage::StorageReference CreateFolder(); static firebase::App* shared_app_; static firebase::auth::Auth* shared_auth_; bool initialized_; firebase::storage::Storage* storage_; // File references that we need to delete on test exit. std::vector<firebase::storage::StorageReference> cleanup_files_; std::string saved_url_; }; // Initialization flow looks like this: // - Once, before any tests run: // - SetUpTestSuite: Initialize App and Auth. Sign in. // - For each test: // - SetUp: Initialize Storage. // - Run the test. // - TearDown: Shut down Storage. // - Once, after all tests are finished: // - TearDownTestSuite: Sign out. Shut down Auth and App. firebase::App* FirebaseStorageTest::shared_app_; firebase::auth::Auth* FirebaseStorageTest::shared_auth_; FirebaseStorageTest::FirebaseStorageTest() : initialized_(false), storage_(nullptr) { FindFirebaseConfig(FIREBASE_CONFIG_STRING); } FirebaseStorageTest::~FirebaseStorageTest() { // Must be cleaned up on exit. assert(storage_ == nullptr); } void FirebaseStorageTest::SetUpTestSuite() { InitializeAppAndAuth(); } void FirebaseStorageTest::InitializeAppAndAuth() { LogDebug("Initialize Firebase App."); FindFirebaseConfig(FIREBASE_CONFIG_STRING); #if defined(__ANDROID__) shared_app_ = ::firebase::App::Create(app_framework::GetJniEnv(), app_framework::GetActivity()); #else shared_app_ = ::firebase::App::Create(); #endif // defined(__ANDROID__) ASSERT_NE(shared_app_, nullptr); LogDebug("Initializing Auth."); // Initialize Firebase Auth. ::firebase::ModuleInitializer initializer; initializer.Initialize(shared_app_, &shared_auth_, [](::firebase::App* app, void* target) { LogDebug("Attempting to initialize Firebase Auth."); ::firebase::InitResult result; *reinterpret_cast<firebase::auth::Auth**>(target) = ::firebase::auth::Auth::GetAuth(app, &result); return result; }); WaitForCompletion(initializer.InitializeLastResult(), "InitializeAuth"); ASSERT_EQ(initializer.InitializeLastResult().error(), 0) << initializer.InitializeLastResult().error_message(); LogDebug("Successfully initialized Auth."); ASSERT_NE(shared_auth_, nullptr); // Sign in anonymously. SignIn(); } void FirebaseStorageTest::TearDownTestSuite() { TerminateAppAndAuth(); } void FirebaseStorageTest::TerminateAppAndAuth() { if (shared_auth_) { LogDebug("Signing out."); SignOut(); LogDebug("Shutdown Auth."); delete shared_auth_; shared_auth_ = nullptr; } if (shared_app_) { LogDebug("Shutdown App."); delete shared_app_; shared_app_ = nullptr; } } void FirebaseStorageTest::SetUp() { FirebaseTest::SetUp(); InitializeStorage(); } void FirebaseStorageTest::TearDown() { if (initialized_) { if (!cleanup_files_.empty() && storage_ && shared_app_) { LogDebug("Cleaning up files."); std::vector<firebase::Future<void>> cleanups; cleanups.reserve(cleanup_files_.size()); for (int i = 0; i < cleanup_files_.size(); ++i) { cleanups.push_back(cleanup_files_[i].Delete()); } for (int i = 0; i < cleanups.size(); ++i) { WaitForCompletion(cleanups[i], "FirebaseStorageTest::TearDown"); } cleanup_files_.clear(); } } TerminateStorage(); FirebaseTest::TearDown(); } void FirebaseStorageTest::InitializeStorage() { LogDebug("Initializing Firebase Storage."); ::firebase::ModuleInitializer initializer; initializer.Initialize( shared_app_, &storage_, [](::firebase::App* app, void* target) { LogDebug("Attempting to initialize Firebase Storage."); ::firebase::InitResult result; *reinterpret_cast<firebase::storage::Storage**>(target) = firebase::storage::Storage::GetInstance(app, kStorageUrl, &result); return result; }); WaitForCompletion(initializer.InitializeLastResult(), "InitializeStorage"); ASSERT_EQ(initializer.InitializeLastResult().error(), 0) << initializer.InitializeLastResult().error_message(); LogDebug("Successfully initialized Firebase Storage."); initialized_ = true; } void FirebaseStorageTest::TerminateStorage() { if (!initialized_) return; if (storage_) { LogDebug("Shutdown the Storage library."); delete storage_; storage_ = nullptr; } initialized_ = false; ProcessEvents(100); } void FirebaseStorageTest::SignIn() { if (shared_auth_->current_user() != nullptr) { // Already signed in. return; } LogDebug("Signing in."); firebase::Future<firebase::auth::User*> sign_in_future = shared_auth_->SignInAnonymously(); WaitForCompletion(sign_in_future, "SignInAnonymously"); if (sign_in_future.error() != 0) { FAIL() << "Ensure your application has the Anonymous sign-in provider " "enabled in Firebase Console."; } ProcessEvents(100); } void FirebaseStorageTest::SignOut() { if (shared_auth_ == nullptr) { // Auth is not set up. return; } if (shared_auth_->current_user() == nullptr) { // Already signed out. return; } if (shared_auth_->current_user()->is_anonymous()) { // If signed in anonymously, delete the anonymous user. WaitForCompletion(shared_auth_->current_user()->Delete(), "DeleteAnonymousUser"); } else { // If not signed in anonymously (e.g. if the tests were modified to sign in // as an actual user), just sign out normally. shared_auth_->SignOut(); // Wait for the sign-out to finish. while (shared_auth_->current_user() != nullptr) { if (ProcessEvents(100)) break; } } EXPECT_EQ(shared_auth_->current_user(), nullptr); } firebase::storage::StorageReference FirebaseStorageTest::CreateFolder() { // Generate a folder for the test data based on the time in milliseconds. int64_t time_in_microseconds = GetCurrentTimeInMicroseconds(); char buffer[21] = {0}; snprintf(buffer, sizeof(buffer), "%lld", static_cast<long long>(time_in_microseconds)); // NOLINT saved_url_ = buffer; return storage_->GetReference(kRootNodeName).Child(saved_url_); } // Test cases below. TEST_F(FirebaseStorageTest, TestInitializeAndTerminate) { // Already tested via SetUp() and TearDown(). } TEST_F(FirebaseStorageTest, TestSignIn) { EXPECT_NE(shared_auth_->current_user(), nullptr); } TEST_F(FirebaseStorageTest, TestCreateWorkingFolder) { SignIn(); // Create a unique child in the storage that we can run our tests in. firebase::storage::StorageReference ref = CreateFolder(); EXPECT_NE(saved_url_, ""); LogDebug("Storage URL: gs://%s%s", ref.bucket().c_str(), ref.full_path().c_str()); // Create the same reference in a few different manners and ensure they're // equivalent. // NOLINTNEXTLINE intentional redundant string conversion { firebase::storage::StorageReference ref_from_str = storage_->GetReference(std::string(kRootNodeName)).Child(saved_url_); EXPECT_EQ(ref.bucket(), ref_from_str.bucket()); EXPECT_EQ(ref.full_path(), ref_from_str.full_path()); } std::string url = "gs://" + ref.bucket() + "/" + kRootNodeName; LogDebug("Calling GetReferenceFromUrl(%s)", url.c_str()); firebase::storage::StorageReference ref_from_url = storage_->GetReferenceFromUrl(url.c_str()).Child(saved_url_); EXPECT_TRUE(ref_from_url.is_valid()); EXPECT_EQ(ref.bucket(), ref_from_url.bucket()); EXPECT_EQ(ref.full_path(), ref_from_url.full_path()); firebase::storage::StorageReference ref_from_url_str = storage_->GetReferenceFromUrl(url).Child(saved_url_); EXPECT_TRUE(ref_from_url_str.is_valid()); EXPECT_EQ(ref.bucket(), ref_from_url_str.bucket()); EXPECT_EQ(ref.full_path(), ref_from_url_str.full_path()); } TEST_F(FirebaseStorageTest, TestStorageUrl) { SignIn(); // Confirm that creating a storage instance with a URL returns a url(), and // creating a storage instance with a null URL returns a blank url(). std::string default_url = std::string("gs://") + storage_->GetReference().bucket(); // Check whether the Storage instance we already have is handled correctly. EXPECT_EQ(storage_->url(), kStorageUrl ? kStorageUrl : ""); delete storage_; storage_ = nullptr; { firebase::storage::Storage* storage_explicit = firebase::storage::Storage::GetInstance(shared_app_, default_url.c_str(), nullptr); ASSERT_NE(storage_explicit, nullptr); EXPECT_EQ(storage_explicit->url(), default_url); delete storage_explicit; } { firebase::storage::Storage* storage_implicit = firebase::storage::Storage::GetInstance(shared_app_, nullptr, nullptr); ASSERT_NE(storage_implicit, nullptr); EXPECT_EQ(storage_implicit->url(), ""); delete storage_implicit; } } // NOLINTNEXTLINE const std::string kSimpleTestFile = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do " "eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim " "ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut " "aliquip ex ea commodo consequat. Duis aute irure dolor in " "reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla " "pariatur. Excepteur sint occaecat cupidatat non proident, sunt in " "culpa qui officia deserunt mollit anim id est laborum."; TEST_F(FirebaseStorageTest, TestWriteAndReadByteBuffer) { SignIn(); firebase::storage::StorageReference ref = CreateFolder().Child("TestFile.txt"); LogDebug("Storage URL: gs://%s%s", ref.bucket().c_str(), ref.full_path().c_str()); cleanup_files_.push_back(ref); // Write to a simple file. { LogDebug("Upload sample file from memory."); firebase::Future<firebase::storage::Metadata> future = ref.PutBytes(&kSimpleTestFile[0], kSimpleTestFile.size()); WaitForCompletion(future, "PutBytes"); auto metadata = future.result(); EXPECT_EQ(metadata->size_bytes(), kSimpleTestFile.size()); } // Now read back the file. { LogDebug("Download sample file to memory."); const size_t kBufferSize = 1024; char buffer[kBufferSize]; memset(buffer, 0, sizeof(buffer)); firebase::Future<size_t> future = ref.GetBytes(buffer, kBufferSize); WaitForCompletion(future, "GetBytes"); ASSERT_NE(future.result(), nullptr); size_t file_size = *future.result(); EXPECT_EQ(file_size, kSimpleTestFile.size()); EXPECT_THAT(kSimpleTestFile, ElementsAreArray(buffer, file_size)) << "Download failed, file contents did not match."; } } TEST_F(FirebaseStorageTest, TestWriteAndReadFileWithCustomMetadata) { SignIn(); firebase::storage::StorageReference ref = CreateFolder().Child("TestFile-CustomMetadata.txt"); LogDebug("Storage URL: gs://%s%s", ref.bucket().c_str(), ref.full_path().c_str()); cleanup_files_.push_back(ref); std::string content_type = "text/plain"; std::string custom_metadata_key = "specialkey"; std::string custom_metadata_value = "secret value"; // Write to a simple file. { LogDebug("Write a sample file with custom metadata from byte buffer."); firebase::storage::Metadata metadata; metadata.set_content_type(content_type.c_str()); (*metadata.custom_metadata())[custom_metadata_key] = custom_metadata_value; firebase::Future<firebase::storage::Metadata> future = ref.PutBytes(&kSimpleTestFile[0], kSimpleTestFile.size(), metadata); WaitForCompletion(future, "PutBytes"); const firebase::storage::Metadata* metadata_written = future.result(); ASSERT_NE(metadata_written, nullptr); EXPECT_EQ(metadata_written->size_bytes(), kSimpleTestFile.size()); EXPECT_EQ(metadata_written->content_type(), content_type); auto& custom_metadata = *metadata_written->custom_metadata(); EXPECT_EQ(custom_metadata[custom_metadata_key], custom_metadata_value); } // Now read back the file. { LogDebug("Download sample file with custom metadata to memory."); const size_t kBufferSize = 1024; char buffer[kBufferSize]; memset(buffer, 0, sizeof(buffer)); firebase::Future<size_t> future = ref.GetBytes(buffer, kBufferSize); WaitForCompletion(future, "GetBytes"); ASSERT_NE(future.result(), nullptr); size_t file_size = *future.result(); EXPECT_EQ(file_size, kSimpleTestFile.size()); EXPECT_THAT(kSimpleTestFile, ElementsAreArray(buffer, file_size)) << "Download failed, file contents did not match."; } // And read the custom metadata. { LogDebug("Read custom metadata."); firebase::Future<firebase::storage::Metadata> future = ref.GetMetadata(); WaitForCompletion(future, "GetFileMetadata"); const firebase::storage::Metadata* metadata = future.result(); ASSERT_NE(metadata, nullptr); // Get the current time to compare to the Timestamp. int64_t current_time_seconds = static_cast<int64_t>(time(nullptr)); int64_t updated_time_milliseconds = metadata->updated_time(); int64_t updated_time_seconds = updated_time_milliseconds / 1000; int64_t time_difference_seconds = updated_time_seconds - current_time_seconds; // As long as our timestamp is within a day, it's correct enough for // our purposes. const int64_t kAllowedTimeDifferenceSeconds = 60L * 60L * 24L; EXPECT_TRUE(time_difference_seconds < kAllowedTimeDifferenceSeconds && time_difference_seconds > -kAllowedTimeDifferenceSeconds) << "Bad timestamp in metadata."; EXPECT_EQ(metadata->size_bytes(), kSimpleTestFile.size()); EXPECT_EQ(metadata->content_type(), content_type); ASSERT_NE(metadata->custom_metadata(), nullptr); auto& custom_metadata = *metadata->custom_metadata(); EXPECT_EQ(custom_metadata[custom_metadata_key], custom_metadata_value); } } const char kPutFileTestFile[] = "PutFileTest.txt"; const char kGetFileTestFile[] = "GetFileTest.txt"; const char kFileUriScheme[] = "file://"; TEST_F(FirebaseStorageTest, TestPutFileAndGetFile) { SignIn(); firebase::storage::StorageReference ref = CreateFolder().Child("TestFile-FileIO.txt"); cleanup_files_.push_back(ref); // Upload a file. { // Write file that we're going to upload. std::string path = PathForResource() + kPutFileTestFile; // Cloud Storage expects a URI, so add file:// in front of local paths. std::string file_path = kFileUriScheme + path; LogDebug("Creating local file: %s", path.c_str()); FILE* file = fopen(path.c_str(), "wb"); std::fwrite(kSimpleTestFile.c_str(), 1, kSimpleTestFile.size(), file); fclose(file); firebase::storage::Metadata new_metadata; std::string content_type = "text/plain"; new_metadata.set_content_type(content_type); LogDebug("Uploading sample file from disk."); firebase::Future<firebase::storage::Metadata> future = ref.PutFile(file_path.c_str(), new_metadata); WaitForCompletion(future, "PutFile"); ASSERT_NE(future.result(), nullptr); const firebase::storage::Metadata* metadata = future.result(); EXPECT_EQ(metadata->size_bytes(), kSimpleTestFile.size()); EXPECT_EQ(metadata->content_type(), content_type); } // Use GetBytes to ensure the file uploaded correctly. { LogDebug("Downloading file to disk."); const size_t kBufferSize = 1024; char buffer[kBufferSize]; memset(buffer, 0, sizeof(buffer)); firebase::Future<size_t> future = ref.GetBytes(buffer, kBufferSize); WaitForCompletion(future, "GetBytes"); ASSERT_NE(future.result(), nullptr); size_t file_size = *future.result(); EXPECT_EQ(file_size, kSimpleTestFile.size()); EXPECT_THAT(kSimpleTestFile, ElementsAreArray(buffer, file_size)) << "Read file to byte buffer failed, file contents did not match."; } // Test GetFile to ensure we can download to a file. { std::string path = PathForResource() + kGetFileTestFile; // Cloud Storage expects a URI, so add file:// in front of local paths. std::string file_path = kFileUriScheme + path; LogDebug("Saving to local file: %s", path.c_str()); firebase::Future<size_t> future = ref.GetFile(file_path.c_str()); WaitForCompletion(future, "GetFile"); ASSERT_NE(future.result(), nullptr); EXPECT_EQ(*future.result(), kSimpleTestFile.size()); std::vector<char> buffer(kSimpleTestFile.size()); FILE* file = fopen(path.c_str(), "rb"); ASSERT_NE(file, nullptr); std::fread(&buffer[0], 1, kSimpleTestFile.size(), file); fclose(file); EXPECT_THAT(kSimpleTestFile, ElementsAreArray(&buffer[0], buffer.size())) << "Download to disk failed, file contents did not match."; } } TEST_F(FirebaseStorageTest, TestDownloadUrl) { SignIn(); const char kTestFileName[] = "TestFile-DownloadUrl.txt"; firebase::storage::StorageReference ref = CreateFolder().Child(kTestFileName); cleanup_files_.push_back(ref); LogDebug("Uploading file."); WaitForCompletion(ref.PutBytes(&kSimpleTestFile[0], kSimpleTestFile.size()), "PutBytes"); LogDebug("Getting download URL."); firebase::Future<std::string> future = ref.GetDownloadUrl(); WaitForCompletion(future, "GetDownloadUrl"); ASSERT_NE(future.result(), nullptr); LogDebug("Got download URL: %s", future.result()->c_str()); // Check for a somewhat well-formed URL, i.e. it starts with "https://" and // has "TestFile-DownloadUrl" in the name. EXPECT_TRUE(future.result()->find("https://") == 0) << "Download Url doesn't start with https://"; EXPECT_TRUE(future.result()->find(kTestFileName) != std::string::npos) << "Download Url doesn't contain the filename " << kTestFileName; } TEST_F(FirebaseStorageTest, TestDeleteFile) { SignIn(); firebase::storage::StorageReference ref = CreateFolder().Child("TestFile-Delete.txt"); // Don't add to cleanup_files_ because we are going to delete it anyway. LogDebug("Uploading file."); WaitForCompletion(ref.PutBytes(&kSimpleTestFile[0], kSimpleTestFile.size()), "PutBytes"); LogDebug("Deleting file."); WaitForCompletion(ref.Delete(), "Delete"); // Need a placeholder buffer. const size_t kBufferSize = 1024; char buffer[kBufferSize]; // Ensure the file was deleted. LogDebug("Ensuring file was deleted."); firebase::Future<size_t> future = ref.GetBytes(buffer, kBufferSize); WaitForCompletion(future, "GetBytes", firebase::storage::kErrorObjectNotFound); } class StorageListener : public firebase::storage::Listener { public: StorageListener() : on_paused_was_called_(false), on_progress_was_called_(false) {} // Tracks whether OnPaused was ever called and resumes the transfer. void OnPaused(firebase::storage::Controller* controller) override { #if FIREBASE_PLATFORM_DESKTOP // Let things be paused for a moment on desktop, since it typically has a // very fast connection. ProcessEvents(1000); #endif // FIREBASE_PLATFORM_DESKTOP on_paused_was_called_ = true; controller->Resume(); } void OnProgress(firebase::storage::Controller* controller) override { LogDebug("Transferred %lld of %lld", controller->bytes_transferred(), controller->total_byte_count()); on_progress_was_called_ = true; } bool on_paused_was_called() const { return on_paused_was_called_; } bool on_progress_was_called() const { return on_progress_was_called_; } public: bool on_paused_was_called_; bool on_progress_was_called_; }; // Contents of a large file, "X" will be replaced with a different character // each line. const char kLargeFileString[] = "X: This is a large file with multiple lines and even some \xB1nary " "char\xAC\ters.\n"; std::string CreateDataForLargeFile(size_t size_bytes) { std::string large_test_file; const std::string kLine = kLargeFileString; large_test_file.reserve(size_bytes + kLine.size()); char replacement[2] = "a"; while (large_test_file.size() < size_bytes) { std::string line = kLine; line.replace(kLine.find("X"), 1, replacement); large_test_file += line; replacement[0] = (replacement[0] - 'a' + 1) % 26 + 'a'; } large_test_file.resize(size_bytes); return large_test_file; } TEST_F(FirebaseStorageTest, TestLargeFilePauseResumeAndDownloadCancel) { SignIn(); firebase::storage::StorageReference ref = CreateFolder().Child("TestFile-LargeFile.txt"); cleanup_files_.push_back(ref); const size_t kLargeFileSize = kLargeFileMegabytes * 1024 * 1024; const std::string kLargeTestFile = CreateDataForLargeFile(kLargeFileSize); { LogDebug("Uploading large file with pause/resume."); StorageListener listener; firebase::storage::Controller controller; firebase::Future<firebase::storage::Metadata> future = ref.PutBytes( kLargeTestFile.c_str(), kLargeFileSize, &listener, &controller); // Ensure the Controller is valid now that we have associated it with an // operation. ASSERT_TRUE(controller.is_valid()); while (controller.bytes_transferred() == 0) { #if FIREBASE_PLATFORM_DESKTOP ProcessEvents(1); #else // FIREBASE_PLATFORM_MOBILE ProcessEvents(500); #endif } // After waiting a moment for the operation to start (above), pause the // operation and verify it was successfully paused when the future // completes. LogDebug("Pausing upload."); EXPECT_TRUE(controller.Pause()) << "Upload pause"; // The StorageListener's OnPaused will call Resume(). LogDebug("Waiting for future."); WaitForCompletion(future, "WriteLargeFile"); LogDebug("Upload complete."); // Ensure the various callbacks were called. EXPECT_TRUE(listener.on_paused_was_called()); EXPECT_TRUE(listener.on_progress_was_called()); ASSERT_EQ(future.error(), firebase::storage::kErrorNone); auto metadata = future.result(); ASSERT_EQ(metadata->size_bytes(), kLargeFileSize) << "Metadata reports incorrect size, file failed to upload."; } // Download the file and confirm it's correct. std::vector<char> buffer(kLargeFileSize); { memset(&buffer[0], 0, kLargeFileSize); LogDebug("Downloading large file for comparison."); StorageListener listener; firebase::Future<size_t> future = ref.GetBytes(&buffer[0], kLargeFileSize, &listener); WaitForCompletion(future, "GetBytes"); ASSERT_NE(future.result(), nullptr); size_t file_size = *future.result(); EXPECT_EQ(file_size, kLargeFileSize) << "Read size did not match"; EXPECT_TRUE(memcmp(kLargeTestFile.c_str(), &buffer[0], kLargeFileSize) == 0) << "Read large file failed, contents did not match."; } #if FIREBASE_PLATFORM_DESKTOP { // Test pausing/resuming while downloading (desktop only). memset(&buffer[0], 0, kLargeFileSize); LogDebug("Downloading large file with pausing/resuming."); StorageListener listener; firebase::storage::Controller controller; firebase::Future<size_t> future = ref.GetBytes(&buffer[0], kLargeFileSize, &listener, &controller); ASSERT_TRUE(controller.is_valid()); while (controller.bytes_transferred() == 0) { ProcessEvents(1); } LogDebug("Pausing download."); EXPECT_TRUE(controller.Pause()) << "Download pause"; WaitForCompletion(future, "GetBytes"); LogDebug("Download complete."); // Ensure the progress and pause callbacks were called. EXPECT_TRUE(listener.on_progress_was_called()); EXPECT_TRUE(listener.on_paused_was_called()); ASSERT_NE(future.result(), nullptr); size_t file_size = *future.result(); EXPECT_EQ(file_size, kLargeFileSize) << "Read size with pause/resume did not match"; EXPECT_TRUE(memcmp(kLargeTestFile.c_str(), &buffer[0], kLargeFileSize) == 0) << "Read large file failed, contents did not match."; } #else { // Test downloading large file (mobile only), without pausing, as mobile // does not support pause during file download, only upload. memset(&buffer[0], 0, kLargeFileSize); LogDebug("Downloading large file."); StorageListener listener; firebase::storage::Controller controller; firebase::Future<size_t> future = ref.GetBytes(&buffer[0], kLargeFileSize, &listener, &controller); ASSERT_TRUE(controller.is_valid()); WaitForCompletion(future, "GetBytes"); LogDebug("Download complete."); // Ensure the progress callback was called. EXPECT_TRUE(listener.on_progress_was_called()); EXPECT_FALSE(listener.on_paused_was_called()); ASSERT_NE(future.result(), nullptr); size_t file_size = *future.result(); EXPECT_EQ(file_size, kLargeFileSize) << "Read size did not match"; EXPECT_TRUE(memcmp(kLargeTestFile.c_str(), &buffer[0], kLargeFileSize) == 0) << "Read large file failed, contents did not match."; } #endif // FIREBASE_PLATFORM_DESKTOP // Try canceling while downloading. { LogDebug("Downloading large file with cancellation."); StorageListener listener; firebase::storage::Controller controller; firebase::Future<size_t> future = ref.GetBytes(&buffer[0], kLargeFileSize, &listener, &controller); ASSERT_TRUE(controller.is_valid()); while (controller.bytes_transferred() == 0) { ProcessEvents(1); } LogDebug("Cancelling download."); EXPECT_TRUE(controller.Cancel()); WaitForCompletion(future, "GetBytes", firebase::storage::kErrorCancelled); } } TEST_F(FirebaseStorageTest, TestLargeFileCancelUpload) { SignIn(); firebase::storage::StorageReference ref = CreateFolder().Child("TestFile-LargeFileCancel.txt"); const size_t kLargeFileSize = kLargeFileMegabytes * 1024 * 1024; const std::string kLargeTestFile = CreateDataForLargeFile(kLargeFileSize); { LogDebug("Write a large file and cancel mid-way."); StorageListener listener; firebase::storage::Controller controller; firebase::Future<firebase::storage::Metadata> future = ref.PutBytes( kLargeTestFile.c_str(), kLargeFileSize, &listener, &controller); // Ensure the Controller is valid now that we have associated it with an // operation. ASSERT_TRUE(controller.is_valid()); while (controller.bytes_transferred() == 0) { ProcessEvents(1); } LogDebug("Cancelling upload."); // Cancel the operation and verify it was successfully canceled. EXPECT_TRUE(controller.Cancel()); WaitForCompletion(future, "PutBytes", firebase::storage::kErrorCancelled); } } TEST_F(FirebaseStorageTest, TestInvalidatingReferencesWhenDeletingStorage) { SignIn(); // Create a file so we can get its metadata and check that it's properly // invalidated. firebase::storage::StorageReference ref = CreateFolder().Child("TestFile-InvalidateReferencesDeletingStorage.txt"); // Don't clean up, will be manually deleted. WaitForCompletion(ref.PutBytes(&kSimpleTestFile[0], kSimpleTestFile.size()), "PutBytes"); ASSERT_NE(ref.PutBytesLastResult().result(), nullptr); firebase::storage::Metadata metadata = *ref.PutBytesLastResult().result(); WaitForCompletion(ref.Delete(), "Delete"); ASSERT_TRUE(ref.is_valid()); ASSERT_TRUE(metadata.is_valid()); delete storage_; storage_ = nullptr; EXPECT_FALSE(ref.is_valid()); EXPECT_FALSE(metadata.is_valid()); } TEST_F(FirebaseStorageTest, TestInvalidatingReferencesWhenDeletingApp) { SignIn(); // Create a file so we can get its metadata and check that it's properly // invalidated. firebase::storage::StorageReference ref = CreateFolder().Child("TestFile-InvalidateReferencesDeletingApp.txt"); // Don't clean up, will be manually deleted. WaitForCompletion(ref.PutBytes(&kSimpleTestFile[0], kSimpleTestFile.size()), "PutBytes"); ASSERT_NE(ref.PutBytesLastResult().result(), nullptr); firebase::storage::Metadata metadata = *ref.PutBytesLastResult().result(); WaitForCompletion(ref.Delete(), "Delete"); ASSERT_TRUE(ref.is_valid()); ASSERT_TRUE(metadata.is_valid()); delete shared_app_; shared_app_ = nullptr; EXPECT_FALSE(ref.is_valid()); EXPECT_FALSE(metadata.is_valid()); // Fully shut down App and Auth so they can be reinitialized. TerminateAppAndAuth(); // Reinitialize App and Auth. InitializeAppAndAuth(); } } // namespace firebase_testapp_automated
35.16648
80
0.706583
[ "vector" ]
3a025fa2a4ea83426e6860d3ceff9b2d200c1b71
4,318
cpp
C++
src/GameObject.cpp
filipecaixeta/NeonEdgeGame
7dbc825507d731d60a96b4a82975a70e6aa68d7e
[ "MIT" ]
6
2017-05-10T19:25:23.000Z
2021-04-08T23:55:17.000Z
src/GameObject.cpp
filipecaixeta/NeonEdgeGame
7dbc825507d731d60a96b4a82975a70e6aa68d7e
[ "MIT" ]
1
2017-11-10T12:17:26.000Z
2017-11-10T12:17:26.000Z
src/GameObject.cpp
filipecaixeta/NeonEdgeGame
7dbc825507d731d60a96b4a82975a70e6aa68d7e
[ "MIT" ]
5
2017-05-30T01:07:46.000Z
2021-04-08T23:55:19.000Z
/** * Copyright 2017 Neon Edge Game. * File Name: GameObject.cpp * Header File Name: GameObject.h * Class Name: GameObject * Objective: it manages game object. */ #include "GameObject.h" #include "Character.h" #include "Game.h" GameObject::~GameObject() { } /** * Objective: it compares given string with name. * * @param string stringName. * @return bool 'stringName == name' - status of given string. */ bool GameObject::Is(std::string stringName) { return (stringName == name); } /** * Objective: it verifies if game object is dead. * * @param none. * @return bool isDead - game object life status. */ bool GameObject::IsDead() { return isDead; } /** * Objective: it says that game object is not a character. * * @param none. * @return bool false. */ bool GameObject::IsCharacter() { return false; } /** * Objective: it says that game object is not a player. * * @param none. * @return bool false. */ bool GameObject::IsPlayer() { return false; } /** * Objective: it gets position of game object. * * @param none. * @return Vec2(box.x, box.y) - position of game object. */ Vec2 GameObject::GetPosition() { return Vec2(box.x, box.y); } /** * Objective: it sets position of game object. * * @param Vec2 position. * @return none. */ void GameObject::SetPosition(Vec2 position) { if ((position.x >= FLOAT_MIN_SIZE && position.x <= FLOAT_MAX_SIZE) && (position.y >= FLOAT_MIN_SIZE && position.y <= FLOAT_MAX_SIZE)) { box.x = position.x; box.y = position.y; } else { // It does nothing. } } /** * Objective: it does nothing. * * @param int tile. * @param Face face. * @return none. */ void GameObject::NotifyTileCollision(int tile, Face face) { } /** * Objective: it does nothing. * * @param GameObject *gameObject. * @return none. */ void GameObject::NotifyObjectCollision(GameObject *gameObject) { } /** * Objective: it manages solid colitions. * * @param GameObject *gameObject. * @return none. */ void GameObject::SolidColision(GameObject *gameObject) { if (gameObject && IsCharacter()) { Character *character = (Character *) this; int y = box.y - character->physicsComponent.velocity.y * Game::GetInstance().GetDeltaTime(); if (footing != GROUNDED && y + box.h < gameObject->box.y) { box.y = gameObject->box.y - box.h - 1; character->physicsComponent.velocity.y = 0.6; if (lastFooting != GROUNDED) { lastFooting = footing; } else { // It does nothing. } footing = GROUNDED; } else { if (character->physicsComponent.velocity.x < 0) { if (box.x < gameObject->box.x + gameObject->box.w && box.x + box.w > gameObject->box.x + gameObject->box.w) { box.x = gameObject->box.x + gameObject->box.w + 1; } else { // It does nothing. } } else if (character->physicsComponent.velocity.x > 0) { if (box.x + box.w > gameObject->box.x && box.x < gameObject->box.x) { box.x = gameObject->box.x - box.w-1; } else { // It does nothing. } } else { // It does nothing. } } if (y > gameObject->box.y + gameObject->box.h) { box.y = gameObject->box.y + gameObject->box.h + 1; character->physicsComponent.velocity.y = 0; } else { // It does nothing. } character->graphicsComponent->Update(this, 0); } else { // It does nothing. } } /** * Objective: it gets colision data. * * @param SDL_Surface **surface * @param SDL_Rect &clipRect * @param Vec2 &position * @param bool &mirror * @return bool false. */ bool GameObject::GetColisionData(SDL_Surface **surface, SDL_Rect &clipRect, Vec2 &position, bool &mirror) { return false; } /** * Objective: it starts death time of game object. * * @param none. * @return none. */ void GameObject::DieAnimation() { dieTimer.Start(); } /** * Objective: it does nothing. * * @param none. * @return none. */ void GameObject::Render() { }
23.467391
125
0.574572
[ "render", "object", "solid" ]
3a084d51d697026ce576b1deaf6a5c5ad7d5cb63
1,194
cpp
C++
abbrev.cpp
celest1us/abbreviation
0075f537c35ce78acdab9897b1fca6a0eab10bf6
[ "Apache-2.0" ]
null
null
null
abbrev.cpp
celest1us/abbreviation
0075f537c35ce78acdab9897b1fca6a0eab10bf6
[ "Apache-2.0" ]
null
null
null
abbrev.cpp
celest1us/abbreviation
0075f537c35ce78acdab9897b1fca6a0eab10bf6
[ "Apache-2.0" ]
null
null
null
#include <vector> #include <ctype.h> #include "abbrev.hpp" using namespace std; bool isStringLower(const string s) { for (int i = 0; i < (int)s.length(); ++i) if (!islower(s[i])) return false; return true; } int abbreviationAux(const string &a, const string &b, int ia, int ib, vector<vector<int>> &dp) { if (ia == (int)a.length()) { if (ib == (int)b.length()) return 1; else return 0; } else if (ib == (int)b.length()) return isStringLower(a.substr(ia)); if (dp[ia][ib] == -1) { if (a[ia] == b[ib]) dp[ia][ib] = abbreviationAux(a, b, ia+1, ib+1, dp); else if (toupper(a[ia]) == b[ib]) dp[ia][ib] = abbreviationAux(a, b, ia+1, ib+1, dp) || abbreviationAux(a, b, ia+1, ib, dp); else if (a[ia] != b[ib] && isupper(a[ia])) dp[ia][ib] = 0; else dp[ia][ib] = abbreviationAux(a, b, ia+1, ib, dp); } return dp[ia][ib]; } string abbreviation(string a, string b) { if (b.length() > a.length()) return "NO"; vector<vector<int>> dp(a.length(), vector<int>(b.length(), -1)); auto res = abbreviationAux(a, b, 0, 0, dp); if (res == 1) return "YES"; else return "NO"; }
29.121951
132
0.544389
[ "vector" ]
3a086c6d1f83d1921a43ca4fa21c5fa359f10d60
41,734
cpp
C++
src/mrp/priority-request-server/PriorityRequestServer.cpp
fredsongyu/mmitss-az
62fb59a9e5a19f62a1096971f3cc0ecc04599106
[ "Apache-2.0" ]
10
2018-12-05T14:48:59.000Z
2022-02-17T02:10:51.000Z
src/mrp/priority-request-server/PriorityRequestServer.cpp
fredsongyu/mmitss-az
62fb59a9e5a19f62a1096971f3cc0ecc04599106
[ "Apache-2.0" ]
null
null
null
src/mrp/priority-request-server/PriorityRequestServer.cpp
fredsongyu/mmitss-az
62fb59a9e5a19f62a1096971f3cc0ecc04599106
[ "Apache-2.0" ]
8
2018-11-16T06:38:25.000Z
2022-03-09T18:22:59.000Z
/* ********************************************************************************** © 2019 Arizona Board of Regents on behalf of the University of Arizona with rights granted for USDOT OSADP distribution with the Apache 2.0 open source license. ********************************************************************************** PriorityRequestServer.cpp Created by: Debashis Das University of Arizona College of Engineering This code was developed under the supervision of Professor Larry Head in the Systems and Industrial Engineering Department. Revision History: 1. This is the initial revision developed for receiving srm data from the vehicle (transceiver) and mainitaining the priority requests. 2. This application matches the intersection ID of the receive SRM to determine whether to accept the SRM or not 3. The scripts either add, update or delete the request from the ART based on the vehicle type 4. If the request comes from an emergency vehicle, the application will create split phase request and append it into the ART. 5. This script use mapengine library to obtain the requested signal group. 6. This application sends the requests list to the solver in a JSON formatted message. 7. This application update the ETA of the available requests in the ART and create a JSON formatted SSM message. 8. This application also delete the timed-out priority request from the ART. */ #include <cstddef> #include <cstdlib> #include <sstream> #include <string> #include <vector> #include <unistd.h> #include <ctime> #include <algorithm> #include "PriorityRequestServer.h" #include "AsnJ2735Lib.h" #include "dsrcConsts.h" #include "geoUtils.h" #include <time.h> using namespace MsgEnum; PriorityRequestServer::PriorityRequestServer() { bool singleFrame{false}; readconfigFile(); LocAware *tempPlocAwareLib = new LocAware(mapPayloadFileName, singleFrame); plocAwareLib = tempPlocAwareLib; } /* - Method for identifying the message type */ int PriorityRequestServer::getMessageType(string jsonString) { int messageType{}; Json::Value jsonObject; Json::CharReaderBuilder builder; Json::CharReader *reader = builder.newCharReader(); string errors{}; bool parsingSuccessful = reader->parse(jsonString.c_str(), jsonString.c_str() + jsonString.size(), &jsonObject, &errors); delete reader; if (parsingSuccessful) { if ((jsonObject["MsgType"]).asString() == "SRM") messageType = MsgEnum::DSRCmsgID_srm; else if ((jsonObject["MsgType"]).asString() == "CoordinationRequest") messageType = static_cast<int>(msgType::coordinationRequest); else { displayConsoleData("Message type is unknown"); loggingData("Message type is unknown"); } } return messageType; } /* Get the Intersection ID from the configuration file. */ int PriorityRequestServer::getIntersectionID() { return intersectionID; } /* Get the Regional ID from the configuration file. */ int PriorityRequestServer::getRegionalID() { return regionalID; } /* If Intersection ID and Regional ID match then accept the srm */ bool PriorityRequestServer::acceptSignalRequest(SignalRequest signalRequest) { bool matchIntersection{false}; msgReceived++; if (intersectionID == signalRequest.getIntersectionID() && regionalID == signalRequest.getRegionalID()) matchIntersection = true; else { displayConsoleData("Discard the SRM since intersectionId doesn't match"); loggingData("Discard the SRM since intersectionId doesn't match"); matchIntersection = false; msgRejected++; } return matchIntersection; } /* If Active Request Table is empty or vehicle ID is not found in the Active Request Table and request type is priority request then add received srm in the Active Request table */ bool PriorityRequestServer::addToActiveRequestTable(SignalRequest signalRequest) { bool addRequest{false}; int vehicleID = signalRequest.getTemporaryVehicleID(); vector<ActiveRequest>::iterator findVehicleIDOnTable = std::find_if(std::begin(ActiveRequestTable), std::end(ActiveRequestTable), [&](ActiveRequest const &p) { return p.vehicleID == vehicleID; }); if (ActiveRequestTable.size() >= Maximum_Number_Of_Priority_Request) addRequest = false; else if (ActiveRequestTable.empty() && (signalRequest.getPriorityRequestType() == static_cast<int>(MsgEnum::requestType::priorityRequest))) addRequest = true; else if (!ActiveRequestTable.empty() && (findVehicleIDOnTable == ActiveRequestTable.end()) && (signalRequest.getPriorityRequestType() == static_cast<int>(MsgEnum::requestType::priorityRequest))) addRequest = true; return addRequest; } /* - If Active Request Table is not empty or vehicle ID is already in the Active Request Table then- if msg count or vehicle Signal group or vehicle ETA changed then update Active request Table */ bool PriorityRequestServer::updateActiveRequestTable(SignalRequest signalRequest) { bool updateValue{false}; int vehicleID = signalRequest.getTemporaryVehicleID(); vector<ActiveRequest>::iterator findVehicleIDOnTable = std::find_if(std::begin(ActiveRequestTable), std::end(ActiveRequestTable), [&](ActiveRequest const &p) { return p.vehicleID == vehicleID; }); if (ActiveRequestTable.empty()) updateValue = false; else if (!ActiveRequestTable.empty() && findVehicleIDOnTable == ActiveRequestTable.end()) updateValue = false; else if (!ActiveRequestTable.empty() && (findVehicleIDOnTable != ActiveRequestTable.end()) && (signalRequest.getPriorityRequestType() == static_cast<int>(MsgEnum::requestType::requestUpdate))) updateValue = true; return updateValue; } /* If Active Request Table is not empty or vehicle ID is already in the Active Request Table then- if priority request type is priorityCancellation then delete the srm from the Active Request Table */ bool PriorityRequestServer::deleteRequestfromActiveRequestTable(SignalRequest signalRequest) { bool deleteRequest{false}; int vehicleID = signalRequest.getTemporaryVehicleID(); std::vector<ActiveRequest>::iterator findVehicleIDOnTable = std::find_if(std::begin(ActiveRequestTable), std::end(ActiveRequestTable), [&](ActiveRequest const &p) { return p.vehicleID == vehicleID; }); if (ActiveRequestTable.empty()) deleteRequest = false; else if (!ActiveRequestTable.empty() && findVehicleIDOnTable == ActiveRequestTable.end()) deleteRequest = false; else if (!ActiveRequestTable.empty() && (findVehicleIDOnTable != ActiveRequestTable.end()) && (signalRequest.getPriorityRequestType() == static_cast<int>(MsgEnum::requestType::priorityCancellation))) deleteRequest = true; return deleteRequest; } /* If there is no signal request is received from a vehicle for more than predifined time(10sec), PRS needs to delete that request. */ bool PriorityRequestServer::checkTimedOutRequestDeletingRequirement() { bool deleteSignalRequest{false}; double currentTime = getPosixTimestamp(); if (!ActiveRequestTable.empty()) { for (size_t i = 0; i < ActiveRequestTable.size(); i++) { if ((currentTime - ActiveRequestTable[i].msgReceivedTime) >= requestTimedOutValue) { deleteSignalRequest = true; setRequestTimedOutVehicleID(ActiveRequestTable[i].vehicleID); deleteTimedOutRequestfromActiveRequestTable(); break; } } } return deleteSignalRequest; } /* -Setters for the timed out request. Set the vehicile ID which is not sending update request for a predefined amount of time */ void PriorityRequestServer::setRequestTimedOutVehicleID(int timedOutVehicleID) { requestTimedOutVehicleID = timedOutVehicleID; } /* -If Active Request Table is empty, set the etaUpdateTime as current time while adding new priority requests */ void PriorityRequestServer::setETAUpdateTime() { double currentTime = getPosixTimestamp(); if (ActiveRequestTable.empty()) etaUpdateTime = currentTime; } /* -Method for the obtaining the timed out vehicle ID */ int PriorityRequestServer::getRequestTimedOutVehicleID() { return requestTimedOutVehicleID; } /* Method to check if EV is in the list to set priority request status */ bool PriorityRequestServer::findEVInList() { bool emergencyVehicleStatusInList{false}; if (!ActiveRequestTable.empty()) { for (size_t i = 0; i < ActiveRequestTable.size(); i++) { if (ActiveRequestTable[i].basicVehicleRole == static_cast<int>(MsgEnum::basicRole::fire)) { emergencyVehicleStatusInList = true; break; } else emergencyVehicleStatusInList = false; } } else emergencyVehicleStatusInList = false; return emergencyVehicleStatusInList; } /* Method to check if received SRM is from EV or not */ bool PriorityRequestServer::findEVInRequest(SignalRequest signalRequest) { bool emergencyVehicleRequest{false}; if (signalRequest.getBasicVehicleRole() == static_cast<int>(MsgEnum::basicRole::fire)) emergencyVehicleRequest = true; return emergencyVehicleRequest; } /* - Obtain Split Phase information if EV is in List */ int PriorityRequestServer::getSplitPhase(int signalGroup) { vector<int>::iterator it; int temporarySplitPhase{}; switch (signalGroup) { case 1: temporarySplitPhase = 6; break; case 2: temporarySplitPhase = 5; break; case 3: temporarySplitPhase = 8; break; case 4: temporarySplitPhase = 7; break; case 5: temporarySplitPhase = 2; break; case 6: temporarySplitPhase = 1; break; case 7: temporarySplitPhase = 4; break; case 8: temporarySplitPhase = 3; break; default: break; } return temporarySplitPhase; } /* - Method to manage (create, update and delete) requests in the Active Request Table - If the request is received from EV, split phase request is added, or updated, or deleted in the ART. - If the the request type is update: - If the update request is received from transit or truck, find the position of the corresponding vehicle and update the information. - If the update request is received from EV, remove the vehicles priority requests both for the requested phase and the split phase request from the list. - The newly received update request in the list - Then append the request regarding the split phase - ETA of the other (already added) priority requests in the ART will be updated. */ void PriorityRequestServer::manageSignalRequestTable(SignalRequest signalRequest) { int vehicleID{}; int temporarySignalGroup{}; double currentTime = getPosixTimestamp(); ActiveRequest activeRequest; activeRequest.reset(); displayConsoleData("Received Priority Request from MsgDecoder"); loggingData("Received Priority Request from MsgDecoder"); if (acceptSignalRequest(signalRequest)) { if (addToActiveRequestTable(signalRequest)) { setETAUpdateTime(); setPRSUpdateCount(); setVehicleType(signalRequest); temporarySignalGroup = getSignalGroup(signalRequest); activeRequest.vehicleID = signalRequest.getTemporaryVehicleID(); activeRequest.requestID = signalRequest.getRequestID(); activeRequest.msgCount = signalRequest.getMsgCount(); activeRequest.basicVehicleRole = signalRequest.getBasicVehicleRole(); activeRequest.vehicleType = vehicleType; activeRequest.vehicleLaneID = signalRequest.getInBoundLaneID(); activeRequest.minuteOfYear = getMinuteOfYear(); activeRequest.secondOfMinute = getMsOfMinute() / SECOND_FROM_MILISECOND; activeRequest.signalGroup = temporarySignalGroup; activeRequest.vehicleETA = signalRequest.getETA_Minute() * SECONDS_IN_A_MINUTE + signalRequest.getETA_Second(); activeRequest.vehicleETADuration = signalRequest.getETA_Duration(); activeRequest.vehicleLatitude = signalRequest.getLatitude_DecimalDegree(); activeRequest.vehicleLongitude = signalRequest.getLongitude_DecimalDegree(); activeRequest.vehicleElevation = signalRequest.getElevation_Meter(); activeRequest.vehicleHeading = signalRequest.getHeading_Degree(); activeRequest.vehicleSpeed = signalRequest.getSpeed_MeterPerSecond(); activeRequest.msgReceivedTime = currentTime; activeRequest.etaUpdateTime = currentTime; ActiveRequestTable.push_back(activeRequest); //Add split phase request in the ART if (findEVInRequest(signalRequest)) { activeRequest.vehicleID = signalRequest.getTemporaryVehicleID(); activeRequest.requestID = signalRequest.getRequestID(); activeRequest.msgCount = signalRequest.getMsgCount(); activeRequest.basicVehicleRole = signalRequest.getBasicVehicleRole(); activeRequest.vehicleType = vehicleType; activeRequest.vehicleLaneID = signalRequest.getInBoundLaneID(); activeRequest.minuteOfYear = getMinuteOfYear(); activeRequest.secondOfMinute = getMsOfMinute() / SECOND_FROM_MILISECOND; activeRequest.signalGroup = getSplitPhase(temporarySignalGroup); activeRequest.vehicleETA = signalRequest.getETA_Minute() * SECONDS_IN_A_MINUTE + signalRequest.getETA_Second(); activeRequest.vehicleETADuration = signalRequest.getETA_Duration(); activeRequest.vehicleLatitude = signalRequest.getLatitude_DecimalDegree(); activeRequest.vehicleLongitude = signalRequest.getLongitude_DecimalDegree(); activeRequest.vehicleElevation = signalRequest.getElevation_Meter(); activeRequest.vehicleHeading = signalRequest.getHeading_Degree(); activeRequest.vehicleSpeed = signalRequest.getSpeed_MeterPerSecond(); activeRequest.msgReceivedTime = currentTime; activeRequest.etaUpdateTime = currentTime; ActiveRequestTable.push_back(activeRequest); } updateETAInActiveRequestTable(); } else if (updateActiveRequestTable(signalRequest)) { setPRSUpdateCount(); vehicleID = signalRequest.getTemporaryVehicleID(); //For EV prioriry requests if (signalRequest.getBasicVehicleRole() == static_cast<int>(MsgEnum::basicRole::fire)) { for (int i = 0; i < 2; i++) { std::vector<ActiveRequest>::iterator findVehicleIDOnTable = std::find_if(std::begin(ActiveRequestTable), std::end(ActiveRequestTable), [&](ActiveRequest const &p) { return p.vehicleID == vehicleID; }); ActiveRequestTable.erase(findVehicleIDOnTable); } setVehicleType(signalRequest); temporarySignalGroup = getSignalGroup(signalRequest); activeRequest.vehicleID = signalRequest.getTemporaryVehicleID(); activeRequest.requestID = signalRequest.getRequestID(); activeRequest.msgCount = signalRequest.getMsgCount(); activeRequest.basicVehicleRole = signalRequest.getBasicVehicleRole(); activeRequest.vehicleType = vehicleType; activeRequest.vehicleLaneID = signalRequest.getInBoundLaneID(); activeRequest.minuteOfYear = getMinuteOfYear(); activeRequest.secondOfMinute = getMsOfMinute() / SECOND_FROM_MILISECOND; activeRequest.signalGroup = temporarySignalGroup; activeRequest.vehicleETA = signalRequest.getETA_Minute() * SECONDS_IN_A_MINUTE + signalRequest.getETA_Second(); activeRequest.vehicleETADuration = signalRequest.getETA_Duration(); activeRequest.vehicleLatitude = signalRequest.getLatitude_DecimalDegree(); activeRequest.vehicleLongitude = signalRequest.getLongitude_DecimalDegree(); activeRequest.vehicleElevation = signalRequest.getElevation_Meter(); activeRequest.vehicleHeading = signalRequest.getHeading_Degree(); activeRequest.vehicleSpeed = signalRequest.getSpeed_MeterPerSecond(); activeRequest.msgReceivedTime = currentTime; activeRequest.etaUpdateTime = currentTime; ActiveRequestTable.push_back(activeRequest); if (findEVInRequest(signalRequest)) { activeRequest.vehicleID = signalRequest.getTemporaryVehicleID(); activeRequest.requestID = signalRequest.getRequestID(); activeRequest.msgCount = signalRequest.getMsgCount(); activeRequest.basicVehicleRole = signalRequest.getBasicVehicleRole(); activeRequest.vehicleType = vehicleType; activeRequest.vehicleLaneID = signalRequest.getInBoundLaneID(); activeRequest.minuteOfYear = getMinuteOfYear(); activeRequest.secondOfMinute = getMsOfMinute() / SECOND_FROM_MILISECOND; activeRequest.signalGroup = getSplitPhase(temporarySignalGroup); activeRequest.vehicleETA = signalRequest.getETA_Minute() * SECONDS_IN_A_MINUTE + signalRequest.getETA_Second(); activeRequest.vehicleETADuration = signalRequest.getETA_Duration(); activeRequest.vehicleLatitude = signalRequest.getLatitude_DecimalDegree(); activeRequest.vehicleLongitude = signalRequest.getLongitude_DecimalDegree(); activeRequest.vehicleElevation = signalRequest.getElevation_Meter(); activeRequest.vehicleHeading = signalRequest.getHeading_Degree(); activeRequest.vehicleSpeed = signalRequest.getSpeed_MeterPerSecond(); activeRequest.msgReceivedTime = currentTime; activeRequest.etaUpdateTime = currentTime; ActiveRequestTable.push_back(activeRequest); } } //For Transit and Truck priority requests else { std::vector<ActiveRequest>::iterator findVehicleIDOnTable = std::find_if(std::begin(ActiveRequestTable), std::end(ActiveRequestTable), [&](ActiveRequest const &p) { return p.vehicleID == vehicleID; }); findVehicleIDOnTable->vehicleID = signalRequest.getTemporaryVehicleID(); findVehicleIDOnTable->requestID = signalRequest.getRequestID(); findVehicleIDOnTable->msgCount = signalRequest.getMsgCount(); findVehicleIDOnTable->basicVehicleRole = signalRequest.getBasicVehicleRole(); findVehicleIDOnTable->vehicleLaneID = signalRequest.getInBoundLaneID(); findVehicleIDOnTable->minuteOfYear = getMinuteOfYear(); findVehicleIDOnTable->secondOfMinute = getMsOfMinute() / SECOND_FROM_MILISECOND; findVehicleIDOnTable->signalGroup = getSignalGroup(signalRequest); findVehicleIDOnTable->vehicleETA = signalRequest.getETA_Minute() * SECONDS_IN_A_MINUTE + signalRequest.getETA_Second(); findVehicleIDOnTable->vehicleETADuration = signalRequest.getETA_Duration(); findVehicleIDOnTable->vehicleLatitude = signalRequest.getLatitude_DecimalDegree(); findVehicleIDOnTable->vehicleLongitude = signalRequest.getLongitude_DecimalDegree(); findVehicleIDOnTable->vehicleElevation = signalRequest.getElevation_Meter(); findVehicleIDOnTable->vehicleHeading = signalRequest.getHeading_Degree(); findVehicleIDOnTable->vehicleSpeed = signalRequest.getSpeed_MeterPerSecond(); findVehicleIDOnTable->msgReceivedTime = currentTime; findVehicleIDOnTable->etaUpdateTime = currentTime; } updateETAInActiveRequestTable(); } else if (deleteRequestfromActiveRequestTable(signalRequest)) { vehicleID = signalRequest.getTemporaryVehicleID(); //If the delete request is for EV we need to delete both EV request (through and left turn phase) if (findEVInRequest(signalRequest)) { for (int i = 0; i < 2; i++) { std::vector<ActiveRequest>::iterator findVehicleIDOnTable = std::find_if(std::begin(ActiveRequestTable), std::end(ActiveRequestTable), [&](ActiveRequest const &p) { return p.vehicleID == vehicleID; }); if (findVehicleIDOnTable != ActiveRequestTable.end()) ActiveRequestTable.erase(findVehicleIDOnTable); } if (!ActiveRequestTable.empty()) { std::vector<ActiveRequest>::iterator findVehicleTypeOnTable = std::find_if(std::begin(ActiveRequestTable), std::end(ActiveRequestTable), [&](ActiveRequest const &p) { return p.vehicleType == emergencyVehicleType; }); if (findVehicleTypeOnTable == ActiveRequestTable.end()) sentClearRequestForEV = true; } } else { std::vector<ActiveRequest>::iterator findVehicleIDOnTable = std::find_if(std::begin(ActiveRequestTable), std::end(ActiveRequestTable), [&](ActiveRequest const &p) { return p.vehicleID == vehicleID; }); if (findVehicleIDOnTable != ActiveRequestTable.end()) ActiveRequestTable.erase(findVehicleIDOnTable); } updateETAInActiveRequestTable(); } setPriorityRequestStatus(); setSrmMessageStatus(signalRequest); sendSSM = true; sendPriorityRequestList = true; } else { sendSSM = false; sendPriorityRequestList = false; } } /* Method to delete vehicle info from Active Request Table if Infrustracture doesn't receive and SRM for predefined time */ void PriorityRequestServer::deleteTimedOutRequestfromActiveRequestTable() { int vehicleID{}; int associatedVehicleID{}; vehicleID = getRequestTimedOutVehicleID(); vector<ActiveRequest>::iterator findVehicleIDOnTable = std::find_if(std::begin(ActiveRequestTable), std::end(ActiveRequestTable), [&](ActiveRequest const &p) { return p.vehicleID == vehicleID; }); //For EV we have to delete two request if ((findVehicleIDOnTable->vehicleType == static_cast<int>(MsgEnum::vehicleType::special)) && (findVehicleIDOnTable != ActiveRequestTable.end())) { ActiveRequestTable.erase(findVehicleIDOnTable); //Deleting the request related to split phase. vector<ActiveRequest>::iterator findSplitPhaseEV = std::find_if(std::begin(ActiveRequestTable), std::end(ActiveRequestTable), [&](ActiveRequest const &p) { return p.vehicleID == vehicleID; }); ActiveRequestTable.erase(findSplitPhaseEV); if (!ActiveRequestTable.empty()) { std::vector<ActiveRequest>::iterator findVehicleTypeOnTable = std::find_if(std::begin(ActiveRequestTable), std::end(ActiveRequestTable), [&](ActiveRequest const &p) { return p.vehicleType == emergencyVehicleType; }); if (findVehicleTypeOnTable == ActiveRequestTable.end()) sentClearRequestForEV = true; } } //For Coordination Request else if ((findVehicleIDOnTable->vehicleType == coordinationVehicleType) && (findVehicleIDOnTable != ActiveRequestTable.end())) { ActiveRequestTable.erase(findVehicleIDOnTable); if (vehicleID == 1) associatedVehicleID = 2; else if (vehicleID == 2) associatedVehicleID = 1; else if (vehicleID == 3) associatedVehicleID = 4; else if (vehicleID == 4) associatedVehicleID = 3; //Deleting the associated coordination request on the same cycle. vector<ActiveRequest>::iterator findAssociatedCoordinationRequest = std::find_if(std::begin(ActiveRequestTable), std::end(ActiveRequestTable), [&](ActiveRequest const &p) { return p.vehicleID == associatedVehicleID; }); ActiveRequestTable.erase(findAssociatedCoordinationRequest); } //For Transit and truck PriorityRequest else if (findVehicleIDOnTable != ActiveRequestTable.end()) ActiveRequestTable.erase(findVehicleIDOnTable); displayConsoleData("Deleted Timed-Out Request"); loggingData("Deleted Timed-Out Request"); } /* Method for creating Signal Status Message from the Active Request Table. */ string PriorityRequestServer::createSSMJsonString(SignalStatus signalStatus) { string ssmJsonString{}; signalStatus.reset(); signalStatus.setMinuteOfYear(getMinuteOfYear()); signalStatus.setMsOfMinute(getMsOfMinute()); signalStatus.setSequenceNumber(getPRSSequenceNumber()); signalStatus.setUpdateCount(getPRSUpdateCount()); signalStatus.setRegionalID(regionalID); signalStatus.setIntersectionID(intersectionID); ssmJsonString = signalStatus.signalStatus2Json(ActiveRequestTable); displayConsoleData("SSM will send to MsgEncoder"); loggingData("SSM will send to MsgEncoder"); loggingData(ssmJsonString); return ssmJsonString; } /* Method for creating json string from the Active Request Table for the Priority Solver. */ string PriorityRequestServer::createJsonStringForPrioritySolver() { string solverJsonString{}; int noOfRequest{}; Json::Value jsonObject; Json::StreamWriterBuilder builder; builder["commentStyle"] = "None"; builder["indentation"] = ""; noOfRequest = static_cast<int>(ActiveRequestTable.size()); if (sentClearRequestForEV || ActiveRequestTable.empty()) { jsonObject["MsgType"] = "ClearRequest"; sentClearRequest = true; sentClearRequestForEV = false; displayConsoleData("Clear Request Message will send to PRSolver"); loggingData("Clear Request Message will send to PRSolver"); } else if (noOfRequest > 0) { jsonObject["MsgType"] = "PriorityRequest"; jsonObject["PriorityRequestList"]["noOfRequest"] = noOfRequest; jsonObject["PriorityRequestList"]["regionalID"] = regionalID; jsonObject["PriorityRequestList"]["intersectionID"] = intersectionID; for (int i = 0; i < noOfRequest; i++) { jsonObject["PriorityRequestList"]["requestorInfo"][i]["vehicleID"] = ActiveRequestTable[i].vehicleID; jsonObject["PriorityRequestList"]["requestorInfo"][i]["vehicleType"] = ActiveRequestTable[i].vehicleType; jsonObject["PriorityRequestList"]["requestorInfo"][i]["basicVehicleRole"] = ActiveRequestTable[i].basicVehicleRole; jsonObject["PriorityRequestList"]["requestorInfo"][i]["requestedSignalGroup"] = ActiveRequestTable[i].signalGroup; if (ActiveRequestTable[i].vehicleETA <= 0) jsonObject["PriorityRequestList"]["requestorInfo"][i]["ETA"] = 1.0; else jsonObject["PriorityRequestList"]["requestorInfo"][i]["ETA"] = ActiveRequestTable[i].vehicleETA; jsonObject["PriorityRequestList"]["requestorInfo"][i]["ETA_Duration"] = ActiveRequestTable[i].vehicleETADuration; jsonObject["PriorityRequestList"]["requestorInfo"][i]["speed_MeterPerSecond"] = ActiveRequestTable[i].vehicleSpeed; } sentClearRequest = false; displayConsoleData("Priority Request Message will send to PRSolver"); loggingData("Priority Request Message will send to PRSolver"); } solverJsonString = Json::writeString(builder, jsonObject); loggingData(solverJsonString); sendSSM = false; sendPriorityRequestList = false; return solverJsonString; } /* - Checking whether PRS need to send SSM or not. - If there is no request in the list, no need to send SSM */ bool PriorityRequestServer::checkSsmSendingRequirement() { return sendSSM; } /* - Getter for priority request list sending requirement */ bool PriorityRequestServer::getPriorityRequestListSendingRequirement() { return sendPriorityRequestList; } /* - Checking whether PRS need to update the ETA in the ART. - If there is no request in the list, no need to update the ETA - If vehicle ETA is zero, no need to update. */ bool PriorityRequestServer::updateETA() { bool etaUpdateRequirement{false}; double currentTime = getPosixTimestamp(); if (!ActiveRequestTable.empty() && (currentTime - etaUpdateTime >= TIME_GAP_BETWEEN_ETA_Update)) { etaUpdateRequirement = true; updateETAInActiveRequestTable(); } return etaUpdateRequirement; } /* - Method for checking whether clear request has to be sent to solver */ bool PriorityRequestServer::sendClearRequest() { bool clearRequestStatus{false}; if (ActiveRequestTable.empty() && (sentClearRequest == false)) clearRequestStatus = true; return clearRequestStatus; } /* - Method to update ETA in Active Request Table if vehile ETA is not zero. */ void PriorityRequestServer::updateETAInActiveRequestTable() { double currentTime = getPosixTimestamp(); if (!ActiveRequestTable.empty()) { for (size_t i = 0; i < ActiveRequestTable.size(); i++) { ActiveRequestTable[i].vehicleETA = ActiveRequestTable[i].vehicleETA - (currentTime - ActiveRequestTable[i].etaUpdateTime); ActiveRequestTable[i].etaUpdateTime = currentTime; if (ActiveRequestTable[i].vehicleETA <= 0) ActiveRequestTable[i].vehicleETA = 0.0; } etaUpdateTime = currentTime; } } /* Method to print Active Request Table */ void PriorityRequestServer::printActiveRequestTable() { double timeStamp = getPosixTimestamp(); if (!ActiveRequestTable.empty() && consoleOutput) { cout << "[" << fixed << showpoint << setprecision(4) << timeStamp << "] Active Request Table is following: " << endl; cout << "VehicleID" << " " << "VehicleType" << " " << "ETA" << " " << "ETADuration" << " " << "SignalGroup" << endl; for (size_t i = 0; i < ActiveRequestTable.size(); i++) cout << " " << ActiveRequestTable[i].vehicleID << " " << ActiveRequestTable[i].vehicleType << " " << ActiveRequestTable[i].vehicleETA << " " << ActiveRequestTable[i].vehicleETADuration << " " << ActiveRequestTable[i].signalGroup << endl; } else { displayConsoleData("Active Request Table is empty"); loggingData("Active Request Table is empty"); } } /* - Method for defining priority request status. - If there is EV in the priority request list for EV priority status will be granted and for rest of the vehicle priority status will be rejected. - If there is no EV in the priority request list for Transit and Truck priority status will be granted. */ void PriorityRequestServer::setPriorityRequestStatus() //work on this wih traffic controller or priority solver or whom. check page 176 of j2735 pdf { emergencyVehicleStatus = findEVInList(); if (emergencyVehicleStatus == true) { for (size_t i = 0; i < ActiveRequestTable.size(); i++) { if (ActiveRequestTable[i].basicVehicleRole == (static_cast<int>(MsgEnum::basicRole::fire))) ActiveRequestTable[i].prsStatus = static_cast<int>(MsgEnum::requestStatus::granted); else if (ActiveRequestTable[i].basicVehicleRole == (static_cast<int>(MsgEnum::basicRole::transit))) ActiveRequestTable[i].prsStatus = static_cast<int>(MsgEnum::requestStatus::rejected); else if (ActiveRequestTable[i].basicVehicleRole == (static_cast<int>(MsgEnum::basicRole::truck))) ActiveRequestTable[i].prsStatus = static_cast<int>(MsgEnum::requestStatus::rejected); else if (ActiveRequestTable[i].basicVehicleRole == (static_cast<int>(MsgEnum::basicRole::roadsideSource))) ActiveRequestTable[i].prsStatus = static_cast<int>(MsgEnum::requestStatus::rejected); else ActiveRequestTable[i].prsStatus = static_cast<int>(MsgEnum::requestStatus::unavailable); } } else if (emergencyVehicleStatus == false) { for (size_t i = 0; i < ActiveRequestTable.size(); i++) { if (ActiveRequestTable[i].basicVehicleRole == (static_cast<int>(MsgEnum::basicRole::transit))) ActiveRequestTable[i].prsStatus = static_cast<int>(MsgEnum::requestStatus::granted); else if (ActiveRequestTable[i].basicVehicleRole == (static_cast<int>(MsgEnum::basicRole::truck))) ActiveRequestTable[i].prsStatus = static_cast<int>(MsgEnum::requestStatus::granted); else if (ActiveRequestTable[i].basicVehicleRole == (static_cast<int>(MsgEnum::basicRole::roadsideSource))) ActiveRequestTable[i].prsStatus = static_cast<int>(MsgEnum::requestStatus::granted); else ActiveRequestTable[i].prsStatus = static_cast<int>(MsgEnum::requestStatus::unavailable); // In standard it is unknown } } } /* - Method for storing the SRM Message status for system performance data log */ void PriorityRequestServer::setSrmMessageStatus(SignalRequest signalRequest) { if ((emergencyVehicleStatus == true) && (signalRequest.getBasicVehicleRole() == static_cast<int>(MsgEnum::basicRole::fire))) msgServed++; else if ((emergencyVehicleStatus == true) && (signalRequest.getBasicVehicleRole() != static_cast<int>(MsgEnum::basicRole::fire))) msgRejected++; else if ((emergencyVehicleStatus == false) && (signalRequest.getBasicVehicleRole() == static_cast<int>(MsgEnum::basicRole::transit))) msgServed++; else if ((emergencyVehicleStatus == false) && (signalRequest.getBasicVehicleRole() == static_cast<int>(MsgEnum::basicRole::truck))) msgServed++; } /* Method for updating the updateCount from the infrastructure side. */ void PriorityRequestServer::setPRSUpdateCount() { if (updateCount < SEQUENCE_NUMBER_MAXLIMIT) updateCount++; else updateCount = SEQUENCE_NUMBER_MINLIMIT; } /* - Method for setting vehicle type based on the basic vehicle role */ void PriorityRequestServer::setVehicleType(SignalRequest signalRequest) { if (signalRequest.getBasicVehicleRole() == static_cast<int>(MsgEnum::basicRole::fire)) vehicleType = static_cast<int>(MsgEnum::vehicleType::special); else if (signalRequest.getBasicVehicleRole() == static_cast<int>(MsgEnum::basicRole::transit)) vehicleType = static_cast<int>(MsgEnum::vehicleType::bus); else if (signalRequest.getBasicVehicleRole() == static_cast<int>(MsgEnum::basicRole::truck)) vehicleType = static_cast<int>(MsgEnum::vehicleType::axleCnt4); else vehicleType = static_cast<int>(MsgEnum::vehicleType::unavailable); } /* Method for obtaining minute of a year based on current time. */ int PriorityRequestServer::getMinuteOfYear() { time_t t = time(NULL); tm *timePtr = gmtime(&t); int dayOfYear = timePtr->tm_yday; int currentHour = timePtr->tm_hour; int currentMinute = timePtr->tm_min; minuteOfYear = (dayOfYear - 1) * HOURS_IN_A_DAY * MINUTES_IN_A_HOUR + currentHour * MINUTES_IN_A_HOUR + currentMinute; return minuteOfYear; } /* Method for obtaining millisecond of a minute based on current time. */ int PriorityRequestServer::getMsOfMinute() { time_t t = time(NULL); tm *timePtr = gmtime(&t); int currentSecond = timePtr->tm_sec; msOfMinute = currentSecond * SECOND_FROM_MILISECOND; return msOfMinute; } /* Method for updating the messageCount from the infrastructure side. */ int PriorityRequestServer::getPRSSequenceNumber() { if (sequenceNumber < SEQUENCE_NUMBER_MAXLIMIT) sequenceNumber++; else sequenceNumber = SEQUENCE_NUMBER_MINLIMIT; return sequenceNumber; } /* Method for obtaining the updateCount. */ int PriorityRequestServer::getPRSUpdateCount() { return updateCount; } /* Method for obtaining signal group based on vehicle laneID and approachID using MapEngine Library. */ int PriorityRequestServer::getSignalGroup(SignalRequest signalRequest) { int phaseNo{}; int approachID{}; approachID = plocAwareLib->getApproachIdByLaneId(static_cast<uint16_t>(regionalID), static_cast<uint16_t>(intersectionID), static_cast<uint8_t>(signalRequest.getInBoundLaneID())); phaseNo = unsigned(plocAwareLib->getControlPhaseByIds(static_cast<uint16_t>(regionalID), static_cast<uint16_t>(intersectionID), static_cast<uint8_t>(approachID), static_cast<uint8_t>(signalRequest.getInBoundLaneID()))); return phaseNo; } /* - The following method delete the mapPayload file which has *.map.payload extension. - The method writes mapPayload in .map.payload formatted file based on the configuration file. - It also checks the logging requirement in the config file */ void PriorityRequestServer::readconfigFile() { string pathDirectory{}; string mapPayload{}; double timeStamp = getPosixTimestamp(); ofstream mapPayloadOutputfile; Json::Value jsonObject; Json::CharReaderBuilder builder; Json::CharReader *reader = builder.newCharReader(); string errors{}; ifstream jsonconfigfile("/nojournal/bin/mmitss-phase3-master-config.json"); string configJsonString((std::istreambuf_iterator<char>(jsonconfigfile)), std::istreambuf_iterator<char>()); reader->parse(configJsonString.c_str(), configJsonString.c_str() + configJsonString.size(), &jsonObject, &errors); delete reader; //Get intersection ID, regional ID, request timed out value for clearing the old request, time interval for logging the system performance data, logging requirement, mapPayload and intersection name intersectionID = jsonObject["IntersectionID"].asInt(); regionalID = jsonObject["RegionalID"].asInt(); requestTimedOutValue = jsonObject["SRMTimedOutTime"].asDouble(); timeInterval = jsonObject["SystemPerformanceTimeInterval"].asDouble(); logging = jsonObject["Logging"].asBool(); consoleOutput = jsonObject["ConsoleOutput"].asBool(); mapPayload = jsonObject["MapPayload"].asString(); intersectionName = jsonObject["IntersectionName"].asString(); mapPayloadFileName = "/nojournal/bin/" + intersectionName + ".map.payload"; //Delete old map file remove(mapPayloadFileName.c_str()); //Write the map palyload in a file mapPayloadOutputfile.open(mapPayloadFileName); mapPayloadOutputfile << "payload" << " " << intersectionName << " " << mapPayload << endl; mapPayloadOutputfile.close(); //Create Log File, if requires time_t now = time(0); struct tm tstruct; char logFileOpenningTime[80]; tstruct = *localtime(&now); strftime(logFileOpenningTime, sizeof(logFileOpenningTime), "%m%d%Y_%H%M%S", &tstruct); string logFileName = "/nojournal/bin/log/" + intersectionName + "_prsLog_" + logFileOpenningTime + ".log"; if (logging) { logFile.open(logFileName); logFile << "[" << fixed << showpoint << setprecision(4) << timeStamp << "] Open PRS log file for " << intersectionName << " intersection" << endl; } msgSentTime = timeStamp; } /* - Method for logging data in a file */ void PriorityRequestServer::loggingData(string logString) { double timeStamp = getPosixTimestamp(); if (logging) { logFile << "\n[" << fixed << showpoint << setprecision(4) << timeStamp << "] "; logFile << logString << endl; } } /* - Method for displaying console output */ void PriorityRequestServer::displayConsoleData(string consoleString) { double timestamp = getPosixTimestamp(); if (consoleOutput) { cout << "\n[" << fixed << showpoint << setprecision(4) << timestamp << "] "; cout << consoleString << endl; } } /* Method to check for sending system peformance data to Data-Collector. */ bool PriorityRequestServer::sendSystemPerformanceDataLog() { bool sendData{false}; double currentTime = getPosixTimestamp(); if (currentTime - msgSentTime >= timeInterval) sendData = true; return sendData; } /* Method to create a JSON string to send system peformance data to Data-Collector. */ string PriorityRequestServer::createJsonStringForSystemPerformanceDataLog() { string systemPerformanceDataLogJsonString{}; Json::Value jsonObject; Json::StreamWriterBuilder builder; builder["commentStyle"] = "None"; builder["indentation"] = ""; jsonObject["MsgType"] = "MsgCount"; jsonObject["MsgInformation"]["MsgSource"] = intersectionName; jsonObject["MsgInformation"]["MsgCountType"] = "SRM"; jsonObject["MsgInformation"]["MsgCount"] = msgReceived; jsonObject["MsgInformation"]["MsgServed"] = msgServed; jsonObject["MsgInformation"]["MsgRejected"] = msgRejected; jsonObject["MsgInformation"]["TimeInterval"] = timeInterval; jsonObject["MsgInformation"]["Timestamp_posix"] = getPosixTimestamp(); jsonObject["MsgInformation"]["Timestamp_verbose"] = getVerboseTimestamp(); systemPerformanceDataLogJsonString = Json::writeString(builder, jsonObject); displayConsoleData("System Performance Data Log will send to data collector"); loggingData("System Performance Data Log will send to data collector"); msgSentTime = getPosixTimestamp(); msgReceived = 0; msgServed = 0; msgRejected = 0; return systemPerformanceDataLogJsonString; } /* - Following method is responsible for managing the Coordination request - The method will check whether a particular coordination request is already available in the list or not (based on the vehicle ID) - If the request is already in the the list, the method will delete the old request. - The request will be added in the list afterwards. - The method will call setPriorityRequestStatus() function, to set the priority request status */ void PriorityRequestServer::manageCoordinationRequest(string jsonString) { double currentTime = getPosixTimestamp(); Json::Value jsonObject; Json::CharReaderBuilder builder; Json::CharReader *reader = builder.newCharReader(); string errors{}; ActiveRequest activeRequest; activeRequest.reset(); displayConsoleData("Received Coordination Request from Signal Coordination Request Generator"); loggingData("Received Coordination Request from Signal Coordination Request Generator"); setETAUpdateTime(); reader->parse(jsonString.c_str(), jsonString.c_str() + jsonString.size(), &jsonObject, &errors); delete reader; int noOfCoordinationRequest = jsonObject["noOfCoordinationRequest"].asInt(); for (size_t i = 0; i < ActiveRequestTable.size(); i++) { if (ActiveRequestTable[i].vehicleType == coordinationVehicleType) { vector<ActiveRequest>::iterator findCoordinationVehicleTypeOnTable = std::find_if(std::begin(ActiveRequestTable), std::end(ActiveRequestTable), [&](ActiveRequest const &p) { return p.vehicleType == coordinationVehicleType; }); ActiveRequestTable.erase(findCoordinationVehicleTypeOnTable); i--; } } if (noOfCoordinationRequest > 0) { for (int i = 0; i < noOfCoordinationRequest; i++) { activeRequest.minuteOfYear = jsonObject["minuteOfYear"].asInt(); activeRequest.secondOfMinute = jsonObject["msOfMinute"].asInt() / SECOND_FROM_MILISECOND; activeRequest.msgCount = jsonObject["msgCount"].asInt(); activeRequest.basicVehicleRole = jsonObject["CoordinationRequestList"]["requestorInfo"][i]["basicVehicleRole"].asInt(); activeRequest.signalGroup = jsonObject["CoordinationRequestList"]["requestorInfo"][i]["requestedPhase"].asInt(); activeRequest.vehicleID = jsonObject["CoordinationRequestList"]["requestorInfo"][i]["vehicleID"].asInt(); activeRequest.vehicleType = jsonObject["CoordinationRequestList"]["requestorInfo"][i]["vehicleType"].asInt(); activeRequest.vehicleETA = jsonObject["CoordinationRequestList"]["requestorInfo"][i]["ETA"].asDouble(); activeRequest.vehicleETADuration = jsonObject["CoordinationRequestList"]["requestorInfo"][i]["CoordinationSplit"].asDouble(); activeRequest.vehicleLaneID = coordinationLaneID; activeRequest.msgReceivedTime = currentTime; activeRequest.etaUpdateTime = currentTime; ActiveRequestTable.push_back(activeRequest); } setPriorityRequestStatus(); updateETAInActiveRequestTable(); sendSSM = true; sendPriorityRequestList = true; } else { sendSSM = false; sendPriorityRequestList = false; } } PriorityRequestServer::~PriorityRequestServer() { logFile.close(); delete plocAwareLib; }
36.102076
269
0.753558
[ "vector" ]
3a0abdd1a0b7d4483856d93cb49acf4b4d30fbe5
1,514
cpp
C++
leetcode/two_sum.cpp
jcpince/algorithms
c43dd8e98a0f0df691ead5f25c2c17a9241db908
[ "MIT" ]
null
null
null
leetcode/two_sum.cpp
jcpince/algorithms
c43dd8e98a0f0df691ead5f25c2c17a9241db908
[ "MIT" ]
null
null
null
leetcode/two_sum.cpp
jcpince/algorithms
c43dd8e98a0f0df691ead5f25c2c17a9241db908
[ "MIT" ]
null
null
null
/* 1. Two Sum Easy Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice. Example: Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1]. */ #include <vector> #include <cassert> #include <iostream> #include <algorithm> using namespace std; class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { vector<int> result = {0, 1}; for (vector<int>::iterator it = nums.begin() ; it != nums.end() ; it++) { int diff = target - *it; vector<int>::iterator it2 = find(it+1, nums.end(), diff); if (it2 != nums.end()) { result[1] = distance(nums.begin(), it2); break; } result[0]++; } cout << "returns [" << result[0] << ", " << result[1] << "]" << endl; return result; } }; int main(int argc, char **argv) { Solution s; vector<int> nums = {2, 7, 11, 15}; int target = 9; vector<int> result = s.twoSum(nums, target); assert((result.size() == 2) && (nums[result[0]] + nums[result[1]]) == target); nums = {3, 2, 4}; target = 6; result = s.twoSum(nums, target); assert((result.size() == 2) && (nums[result[0]] + nums[result[1]]) == target); cout << "All tests succeeded" << endl; return 0; }
24.031746
107
0.544254
[ "vector" ]
3a0c47cc87498cfbbd8bb369ef7b2893355941dc
177,634
cpp
C++
src/common/DataObjectRepository.cpp
Fabien-Bosquet/fesapi
73cec4d1665dba7a11864d90cb16f0205204946e
[ "Apache-2.0" ]
null
null
null
src/common/DataObjectRepository.cpp
Fabien-Bosquet/fesapi
73cec4d1665dba7a11864d90cb16f0205204946e
[ "Apache-2.0" ]
null
null
null
src/common/DataObjectRepository.cpp
Fabien-Bosquet/fesapi
73cec4d1665dba7a11864d90cb16f0205204946e
[ "Apache-2.0" ]
null
null
null
/*----------------------------------------------------------------------- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"; you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANYRockVolumeFeature KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -----------------------------------------------------------------------*/ #include "DataObjectRepository.h" #include <algorithm> #include <array> #include <functional> #include <ctime> #include "../common/DataFeeder.h" #include "../common/HdfProxyFactory.h" #include "../eml2_1/PropertyKind.h" #include "../resqml2_0_1/PropertyKindMapper.h" #include "../resqml2_0_1/BoundaryFeatureInterpretation.h" #include "../resqml2_0_1/LocalDepth3dCrs.h" #include "../resqml2_0_1/LocalTime3dCrs.h" #include "../resqml2_0_1/Horizon.h" #include "../resqml2_0_1/FluidBoundaryFeature.h" #include "../resqml2_0_1/TectonicBoundaryFeature.h" #include "../resqml2_0_1/FrontierFeature.h" #include "../resqml2_0_1/GeobodyFeature.h" #include "../resqml2_0_1/GenericFeatureInterpretation.h" #include "../resqml2_0_1/FaultInterpretation.h" #include "../resqml2_0_1/HorizonInterpretation.h" #include "../resqml2_0_1/GeobodyBoundaryInterpretation.h" #include "../resqml2_0_1/GeobodyInterpretation.h" #include "../resqml2_0_1/PolylineSetRepresentation.h" #include "../resqml2_0_1/PointSetRepresentation.h" #include "../resqml2_0_1/PlaneSetRepresentation.h" #include "../resqml2_0_1/SeismicLatticeFeature.h" #include "../resqml2_0_1/Grid2dRepresentation.h" #include "../resqml2_0_1/TriangulatedSetRepresentation.h" #include "../resqml2_0_1/WellboreFeature.h" #include "../resqml2_0_1/WellboreInterpretation.h" #include "../resqml2_0_1/WellboreFrameRepresentation.h" #include "../resqml2_0_1/WellboreMarkerFrameRepresentation.h" #include "../resqml2_0_1/WellboreMarker.h" #include "../resqml2_0_1/WellboreTrajectoryRepresentation.h" #include "../resqml2_0_1/DeviationSurveyRepresentation.h" #include "../resqml2_0_1/MdDatum.h" #include "../resqml2_0_1/PolylineRepresentation.h" #include "../resqml2_0_1/SubRepresentation.h" #include "../resqml2_0_1/GridConnectionSetRepresentation.h" #include "../resqml2_0_1/TimeSeries.h" #include "../resqml2_0_1/PropertyKind.h" #include "../resqml2_0_1/PropertySet.h" #include "../resqml2_0_1/ContinuousProperty.h" #include "../resqml2_0_1/CategoricalProperty.h" #include "../resqml2_0_1/DiscreteProperty.h" #include "../resqml2_0_1/PointsProperty.h" #include "../resqml2_0_1/CommentProperty.h" #include "../resqml2_0_1/DoubleTableLookup.h" #include "../resqml2_0_1/StringTableLookup.h" #include "../resqml2_0_1/SeismicLineFeature.h" #include "../resqml2_0_1/SeismicLineSetFeature.h" #include "../resqml2_0_1/OrganizationFeature.h" #include "../resqml2_0_1/BlockedWellboreRepresentation.h" #include "../resqml2_0_1/EarthModelInterpretation.h" #include "../resqml2_0_1/RepresentationSetRepresentation.h" #include "../resqml2_0_1/StructuralOrganizationInterpretation.h" #include "../resqml2_0_1/NonSealedSurfaceFrameworkRepresentation.h" #include "../resqml2_0_1/SealedSurfaceFrameworkRepresentation.h" #include "../resqml2_0_1/SealedVolumeFrameworkRepresentation.h" #include "../resqml2_0_1/RockFluidUnitFeature.h" #include "../resqml2_0_1/RockFluidUnitInterpretation.h" #include "../resqml2_0_1/RockFluidOrganizationInterpretation.h" #include "../resqml2_0_1/StratigraphicUnitFeature.h" #include "../resqml2_0_1/StratigraphicUnitInterpretation.h" #include "../resqml2_0_1/StratigraphicColumn.h" #include "../resqml2_0_1/StratigraphicColumnRankInterpretation.h" #include "../resqml2_0_1/StratigraphicOccurrenceInterpretation.h" #include "../resqml2_0_1/IjkGridExplicitRepresentation.h" #include "../resqml2_0_1/IjkGridLatticeRepresentation.h" #include "../resqml2_0_1/IjkGridNoGeometryRepresentation.h" #include "../resqml2_0_1/IjkGridParametricRepresentation.h" #include "../resqml2_0_1/UnstructuredGridRepresentation.h" #include "../resqml2_0_1/StreamlinesFeature.h" #include "../resqml2_0_1/StreamlinesRepresentation.h" #include "../resqml2_0_1/Activity.h" #include "../resqml2_0_1/ActivityTemplate.h" #if WITH_RESQML2_2 #include "../eml2_3/Activity.h" #include "../eml2_3/ActivityTemplate.h" #include "../eml2_3/GraphicalInformationSet.h" #include "../eml2_3/PropertyKind.h" #include "../eml2_3/TimeSeries.h" #include "../resqml2_2/BlockedWellboreRepresentation.h" #include "../resqml2_2/BoundaryFeature.h" #include "../resqml2_2/BoundaryFeatureInterpretation.h" #include "../resqml2_2/CategoricalProperty.h" #include "../resqml2_2/CmpLineFeature.h" #include "../resqml2_2/CommentProperty.h" #include "../resqml2_2/ContinuousProperty.h" #include "../resqml2_2/ContinuousColorMap.h" #include "../resqml2_2/CulturalFeature.h" #include "../resqml2_2/DeviationSurveyRepresentation.h" #include "../resqml2_2/DiscreteProperty.h" #include "../resqml2_2/DiscreteColorMap.h" #include "../resqml2_2/DoubleTableLookup.h" #include "../resqml2_2/EarthModelInterpretation.h" #include "../resqml2_2/FaultInterpretation.h" #include "../resqml2_2/FluidBoundaryInterpretation.h" #include "../resqml2_2/GenericFeatureInterpretation.h" #include "../resqml2_2/GeobodyBoundaryInterpretation.h" #include "../resqml2_2/GeobodyInterpretation.h" #include "../resqml2_2/Grid2dRepresentation.h" #include "../resqml2_2/GridConnectionSetRepresentation.h" #include "../resqml2_2/HorizonInterpretation.h" #include "../resqml2_2/IjkGridExplicitRepresentation.h" #include "../resqml2_2/IjkGridLatticeRepresentation.h" #include "../resqml2_2/IjkGridNoGeometryRepresentation.h" #include "../resqml2_2/IjkGridParametricRepresentation.h" #include "../resqml2_2/LocalDepth3dCrs.h" #include "../resqml2_2/LocalTime3dCrs.h" #include "../resqml2_2/MdDatum.h" #include "../resqml2_2/Model.h" #include "../resqml2_2/NonSealedSurfaceFrameworkRepresentation.h" #include "../resqml2_2/PlaneSetRepresentation.h" #include "../resqml2_2/PointSetRepresentation.h" #include "../resqml2_2/PointsProperty.h" #include "../resqml2_2/PolylineRepresentation.h" #include "../resqml2_2/PolylineSetRepresentation.h" #include "../resqml2_2/PropertySet.h" #include "../resqml2_2/RepresentationSetRepresentation.h" #include "../resqml2_2/RockFluidOrganizationInterpretation.h" #include "../resqml2_2/RockFluidUnitInterpretation.h" #include "../resqml2_2/RockVolumeFeature.h" #include "../resqml2_2/SealedSurfaceFrameworkRepresentation.h" #include "../resqml2_2/SealedVolumeFrameworkRepresentation.h" #include "../resqml2_2/SeismicLatticeFeature.h" #include "../resqml2_2/SeismicLineSetFeature.h" #include "../resqml2_2/SeismicWellboreFrameRepresentation.h" #include "../resqml2_2/ShotPointLineFeature.h" #include "../resqml2_2/StratigraphicColumn.h" #include "../resqml2_2/StratigraphicColumnRankInterpretation.h" #include "../resqml2_2/StratigraphicOccurrenceInterpretation.h" #include "../resqml2_2/StratigraphicUnitInterpretation.h" #include "../resqml2_2/StreamlinesFeature.h" #include "../resqml2_2/StreamlinesRepresentation.h" #include "../resqml2_2/StringTableLookup.h" #include "../resqml2_2/StructuralOrganizationInterpretation.h" #include "../resqml2_2/SubRepresentation.h" #include "../resqml2_2/TriangulatedSetRepresentation.h" #include "../resqml2_2/UnstructuredGridRepresentation.h" #include "../resqml2_2/WellboreFeature.h" #include "../resqml2_2/WellboreFrameRepresentation.h" #include "../resqml2_2/WellboreInterpretation.h" #include "../resqml2_2/WellboreMarkerFrameRepresentation.h" #include "../resqml2_2/WellboreTrajectoryRepresentation.h" #endif #include "../witsml2_0/Well.h" #include "../witsml2_0/Wellbore.h" #include "../witsml2_0/Trajectory.h" #include "../witsml2_0/WellCompletion.h" #include "../witsml2_0/WellboreCompletion.h" #include "../witsml2_0/WellboreGeometry.h" #include "../witsml2_0/WellboreMarker.h" #include "../witsml2_0/Log.h" #include "../witsml2_0/ChannelSet.h" #include "../witsml2_0/Channel.h" #if WITH_WITSML2_1 #include "../witsml2_1/Well.h" #include "../witsml2_1/Wellbore.h" #include "../witsml2_1/Trajectory.h" #include "../witsml2_1/Log.h" #include "../witsml2_1/WellboreMarkerSet.h" #include "../witsml2_1/ToolErrorModelDictionary.h" #include "../witsml2_1/ErrorTermDictionary.h" #include "../witsml2_1/WeightingFunction.h" #endif #include "../prodml2_1/FluidSystem.h" #include "../prodml2_1/FluidCharacterization.h" #include "../prodml2_1/TimeSeriesData.h" #include <boost/uuid/random_generator.hpp> #include <boost/uuid/uuid_io.hpp> using namespace std; using namespace COMMON_NS; using namespace RESQML2_0_1_NS; using namespace WITSML2_0_NS; using namespace PRODML2_1_NS; namespace { class SameVersion { private: std::string version; public: explicit SameVersion(const std::string & version_) : version(version_) {} bool operator()(COMMON_NS::AbstractObject const * dataObj) const { return dataObj->getVersion() == version; } }; } // Create a fesapi partial wrapper based on a data type and its version #define CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(className)\ (dataType.compare(className::XML_TAG) == 0) {\ return createPartial<className>(uuid, title, version);\ } ///////////////////// /////// RESQML ////// ///////////////////// #define GET_RESQML_2_0_1_GSOAP_PROXY_FROM_GSOAP_CONTEXT(className)\ gsoap_resqml2_0_1::_resqml20__##className* read = gsoap_resqml2_0_1::soap_new_resqml20__obj_USCORE##className(gsoapContext);\ gsoap_resqml2_0_1::soap_read_resqml20__obj_USCORE##className(gsoapContext, read); #define GET_RESQML_2_0_1_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(className)\ GET_RESQML_2_0_1_GSOAP_PROXY_FROM_GSOAP_CONTEXT(className)\ wrapper = new RESQML2_0_1_NS::className(read); #define CHECK_AND_GET_RESQML_2_0_1_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(className)\ (resqmlContentType.compare(RESQML2_0_1_NS::className::XML_TAG) == 0)\ {\ GET_RESQML_2_0_1_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(className);\ } /////////////////////////// /////// RESQML 2.2 ////// /////////////////////////// #define GET_RESQML_2_2_GSOAP_PROXY_FROM_GSOAP_CONTEXT(className)\ gsoap_eml2_3::_resqml22__##className* read = gsoap_eml2_3::soap_new_resqml22__##className(gsoapContext);\ gsoap_eml2_3::soap_read_resqml22__##className(gsoapContext, read); #define GET_RESQML_2_2_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(className)\ GET_RESQML_2_2_GSOAP_PROXY_FROM_GSOAP_CONTEXT(className)\ wrapper = new RESQML2_2_NS::className(read); #define CHECK_AND_GET_RESQML_2_2_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(className)\ (resqmlContentType.compare(RESQML2_2_NS::className::XML_TAG) == 0)\ {\ GET_RESQML_2_2_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(className);\ } ///////////////////// ///// WITSML 2.0 //// ///////////////////// #define GET_WITSML_2_GSOAP_PROXY_FROM_GSOAP_CONTEXT(className, gsoapNameSpace)\ gsoapNameSpace::_witsml20__##className* read = gsoapNameSpace::soap_new_witsml20__##className(gsoapContext);\ gsoapNameSpace::soap_read_witsml20__##className(gsoapContext, read); #define GET_WITSML_2_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(classNamespace, className, gsoapNameSpace)\ GET_WITSML_2_GSOAP_PROXY_FROM_GSOAP_CONTEXT(className, gsoapNameSpace)\ wrapper = new classNamespace::className(read); #define CHECK_AND_GET_WITSML_2_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(classNamespace, className, gsoapNameSpace)\ (datatype.compare(classNamespace::className::XML_TAG) == 0)\ {\ GET_WITSML_2_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(classNamespace, className, gsoapNameSpace);\ } ///////////////////// ///// PRODML 2.1 //// ///////////////////// #define GET_PRODML_2_1_GSOAP_PROXY_FROM_GSOAP_CONTEXT(className, gsoapNameSpace)\ gsoapNameSpace::_prodml21__##className* read = gsoapNameSpace::soap_new_prodml21__##className(gsoapContext);\ gsoapNameSpace::soap_read_prodml21__##className(gsoapContext, read); #define GET_PRODML_2_1_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(classNamespace, className, gsoapNameSpace)\ GET_PRODML_2_1_GSOAP_PROXY_FROM_GSOAP_CONTEXT(className, gsoapNameSpace)\ wrapper = new classNamespace::className(read); #define CHECK_AND_GET_PRODML_2_1_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(classNamespace, className, gsoapNameSpace)\ (datatype.compare(classNamespace::className::XML_TAG) == 0)\ {\ GET_PRODML_2_1_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(classNamespace, className, gsoapNameSpace);\ } ///////////////////// ////// EML ////// ///////////////////// #define GET_EML_GSOAP_PROXY_FROM_GSOAP_CONTEXT(className, gsoapNameSpace, xmlNamespace)\ gsoapNameSpace::_##xmlNamespace ##__##className* read = gsoapNameSpace::soap_new_##xmlNamespace ##__##className(gsoapContext);\ gsoapNameSpace::soap_read_##xmlNamespace ##__##className(gsoapContext, read); #define GET_EML_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(classNamespace, className, gsoapNameSpace, xmlNamespace)\ GET_EML_GSOAP_PROXY_FROM_GSOAP_CONTEXT(className, gsoapNameSpace, xmlNamespace)\ wrapper = new classNamespace::className(read); #define CHECK_AND_GET_EML_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(classNamespace, className, gsoapNameSpace, xmlNamespace)\ (datatype.compare(classNamespace::className::XML_TAG) == 0)\ {\ GET_EML_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(classNamespace, className, gsoapNameSpace, xmlNamespace);\ } DataObjectRepository::DataObjectRepository() : dataObjects(), forwardRels(), backwardRels(), gsoapContext(soap_new2(SOAP_XML_STRICT | SOAP_C_UTFSTRING | SOAP_XML_IGNORENS, SOAP_XML_TREE | SOAP_XML_INDENT | SOAP_XML_CANONICAL | SOAP_C_UTFSTRING)), warnings(), propertyKindMapper(), defaultHdfProxy(nullptr), defaultCrs(nullptr), hdfProxyFactory(new COMMON_NS::HdfProxyFactory()), #if WITH_RESQML2_2 defaultEmlVersion(COMMON_NS::DataObjectRepository::EnergisticsStandard::EML2_3), #else defaultEmlVersion(COMMON_NS::DataObjectRepository::EnergisticsStandard::EML2_0), #endif defaultProdmlVersion(COMMON_NS::DataObjectRepository::EnergisticsStandard::PRODML2_1), #if WITH_RESQML2_2 defaultResqmlVersion(COMMON_NS::DataObjectRepository::EnergisticsStandard::RESQML2_2), #else defaultResqmlVersion(COMMON_NS::DataObjectRepository::EnergisticsStandard::RESQML2_0_1), #endif defaultWitsmlVersion(COMMON_NS::DataObjectRepository::EnergisticsStandard::WITSML2_0) {} DataObjectRepository::DataObjectRepository(const std::string & propertyKindMappingFilesDirectory) : dataObjects(), forwardRels(), backwardRels(), gsoapContext(soap_new2(SOAP_XML_STRICT | SOAP_C_UTFSTRING | SOAP_XML_IGNORENS, SOAP_XML_TREE | SOAP_XML_INDENT | SOAP_XML_CANONICAL | SOAP_C_UTFSTRING)), warnings(), propertyKindMapper(new PropertyKindMapper(this)), defaultHdfProxy(nullptr), defaultCrs(nullptr), hdfProxyFactory(new COMMON_NS::HdfProxyFactory()), #if WITH_RESQML2_2 defaultEmlVersion(COMMON_NS::DataObjectRepository::EnergisticsStandard::EML2_3), #else defaultEmlVersion(COMMON_NS::DataObjectRepository::EnergisticsStandard::EML2_0), #endif defaultProdmlVersion(COMMON_NS::DataObjectRepository::EnergisticsStandard::PRODML2_1), #if WITH_RESQML2_2 defaultResqmlVersion(COMMON_NS::DataObjectRepository::EnergisticsStandard::RESQML2_2), #else defaultResqmlVersion(COMMON_NS::DataObjectRepository::EnergisticsStandard::RESQML2_0_1), #endif defaultWitsmlVersion(COMMON_NS::DataObjectRepository::EnergisticsStandard::WITSML2_0) { const string error = propertyKindMapper->loadMappingFilesFromDirectory(propertyKindMappingFilesDirectory); if (!error.empty()) { propertyKindMapper.reset(); throw invalid_argument("Could not import property kind mappers : " + error); } } DataObjectRepository::~DataObjectRepository() { clear(); soap_destroy(gsoapContext); // remove deserialized C++ objects soap_end(gsoapContext); // remove deserialized data soap_done(gsoapContext); // finalize last use of the context soap_free(gsoapContext); // Free the context } void DataObjectRepository::clear() { for (std::unordered_map< std::string, std::vector< COMMON_NS::AbstractObject* > >::const_iterator it = dataObjects.begin(); it != dataObjects.end(); ++it) { for (size_t i = 0; i < it->second.size(); ++i) { delete it->second[i]; } } dataObjects.clear(); forwardRels.clear(); backwardRels.clear(); warnings.clear(); } void DataObjectRepository::addRelationship(COMMON_NS::AbstractObject * source, COMMON_NS::AbstractObject * target) { if (source == nullptr || target == nullptr) { throw invalid_argument("Cannot set a relationship with a null pointer"); } auto sourceIt = forwardRels.find(source); if (sourceIt == forwardRels.end()) { forwardRels[source].push_back(target); } else { if (std::find(sourceIt->second.begin(), sourceIt->second.end(), target) == sourceIt->second.end()) { sourceIt->second.push_back(target); } else { return; } } backwardRels[target].push_back(source); RESQML2_NS::AbstractLocal3dCrs const * crs = dynamic_cast<RESQML2_NS::AbstractLocal3dCrs const *>(target); if (crs != nullptr) { RESQML2_NS::AbstractRepresentation const * rep = dynamic_cast<RESQML2_NS::AbstractRepresentation const *>(source); if (rep != nullptr && !rep->isPartial()) { RESQML2_NS::AbstractFeatureInterpretation * interp = rep->getInterpretation(); if (interp != nullptr && !interp->isPartial()) { interp->initDomain(gsoap_resqml2_0_1::resqml20__Domain__mixed); } } } } void DataObjectRepository::deleteRelationship(COMMON_NS::AbstractObject * source, COMMON_NS::AbstractObject * target) { if (source == nullptr || target == nullptr) { throw invalid_argument("Cannot set a relationship with a null pointer"); } auto sourceIt = forwardRels.find(source); if (sourceIt != forwardRels.end()) { auto targetIt = std::find(sourceIt->second.begin(), sourceIt->second.end(), target); if (targetIt != sourceIt->second.end()) { // Erase in Forward Rels sourceIt->second.erase(targetIt); // Erase in Backward rels auto& sources = backwardRels[target]; sources.erase(std::find(sources.begin(), sources.end(), source)); } } } std::vector<COMMON_NS::AbstractObject*> DataObjectRepository::getTargetObjects(COMMON_NS::AbstractObject const * dataObj, size_t depth, const std::vector<std::string>& filteredDatatypes) const { std::vector< COMMON_NS::AbstractObject*> result; if (depth == 0) { result.push_back(getDataObjectByUuidAndVersion(dataObj->getUuid(), dataObj->getVersion())); } else { result = getTargetObjects(dataObj); if (depth > 1) { for (auto target : result) { const std::vector< COMMON_NS::AbstractObject*>& nextTargets = getTargetObjects(target, depth - 1); result.insert(result.end(), nextTargets.begin(), nextTargets.end()); } } } // Filter on datatype if (!filteredDatatypes.empty()) { result.erase( std::remove_if(result.begin(), result.end(), [&filteredDatatypes](COMMON_NS::AbstractObject* obj) { return std::find_if(filteredDatatypes.begin(), filteredDatatypes.end(), [obj](const std::string & filter) { return obj->getQualifiedType() == filter || (obj->getXmlNamespace() + ".*" == filter); }) == filteredDatatypes.end(); }), result.end() ); } return result; } std::vector<COMMON_NS::AbstractObject*> DataObjectRepository::getSourceObjects(COMMON_NS::AbstractObject const * dataObj, size_t depth, const std::vector<std::string>& filteredDatatypes) const { std::vector< COMMON_NS::AbstractObject*> result; if (depth == 0) { result.push_back(getDataObjectByUuidAndVersion(dataObj->getUuid(), dataObj->getVersion())); } else { result = getSourceObjects(dataObj); if (depth > 1) { for (auto source : result) { const std::vector< COMMON_NS::AbstractObject*>& nextSources = getSourceObjects(source, depth - 1); result.insert(result.end(), nextSources.begin(), nextSources.end()); } } } // Filter on datatype if (!filteredDatatypes.empty()) { result.erase( std::remove_if(result.begin(), result.end(), [&filteredDatatypes](COMMON_NS::AbstractObject* obj) { return std::find_if(filteredDatatypes.begin(), filteredDatatypes.end(), [obj](const std::string & filter) { return obj->getQualifiedType() == filter || (obj->getXmlNamespace() + ".*" == filter); }) == filteredDatatypes.end(); }), result.end() ); } return result; } namespace { void clearVectorOfMapEntry(std::pair< COMMON_NS::AbstractObject const * const, std::vector< COMMON_NS::AbstractObject * > > & entry) { entry.second.clear(); } } void DataObjectRepository::updateAllRelationships() { // Tansform the map values into a vector because we are going to potentially insert new elements in the map when looping. vector<COMMON_NS::AbstractObject*> nonPartialObjects; for (std::unordered_map< std::string, std::vector< COMMON_NS::AbstractObject* > >::const_iterator it = dataObjects.begin(); it != dataObjects.end(); ++it) { for (size_t i = 0; i < it->second.size(); ++i) { if (!it->second[i]->isPartial()) { nonPartialObjects.push_back(it->second[i]); } } } std::for_each(forwardRels.begin(), forwardRels.end(), clearVectorOfMapEntry); std::for_each(backwardRels.begin(), backwardRels.end(), clearVectorOfMapEntry); for (size_t nonPartialObjIndex = 0; nonPartialObjIndex < nonPartialObjects.size(); ++nonPartialObjIndex) { nonPartialObjects[nonPartialObjIndex]->loadTargetRelationships(); } } namespace { void replaceDataObjectInARelMap(COMMON_NS::AbstractObject* dataObjToReplace, COMMON_NS::AbstractObject * newDataObj, std::unordered_map< COMMON_NS::AbstractObject const *, std::vector< COMMON_NS::AbstractObject * > > & myMap) { for (auto& pair : myMap) { if (pair.first == dataObjToReplace) { myMap[newDataObj] = pair.second; } else { std::replace(pair.second.begin(), pair.second.end(), dataObjToReplace, newDataObj); } } myMap.erase(dataObjToReplace); } } void DataObjectRepository::replaceDataObjectInRels(COMMON_NS::AbstractObject* dataObjToReplace, COMMON_NS::AbstractObject* newDataObj) { replaceDataObjectInARelMap(dataObjToReplace, newDataObj, forwardRels); replaceDataObjectInARelMap(dataObjToReplace, newDataObj, backwardRels); } COMMON_NS::AbstractObject* DataObjectRepository::addOrReplaceDataObject(COMMON_NS::AbstractObject* proxy, bool replaceOnlyContent) { proxy->repository = this; if (getDataObjectByUuid(proxy->getUuid()) == nullptr) { dataObjects[proxy->getUuid()].push_back(proxy); if (forwardRels.count(proxy) == 0) { forwardRels[proxy] = std::vector<COMMON_NS::AbstractObject *>(); } if (backwardRels.count(proxy) == 0) { backwardRels[proxy] = std::vector<COMMON_NS::AbstractObject *>(); } auto now = std::chrono::system_clock::now(); journal.push_back(std::make_tuple(now, DataObjectReference(proxy), CREATED)); on_CreateDataObject(std::vector<std::pair<std::chrono::time_point<std::chrono::system_clock>, COMMON_NS::AbstractObject*>> { std::make_pair(now, proxy) }); } else { std::vector< COMMON_NS::AbstractObject* >& versions = dataObjects[proxy->getUuid()]; std::vector< COMMON_NS::AbstractObject* >::iterator same = std::find_if(versions.begin(), versions.end(), SameVersion(proxy->getVersion())); // Assume "no version" means current latest version in the repository if (same == versions.end()) { if (proxy->getVersion().empty()) { if (versions.size() == 1) { // replace the single present version which is consequently the current latest version in the repository proxy->setVersion(versions[0]->getVersion()); same = versions.begin(); } else { throw logic_error("Ordering of different versions is not implemented yet."); } } else { // replace repository unversionned version by the versioned version which are consequently both the current latest version in the repository same = std::find_if(versions.begin(), versions.end(), SameVersion("")); } } if (same == versions.end()) { // New version of an existing UUID dataObjects[proxy->getUuid()].push_back(proxy); auto now = std::chrono::system_clock::now(); journal.push_back(std::make_tuple(now, DataObjectReference(*same), CREATED)); on_CreateDataObject(std::vector<std::pair<std::chrono::time_point<std::chrono::system_clock>, COMMON_NS::AbstractObject*>> { std::make_pair(now, proxy) }); } else { // Replacement if (proxy->getContentType() != (*same)->getContentType()) { throw invalid_argument("Cannot replace " + proxy->getUuid() + " with a different content type : " + proxy->getContentType() + " vs " + (*same)->getContentType()); } if (!replaceOnlyContent || dynamic_cast<RESQML2_NS::AbstractIjkGridRepresentation*>(*same) != nullptr) { replaceDataObjectInRels(*same, proxy); if (!(*same)->isPartial()) { auto now = std::chrono::system_clock::now(); journal.push_back(std::make_tuple(now, DataObjectReference(proxy), UPDATED)); on_UpdateDataObject(std::vector<std::pair<std::chrono::time_point<std::chrono::system_clock>, COMMON_NS::AbstractObject*>> { std::make_pair(now, proxy) }); } delete *same; *same = proxy; } else { if (!(*same)->isPartial()) { auto now = std::chrono::system_clock::now(); journal.push_back(std::make_tuple(now, DataObjectReference(*same), UPDATED)); on_UpdateDataObject(std::vector<std::pair<std::chrono::time_point<std::chrono::system_clock>, COMMON_NS::AbstractObject*>> { std::make_pair(now, proxy) }); } const std::string xmlNs = proxy->getXmlNamespace(); if (xmlNs == "resqml20" || xmlNs == "eml20") { (*same)->setGsoapProxy(proxy->getEml20GsoapProxy()); } else if (xmlNs == "witsml20" || xmlNs == "eml21") { (*same)->setGsoapProxy(proxy->getEml21GsoapProxy()); } else if (xmlNs == "prodml21" || xmlNs == "eml22") { (*same)->setGsoapProxy(proxy->getEml22GsoapProxy()); } #if WITH_RESQML2_2 else if (xmlNs == "resqml22" || xmlNs == "eml23") { (*same)->setGsoapProxy(proxy->getEml23GsoapProxy()); } #endif delete proxy; return *same; } } } return proxy; } COMMON_NS::AbstractObject* DataObjectRepository::addOrReplaceGsoapProxy(const std::string & xml, const string & contentOrDataType) { istringstream iss(xml); setGsoapStream(&iss); string ns; size_t dataTypeCharPos; if (contentOrDataType.find("application/x-") == 0) { // content type // datatype dataTypeCharPos = contentOrDataType.find_last_of('_'); // The XML tag is after "obj_" if (dataTypeCharPos == string::npos) { dataTypeCharPos = contentOrDataType.find_last_of('='); } //namespace const size_t dashPos = contentOrDataType.find('-'); const size_t plusPos = contentOrDataType.find('+'); ns = contentOrDataType.substr(dashPos + 1, plusPos - dashPos - 1); const size_t equalPos = contentOrDataType.find('='); ns += contentOrDataType[equalPos + 1]; ns += contentOrDataType[equalPos + 3]; } else { // qualified data type const size_t dotPos = contentOrDataType.find('.'); // datatype dataTypeCharPos = contentOrDataType.find_last_of('_'); // The XML tag is after "obj_" if (dataTypeCharPos == string::npos) { dataTypeCharPos = dotPos; } //namespace ns = contentOrDataType.substr(0, dotPos); } const string datatype = contentOrDataType.substr(dataTypeCharPos + 1); COMMON_NS::AbstractObject* wrapper = nullptr; if (ns == "eml20" && datatype == "EpcExternalPartReference") { gsoap_resqml2_0_1::_eml20__EpcExternalPartReference* read = gsoap_resqml2_0_1::soap_new_eml20__obj_USCOREEpcExternalPartReference(gsoapContext); soap_read_eml20__obj_USCOREEpcExternalPartReference(gsoapContext, read); wrapper = hdfProxyFactory->make(read); } else if (ns == "eml23" && datatype == "EpcExternalPartReference") { gsoap_eml2_3::_eml23__EpcExternalPartReference* read = gsoap_eml2_3::soap_new_eml23__EpcExternalPartReference(gsoapContext); soap_read__eml23__EpcExternalPartReference(gsoapContext, read); wrapper = hdfProxyFactory->make(read); } else if (ns == "resqml20") { wrapper = getResqml2_0_1WrapperFromGsoapContext(datatype); } else if (ns == "witsml20") { wrapper = getWitsml2_0WrapperFromGsoapContext(datatype); } else if (ns == "eml21") { wrapper = getEml2_1WrapperFromGsoapContext(datatype); } else if (ns == "prodml21") { wrapper = getProdml2_1WrapperFromGsoapContext(datatype); } else if (ns == "resqml22") { wrapper = getResqml2_2WrapperFromGsoapContext(datatype); } /* else if (ns == "witsml21") { wrapper = getWitsml2_1WrapperFromGsoapContext(datatype); } */ else if (ns == "eml23") { wrapper = getEml2_3WrapperFromGsoapContext(datatype); } if (wrapper != nullptr) { if (gsoapContext->error != SOAP_OK) { ostringstream oss; soap_stream_fault(gsoapContext, oss); addWarning(oss.str()); delete wrapper; } else { return addOrReplaceDataObject(wrapper, true); } } addWarning("The content or data type " + contentOrDataType + " could not be wrapped by fesapi. The related instance will be ignored."); return nullptr; } std::unordered_map< std::string, std::vector<COMMON_NS::AbstractObject*> > DataObjectRepository::getDataObjectsGroupedByDataType() const { std::unordered_map< std::string, std::vector<COMMON_NS::AbstractObject*> > result; for (std::unordered_map< std::string, std::vector< COMMON_NS::AbstractObject* > >::const_iterator it = dataObjects.begin(); it != dataObjects.end(); ++it) { for (size_t i = 0; i < it->second.size(); ++i) { result[it->second[i]->getQualifiedType()].push_back(it->second[i]); } } return result; } std::unordered_map< std::string, std::vector<COMMON_NS::AbstractObject*> > DataObjectRepository::getDataObjectsGroupedByDataType(const std::string & filter) const { std::unordered_map< std::string, std::vector<COMMON_NS::AbstractObject*> > result; for (std::unordered_map< std::string, std::vector< COMMON_NS::AbstractObject* > >::const_iterator it = dataObjects.begin(); it != dataObjects.end(); ++it) { for (size_t i = 0; i < it->second.size(); ++i) { std::string datatype = it->second[i]->getQualifiedType(); if (datatype.find(filter) != std::string::npos) { result[datatype].push_back(it->second[i]); } } } return result; } std::vector<COMMON_NS::AbstractObject*> DataObjectRepository::getDataObjectsByContentType(const std::string & contentType) const { std::vector<COMMON_NS::AbstractObject*> result; for (std::unordered_map< std::string, std::vector< COMMON_NS::AbstractObject* > >::const_iterator it = dataObjects.begin(); it != dataObjects.end(); ++it) { for (size_t i = 0; i < it->second.size(); ++i) { if (it->second[i]->getContentType() == contentType) { result.push_back(it->second[i]); } } } return result; } COMMON_NS::AbstractObject* DataObjectRepository::getDataObjectByUuid(const string & uuid) const { std::unordered_map< std::string, std::vector< COMMON_NS::AbstractObject* > >::const_iterator it = dataObjects.find(uuid); return it == dataObjects.end() || it->second.empty() ? nullptr : it->second.back(); } COMMON_NS::AbstractObject* DataObjectRepository::getDataObjectByUuidAndVersion(const string & uuid, const std::string & version) const { std::unordered_map< std::string, std::vector< COMMON_NS::AbstractObject* > >::const_iterator it = dataObjects.find(uuid); if (it == dataObjects.end() || it->second.empty()) { return nullptr; } if (!version.empty()) { std::vector< COMMON_NS::AbstractObject* >::const_iterator vectIt = std::find_if(it->second.begin(), it->second.end(), SameVersion(version)); return vectIt == it->second.end() ? nullptr : *vectIt; } else { return it->second.empty() ? nullptr : it->second.back(); } } COMMON_NS::AbstractObject* DataObjectRepository::getDataObjectByUuidAndVersion(const std::array<uint8_t, 16> & uuid, const std::string & version) const { boost::uuids::uuid const* boostUuid = reinterpret_cast<boost::uuids::uuid const*>(uuid.data()); return getDataObjectByUuidAndVersion(boost::uuids::to_string(*boostUuid), version); } void DataObjectRepository::addWarning(const std::string & warning) { warnings.push_back(warning); } const std::vector<std::string> & DataObjectRepository::getWarnings() const { return warnings; } std::vector<std::string> DataObjectRepository::getUuids() const { std::vector<std::string> keys; keys.reserve(dataObjects.size()); for (auto kv : dataObjects) { keys.push_back(kv.first); } return keys; } COMMON_NS::AbstractObject* DataObjectRepository::createPartial(const std::string & uuid, const std::string & title, const std::string & contentType, const std::string & version) { size_t characterPos = contentType.find_last_of('_'); // The XML tag is after "obj_" if (characterPos == string::npos) { characterPos = contentType.find_last_of('='); } if (characterPos == string::npos) { throw logic_error("The content type " + contentType + " has an invalid syntax."); } const string dataType = contentType.substr(characterPos + 1); characterPos = contentType.find('-'); // The namespace starts after "application/x-" size_t plusPos = contentType.find('+'); // The namespace without version ends before "+xml" if (characterPos == string::npos || plusPos == string::npos || plusPos < characterPos) { throw logic_error("The content type " + contentType + " has an invalid syntax."); } string ns = contentType.substr(characterPos + 1, plusPos - characterPos - 1); characterPos = contentType.find('='); // The version starts after "version=" if (characterPos == string::npos || contentType.size() < characterPos + 3) { throw logic_error("The content type " + contentType + " has an invalid syntax."); } ns += contentType[characterPos + 1]; // ignore the dot in the version ns += contentType[characterPos + 3]; if (ns == "eml20") { if (dataType.compare(EML2_NS::EpcExternalPartReference::XML_TAG) == 0) { gsoap_resqml2_0_1::eml20__DataObjectReference* dor = createDor(uuid, title, version); dor->ContentType = contentType; COMMON_NS::AbstractObject* result = hdfProxyFactory->make(dor); addOrReplaceDataObject(result); return result; } } else if (ns == "eml21") { if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(EML2_1_NS::PropertyKind) } #if WITH_RESQML2_2 else if (ns == "eml23") { if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(EML2_3_NS::Activity) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(EML2_3_NS::ActivityTemplate) else if (dataType.compare(EML2_NS::EpcExternalPartReference::XML_TAG) == 0) { gsoap_eml2_3::eml23__DataObjectReference* dor = gsoap_eml2_3::soap_new_eml23__DataObjectReference(gsoapContext); dor->Uuid = uuid; dor->Title = title; dor->ContentType = contentType; if (!version.empty()) { dor->ObjectVersion = gsoap_eml2_3::soap_new_std__string(gsoapContext); dor->ObjectVersion->assign(version); } COMMON_NS::AbstractObject* result = hdfProxyFactory->make(dor); addOrReplaceDataObject(result); return result; } else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(EML2_3_NS::GraphicalInformationSet) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(EML2_3_NS::PropertyKind) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(EML2_3_NS::TimeSeries) } #endif else if (ns == "prodml21") { if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(PRODML2_1_NS::FluidSystem) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(PRODML2_1_NS::FluidCharacterization) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(PRODML2_1_NS::TimeSeriesData) } else if (ns == "resqml20") { if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_0_1_NS::Activity) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_0_1_NS::ActivityTemplate) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_0_1_NS::BlockedWellboreRepresentation) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_0_1_NS::BoundaryFeature) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_0_1_NS::BoundaryFeatureInterpretation) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_0_1_NS::CategoricalProperty) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_0_1_NS::CommentProperty) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_0_1_NS::ContinuousProperty) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_0_1_NS::DeviationSurveyRepresentation) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_0_1_NS::DiscreteProperty) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_0_1_NS::DoubleTableLookup) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_0_1_NS::EarthModelInterpretation) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_0_1_NS::FaultInterpretation) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_0_1_NS::FluidBoundaryFeature) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_0_1_NS::FrontierFeature) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_0_1_NS::GenericFeatureInterpretation) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_0_1_NS::GeneticBoundaryFeature) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_0_1_NS::GeobodyBoundaryInterpretation) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_0_1_NS::GeobodyFeature) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_0_1_NS::GeobodyInterpretation) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_0_1_NS::GeologicUnitFeature) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_0_1_NS::Grid2dRepresentation) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_0_1_NS::GridConnectionSetRepresentation) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_0_1_NS::HorizonInterpretation) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_0_1_NS::LocalDepth3dCrs) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_0_1_NS::LocalTime3dCrs) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_0_1_NS::MdDatum) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_0_1_NS::NonSealedSurfaceFrameworkRepresentation) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_0_1_NS::OrganizationFeature) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_0_1_NS::PlaneSetRepresentation) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_0_1_NS::PointSetRepresentation) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_0_1_NS::PointsProperty) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_0_1_NS::PolylineRepresentation) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_0_1_NS::PolylineSetRepresentation) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_0_1_NS::PropertyKind) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_0_1_NS::PropertySet) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_0_1_NS::RepresentationSetRepresentation) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_0_1_NS::RockFluidOrganizationInterpretation) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_0_1_NS::RockFluidUnitFeature) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_0_1_NS::RockFluidUnitInterpretation) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_0_1_NS::SealedSurfaceFrameworkRepresentation) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_0_1_NS::SealedVolumeFrameworkRepresentation) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_0_1_NS::SeismicLatticeFeature) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_0_1_NS::SeismicLineFeature) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_0_1_NS::SeismicLineSetFeature) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_0_1_NS::StratigraphicColumn) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_0_1_NS::StratigraphicColumnRankInterpretation) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_0_1_NS::StratigraphicOccurrenceInterpretation) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_0_1_NS::StratigraphicUnitFeature) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_0_1_NS::StratigraphicUnitInterpretation) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_0_1_NS::StringTableLookup) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_0_1_NS::StructuralOrganizationInterpretation) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_0_1_NS::SubRepresentation) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_0_1_NS::TectonicBoundaryFeature) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_0_1_NS::TimeSeries) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_0_1_NS::TriangulatedSetRepresentation) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_0_1_NS::UnstructuredGridRepresentation) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_0_1_NS::WellboreFeature) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_0_1_NS::WellboreFrameRepresentation) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_0_1_NS::WellboreInterpretation) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_0_1_NS::WellboreMarkerFrameRepresentation) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_0_1_NS::WellboreTrajectoryRepresentation) else if (dataType.compare(RESQML2_NS::AbstractIjkGridRepresentation::XML_TAG) == 0) { gsoap_resqml2_0_1::eml20__DataObjectReference* dor = gsoap_resqml2_0_1::soap_new_eml20__DataObjectReference(gsoapContext); dor->UUID = uuid; dor->Title = title; if (!version.empty()) { dor->VersionString = gsoap_resqml2_0_1::soap_new_std__string(gsoapContext); dor->VersionString->assign(version); } dor->ContentType = contentType; RESQML2_NS::AbstractIjkGridRepresentation* result = new RESQML2_NS::AbstractIjkGridRepresentation(dor); addOrReplaceDataObject(result); return result; } } #if WITH_RESQML2_2 else if (ns == "resqml22") { if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_2_NS::BlockedWellboreRepresentation) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_2_NS::BoundaryFeature) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_2_NS::BoundaryFeatureInterpretation) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_2_NS::CategoricalProperty) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_2_NS::CmpLineFeature) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_2_NS::CommentProperty) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_2_NS::ContinuousColorMap) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_2_NS::ContinuousProperty) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_2_NS::CulturalFeature) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_2_NS::DeviationSurveyRepresentation) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_2_NS::DiscreteColorMap) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_2_NS::DiscreteProperty) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_2_NS::DoubleTableLookup) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_2_NS::EarthModelInterpretation) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_2_NS::FaultInterpretation) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_2_NS::FluidBoundaryInterpretation) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_2_NS::GenericFeatureInterpretation) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_2_NS::GeobodyBoundaryInterpretation) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_2_NS::GeobodyInterpretation) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_2_NS::Grid2dRepresentation) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_2_NS::GridConnectionSetRepresentation) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_2_NS::HorizonInterpretation) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_2_NS::LocalDepth3dCrs) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_2_NS::LocalTime3dCrs) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_2_NS::MdDatum) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_2_NS::Model) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_2_NS::NonSealedSurfaceFrameworkRepresentation) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_2_NS::PlaneSetRepresentation) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_2_NS::PointSetRepresentation) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_2_NS::PointsProperty) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_2_NS::PolylineRepresentation) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_2_NS::PolylineSetRepresentation) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_2_NS::PropertySet) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_2_NS::RepresentationSetRepresentation) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_2_NS::RockFluidOrganizationInterpretation) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_2_NS::RockFluidUnitInterpretation) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_2_NS::RockVolumeFeature) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_2_NS::SealedSurfaceFrameworkRepresentation) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_2_NS::SealedVolumeFrameworkRepresentation) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_2_NS::SeismicLatticeFeature) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_2_NS::SeismicLineSetFeature) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_2_NS::SeismicWellboreFrameRepresentation) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_2_NS::ShotPointLineFeature) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_2_NS::StratigraphicColumn) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_2_NS::StratigraphicColumnRankInterpretation) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_2_NS::StratigraphicOccurrenceInterpretation) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_2_NS::StratigraphicUnitInterpretation) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_2_NS::StringTableLookup) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_2_NS::StructuralOrganizationInterpretation) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_2_NS::SubRepresentation) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_2_NS::TriangulatedSetRepresentation) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_2_NS::UnstructuredGridRepresentation) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_2_NS::WellboreFeature) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_2_NS::WellboreFrameRepresentation) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_2_NS::WellboreInterpretation) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_2_NS::WellboreMarkerFrameRepresentation) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(RESQML2_2_NS::WellboreTrajectoryRepresentation) else if (dataType.compare(RESQML2_NS::AbstractIjkGridRepresentation::XML_TAG) == 0) { gsoap_resqml2_0_1::eml20__DataObjectReference* dor = gsoap_resqml2_0_1::soap_new_eml20__DataObjectReference(gsoapContext); dor->UUID = uuid; dor->Title = title; if (!version.empty()) { dor->VersionString = gsoap_resqml2_0_1::soap_new_std__string(gsoapContext); dor->VersionString->assign(version); } dor->ContentType = contentType; RESQML2_NS::AbstractIjkGridRepresentation* result = new RESQML2_NS::AbstractIjkGridRepresentation(dor); addOrReplaceDataObject(result); return result; } } #endif else if (ns == "witsml20") { if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(WITSML2_0_NS::Channel) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(WITSML2_0_NS::ChannelSet) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(WITSML2_0_NS::Log) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(WITSML2_0_NS::Trajectory) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(WITSML2_0_NS::Well) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(WITSML2_0_NS::Wellbore) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(WITSML2_0_NS::WellboreCompletion) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(WITSML2_0_NS::WellboreGeometry) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(WITSML2_0_NS::WellboreMarker) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(WITSML2_0_NS::WellCompletion) } #if WITH_WITSML2_1 else if (ns == "witsml21") { if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(WITSML2_1_NS::ToolErrorModel) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(WITSML2_1_NS::ErrorTerm) else if CREATE_FESAPI_PARTIAL_WRAPPER_WITH_VERSION(WITSML2_1_NS::WeightingFunction) } #endif throw invalid_argument("The content type " + contentType + " of the partial object to create has not been recognized by fesapi."); } COMMON_NS::AbstractObject* DataObjectRepository::createPartial(const DataObjectReference& dor) { return createPartial(dor.getUuid(), dor.getTitle(), dor.getContentType(), dor.getVersion()); } //************************************ //************ HDF ******************* //************************************ EML2_NS::AbstractHdfProxy* DataObjectRepository::createHdfProxy(const std::string & guid, const std::string & title, const std::string & packageDirAbsolutePath, const std::string & filePath, DataObjectRepository::openingMode hdfPermissionAccess) { return hdfProxyFactory->make(this, guid, title, packageDirAbsolutePath, filePath, hdfPermissionAccess); } //************************************ //************ CRS ******************* //************************************ RESQML2_NS::LocalDepth3dCrs* DataObjectRepository::createLocalDepth3dCrs(const std::string & guid, const std::string & title, double originOrdinal1, double originOrdinal2, double originOrdinal3, double arealRotation, gsoap_resqml2_0_1::eml20__LengthUom projectedUom, unsigned long projectedEpsgCode, gsoap_resqml2_0_1::eml20__LengthUom verticalUom, unsigned int verticalEpsgCode, bool isUpOriented) { switch (defaultResqmlVersion) { case DataObjectRepository::EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::LocalDepth3dCrs(this, guid, title, originOrdinal1, originOrdinal2, originOrdinal3, arealRotation, projectedUom, projectedEpsgCode, verticalUom, verticalEpsgCode, isUpOriented); #ifdef WITH_RESQML2_2 case DataObjectRepository::EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::LocalDepth3dCrs(this, guid, title, originOrdinal1, originOrdinal2, originOrdinal3, arealRotation, projectedUom, projectedEpsgCode, verticalUom, verticalEpsgCode, isUpOriented); #endif default: throw std::invalid_argument("Unrecognized Energistics standard."); } } RESQML2_NS::LocalDepth3dCrs* DataObjectRepository::createLocalDepth3dCrs(const std::string & guid, const std::string & title, double originOrdinal1, double originOrdinal2, double originOrdinal3, double arealRotation, gsoap_resqml2_0_1::eml20__LengthUom projectedUom, const std::string & projectedUnknownReason, gsoap_resqml2_0_1::eml20__LengthUom verticalUom, const std::string & verticalUnknownReason, bool isUpOriented) { switch (defaultResqmlVersion) { case DataObjectRepository::EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::LocalDepth3dCrs(this, guid, title, originOrdinal1, originOrdinal2, originOrdinal3, arealRotation, projectedUom, projectedUnknownReason, verticalUom, verticalUnknownReason, isUpOriented); #ifdef WITH_RESQML2_2 case DataObjectRepository::EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::LocalDepth3dCrs(this, guid, title, originOrdinal1, originOrdinal2, originOrdinal3, arealRotation, projectedUom, projectedUnknownReason, verticalUom, verticalUnknownReason, isUpOriented); #endif default: throw std::invalid_argument("Unrecognized Energistics standard."); } } RESQML2_NS::LocalDepth3dCrs* DataObjectRepository::createLocalDepth3dCrs(const std::string & guid, const std::string & title, double originOrdinal1, double originOrdinal2, double originOrdinal3, double arealRotation, gsoap_resqml2_0_1::eml20__LengthUom projectedUom, unsigned long projectedEpsgCode, gsoap_resqml2_0_1::eml20__LengthUom verticalUom, const std::string & verticalUnknownReason, bool isUpOriented) { switch (defaultResqmlVersion) { case DataObjectRepository::EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::LocalDepth3dCrs(this, guid, title, originOrdinal1, originOrdinal2, originOrdinal3, arealRotation, projectedUom, projectedEpsgCode, verticalUom, verticalUnknownReason, isUpOriented); #ifdef WITH_RESQML2_2 case DataObjectRepository::EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::LocalDepth3dCrs(this, guid, title, originOrdinal1, originOrdinal2, originOrdinal3, arealRotation, projectedUom, projectedEpsgCode, verticalUom, verticalUnknownReason, isUpOriented); #endif default: throw std::invalid_argument("Unrecognized Energistics standard."); } } RESQML2_NS::LocalDepth3dCrs* DataObjectRepository::createLocalDepth3dCrs(const std::string & guid, const std::string & title, double originOrdinal1, double originOrdinal2, double originOrdinal3, double arealRotation, gsoap_resqml2_0_1::eml20__LengthUom projectedUom, const std::string & projectedUnknownReason, gsoap_resqml2_0_1::eml20__LengthUom verticalUom, unsigned int verticalEpsgCode, bool isUpOriented) { switch (defaultResqmlVersion) { case DataObjectRepository::EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::LocalDepth3dCrs(this, guid, title, originOrdinal1, originOrdinal2, originOrdinal3, arealRotation, projectedUom, projectedUnknownReason, verticalUom, verticalEpsgCode, isUpOriented); #ifdef WITH_RESQML2_2 case DataObjectRepository::EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::LocalDepth3dCrs(this, guid, title, originOrdinal1, originOrdinal2, originOrdinal3, arealRotation, projectedUom, projectedUnknownReason, verticalUom, verticalEpsgCode, isUpOriented); #endif default: throw std::invalid_argument("Unrecognized Energistics standard."); } } RESQML2_NS::LocalTime3dCrs* DataObjectRepository::createLocalTime3dCrs(const std::string & guid, const std::string & title, double originOrdinal1, double originOrdinal2, double originOrdinal3, double arealRotation, gsoap_resqml2_0_1::eml20__LengthUom projectedUom, unsigned long projectedEpsgCode, gsoap_resqml2_0_1::eml20__TimeUom timeUom, gsoap_resqml2_0_1::eml20__LengthUom verticalUom, unsigned int verticalEpsgCode, bool isUpOriented) { switch (defaultResqmlVersion) { case DataObjectRepository::EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::LocalTime3dCrs(this, guid, title, originOrdinal1, originOrdinal2, originOrdinal3, arealRotation, projectedUom, projectedEpsgCode, timeUom, verticalUom, verticalEpsgCode, isUpOriented); #ifdef WITH_RESQML2_2 case DataObjectRepository::EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::LocalTime3dCrs(this, guid, title, originOrdinal1, originOrdinal2, originOrdinal3, arealRotation, projectedUom, projectedEpsgCode, timeUom, verticalUom, verticalEpsgCode, isUpOriented); #endif default: throw std::invalid_argument("Unrecognized Energistics standard."); } } RESQML2_NS::LocalTime3dCrs* DataObjectRepository::createLocalTime3dCrs(const std::string & guid, const std::string & title, double originOrdinal1, double originOrdinal2, double originOrdinal3, double arealRotation, gsoap_resqml2_0_1::eml20__LengthUom projectedUom, const std::string & projectedUnknownReason, gsoap_resqml2_0_1::eml20__TimeUom timeUom, gsoap_resqml2_0_1::eml20__LengthUom verticalUom, const std::string & verticalUnknownReason, bool isUpOriented) { switch (defaultResqmlVersion) { case DataObjectRepository::EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::LocalTime3dCrs(this, guid, title, originOrdinal1, originOrdinal2, originOrdinal3, arealRotation, projectedUom, projectedUnknownReason, timeUom, verticalUom, verticalUnknownReason, isUpOriented); #ifdef WITH_RESQML2_2 case DataObjectRepository::EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::LocalTime3dCrs(this, guid, title, originOrdinal1, originOrdinal2, originOrdinal3, arealRotation, projectedUom, projectedUnknownReason, timeUom, verticalUom, verticalUnknownReason, isUpOriented); #endif default: throw std::invalid_argument("Unrecognized Energistics standard."); } } RESQML2_NS::LocalTime3dCrs* DataObjectRepository::createLocalTime3dCrs(const std::string & guid, const std::string & title, double originOrdinal1, double originOrdinal2, double originOrdinal3, double arealRotation, gsoap_resqml2_0_1::eml20__LengthUom projectedUom, unsigned long projectedEpsgCode, gsoap_resqml2_0_1::eml20__TimeUom timeUom, gsoap_resqml2_0_1::eml20__LengthUom verticalUom, const std::string & verticalUnknownReason, bool isUpOriented) { switch (defaultResqmlVersion) { case DataObjectRepository::EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::LocalTime3dCrs(this, guid, title, originOrdinal1, originOrdinal2, originOrdinal3, arealRotation, projectedUom, projectedEpsgCode, timeUom, verticalUom, verticalUnknownReason, isUpOriented); #ifdef WITH_RESQML2_2 case DataObjectRepository::EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::LocalTime3dCrs(this, guid, title, originOrdinal1, originOrdinal2, originOrdinal3, arealRotation, projectedUom, projectedEpsgCode, timeUom, verticalUom, verticalUnknownReason, isUpOriented); #endif default: throw std::invalid_argument("Unrecognized Energistics standard."); } } RESQML2_NS::LocalTime3dCrs* DataObjectRepository::createLocalTime3dCrs(const std::string & guid, const std::string & title, double originOrdinal1, double originOrdinal2, double originOrdinal3, double arealRotation, gsoap_resqml2_0_1::eml20__LengthUom projectedUom, const std::string & projectedUnknownReason, gsoap_resqml2_0_1::eml20__TimeUom timeUom, gsoap_resqml2_0_1::eml20__LengthUom verticalUom, unsigned int verticalEpsgCode, bool isUpOriented) { switch (defaultResqmlVersion) { case DataObjectRepository::EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::LocalTime3dCrs(this, guid, title, originOrdinal1, originOrdinal2, originOrdinal3, arealRotation, projectedUom, projectedUnknownReason, timeUom, verticalUom, verticalEpsgCode, isUpOriented); #ifdef WITH_RESQML2_2 case DataObjectRepository::EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::LocalTime3dCrs(this, guid, title, originOrdinal1, originOrdinal2, originOrdinal3, arealRotation, projectedUom, projectedUnknownReason, timeUom, verticalUom, verticalEpsgCode, isUpOriented); #endif default: throw std::invalid_argument("Unrecognized Energistics standard."); } } RESQML2_NS::MdDatum* DataObjectRepository::createMdDatum(const std::string & guid, const std::string & title, RESQML2_NS::AbstractLocal3dCrs * locCrs, gsoap_eml2_3::eml23__WellboreDatumReference originKind, double referenceLocationOrdinal1, double referenceLocationOrdinal2, double referenceLocationOrdinal3) { switch (defaultResqmlVersion) { case DataObjectRepository::EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::MdDatum(this, guid, title, locCrs, originKind, referenceLocationOrdinal1, referenceLocationOrdinal2, referenceLocationOrdinal3); #ifdef WITH_RESQML2_2 case DataObjectRepository::EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::MdDatum(this, guid, title, locCrs, originKind, referenceLocationOrdinal1, referenceLocationOrdinal2, referenceLocationOrdinal3); #endif default: throw std::invalid_argument("Unrecognized Energistics standard."); } } //************************************ //************ FEATURE *************** //************************************ RESQML2_NS::BoundaryFeature* DataObjectRepository::createBoundaryFeature(const std::string & guid, const std::string & title) { switch (defaultResqmlVersion) { case DataObjectRepository::EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::BoundaryFeature(this, guid, title); #ifdef WITH_RESQML2_2 case DataObjectRepository::EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::BoundaryFeature(this, guid, title); #endif default: throw std::invalid_argument("Unrecognized Energistics standard."); } } RESQML2_NS::BoundaryFeature* DataObjectRepository::createHorizon(const std::string & guid, const std::string & title) { switch (defaultResqmlVersion) { case DataObjectRepository::EnergisticsStandard::RESQML2_0_1: return new Horizon(this, guid, title); #ifdef WITH_RESQML2_2 case DataObjectRepository::EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::BoundaryFeature(this, guid, title); #endif default: throw std::invalid_argument("Unrecognized Energistics standard."); } } RESQML2_NS::BoundaryFeature* DataObjectRepository::createGeobodyBoundaryFeature(const std::string & guid, const std::string & title) { switch (defaultResqmlVersion) { case DataObjectRepository::EnergisticsStandard::RESQML2_0_1: return new GeneticBoundaryFeature(this, guid, title, false); #ifdef WITH_RESQML2_2 case DataObjectRepository::EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::BoundaryFeature(this, guid, title); #endif default: throw std::invalid_argument("Unrecognized Energistics standard."); } } RESQML2_NS::RockVolumeFeature* DataObjectRepository::createGeobodyFeature(const std::string & guid, const std::string & title) { switch (defaultResqmlVersion) { case DataObjectRepository::EnergisticsStandard::RESQML2_0_1: return new GeobodyFeature(this, guid, title); #ifdef WITH_RESQML2_2 case DataObjectRepository::EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::RockVolumeFeature(this, guid, title); #endif default: throw std::invalid_argument("Unrecognized Energistics standard."); } } RESQML2_NS::BoundaryFeature* DataObjectRepository::createFault(const std::string & guid, const std::string & title) { switch (defaultResqmlVersion) { case DataObjectRepository::EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::TectonicBoundaryFeature(this, guid, title, false); #ifdef WITH_RESQML2_2 case DataObjectRepository::EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::BoundaryFeature(this, guid, title); #endif default: throw std::invalid_argument("Unrecognized Energistics standard."); } } RESQML2_NS::BoundaryFeature* DataObjectRepository::createFracture(const std::string & guid, const std::string & title) { switch (defaultResqmlVersion) { case DataObjectRepository::EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::TectonicBoundaryFeature(this, guid, title, true); #ifdef WITH_RESQML2_2 case DataObjectRepository::EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::BoundaryFeature(this, guid, title); #endif default: throw std::invalid_argument("Unrecognized Energistics standard."); } } RESQML2_NS::WellboreFeature* DataObjectRepository::createWellboreFeature(const std::string & guid, const std::string & title) { switch (defaultResqmlVersion) { case DataObjectRepository::EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::WellboreFeature(this, guid, title); #ifdef WITH_RESQML2_2 case DataObjectRepository::EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::WellboreFeature(this, guid, title); #endif default: throw std::invalid_argument("Unrecognized Energistics standard."); } } RESQML2_NS::SeismicLatticeFeature* DataObjectRepository::createSeismicLattice(const std::string & guid, const std::string & title, int inlineIncrement, int crosslineIncrement, unsigned int originInline, unsigned int originCrossline, unsigned int inlineCount, unsigned int crosslineCount) { switch (defaultResqmlVersion) { case DataObjectRepository::EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::SeismicLatticeFeature(this, guid, title, inlineIncrement, crosslineIncrement, originInline, originCrossline, inlineCount, crosslineCount); #ifdef WITH_RESQML2_2 case DataObjectRepository::EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::SeismicLatticeFeature(this, guid, title, inlineIncrement, crosslineIncrement, originInline, originCrossline, inlineCount, crosslineCount); #endif default: throw std::invalid_argument("Unrecognized Energistics standard."); } } RESQML2_0_1_NS::SeismicLineFeature* DataObjectRepository::createSeismicLine(const std::string & guid, const std::string & title, int traceIndexIncrement, unsigned int firstTraceIndex, unsigned int traceCount) { return new RESQML2_0_1_NS::SeismicLineFeature(this, guid, title, traceIndexIncrement, firstTraceIndex, traceCount); } #ifdef WITH_RESQML2_2 RESQML2_NS::CmpLineFeature* DataObjectRepository::createCmpLine(const std::string & guid, const std::string & title, int nearestShotPointIndicesIncrement, int firstNearestShotPointIndex, unsigned int nearestShotPointCount) { return new RESQML2_2_NS::CmpLineFeature(this, guid, title, nearestShotPointIndicesIncrement, firstNearestShotPointIndex, nearestShotPointCount); #else RESQML2_NS::CmpLineFeature* DataObjectRepository::createCmpLine(const std::string&, const std::string&, int, int, unsigned int) { throw std::logic_error("RESQML2.2 support has not been built in this library."); #endif } #ifdef WITH_RESQML2_2 RESQML2_NS::ShotPointLineFeature* DataObjectRepository::createShotPointLine(const std::string & guid, const std::string & title) { return new RESQML2_2_NS::ShotPointLineFeature(this, guid, title); #else RESQML2_NS::ShotPointLineFeature* DataObjectRepository::createShotPointLine(const std::string&, const std::string&) { throw std::logic_error("RESQML2.2 support has not been built in this library."); #endif } RESQML2_NS::SeismicLineSetFeature* DataObjectRepository::createSeismicLineSet(const std::string & guid, const std::string & title) { switch (defaultResqmlVersion) { case DataObjectRepository::EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::SeismicLineSetFeature(this, guid, title); #ifdef WITH_RESQML2_2 case DataObjectRepository::EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::SeismicLineSetFeature(this, guid, title); #endif default: throw std::invalid_argument("Unrecognized Energistics standard."); } } RESQML2_NS::CulturalFeature* DataObjectRepository::createCultural(const std::string & guid, const std::string & title, #ifdef WITH_RESQML2_2 gsoap_eml2_3::resqml22__CulturalFeatureKind kind) #else gsoap_eml2_3::resqml22__CulturalFeatureKind) #endif { switch (defaultResqmlVersion) { case DataObjectRepository::EnergisticsStandard::RESQML2_0_1: return new FrontierFeature(this, guid, title); #ifdef WITH_RESQML2_2 case DataObjectRepository::EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::CulturalFeature(this, guid, title, kind); #endif default: throw std::invalid_argument("Unrecognized Energistics standard."); } } RESQML2_NS::RockVolumeFeature* DataObjectRepository::createStratigraphicUnitFeature(const std::string & guid, const std::string & title) { switch (defaultResqmlVersion) { case DataObjectRepository::EnergisticsStandard::RESQML2_0_1: return new StratigraphicUnitFeature(this, guid, title); #ifdef WITH_RESQML2_2 case DataObjectRepository::EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::RockVolumeFeature(this, guid, title); #endif default: throw std::invalid_argument("Unrecognized Energistics standard."); } } #ifdef WITH_RESQML2_2 RESQML2_NS::RockVolumeFeature* DataObjectRepository::createRockVolumeFeature(const std::string & guid, const std::string & title) { return new RESQML2_2_NS::RockVolumeFeature(this, guid, title); #else RESQML2_NS::RockVolumeFeature* DataObjectRepository::createRockVolumeFeature(const std::string&, const std::string&) { throw std::logic_error("RESQML2.2 support has not been built in this library."); #endif } #ifdef WITH_RESQML2_2 RESQML2_NS::Model* DataObjectRepository::createModel(const std::string & guid, const std::string & title) { return new RESQML2_2_NS::Model(this, guid, title); #else RESQML2_NS::Model* DataObjectRepository::createModel(const std::string&, const std::string&) { throw std::logic_error("RESQML2.2 support has not been built in this library."); #endif } RESQML2_0_1_NS::RockFluidUnitFeature* DataObjectRepository::createRockFluidUnit(const std::string & guid, const std::string & title, gsoap_resqml2_0_1::resqml20__Phase phase, RESQML2_0_1_NS::FluidBoundaryFeature* fluidBoundaryTop, RESQML2_0_1_NS::FluidBoundaryFeature* fluidBoundaryBottom) { return new RockFluidUnitFeature(this, guid, title, phase, fluidBoundaryTop, fluidBoundaryBottom); } RESQML2_NS::Model* DataObjectRepository::createStructuralModel(const std::string & guid, const std::string & title) { switch (defaultResqmlVersion) { case DataObjectRepository::EnergisticsStandard::RESQML2_0_1: return new OrganizationFeature(this, guid, title, gsoap_resqml2_0_1::resqml20__OrganizationKind__structural); #ifdef WITH_RESQML2_2 case DataObjectRepository::EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::Model(this, guid, title); #endif default: throw std::invalid_argument("Unrecognized Energistics standard."); } } RESQML2_NS::Model* DataObjectRepository::createStratigraphicModel(const std::string & guid, const std::string & title) { switch (defaultResqmlVersion) { case DataObjectRepository::EnergisticsStandard::RESQML2_0_1: return new OrganizationFeature(this, guid, title, gsoap_resqml2_0_1::resqml20__OrganizationKind__stratigraphic); #ifdef WITH_RESQML2_2 case DataObjectRepository::EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::Model(this, guid, title); #endif default: throw std::invalid_argument("Unrecognized Energistics standard."); } } RESQML2_NS::Model* DataObjectRepository::createRockFluidModel(const std::string & guid, const std::string & title) { switch (defaultResqmlVersion) { case DataObjectRepository::EnergisticsStandard::RESQML2_0_1: return new OrganizationFeature(this, guid, title, gsoap_resqml2_0_1::resqml20__OrganizationKind__fluid); #ifdef WITH_RESQML2_2 case DataObjectRepository::EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::Model(this, guid, title); #endif default: throw std::invalid_argument("Unrecognized Energistics standard."); } } RESQML2_NS::Model* DataObjectRepository::createEarthModel(const std::string & guid, const std::string & title) { switch (defaultResqmlVersion) { case DataObjectRepository::EnergisticsStandard::RESQML2_0_1: return new OrganizationFeature(this, guid, title, gsoap_resqml2_0_1::resqml20__OrganizationKind__earth_x0020model); #ifdef WITH_RESQML2_2 case DataObjectRepository::EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::Model(this, guid, title); #endif default: throw std::invalid_argument("Unrecognized Energistics standard."); } } FluidBoundaryFeature* DataObjectRepository::createFluidBoundaryFeature(const std::string & guid, const std::string & title, gsoap_resqml2_0_1::resqml20__FluidContact fluidContact) { return new FluidBoundaryFeature(this, guid, title, fluidContact); } //************************************ //************ INTERPRETATION ******** //************************************ RESQML2_NS::GenericFeatureInterpretation* DataObjectRepository::createGenericFeatureInterpretation(RESQML2_NS::AbstractFeature * feature, const std::string & guid, const std::string & title) { switch (defaultResqmlVersion) { case DataObjectRepository::EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::GenericFeatureInterpretation(feature, guid, title); #ifdef WITH_RESQML2_2 case DataObjectRepository::EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::GenericFeatureInterpretation(feature, guid, title); #endif default: throw std::invalid_argument("Unrecognized Energistics standard."); } } RESQML2_NS::BoundaryFeatureInterpretation* DataObjectRepository::createBoundaryFeatureInterpretation(RESQML2_NS::BoundaryFeature * feature, const std::string & guid, const std::string & title) { switch (defaultResqmlVersion) { case DataObjectRepository::EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::BoundaryFeatureInterpretation(feature, guid, title); #ifdef WITH_RESQML2_2 case DataObjectRepository::EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::BoundaryFeatureInterpretation(feature, guid, title); #endif default: throw std::invalid_argument("Unrecognized Energistics standard."); } } RESQML2_NS::HorizonInterpretation* DataObjectRepository::createHorizonInterpretation(RESQML2_NS::BoundaryFeature * horizon, const std::string & guid, const std::string & title) { switch (defaultResqmlVersion) { case DataObjectRepository::EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::HorizonInterpretation(horizon, guid, title); #ifdef WITH_RESQML2_2 case DataObjectRepository::EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::HorizonInterpretation(horizon, guid, title); #endif default: throw std::invalid_argument("Unrecognized Energistics standard."); } } RESQML2_NS::GeobodyBoundaryInterpretation* DataObjectRepository::createGeobodyBoundaryInterpretation(RESQML2_NS::BoundaryFeature * geobodyBoundary, const std::string & guid, const std::string & title) { switch (defaultResqmlVersion) { case DataObjectRepository::EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::GeobodyBoundaryInterpretation(geobodyBoundary, guid, title); #ifdef WITH_RESQML2_2 case DataObjectRepository::EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::GeobodyBoundaryInterpretation(geobodyBoundary, guid, title); #endif default: throw std::invalid_argument("Unrecognized Energistics standard."); } } RESQML2_NS::FaultInterpretation* DataObjectRepository::createFaultInterpretation(RESQML2_NS::BoundaryFeature * fault, const std::string & guid, const std::string & title) { switch (defaultResqmlVersion) { case DataObjectRepository::EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::FaultInterpretation(fault, guid, title); #ifdef WITH_RESQML2_2 case DataObjectRepository::EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::FaultInterpretation(fault, guid, title); #endif default: throw std::invalid_argument("Unrecognized Energistics standard."); } } #ifdef WITH_RESQML2_2 RESQML2_NS::FluidBoundaryInterpretation* DataObjectRepository::createFluidBoundaryInterpretation(RESQML2_NS::BoundaryFeature * boundary, const std::string & guid, const std::string & title, gsoap_eml2_3::resqml22__FluidContact fluidContact) { return new RESQML2_2_NS::FluidBoundaryInterpretation(boundary, guid, title, fluidContact); #else RESQML2_NS::FluidBoundaryInterpretation* DataObjectRepository::createFluidBoundaryInterpretation(RESQML2_NS::BoundaryFeature * boundary, const std::string & guid, const std::string & title, gsoap_eml2_3::resqml22__FluidContact fluidContact) { throw std::logic_error("RESQML2.2 support has not been built in this library."); #endif } RESQML2_NS::WellboreInterpretation* DataObjectRepository::createWellboreInterpretation(RESQML2_NS::WellboreFeature * wellbore, const std::string & guid, const std::string & title, bool isDrilled) { switch (defaultResqmlVersion) { case DataObjectRepository::EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::WellboreInterpretation(wellbore, guid, title, isDrilled); #ifdef WITH_RESQML2_2 case DataObjectRepository::EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::WellboreInterpretation(wellbore, guid, title, isDrilled); #endif default: throw std::invalid_argument("Unrecognized Energistics standard."); } } RESQML2_NS::EarthModelInterpretation* DataObjectRepository::createEarthModelInterpretation(RESQML2_NS::Model * orgFeat, const std::string & guid, const std::string & title) { switch (defaultResqmlVersion) { case DataObjectRepository::EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::EarthModelInterpretation(orgFeat, guid, title); #ifdef WITH_RESQML2_2 case DataObjectRepository::EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::EarthModelInterpretation(orgFeat, guid, title); #endif default: throw std::invalid_argument("Unrecognized Energistics standard."); } } RESQML2_NS::StructuralOrganizationInterpretation* DataObjectRepository::createStructuralOrganizationInterpretationInAge(RESQML2_NS::Model * orgFeat, const std::string & guid, const std::string & title) { switch (defaultResqmlVersion) { case DataObjectRepository::EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::StructuralOrganizationInterpretation(orgFeat, guid, title, gsoap_resqml2_0_1::resqml20__OrderingCriteria__age); #ifdef WITH_RESQML2_2 case DataObjectRepository::EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::StructuralOrganizationInterpretation(orgFeat, guid, title, gsoap_resqml2_0_1::resqml20__OrderingCriteria__age); #endif default: throw std::invalid_argument("Unrecognized Energistics standard."); } } RESQML2_NS::StructuralOrganizationInterpretation* DataObjectRepository::createStructuralOrganizationInterpretationInApparentDepth(RESQML2_NS::Model * orgFeat, const std::string & guid, const std::string & title) { switch (defaultResqmlVersion) { case DataObjectRepository::EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::StructuralOrganizationInterpretation(orgFeat, guid, title, gsoap_resqml2_0_1::resqml20__OrderingCriteria__apparent_x0020depth); #ifdef WITH_RESQML2_2 case DataObjectRepository::EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::StructuralOrganizationInterpretation(orgFeat, guid, title, gsoap_resqml2_0_1::resqml20__OrderingCriteria__apparent_x0020depth); #endif default: throw std::invalid_argument("Unrecognized Energistics standard."); } } RESQML2_NS::StructuralOrganizationInterpretation* DataObjectRepository::createStructuralOrganizationInterpretationInMeasuredDepth(RESQML2_NS::Model * orgFeat, const std::string & guid, const std::string & title) { switch (defaultResqmlVersion) { case DataObjectRepository::EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::StructuralOrganizationInterpretation(orgFeat, guid, title, gsoap_resqml2_0_1::resqml20__OrderingCriteria__measured_x0020depth); #ifdef WITH_RESQML2_2 case DataObjectRepository::EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::StructuralOrganizationInterpretation(orgFeat, guid, title, gsoap_resqml2_0_1::resqml20__OrderingCriteria__measured_x0020depth); #endif default: throw std::invalid_argument("Unrecognized Energistics standard."); } } RESQML2_NS::RockFluidOrganizationInterpretation* DataObjectRepository::createRockFluidOrganizationInterpretation(RESQML2_NS::Model * orgFeat, const std::string & guid, const std::string & title) { switch (defaultResqmlVersion) { case DataObjectRepository::EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::RockFluidOrganizationInterpretation(orgFeat, guid, title); #ifdef WITH_RESQML2_2 case DataObjectRepository::EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::RockFluidOrganizationInterpretation(orgFeat, guid, title); #endif default: throw std::invalid_argument("Unrecognized Energistics standard."); } } RESQML2_NS::RockFluidUnitInterpretation* DataObjectRepository::createRockFluidUnitInterpretation(RESQML2_NS::RockVolumeFeature * rockFluidUnitFeature, const std::string & guid, const std::string & title) { switch (defaultResqmlVersion) { case DataObjectRepository::EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::RockFluidUnitInterpretation(rockFluidUnitFeature, guid, title); #ifdef WITH_RESQML2_2 case DataObjectRepository::EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::RockFluidUnitInterpretation(rockFluidUnitFeature, guid, title); #endif default: throw std::invalid_argument("Unrecognized Energistics standard."); } } RESQML2_NS::StratigraphicColumn* DataObjectRepository::createStratigraphicColumn(const std::string & guid, const std::string & title) { switch (defaultResqmlVersion) { case DataObjectRepository::EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::StratigraphicColumn(this, guid, title); #ifdef WITH_RESQML2_2 case DataObjectRepository::EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::StratigraphicColumn(this, guid, title); #endif default: throw std::invalid_argument("Unrecognized Energistics standard."); } } RESQML2_NS::GeobodyInterpretation* DataObjectRepository::createGeobodyInterpretation(RESQML2_NS::RockVolumeFeature * geobody, const std::string & guid, const std::string & title) { switch (defaultResqmlVersion) { case DataObjectRepository::EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::GeobodyInterpretation(geobody, guid, title); #ifdef WITH_RESQML2_2 case DataObjectRepository::EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::GeobodyInterpretation(geobody, guid, title); #endif default: throw std::invalid_argument("Unrecognized Energistics standard."); } } RESQML2_NS::StratigraphicUnitInterpretation* DataObjectRepository::createStratigraphicUnitInterpretation(RESQML2_NS::RockVolumeFeature* stratiUnitFeature, const std::string & guid, const std::string & title) { switch (defaultResqmlVersion) { case DataObjectRepository::EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::StratigraphicUnitInterpretation(stratiUnitFeature, guid, title); #ifdef WITH_RESQML2_2 case DataObjectRepository::EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::StratigraphicUnitInterpretation(stratiUnitFeature, guid, title); #endif default: throw std::invalid_argument("Unrecognized Energistics standard."); } } RESQML2_NS::StratigraphicColumnRankInterpretation* DataObjectRepository::createStratigraphicColumnRankInterpretationInAge(RESQML2_NS::Model * orgFeat, const std::string & guid, const std::string & title, const unsigned long & rank) { switch (defaultResqmlVersion) { case DataObjectRepository::EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::StratigraphicColumnRankInterpretation(orgFeat, guid, title, rank, gsoap_resqml2_0_1::resqml20__OrderingCriteria__age); #ifdef WITH_RESQML2_2 case DataObjectRepository::EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::StratigraphicColumnRankInterpretation(orgFeat, guid, title, rank, gsoap_resqml2_0_1::resqml20__OrderingCriteria__age); #endif default: throw std::invalid_argument("Unrecognized Energistics standard."); } } RESQML2_NS::StratigraphicColumnRankInterpretation* DataObjectRepository::createStratigraphicColumnRankInterpretationInApparentDepth(RESQML2_NS::Model * orgFeat, const std::string & guid, const std::string & title, const unsigned long & rank) { switch (defaultResqmlVersion) { case DataObjectRepository::EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::StratigraphicColumnRankInterpretation(orgFeat, guid, title, rank, gsoap_resqml2_0_1::resqml20__OrderingCriteria__apparent_x0020depth); #ifdef WITH_RESQML2_2 case DataObjectRepository::EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::StratigraphicColumnRankInterpretation(orgFeat, guid, title, rank, gsoap_resqml2_0_1::resqml20__OrderingCriteria__apparent_x0020depth); #endif default: throw std::invalid_argument("Unrecognized Energistics standard."); } } RESQML2_NS::StratigraphicOccurrenceInterpretation* DataObjectRepository::createStratigraphicOccurrenceInterpretationInAge(RESQML2_NS::Model * orgFeat, const std::string & guid, const std::string & title) { switch (defaultResqmlVersion) { case DataObjectRepository::EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::StratigraphicOccurrenceInterpretation(orgFeat, guid, title, gsoap_resqml2_0_1::resqml20__OrderingCriteria__age); #ifdef WITH_RESQML2_2 case DataObjectRepository::EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::StratigraphicOccurrenceInterpretation(orgFeat, guid, title, gsoap_resqml2_0_1::resqml20__OrderingCriteria__age); #endif default: throw std::invalid_argument("Unrecognized Energistics standard."); } } RESQML2_NS::StratigraphicOccurrenceInterpretation* DataObjectRepository::createStratigraphicOccurrenceInterpretationInApparentDepth(RESQML2_NS::Model * orgFeat, const std::string & guid, const std::string & title) { switch (defaultResqmlVersion) { case DataObjectRepository::EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::StratigraphicOccurrenceInterpretation(orgFeat, guid, title, gsoap_resqml2_0_1::resqml20__OrderingCriteria__apparent_x0020depth); #ifdef WITH_RESQML2_2 case DataObjectRepository::EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::StratigraphicOccurrenceInterpretation(orgFeat, guid, title, gsoap_resqml2_0_1::resqml20__OrderingCriteria__apparent_x0020depth); #endif default: throw std::invalid_argument("Unrecognized Energistics standard."); } } //************************************ //************ REPRESENTATION ******** //************************************ RESQML2_NS::TriangulatedSetRepresentation* DataObjectRepository::createTriangulatedSetRepresentation(const std::string & guid, const std::string & title) { switch (defaultResqmlVersion) { case DataObjectRepository::EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::TriangulatedSetRepresentation(this, guid, title); #ifdef WITH_RESQML2_2 case DataObjectRepository::EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::TriangulatedSetRepresentation(this, guid, title); #endif default: throw std::invalid_argument("Unrecognized Energistics standard."); } } RESQML2_NS::TriangulatedSetRepresentation* DataObjectRepository::createTriangulatedSetRepresentation(RESQML2_NS::AbstractFeatureInterpretation* interp, const std::string & guid, const std::string & title) { switch (defaultResqmlVersion) { case DataObjectRepository::EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::TriangulatedSetRepresentation(interp, guid, title); #ifdef WITH_RESQML2_2 case DataObjectRepository::EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::TriangulatedSetRepresentation(interp, guid, title); #endif default: throw std::invalid_argument("Unrecognized Energistics standard."); } } RESQML2_NS::PolylineSetRepresentation* DataObjectRepository::createPolylineSetRepresentation(const std::string & guid, const std::string & title) { switch (defaultResqmlVersion) { case DataObjectRepository::EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::PolylineSetRepresentation(this, guid, title); #ifdef WITH_RESQML2_2 case DataObjectRepository::EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::PolylineSetRepresentation(this, guid, title); #endif default: throw std::invalid_argument("Unrecognized Energistics standard."); } } RESQML2_NS::PolylineSetRepresentation* DataObjectRepository::createPolylineSetRepresentation(RESQML2_NS::AbstractFeatureInterpretation* interp, const std::string & guid, const std::string & title) { switch (defaultResqmlVersion) { case DataObjectRepository::EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::PolylineSetRepresentation(interp, guid, title); #ifdef WITH_RESQML2_2 case DataObjectRepository::EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::PolylineSetRepresentation(interp, guid, title); #endif default: throw std::invalid_argument("Unrecognized Energistics standard."); } } RESQML2_NS::PolylineSetRepresentation* DataObjectRepository::createPolylineSetRepresentation(RESQML2_NS::AbstractFeatureInterpretation* interp, const std::string & guid, const std::string & title, gsoap_eml2_3::resqml22__LineRole roleKind) { switch (defaultResqmlVersion) { case DataObjectRepository::EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::PolylineSetRepresentation(interp, guid, title, roleKind); #ifdef WITH_RESQML2_2 case DataObjectRepository::EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::PolylineSetRepresentation(interp, guid, title, roleKind); #endif default: throw std::invalid_argument("Unrecognized Energistics standard."); } } RESQML2_NS::PointSetRepresentation* DataObjectRepository::createPointSetRepresentation(const std::string & guid, const std::string & title) { switch (defaultResqmlVersion) { case DataObjectRepository::EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::PointSetRepresentation(this, guid, title); #ifdef WITH_RESQML2_2 case DataObjectRepository::EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::PointSetRepresentation(this, guid, title); #endif default: throw std::invalid_argument("Unrecognized Energistics standard."); } } RESQML2_NS::PointSetRepresentation* DataObjectRepository::createPointSetRepresentation(RESQML2_NS::AbstractFeatureInterpretation* interp, const std::string & guid, const std::string & title) { switch (defaultResqmlVersion) { case DataObjectRepository::EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::PointSetRepresentation(interp, guid, title); #ifdef WITH_RESQML2_2 case DataObjectRepository::EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::PointSetRepresentation(interp, guid, title); #endif default: throw std::invalid_argument("Unrecognized Energistics standard."); } } RESQML2_NS::PlaneSetRepresentation* DataObjectRepository::createPlaneSetRepresentation(RESQML2_NS::AbstractFeatureInterpretation* interp, const std::string & guid, const std::string & title) { switch (defaultResqmlVersion) { case DataObjectRepository::EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::PlaneSetRepresentation(interp, guid, title); #ifdef WITH_RESQML2_2 case DataObjectRepository::EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::PlaneSetRepresentation(interp, guid, title); #endif default: throw std::invalid_argument("Unrecognized Energistics standard."); } } RESQML2_NS::PolylineRepresentation* DataObjectRepository::createPolylineRepresentation(const std::string & guid, const std::string & title, bool isClosed) { switch (defaultResqmlVersion) { case DataObjectRepository::EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::PolylineRepresentation(this, guid, title, isClosed); #ifdef WITH_RESQML2_2 case DataObjectRepository::EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::PolylineRepresentation(this, guid, title, isClosed); #endif default: throw std::invalid_argument("Unrecognized Energistics standard."); } } RESQML2_NS::PolylineRepresentation* DataObjectRepository::createPolylineRepresentation(RESQML2_NS::AbstractFeatureInterpretation* interp, const std::string & guid, const std::string & title, bool isClosed) { switch (defaultResqmlVersion) { case DataObjectRepository::EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::PolylineRepresentation(interp, guid, title, isClosed); #ifdef WITH_RESQML2_2 case DataObjectRepository::EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::PolylineRepresentation(interp, guid, title, isClosed); #endif default: throw std::invalid_argument("Unrecognized Energistics standard."); } } RESQML2_NS::PolylineRepresentation* DataObjectRepository::createPolylineRepresentation(RESQML2_NS::AbstractFeatureInterpretation* interp, const std::string & guid, const std::string & title, gsoap_eml2_3::resqml22__LineRole roleKind, bool isClosed) { switch (defaultResqmlVersion) { case DataObjectRepository::EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::PolylineRepresentation(interp, guid, title, roleKind, isClosed); #ifdef WITH_RESQML2_2 case DataObjectRepository::EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::PolylineRepresentation(interp, guid, title, roleKind, isClosed); #endif default: throw std::invalid_argument("Unrecognized Energistics standard."); } } RESQML2_NS::Grid2dRepresentation* DataObjectRepository::createGrid2dRepresentation(RESQML2_NS::AbstractFeatureInterpretation* interp, const std::string & guid, const std::string & title) { switch (defaultResqmlVersion) { case DataObjectRepository::EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::Grid2dRepresentation(interp, guid, title); #ifdef WITH_RESQML2_2 case DataObjectRepository::EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::Grid2dRepresentation(interp, guid, title); #endif default: throw std::invalid_argument("Unrecognized Energistics standard."); } } RESQML2_NS::WellboreTrajectoryRepresentation* DataObjectRepository::createWellboreTrajectoryRepresentation(RESQML2_NS::WellboreInterpretation * interp, const std::string & guid, const std::string & title, RESQML2_NS::MdDatum * mdInfo) { switch (defaultResqmlVersion) { case DataObjectRepository::EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::WellboreTrajectoryRepresentation(interp, guid, title, mdInfo); #ifdef WITH_RESQML2_2 case DataObjectRepository::EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::WellboreTrajectoryRepresentation(interp, guid, title, mdInfo); #endif default: throw std::invalid_argument("Unrecognized Energistics standard."); } } RESQML2_NS::WellboreTrajectoryRepresentation* DataObjectRepository::createWellboreTrajectoryRepresentation(RESQML2_NS::WellboreInterpretation * interp, const std::string & guid, const std::string & title, RESQML2_NS::DeviationSurveyRepresentation * deviationSurvey) { switch (defaultResqmlVersion) { case DataObjectRepository::EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::WellboreTrajectoryRepresentation(interp, guid, title, deviationSurvey); #ifdef WITH_RESQML2_2 case DataObjectRepository::EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::WellboreTrajectoryRepresentation(interp, guid, title, deviationSurvey); #endif default: throw std::invalid_argument("Unrecognized Energistics standard."); } } RESQML2_NS::DeviationSurveyRepresentation* DataObjectRepository::createDeviationSurveyRepresentation(RESQML2_NS::WellboreInterpretation * interp, const std::string & guid, const std::string & title, const bool & isFinal, RESQML2_NS::MdDatum * mdInfo) { switch (defaultResqmlVersion) { case DataObjectRepository::EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::DeviationSurveyRepresentation(interp, guid, title, isFinal, mdInfo); #ifdef WITH_RESQML2_2 case DataObjectRepository::EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::DeviationSurveyRepresentation(interp, guid, title, isFinal, mdInfo); #endif default: throw std::invalid_argument("Unrecognized Energistics standard."); } } RESQML2_NS::WellboreFrameRepresentation* DataObjectRepository::createWellboreFrameRepresentation(RESQML2_NS::WellboreInterpretation * interp, const std::string & guid, const std::string & title, RESQML2_NS::WellboreTrajectoryRepresentation * traj) { switch (defaultResqmlVersion) { case DataObjectRepository::EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::WellboreFrameRepresentation(interp, guid, title, traj); #ifdef WITH_RESQML2_2 case DataObjectRepository::EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::WellboreFrameRepresentation(interp, guid, title, traj); #endif default: throw std::invalid_argument("Unrecognized Energistics standard."); } } #ifdef WITH_RESQML2_2 RESQML2_NS::SeismicWellboreFrameRepresentation* DataObjectRepository::createSeismicWellboreFrameRepresentation( RESQML2_NS::WellboreInterpretation* interp, const std::string& guid, const std::string& title, RESQML2_NS::WellboreTrajectoryRepresentation* traj, double seismicReferenceDatum, double weatheringVelocity, RESQML2_NS::LocalTime3dCrs* crs) { return new RESQML2_2_NS::SeismicWellboreFrameRepresentation(interp, guid, title, traj, seismicReferenceDatum, weatheringVelocity, crs); #else RESQML2_NS::SeismicWellboreFrameRepresentation* DataObjectRepository::createSeismicWellboreFrameRepresentation( RESQML2_NS::WellboreInterpretation*, const std::string&, const std::string&, RESQML2_NS::WellboreTrajectoryRepresentation*, double, double, RESQML2_NS::LocalTime3dCrs*) { throw std::logic_error("RESQML2.2 support has not been built in this library."); #endif } RESQML2_NS::WellboreMarkerFrameRepresentation* DataObjectRepository::createWellboreMarkerFrameRepresentation(RESQML2_NS::WellboreInterpretation * interp, const std::string & guid, const std::string & title, RESQML2_NS::WellboreTrajectoryRepresentation * traj) { switch (defaultResqmlVersion) { case DataObjectRepository::EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::WellboreMarkerFrameRepresentation(interp, guid, title, traj); #ifdef WITH_RESQML2_2 case DataObjectRepository::EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::WellboreMarkerFrameRepresentation(interp, guid, title, traj); #endif default: throw std::invalid_argument("Unrecognized Energistics standard."); } } RESQML2_NS::WellboreMarker* DataObjectRepository::createWellboreMarker(RESQML2_NS::WellboreMarkerFrameRepresentation* wellboreMarkerFrame, const std::string& guid, const std::string& title) { if (dynamic_cast<RESQML2_0_1_NS::WellboreMarkerFrameRepresentation*>(wellboreMarkerFrame) != nullptr) { return new RESQML2_0_1_NS::WellboreMarker(static_cast<RESQML2_0_1_NS::WellboreMarkerFrameRepresentation*>(wellboreMarkerFrame), guid, title); } #ifdef WITH_RESQML2_2 else if (dynamic_cast<RESQML2_2_NS::WellboreMarkerFrameRepresentation*>(wellboreMarkerFrame) != nullptr) { return new RESQML2_2_NS::WellboreMarker(static_cast<RESQML2_2_NS::WellboreMarkerFrameRepresentation*>(wellboreMarkerFrame), guid, title); } #endif else { throw std::invalid_argument("Unrecognized Energistics standard."); } } RESQML2_NS::WellboreMarker* DataObjectRepository::createWellboreMarker(RESQML2_NS::WellboreMarkerFrameRepresentation* wellboreMarkerFrame, const std::string& guid, const std::string& title, gsoap_resqml2_0_1::resqml20__GeologicBoundaryKind geologicBoundaryKind) { if (dynamic_cast<RESQML2_0_1_NS::WellboreMarkerFrameRepresentation*>(wellboreMarkerFrame) != nullptr) { return new RESQML2_0_1_NS::WellboreMarker(static_cast<RESQML2_0_1_NS::WellboreMarkerFrameRepresentation*>(wellboreMarkerFrame), guid, title, geologicBoundaryKind); } #ifdef WITH_RESQML2_2 else if (dynamic_cast<RESQML2_2_NS::WellboreMarkerFrameRepresentation*>(wellboreMarkerFrame) != nullptr) { return new RESQML2_2_NS::WellboreMarker(static_cast<RESQML2_2_NS::WellboreMarkerFrameRepresentation*>(wellboreMarkerFrame), guid, title, geologicBoundaryKind); } #endif else { throw std::invalid_argument("Unrecognized Energistics standard."); } } RESQML2_NS::BlockedWellboreRepresentation* DataObjectRepository::createBlockedWellboreRepresentation(RESQML2_NS::WellboreInterpretation * interp, const std::string & guid, const std::string & title, RESQML2_NS::WellboreTrajectoryRepresentation * traj) { switch (defaultResqmlVersion) { case DataObjectRepository::EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::BlockedWellboreRepresentation(interp, guid, title, traj); #ifdef WITH_RESQML2_2 case DataObjectRepository::EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::BlockedWellboreRepresentation(interp, guid, title, traj); #endif default: throw std::invalid_argument("Unrecognized Energistics standard."); } } RESQML2_NS::RepresentationSetRepresentation* DataObjectRepository::createRepresentationSetRepresentation( RESQML2_NS::AbstractOrganizationInterpretation* interp, const std::string & guid, const std::string & title) { switch (defaultResqmlVersion) { case DataObjectRepository::EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::RepresentationSetRepresentation(interp, guid, title); #ifdef WITH_RESQML2_2 case DataObjectRepository::EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::RepresentationSetRepresentation(interp, guid, title); #endif default: throw std::invalid_argument("Unrecognized Energistics standard."); } } RESQML2_NS::RepresentationSetRepresentation* DataObjectRepository::createRepresentationSetRepresentation( const std::string & guid, const std::string & title) { switch (defaultResqmlVersion) { case DataObjectRepository::EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::RepresentationSetRepresentation(this, guid, title); #ifdef WITH_RESQML2_2 case DataObjectRepository::EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::RepresentationSetRepresentation(this, guid, title); #endif default: throw std::invalid_argument("Unrecognized Energistics standard."); } } RESQML2_NS::NonSealedSurfaceFrameworkRepresentation* DataObjectRepository::createNonSealedSurfaceFrameworkRepresentation( RESQML2_NS::StructuralOrganizationInterpretation* interp, const std::string & guid, const std::string & title) { switch (defaultResqmlVersion) { case DataObjectRepository::EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::NonSealedSurfaceFrameworkRepresentation(interp, guid, title); #ifdef WITH_RESQML2_2 case DataObjectRepository::EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::NonSealedSurfaceFrameworkRepresentation(interp, guid, title); #endif default: throw std::invalid_argument("Unrecognized Energistics standard."); } } RESQML2_NS::SealedSurfaceFrameworkRepresentation* DataObjectRepository::createSealedSurfaceFrameworkRepresentation( RESQML2_NS::StructuralOrganizationInterpretation* interp, const std::string & guid, const std::string & title) { switch (defaultResqmlVersion) { case DataObjectRepository::EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::SealedSurfaceFrameworkRepresentation(interp, guid, title); #ifdef WITH_RESQML2_2 case DataObjectRepository::EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::SealedSurfaceFrameworkRepresentation(interp, guid, title); #endif default: throw std::invalid_argument("Unrecognized Energistics standard."); } } RESQML2_NS::SealedVolumeFrameworkRepresentation* DataObjectRepository::createSealedVolumeFrameworkRepresentation( RESQML2_NS::StratigraphicColumnRankInterpretation* interp, const std::string & guid, const std::string & title, RESQML2_NS::SealedSurfaceFrameworkRepresentation* ssf) { switch (defaultResqmlVersion) { case DataObjectRepository::EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::SealedVolumeFrameworkRepresentation(interp, guid, title, ssf); #ifdef WITH_RESQML2_2 case DataObjectRepository::EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::SealedVolumeFrameworkRepresentation(interp, guid, title, ssf); #endif default: throw std::invalid_argument("Unrecognized Energistics standard."); } } RESQML2_NS::AbstractIjkGridRepresentation* DataObjectRepository::createPartialIjkGridRepresentation(const std::string & guid, const std::string & title) { gsoap_resqml2_0_1::eml20__DataObjectReference* dor = createDor(guid, title, ""); dor->ContentType = getDefaultResqmlVersion() == EnergisticsStandard::RESQML2_2 ? "application/x-resqml+xml;version=2.2;type=obj_IjkGridRepresentation" : "application/x-resqml+xml;version=2.0;type=obj_IjkGridRepresentation"; auto result = new RESQML2_NS::AbstractIjkGridRepresentation(dor, false); addOrReplaceDataObject(result); return result; } RESQML2_NS::AbstractIjkGridRepresentation* DataObjectRepository::createPartialTruncatedIjkGridRepresentation(const std::string & guid, const std::string & title) { gsoap_resqml2_0_1::eml20__DataObjectReference* dor = createDor(guid, title, ""); dor->ContentType = getDefaultResqmlVersion() == EnergisticsStandard::RESQML2_2 ? "application/x-resqml+xml;version=2.2;type=obj_TruncatedIjkGridRepresentation" : "application/x-resqml+xml;version=2.0;type=obj_TruncatedIjkGridRepresentation"; auto result = new RESQML2_NS::AbstractIjkGridRepresentation(dor, true); addOrReplaceDataObject(result); return result; } RESQML2_NS::IjkGridExplicitRepresentation* DataObjectRepository::createIjkGridExplicitRepresentation(const std::string & guid, const std::string & title, unsigned int iCount, unsigned int jCount, unsigned int kCount, bool* kGaps, EML2_NS::AbstractHdfProxy* proxy) { switch (defaultResqmlVersion) { case EnergisticsStandard::RESQML2_0_1 : return new RESQML2_0_1_NS::IjkGridExplicitRepresentation(this, guid, title, iCount, jCount, kCount, kGaps, proxy); #ifdef WITH_RESQML2_2 case EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::IjkGridExplicitRepresentation(this, guid, title, iCount, jCount, kCount, kGaps, proxy); #endif default: throw std::logic_error("The RESQML version is not supported."); } } RESQML2_NS::IjkGridExplicitRepresentation* DataObjectRepository::createIjkGridExplicitRepresentation(RESQML2_NS::AbstractFeatureInterpretation* interp, const std::string & guid, const std::string & title, unsigned int iCount, unsigned int jCount, unsigned int kCount, bool* kGaps, EML2_NS::AbstractHdfProxy* proxy) { switch (defaultResqmlVersion) { case EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::IjkGridExplicitRepresentation(interp, guid, title, iCount, jCount, kCount, kGaps, proxy); #ifdef WITH_RESQML2_2 case EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::IjkGridExplicitRepresentation(interp, guid, title, iCount, jCount, kCount, kGaps, proxy); #endif default: throw std::logic_error("The RESQML version is not supported."); } } RESQML2_NS::IjkGridParametricRepresentation* DataObjectRepository::createIjkGridParametricRepresentation(const std::string & guid, const std::string & title, unsigned int iCount, unsigned int jCount, unsigned int kCount, bool* kGaps, EML2_NS::AbstractHdfProxy* proxy) { switch (defaultResqmlVersion) { case EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::IjkGridParametricRepresentation(this, guid, title, iCount, jCount, kCount, kGaps, proxy); #ifdef WITH_RESQML2_2 case EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::IjkGridParametricRepresentation(this, guid, title, iCount, jCount, kCount, kGaps, proxy); #endif default: throw std::logic_error("The RESQML version is not supported."); } } RESQML2_NS::IjkGridParametricRepresentation* DataObjectRepository::createIjkGridParametricRepresentation(RESQML2_NS::AbstractFeatureInterpretation* interp, const std::string & guid, const std::string & title, unsigned int iCount, unsigned int jCount, unsigned int kCount, bool* kGaps, EML2_NS::AbstractHdfProxy* proxy) { switch (defaultResqmlVersion) { case EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::IjkGridParametricRepresentation(interp, guid, title, iCount, jCount, kCount, kGaps, proxy); #ifdef WITH_RESQML2_2 case EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::IjkGridParametricRepresentation(interp, guid, title, iCount, jCount, kCount, kGaps, proxy); #endif default: throw std::logic_error("The RESQML version is not supported."); } } RESQML2_NS::IjkGridLatticeRepresentation* DataObjectRepository::createIjkGridLatticeRepresentation(const std::string & guid, const std::string & title, unsigned int iCount, unsigned int jCount, unsigned int kCount) { switch (defaultResqmlVersion) { case EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::IjkGridLatticeRepresentation(this, guid, title, iCount, jCount, kCount); #ifdef WITH_RESQML2_2 case EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::IjkGridLatticeRepresentation(this, guid, title, iCount, jCount, kCount); #endif default: throw std::logic_error("The RESQML version is not supported."); } } RESQML2_NS::IjkGridLatticeRepresentation* DataObjectRepository::createIjkGridLatticeRepresentation(RESQML2_NS::AbstractFeatureInterpretation* interp, const std::string & guid, const std::string & title, unsigned int iCount, unsigned int jCount, unsigned int kCount) { switch (defaultResqmlVersion) { case EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::IjkGridLatticeRepresentation(interp, guid, title, iCount, jCount, kCount); #ifdef WITH_RESQML2_2 case EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::IjkGridLatticeRepresentation(interp, guid, title, iCount, jCount, kCount); #endif default: throw std::logic_error("The RESQML version is not supported."); } } RESQML2_NS::IjkGridNoGeometryRepresentation* DataObjectRepository::createIjkGridNoGeometryRepresentation( const std::string & guid, const std::string & title, unsigned int iCount, unsigned int jCount, unsigned int kCount, bool* kGaps, EML2_NS::AbstractHdfProxy* proxy) { switch (defaultResqmlVersion) { case EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::IjkGridNoGeometryRepresentation(this, guid, title, iCount, jCount, kCount, kGaps, proxy); #ifdef WITH_RESQML2_2 case EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::IjkGridNoGeometryRepresentation(this, guid, title, iCount, jCount, kCount, kGaps, proxy); #endif default: throw std::logic_error("The RESQML version is not supported."); } } RESQML2_NS::IjkGridNoGeometryRepresentation* DataObjectRepository::createIjkGridNoGeometryRepresentation(RESQML2_NS::AbstractFeatureInterpretation* interp, const std::string & guid, const std::string & title, unsigned int iCount, unsigned int jCount, unsigned int kCount, bool* kGaps, EML2_NS::AbstractHdfProxy* proxy) { switch (defaultResqmlVersion) { case EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::IjkGridNoGeometryRepresentation(interp, guid, title, iCount, jCount, kCount, kGaps, proxy); #ifdef WITH_RESQML2_2 case EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::IjkGridNoGeometryRepresentation(interp, guid, title, iCount, jCount, kCount, kGaps, proxy); #endif default: throw std::logic_error("The RESQML version is not supported."); } } RESQML2_NS::UnstructuredGridRepresentation* DataObjectRepository::createUnstructuredGridRepresentation(const std::string & guid, const std::string & title, const uint64_t & cellCount) { switch (defaultResqmlVersion) { case EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::UnstructuredGridRepresentation(this, guid, title, cellCount); #ifdef WITH_RESQML2_2 case EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::UnstructuredGridRepresentation(this, guid, title, cellCount); #endif default: throw std::logic_error("The RESQML version is not supported."); } } RESQML2_NS::SubRepresentation* DataObjectRepository::createSubRepresentation(const std::string & guid, const std::string & title) { switch (defaultResqmlVersion) { case EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::SubRepresentation(this, guid, title); #ifdef WITH_RESQML2_2 case EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::SubRepresentation(this, guid, title); #endif default: throw std::logic_error("The RESQML version is not supported."); } } RESQML2_NS::SubRepresentation* DataObjectRepository::createSubRepresentation(RESQML2_NS::AbstractFeatureInterpretation* interp, const std::string & guid, const std::string & title) { switch (defaultResqmlVersion) { case EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::SubRepresentation(interp, guid, title); #ifdef WITH_RESQML2_2 case EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::SubRepresentation(interp, guid, title); #endif default: throw std::logic_error("The RESQML version is not supported."); } } RESQML2_NS::GridConnectionSetRepresentation* DataObjectRepository::createGridConnectionSetRepresentation(const std::string & guid, const std::string & title) { switch (defaultResqmlVersion) { case EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::GridConnectionSetRepresentation(this, guid, title); #ifdef WITH_RESQML2_2 case EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::GridConnectionSetRepresentation(this, guid, title); #endif default: throw std::logic_error("The RESQML version is not supported."); } } RESQML2_NS::GridConnectionSetRepresentation* DataObjectRepository::createGridConnectionSetRepresentation(RESQML2_NS::AbstractFeatureInterpretation* interp, const std::string & guid, const std::string & title) { switch (defaultResqmlVersion) { case EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::GridConnectionSetRepresentation(interp, guid, title); #ifdef WITH_RESQML2_2 case EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::GridConnectionSetRepresentation(interp, guid, title); #endif default: throw std::logic_error("The RESQML version is not supported."); } } RESQML2_NS::StreamlinesFeature* DataObjectRepository::createStreamlinesFeature(const std::string & guid, const std::string & title, uint64_t timeIndex, EML2_NS::TimeSeries* timeSeries) { switch (defaultResqmlVersion) { case EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::StreamlinesFeature(this, guid, title, timeIndex, timeSeries); #ifdef WITH_RESQML2_2 case EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::StreamlinesFeature(this, guid, title, timeIndex, timeSeries); #endif default: throw std::logic_error("The RESQML version is not supported."); } } RESQML2_NS::StreamlinesRepresentation* DataObjectRepository::createStreamlinesRepresentation(RESQML2_NS::GenericFeatureInterpretation* interp, const std::string & guid, const std::string & title, uint64_t lineCount) { switch (defaultResqmlVersion) { case EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::StreamlinesRepresentation(interp, guid, title, lineCount); #ifdef WITH_RESQML2_2 case EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::StreamlinesRepresentation(interp, guid, title, lineCount); #endif default: throw std::logic_error("The RESQML version is not supported."); } } //************************************ //************* PROPERTIES *********** //************************************ EML2_NS::TimeSeries* DataObjectRepository::createTimeSeries(const std::string & guid, const std::string & title) { switch (defaultEmlVersion) { case DataObjectRepository::EnergisticsStandard::EML2_0: return new RESQML2_0_1_NS::TimeSeries(this, guid, title); #ifdef WITH_RESQML2_2 case DataObjectRepository::EnergisticsStandard::EML2_3: return new EML2_3_NS::TimeSeries(this, guid, title); #endif default: throw std::invalid_argument("Unrecognized Energistics standard."); } } RESQML2_NS::DoubleTableLookup* DataObjectRepository::createDoubleTableLookup(const std::string & guid, const std::string & title) { switch (defaultResqmlVersion) { case EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::DoubleTableLookup(this, guid, title); #ifdef WITH_RESQML2_2 case EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::DoubleTableLookup(this, guid, title); #endif default: throw std::logic_error("The RESQML version is not supported."); } } RESQML2_NS::StringTableLookup* DataObjectRepository::createStringTableLookup(const std::string & guid, const std::string & title) { switch (defaultResqmlVersion) { case EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::StringTableLookup(this, guid, title); #ifdef WITH_RESQML2_2 case EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::StringTableLookup(this, guid, title); #endif default: throw std::logic_error("The RESQML version is not supported."); } } RESQML2_0_1_NS::PropertyKind* DataObjectRepository::createPropertyKind(const std::string & guid, const std::string & title, const std::string & namingSystem, gsoap_resqml2_0_1::resqml20__ResqmlUom uom, gsoap_resqml2_0_1::resqml20__ResqmlPropertyKind parentEnergisticsPropertyKind) { return new RESQML2_0_1_NS::PropertyKind(this, guid, title, namingSystem, uom, parentEnergisticsPropertyKind); } RESQML2_0_1_NS::PropertyKind* DataObjectRepository::createPropertyKind(const std::string & guid, const std::string & title, const std::string & namingSystem, gsoap_resqml2_0_1::resqml20__ResqmlUom uom, EML2_NS::PropertyKind * parentPropType) { return new RESQML2_0_1_NS::PropertyKind(guid, title, namingSystem, uom, parentPropType); } RESQML2_0_1_NS::PropertyKind* DataObjectRepository::createPropertyKind(const std::string & guid, const std::string & title, const std::string & namingSystem, const std::string & nonStandardUom, gsoap_resqml2_0_1::resqml20__ResqmlPropertyKind parentEnergisticsPropertyKind) { return new RESQML2_0_1_NS::PropertyKind(this, guid, title, namingSystem, nonStandardUom, parentEnergisticsPropertyKind); } RESQML2_0_1_NS::PropertyKind* DataObjectRepository::createPropertyKind(const std::string & guid, const std::string & title, const std::string & namingSystem, const std::string & nonStandardUom, EML2_NS::PropertyKind * parentPropType) { return new RESQML2_0_1_NS::PropertyKind(guid, title, namingSystem, nonStandardUom, parentPropType); } EML2_NS::PropertyKind* DataObjectRepository::createPropertyKind(const std::string & guid, const std::string & title, gsoap_eml2_1::eml21__QuantityClassKind quantityClass, bool isAbstract, EML2_NS::PropertyKind* parentPropertyKind) { switch (defaultEmlVersion) { case DataObjectRepository::EnergisticsStandard::EML2_0: case DataObjectRepository::EnergisticsStandard::EML2_1: return new EML2_1_NS::PropertyKind(this, guid, title, quantityClass, isAbstract, parentPropertyKind); #ifdef WITH_RESQML2_2 case DataObjectRepository::EnergisticsStandard::EML2_3: return new EML2_3_NS::PropertyKind(this, guid, title, quantityClass, isAbstract, parentPropertyKind); #endif default: throw std::invalid_argument("Unrecognized Energistics standard."); } } RESQML2_NS::PropertySet* DataObjectRepository::createPropertySet(const std::string & guid, const std::string & title, bool hasMultipleRealizations, bool hasSinglePropertyKind, gsoap_eml2_3::resqml22__TimeSetKind timeSetKind) { switch (defaultResqmlVersion) { case DataObjectRepository::EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::PropertySet(this, guid, title, hasMultipleRealizations, hasSinglePropertyKind, timeSetKind); #ifdef WITH_RESQML2_2 case DataObjectRepository::EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::PropertySet(this, guid, title, hasMultipleRealizations, hasSinglePropertyKind, timeSetKind); #endif default: throw std::invalid_argument("Unrecognized Energistics standard."); } } RESQML2_0_1_NS::CommentProperty* DataObjectRepository::createCommentProperty(RESQML2_NS::AbstractRepresentation * rep, const std::string & guid, const std::string & title, unsigned int dimension, gsoap_eml2_3::resqml22__IndexableElement attachmentKind, gsoap_resqml2_0_1::resqml20__ResqmlPropertyKind energisticsPropertyKind) { return new RESQML2_0_1_NS::CommentProperty(rep, guid, title, dimension, attachmentKind, energisticsPropertyKind); } RESQML2_NS::CommentProperty* DataObjectRepository::createCommentProperty(RESQML2_NS::AbstractRepresentation * rep, const std::string & guid, const std::string & title, unsigned int dimension, gsoap_eml2_3::resqml22__IndexableElement attachmentKind, EML2_NS::PropertyKind * localPropType) { switch (defaultResqmlVersion) { case DataObjectRepository::EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::CommentProperty(rep, guid, title, dimension, attachmentKind, localPropType); #ifdef WITH_RESQML2_2 case DataObjectRepository::EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::CommentProperty(rep, guid, title, dimension, attachmentKind, localPropType); #endif default: throw std::invalid_argument("Unrecognized Energistics standard."); } } RESQML2_0_1_NS::ContinuousProperty* DataObjectRepository::createContinuousProperty(RESQML2_NS::AbstractRepresentation * rep, const std::string & guid, const std::string & title, unsigned int dimension, gsoap_eml2_3::resqml22__IndexableElement attachmentKind, gsoap_resqml2_0_1::resqml20__ResqmlUom uom, gsoap_resqml2_0_1::resqml20__ResqmlPropertyKind energisticsPropertyKind) { return new RESQML2_0_1_NS::ContinuousProperty(rep, guid, title, dimension, attachmentKind, uom, energisticsPropertyKind); } RESQML2_NS::ContinuousProperty* DataObjectRepository::createContinuousProperty(RESQML2_NS::AbstractRepresentation * rep, const std::string & guid, const std::string & title, unsigned int dimension, gsoap_eml2_3::resqml22__IndexableElement attachmentKind, gsoap_resqml2_0_1::resqml20__ResqmlUom uom, EML2_NS::PropertyKind * localPropType) { switch (defaultResqmlVersion) { case DataObjectRepository::EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::ContinuousProperty(rep, guid, title, dimension, attachmentKind, uom, localPropType); #ifdef WITH_RESQML2_2 case DataObjectRepository::EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::ContinuousProperty(rep, guid, title, dimension, attachmentKind, uom, localPropType); #endif default: throw std::invalid_argument("Unrecognized Energistics standard."); } } RESQML2_0_1_NS::ContinuousProperty* DataObjectRepository::createContinuousProperty(RESQML2_NS::AbstractRepresentation * rep, const std::string & guid, const std::string & title, unsigned int dimension, gsoap_eml2_3::resqml22__IndexableElement attachmentKind, std::string nonStandardUom, gsoap_resqml2_0_1::resqml20__ResqmlPropertyKind energisticsPropertyKind) { return new RESQML2_0_1_NS::ContinuousProperty(rep, guid, title, dimension, attachmentKind, nonStandardUom, energisticsPropertyKind); } RESQML2_NS::ContinuousProperty* DataObjectRepository::createContinuousProperty(RESQML2_NS::AbstractRepresentation * rep, const std::string & guid, const std::string & title, unsigned int dimension, gsoap_eml2_3::resqml22__IndexableElement attachmentKind, const std::string & nonStandardUom, EML2_NS::PropertyKind * localPropType) { switch (defaultResqmlVersion) { case DataObjectRepository::EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::ContinuousProperty(rep, guid, title, dimension, attachmentKind, nonStandardUom, localPropType); #ifdef WITH_RESQML2_2 case DataObjectRepository::EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::ContinuousProperty(rep, guid, title, dimension, attachmentKind, nonStandardUom, localPropType); #endif default: throw std::invalid_argument("Unrecognized Energistics standard."); } } RESQML2_0_1_NS::DiscreteProperty* DataObjectRepository::createDiscreteProperty(RESQML2_NS::AbstractRepresentation * rep, const std::string & guid, const std::string & title, unsigned int dimension, gsoap_eml2_3::resqml22__IndexableElement attachmentKind, gsoap_resqml2_0_1::resqml20__ResqmlPropertyKind energisticsPropertyKind) { return new RESQML2_0_1_NS::DiscreteProperty(rep, guid, title, dimension, attachmentKind, energisticsPropertyKind); } RESQML2_NS::DiscreteProperty* DataObjectRepository::createDiscreteProperty(RESQML2_NS::AbstractRepresentation * rep, const std::string & guid, const std::string & title, unsigned int dimension, gsoap_eml2_3::resqml22__IndexableElement attachmentKind, EML2_NS::PropertyKind * localPropType) { switch (defaultResqmlVersion) { case DataObjectRepository::EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::DiscreteProperty(rep, guid, title, dimension, attachmentKind, localPropType); #ifdef WITH_RESQML2_2 case DataObjectRepository::EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::DiscreteProperty(rep, guid, title, dimension, attachmentKind, localPropType); #endif default: throw std::invalid_argument("Unrecognized Energistics standard."); } } RESQML2_0_1_NS::CategoricalProperty* DataObjectRepository::createCategoricalProperty(RESQML2_NS::AbstractRepresentation * rep, const std::string & guid, const std::string & title, unsigned int dimension, gsoap_eml2_3::resqml22__IndexableElement attachmentKind, RESQML2_NS::StringTableLookup* strLookup, gsoap_resqml2_0_1::resqml20__ResqmlPropertyKind energisticsPropertyKind) { return new RESQML2_0_1_NS::CategoricalProperty(rep, guid, title, dimension, attachmentKind, strLookup, energisticsPropertyKind); } RESQML2_0_1_NS::CategoricalProperty* DataObjectRepository::createCategoricalProperty(RESQML2_NS::AbstractRepresentation * rep, const std::string & guid, const std::string & title, unsigned int dimension, gsoap_eml2_3::resqml22__IndexableElement attachmentKind, RESQML2_NS::DoubleTableLookup* dblLookup, gsoap_resqml2_0_1::resqml20__ResqmlPropertyKind energisticsPropertyKind) { return new RESQML2_0_1_NS::CategoricalProperty(rep, guid, title, dimension, attachmentKind, dblLookup, energisticsPropertyKind); } RESQML2_NS::CategoricalProperty* DataObjectRepository::createCategoricalProperty(RESQML2_NS::AbstractRepresentation * rep, const std::string & guid, const std::string & title, unsigned int dimension, gsoap_eml2_3::resqml22__IndexableElement attachmentKind, RESQML2_NS::StringTableLookup* strLookup, EML2_NS::PropertyKind * localPropType) { switch (defaultResqmlVersion) { case DataObjectRepository::EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::CategoricalProperty(rep, guid, title, dimension, attachmentKind, strLookup, localPropType); #ifdef WITH_RESQML2_2 case DataObjectRepository::EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::CategoricalProperty(rep, guid, title, dimension, attachmentKind, strLookup, localPropType); #endif default: throw std::invalid_argument("Unrecognized Energistics standard."); } } RESQML2_NS::CategoricalProperty* DataObjectRepository::createCategoricalProperty(RESQML2_NS::AbstractRepresentation * rep, const std::string & guid, const std::string & title, unsigned int dimension, gsoap_eml2_3::resqml22__IndexableElement attachmentKind, RESQML2_NS::DoubleTableLookup* dblLookup, EML2_NS::PropertyKind * localPropType) { switch (defaultResqmlVersion) { case DataObjectRepository::EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::CategoricalProperty(rep, guid, title, dimension, attachmentKind, dblLookup, localPropType); #ifdef WITH_RESQML2_2 case DataObjectRepository::EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::CategoricalProperty(rep, guid, title, dimension, attachmentKind, dblLookup, localPropType); #endif default: throw std::invalid_argument("Unrecognized Energistics standard."); } } RESQML2_0_1_NS::PointsProperty* DataObjectRepository::createPointsProperty(RESQML2_NS::AbstractRepresentation * rep, const std::string & guid, const std::string & title, unsigned int dimension, gsoap_eml2_3::resqml22__IndexableElement attachmentKind, RESQML2_NS::AbstractLocal3dCrs* localCrs, gsoap_resqml2_0_1::resqml20__ResqmlPropertyKind energisticsPropertyKind) { return new RESQML2_0_1_NS::PointsProperty(rep, guid, title, dimension, attachmentKind, localCrs, energisticsPropertyKind); } RESQML2_NS::PointsProperty* DataObjectRepository::createPointsProperty(RESQML2_NS::AbstractRepresentation * rep, const std::string & guid, const std::string & title, unsigned int dimension, gsoap_eml2_3::resqml22__IndexableElement attachmentKind, RESQML2_NS::AbstractLocal3dCrs* localCrs, EML2_NS::PropertyKind * localPropType) { switch (defaultResqmlVersion) { case DataObjectRepository::EnergisticsStandard::RESQML2_0_1: return new RESQML2_0_1_NS::PointsProperty(rep, guid, title, dimension, attachmentKind, localCrs, localPropType); #ifdef WITH_RESQML2_2 case DataObjectRepository::EnergisticsStandard::RESQML2_2: return new RESQML2_2_NS::PointsProperty(rep, guid, title, dimension, attachmentKind, localCrs, localPropType); #endif default: throw std::invalid_argument("Unrecognized Energistics standard."); } } //************************************ //************* ACTIVITIES *********** //************************************ EML2_NS::ActivityTemplate* DataObjectRepository::createActivityTemplate(const std::string & guid, const std::string & title) { switch (defaultEmlVersion) { case DataObjectRepository::EnergisticsStandard::EML2_0: return new RESQML2_0_1_NS::ActivityTemplate(this, guid, title); #ifdef WITH_RESQML2_2 case DataObjectRepository::EnergisticsStandard::EML2_3: return new EML2_3_NS::ActivityTemplate(this, guid, title); #endif default: throw std::invalid_argument("Unrecognized Energistics standard."); } } EML2_NS::Activity* DataObjectRepository::createActivity(EML2_NS::ActivityTemplate* activityTemplate, const std::string & guid, const std::string & title) { switch (defaultEmlVersion) { case DataObjectRepository::EnergisticsStandard::EML2_0: return new Activity(activityTemplate, guid, title); #ifdef WITH_RESQML2_2 case DataObjectRepository::EnergisticsStandard::EML2_3: return new EML2_3_NS::Activity(activityTemplate, guid, title); #endif default: throw std::invalid_argument("Unrecognized Energistics standard."); } } //************************************ //*************** WITSML ************* //************************************ WITSML2_0_NS::Well* DataObjectRepository::createWell(const std::string & guid, const std::string & title) { return new WITSML2_0_NS::Well(this, guid, title); } WITSML2_0_NS::Well* DataObjectRepository::createWell(const std::string & guid, const std::string & title, const std::string & operator_, gsoap_eml2_1::eml21__WellStatus statusWell, gsoap_eml2_1::witsml20__WellDirection directionWell) { return new WITSML2_0_NS::Well(this, guid, title, operator_, statusWell, directionWell); } WITSML2_0_NS::Wellbore* DataObjectRepository::createWellbore(WITSML2_0_NS::Well* witsmlWell, const std::string & guid, const std::string & title) { return new WITSML2_0_NS::Wellbore(witsmlWell, guid, title); } WITSML2_0_NS::Wellbore* DataObjectRepository::createWellbore(WITSML2_0_NS::Well* witsmlWell, const std::string & guid, const std::string & title, gsoap_eml2_1::eml21__WellStatus statusWellbore, bool isActive, bool achievedTD) { return new WITSML2_0_NS::Wellbore(witsmlWell, guid, title, statusWellbore, isActive, achievedTD); } WITSML2_0_NS::WellCompletion* DataObjectRepository::createWellCompletion(WITSML2_0_NS::Well* witsmlWell, const std::string & guid, const std::string & title) { return new WITSML2_0_NS::WellCompletion(witsmlWell, guid, title); } WITSML2_0_NS::WellboreCompletion* DataObjectRepository::createWellboreCompletion(WITSML2_0_NS::Wellbore* witsmlWellbore, WITSML2_0_NS::WellCompletion* wellCompletion, const std::string & guid, const std::string & title, const std::string & wellCompletionName) { return new WITSML2_0_NS::WellboreCompletion(witsmlWellbore, wellCompletion, guid, title, wellCompletionName); } WITSML2_0_NS::WellboreGeometry* DataObjectRepository::createWellboreGeometry(WITSML2_0_NS::Wellbore* witsmlWellbore, const std::string & guid, const std::string & title, gsoap_eml2_1::witsml20__ChannelStatus channelStatus) { return new WellboreGeometry(witsmlWellbore, guid, title, channelStatus); } WITSML2_0_NS::Trajectory* DataObjectRepository::createTrajectory(WITSML2_0_NS::Wellbore* witsmlWellbore, const std::string & guid, const std::string & title, gsoap_eml2_1::witsml20__ChannelStatus channelStatus) { return new WITSML2_0_NS::Trajectory(witsmlWellbore, guid, title, channelStatus); } WITSML2_0_NS::Log* DataObjectRepository::createLog(WITSML2_0_NS::Wellbore* witsmlWellbore, const std::string & guid, const std::string & title) { return new WITSML2_0_NS::Log(witsmlWellbore, guid, title); } WITSML2_0_NS::ChannelSet* DataObjectRepository::createChannelSet(const std::string & guid, const std::string & title) { return new WITSML2_0_NS::ChannelSet(this, guid, title); } WITSML2_0_NS::Channel* DataObjectRepository::createChannel(EML2_NS::PropertyKind * propertyKind, const std::string & guid, const std::string & title, const std::string & mnemonic, gsoap_eml2_1::eml21__UnitOfMeasure uom, gsoap_eml2_1::witsml20__EtpDataType dataType, gsoap_eml2_1::witsml20__ChannelStatus growingStatus, const std::string & timeDepth, const std::string & loggingCompanyName) { return new WITSML2_0_NS::Channel(propertyKind, guid, title, mnemonic, uom, dataType, growingStatus, timeDepth, loggingCompanyName); } WITSML2_0_NS::WellboreMarker* DataObjectRepository::createWellboreMarker( const std::string & guid, const std::string & title, double md, gsoap_eml2_1::eml21__LengthUom mdUom, const std::string & mdDatum) { return new WITSML2_0_NS::WellboreMarker(this, guid, title, md, mdUom, mdDatum); } WITSML2_0_NS::WellboreMarker* DataObjectRepository::createWellboreMarker(WITSML2_0_NS::Wellbore* witsmlWellbore, const std::string & guid, const std::string & title, double md, gsoap_eml2_1::eml21__LengthUom mdUom, const std::string & mdDatum) { return new WITSML2_0_NS::WellboreMarker(witsmlWellbore, guid, title, md, mdUom, mdDatum); } //************************************ //*************** PRODML ************* //************************************ PRODML2_1_NS::FluidSystem* DataObjectRepository::createFluidSystem(const std::string & guid, const std::string & title, double temperatureValue, gsoap_eml2_2::eml22__ThermodynamicTemperatureUom temperatureUom, double pressureValue, gsoap_eml2_2::eml22__PressureUom pressureUom, gsoap_eml2_2::prodml21__ReservoirFluidKind reservoirFluidKind, double gasOilRatio, gsoap_eml2_2::eml22__VolumePerVolumeUom gasOilRatioUom) { return new PRODML2_1_NS::FluidSystem(this, guid, title, temperatureValue, temperatureUom, pressureValue, pressureUom, reservoirFluidKind, gasOilRatio, gasOilRatioUom); } PRODML2_1_NS::FluidSystem* DataObjectRepository::createFluidSystem(const std::string & guid, const std::string & title, gsoap_eml2_2::eml22__ReferenceCondition referenceCondition, gsoap_eml2_2::prodml21__ReservoirFluidKind reservoirFluidKind, double gasOilRatio, gsoap_eml2_2::eml22__VolumePerVolumeUom gasOilRatioUom) { return new PRODML2_1_NS::FluidSystem(this, guid, title, referenceCondition, reservoirFluidKind, gasOilRatio, gasOilRatioUom); } PRODML2_1_NS::FluidCharacterization* DataObjectRepository::createFluidCharacterization(const std::string & guid, const std::string & title) { return new PRODML2_1_NS::FluidCharacterization(this, guid, title); } PRODML2_1_NS::TimeSeriesData* DataObjectRepository::createTimeSeriesData(const std::string & guid, const std::string & title) { return new PRODML2_1_NS::TimeSeriesData(this, guid, title); } #if WITH_RESQML2_2 EML2_NS::GraphicalInformationSet* DataObjectRepository::createGraphicalInformationSet(const std::string & guid, const std::string & title) { return new EML2_3_NS::GraphicalInformationSet(this, guid, title); #else EML2_NS::GraphicalInformationSet* DataObjectRepository::createGraphicalInformationSet(const std::string&, const std::string&) { throw std::logic_error("RESQML2.2 support has not been built in this library."); #endif } #if WITH_RESQML2_2 RESQML2_NS::DiscreteColorMap* DataObjectRepository::createDiscreteColorMap(const std::string& guid, const std::string& title) { return new RESQML2_2_NS::DiscreteColorMap(this, guid, title); #else RESQML2_NS::DiscreteColorMap* DataObjectRepository::createDiscreteColorMap(const std::string&, const std::string&) { throw std::logic_error("RESQML2.2 support has not been built in this library."); #endif } #if WITH_RESQML2_2 RESQML2_NS::ContinuousColorMap* DataObjectRepository::createContinuousColorMap(const std::string& guid, const std::string& title, gsoap_eml2_3::resqml22__InterpolationDomain interpolationDomain, gsoap_eml2_3::resqml22__InterpolationMethod interpolationMethod) { return new RESQML2_2_NS::ContinuousColorMap(this, guid, title, interpolationDomain, interpolationMethod); #else RESQML2_NS::ContinuousColorMap* DataObjectRepository::createContinuousColorMap(const std::string&, const std::string&, gsoap_eml2_3::resqml22__InterpolationDomain, gsoap_eml2_3::resqml22__InterpolationMethod) { throw std::logic_error("RESQML2.2 support has not been built in this library."); #endif } /* WITSML2_1_NS::ToolErrorModel* DataObjectRepository::createToolErrorModel( const std::string & guid, const std::string & title, gsoap_eml2_2::witsml2__MisalignmentMode misalignmentMode) { return new WITSML2_1_NS::ToolErrorModel(this, guid, title, misalignmentMode); } WITSML2_1_NS::ToolErrorModelDictionary* DataObjectRepository::createToolErrorModelDictionary( const std::string & guid, const std::string & title) { return new WITSML2_1_NS::ToolErrorModelDictionary(this, guid, title); } WITSML2_1_NS::ErrorTerm* DataObjectRepository::createErrorTerm( const std::string & guid, const std::string & title, gsoap_eml2_2::witsml2__ErrorPropagationMode propagationMode, WITSML2_1_NS::WeightingFunction* weightingFunction) { return new WITSML2_1_NS::ErrorTerm(this, guid, title, propagationMode, weightingFunction); } WITSML2_1_NS::ErrorTermDictionary* DataObjectRepository::createErrorTermDictionary( const std::string & guid, const std::string & title) { return new WITSML2_1_NS::ErrorTermDictionary(this, guid, title); } WITSML2_1_NS::WeightingFunction* DataObjectRepository::createWeightingFunction( const std::string & guid, const std::string & title, const std::string & depthFormula, const std::string & inclinationFormula, const std::string & azimuthFormula) { return new WITSML2_1_NS::WeightingFunction(this, guid, title, depthFormula, inclinationFormula, azimuthFormula); } WITSML2_1_NS::WeightingFunctionDictionary* DataObjectRepository::createWeightingFunctionDictionary( const std::string & guid, const std::string & title) { return new WITSML2_1_NS::WeightingFunctionDictionary(this, guid, title); } */ std::vector<RESQML2_NS::LocalDepth3dCrs*> DataObjectRepository::getLocalDepth3dCrsSet() const { return getDataObjects<RESQML2_NS::LocalDepth3dCrs>(); } std::vector<RESQML2_NS::LocalTime3dCrs*> DataObjectRepository::getLocalTime3dCrsSet() const { return getDataObjects<RESQML2_NS::LocalTime3dCrs>(); } std::vector<RESQML2_NS::StratigraphicColumn*> DataObjectRepository::getStratigraphicColumnSet() const { return getDataObjects<RESQML2_NS::StratigraphicColumn>(); } std::vector<RESQML2_NS::BoundaryFeature*> DataObjectRepository::getFaultSet() const { std::vector<RESQML2_NS::FaultInterpretation*> faultInterps = getDataObjects<RESQML2_NS::FaultInterpretation>(); std::vector<RESQML2_NS::BoundaryFeature*> result; for (auto faultinterp : faultInterps) { auto feature = faultinterp->getInterpretedFeature(); if (std::find(result.begin(), result.end(), feature) == result.end()) { result.push_back(static_cast<RESQML2_NS::BoundaryFeature*>(feature)); } } return result; } std::vector<RESQML2_NS::BoundaryFeature*> DataObjectRepository::getFractureSet() const { std::vector<RESQML2_NS::BoundaryFeatureInterpretation*> interps = getDataObjects<RESQML2_NS::BoundaryFeatureInterpretation>(); std::vector<RESQML2_NS::BoundaryFeature*> result; for (auto interp : interps) { if (interp->getXmlTag() == "BoundaryFeatureInterpretation") { auto feature = interp->getInterpretedFeature(); if (std::find(result.begin(), result.end(), feature) == result.end()) { result.push_back(static_cast<RESQML2_NS::BoundaryFeature*>(feature)); } } } return result; } vector<RESQML2_NS::PolylineSetRepresentation *> DataObjectRepository::getFaultPolylineSetRepSet() const { const std::vector<RESQML2_NS::BoundaryFeature*> faultSet = getFaultSet(); vector<RESQML2_NS::PolylineSetRepresentation *> result; for (size_t featureIndex = 0; featureIndex < faultSet.size(); ++featureIndex) { const vector<RESQML2_NS::AbstractFeatureInterpretation *> interpSet = faultSet[featureIndex]->getInterpretationSet(); for (size_t interpIndex = 0; interpIndex < interpSet.size(); ++interpIndex) { const vector<RESQML2_NS::AbstractRepresentation *> repSet = interpSet[interpIndex]->getRepresentationSet(); for (size_t repIndex = 0; repIndex < repSet.size(); ++repIndex) { if (dynamic_cast<RESQML2_NS::PolylineSetRepresentation*>(repSet[repIndex]) != nullptr) { result.push_back(static_cast<RESQML2_NS::PolylineSetRepresentation*>(repSet[repIndex])); } } } } return result; } vector<RESQML2_NS::PolylineSetRepresentation *> DataObjectRepository::getFracturePolylineSetRepSet() const { const std::vector<RESQML2_NS::BoundaryFeature*> fractureSet = getFractureSet(); vector<RESQML2_NS::PolylineSetRepresentation *> result; for (size_t featureIndex = 0; featureIndex < fractureSet.size(); ++featureIndex) { const vector<RESQML2_NS::AbstractFeatureInterpretation *> interpSet = fractureSet[featureIndex]->getInterpretationSet(); for (size_t interpIndex = 0; interpIndex < interpSet.size(); ++interpIndex) { const vector<RESQML2_NS::AbstractRepresentation *> repSet = interpSet[interpIndex]->getRepresentationSet(); for (size_t repIndex = 0; repIndex < repSet.size(); ++repIndex) { if (dynamic_cast<RESQML2_NS::PolylineSetRepresentation*>(repSet[repIndex]) != nullptr) { result.push_back(static_cast<RESQML2_NS::PolylineSetRepresentation*>(repSet[repIndex])); } } } } return result; } vector<RESQML2_NS::PolylineSetRepresentation *> DataObjectRepository::getCulturalPolylineSetRepSet() const { const std::vector<RESQML2_NS::CulturalFeature*> frontierSet = getCulturalSet(); vector<RESQML2_NS::PolylineSetRepresentation *> result; for (size_t featureIndex = 0; featureIndex < frontierSet.size(); ++featureIndex) { const vector<RESQML2_NS::AbstractFeatureInterpretation *> interpSet = frontierSet[featureIndex]->getInterpretationSet(); for (size_t interpIndex = 0; interpIndex < interpSet.size(); ++interpIndex) { const vector<RESQML2_NS::AbstractRepresentation *> repSet = interpSet[interpIndex]->getRepresentationSet(); for (size_t repIndex = 0; repIndex < repSet.size(); ++repIndex) { if (dynamic_cast<RESQML2_NS::PolylineSetRepresentation*>(repSet[repIndex]) != nullptr) { result.push_back(static_cast<RESQML2_NS::PolylineSetRepresentation*>(repSet[repIndex])); } } } } return result; } vector<RESQML2_NS::TriangulatedSetRepresentation *> DataObjectRepository::getFaultTriangulatedSetRepSet() const { const std::vector<RESQML2_NS::BoundaryFeature*> faultSet = getFaultSet(); vector<RESQML2_NS::TriangulatedSetRepresentation *> result; for (size_t featureIndex = 0; featureIndex < faultSet.size(); ++featureIndex) { const vector<RESQML2_NS::AbstractFeatureInterpretation *> interpSet = faultSet[featureIndex]->getInterpretationSet(); for (size_t interpIndex = 0; interpIndex < interpSet.size(); ++interpIndex) { const vector<RESQML2_NS::AbstractRepresentation *> repSet = interpSet[interpIndex]->getRepresentationSet(); for (size_t repIndex = 0; repIndex < repSet.size(); ++repIndex) { if (dynamic_cast<RESQML2_NS::TriangulatedSetRepresentation*>(repSet[repIndex]) != nullptr) { result.push_back(static_cast<RESQML2_NS::TriangulatedSetRepresentation*>(repSet[repIndex])); } } } } return result; } vector<RESQML2_NS::TriangulatedSetRepresentation *> DataObjectRepository::getFractureTriangulatedSetRepSet() const { const std::vector<RESQML2_NS::BoundaryFeature*> fractureSet = getFractureSet(); vector<RESQML2_NS::TriangulatedSetRepresentation *> result; for (size_t featureIndex = 0; featureIndex < fractureSet.size(); ++featureIndex) { const vector<RESQML2_NS::AbstractFeatureInterpretation *> interpSet = fractureSet[featureIndex]->getInterpretationSet(); for (size_t interpIndex = 0; interpIndex < interpSet.size(); ++interpIndex) { const vector<RESQML2_NS::AbstractRepresentation *> repSet = interpSet[interpIndex]->getRepresentationSet(); for (size_t repIndex = 0; repIndex < repSet.size(); ++repIndex) { if (dynamic_cast<RESQML2_NS::TriangulatedSetRepresentation*>(repSet[repIndex]) != nullptr) { result.push_back(static_cast<RESQML2_NS::TriangulatedSetRepresentation*>(repSet[repIndex])); } } } } return result; } std::vector<RESQML2_NS::BoundaryFeature*> DataObjectRepository::getHorizonSet() const { std::vector<RESQML2_NS::HorizonInterpretation*> horizonInterps = getDataObjects<RESQML2_NS::HorizonInterpretation>(); std::vector<RESQML2_NS::BoundaryFeature*> result; for (auto horizonInterp : horizonInterps) { auto feature = horizonInterp->getInterpretedFeature(); if (std::find(result.begin(), result.end(), feature) == result.end()) { result.push_back(static_cast<RESQML2_NS::BoundaryFeature*>(feature)); } } return result; } std::vector<RESQML2_NS::BoundaryFeature*> DataObjectRepository::getGeobodyBoundarySet() const { std::vector<RESQML2_NS::GeobodyBoundaryInterpretation*> horizonInterps = getDataObjects<RESQML2_NS::GeobodyBoundaryInterpretation>(); std::vector<RESQML2_NS::BoundaryFeature*> result; for (auto horizonInterp : horizonInterps) { auto feature = horizonInterp->getInterpretedFeature(); if (std::find(result.begin(), result.end(), feature) == result.end()) { result.push_back(static_cast<RESQML2_NS::BoundaryFeature*>(feature)); } } return result; } std::vector<RESQML2_NS::RockVolumeFeature*> DataObjectRepository::getGeobodySet() const { auto interps = getDataObjects<RESQML2_NS::GeobodyInterpretation>(); std::vector<RESQML2_NS::RockVolumeFeature*> result; for (auto interp : interps) { auto feature = interp->getInterpretedFeature(); if (std::find(result.begin(), result.end(), feature) == result.end()) { result.push_back(static_cast<RESQML2_NS::RockVolumeFeature*>(feature)); } } return result; } vector<RESQML2_NS::Grid2dRepresentation *> DataObjectRepository::getHorizonGrid2dRepSet() const { vector<RESQML2_NS::Grid2dRepresentation *> result; const vector<RESQML2_NS::BoundaryFeature*> horizonSet = getHorizonSet(); for (size_t featureIndex = 0; featureIndex < horizonSet.size(); ++featureIndex) { const vector<RESQML2_NS::AbstractFeatureInterpretation *> interpSet = horizonSet[featureIndex]->getInterpretationSet(); for (size_t interpIndex = 0; interpIndex < interpSet.size(); ++interpIndex) { const vector<RESQML2_NS::AbstractRepresentation *> repSet = interpSet[interpIndex]->getRepresentationSet(); for (size_t repIndex = 0; repIndex < repSet.size(); ++repIndex) { if (dynamic_cast<RESQML2_NS::Grid2dRepresentation*>(repSet[repIndex]) != nullptr) { result.push_back(static_cast<RESQML2_NS::Grid2dRepresentation*>(repSet[repIndex])); } } } } return result; } std::vector<RESQML2_NS::PolylineRepresentation *> DataObjectRepository::getHorizonPolylineRepSet() const { vector<RESQML2_NS::PolylineRepresentation *> result; const vector<RESQML2_NS::BoundaryFeature*> horizonSet = getHorizonSet(); for (size_t featureIndex = 0; featureIndex < horizonSet.size(); ++featureIndex) { const vector<RESQML2_NS::AbstractFeatureInterpretation *> interpSet = horizonSet[featureIndex]->getInterpretationSet(); for (size_t interpIndex = 0; interpIndex < interpSet.size(); ++interpIndex) { const vector<RESQML2_NS::AbstractRepresentation *> repSet = interpSet[interpIndex]->getRepresentationSet(); for (size_t repIndex = 0; repIndex < repSet.size(); ++repIndex) { if (dynamic_cast<RESQML2_NS::PolylineRepresentation*>(repSet[repIndex]) != nullptr) { result.push_back(static_cast<RESQML2_NS::PolylineRepresentation*>(repSet[repIndex])); } } } } return result; } std::vector<RESQML2_NS::PolylineSetRepresentation *> DataObjectRepository::getHorizonPolylineSetRepSet() const { vector<RESQML2_NS::PolylineSetRepresentation *> result; const vector<RESQML2_NS::BoundaryFeature*> horizonSet = getHorizonSet(); for (size_t featureIndex = 0; featureIndex < horizonSet.size(); ++featureIndex) { const vector<RESQML2_NS::AbstractFeatureInterpretation *> interpSet = horizonSet[featureIndex]->getInterpretationSet(); for (size_t interpIndex = 0; interpIndex < interpSet.size(); ++interpIndex) { const vector<RESQML2_NS::AbstractRepresentation *> repSet = interpSet[interpIndex]->getRepresentationSet(); for (size_t repIndex = 0; repIndex < repSet.size(); ++repIndex) { if (dynamic_cast<RESQML2_NS::PolylineSetRepresentation*>(repSet[repIndex]) != nullptr) { result.push_back(static_cast<RESQML2_NS::PolylineSetRepresentation*>(repSet[repIndex])); } } } } return result; } vector<RESQML2_NS::TriangulatedSetRepresentation *> DataObjectRepository::getHorizonTriangulatedSetRepSet() const { vector<RESQML2_NS::TriangulatedSetRepresentation *> result; const vector<RESQML2_NS::BoundaryFeature*> horizonSet = getHorizonSet(); for (size_t featureIndex = 0; featureIndex < horizonSet.size(); ++featureIndex) { const vector<RESQML2_NS::AbstractFeatureInterpretation *> interpSet = horizonSet[featureIndex]->getInterpretationSet(); for (size_t interpIndex = 0; interpIndex < interpSet.size(); ++interpIndex) { const vector<RESQML2_NS::AbstractRepresentation *> repSet = interpSet[interpIndex]->getRepresentationSet(); for (size_t repIndex = 0; repIndex < repSet.size(); ++repIndex) { if (dynamic_cast<RESQML2_NS::TriangulatedSetRepresentation*>(repSet[repIndex]) != nullptr) { result.push_back(static_cast<RESQML2_NS::TriangulatedSetRepresentation*>(repSet[repIndex])); } } } } return result; } std::vector<RESQML2_NS::TriangulatedSetRepresentation*> DataObjectRepository::getAllTriangulatedSetRepSet() const { return getDataObjects<RESQML2_NS::TriangulatedSetRepresentation>(); } std::vector<RESQML2_NS::Grid2dRepresentation*> DataObjectRepository::getAllGrid2dRepresentationSet() const { return getDataObjects<RESQML2_NS::Grid2dRepresentation>(); } std::vector<RESQML2_NS::PolylineSetRepresentation*> DataObjectRepository::getAllPolylineSetRepSet() const { return getDataObjects<RESQML2_NS::PolylineSetRepresentation>(); } namespace { bool isClassified(RESQML2_NS::TriangulatedSetRepresentation* tsr) { RESQML2_NS::AbstractFeatureInterpretation const * const interp = tsr->getInterpretation(); if (interp == nullptr) { return false; } if (!interp->isPartial()) { if (dynamic_cast<RESQML2_NS::FaultInterpretation const*>(interp) == nullptr && dynamic_cast<RESQML2_NS::HorizonInterpretation const*>(interp) == nullptr) { return false; } } else { const std::string contentType = tsr->getInterpretationDor().getContentType(); if (contentType.find("Horizon") == string::npos && contentType.find("Fault") == string::npos) { return false; } } return true; } } std::vector<RESQML2_NS::TriangulatedSetRepresentation*> DataObjectRepository::getUnclassifiedTriangulatedSetRepSet() const { std::vector<RESQML2_NS::TriangulatedSetRepresentation*> result = getDataObjects<RESQML2_NS::TriangulatedSetRepresentation>(); result.erase(std::remove_if(result.begin(), result.end(), isClassified), result.end()); return result; } std::vector<RESQML2_NS::AbstractSeismicLineFeature*> DataObjectRepository::getSeismicLineSet() const { return getDataObjects<RESQML2_NS::AbstractSeismicLineFeature>(); } std::vector<RESQML2_NS::WellboreFeature*> DataObjectRepository::getWellboreSet() const { return getDataObjects<RESQML2_NS::WellboreFeature>(); } vector<RESQML2_NS::WellboreTrajectoryRepresentation *> DataObjectRepository::getWellboreTrajectoryRepresentationSet() const { vector<RESQML2_NS::WellboreTrajectoryRepresentation *> result; const std::vector<RESQML2_NS::WellboreFeature*> wellboreSet = getWellboreSet(); for (size_t featureIndex = 0; featureIndex < wellboreSet.size(); ++featureIndex) { const std::vector<RESQML2_NS::AbstractFeatureInterpretation *> interpSet = wellboreSet[featureIndex]->getInterpretationSet(); for (size_t interpIndex = 0; interpIndex < interpSet.size(); ++interpIndex) { const std::vector<RESQML2_NS::AbstractRepresentation *> repSet = interpSet[interpIndex]->getRepresentationSet(); for (size_t repIndex = 0; repIndex < repSet.size(); ++repIndex) { if (dynamic_cast<RESQML2_NS::WellboreTrajectoryRepresentation*>(repSet[repIndex]) != nullptr) { result.push_back(static_cast<RESQML2_NS::WellboreTrajectoryRepresentation*>(repSet[repIndex])); } } } } return result; } vector<RESQML2_NS::DeviationSurveyRepresentation *> DataObjectRepository::getDeviationSurveyRepresentationSet() const { vector<RESQML2_NS::DeviationSurveyRepresentation *> result; const std::vector<RESQML2_NS::WellboreFeature*> wellboreSet = getWellboreSet(); for (size_t featureIndex = 0; featureIndex < wellboreSet.size(); ++featureIndex) { const std::vector<RESQML2_NS::AbstractFeatureInterpretation *> interpSet = wellboreSet[featureIndex]->getInterpretationSet(); for (size_t interpIndex = 0; interpIndex < interpSet.size(); ++interpIndex) { const std::vector<RESQML2_NS::AbstractRepresentation *> repSet = interpSet[interpIndex]->getRepresentationSet(); for (size_t repIndex = 0; repIndex < repSet.size(); ++repIndex) { if (dynamic_cast<RESQML2_NS::DeviationSurveyRepresentation*>(repSet[repIndex]) != nullptr) { result.push_back(static_cast<RESQML2_NS::DeviationSurveyRepresentation*>(repSet[repIndex])); } } } } return result; } std::vector<RESQML2_NS::RepresentationSetRepresentation*> DataObjectRepository::getRepresentationSetRepresentationSet() const { return getDataObjects<RESQML2_NS::RepresentationSetRepresentation>(); } std::vector<RESQML2_NS::PolylineRepresentation*> DataObjectRepository::getAllPolylineRepresentationSet() const { return getDataObjects<RESQML2_NS::PolylineRepresentation>(); } namespace { bool isSeismicOrFaciesLine(RESQML2_NS::PolylineRepresentation* pr) { return pr->isASeismicLine() || pr->isAFaciesLine(); } } std::vector<RESQML2_NS::PolylineRepresentation*> DataObjectRepository::getSeismicLinePolylineRepSet() const { std::vector<RESQML2_NS::PolylineRepresentation*> result = getDataObjects<RESQML2_NS::PolylineRepresentation>(); result.erase(std::remove_if(result.begin(), result.end(), std::not1(std::ptr_fun(isSeismicOrFaciesLine))), result.end()); return result; } std::vector<RESQML2_NS::AbstractIjkGridRepresentation*> DataObjectRepository::getIjkGridRepresentationSet() const { return getDataObjects<RESQML2_NS::AbstractIjkGridRepresentation>(); } std::vector<RESQML2_NS::IjkGridParametricRepresentation*> DataObjectRepository::getIjkGridParametricRepresentationSet() const { return getDataObjects<RESQML2_NS::IjkGridParametricRepresentation>(); } std::vector<RESQML2_NS::IjkGridExplicitRepresentation*> DataObjectRepository::getIjkGridExplicitRepresentationSet() const { return getDataObjects<RESQML2_NS::IjkGridExplicitRepresentation>(); } namespace { bool isSeismicOrFaciesCube(RESQML2_NS::IjkGridLatticeRepresentation* Ijkglr) { return Ijkglr->isASeismicCube() || Ijkglr->isAFaciesCube(); } } vector<RESQML2_NS::IjkGridLatticeRepresentation*> DataObjectRepository::getIjkSeismicCubeGridRepresentationSet() const { std::vector<RESQML2_NS::IjkGridLatticeRepresentation*> result = getDataObjects<RESQML2_NS::IjkGridLatticeRepresentation>(); result.erase(std::remove_if(result.begin(), result.end(), std::not1(std::ptr_fun(isSeismicOrFaciesCube))), result.end()); return result; } std::vector<RESQML2_NS::UnstructuredGridRepresentation*> DataObjectRepository::getUnstructuredGridRepresentationSet() const { return getDataObjects<RESQML2_NS::UnstructuredGridRepresentation>(); } std::vector<RESQML2_NS::CulturalFeature*> DataObjectRepository::getCulturalSet() const { return getDataObjects<RESQML2_NS::CulturalFeature>(); } std::vector<RESQML2_NS::Model*> DataObjectRepository::getModelSet() const { return getDataObjects<RESQML2_NS::Model>(); } std::vector<EML2_NS::TimeSeries*> DataObjectRepository::getTimeSeriesSet() const { return getDataObjects<EML2_NS::TimeSeries>(); } std::vector<RESQML2_NS::SubRepresentation*> DataObjectRepository::getSubRepresentationSet() const { return getDataObjects<RESQML2_NS::SubRepresentation>(); } std::vector<RESQML2_NS::PointSetRepresentation*> DataObjectRepository::getPointSetRepresentationSet() const { return getDataObjects<RESQML2_NS::PointSetRepresentation>(); } std::vector<EML2_NS::AbstractHdfProxy*> DataObjectRepository::getHdfProxySet() const { return getDataObjects<EML2_NS::AbstractHdfProxy>(); } std::vector<RESQML2_NS::StreamlinesFeature*> DataObjectRepository::getStreamlinesFeatureSet() const { return getDataObjects<RESQML2_NS::StreamlinesFeature>(); } std::vector<RESQML2_NS::StreamlinesRepresentation*> DataObjectRepository::getStreamlinesRepresentationSet() const { return getDataObjects<RESQML2_NS::StreamlinesRepresentation>(); } COMMON_NS::AbstractObject* DataObjectRepository::getResqml2_0_1WrapperFromGsoapContext(const std::string & resqmlContentType) { COMMON_NS::AbstractObject* wrapper = nullptr; if CHECK_AND_GET_RESQML_2_0_1_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(MdDatum) else if CHECK_AND_GET_RESQML_2_0_1_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(Activity) else if CHECK_AND_GET_RESQML_2_0_1_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(ActivityTemplate) else if CHECK_AND_GET_RESQML_2_0_1_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(SeismicLatticeFeature) else if CHECK_AND_GET_RESQML_2_0_1_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(SeismicLineFeature) else if CHECK_AND_GET_RESQML_2_0_1_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(SeismicLineSetFeature) else if CHECK_AND_GET_RESQML_2_0_1_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(FrontierFeature) else if CHECK_AND_GET_RESQML_2_0_1_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(LocalDepth3dCrs) else if CHECK_AND_GET_RESQML_2_0_1_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(LocalTime3dCrs) else if CHECK_AND_GET_RESQML_2_0_1_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(TectonicBoundaryFeature) else if CHECK_AND_GET_RESQML_2_0_1_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(GeneticBoundaryFeature) else if CHECK_AND_GET_RESQML_2_0_1_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(BoundaryFeature) else if CHECK_AND_GET_RESQML_2_0_1_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(WellboreFeature) else if CHECK_AND_GET_RESQML_2_0_1_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(StratigraphicUnitFeature) else if CHECK_AND_GET_RESQML_2_0_1_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(StratigraphicColumn) else if CHECK_AND_GET_RESQML_2_0_1_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(GenericFeatureInterpretation) else if CHECK_AND_GET_RESQML_2_0_1_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(BoundaryFeatureInterpretation) else if CHECK_AND_GET_RESQML_2_0_1_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(WellboreInterpretation) else if CHECK_AND_GET_RESQML_2_0_1_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(FaultInterpretation) else if CHECK_AND_GET_RESQML_2_0_1_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(HorizonInterpretation) else if CHECK_AND_GET_RESQML_2_0_1_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(StratigraphicUnitInterpretation) else if CHECK_AND_GET_RESQML_2_0_1_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(StratigraphicColumnRankInterpretation) else if (resqmlContentType.compare(RESQML2_NS::StratigraphicOccurrenceInterpretation::XML_TAG) == 0) { GET_RESQML_2_0_1_GSOAP_PROXY_FROM_GSOAP_CONTEXT(StratigraphicOccurrenceInterpretation) if (!read->GeologicUnitIndex.empty() && read->GeologicUnitIndex.front()->Unit->ContentType.find("RockFluidUnitInterpretation")) { wrapper = new RESQML2_0_1_NS::RockFluidOrganizationInterpretation(read); } else { wrapper = new RESQML2_0_1_NS::StratigraphicOccurrenceInterpretation(read); } } else if CHECK_AND_GET_RESQML_2_0_1_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(WellboreFrameRepresentation) else if CHECK_AND_GET_RESQML_2_0_1_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(WellboreMarkerFrameRepresentation) else if CHECK_AND_GET_RESQML_2_0_1_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(WellboreTrajectoryRepresentation) else if CHECK_AND_GET_RESQML_2_0_1_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(PolylineSetRepresentation) else if CHECK_AND_GET_RESQML_2_0_1_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(PointSetRepresentation) else if CHECK_AND_GET_RESQML_2_0_1_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(PlaneSetRepresentation) else if CHECK_AND_GET_RESQML_2_0_1_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(PolylineRepresentation) else if CHECK_AND_GET_RESQML_2_0_1_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(Grid2dRepresentation) else if CHECK_AND_GET_RESQML_2_0_1_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(TriangulatedSetRepresentation) else if CHECK_AND_GET_RESQML_2_0_1_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(BlockedWellboreRepresentation) else if CHECK_AND_GET_RESQML_2_0_1_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(DeviationSurveyRepresentation) else if (resqmlContentType.compare(RESQML2_NS::AbstractIjkGridRepresentation::XML_TAG) == 0) { GET_RESQML_2_0_1_GSOAP_PROXY_FROM_GSOAP_CONTEXT(IjkGridRepresentation) if (read->Geometry != nullptr) { switch (read->Geometry->Points->soap_type()) { case SOAP_TYPE_gsoap_resqml2_0_1_resqml20__Point3dHdf5Array: wrapper = new RESQML2_0_1_NS::IjkGridExplicitRepresentation(read); break; case SOAP_TYPE_gsoap_resqml2_0_1_resqml20__Point3dParametricArray: wrapper = new RESQML2_0_1_NS::IjkGridParametricRepresentation(read); break; case SOAP_TYPE_gsoap_resqml2_0_1_resqml20__Point3dLatticeArray: wrapper = new RESQML2_0_1_NS::IjkGridLatticeRepresentation(read); break; } } else { wrapper = new RESQML2_0_1_NS::IjkGridNoGeometryRepresentation(read); } } else if (resqmlContentType.compare(RESQML2_NS::AbstractIjkGridRepresentation::XML_TAG_TRUNCATED) == 0) { GET_RESQML_2_0_1_GSOAP_PROXY_FROM_GSOAP_CONTEXT(TruncatedIjkGridRepresentation) if (read->Geometry != nullptr) { switch (read->Geometry->Points->soap_type()) { case SOAP_TYPE_gsoap_resqml2_0_1_resqml20__Point3dHdf5Array: wrapper = new RESQML2_0_1_NS::IjkGridExplicitRepresentation(read); break; case SOAP_TYPE_gsoap_resqml2_0_1_resqml20__Point3dParametricArray: wrapper = new RESQML2_0_1_NS::IjkGridParametricRepresentation(read); break; case SOAP_TYPE_gsoap_resqml2_0_1_resqml20__Point3dLatticeArray: wrapper = new RESQML2_0_1_NS::IjkGridLatticeRepresentation(read); break; } } else { wrapper = new RESQML2_0_1_NS::IjkGridNoGeometryRepresentation(read); } } else if CHECK_AND_GET_RESQML_2_0_1_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(UnstructuredGridRepresentation) else if CHECK_AND_GET_RESQML_2_0_1_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(PropertyKind) else if CHECK_AND_GET_RESQML_2_0_1_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(PropertySet) else if CHECK_AND_GET_RESQML_2_0_1_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(ContinuousProperty) else if CHECK_AND_GET_RESQML_2_0_1_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(CategoricalProperty) else if CHECK_AND_GET_RESQML_2_0_1_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(DiscreteProperty) else if CHECK_AND_GET_RESQML_2_0_1_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(PointsProperty) else if CHECK_AND_GET_RESQML_2_0_1_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(CommentProperty) else if CHECK_AND_GET_RESQML_2_0_1_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(DoubleTableLookup) else if CHECK_AND_GET_RESQML_2_0_1_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(StringTableLookup) else if CHECK_AND_GET_RESQML_2_0_1_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(EarthModelInterpretation) else if CHECK_AND_GET_RESQML_2_0_1_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(OrganizationFeature) else if CHECK_AND_GET_RESQML_2_0_1_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(StructuralOrganizationInterpretation) else if CHECK_AND_GET_RESQML_2_0_1_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(FluidBoundaryFeature) else if CHECK_AND_GET_RESQML_2_0_1_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(SubRepresentation) else if CHECK_AND_GET_RESQML_2_0_1_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(GridConnectionSetRepresentation) else if CHECK_AND_GET_RESQML_2_0_1_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(TimeSeries) else if CHECK_AND_GET_RESQML_2_0_1_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(RepresentationSetRepresentation) else if CHECK_AND_GET_RESQML_2_0_1_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(NonSealedSurfaceFrameworkRepresentation) else if CHECK_AND_GET_RESQML_2_0_1_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(SealedSurfaceFrameworkRepresentation) else if CHECK_AND_GET_RESQML_2_0_1_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(SealedVolumeFrameworkRepresentation) else if CHECK_AND_GET_RESQML_2_0_1_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(GeobodyFeature) else if CHECK_AND_GET_RESQML_2_0_1_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(GeobodyBoundaryInterpretation) else if CHECK_AND_GET_RESQML_2_0_1_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(GeobodyInterpretation) else if CHECK_AND_GET_RESQML_2_0_1_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(RockFluidUnitInterpretation) else if CHECK_AND_GET_RESQML_2_0_1_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(RockFluidUnitFeature) else if CHECK_AND_GET_RESQML_2_0_1_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(StreamlinesFeature) else if CHECK_AND_GET_RESQML_2_0_1_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(StreamlinesRepresentation) else if (resqmlContentType.compare(EML2_NS::EpcExternalPartReference::XML_TAG) == 0) { throw invalid_argument("Please handle this type outside this method since it is not only XML related."); } return wrapper; } COMMON_NS::AbstractObject* DataObjectRepository::getWitsml2_0WrapperFromGsoapContext(const std::string & datatype) { COMMON_NS::AbstractObject* wrapper = nullptr; if CHECK_AND_GET_WITSML_2_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(WITSML2_0_NS, Well, gsoap_eml2_1) else if CHECK_AND_GET_WITSML_2_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(WITSML2_0_NS, WellCompletion, gsoap_eml2_1) else if CHECK_AND_GET_WITSML_2_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(WITSML2_0_NS, Wellbore, gsoap_eml2_1) else if CHECK_AND_GET_WITSML_2_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(WITSML2_0_NS, WellboreCompletion, gsoap_eml2_1) else if CHECK_AND_GET_WITSML_2_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(WITSML2_0_NS, WellboreGeometry, gsoap_eml2_1) else if CHECK_AND_GET_WITSML_2_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(WITSML2_0_NS, WellboreMarker, gsoap_eml2_1) else if CHECK_AND_GET_WITSML_2_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(WITSML2_0_NS, Trajectory, gsoap_eml2_1) else if CHECK_AND_GET_WITSML_2_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(WITSML2_0_NS, Log, gsoap_eml2_1) else if CHECK_AND_GET_WITSML_2_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(WITSML2_0_NS, ChannelSet, gsoap_eml2_1) else if CHECK_AND_GET_WITSML_2_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(WITSML2_0_NS, Channel, gsoap_eml2_1) return wrapper; } COMMON_NS::AbstractObject* DataObjectRepository::getProdml2_1WrapperFromGsoapContext(const std::string & datatype) { COMMON_NS::AbstractObject* wrapper = nullptr; if CHECK_AND_GET_PRODML_2_1_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(PRODML2_1_NS, FluidSystem, gsoap_eml2_2) else if CHECK_AND_GET_PRODML_2_1_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(PRODML2_1_NS, FluidCharacterization, gsoap_eml2_2) else if CHECK_AND_GET_PRODML_2_1_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(PRODML2_1_NS, TimeSeriesData, gsoap_eml2_2) return wrapper; } /* COMMON_NS::AbstractObject* DataObjectRepository::getWitsml2_1WrapperFromGsoapContext(const std::string & datatype) { COMMON_NS::AbstractObject* wrapper = nullptr; #if WITH_WITSML2_1 if CHECK_AND_GET_WITSML_2_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(WITSML2_1_NS, ToolErrorModel, gsoap_eml2_2) else if CHECK_AND_GET_WITSML_2_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(WITSML2_1_NS, ToolErrorModelDictionary, gsoap_eml2_2) else if CHECK_AND_GET_WITSML_2_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(WITSML2_1_NS, ErrorTerm, gsoap_eml2_2) else if CHECK_AND_GET_WITSML_2_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(WITSML2_1_NS, ErrorTermDictionary, gsoap_eml2_2) else if CHECK_AND_GET_WITSML_2_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(WITSML2_1_NS, WeightingFunction, gsoap_eml2_2) else if CHECK_AND_GET_WITSML_2_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(WITSML2_1_NS, WeightingFunctionDictionary, gsoap_eml2_2) #endif return wrapper; } */ #if WITH_RESQML2_2 COMMON_NS::AbstractObject* DataObjectRepository::getResqml2_2WrapperFromGsoapContext(const std::string& resqmlContentType) { COMMON_NS::AbstractObject* wrapper = nullptr; if CHECK_AND_GET_RESQML_2_2_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(BoundaryFeature) else if CHECK_AND_GET_RESQML_2_2_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(BoundaryFeatureInterpretation) else if CHECK_AND_GET_RESQML_2_2_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(CategoricalProperty) else if CHECK_AND_GET_RESQML_2_2_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(CmpLineFeature) else if CHECK_AND_GET_RESQML_2_2_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(CommentProperty) else if CHECK_AND_GET_RESQML_2_2_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(ContinuousProperty) else if CHECK_AND_GET_RESQML_2_2_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(ContinuousColorMap) else if CHECK_AND_GET_RESQML_2_2_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(CulturalFeature) else if CHECK_AND_GET_RESQML_2_2_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(DeviationSurveyRepresentation) else if CHECK_AND_GET_RESQML_2_2_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(DiscreteProperty) else if CHECK_AND_GET_RESQML_2_2_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(DiscreteColorMap) else if CHECK_AND_GET_RESQML_2_2_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(DoubleTableLookup) else if CHECK_AND_GET_RESQML_2_2_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(EarthModelInterpretation) else if CHECK_AND_GET_RESQML_2_2_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(FaultInterpretation) else if CHECK_AND_GET_RESQML_2_2_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(FluidBoundaryInterpretation) else if CHECK_AND_GET_RESQML_2_2_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(GenericFeatureInterpretation) else if CHECK_AND_GET_RESQML_2_2_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(GeobodyBoundaryInterpretation) else if CHECK_AND_GET_RESQML_2_2_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(GeobodyInterpretation) else if CHECK_AND_GET_RESQML_2_2_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(Grid2dRepresentation) else if CHECK_AND_GET_RESQML_2_2_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(GridConnectionSetRepresentation) else if CHECK_AND_GET_RESQML_2_2_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(HorizonInterpretation) else if (resqmlContentType.compare(RESQML2_NS::AbstractIjkGridRepresentation::XML_TAG) == 0) { GET_RESQML_2_2_GSOAP_PROXY_FROM_GSOAP_CONTEXT(IjkGridRepresentation) if (read->Geometry != nullptr) { switch (read->Geometry->Points->soap_type()) { case SOAP_TYPE_gsoap_eml2_3_resqml22__Point3dExternalArray: wrapper = new RESQML2_2_NS::IjkGridExplicitRepresentation(read); break; case SOAP_TYPE_gsoap_eml2_3_resqml22__Point3dParametricArray: wrapper = new RESQML2_2_NS::IjkGridParametricRepresentation(read); break; case SOAP_TYPE_gsoap_eml2_3_resqml22__Point3dLatticeArray: wrapper = new RESQML2_2_NS::IjkGridLatticeRepresentation(read); break; } } else { wrapper = new RESQML2_2_NS::IjkGridNoGeometryRepresentation(read); } } else if (resqmlContentType.compare(RESQML2_NS::AbstractIjkGridRepresentation::XML_TAG_TRUNCATED) == 0) { GET_RESQML_2_2_GSOAP_PROXY_FROM_GSOAP_CONTEXT(TruncatedIjkGridRepresentation) if (read->Geometry != nullptr) { switch (read->Geometry->Points->soap_type()) { case SOAP_TYPE_gsoap_eml2_3_resqml22__Point3dExternalArray: wrapper = new RESQML2_2_NS::IjkGridExplicitRepresentation(read); break; case SOAP_TYPE_gsoap_eml2_3_resqml22__Point3dParametricArray: wrapper = new RESQML2_2_NS::IjkGridParametricRepresentation(read); break; case SOAP_TYPE_gsoap_eml2_3_resqml22__Point3dLatticeArray: wrapper = new RESQML2_2_NS::IjkGridLatticeRepresentation(read); break; } } else { wrapper = new RESQML2_2_NS::IjkGridNoGeometryRepresentation(read); } } else if CHECK_AND_GET_RESQML_2_2_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(LocalDepth3dCrs) else if CHECK_AND_GET_RESQML_2_2_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(LocalTime3dCrs) else if CHECK_AND_GET_RESQML_2_2_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(MdDatum) else if CHECK_AND_GET_RESQML_2_2_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(Model) else if CHECK_AND_GET_RESQML_2_2_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(NonSealedSurfaceFrameworkRepresentation) else if CHECK_AND_GET_RESQML_2_2_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(PlaneSetRepresentation) else if CHECK_AND_GET_RESQML_2_2_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(PointSetRepresentation) else if CHECK_AND_GET_RESQML_2_2_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(PointsProperty) else if CHECK_AND_GET_RESQML_2_2_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(PolylineRepresentation) else if CHECK_AND_GET_RESQML_2_2_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(PolylineSetRepresentation) else if CHECK_AND_GET_RESQML_2_2_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(PropertySet) else if CHECK_AND_GET_RESQML_2_2_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(RepresentationSetRepresentation) else if CHECK_AND_GET_RESQML_2_2_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(RockFluidOrganizationInterpretation) else if CHECK_AND_GET_RESQML_2_2_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(RockFluidUnitInterpretation) else if CHECK_AND_GET_RESQML_2_2_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(RockVolumeFeature) else if CHECK_AND_GET_RESQML_2_2_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(SealedSurfaceFrameworkRepresentation) else if CHECK_AND_GET_RESQML_2_2_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(SealedVolumeFrameworkRepresentation) else if CHECK_AND_GET_RESQML_2_2_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(SeismicLatticeFeature) else if CHECK_AND_GET_RESQML_2_2_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(SeismicLineSetFeature) else if CHECK_AND_GET_RESQML_2_2_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(SeismicWellboreFrameRepresentation) else if CHECK_AND_GET_RESQML_2_2_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(ShotPointLineFeature) else if CHECK_AND_GET_RESQML_2_2_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(StratigraphicColumn) else if CHECK_AND_GET_RESQML_2_2_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(StratigraphicColumnRankInterpretation) else if CHECK_AND_GET_RESQML_2_2_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(StratigraphicOccurrenceInterpretation) else if CHECK_AND_GET_RESQML_2_2_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(StratigraphicUnitInterpretation) else if CHECK_AND_GET_RESQML_2_2_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(StreamlinesFeature) else if CHECK_AND_GET_RESQML_2_2_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(StreamlinesRepresentation) else if CHECK_AND_GET_RESQML_2_2_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(StringTableLookup) else if CHECK_AND_GET_RESQML_2_2_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(StructuralOrganizationInterpretation) else if CHECK_AND_GET_RESQML_2_2_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(SubRepresentation) else if CHECK_AND_GET_RESQML_2_2_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(TriangulatedSetRepresentation) else if CHECK_AND_GET_RESQML_2_2_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(UnstructuredGridRepresentation) else if CHECK_AND_GET_RESQML_2_2_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(WellboreFeature) else if CHECK_AND_GET_RESQML_2_2_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(WellboreFrameRepresentation) else if CHECK_AND_GET_RESQML_2_2_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(WellboreInterpretation) else if CHECK_AND_GET_RESQML_2_2_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(WellboreMarkerFrameRepresentation) else if CHECK_AND_GET_RESQML_2_2_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(WellboreTrajectoryRepresentation) return wrapper; } #else COMMON_NS::AbstractObject* DataObjectRepository::getResqml2_2WrapperFromGsoapContext(const std::string&) { return nullptr; } #endif COMMON_NS::AbstractObject* DataObjectRepository::getEml2_1WrapperFromGsoapContext(const std::string & datatype) { COMMON_NS::AbstractObject* wrapper = nullptr; if CHECK_AND_GET_EML_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(EML2_1_NS, PropertyKind, gsoap_eml2_1, eml21) return wrapper; } #if WITH_RESQML2_2 COMMON_NS::AbstractObject* DataObjectRepository::getEml2_3WrapperFromGsoapContext(const std::string & datatype) { COMMON_NS::AbstractObject* wrapper = nullptr; if CHECK_AND_GET_EML_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(EML2_3_NS, Activity, gsoap_eml2_3, eml23) else if CHECK_AND_GET_EML_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(EML2_3_NS, ActivityTemplate, gsoap_eml2_3, eml23) else if CHECK_AND_GET_EML_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(EML2_3_NS, GraphicalInformationSet, gsoap_eml2_3, eml23) else if CHECK_AND_GET_EML_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(EML2_3_NS, PropertyKind, gsoap_eml2_3, eml23) else if CHECK_AND_GET_EML_FESAPI_WRAPPER_FROM_GSOAP_CONTEXT(EML2_3_NS, TimeSeries, gsoap_eml2_3, eml23) return wrapper; } #else COMMON_NS::AbstractObject* DataObjectRepository::getEml2_3WrapperFromGsoapContext(const std::string&) { return nullptr; } #endif int DataObjectRepository::getGsoapErrorCode() const { return gsoapContext->error; } std::string DataObjectRepository::getGsoapErrorMessage() const { ostringstream oss; soap_stream_fault(gsoapContext, oss); return oss.str(); } void DataObjectRepository::registerDataFeeder(COMMON_NS::DataFeeder * dataFeeder) { dataFeeders.push_back(dataFeeder); } void DataObjectRepository::setHdfProxyFactory(COMMON_NS::HdfProxyFactory * factory) { if (factory == nullptr) { throw invalid_argument("You cannot set a NULL HDF proxy factory."); } hdfProxyFactory.reset(factory); } COMMON_NS::AbstractObject* DataObjectRepository::resolvePartial(COMMON_NS::AbstractObject * partialObj) { for (size_t i = 0; i < dataFeeders.size(); ++i) { const std::string xml = dataFeeders[i]->resolvePartial(partialObj); if (!xml.empty()) { return addOrReplaceGsoapProxy(xml, partialObj->getContentType()); } } return nullptr; } gsoap_resqml2_0_1::eml20__DataObjectReference* DataObjectRepository::createDor(const std::string & guid, const std::string & title, const std::string & version) { gsoap_resqml2_0_1::eml20__DataObjectReference* dor = gsoap_resqml2_0_1::soap_new_eml20__DataObjectReference(gsoapContext); if (guid.empty()) { boost::uuids::random_generator gen; dor->UUID = boost::uuids::to_string(gen()); } else { dor->UUID = guid; } dor->Title = title.empty() ? "unknown" : title; if (!version.empty()) { dor->VersionString = gsoap_resqml2_0_1::soap_new_std__string(gsoapContext); dor->VersionString->assign(version); } return dor; }
47.394344
265
0.807182
[ "geometry", "object", "vector", "model" ]
3a0c9a7f67823fc9444e6bfd2f84a9d87a639185
462
hpp
C++
include/wge/core/instance.hpp
clman94/Wolf-Gang-Engine
52fa71d6be1fb940a0998f29b4e0ce631e624b25
[ "MIT" ]
5
2016-09-18T01:39:19.000Z
2020-05-24T02:37:45.000Z
include/wge/core/instance.hpp
clman94/Wolf-Gang-Engine
52fa71d6be1fb940a0998f29b4e0ce631e624b25
[ "MIT" ]
25
2017-02-11T21:13:24.000Z
2020-06-24T08:48:33.000Z
include/wge/core/instance.hpp
clman94/Wolf-Gang-Engine
52fa71d6be1fb940a0998f29b4e0ce631e624b25
[ "MIT" ]
2
2017-04-29T22:12:16.000Z
2018-04-05T10:35:25.000Z
#pragma once #include <wge/core/asset.hpp> #include <wge/core/object.hpp> #include <wge/core/asset_manager.hpp> #include <wge/math/transform.hpp> namespace wge::core { struct instantiation_options { std::string name; math::transform transform; asset_id instantiable_asset_id; asset_id creation_script_id; }; void instantiate_asset(const instantiation_options& pOptions, object pObject, const core::asset_manager& pAsset_mgr); } // namespace wge::core
19.25
61
0.779221
[ "object", "transform" ]
3a0f67791c700e14deb0c3c3b84e50c36f44d95d
528
cpp
C++
TestingModules/multipleAssertionInTest.cpp
eduardorasgado/CppUnitTestingWinter2018
361ec756ef0c7d709b9aacf1448ae037cfe763d6
[ "MIT" ]
null
null
null
TestingModules/multipleAssertionInTest.cpp
eduardorasgado/CppUnitTestingWinter2018
361ec756ef0c7d709b9aacf1448ae037cfe763d6
[ "MIT" ]
null
null
null
TestingModules/multipleAssertionInTest.cpp
eduardorasgado/CppUnitTestingWinter2018
361ec756ef0c7d709b9aacf1448ae037cfe763d6
[ "MIT" ]
null
null
null
// // Created by cheetos on 15/12/18. // #include "../dependencies/catch.h" /* * MULTIPLE ASSERTIONS IN ONE TEST * * Recomendations: * -Split to multiple Tests * -Use CHECK * Override operator == * Compare Collections // comparing using std collections * * */ TEST_CASE("<Check> 3 types of data in the custom vector", "[DATATYPE]") { CHECK(2 == 1); CHECK("n" == "n"); std::vector<int> myv{1,2,3,4,5,6}; std::vector<float> myv2{1.2,1.3,1.4,1.5,1.6,1.7}; CHECK(myv.size() == myv2.size()); }
18.206897
71
0.598485
[ "vector" ]
3a106bac9d67829e5391047b4420a10a9d9dacc0
15,659
cc
C++
Alignment/CocoaModel/src/Entry.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
852
2015-01-11T21:03:51.000Z
2022-03-25T21:14:00.000Z
Alignment/CocoaModel/src/Entry.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
30,371
2015-01-02T00:14:40.000Z
2022-03-31T23:26:05.000Z
Alignment/CocoaModel/src/Entry.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
3,240
2015-01-02T05:53:18.000Z
2022-03-31T17:24:21.000Z
// COCOA class implementation file //Id: Entry.cc //CAT: Model // // History: v1.0 // Pedro Arce #include "Alignment/CocoaModel/interface/Entry.h" #include "Alignment/CocoaModel/interface/Model.h" #include "Alignment/CocoaModel/interface/OpticalObject.h" #include "Alignment/CocoaUtilities/interface/ALIFileIn.h" #include "Alignment/CocoaUtilities/interface/ALIUtils.h" #include "Alignment/CocoaUtilities/interface/GlobalOptionMgr.h" #include "Alignment/CocoaModel/interface/ParameterMgr.h" #include "Alignment/CocoaModel/interface/EntryMgr.h" #include "Alignment/CocoaModel/interface/EntryData.h" #include <cstdlib> //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ //@@ Constructor //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ Entry::Entry(const ALIstring& type) : type_(type), fitPos_(-1) { // std::cout << "entry" << std::endl; //---------- Set displacement by fitting to zero valueDisplacementByFitting_ = 0.; if (ALIUtils::debug >= 5) std::cout << this << " theValueDisplacementByFitting set " << valueDisplacementByFitting_ << std::endl; } //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ void Entry::fill(const std::vector<ALIstring>& wordlist) { ALIdouble byshort; GlobalOptionMgr* gomgr = GlobalOptionMgr::getInstance(); gomgr->getGlobalOptionValue("reportOutEntriesByShortName", byshort); //----- Check format of input file if (ALIUtils::debug >= 4) std::cout << "@@@ Filling entry: " << name() << std::endl; //--- Check there are 4 attributes if (wordlist.size() != 4) { ALIFileIn::getInstance(Model::SDFName()).ErrorInLine(); ALIUtils::dumpVS(wordlist, " !!! Incorrect format for Entry:", std::cerr); std::cerr << std::endl << " There should be four words: name value sigma quality " << std::endl; exit(2); } EntryData* entryData; if (byshort == 0) { entryData = EntryMgr::getInstance()->findEntryByLongName(OptOCurrent()->longName(), name()); } else { entryData = EntryMgr::getInstance()->findEntryByShortName(OptOCurrent()->longName(), name()); } if (ALIUtils::debug >= 5) std::cout << " entryData " << entryData << " " << OptOCurrent()->longName() << " " << name() << std::endl; /*t if( name_ == "centre_R" || name_ == "centre_PHI" || name_ == "centre_THE" ){ if( EntryMgr::getInstance()->numberOfEntries() > 0 ) { std::cerr << "!!!!FATAL ERROR: Filling entry from 'report.out' while entry is in cylindrical or spherical coordinates is not supported yet. " << OptOCurrent()->name() << " " << name_ << std::endl; abort(); } } */ ALIdouble fre; gomgr->getGlobalOptionValue("reportOutReadValue", fre); if (entryData != nullptr && fre == 1) { // std::cout << OptOCurrent()->name() << " " << name_ << "call fillFromReportOutFileValue " << type_ << std::endl; fillFromReportOutFileValue(entryData); } else { // std::cout << OptOCurrent()->name() << " " << name_ << "call fillFromInputFileValue " << type_ << std::endl; fillFromInputFileValue(wordlist); } gomgr->getGlobalOptionValue("reportOutReadSigma", fre); if (entryData != nullptr && fre == 1) { fillFromReportOutFileSigma(entryData); } else { fillFromInputFileSigma(wordlist); } gomgr->getGlobalOptionValue("reportOutReadQuality", fre); if (entryData != nullptr && fre == 1) { fillFromReportOutFileQuality(entryData); } else { fillFromInputFileQuality(wordlist); } } //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ void Entry::fillFromInputFileValue(const std::vector<ALIstring>& wordlist) { //- ALIUtils::dumpVS( wordlist, " fillFromInputFileValue " ); //- ParameterMgr* parmgr = ParameterMgr::getInstance(); //---------- Translate parameter used for value_ ALIdouble val = 0.; if (!ALIUtils::IsNumber(wordlist[1])) { if (parmgr->getParameterValue(wordlist[1], val) == 0) { ALIFileIn::getInstance(Model::SDFName()).ErrorInLine(); std::cerr << "!!! parameter for value not found: " << wordlist[1].c_str() << std::endl; exit(2); } //d val *= ValueDimensionFactor(); } else { //d val = DimensionMgr()::getInstance()->extractValue( wordlist[1], ValueDimensionFactor() ); val = atof(wordlist[1].c_str()); } val *= ValueDimensionFactor(); if (ALIUtils::debug >= 4) { std::cout << "VALUE = " << val << " (ValueDimensionFactor= " << ValueDimensionFactor() << std::endl; } value_ = val; valueOriginalOriginal_ = value_; } void Entry::fillFromInputFileSigma(const std::vector<ALIstring>& wordlist) { ParameterMgr* parmgr = ParameterMgr::getInstance(); //---------- translate parameter used for sigma_ /* ALIdouble sig; char** endptr; sig = strtod( wordlist[2].c_str(), endptr ); // ALIint isNumber = sscanf(wordlist[2].c_str(),"%f",sig); if ( *endptr == wordlist[2].c_str() ) { // if ( !isNumber ) { */ ALIdouble sig = 0.; if (!ALIUtils::IsNumber(wordlist[2])) { if (parmgr->getParameterValue(wordlist[2], sig) == 0) { ALIFileIn::getInstance(Model::SDFName()).ErrorInLine(); // std::cerr << "!!! parameter for sigma not found: " << wordlist[2].c_str() << std::endl; std::cerr << "!!! parameter for sigma not found: " << wordlist[0] << " " << wordlist[1] << " " << wordlist[2] << std::endl; exit(2); } //d sig *= SigmaDimensionFactor(); //- std::cout << sig<< " valueparam " << wordlist[2] << std::endl; } else { //d sig = DimensionMgr()::getInstance()->extractValue( wordlist[2], ValueDimensionFactor() ); sig = atof(wordlist[2].c_str()); // for range studies, make all 'cal' entries 'fix' ALIdouble rs; GlobalOptionMgr* gomgr = GlobalOptionMgr::getInstance(); gomgr->getGlobalOptionValue("range_studies", rs); if (rs == 1) sig *= 1.E-6; //- std::cout << sig << " valuem " << wordlist[2] << std::endl; } sig *= SigmaDimensionFactor(); if (ALIUtils::debug >= 4) { std::cout << "SIGMA = " << sig << " (SigmaDimensionFactor= " << SigmaDimensionFactor() << std::endl; } sigma_ = sig; sigmaOriginalOriginal_ = sigma_; } //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ void Entry::fillFromInputFileQuality(const std::vector<ALIstring>& wordlist) { //---------- set _quality if (wordlist[3] == ALIstring("unk")) { quality_ = 2; } else if (wordlist[3] == ALIstring("cal")) { quality_ = 1; //t // for range studies, make all 'cal' entries 'fix' //t ALIdouble rs; //t Model::getGlobalOptionValue("range_studies", rs ); //t if(rs == 1) quality_ = 0; } else if (wordlist[3] == ALIstring("fix")) { quality_ = 0; } else { ALIFileIn::getInstance(Model::SDFName()).ErrorInLine(); std::cerr << " quality should be 'unk' or 'cal' or 'fix', instead of " << wordlist[3] << std::endl; exit(3); } //------ If sigma_ = 0 make quality_ 'fix' if (sigma_ == 0) { // std::cout << "SIG=0" << std::endl; quality_ = 0; } if (ALIUtils::debug >= 4) std::cout << OptOCurrent()->name() << " " << name() << " " << sigma_ << "QUALITY:" << quality_ << std::endl; sigmaOriginalOriginal_ = sigma_; } //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ //@@ Fill the attributes with values read from a 'report.out' file //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ void Entry::fillFromReportOutFileValue(EntryData* entryData) { value_ = entryData->valueOriginal(); //---- For extra entries, value is not in proper units, as the 'report.out' file does not have the type (length/angle/nodim) EntryMgr* entryMgr = EntryMgr::getInstance(); //- std::cout << OptOCurrent()->name() << " " << name_ << " fillFromReportOutFileValue " << type_ << std::endl; if (type_ == "centre" || type_ == "length") { value_ *= entryMgr->getDimOutLengthVal(); //set valueDisp as it will be used to displace entries entryData->setValueDisplacement(entryData->valueDisplacement() * entryMgr->getDimOutLengthVal()); if (ALIUtils::debug >= 5) std::cout << " fillFromReportOut " << OptOCurrent()->name() << " " << name() << "" << value_ << " disp " << entryData->valueDisplacement() * entryMgr->getDimOutLengthVal() << std::endl; } else if (type_ == "angles" || type_ == "angle") { value_ *= entryMgr->getDimOutAngleVal(); entryData->setValueDisplacement(entryData->valueDisplacement() * entryMgr->getDimOutAngleVal()); if (ALIUtils::debug >= 5) std::cout << " fillFromReportOut " << OptOCurrent()->name() << " " << name() << "" << value_ << " disp " << entryData->valueDisplacement() * entryMgr->getDimOutAngleVal() << std::endl; } valueOriginalOriginal_ = value_; } //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ void Entry::fillFromReportOutFileSigma(const EntryData* entryData) { sigma_ = entryData->sigma(); //---- For extra entries, value is not in proper units, as the 'report.out' file does not have the type (length/angle/nodim) EntryMgr* entryMgr = EntryMgr::getInstance(); if (type_ == "centre" || type_ == "length") { sigma_ *= entryMgr->getDimOutLengthSig(); //- std::cout << " fillFromReportOut " << value_ << " +- " << sigma_ << std::endl; } else if (type_ == "angles" || type_ == "angle") { sigma_ *= entryMgr->getDimOutAngleSig(); } sigmaOriginalOriginal_ = sigma_; } //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ void Entry::fillFromReportOutFileQuality(const EntryData* entryData) { quality_ = entryData->quality(); } //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ //@@ Fill the name (in derived classes is not simply calling setName) //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ void Entry::fillName(const ALIstring& name) { setName(name); } //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ //@@ Fill the attributes //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ void Entry::fillNull() { //- fillName( name ); value_ = 0.; valueOriginalOriginal_ = value_; sigma_ = 0.; sigmaOriginalOriginal_ = sigma_; quality_ = 0; } //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ //@@ Displace an extra entry (coordinate entries have their own classes) //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ void Entry::displace(ALIdouble disp) { if (ALIUtils::debug >= 9) std::cout << "ExtraEntry::Displace" << disp << std::endl; ALIuint entryNo = OptOCurrent()->extraEntryNo(name()); OptOCurrent()->displaceExtraEntry(entryNo, disp); } //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ //@@ Displace an extra entry Original value for iteratin in non linear fit (coordinate entries have their own classes) //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ void Entry::displaceOriginal(ALIdouble disp) { if (ALIUtils::debug >= 9) std::cout << "ExtraEntry::DisplaceOriginal" << disp << std::endl; ALIuint entryNo = OptOCurrent()->extraEntryNo(name()); OptOCurrent()->displaceExtraEntryOriginal(entryNo, disp); } //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ //@@ Displace an extra entry OriginalOriginal value for iteratin in non linear fit (coordinate entries have their own classes) //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ void Entry::displaceOriginalOriginal(ALIdouble disp) { if (ALIUtils::debug >= 9) std::cout << "ExtraEntry::DisplaceOriginalOriginal" << disp << std::endl; ALIuint entryNo = OptOCurrent()->extraEntryNo(name()); OptOCurrent()->displaceExtraEntryOriginalOriginal(entryNo, disp); } //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ //@@ Destructor //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ Entry::~Entry() {} //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ //@@ Add fitted displacement to value: save it as valueDisplacementByFitting_, as when the value is asked for, it will get the original value + this displacement //@@ Then update the rmGlob, centreGlob //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ void Entry::addFittedDisplacementToValue(const ALIdouble val) { valueDisplacementByFitting_ += val; lastAdditionToValueDisplacementByFitting_ = val; if (ALIUtils::debug >= 3) std::cout << OptOCurrent()->name() << " " << name() << " Entry::addFittedDisplacementToValue " << val << " total= " << valueDisplacementByFitting_ << std::endl; //---------- Displace original centre, rotation matrix, ... displaceOriginal(val); OptOCurrent()->resetGlobalCoordinates(); } //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ //@@ Add fitted displacement to value: save it as theValueDisplacementByFitting, as when the value is asked for, it will get the origianl value + this displacement //@@ Then update the rmGlob, centreGlob //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ void Entry::substractToHalfFittedDisplacementToValue() { addFittedDisplacementToValue(-lastAdditionToValueDisplacementByFitting_ / 2.); // addFittedDisplacementToValue( -1.01*theLastAdditionToValueDisplacementByFitting ); //addFittedDisplacementToValue( -theLastAdditionToValueDisplacementByFitting ); lastAdditionToValueDisplacementByFitting_ *= -1; // addFittedDisplacementToValue( 0. ); } //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ALIdouble Entry::valueDisplaced() const { ALIuint entryNo = OptOCurrent()->extraEntryNo(name()); if (ALIUtils::debug >= 5) std::cout << entryNo << " Entry::valueDisplaced " << name() << " in " << OptOCurrent()->name() << " orig " << OptOCurrent()->ExtraEntryValueOriginalList()[entryNo] << " new " << OptOCurrent()->ExtraEntryValueList()[entryNo] << std::endl; return OptOCurrent()->ExtraEntryValueList()[entryNo] - OptOCurrent()->ExtraEntryValueOriginalList()[entryNo]; } //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ void Entry::resetValueDisplacementByFitting() { valueDisplacementByFitting_ = 0.; } //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ std::ostream& operator<<(std::ostream& os, const Entry& c) { os << "ENTRY: " << c.name() << " of type: " << c.type() << std::endl << " value " << c.value_ << " original " << c.valueOriginalOriginal_ << std::endl << " sigma " << c.sigma_ << " original " << c.sigmaOriginalOriginal_ << std::endl << " quality " << c.quality_ << " opto " << (c.OptOCurrent_)->name() << std::endl << " fitpos " << c.fitPos_ << " valueDisplacementByFitting " << c.valueDisplacementByFitting_ << " lastAdditionToValueDisplacementByFitting " << c.lastAdditionToValueDisplacementByFitting_ << std::endl; return os; } //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ const ALIstring Entry::longName() const { return OptOCurrent_->name() + "/" + name_; }
46.465875
204
0.548375
[ "vector", "model" ]
3a1260975aaf7865eb8e7421664c2858b0a64b34
631
cpp
C++
codes/leetcode/RemoveDuplicatesfromSortedArrayll.cpp
smmehrab/problem-solving
4aeab1673f18d3270ee5fc9b64ed6805eacf4af5
[ "MIT" ]
null
null
null
codes/leetcode/RemoveDuplicatesfromSortedArrayll.cpp
smmehrab/problem-solving
4aeab1673f18d3270ee5fc9b64ed6805eacf4af5
[ "MIT" ]
null
null
null
codes/leetcode/RemoveDuplicatesfromSortedArrayll.cpp
smmehrab/problem-solving
4aeab1673f18d3270ee5fc9b64ed6805eacf4af5
[ "MIT" ]
null
null
null
/* ************************************************ username : smmehrab fullname : s.m.mehrabul islam email : mehrab.24csedu.001@gmail.com institute : university of dhaka, bangladesh session : 2017-2018 ************************************************ */ class Solution { public: int removeDuplicates(vector<int>& numbers) { int count = 1; for(int i=0; i<numbers.size();) { if(i==0 || numbers[i]!=numbers[i-1]) count = 1, i++; else if(count==1) count++, i++; else numbers.erase(numbers.begin()+i); } return numbers.size(); } };
30.047619
64
0.465927
[ "vector" ]
3a1e31c14276f3c8aef6b5c1409f19aa4c7122cc
4,075
hh
C++
src/callow/matrix/MatrixDense.hh
baklanovp/libdetran
820efab9d03ae425ccefb9520bdb6c086fdbf939
[ "MIT" ]
4
2015-03-07T16:20:23.000Z
2020-02-10T13:40:16.000Z
src/callow/matrix/MatrixDense.hh
baklanovp/libdetran
820efab9d03ae425ccefb9520bdb6c086fdbf939
[ "MIT" ]
3
2018-02-27T21:24:22.000Z
2020-12-16T00:56:44.000Z
src/callow/matrix/MatrixDense.hh
baklanovp/libdetran
820efab9d03ae425ccefb9520bdb6c086fdbf939
[ "MIT" ]
9
2015-03-07T16:20:26.000Z
2022-01-29T00:14:23.000Z
//----------------------------------*-C++-*-----------------------------------// /** * @file MatrixDense.hh * @brief MatrixDense class definition * @note Copyright (C) 2013 Jeremy Roberts */ //----------------------------------------------------------------------------// #ifndef callow_MATRIXDENSE_HH_ #define callow_MATRIXDENSE_HH_ #include "MatrixBase.hh" #include <ostream> #include <vector> #include <string> namespace callow { #define MATRIXDENSE_COLMAJ /** * @class MatrixDense * @brief Dense matrix * * This class uses a column-major storage format lie Fortran. This makes * it easier to couple with PETSc, BLAS, etc. */ class CALLOW_EXPORT MatrixDense: public MatrixBase { public: //--------------------------------------------------------------------------// // ENUMERATIONS //--------------------------------------------------------------------------// enum insert_type { INSERT, ADD, END_INSERT_TYPE }; //--------------------------------------------------------------------------// // TYPEDEFS //--------------------------------------------------------------------------// typedef detran_utilities::SP<MatrixDense> SP_matrix; //--------------------------------------------------------------------------// // CONSTRUCTOR & DESTRUCTOR //--------------------------------------------------------------------------// // construction with sizing but deferred allocation MatrixDense(const int m, const int n, const double v = 0.0); // copy constructor MatrixDense(const MatrixDense &A); // destructor virtual ~MatrixDense(); // sp constructor static SP_matrix Create(const int m, const int n, const double v = 0.0); //--------------------------------------------------------------------------// // PUBLIC FUNCTIONS //--------------------------------------------------------------------------// /// add one value (return false if can't add) bool insert(int i, int j, double v, const int type = INSERT); /// add a row (return false if can't add) bool insert_row(int i, double *v, const int type = INSERT); /// add a column (return false if can't add) bool insert_col(int j, double *v, const int type = INSERT); /// value at a cardinal index const double& operator[](const int p) const; double& operator[](const int p); /// value at ij and returns 0 if not present const double& operator()(const int i, const int j) const; double& operator()(const int i, const int j); // get underlying storage and indexing. careful! double* values() {return d_values;} /// print (i, j, v) to ascii file with 1-based indexing for matlab void print_matlab(std::string filename = "matrix.out") const; //--------------------------------------------------------------------------// // ABSTRACT INTERFACE -- ALL MATRICES MUST IMPLEMENT //--------------------------------------------------------------------------// // doesn't do anything for dense matrix void assemble(){ /* ... */ } // action y <-- A * x void multiply(const Vector &x, Vector &y); // action y <-- A' * x void multiply_transpose(const Vector &x, Vector &y); // pretty print to screen void display(bool forceprint = false) const; // clear the matrix contents void clear(); protected: //--------------------------------------------------------------------------// // DATA //--------------------------------------------------------------------------// /// expose base members using MatrixBase::d_m; using MatrixBase::d_n; using MatrixBase::d_is_ready; #ifdef CALLOW_ENABLE_PETSC using MatrixBase::d_petsc_matrix; #endif /// matrix elements double* d_values; private: }; CALLOW_TEMPLATE_EXPORT(detran_utilities::SP<MatrixDense>) } // end namespace callow // Inline members #include "MatrixDense.i.hh" #endif // callow_MATRIXDENSE_HH_ //----------------------------------------------------------------------------// // end of file MatrixDense.hh //----------------------------------------------------------------------------//
29.744526
80
0.471166
[ "vector" ]
3a24cec0599aa64fc1ea12f32a860cc2b1f5f7de
656
cpp
C++
leetcode/maximum-sum-obtained-of-any-permutation/solution.cpp
rtxu/cp
16b8d6337e202f19ce75db644d4c54f4ef7baa32
[ "MIT" ]
null
null
null
leetcode/maximum-sum-obtained-of-any-permutation/solution.cpp
rtxu/cp
16b8d6337e202f19ce75db644d4c54f4ef7baa32
[ "MIT" ]
null
null
null
leetcode/maximum-sum-obtained-of-any-permutation/solution.cpp
rtxu/cp
16b8d6337e202f19ce75db644d4c54f4ef7baa32
[ "MIT" ]
null
null
null
class Solution { constexpr static int MOD = 1e9+7; public: int maxSumRangeQuery(vector<int>& nums, vector<vector<int>>& requests) { int n = nums.size(); vector<int> count(n); for (auto r : requests) { count[r[0]]++; if (r[1]+1 < n) count[r[1]+1]--; } for (int i = 1; i < n; i++) { count[i] += count[i-1]; } sort(count.begin(), count.end()); sort(nums.begin(), nums.end()); int sum = 0; for (int i = 0; i < n; i++) { sum += (1LL * count[i] * nums[i]) % MOD; sum %= MOD; } return sum; } };
27.333333
76
0.429878
[ "vector" ]
3a27dd63aedeed5d3f6056e43eb7ca4dc97599a8
23,088
cc
C++
components/sync/driver/glue/sync_engine_impl.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
components/sync/driver/glue/sync_engine_impl.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
components/sync/driver/glue/sync_engine_impl.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/sync/driver/glue/sync_engine_impl.h" #include <utility> #include "base/base64.h" #include "base/bind.h" #include "base/callback_forward.h" #include "base/callback_helpers.h" #include "base/command_line.h" #include "base/feature_list.h" #include "base/location.h" #include "base/logging.h" #include "base/metrics/histogram_functions.h" #include "base/rand_util.h" #include "base/task/task_runner_util.h" #include "build/build_config.h" #include "components/invalidation/impl/invalidation_switches.h" #include "components/invalidation/public/invalidation_service.h" #include "components/invalidation/public/topic_invalidation_map.h" #include "components/sync/base/bind_to_task_runner.h" #include "components/sync/base/invalidation_helper.h" #include "components/sync/base/sync_prefs.h" #include "components/sync/driver/active_devices_provider.h" #include "components/sync/driver/glue/sync_engine_backend.h" #include "components/sync/driver/glue/sync_transport_data_prefs.h" #include "components/sync/driver/sync_driver_switches.h" #include "components/sync/engine/data_type_activation_response.h" #include "components/sync/engine/engine_components_factory.h" #include "components/sync/engine/engine_components_factory_impl.h" #include "components/sync/engine/events/protocol_event.h" #include "components/sync/engine/net/http_bridge.h" #include "components/sync/engine/nigori/nigori.h" #include "components/sync/engine/polling_constants.h" #include "components/sync/engine/sync_engine_host.h" #include "components/sync/engine/sync_string_conversions.h" #include "components/sync/invalidations/fcm_handler.h" #include "components/sync/invalidations/switches.h" #include "components/sync/invalidations/sync_invalidations_service.h" namespace syncer { namespace { // Reads from prefs into a struct, to be posted across sequences. SyncEngineBackend::RestoredLocalTransportData RestoreLocalTransportDataFromPrefs(const SyncTransportDataPrefs& prefs) { SyncEngineBackend::RestoredLocalTransportData result; result.cache_guid = prefs.GetCacheGuid(); result.birthday = prefs.GetBirthday(); result.bag_of_chips = prefs.GetBagOfChips(); result.invalidation_versions = prefs.GetInvalidationVersions(); result.poll_interval = prefs.GetPollInterval(); if (result.poll_interval.is_zero()) { result.poll_interval = kDefaultPollInterval; } return result; } // These values are persisted to logs. Entries should not be renumbered and // numeric values should never be reused. When adding values, be certain to also // update the corresponding definition in enums.xml. enum class SyncTransportDataStartupState { kValidData = 0, kEmptyCacheGuid = 1, kEmptyBirthday = 2, kGaiaIdMismatch = 3, kMaxValue = kGaiaIdMismatch }; std::string GenerateCacheGUID() { // Generate a GUID with 128 bits of randomness. const int kGuidBytes = 128 / 8; std::string guid; base::Base64Encode(base::RandBytesAsString(kGuidBytes), &guid); return guid; } SyncTransportDataStartupState ValidateSyncTransportData( const SyncTransportDataPrefs& prefs, const CoreAccountInfo& core_account_info) { // If the cache GUID is empty, it most probably is because local sync data // has been fully cleared. Let's treat this as invalid to make sure all prefs // are cleared and a new random cache GUID generated. if (prefs.GetCacheGuid().empty()) { return SyncTransportDataStartupState::kEmptyCacheGuid; } // If cache GUID is initialized but the birthday isn't, it means the first // sync cycle never completed (OnEngineInitialized()). This should be a rare // case and theoretically harmless to resume, but as safety precaution, its // simpler to regenerate the cache GUID and start from scratch, to avoid // protocol violations (fetching updates requires that the request either has // a birthday, or there should be no progress marker). if (prefs.GetBirthday().empty()) { return SyncTransportDataStartupState::kEmptyBirthday; } // Make sure the cached account information (gaia ID) is equal to the current // one (otherwise the data may be corrupt). Note that, for local sync, the // authenticated account is always empty. if (prefs.GetGaiaId() != core_account_info.gaia) { DLOG(WARNING) << "Found mismatching gaia ID in sync preferences"; return SyncTransportDataStartupState::kGaiaIdMismatch; } // All good: local sync data looks initialized and valid. return SyncTransportDataStartupState::kValidData; } } // namespace SyncEngineImpl::SyncEngineImpl( const std::string& name, invalidation::InvalidationService* invalidator, SyncInvalidationsService* sync_invalidations_service, std::unique_ptr<ActiveDevicesProvider> active_devices_provider, std::unique_ptr<SyncTransportDataPrefs> prefs, const base::FilePath& sync_data_folder, scoped_refptr<base::SequencedTaskRunner> sync_task_runner, const base::RepeatingClosure& sync_transport_data_cleared_cb) : sync_task_runner_(std::move(sync_task_runner)), name_(name), prefs_(std::move(prefs)), sync_transport_data_cleared_cb_(sync_transport_data_cleared_cb), invalidator_(invalidator), sync_invalidations_service_(sync_invalidations_service), #if defined(OS_ANDROID) sessions_invalidation_enabled_(false), #else sessions_invalidation_enabled_(true), #endif active_devices_provider_(std::move(active_devices_provider)) { DCHECK(prefs_); backend_ = base::MakeRefCounted<SyncEngineBackend>( name_, sync_data_folder, weak_ptr_factory_.GetWeakPtr()); } SyncEngineImpl::~SyncEngineImpl() { DCHECK(!backend_ && !host_) << "Must call Shutdown before destructor."; } void SyncEngineImpl::Initialize(InitParams params) { DCHECK(params.host); host_ = params.host; // The gaia ID in sync prefs was introduced with M81, so having an empty value // is legitimate and should be populated as a one-off migration. // TODO(mastiz): Clean up this migration code after a grace period (e.g. 1 // year). if (prefs_->GetGaiaId().empty()) { prefs_->SetGaiaId(params.authenticated_account_info.gaia); } const SyncTransportDataStartupState state = ValidateSyncTransportData(*prefs_, params.authenticated_account_info); if (state != SyncTransportDataStartupState::kValidData) { // The local data is either uninitialized or corrupt, so let's throw // everything away and start from scratch with a new cache GUID, which also // cascades into datatypes throwing away their dangling sync metadata due to // cache GUID mismatches. ClearLocalTransportDataAndNotify(); prefs_->SetCacheGuid(GenerateCacheGUID()); prefs_->SetGaiaId(params.authenticated_account_info.gaia); } sync_task_runner_->PostTask( FROM_HERE, base::BindOnce(&SyncEngineBackend::DoInitialize, backend_, std::move(params), RestoreLocalTransportDataFromPrefs(*prefs_))); // If the new invalidations system (SyncInvalidationsService) is fully // enabled, then the SyncService doesn't need to communicate with the old // InvalidationService anymore. if (invalidator_ && base::FeatureList::IsEnabled(switches::kSyncSendInterestedDataTypes) && base::FeatureList::IsEnabled(switches::kUseSyncInvalidations) && base::FeatureList::IsEnabled( switches::kUseSyncInvalidationsForWalletAndOffer)) { DCHECK(!invalidation_handler_registered_); invalidator_->RegisterInvalidationHandler(this); bool success = invalidator_->UpdateInterestedTopics(this, /*topics=*/{}); DCHECK(success); invalidator_->UnregisterInvalidationHandler(this); invalidator_ = nullptr; } } bool SyncEngineImpl::IsInitialized() const { return initialized_; } void SyncEngineImpl::TriggerRefresh(const ModelTypeSet& types) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); sync_task_runner_->PostTask( FROM_HERE, base::BindOnce(&SyncEngineBackend::DoRefreshTypes, backend_, types)); } void SyncEngineImpl::UpdateCredentials(const SyncCredentials& credentials) { sync_task_runner_->PostTask( FROM_HERE, base::BindOnce(&SyncEngineBackend::DoUpdateCredentials, backend_, credentials)); } void SyncEngineImpl::InvalidateCredentials() { sync_task_runner_->PostTask( FROM_HERE, base::BindOnce(&SyncEngineBackend::DoInvalidateCredentials, backend_)); } std::string SyncEngineImpl::GetCacheGuid() const { return prefs_->GetCacheGuid(); } std::string SyncEngineImpl::GetBirthday() const { return prefs_->GetBirthday(); } base::Time SyncEngineImpl::GetLastSyncedTimeForDebugging() const { return prefs_->GetLastSyncedTime(); } void SyncEngineImpl::StartConfiguration() { sync_task_runner_->PostTask( FROM_HERE, base::BindOnce(&SyncEngineBackend::DoStartConfiguration, backend_)); } void SyncEngineImpl::StartSyncingWithServer() { DVLOG(1) << name_ << ": SyncEngineImpl::StartSyncingWithServer called."; base::Time last_poll_time = prefs_->GetLastPollTime(); // If there's no known last poll time (e.g. on initial start-up), we treat // this as if a poll just happened. if (last_poll_time.is_null()) { last_poll_time = base::Time::Now(); prefs_->SetLastPollTime(last_poll_time); } sync_task_runner_->PostTask( FROM_HERE, base::BindOnce(&SyncEngineBackend::DoStartSyncing, backend_, last_poll_time)); } void SyncEngineImpl::SetEncryptionPassphrase(const std::string& passphrase) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); sync_task_runner_->PostTask( FROM_HERE, base::BindOnce(&SyncEngineBackend::DoSetEncryptionPassphrase, backend_, passphrase)); } void SyncEngineImpl::SetExplicitPassphraseDecryptionKey( std::unique_ptr<Nigori> key) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); sync_task_runner_->PostTask( FROM_HERE, base::BindOnce(&SyncEngineBackend::DoSetExplicitPassphraseDecryptionKey, backend_, std::move(key))); } void SyncEngineImpl::AddTrustedVaultDecryptionKeys( const std::vector<std::vector<uint8_t>>& keys, base::OnceClosure done_cb) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); sync_task_runner_->PostTaskAndReply( FROM_HERE, base::BindOnce(&SyncEngineBackend::DoAddTrustedVaultDecryptionKeys, backend_, keys), std::move(done_cb)); } void SyncEngineImpl::StopSyncingForShutdown() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); // Stop getting messages from the sync thread. weak_ptr_factory_.InvalidateWeakPtrs(); // Immediately stop sending messages to the host. host_ = nullptr; backend_->ShutdownOnUIThread(); } void SyncEngineImpl::Shutdown(ShutdownReason reason) { // StopSyncingForShutdown() (which nulls out |host_|) should be // called first. DCHECK(!host_); if (invalidation_handler_registered_) { if (reason != ShutdownReason::BROWSER_SHUTDOWN_AND_KEEP_DATA) { bool success = invalidator_->UpdateInterestedTopics(this, /*topics=*/{}); DCHECK(success); } invalidator_->UnregisterInvalidationHandler(this); invalidator_ = nullptr; } if (sync_invalidations_service_) { // It's safe to call RemoveListener even if AddListener wasn't called // before. sync_invalidations_service_->RemoveListener(this); sync_invalidations_service_ = nullptr; } last_enabled_types_.Clear(); invalidation_handler_registered_ = false; active_devices_provider_->SetActiveDevicesChangedCallback( base::RepeatingClosure()); model_type_connector_.reset(); // Shut down and destroy SyncManager. sync_task_runner_->PostTask( FROM_HERE, base::BindOnce(&SyncEngineBackend::DoShutdown, backend_, reason)); // Ensure that |backend_| destroyed inside Sync sequence, not inside current // one. sync_task_runner_->ReleaseSoon(FROM_HERE, std::move(backend_)); if (reason == ShutdownReason::DISABLE_SYNC_AND_CLEAR_DATA) { ClearLocalTransportDataAndNotify(); } } void SyncEngineImpl::ConfigureDataTypes(ConfigureParams params) { DCHECK(Difference(params.to_download, ProtocolTypes()).Empty()); sync_task_runner_->PostTask( FROM_HERE, base::BindOnce(&SyncEngineBackend::DoPurgeDisabledTypes, backend_, params.to_purge)); sync_task_runner_->PostTask( FROM_HERE, base::BindOnce(&SyncEngineBackend::DoConfigureSyncer, backend_, std::move(params))); } void SyncEngineImpl::ConnectDataType( ModelType type, std::unique_ptr<DataTypeActivationResponse> activation_response) { DCHECK(ProtocolTypes().Has(type)); model_type_connector_->ConnectDataType(type, std::move(activation_response)); } void SyncEngineImpl::DisconnectDataType(ModelType type) { model_type_connector_->DisconnectDataType(type); } void SyncEngineImpl::SetProxyTabsDatatypeEnabled(bool enabled) { model_type_connector_->SetProxyTabsDatatypeEnabled(enabled); } const SyncEngineImpl::Status& SyncEngineImpl::GetDetailedStatus() const { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(IsInitialized()); return cached_status_; } void SyncEngineImpl::HasUnsyncedItemsForTest( base::OnceCallback<void(bool)> cb) const { DCHECK(IsInitialized()); base::PostTaskAndReplyWithResult( sync_task_runner_.get(), FROM_HERE, base::BindOnce(&SyncEngineBackend::HasUnsyncedItemsForTest, backend_), std::move(cb)); } void SyncEngineImpl::GetThrottledDataTypesForTest( base::OnceCallback<void(ModelTypeSet)> cb) const { DCHECK(IsInitialized()); // Instead of reading directly from |cached_status_.throttled_types|, issue // a round trip to the backend sequence, in case there is an ongoing cycle // that could update the throttled types. sync_task_runner_->PostTaskAndReply( FROM_HERE, base::DoNothing(), base::BindOnce( [](base::WeakPtr<SyncEngineImpl> engine, base::OnceCallback<void(ModelTypeSet)> cb) { std::move(cb).Run(engine->cached_status_.throttled_types); }, weak_ptr_factory_.GetWeakPtr(), std::move(cb))); } void SyncEngineImpl::RequestBufferedProtocolEventsAndEnableForwarding() { sync_task_runner_->PostTask( FROM_HERE, base::BindOnce( &SyncEngineBackend::SendBufferedProtocolEventsAndEnableForwarding, backend_)); } void SyncEngineImpl::DisableProtocolEventForwarding() { sync_task_runner_->PostTask( FROM_HERE, base::BindOnce(&SyncEngineBackend::DisableProtocolEventForwarding, backend_)); } void SyncEngineImpl::FinishConfigureDataTypesOnFrontendLoop( const ModelTypeSet enabled_types, base::OnceClosure ready_task) { last_enabled_types_ = enabled_types; SendInterestedTopicsToInvalidator(); std::move(ready_task).Run(); } void SyncEngineImpl::HandleInitializationSuccessOnFrontendLoop( const WeakHandle<DataTypeDebugInfoListener> debug_info_listener, std::unique_ptr<ModelTypeConnector> model_type_connector, const std::string& birthday, const std::string& bag_of_chips) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); model_type_connector_ = std::move(model_type_connector); initialized_ = true; if (invalidator_) { invalidator_->RegisterInvalidationHandler(this); invalidation_handler_registered_ = true; // Fake a state change to initialize the SyncManager's cached invalidator // state. // TODO(crbug.com/1132868): Do this for the new invalidations as well. OnInvalidatorStateChange(invalidator_->GetInvalidatorState()); } if (sync_invalidations_service_) { sync_invalidations_service_->AddListener(this); } active_devices_provider_->SetActiveDevicesChangedCallback(base::BindRepeating( &SyncEngineImpl::OnActiveDevicesChanged, weak_ptr_factory_.GetWeakPtr())); // Initialize active devices count. OnActiveDevicesChanged(); // Save initialization data to preferences. prefs_->SetBirthday(birthday); prefs_->SetBagOfChips(bag_of_chips); // The very first time the backend initializes is effectively the first time // we can say we successfully "synced". This gets determined based on whether // there used to be local transport metadata or not. bool is_first_time_sync_configure = false; if (prefs_->GetLastSyncedTime().is_null()) { is_first_time_sync_configure = true; UpdateLastSyncedTime(); } host_->OnEngineInitialized(debug_info_listener, /*success=*/true, is_first_time_sync_configure); } void SyncEngineImpl::HandleInitializationFailureOnFrontendLoop() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); host_->OnEngineInitialized(WeakHandle<DataTypeDebugInfoListener>(), /*success=*/false, /*is_first_time_sync_configure=*/false); } void SyncEngineImpl::HandleSyncCycleCompletedOnFrontendLoop( const SyncCycleSnapshot& snapshot) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); // Process any changes to the datatypes we're syncing. // TODO(sync): add support for removing types. if (!IsInitialized()) { return; } UpdateLastSyncedTime(); if (!snapshot.poll_finish_time().is_null()) { prefs_->SetLastPollTime(snapshot.poll_finish_time()); } DCHECK(!snapshot.poll_interval().is_zero()); prefs_->SetPollInterval(snapshot.poll_interval()); prefs_->SetBagOfChips(snapshot.bag_of_chips()); host_->OnSyncCycleCompleted(snapshot); } void SyncEngineImpl::HandleActionableErrorEventOnFrontendLoop( const SyncProtocolError& sync_error) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); host_->OnActionableError(sync_error); } void SyncEngineImpl::HandleMigrationRequestedOnFrontendLoop( ModelTypeSet types) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); host_->OnMigrationNeededForTypes(types); } void SyncEngineImpl::OnInvalidatorStateChange( invalidation::InvalidatorState state) { sync_task_runner_->PostTask( FROM_HERE, base::BindOnce(&SyncEngineBackend::DoOnInvalidatorStateChange, backend_, state)); } void SyncEngineImpl::OnIncomingInvalidation( const invalidation::TopicInvalidationMap& invalidation_map) { sync_task_runner_->PostTask( FROM_HERE, base::BindOnce(&SyncEngineBackend::DoOnIncomingInvalidation, backend_, invalidation_map)); } std::string SyncEngineImpl::GetOwnerName() const { return "SyncEngineImpl"; } void SyncEngineImpl::HandleConnectionStatusChangeOnFrontendLoop( ConnectionStatus status) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DVLOG(1) << "Connection status changed: " << ConnectionStatusToString(status); host_->OnConnectionStatusChange(status); } void SyncEngineImpl::HandleProtocolEventOnFrontendLoop( std::unique_ptr<ProtocolEvent> event) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); host_->OnProtocolEvent(*event); } void SyncEngineImpl::UpdateInvalidationVersions( const std::map<ModelType, int64_t>& invalidation_versions) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); prefs_->UpdateInvalidationVersions(invalidation_versions); } void SyncEngineImpl::HandleSyncStatusChanged(const SyncStatus& status) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); const bool backed_off_types_changed = (status.backed_off_types != cached_status_.backed_off_types); cached_status_ = status; if (backed_off_types_changed) { host_->OnBackedOffTypesChanged(); } } void SyncEngineImpl::OnCookieJarChanged(bool account_mismatch, base::OnceClosure callback) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); sync_task_runner_->PostTask( FROM_HERE, base::BindOnce(&SyncEngineBackend::DoOnCookieJarChanged, backend_, account_mismatch, std::move(callback))); } void SyncEngineImpl::SetInvalidationsForSessionsEnabled(bool enabled) { sessions_invalidation_enabled_ = enabled; SendInterestedTopicsToInvalidator(); } void SyncEngineImpl::GetNigoriNodeForDebugging(AllNodesCallback callback) { DCHECK(backend_); sync_task_runner_->PostTask( FROM_HERE, base::BindOnce(&SyncEngineBackend::GetNigoriNodeForDebugging, backend_, BindToCurrentSequence(std::move(callback)))); } void SyncEngineImpl::OnInvalidatorClientIdChange(const std::string& client_id) { sync_task_runner_->PostTask( FROM_HERE, base::BindOnce(&SyncEngineBackend::DoOnInvalidatorClientIdChange, backend_, client_id)); } void SyncEngineImpl::OnInvalidationReceived(const std::string& payload) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); // TODO(crbug.com/1082122): check that sync engine is fully initialized. sync_task_runner_->PostTask( FROM_HERE, base::BindOnce(&SyncEngineBackend::DoOnInvalidationReceived, backend_, payload)); } // static std::string SyncEngineImpl::GenerateCacheGUIDForTest() { return GenerateCacheGUID(); } void SyncEngineImpl::OnCookieJarChangedDoneOnFrontendLoop( base::OnceClosure callback) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); std::move(callback).Run(); } void SyncEngineImpl::SendInterestedTopicsToInvalidator() { if (!invalidator_) { return; } // No need to register invalidations for CommitOnlyTypes(). ModelTypeSet invalidation_enabled_types( Difference(last_enabled_types_, CommitOnlyTypes())); if (!sessions_invalidation_enabled_) { invalidation_enabled_types.Remove(syncer::SESSIONS); } // switches::kUseSyncInvalidations means that the new invalidations system is // used for all data types except Wallet and Offer, so only keep these types. if (base::FeatureList::IsEnabled(switches::kSyncSendInterestedDataTypes) && base::FeatureList::IsEnabled(switches::kUseSyncInvalidations)) { invalidation_enabled_types.RetainAll( {AUTOFILL_WALLET_DATA, AUTOFILL_WALLET_OFFER}); } bool success = invalidator_->UpdateInterestedTopics( this, ModelTypeSetToTopicSet(invalidation_enabled_types)); DCHECK(success); } void SyncEngineImpl::OnActiveDevicesChanged() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); sync_task_runner_->PostTask( FROM_HERE, base::BindOnce(&SyncEngineBackend::DoOnActiveDevicesChanged, backend_, active_devices_provider_->CalculateInvalidationInfo( cached_status_.cache_guid))); } void SyncEngineImpl::UpdateLastSyncedTime() { prefs_->SetLastSyncedTime(base::Time::Now()); } void SyncEngineImpl::ClearLocalTransportDataAndNotify() { prefs_->ClearAll(); sync_transport_data_cleared_cb_.Run(); } } // namespace syncer
36.359055
80
0.751473
[ "vector" ]
3a28f1b5ce5ea9550a6d9ed72df24ec3b9310c11
6,589
cpp
C++
src/cpp/Sampler.cpp
SiyuanQi/human-centric-scene-synthesis
6f2215d07052426f0f4a27b8ca71844ea5d347c4
[ "MIT" ]
77
2018-02-25T00:59:18.000Z
2022-03-27T15:55:21.000Z
src/cpp/Sampler.cpp
Pandinosaurus/human-centric-scene-synthesis
6f2215d07052426f0f4a27b8ca71844ea5d347c4
[ "MIT" ]
4
2018-03-05T12:54:27.000Z
2018-09-10T14:56:59.000Z
src/cpp/Sampler.cpp
Pandinosaurus/human-centric-scene-synthesis
6f2215d07052426f0f4a27b8ca71844ea5d347c4
[ "MIT" ]
15
2018-02-23T21:19:39.000Z
2022-01-01T12:21:32.000Z
// // Created by siyuan on 6/20/17. // #include "Sampler.h" namespace FurnitureArranger{ int Sampler::_iterationMax = 5000; Sampler::Sampler() { } Sampler::Sampler(Learner learner, std::string suncgRoot, std::string metadataPath, std::string workspacePath): _suncgRoot(suncgRoot), _metadataPath(metadataPath), _workspacePath(workspacePath){ _rooms = learner.get_rooms(); std::random_shuffle(_rooms.begin(), _rooms.end()); Room::read_group_metadata(metadataPath); Room::read_prior_data(metadataPath); Furniture::read_metadata(metadataPath); json weight; read_json_file(_metadataPath + "costWeight.json", weight); _costWeights = json_to_ub_vector(weight); } void Sampler::arrange(int process_id) { std::cout << process_id << std::endl; int sample_interval = 1000, sample_index = sample_interval * process_id; std::vector<Room>::const_iterator first = _rooms.begin() + sample_index; std::vector<Room>::const_iterator last = _rooms.begin() + sample_index + sample_interval + 1; std::vector<Room> new_rooms(first, last); for(Room room : new_rooms){ std::cout << sample_index << " " << room.get_caption() << std::endl; //std::cout << room.get_id() << std::endl; room.initialize_prior_distributions(); room.sample_group_affordance(); room.sample_supporting_affordance(); //cool_down_wall_objects(room); run_mcmc(room, 0, room.get_furniture_list().size()); std::string jsonOutputFolder = _workspacePath+"tmp/samples/"+room.get_caption()+"/json/", txtOutputFolder = _workspacePath+"tmp/samples/"+room.get_caption()+"/txt/"; boost::filesystem::create_directories(jsonOutputFolder); boost::filesystem::create_directories(txtOutputFolder); std::stringstream outputFilename; outputFilename << "sample_"; outputFilename << std::setfill('0') << std::setw(10) << sample_index; room.write_to_room_arranger_file(txtOutputFolder+outputFilename.str()+".txt"); room.write_to_json(jsonOutputFolder+outputFilename.str()+".json"); sample_index++; } } void Sampler::run_mcmc(Room &room, size_t startFurnIndex, size_t endFurnIndex) { _iterationMax = 5000 * room.get_furniture_list().size(); //std::cout << "compute_total_energy" << std::endl; double currentEnergy = room.compute_total_energy(_costWeights), proposedEnergy; _temperature = 10; for (int i = 0; i < _iterationMax; i++) { //std::cout << "MCMC iteration: " << i << ", temperature: " << _temperature << std::endl; anneal(i); Room proposedRoom = room; proposedRoom.propose(_stepSize, startFurnIndex, endFurnIndex, false); proposedEnergy = proposedRoom.compute_total_energy(_costWeights); double r = (rand() / (double)RAND_MAX), acceptanceProb = std::min(1.0, exp( (currentEnergy - proposedEnergy)/_temperature) ); if (r < acceptanceProb){ //std::cout << "Accepted: " << currentEnergy << " " << proposedEnergy << " " << r << " " << acceptanceProb << " " << _temperature << std::endl; room = proposedRoom; currentEnergy = proposedEnergy; }else{ //std::cout << "Rejected: " << currentEnergy << " " << proposedEnergy << " " << r << " " << acceptanceProb << " " << _temperature << std::endl; } //if (i % 100 == 0){ // // Output every result to file for visualization // std::stringstream outputFilename; // outputFilename << "sample_"; // outputFilename << std::setfill('0') << std::setw(8) << i; // room.write_to_room_arranger_file(_workspacePath+"tmp/samples/mcmc/txt/"+outputFilename.str()+".txt"); // room.write_to_json(_workspacePath+"tmp/samples/mcmc/json/"+outputFilename.str()+".json"); //} } } void Sampler::anneal(int iteration) { if (iteration % 100 == 0){ _temperature *= 0.9; } _stepSize = (_iterationMax-iteration)/double(_iterationMax) + 0.01; } void Sampler::cool_down_wall_objects(Room &room){ _iterationMax = 5000; for (unsigned int iFurn = 0; iFurn < room.get_furniture_list().size(); iFurn++){ if (room.get_supporting_index(iFurn) == -2){ double currentEnergy = room.compute_total_energy(_costWeights), proposedEnergy; _temperature = 0.1; for (unsigned int i = 0; i < _iterationMax; i++) { //std::cout << "Cool down iteration: " << i << ", temperature: " << _temperature << std::endl; anneal(i); _stepSize = 0.05*(_iterationMax-i)/double(_iterationMax) + 0.01; Room proposedRoom = room; proposedRoom.propose(_stepSize, iFurn, iFurn+1); proposedEnergy = proposedRoom.compute_total_energy(_costWeights); double r = (rand() / (double)RAND_MAX), acceptanceProb = std::min(1.0, exp( (currentEnergy - proposedEnergy)/_temperature) ); if (r < acceptanceProb){ //std::cout << "Accepted: " << currentEnergy << " " << proposedEnergy << " " << r << " " << acceptanceProb << " " << _temperature << std::endl; room = proposedRoom; currentEnergy = proposedEnergy; }else{ //std::cout << "Rejected: " << currentEnergy << " " << proposedEnergy << " " << r << " " << acceptanceProb << " " << _temperature << std::endl; } //if (i % 100 == 0) { // // Output iteration results to file for visualization // std::stringstream outputFilename; // outputFilename << "sample_"; // outputFilename << std::setfill('0') << std::setw(8) << total_iteration; // room.write_to_room_arranger_file( // _workspacePath + "tmp/samples/mcmc/txt/" + outputFilename.str() + ".txt"); // room.write_to_json(_workspacePath + "tmp/samples/mcmc/json/" + outputFilename.str() + ".json"); //} } } } } }
48.448529
197
0.563363
[ "vector" ]
3a2c7a15ec1f6e2ba6011de9e7a43ca28d7aa2d6
7,188
inl
C++
Libraries/include/glm/ext/scalar_integer.inl
Chokearth/OpenGL_training
2baf712222da121722342cbac78c74ff9a685a0e
[ "MIT" ]
null
null
null
Libraries/include/glm/ext/scalar_integer.inl
Chokearth/OpenGL_training
2baf712222da121722342cbac78c74ff9a685a0e
[ "MIT" ]
null
null
null
Libraries/include/glm/ext/scalar_integer.inl
Chokearth/OpenGL_training
2baf712222da121722342cbac78c74ff9a685a0e
[ "MIT" ]
null
null
null
#include "glm/integer.hpp" namespace glm{ namespace detail { template<length_t L, typename T, qualifier Q, bool compute = false> struct compute_ceilShift { GLM_FUNC_QUALIFIER static vec<L, T, Q> call(vec<L, T, Q> const& v, T) { return v; } }; template<length_t L, typename T, qualifier Q> struct compute_ceilShift<L, T, Q, true> { GLM_FUNC_QUALIFIER static vec<L, T, Q> call(vec<L, T, Q> const& v, T Shift) { return v | (v >> Shift); } }; template<length_t L, typename T, qualifier Q, bool isSigned = true> struct compute_ceilPowerOfTwo { GLM_FUNC_QUALIFIER static vec<L, T, Q> call(vec<L, T, Q> const& x) { GLM_STATIC_ASSERT(!std::numeric_limits<T>::is_iec559, "'ceilPowerOfTwo' only accept integer scalar or vector inputs"); vec<L, T, Q> const Sign(sign(x)); vec<L, T, Q> v(abs(x)); v = v - static_cast<T>(1); v = v | (v >> static_cast<T>(1)); v = v | (v >> static_cast<T>(2)); v = v | (v >> static_cast<T>(4)); v = compute_ceilShift<L, T, Q, sizeof(T) >= 2>::call(v, 8); v = compute_ceilShift<L, T, Q, sizeof(T) >= 4>::call(v, 16); v = compute_ceilShift<L, T, Q, sizeof(T) >= 8>::call(v, 32); return (v + static_cast<T>(1)) * Sign; } }; template<length_t L, typename T, qualifier Q> struct compute_ceilPowerOfTwo<L, T, Q, false> { GLM_FUNC_QUALIFIER static vec<L, T, Q> call(vec<L, T, Q> const& x) { GLM_STATIC_ASSERT(!std::numeric_limits<T>::is_iec559, "'ceilPowerOfTwo' only accept integer scalar or vector inputs"); vec<L, T, Q> v(x); v = v - static_cast<T>(1); v = v | (v >> static_cast<T>(1)); v = v | (v >> static_cast<T>(2)); v = v | (v >> static_cast<T>(4)); v = compute_ceilShift<L, T, Q, sizeof(T) >= 2>::call(v, 8); v = compute_ceilShift<L, T, Q, sizeof(T) >= 4>::call(v, 16); v = compute_ceilShift<L, T, Q, sizeof(T) >= 8>::call(v, 32); return v + static_cast<T>(1); } }; template<bool is_float, bool is_signed> struct compute_ceilMultiple{}; template<> struct compute_ceilMultiple<true, true> { template<typename genType> GLM_FUNC_QUALIFIER static genType call(genType Source, genType Multiple) { if(Source > genType(0)) return Source + (Multiple - std::fmod(Source, Multiple)); else return Source + std::fmod(-Source, Multiple); } }; template<> struct compute_ceilMultiple<false, false> { template<typename genType> GLM_FUNC_QUALIFIER static genType call(genType Source, genType Multiple) { genType Tmp = Source - genType(1); return Tmp + (Multiple - (Tmp % Multiple)); } }; template<> struct compute_ceilMultiple<false, true> { template<typename genType> GLM_FUNC_QUALIFIER static genType call(genType Source, genType Multiple) { assert(Multiple > genType(0)); if(Source > genType(0)) { genType Tmp = Source - genType(1); return Tmp + (Multiple - (Tmp % Multiple)); } else return Source + (-Source % Multiple); } }; template<bool is_float, bool is_signed> struct compute_floorMultiple{}; template<> struct compute_floorMultiple<true, true> { template<typename genType> GLM_FUNC_QUALIFIER static genType call(genType Source, genType Multiple) { if(Source >= genType(0)) return Source - std::fmod(Source, Multiple); else return Source - std::fmod(Source, Multiple) - Multiple; } }; template<> struct compute_floorMultiple<false, false> { template<typename genType> GLM_FUNC_QUALIFIER static genType call(genType Source, genType Multiple) { if(Source >= genType(0)) return Source - Source % Multiple; else { genType Tmp = Source + genType(1); return Tmp - Tmp % Multiple - Multiple; } } }; template<> struct compute_floorMultiple<false, true> { template<typename genType> GLM_FUNC_QUALIFIER static genType call(genType Source, genType Multiple) { if(Source >= genType(0)) return Source - Source % Multiple; else { genType Tmp = Source + genType(1); return Tmp - Tmp % Multiple - Multiple; } } }; }//namespace detail template<typename genIUType> GLM_FUNC_QUALIFIER bool isPowerOfTwo(genIUType Value) { GLM_STATIC_ASSERT(std::numeric_limits<genIUType>::is_integer, "'isPowerOfTwo' only accept integer inputs"); genIUType const Result = glm::abs(Value); return !(Result & (Result - 1)); } template<typename genIUType> GLM_FUNC_QUALIFIER genIUType nextPowerOfTwo(genIUType value) { GLM_STATIC_ASSERT(std::numeric_limits<genIUType>::is_integer, "'nextPowerOfTwo' only accept integer inputs"); return detail::compute_ceilPowerOfTwo<1, genIUType, defaultp, std::numeric_limits<genIUType>::is_signed>::call(vec<1, genIUType, defaultp>(value)).x; } template<typename genIUType> GLM_FUNC_QUALIFIER genIUType prevPowerOfTwo(genIUType value) { GLM_STATIC_ASSERT(std::numeric_limits<genIUType>::is_integer, "'prevPowerOfTwo' only accept integer inputs"); return isPowerOfTwo(value) ? value : static_cast<genIUType>(static_cast<genIUType>(1) << static_cast<genIUType>(findMSB(value))); } template<typename genIUType> GLM_FUNC_QUALIFIER bool isMultiple(genIUType Value, genIUType Multiple) { GLM_STATIC_ASSERT(std::numeric_limits<genIUType>::is_integer, "'isMultiple' only accept integer inputs"); return isMultiple(vec<1, genIUType>(Value), vec<1, genIUType>(Multiple)).x; } template<typename genIUType> GLM_FUNC_QUALIFIER genIUType nextMultiple(genIUType Source, genIUType Multiple) { GLM_STATIC_ASSERT(std::numeric_limits<genIUType>::is_integer, "'nextMultiple' only accept integer inputs"); return detail::compute_ceilMultiple<std::numeric_limits<genIUType>::is_iec559, std::numeric_limits<genIUType>::is_signed>::call(Source, Multiple); } template<typename genIUType> GLM_FUNC_QUALIFIER genIUType prevMultiple(genIUType Source, genIUType Multiple) { GLM_STATIC_ASSERT(std::numeric_limits<genIUType>::is_integer, "'prevMultiple' only accept integer inputs"); return detail::compute_floorMultiple<std::numeric_limits<genIUType>::is_iec559, std::numeric_limits<genIUType>::is_signed>::call(Source, Multiple); } template<typename genIUType> GLM_FUNC_QUALIFIER int findNSB(genIUType x, int significantBitCount) { GLM_STATIC_ASSERT(std::numeric_limits<genIUType>::is_integer, "'findNSB' only accept integer inputs"); if(bitCount(x) < significantBitCount) return -1; genIUType const One = static_cast<genIUType>(1); int bitPos = 0; genIUType key = x; int nBitCount = significantBitCount; int Step = sizeof(x) * 8 / 2; while (key > One) { genIUType Mask = static_cast<genIUType>((One << Step) - One); genIUType currentKey = key & Mask; int currentBitCount = bitCount(currentKey); if (nBitCount > currentBitCount) { nBitCount -= currentBitCount; bitPos += Step; key >>= static_cast<genIUType>(Step); } else { key = key & Mask; } Step >>= 1; } return static_cast<int>(bitPos); } }//namespace glm
29.459016
152
0.669588
[ "vector" ]
3a3222c7d0eb050f41e3327f0f66c771953a5972
17,578
hpp
C++
bra/include/bra/gates.hpp
naoki-yoshioka/bracket
6eff40e6ee5768744974e9d79bf6ff892bd67390
[ "MIT" ]
2
2021-02-26T21:50:37.000Z
2022-01-26T07:35:14.000Z
bra/include/bra/gates.hpp
naoki-yoshioka/braket
d4fbf1b19691e71dbc6fa62d8a66c7c61b6c4d68
[ "MIT" ]
50
2018-06-05T12:23:57.000Z
2022-03-05T15:04:30.000Z
bra/include/bra/gates.hpp
naoki-yoshioka/bracket
6eff40e6ee5768744974e9d79bf6ff892bd67390
[ "MIT" ]
null
null
null
#ifndef BRA_GATES_HPP # define BRA_GATES_HPP # include <cassert> # include <iosfwd> # include <vector> # include <string> # include <tuple> # include <algorithm> # include <iterator> # include <utility> # include <memory> # include <stdexcept> # include <initializer_list> # if __cplusplus >= 201703L # include <type_traits> # else # include <boost/type_traits/is_nothrow_swappable.hpp> # endif # include <boost/lexical_cast.hpp> # ifndef BRA_NO_MPI # include <yampi/allocator.hpp> # include <yampi/communicator.hpp> # include <yampi/environment.hpp> # endif // BRA_NO_MPI # include <bra/state.hpp> # include <bra/gate/gate.hpp> # if __cplusplus >= 201703L # define BRA_is_nothrow_swappable std::is_nothrow_swappable # else # define BRA_is_nothrow_swappable boost::is_nothrow_swappable # endif namespace bra { class unsupported_mnemonic_error : public std::runtime_error { public: unsupported_mnemonic_error(std::string const& mnemonic); }; // class unsupported_mnemonic_error class wrong_mnemonics_error : public std::runtime_error { public: using columns_type = std::vector<std::string>; wrong_mnemonics_error(columns_type const& columns); private: std::string generate_what_string(columns_type const& columns); }; // class wrong_mnemonic_error # ifndef BRA_NO_MPI class wrong_mpi_communicator_size_error : public std::runtime_error { public: wrong_mpi_communicator_size_error(); }; // class wrong_mpi_communicator_size_error # endif // BRA_NO_MPI enum class begin_statement : int { measurement, learning_machine }; enum class bit_statement : int { assignment }; enum class generate_statement : int { events }; enum class depolarizing_statement : int { channel }; class gates { using value_type_ = std::unique_ptr< ::bra::gate::gate >; # ifndef BRA_NO_MPI using data_type = std::vector<value_type_, yampi::allocator<value_type_>>; # else using data_type = std::vector<value_type_>; # endif data_type data_; public: using bit_integer_type = ::bra::state::bit_integer_type; using state_integer_type = ::bra::state::state_integer_type; using qubit_type = ::bra::state::qubit_type; using control_qubit_type = ::bra::state::control_qubit_type; # ifndef BRA_NO_MPI using permutated_qubit_type = ::bra::state::permutated_qubit_type; using permutated_control_qubit_type = ::bra::state::permutated_control_qubit_type; # endif using real_type = ::bra::state::real_type; using columns_type = wrong_mnemonics_error::columns_type; private: bit_integer_type num_qubits_; # ifndef BRA_NO_MPI bit_integer_type num_lqubits_; bit_integer_type num_uqubits_; unsigned int num_processes_per_unit_; # endif state_integer_type initial_state_value_; # ifndef BRA_NO_MPI std::vector<permutated_qubit_type> initial_permutation_; # endif using complex_type = ::bra::state::complex_type; # ifndef BRA_NO_MPI using phase_coefficients_type = std::vector<complex_type, yampi::allocator<complex_type>>; # else using phase_coefficients_type = std::vector<complex_type>; # endif phase_coefficients_type phase_coefficients_; # ifndef BRA_NO_MPI yampi::rank root_; # endif public: using value_type = data_type::value_type; using allocator_type = data_type::allocator_type; using size_type = data_type::size_type; using difference_type = data_type::difference_type; using reference = data_type::reference; using const_reference = data_type::const_reference; using pointer = data_type::pointer; using const_pointer = data_type::const_pointer; using iterator = data_type::iterator; using const_iterator = data_type::const_iterator; using reverse_iterator = data_type::reverse_iterator; using const_reverse_iterator = data_type::const_reverse_iterator; gates(); explicit gates(allocator_type const& allocator); gates(gates&& other, allocator_type const& allocator); # ifndef BRA_NO_MPI gates( std::istream& input_stream, bit_integer_type num_uqubits, unsigned int num_processes_per_unit, yampi::environment const& environment, yampi::rank const root = yampi::rank{}, yampi::communicator const& communicator = yampi::communicator{::yampi::world_communicator_t()}, size_type const num_reserved_gates = size_type{0u}); # else // BRA_NO_MPI explicit gates(std::istream& input_stream); gates(std::istream& input_stream, size_type const num_reserved_gates); # endif // BRA_NO_MPI bool operator==(gates const& other) const; bit_integer_type const& num_qubits() const { return num_qubits_; } # ifndef BRA_NO_MPI bit_integer_type const& num_lqubits() const { return num_lqubits_; } bit_integer_type const& num_uqubits() const { return num_uqubits_; } unsigned int const& num_processes_per_unit() const { return num_processes_per_unit_; } # endif state_integer_type const& initial_state_value() const { return initial_state_value_; } # ifndef BRA_NO_MPI std::vector<permutated_qubit_type> const& initial_permutation() const { return initial_permutation_; } # endif # ifndef BRA_NO_MPI void num_qubits( bit_integer_type const new_num_qubits, yampi::communicator const& communicator, yampi::environment const& environment); void num_lqubits( bit_integer_type const new_num_lqubits, yampi::communicator const& communicator, yampi::environment const& environment); # else // BRA_NO_MPI void num_qubits(bit_integer_type const new_num_qubits); # endif // BRA_NO_MPI private: # ifndef BRA_NO_MPI void set_num_qubits_params( bit_integer_type const new_num_lqubits, bit_integer_type const num_gqubits, yampi::communicator const& communicator, yampi::environment const& environment); # else // BRA_NO_MPI void set_num_qubits_params(bit_integer_type const new_num_qubits); # endif // BRA_NO_MPI public: # ifndef BRA_NO_MPI void assign( std::istream& input_stream, yampi::environment const& environment, yampi::communicator const& communicator = yampi::communicator{yampi::world_communicator_t()}, size_type const num_reserved_gates = size_type{0u}); # else // BRA_NO_MPI void assign( std::istream& input_stream, size_type const num_reserved_gates = size_type{0u}); # endif // BRA_NO_MPI allocator_type get_allocator() const { return data_.get_allocator(); } // Element access //reference at(size_type const index) { return data_.at(index); } const_reference at(size_type const index) const { return data_.at(index); } //reference operator[](size_type const index) { return data_[index]; } const_reference operator[](size_type const index) const { return data_[index]; } //reference front() { return data_.front(); } const_reference front() const { return data_.front(); } //reference back() { return data_.back(); } const_reference back() const { return data_.back(); } // Iterators //iterator begin() noexcept { return data_.begin(); } const_iterator begin() const noexcept { return data_.begin(); } //iterator end() noexcept { return data_.end(); } const_iterator end() const noexcept { return data_.end(); } //reverse_iterator rbegin() noexcept { return data_.rbegin(); } const_reverse_iterator rbegin() const noexcept { return data_.rbegin(); } //reverse_iterator rend() noexcept { return data_.rend(); } const_reverse_iterator rend() const noexcept { return data_.rend(); } // Capacity bool empty() const noexcept { return data_.empty(); } size_type size() const noexcept { return data_.size(); } size_type max_size() const noexcept { return data_.max_size(); } void reserve(size_type const new_capacity) { data_.reserve(new_capacity); } size_type capacity() const noexcept { return data_.capacity(); } // Modifiers void clear() noexcept { data_.clear(); } /* iterator insert(const_iterator position, value_type&& value) { return data_.insert(position, std::move(value)); } template <typename... Arguments> iterator emplace(const_iterator const position, Arguments&&... arguments) { return data_.emplace(position, std::forward<Arguments>(arguments)...); } */ iterator erase(iterator const position) { return data_.erase(position); } iterator erase(iterator const first, iterator const last) { return data_.erase(first, last); } /* void push_back(value_type&& value) { data_.push_back(std::move(value)); } template <typename... Arguments> void emplace_back(Arguments&&... arguments) { data_.emplace_back(std::forward<Arguments>(arguments)...); } */ void pop_back() { data_.pop_back(); } //void resize(size_type const count) { data_.resize(count); } void swap(gates& other) noexcept( BRA_is_nothrow_swappable<data_type>::value and BRA_is_nothrow_swappable<bit_integer_type>::value and BRA_is_nothrow_swappable<state_integer_type>::value and BRA_is_nothrow_swappable<qubit_type>::value); private: bit_integer_type read_num_qubits(columns_type const& columns) const; state_integer_type read_initial_state_value(columns_type& columns) const; bit_integer_type read_num_mpi_processes(columns_type const& columns) const; state_integer_type read_mpi_buffer_size(columns_type const& columns) const; # ifndef BRA_NO_MPI std::vector<permutated_qubit_type> read_initial_permutation(columns_type const& columns) const; # endif qubit_type read_target(columns_type const& columns) const; std::tuple<qubit_type, real_type> read_target_phase(columns_type const& columns) const; std::tuple<qubit_type, real_type, real_type> read_target_2phases(columns_type const& columns) const; std::tuple<qubit_type, real_type, real_type, real_type> read_target_3phases(columns_type const& columns) const; std::tuple<qubit_type, int> read_target_phaseexp(columns_type const& columns) const; std::tuple<control_qubit_type, qubit_type> read_control_target(columns_type const& columns) const; std::tuple<control_qubit_type, qubit_type, int> read_control_target_phaseexp(columns_type const& columns) const; std::tuple<control_qubit_type, control_qubit_type, qubit_type> read_2controls_target(columns_type const& columns) const; qubit_type read_hadamard(columns_type const& columns) const { return read_target(columns); } qubit_type read_pauli_x(columns_type const& columns) const { return read_target(columns); } qubit_type read_pauli_y(columns_type const& columns) const { return read_target(columns); } qubit_type read_pauli_z(columns_type const& columns) const { return read_target(columns); } qubit_type read_s_gate(columns_type const& columns) const { return read_target(columns); } qubit_type read_adj_s_gate(columns_type const& columns) const { return read_target(columns); } qubit_type read_t_gate(columns_type const& columns) const { return read_target(columns); } qubit_type read_adj_t_gate(columns_type const& columns) const { return read_target(columns); } std::tuple<qubit_type, real_type> read_u1(columns_type const& columns) const { return read_target_phase(columns); } std::tuple<qubit_type, real_type, real_type> read_u2(columns_type const& columns) const { return read_target_2phases(columns); } std::tuple<qubit_type, real_type, real_type, real_type> read_u3(columns_type const& columns) const { return read_target_3phases(columns); } std::tuple<qubit_type, int> read_phase_shift(columns_type const& columns) const { return read_target_phaseexp(columns); } qubit_type read_x_rotation_half_pi(columns_type const& columns) const { return read_target(columns); } qubit_type read_adj_x_rotation_half_pi(columns_type const& columns) const { return read_target(columns); } qubit_type read_y_rotation_half_pi(columns_type const& columns) const { return read_target(columns); } qubit_type read_adj_y_rotation_half_pi(columns_type const& columns) const { return read_target(columns); } std::tuple<control_qubit_type, qubit_type> read_controlled_not(columns_type const& columns) const { return read_control_target(columns); } std::tuple<control_qubit_type, qubit_type, int> read_controlled_phase_shift(columns_type const& columns) const { return read_control_target_phaseexp(columns); } std::tuple<control_qubit_type, qubit_type, int> read_controlled_v(columns_type const& columns) const { return read_control_target_phaseexp(columns); } std::tuple<control_qubit_type, control_qubit_type, qubit_type> read_toffoli(columns_type const& columns) const { return read_2controls_target(columns); } qubit_type read_projective_measurement(columns_type const& columns) const { return read_target(columns); } ::bra::begin_statement read_begin_statement(columns_type& columns) const; ::bra::bit_statement read_bit_statement(columns_type& columns) const; std::tuple<bit_integer_type, state_integer_type, state_integer_type> read_shor_box(columns_type const& columns) const; std::tuple< ::bra::generate_statement, int, int > read_generate_statement(columns_type& columns) const; qubit_type read_clear(columns_type const& columns) const { return read_target(columns); } qubit_type read_set(columns_type const& columns) const { return read_target(columns); } std::tuple< ::bra::depolarizing_statement, real_type, real_type, real_type, int > read_depolarizing_statement(columns_type& columns) const; }; // class gates inline bool operator!=(::bra::gates const& lhs, ::bra::gates const& rhs) { return not (lhs == rhs); } inline void swap(::bra::gates& lhs, ::bra::gates& rhs) noexcept(noexcept(lhs.swap(rhs))) { lhs.swap(rhs); } inline ::bra::state& operator<<(::bra::state& state, ::bra::gates const& gates) { for (auto const& gate_ptr: gates) state << *gate_ptr; return state; } namespace gates_detail { template <typename Value> void read_value_in_depolarizing_statement( Value& value, std::string& present_string, // "xxx" or "xxx," or "xxx,..." ::bra::gates::columns_type::const_iterator& column_iter, ::bra::gates::columns_type::const_iterator const& column_last, ::bra::gates::columns_type const& columns) { auto string_found = std::find(present_string.cbegin(), present_string.cend(), ','); value = boost::lexical_cast<Value>(std::string{present_string.cbegin(), string_found}); if (string_found == present_string.cend()) // present_string == "xxx" { if (++column_iter == column_last) { present_string.clear(); return; } present_string = *column_iter; // present_string == "," or ",..." if (present_string[0] != ',') throw wrong_mnemonics_error{columns}; if (present_string.size() == 1u) // present_string == "," { if (++column_iter == column_last) throw wrong_mnemonics_error{columns}; present_string = *column_iter; // present_string == "..." } else // present_string == ",..." present_string.assign(present_string, 1u, std::string::npos); // present_string == "..." } else // present_string == "xxx," or "xxx,..." { present_string.assign(++string_found, present_string.cend()); // present_string == "" or "..." if (present_string.empty()) // present_string == "" { if (++column_iter == column_last) throw wrong_mnemonics_error{columns}; present_string = *column_iter; // present_string == "..." } } } template <typename Value> void read_depolarizing_statement( Value& value, std::string& present_string, ::bra::gates::columns_type::const_iterator& column_iter, ::bra::gates::columns_type::const_iterator const& column_last, std::string::const_iterator string_found, ::bra::gates::columns_type const& columns) { if (string_found == present_string.cend()) // present_string == "XXX" { if (++column_iter == column_last) throw wrong_mnemonics_error{columns}; present_string = *column_iter; // present_string == "=" or "=xxx" or "=xxx," or "=xxx,..." if (present_string[0] != '=') throw wrong_mnemonics_error{columns}; if (present_string.size() == 1u) // present_string == "=" { if (++column_iter == column_last) throw wrong_mnemonics_error{columns}; present_string = *column_iter; // present_string == "xxx" or "xxx," or "xxx,..." } else // presnet_string == "=xxx" or "=xxx," or "=xxx,..." present_string.assign(present_string, 1u, std::string::npos); // presnet_string == "xxx" or "xxx," or "xxx,..." } else // present_string == "XXX=" or "XXX=xxx" or "XXX=xxx," or "XXX=xxx,..." { present_string.assign(++string_found, present_string.cend()); // present_string == "" or "xxx" or "xxx," or "xxx,..." if (present_string.empty()) // present_string == "" { if (++column_iter == column_last) throw wrong_mnemonics_error{columns}; present_string = *column_iter; // present_string == "xxx" or "xxx," or "xxx,..." } } read_value_in_depolarizing_statement(value, present_string, column_iter, column_last, columns); } } // namespace gates_detail } // namespace bra # undef BRA_is_nothrow_swappable #endif // BRA_GATES_HPP
42.977995
164
0.715838
[ "vector" ]
3a3261345c4af1ad873264e9b48ffdb00b6ded02
2,949
cpp
C++
examples/scenes/dialogscene.cpp
bdamer/dukat
e138893b1c7e28ef50c19f256bae98a79d22f9c5
[ "MIT" ]
4
2019-05-20T18:30:36.000Z
2021-10-01T15:54:59.000Z
examples/scenes/dialogscene.cpp
bdamer/dukat
e138893b1c7e28ef50c19f256bae98a79d22f9c5
[ "MIT" ]
19
2017-02-20T23:54:34.000Z
2021-09-30T05:43:49.000Z
examples/scenes/dialogscene.cpp
bdamer/dukat
e138893b1c7e28ef50c19f256bae98a79d22f9c5
[ "MIT" ]
2
2020-06-05T07:18:23.000Z
2021-10-01T15:55:02.000Z
#include "stdafx.h" #include "dialogscene.h" namespace dukat { DialogScene::DialogScene(Game3* game3) : game(game3) { overlay_meshes.stage = RenderStage::Overlay; overlay_meshes.visible = true; auto title_text = game->create_text_mesh(); title_text->set_size(1.0f / 10.0f); title_text->transform.position = { -0.75f, 0.25f, 0.0f }; title_text->set_text("<#dd0907>Options screen</>"); overlay_meshes.add_instance(std::move(title_text)); auto fullscreen_text = game->create_text_mesh(); fullscreen_text->set_size(1.0f / 20.0f); fullscreen_text->transform.position = { -1.0f, 0.0f, 0.0f }; fullscreen_button = std::make_unique<TextButton>(fullscreen_text.get()); fullscreen_button->set_text("Fullscreen"); fullscreen_button->set_index(0); fullscreen_button->set_trigger([&](void) { bool fullscreen = !game->get_window()->is_fullscreen(); game->get_window()->set_fullscreen(fullscreen); fullscreen_button->set_text(fullscreen ? "Windowed" : "Fullscreen"); }); overlay_meshes.add_instance(std::move(fullscreen_text)); auto return_text = game->create_text_mesh(); return_text->set_size(1.0f / 20.0f); return_text->transform.position = { -1.0f, -0.1f, 0.0f }; return_button = std::make_unique<TextButton>(return_text.get()); return_button->set_text("Back"); return_button->set_index(1); return_button->set_trigger([&](void) { game->pop_scene(); }); overlay_meshes.add_instance(std::move(return_text)); } void DialogScene::activate(void) { auto settings = game->get_settings(); auto camera = std::make_unique<FixedCamera3>(game, Vector3{ 0.0f, 0.0f, 2.5f }, Vector3{ 0.0f, 0.0f, 0.0f }, Vector3::unit_y); camera->set_vertical_fov(settings.get_float("camera.fov")); camera->set_clip(settings.get_float("camera.nearclip"), settings.get_float("camera.farclip")); camera->refresh(); game->get_renderer()->set_camera(std::move(camera)); game->set_controller(this); game->get<UIManager>()->add_control(fullscreen_button.get()); game->get<UIManager>()->add_control(return_button.get()); } void DialogScene::deactivate(void) { game->get<UIManager>()->remove_control(fullscreen_button.get()); game->get<UIManager>()->remove_control(return_button.get()); } void DialogScene::update(float delta) { overlay_meshes.update(delta); } void DialogScene::handle_keyboard(const SDL_Event& e) { switch (e.key.keysym.sym) { case SDLK_ESCAPE: game->pop_scene(); break; case SDLK_SPACE: case SDLK_RETURN: game->get<UIManager>()->trigger_focus(); break; case SDLK_UP: game->get<UIManager>()->prev_control(); break; case SDLK_DOWN: game->get<UIManager>()->next_control(); break; } } void DialogScene::render(void) { auto renderer = game->get_renderer(); std::vector<Mesh*> meshes; meshes.push_back(game->get_debug_meshes()); meshes.push_back(&overlay_meshes); renderer->render(meshes); } }
30.71875
128
0.700576
[ "mesh", "render", "vector", "transform" ]
3a39e2c003051a3927cd1e26993ea4042abec54f
3,144
cc
C++
saphIR/src/ir/canon/bb.cc
balayette/saphIR-project
18da494ac21e5433fdf1c646be02c9bf25177d7d
[ "MIT" ]
14
2020-07-31T09:35:23.000Z
2021-11-15T11:18:35.000Z
saphIR/src/ir/canon/bb.cc
balayette/saphIR-project
18da494ac21e5433fdf1c646be02c9bf25177d7d
[ "MIT" ]
null
null
null
saphIR/src/ir/canon/bb.cc
balayette/saphIR-project
18da494ac21e5433fdf1c646be02c9bf25177d7d
[ "MIT" ]
null
null
null
#include "ir/canon/bb.hh" #include "ir/visitors/ir-pretty-printer.hh" #include "utils/assert.hh" #include "mach/target.hh" namespace ir { bb::bb(tree::rnodevec::iterator begin, tree::rnodevec::iterator end) : instrs_(tree::rnodevec(begin, end)) { } std::vector<utils::label> bb::successors() { if (auto cjump = instrs_.back().as<tree::cjump>()) return {cjump->ltrue_, cjump->lfalse_}; if (auto jump = instrs_.back().as<tree::jump>()) return jump->avlbl_dests_; // epilogue return {}; } utils::label bb::entry() { auto lbl = instrs_.front().as<tree::label>(); ASSERT(lbl != nullptr, "First instruction of a basic block not a label."); return lbl->name_; } bool is_jump(tree::tree_kind k) { return k == tree::tree_kind::cjump || k == tree::tree_kind::jump; } std::unordered_map<utils::label, bb> create_bbs(tree::rnode stm, utils::label &body, utils::label epilogue) { // stm is a seq, and is the only seq/eseq in the program. auto seq = stm.as<tree::seq>(); auto &target = stm->target(); tree::rnodevec::iterator bb_begin = seq->children().begin(); std::vector<bb> basic_blocks; tree::rnodevec stmts; for (auto ichild = seq->children().begin(); ichild < seq->children().end(); ichild++) { if (!is_jump((*ichild)->kind()) && (*ichild)->kind() != tree::tree_kind::label) { stmts.emplace_back(*ichild); continue; } // End the block and start a new one. if (bb_begin == seq->children().begin()) { // First block, we need to add a label if it doesn't // have one, and tell the prologue to jump to it. // If the block already has a label, we use it. if (stmts.size() > 0 && stmts.front()->kind() == tree::tree_kind::label) body = stmts.front().as<tree::label>()->name_; else { body = unique_label("body"); stmts.insert(stmts.begin(), target.make_label(body)); } } auto child = *ichild; // If we're ending a block because we reached a jump, include // the jump in the block. // Otherwise, add a jump to the label if (is_jump(child->kind())) { stmts.push_back(*ichild); ++ichild; } else { auto lbl = child.as<tree::label>(); stmts.emplace_back(target.make_jump( target.make_name(lbl->name_), {lbl->name_})); } // At this point we have a complete basic block. // If the basic block is a single jump, then we can remove it, // because no label => no one can jump to it. if (stmts.size() > 1 && !is_jump(stmts.front()->kind())) { bb block(stmts.begin(), stmts.end()); basic_blocks.push_back(block); } bb_begin = ichild; stmts.clear(); // If we ended on a label, include it in the next block. if (ichild != seq->children().end() && (*ichild)->kind() == tree::tree_kind::label) stmts.push_back(*ichild); } if (bb_begin != seq->children().end()) { bb block(bb_begin, seq->children().end()); block.instrs_.push_back(target.make_jump( target.make_name(epilogue), {epilogue})); basic_blocks.push_back(block); } std::unordered_map<utils::label, bb> ret; for (auto block : basic_blocks) { ret.insert({block.entry(), block}); } return ret; } } // namespace ir
26.644068
70
0.639313
[ "vector" ]
3a3d397c7bf130b622de7931a85bf5cf955363dc
2,911
cpp
C++
MeshLib/MeshEditing/RasterDataToMesh.cpp
ChaofanChen/ogs
0f30c514ac6d905302a453cb9928016c996d78e6
[ "BSD-4-Clause" ]
null
null
null
MeshLib/MeshEditing/RasterDataToMesh.cpp
ChaofanChen/ogs
0f30c514ac6d905302a453cb9928016c996d78e6
[ "BSD-4-Clause" ]
null
null
null
MeshLib/MeshEditing/RasterDataToMesh.cpp
ChaofanChen/ogs
0f30c514ac6d905302a453cb9928016c996d78e6
[ "BSD-4-Clause" ]
1
2021-02-15T00:07:22.000Z
2021-02-15T00:07:22.000Z
/** * \file * \copyright * Copyright (c) 2012-2020, OpenGeoSys Community (http://www.opengeosys.org) * Distributed under a Modified BSD License. * See accompanying file LICENSE.txt or * http://www.opengeosys.org/project/license * */ #include "RasterDataToMesh.h" #include "MeshLib/Node.h" #include "MeshLib/Elements/Element.h" namespace MeshLib { namespace RasterDataToMesh { static bool checkMesh(MeshLib::Mesh const& mesh) { if (mesh.getDimension() > 2) { ERR("This functionality is currently only available for 2D meshes."); return false; } return true; } static std::string getValidName(std::vector<std::string> const& vec_names, std::string const& array_name) { std::string new_name = array_name; std::size_t count = 1; while (std::find(vec_names.cbegin(), vec_names.cend(), new_name) != vec_names.end()) { count++; new_name = array_name + "-" + std::to_string(count); } return new_name; } static double evaluatePixel(double const value, double const no_data, double const replacement) { if (std::abs(value - no_data) < std::numeric_limits<double>::epsilon()) { return replacement; } return value; } bool projectToNodes(MeshLib::Mesh& mesh, GeoLib::Raster const& raster, double const def, std::string const& array_name) { if (!checkMesh(mesh)) { return false; } auto& nodes = mesh.getNodes(); auto& props = mesh.getProperties(); std::string const name = getValidName(props.getPropertyVectorNames(), array_name); auto vec = props.createNewPropertyVector<double>( name, MeshLib::MeshItemType::Node, 1); double const no_data = raster.getHeader().no_data; std::transform(nodes.cbegin(), nodes.cend(), std::back_inserter(*vec), [&](auto const node) { return evaluatePixel(raster.getValueAtPoint(*node), no_data, def); }); return true; } bool projectToElements(MeshLib::Mesh& mesh, GeoLib::Raster const& raster, double const def, std::string const& array_name) { if (!checkMesh(mesh)) { return false; } auto& elems = mesh.getElements(); auto& props = mesh.getProperties(); std::string const name = getValidName(props.getPropertyVectorNames(), array_name); auto vec = props.createNewPropertyVector<double>( name, MeshLib::MeshItemType::Cell, 1); double const no_data = raster.getHeader().no_data; std::transform(elems.cbegin(), elems.cend(), std::back_inserter(*vec), [&](auto const elem) { auto node = elem->getCenterOfGravity(); return evaluatePixel(raster.getValueAtPoint(node), no_data, def); }); return true; } } // end namespace RasterDataToMesh } // end namespace MeshLib
28.539216
97
0.632429
[ "mesh", "vector", "transform" ]
3a4a77d82ed53cb982b4d585c37a67173467e406
6,506
cpp
C++
src/solvers/mp/rcspp/PrincipalGraph.cpp
wssuite/NurseScheduler
e5059e06b97154d5993a67aa3a0aa2c65ff45d0a
[ "MIT" ]
14
2020-05-04T01:24:36.000Z
2022-03-20T15:04:52.000Z
src/solvers/mp/rcspp/PrincipalGraph.cpp
legraina/StaticNurseScheduler
e5059e06b97154d5993a67aa3a0aa2c65ff45d0a
[ "MIT" ]
19
2020-04-28T18:55:00.000Z
2020-05-15T08:59:00.000Z
src/solvers/mp/rcspp/PrincipalGraph.cpp
legraina/NurseScheduler
e5059e06b97154d5993a67aa3a0aa2c65ff45d0a
[ "MIT" ]
6
2018-09-28T01:51:31.000Z
2020-04-19T04:53:03.000Z
// // Created by antoine legrain on 2020-04-11. // #include "PrincipalGraph.h" #include "SubProblem.h" using std::string; using std::vector; PrincipalGraph::PrincipalGraph(int shift_type, SubProblem* sp): pSP_(sp), shift_type_(shift_type), max_cons_(-1) { if(sp) { max_cons_ = sp->maxCons(shift_type); int i = 0; for (int s: sp->scenario()->shiftTypeIDToShiftID_[shift_type_]) shifts_to_indices_[s] = i++; build(); } } PrincipalGraph::~PrincipalGraph() {} void PrincipalGraph::build() { PScenario pScenario = pSP_->scenario(); int nDays = pSP_->nDays(); // CREATE THE NODES for(int k=0; k<nDays; k++){ // For each date vector<int> vec; for(int cons=0; cons<=max_cons_; cons++) // For each level of network vec.emplace_back(pSP_->addSingleNode(PRINCIPAL_NETWORK)); principalNetworkNodes_.push_back(vec); } // CREATE THE ARCS unsigned int nShifts = pScenario->shiftTypeIDToShiftID_[shift_type_].size(); // initialization Tools::initVector3D(arcsShiftToSameShift_, nDays-1, max_cons_, nShifts, -1); Tools::initVector2D(arcsRepeatShift_, nDays-1, nShifts, -1); Tools::initVector2D(arcsShiftToEndsequence_, nDays, max_cons_, -1); // FOR EACH OF THE DAYS // int origin, destin; for(int k=0; k<nDays-1; k++){ // 1. WORK ONE MORE DAY ON THE SAME SHIFT WHEN MAXIMUM IS NOT REACHED YET // for(int nCons=0; nCons<max_cons_; nCons ++){ origin = principalNetworkNodes_[k][nCons]; int dest_day = k+(nCons>0); destin = principalNetworkNodes_[dest_day][nCons+1]; // stay on same day for the first level for (unsigned int s = 0; s < nShifts; s++) { int shiftID = pScenario-> shiftTypeIDToShiftID_[shift_type_][s]; int a = pSP_->addSingleArc(origin, destin, 0, {1,-1}, SHIFT_TO_SAMESHIFT, dest_day, {shiftID}); arcsShiftToSameShift_[k][nCons][s] = a; } } // 2. WORK ONE MORE DAY ON THE SAME SHIFT WHEN MAXIMUM IS ALREADY REACHED // origin = principalNetworkNodes_[k][max_cons_]; destin = principalNetworkNodes_[k+1][max_cons_]; double cost = pSP_->isUnlimited(shift_type_) ? 0 : WEIGHT_CONS_SHIFTS; for (unsigned int s = 0; s < nShifts; s++) { int shiftID = pScenario-> shiftTypeIDToShiftID_[shift_type_][s]; int a = pSP_->addSingleArc(origin, destin, cost, {1,-1}, REPEATSHIFT, k+1, {shiftID}); arcsRepeatShift_[k][s] = a; } // 3. END THE CONSECUTIVE SHIFT SEQUENCE // cannot end for the initial level: must perform at least one shift for(int nCons=1; nCons<max_cons_; nCons++){ origin = principalNetworkNodes_[k][nCons]; destin = principalNetworkNodes_[k][max_cons_]; arcsShiftToEndsequence_[k][nCons] = pSP_->addSingleArc(origin, destin, pScenario->consShiftTypeCost(shift_type_, nCons), {0,0}, SHIFT_TO_ENDSEQUENCE, k); } } // SPECIAL CASE: LAST DAY // be able to work one shift to reach level 1 from level 0 origin = principalNetworkNodes_[nDays-1][0]; destin = principalNetworkNodes_[nDays-1][1]; std::vector<int> last_arcs; for (unsigned int s = 0; s < nShifts; s++) { int shiftID = pScenario-> shiftTypeIDToShiftID_[shift_type_][s]; last_arcs.emplace_back(pSP_->addSingleArc(origin, destin, 0, {1,-1}, SHIFT_TO_SAMESHIFT, nDays-1, {shiftID})); } arcsShiftToSameShift_.push_back({last_arcs}); // do not pay any penalty for the minimum for(int nCons=1; nCons<max_cons_; nCons++){ origin = principalNetworkNodes_[nDays-1][nCons]; destin = principalNetworkNodes_[nDays-1][max_cons_]; arcsShiftToEndsequence_[nDays-1][nCons] = pSP_->addSingleArc(origin, destin, 0, {0,0}, SHIFT_TO_ENDSEQUENCE, nDays-1); } } // check if feasible to link this arc at this level bool PrincipalGraph::checkFeasibilityEntranceArc(const Arc_Properties& arc_prop, int level) const { if( !checkIfShiftBelongsHere(arc_prop.shifts.back(), true) ) return false; // find which level should be reached int sh = -1, n = 0; if(arc_prop.day == 0) { sh = pSP_->liveNurse()->pStateIni_->shiftType_; n = pSP_->liveNurse()->pStateIni_->consShifts_; if(arc_prop.shifts.empty()) { std::cerr << "Arc must contain at least a shift " << "when starting the first to take into account the historical state." << std::endl; return false; } } for(int s: arc_prop.shifts) { int new_sh = pSP_->scenario()->shiftIDToShiftTypeID_[s]; if(new_sh == sh) ++n; else n = 1; sh = new_sh; } if(n > max_cons_) n = max_cons_; return n == level; } void PrincipalGraph::updateArcCosts() { if(!pSP_) return; for (int k = 0; k < pSP_->nDays() - 1; k++) { for (int n = 0; n < max_cons_; n++) for (int a: arcsShiftToSameShift_[k][n]) pSP_->g().updateCost(a, pSP_->workCost(a)); for(int a: arcsRepeatShift_[k]) pSP_->g().updateCost(a, pSP_->workCost(a)); } for (int a: arcsShiftToSameShift_[pSP_->nDays()-1][0]) pSP_->g().updateCost(a, pSP_->workCost(a)); } void PrincipalGraph::forbidDayShift(int k, int s) { if( !checkIfShiftBelongsHere(s, true) ) return; int i = shifts_to_indices_.at(s); pSP_->g().forbidArc(arcsShiftToSameShift_[k][0][i]); // forbid first cons shift if(k-- > 0) { // if k>0, coninue and do --k // forbid any ingoing arcs using shift s for (int n = 1; n < max_cons_; n++) { // pSP_->g().forbidNode(principalNetworkNodes_[k][n]); pSP_->g().forbidArc(arcsShiftToSameShift_[k][n][i]); } pSP_->g().forbidArc(arcsRepeatShift_[k][i]); } } void PrincipalGraph::authorizeDayShift(int k, int s){ if( !checkIfShiftBelongsHere(s, true) ) return; int i = shifts_to_indices_.at(s); pSP_->g().authorizeArc(arcsShiftToSameShift_[k][0][i]); // authorize first cons shift if(k>0) { // authorize any ingoing arcs using shift s for (int n = 1; n < max_cons_; n++) { // pSP_->g().forbidNode(principalNetworkNodes_[k][n]); pSP_->g().authorizeArc(arcsShiftToSameShift_[k-1][n][i]); } pSP_->g().authorizeArc(arcsRepeatShift_[k-1][i]); } } bool PrincipalGraph::checkIfShiftBelongsHere(int s, bool print_err) const { if(pSP_ == nullptr) return false; int sh = pSP_->scenario()->shiftIDToShiftTypeID_[s]; if(shift_type_ != sh) { if(print_err) std::cerr << "Shift " << s << " of type " << sh << "does not belong to the principal graph associated to type " << shift_type_ << std::endl; return false; } return true; }
33.885417
114
0.655088
[ "vector" ]
3a4d933db1f7e7cafb086e4c0b91b9d62b435c1b
5,933
cc
C++
source/neuropod/bindings/c/c_api.cc
Moti-H/neuropod
6f3e5862230cecf8b0d0b463eb145f187a398e64
[ "Apache-2.0" ]
null
null
null
source/neuropod/bindings/c/c_api.cc
Moti-H/neuropod
6f3e5862230cecf8b0d0b463eb145f187a398e64
[ "Apache-2.0" ]
null
null
null
source/neuropod/bindings/c/c_api.cc
Moti-H/neuropod
6f3e5862230cecf8b0d0b463eb145f187a398e64
[ "Apache-2.0" ]
null
null
null
/* Copyright (c) 2020 The Neuropod Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Inspired by the TensorFlow C API #include "neuropod/bindings/c/c_api.h" #include "neuropod/bindings/c/c_api_internal.h" #include "neuropod/bindings/c/np_status_internal.h" #include "neuropod/bindings/c/np_tensor_allocator_internal.h" #include "neuropod/bindings/c/np_valuemap_internal.h" #include "neuropod/core/generic_tensor.hh" #include <exception> #include <string> #include <vector> // NOLINTNEXTLINE(readability-identifier-naming): Ignore function case for C API methods void NP_LoadNeuropodWithOpts(const char * neuropod_path, const NP_RuntimeOptions *options, NP_Neuropod ** model, NP_Status * status) { try { *model = new NP_Neuropod(); (*model)->model = std::make_unique<neuropod::Neuropod>(neuropod_path); NP_ClearStatus(status); } catch (std::exception &e) { status->code = NEUROPOD_ERROR; status->message = e.what(); } } // NOLINTNEXTLINE(readability-identifier-naming): Ignore function case for C API methods NP_RuntimeOptions NP_DefaultRuntimeOptions() { // Use C++ runtime options object to set default values. neuropod::RuntimeOptions default_options; NP_RuntimeOptions options; options.use_ope = default_options.use_ope; options.visible_device = static_cast<NP_RuntimeOptions::NP_Device>(default_options.visible_device); options.load_model_at_construction = default_options.load_model_at_construction; options.disable_shape_and_type_checking = default_options.disable_shape_and_type_checking; auto ope_options = &options.ope_options; ope_options->free_memory_every_cycle = default_options.ope_options.free_memory_every_cycle; // Control queue name is empty, a new worker will be started. // This is what is expected by default. ope_options->control_queue_name[0] = '\0'; return options; } // NOLINTNEXTLINE(readability-identifier-naming): Ignore function case for C API methods void NP_LoadNeuropod(const char *neuropod_path, NP_Neuropod **model, NP_Status *status) { const auto &options = NP_DefaultRuntimeOptions(); NP_LoadNeuropodWithOpts(neuropod_path, &options, model, status); } // NOLINTNEXTLINE(readability-identifier-naming): Ignore function case for C API methods void NP_FreeNeuropod(NP_Neuropod *model) { delete model; } // NOLINTNEXTLINE(readability-identifier-naming): Ignore function case for C API methods void NP_Infer(NP_Neuropod *model, const NP_NeuropodValueMap *inputs, NP_NeuropodValueMap **outputs, NP_Status *status) { NP_InferWithRequestedOutputs(model, inputs, 0, nullptr, outputs, status); } // NOLINTNEXTLINE(readability-identifier-naming): Ignore function case for C API methods void NP_InferWithRequestedOutputs(NP_Neuropod * model, const NP_NeuropodValueMap *inputs, size_t noutputs, const char ** requested_outputs, NP_NeuropodValueMap ** outputs, NP_Status * status) { try { // By default empty collection of requested_ouputs expected. // Note that it copies C-strings (0-terminated) from given array. // User must guarantee that noutputs and requested_outputs address valid data.. std::vector<std::string> rout; if (requested_outputs != nullptr) { for (size_t i = 0; i < noutputs; ++i) { rout.emplace_back(requested_outputs[i]); } } *outputs = new NP_NeuropodValueMap(); (*outputs)->data = std::move(*model->model->infer(inputs->data, rout)); NP_ClearStatus(status); } catch (std::exception &e) { status->code = NEUROPOD_ERROR; status->message = e.what(); } } // NOLINTNEXTLINE(readability-identifier-naming): Ignore function case for C API methods const char *NP_GetName(NP_Neuropod *model) { return model->model->get_name().c_str(); } // NOLINTNEXTLINE(readability-identifier-naming): Ignore function case for C API methods const char *NP_GetPlatform(NP_Neuropod *model) { return model->model->get_platform().c_str(); } // NOLINTNEXTLINE(readability-identifier-naming): Ignore function case for C API methods size_t NP_GetNumInputs(NP_Neuropod *model) { return model->model->get_inputs().size(); } // NOLINTNEXTLINE(readability-identifier-naming): Ignore function case for C API methods size_t NP_GetNumOutputs(NP_Neuropod *model) { return model->model->get_outputs().size(); } // NOLINTNEXTLINE(readability-identifier-naming): Ignore function case for C API methods NP_TensorAllocator *NP_GetAllocator(NP_Neuropod *model) { auto out = new NP_TensorAllocator(); out->allocator = model->model->get_tensor_allocator(); return out; } // NOLINTNEXTLINE(readability-identifier-naming): Ignore function case for C API methods NP_TensorAllocator *NP_GetGenericAllocator() { auto out = new NP_TensorAllocator(); out->allocator = neuropod::get_generic_tensor_allocator(); return out; }
37.08125
120
0.681443
[ "object", "vector", "model" ]
3a4ed06664be48cf0f754cbc58dcf322259e4ee0
2,211
hpp
C++
include/tmm/json_serilisation.hpp
readex-eu/readex-rrl
ac8722c44f84d65668e2a60e4237ebf51b298c9b
[ "BSD-3-Clause" ]
1
2019-10-09T09:15:47.000Z
2019-10-09T09:15:47.000Z
include/tmm/json_serilisation.hpp
readex-eu/readex-rrl
ac8722c44f84d65668e2a60e4237ebf51b298c9b
[ "BSD-3-Clause" ]
null
null
null
include/tmm/json_serilisation.hpp
readex-eu/readex-rrl
ac8722c44f84d65668e2a60e4237ebf51b298c9b
[ "BSD-3-Clause" ]
1
2018-07-13T11:31:05.000Z
2018-07-13T11:31:05.000Z
/** Json serilisation * https://github.com/nlohmann/json#basic-usage */ #ifndef INCLUDE_TMM_JSON_SERILISATION_HPP_ #define INCLUDE_TMM_JSON_SERILISATION_HPP_ #include <json.hpp> #include <tmm/identifiers.hpp> #include <tmm/simple_callpath.hpp> #include <tmm/tuning_model_manager.hpp> namespace rrl { namespace tmm { class serialisation_error : public std::exception { public: serialisation_error(const std::string &what_arg, std::vector<simple_callpath_element> &elem) { std::stringstream ss; ss << elem; message = what_arg; message += " for RTS: "; message += ss.str(); } const char *what() const noexcept override { return message.c_str(); } private: std::string message; }; template <typename T> inline void to_json(nlohmann::json &j, const identifier<T> &i) { j = nlohmann::json{{"id", i.id}, {"value", i.value}}; } template <typename T> inline void from_json(const nlohmann::json &j, identifier<T> &i) { i.id = j.at("id").get<std::size_t>(); i.value = j.at("ints").get<T>(); } inline void to_json(nlohmann::json &j, const identifier_set &i) { j = nlohmann::json{{"uints", i.uints}, {"ints", i.ints}, {"strings", i.strings}}; } inline void from_json(const nlohmann::json &j, identifier_set &i) { i.uints = j.at("uints").get<std::vector<identifier<std::uint64_t>>>(); i.ints = j.at("ints").get<std::vector<identifier<std::int64_t>>>(); i.strings = j.at("strings").get<std::vector<identifier<std::string>>>(); } inline void to_json(nlohmann::json &j, const simple_callpath_element &s) { auto tmm = tmm::get_tuning_model_manager(""); j = nlohmann::json{{"id_set", s.id_set}, {"calibrate", s.calibrate}, {"fn_name", tmm->get_name_from_region_id(s.region_id)}}; } inline void from_json(const nlohmann::json &j, simple_callpath_element &s) { auto tmm = tmm::get_tuning_model_manager(""); s.region_id = tmm->get_id_from_region_name(j.at("fn_name").get<std::string>()); s.id_set = j.at("id_set").get<identifier_set>(); s.calibrate = j.at("calibrate").get<bool>(); } }; // namespace tmm }; // namespace rrl #endif /* INCLUDE_TMM_JSON_SERILISATION_HPP_ */
26.638554
96
0.661692
[ "vector" ]
3a4ed212dfe0c6aee23f0444620b34f71688284f
13,519
hh
C++
gazebo/util/LogRecord.hh
horikawahorikawa/gazebo-PR
bdb99bec78b8adb95f8855057aae7c028f9e78c2
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
gazebo/util/LogRecord.hh
horikawahorikawa/gazebo-PR
bdb99bec78b8adb95f8855057aae7c028f9e78c2
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
gazebo/util/LogRecord.hh
horikawahorikawa/gazebo-PR
bdb99bec78b8adb95f8855057aae7c028f9e78c2
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2012-2015 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /* Desc: A class to log data * Author: Nate Koenig * Date: 1 Jun 2010 */ #ifndef _LOGRECORD_HH_ #define _LOGRECORD_HH_ #include <fstream> #include <string> #include <map> #include <boost/thread.hpp> #include <boost/archive/iterators/base64_from_binary.hpp> #include <boost/archive/iterators/insert_linebreaks.hpp> #include <boost/archive/iterators/transform_width.hpp> #include <boost/archive/iterators/ostream_iterator.hpp> #include <boost/filesystem.hpp> #include "gazebo/msgs/msgs.hh" #include "gazebo/transport/TransportTypes.hh" #include "gazebo/common/UpdateInfo.hh" #include "gazebo/common/Event.hh" #include "gazebo/common/SingletonT.hh" #include "gazebo/util/system.hh" #define GZ_LOG_VERSION "1.0" namespace gazebo { namespace util { /// addtogroup gazebo_util /// \{ /// \class LogRecord LogRecord.hh util/util.hh /// \brief Handles logging of data to disk /// /// The LogRecord class is a Singleton that manages data logging of any /// entity within a running simulation. An entity may be a World, Model, /// or any of their child entities. This class only writes log files, /// see LogPlay for playback functionality. /// /// State information for an entity may be logged through the LogRecord::Add /// function, and stopped through the LogRecord::Remove function. Data may /// be logged into a single file, or split into many separate files by /// specifying different filenames for the LogRecord::Add function. /// /// The LogRecord is updated at the start of each simulation step. This /// guarantees that all data is stored. /// /// \sa Logplay, State class GZ_UTIL_VISIBLE LogRecord : public SingletonT<LogRecord> { /// \brief Constructor private: LogRecord(); /// \brief Destructor private: virtual ~LogRecord(); /// \brief Initialize logging into a subdirectory. /// /// Init may only be called once, False will be returned if called /// multiple times. /// \param[in] _subdir Directory to record to /// \return True if successful. public: bool Init(const std::string &_subdir); /// \brief Add an object to a log file. /// /// Add a new object to a log. An object can be any valid named object /// in simulation, including the world itself. Duplicate additions are /// ignored. Objects can be added to the same file by /// specifying the same _filename. /// \param[in] _name Name of the object to log. /// \param[in] _filename Filename of the log file. /// \param[in] _logCallback Function used to log data for the object. /// Typically an object will have a log function that outputs data to /// the provided ofstream. /// \throws Exception public: void Add(const std::string &_name, const std::string &_filename, boost::function<bool (std::ostringstream &)> _logCallback); /// \brief Remove an entity from a log /// /// Removes an entity from the logger. The stops data recording for /// the entity and all its children. For example, specifying a world /// will stop all data logging. /// \param[in] _name Name of the log /// \return True if the entity existed and was removed. False if the /// entity was not registered with the logger. public: bool Remove(const std::string &_name); /// \brief Stop the logger. public: void Stop(); /// \brief Tell the recorder that an update should occur. public: void Notify(); /// \brief Set whether logging should pause. A paused state means the /// log file is still open, but data is not written to it. /// \param[in] _paused True to pause data logging. /// \sa LogRecord::GetPaused public: void SetPaused(bool _paused); /// \brief Get whether logging is paused. /// \return True if logging is paused. /// \sa LogRecord::SetPaused public: bool GetPaused() const; /// \brief Get whether the logger is ready to start, which implies /// that any previous runs have finished. // \return True if logger is ready to start. public: bool IsReadyToStart() const; /// \brief Get whether logging is running. /// \return True if logging has been started. public: bool GetRunning() const; /// \brief Start the logger. /// \param[in] _encoding The type of encoding (txt, zlib, or bz2). /// \param[in] _path Path in which to store log files. public: bool Start(const std::string &_encoding="zlib", const std::string &_path=""); /// \brief Get the encoding used. /// \return Either [txt, zlib, or bz2], where txt is plain txt and bz2 /// and zlib are compressed data with Base64 encoding. public: const std::string &GetEncoding() const; /// \brief Get the filename for a log object. /// \param[in] _name Name of the log object. /// \return Filename, empty string if not found. public: std::string GetFilename(const std::string &_name = "") const; /// \brief Get the file size for a log object. /// \param[in] _name Name of the log object. /// \return Size in bytes. public: unsigned int GetFileSize(const std::string &_name = "") const; /// \brief Set the base path. /// \param[in] _path Path to the new logging location. public: void SetBasePath(const std::string &_path); /// \brief Get the base path for a log recording. /// \return Path for log recording. public: std::string GetBasePath() const; /// \brief Get the run time in sim time. /// \return Run sim time. public: common::Time GetRunTime() const; /// \brief Finialize, and shutdown. public: void Fini(); /// \brief Return true if an Update has not yet been completed. /// \return True if an Update has not yet been completed. public: bool GetFirstUpdate() const; /// \brief Write all logs. /// \param[in] _force True to skip waiting on dataAvailableCondition. public: void Write(bool _force = false); /// \brief Get the size of the buffer. /// \return Size of the buffer, in bytes. public: unsigned int GetBufferSize() const; /// \brief Update the log files /// /// Captures the current state of all registered entities, and outputs /// the data to their respective log files. // private: void Update(const common::UpdateInfo &_info); private: void Update(); /// \brief Function used by the update thread. private: void RunUpdate(); /// \brief Run the Write loop. private: void RunWrite(); /// \brief Clear and delete the log buffers. private: void ClearLogs(); /// \brief Publish log status message. private: void PublishLogStatus(); /// \brief Called when a log control message is received. /// \param[in] _data The log control message. private: void OnLogControl(ConstLogControlPtr &_data); /// \brief Cleanup log recording. A thread uses this function, you /// should never call this function directly. Use the Stop() function /// to trigger a cleanup. private: void Cleanup(); /// \brief Used to get the simulation pause state. private: void OnPause(bool _pause); /// \cond private: class Log { /// \brief Constructor /// \param[in] _parent Pointer to the LogRecord parent. /// \param[in] _relativeFilename The name of the log file to /// generate, sans the complete path. /// \param[in] _logCB Callback function, which is used to get log /// data. public: Log(LogRecord *_parent, const std::string &_relativeFilename, boost::function<bool (std::ostringstream &)> _logCB); /// \brief Destructor public: virtual ~Log(); /// \brief Start the log. /// \param[in] _path The complete path in which to put the log file. public: void Start(const boost::filesystem::path &_path); /// \brief Stop logging. public: void Stop(); /// \brief Write data to disk. public: void Write(); /// \brief Update the data buffer. /// \return The size of the data buffer. public: unsigned int Update(); /// \brief Clear the data buffer. public: void ClearBuffer(); /// \brief Get the byte size of the buffer. /// \return Buffer byte size. public: unsigned int GetBufferSize(); /// \brief Get the relative filename. This is the filename passed /// to the constructor. /// \return The relative filename. public: std::string GetRelativeFilename() const; /// \brief Get the complete filename. /// \return The complete filename. public: std::string GetCompleteFilename() const; /// \brief Pointer to the log record parent. public: LogRecord *parent; /// \brief Callback from which to get data. public: boost::function<bool (std::ostringstream &)> logCB; /// \brief Data buffer. public: std::string buffer; /// \brief The log file. public: std::ofstream logFile; /// \brief Relative log filename. public: std::string relativeFilename; /// \brief Complete file path. private: boost::filesystem::path completePath; }; /// \endcond /// \def Log_M /// \brief Map of names to logs. private: typedef std::map<std::string, Log*> Log_M; /// \brief All the log objects. private: Log_M logs; /// \brief Iterator used to update the log objects. private: Log_M::iterator updateIter; /// \brief Convenience iterator to the end of the log objects map. private: Log_M::iterator logsEnd; /// \brief Condition used to start threads private: boost::condition_variable startThreadCondition; /// \brief Condition used to trigger an update private: boost::condition_variable updateCondition; /// \brief Used by the cleanupThread to wait for a cleanup signal. private: boost::condition_variable cleanupCondition; /// \brief True if logging is running. private: bool running; /// \brief Thread used to write data to disk. private: boost::thread *writeThread; /// \brief Thread used to update data. private: boost::thread *updateThread; /// \brief Thread to cleanup log recording. private: boost::thread cleanupThread; /// \brief Mutex to protect against parallel calls to Write() private: mutable boost::mutex writeMutex; /// \brief Mutex to synchronize with RunWrite() private: mutable boost::mutex runWriteMutex; /// \brief Mutex to synchronize with RunUpdate() private: mutable boost::mutex updateMutex; /// \brief Mutex to protect logging control. private: boost::mutex controlMutex; /// \brief Used by the write thread to know when data needs to be /// written to disk private: boost::condition_variable dataAvailableCondition; /// \brief The base pathname for all the logs. private: boost::filesystem::path logBasePath; /// \brief The complete pathname for all the logs. private: boost::filesystem::path logCompletePath; /// \brief Subdirectory for log files. This is appended to /// logBasePath. private: std::string logSubDir; /// \brief Encoding format for each chunk. private: std::string encoding; /// \brief True if initialized. private: bool initialized; /// \brief True to pause recording. private: bool paused; /// \brief Used to indicate the first update callback. private: bool firstUpdate; /// \brief Flag used to stop the write thread. private: bool stopThread; /// \brief Start simulation time. private: common::Time startTime; /// \brief Current simulation time. private: common::Time currTime; /// \brief Transportation node. private: transport::NodePtr node; /// \brief Subscriber to log control messages. private: transport::SubscriberPtr logControlSub; /// \brief Publisher of log status messages. private: transport::PublisherPtr logStatusPub; /// \brief All the event connections. private: event::Connection_V connections; /// \brief Simulation pause state. private: bool pauseState; /// \brief This is a singleton private: friend class SingletonT<LogRecord>; /// \brief True if the logger is ready to start, and the previous run /// has finished. private: bool readyToStart; }; /// \} } } #endif
35.023316
80
0.642503
[ "object", "model" ]
3a4fddaa6fec71e91f42cde286014deb7ccb2ba4
19,755
cpp
C++
packages/monte_carlo/collision/photon/test/tstAdjointPhotoatomCore.cpp
bam241/FRENSIE
e1760cd792928699c84f2bdce70ff54228e88094
[ "BSD-3-Clause" ]
10
2019-11-14T19:58:30.000Z
2021-04-04T17:44:09.000Z
packages/monte_carlo/collision/photon/test/tstAdjointPhotoatomCore.cpp
bam241/FRENSIE
e1760cd792928699c84f2bdce70ff54228e88094
[ "BSD-3-Clause" ]
43
2020-03-03T19:59:20.000Z
2021-09-08T03:36:08.000Z
packages/monte_carlo/collision/photon/test/tstAdjointPhotoatomCore.cpp
bam241/FRENSIE
e1760cd792928699c84f2bdce70ff54228e88094
[ "BSD-3-Clause" ]
6
2020-02-12T17:37:07.000Z
2020-09-08T18:59:51.000Z
//---------------------------------------------------------------------------// //! //! \file tstAdjointPhotoatomCore.cpp //! \author Alex Robinson //! \brief Adjoint photoatom core unit tests //! //---------------------------------------------------------------------------// // Std Lib Includes #include <iostream> // FRENSIE Includes #include "MonteCarlo_AdjointPhotoatomCore.hpp" #include "MonteCarlo_AdjointPhotoatomicReactionNativeFactory.hpp" #include "Data_AdjointElectronPhotonRelaxationDataContainer.hpp" #include "Utility_StandardHashBasedGridSearcher.hpp" #include "Utility_PhysicalConstants.hpp" #include "Utility_UnitTestHarnessWithMain.hpp" //---------------------------------------------------------------------------// // Testing Variables //---------------------------------------------------------------------------// std::shared_ptr<MonteCarlo::AdjointPhotoatomCore> adjoint_photoatom_core; //---------------------------------------------------------------------------// // Check that the total forward reaction can be returned FRENSIE_UNIT_TEST( AdjointPhotoatomCore, getTotalForwardReaction ) { const MonteCarlo::PhotoatomicReaction& total_forward_reaction = adjoint_photoatom_core->getTotalForwardReaction(); FRENSIE_CHECK_EQUAL( total_forward_reaction.getReactionType(), MonteCarlo::TOTAL_PHOTOATOMIC_REACTION ); FRENSIE_CHECK_FLOATING_EQUALITY( total_forward_reaction.getThresholdEnergy(), 1e-3, 1e-15 ); double cross_section = total_forward_reaction.getCrossSection( 0.001 ); FRENSIE_CHECK_FLOATING_EQUALITY( cross_section, 73136.5325778411352, 1e-12 ); cross_section = total_forward_reaction.getCrossSection( 1.0 ); FRENSIE_CHECK_FLOATING_EQUALITY( cross_section, 2.96240900282447228, 1e-12 ); cross_section = total_forward_reaction.getCrossSection( 20.0 ); FRENSIE_CHECK_FLOATING_EQUALITY( cross_section, 1.08806003440055754, 1e-12 ); } //---------------------------------------------------------------------------// // Check that the scattering reactions can be returned FRENSIE_UNIT_TEST( AdjointPhotoatomCore, getScatteringReactions ) { const MonteCarlo::AdjointPhotoatomCore::ConstReactionMap& scattering_reactions = adjoint_photoatom_core->getScatteringReactions(); FRENSIE_CHECK_EQUAL( scattering_reactions.size(), 2 ); FRENSIE_CHECK( scattering_reactions.count( MonteCarlo::TOTAL_INCOHERENT_ADJOINT_PHOTOATOMIC_REACTION ) ); FRENSIE_CHECK( scattering_reactions.count( MonteCarlo::COHERENT_ADJOINT_PHOTOATOMIC_REACTION ) ); const MonteCarlo::AdjointPhotoatomicReaction& incoherent_reaction = *(scattering_reactions.find(MonteCarlo::TOTAL_INCOHERENT_ADJOINT_PHOTOATOMIC_REACTION)->second); double cross_section = incoherent_reaction.getCrossSection( 1e-3 ); FRENSIE_CHECK_FLOATING_EQUALITY( cross_section, 0.620920802623559753, 1e-12 ); cross_section = incoherent_reaction.getCrossSection( 1.0 ); FRENSIE_CHECK_FLOATING_EQUALITY( cross_section, 5.50415974966055277, 1e-12 ); cross_section = incoherent_reaction.getCrossSection( 20.0 ); FRENSIE_CHECK_SMALL( cross_section, 1e-12 ); const MonteCarlo::AdjointPhotoatomicReaction& coherent_reaction = *(scattering_reactions.find(MonteCarlo::COHERENT_ADJOINT_PHOTOATOMIC_REACTION)->second); cross_section = coherent_reaction.getCrossSection( 1e-3 ); FRENSIE_CHECK_FLOATING_EQUALITY( cross_section, 99.9639104922271571, 1e-12 ); cross_section = coherent_reaction.getCrossSection( 1.0 ); FRENSIE_CHECK_FLOATING_EQUALITY( cross_section, 0.00783640704399895215, 1e-12 ); cross_section = coherent_reaction.getCrossSection( 20.0 ); FRENSIE_CHECK_FLOATING_EQUALITY( cross_section, 1.96243862843467646e-05, 1e-12 ); } //---------------------------------------------------------------------------// // Check that the scattering reaction types can be returned FRENSIE_UNIT_TEST( AdjointPhotoatomCore, getScatteringReactionTypes ) { MonteCarlo::AdjointPhotoatomCore::ReactionEnumTypeSet reaction_types; adjoint_photoatom_core->getScatteringReactionTypes( reaction_types ); FRENSIE_CHECK_EQUAL( reaction_types.size(), 2 ); FRENSIE_CHECK( reaction_types.count( MonteCarlo::TOTAL_INCOHERENT_ADJOINT_PHOTOATOMIC_REACTION ) ); FRENSIE_CHECK( reaction_types.count( MonteCarlo::COHERENT_ADJOINT_PHOTOATOMIC_REACTION ) ); } //---------------------------------------------------------------------------// // Check that the absorption reactions can be returned FRENSIE_UNIT_TEST( AdjointPhotoatomCore, getAbsorptionReactions ) { const MonteCarlo::AdjointPhotoatomCore::ConstReactionMap& absorption_reactions = adjoint_photoatom_core->getAbsorptionReactions(); FRENSIE_CHECK_EQUAL( absorption_reactions.size(), 0 ); } //---------------------------------------------------------------------------// // Check that the absorption reaction types can be returned FRENSIE_UNIT_TEST( AdjointPhotoatomCore, getAbsorptionReactionTypes ) { MonteCarlo::AdjointPhotoatomCore::ReactionEnumTypeSet reaction_types; adjoint_photoatom_core->getAbsorptionReactionTypes( reaction_types ); FRENSIE_CHECK_EQUAL( reaction_types.size(), 0 ); } //---------------------------------------------------------------------------// // Check that the miscellaneous reactions can be returned FRENSIE_UNIT_TEST( AdjointPhotoatomCore, getMiscReactions ) { const MonteCarlo::AdjointPhotoatomCore::ConstReactionMap& misc_reactions = adjoint_photoatom_core->getMiscReactions(); FRENSIE_CHECK_EQUAL( misc_reactions.size(), 0 ); } //---------------------------------------------------------------------------// // Check that the miscellaneous reaction types can be returned FRENSIE_UNIT_TEST( AdjointPhotoatomCore, getMiscReactionTypes ) { MonteCarlo::AdjointPhotoatomCore::ReactionEnumTypeSet reaction_types; adjoint_photoatom_core->getMiscReactionTypes( reaction_types ); FRENSIE_CHECK_EQUAL( reaction_types.size(), 0 ); } //---------------------------------------------------------------------------// // Check that the reaction types can be returned FRENSIE_UNIT_TEST( AdjointPhotoatomCore, getReactionTypes ) { MonteCarlo::AdjointPhotoatomCore::ReactionEnumTypeSet reaction_types; adjoint_photoatom_core->getReactionTypes( reaction_types ); FRENSIE_CHECK_EQUAL( reaction_types.size(), 3 ); FRENSIE_CHECK( reaction_types.count( MonteCarlo::TOTAL_ADJOINT_PHOTOATOMIC_REACTION ) ); FRENSIE_CHECK( reaction_types.count( MonteCarlo::TOTAL_INCOHERENT_ADJOINT_PHOTOATOMIC_REACTION ) ); FRENSIE_CHECK( reaction_types.count( MonteCarlo::COHERENT_ADJOINT_PHOTOATOMIC_REACTION ) ); } //---------------------------------------------------------------------------// // Check that the line energy reactions can be returned FRENSIE_UNIT_TEST( AdjointPhotoatomCore, getLineEnergyReactions ) { const MonteCarlo::AdjointPhotoatomCore::ConstLineEnergyReactionMap& line_energy_reactions = adjoint_photoatom_core->getLineEnergyReactions(); FRENSIE_CHECK_EQUAL( line_energy_reactions.size(), 1 ); FRENSIE_CHECK( line_energy_reactions.count( Utility::PhysicalConstants::electron_rest_mass_energy ) ); const MonteCarlo::AdjointPhotoatomCore::ConstReactionMap& me_line_energy_reactions = line_energy_reactions.find( Utility::PhysicalConstants::electron_rest_mass_energy )->second; FRENSIE_CHECK_EQUAL( me_line_energy_reactions.size(), 2 ); FRENSIE_CHECK( me_line_energy_reactions.count( MonteCarlo::PAIR_PRODUCTION_ADJOINT_PHOTOATOMIC_REACTION ) ); FRENSIE_CHECK( me_line_energy_reactions.count( MonteCarlo::TRIPLET_PRODUCTION_ADJOINT_PHOTOATOMIC_REACTION ) ); const MonteCarlo::AdjointPhotoatomicReaction& pp_reaction = *(me_line_energy_reactions.find( MonteCarlo::PAIR_PRODUCTION_ADJOINT_PHOTOATOMIC_REACTION )->second ); FRENSIE_CHECK_FLOATING_EQUALITY( pp_reaction.getCrossSection( Utility::PhysicalConstants::electron_rest_mass_energy ), 14.739362127632583, 1e-12 ); const MonteCarlo::AdjointPhotoatomicReaction& tp_reaction = *(me_line_energy_reactions.find( MonteCarlo::TRIPLET_PRODUCTION_ADJOINT_PHOTOATOMIC_REACTION )->second ); FRENSIE_CHECK_FLOATING_EQUALITY( tp_reaction.getCrossSection( Utility::PhysicalConstants::electron_rest_mass_energy ), 0.6221793747726394, 1e-12 ); } //---------------------------------------------------------------------------// // Check that the critical line energies can be returned FRENSIE_UNIT_TEST( AdjointPhotoatomCore, getCriticalLineEnergies ) { const std::vector<double>& line_energies = adjoint_photoatom_core->getCriticalLineEnergies(); FRENSIE_REQUIRE_EQUAL( line_energies.size(), 2 ); FRENSIE_CHECK_EQUAL( line_energies[0], Utility::PhysicalConstants::electron_rest_mass_energy ); FRENSIE_CHECK_EQUAL( line_energies[1], 20.0 ); } //---------------------------------------------------------------------------// // Check that the grid searcher can be returned FRENSIE_UNIT_TEST( AdjointPhotoatomCore, getGridSearcher ) { const Utility::HashBasedGridSearcher<double>& grid_searcher = adjoint_photoatom_core->getGridSearcher(); size_t grid_index = grid_searcher.findLowerBinIndex( 1e-3 ); FRENSIE_CHECK_EQUAL( grid_index, 0u ); grid_index = grid_searcher.findLowerBinIndex( 20.0 ); FRENSIE_CHECK_EQUAL( grid_index, 1261 ); } //---------------------------------------------------------------------------// // Check if all of the reactions share a common energy grid FRENSIE_UNIT_TEST( AdjointPhotoatomCore, hasSharedEnergyGrid ) { FRENSIE_CHECK( adjoint_photoatom_core->hasSharedEnergyGrid() ); } //---------------------------------------------------------------------------// // Check the copy constructor FRENSIE_UNIT_TEST( AdjointPhotoatomCore, copy_constructor ) { MonteCarlo::AdjointPhotoatomCore core_copy( *adjoint_photoatom_core ); FRENSIE_CHECK_EQUAL( adjoint_photoatom_core->getCriticalLineEnergies(), core_copy.getCriticalLineEnergies() ); const MonteCarlo::PhotoatomicReaction& total_forward_reaction = core_copy.getTotalForwardReaction(); FRENSIE_CHECK_EQUAL( total_forward_reaction.getReactionType(), MonteCarlo::TOTAL_PHOTOATOMIC_REACTION ); FRENSIE_CHECK_FLOATING_EQUALITY( total_forward_reaction.getThresholdEnergy(), 1e-3, 1e-15 ); const MonteCarlo::AdjointPhotoatomCore::ConstReactionMap& scattering_reactions = core_copy.getScatteringReactions(); FRENSIE_CHECK_EQUAL( scattering_reactions.size(), 2 ); FRENSIE_CHECK( scattering_reactions.count( MonteCarlo::TOTAL_INCOHERENT_ADJOINT_PHOTOATOMIC_REACTION ) ); FRENSIE_CHECK( scattering_reactions.count( MonteCarlo::COHERENT_ADJOINT_PHOTOATOMIC_REACTION ) ); const MonteCarlo::AdjointPhotoatomCore::ConstReactionMap& absorption_reactions = core_copy.getAbsorptionReactions(); FRENSIE_CHECK_EQUAL( absorption_reactions.size(), 0 ); const MonteCarlo::AdjointPhotoatomCore::ConstLineEnergyReactionMap& line_energy_reactions = core_copy.getLineEnergyReactions(); FRENSIE_CHECK_EQUAL( line_energy_reactions.size(), 1 ); FRENSIE_CHECK( line_energy_reactions.count( Utility::PhysicalConstants::electron_rest_mass_energy ) ); const MonteCarlo::AdjointPhotoatomCore::ConstReactionMap& me_line_energy_reactions = line_energy_reactions.find( Utility::PhysicalConstants::electron_rest_mass_energy )->second; FRENSIE_CHECK_EQUAL( me_line_energy_reactions.size(), 2 ); FRENSIE_CHECK( me_line_energy_reactions.count( MonteCarlo::PAIR_PRODUCTION_ADJOINT_PHOTOATOMIC_REACTION ) ); FRENSIE_CHECK( me_line_energy_reactions.count( MonteCarlo::TRIPLET_PRODUCTION_ADJOINT_PHOTOATOMIC_REACTION ) ); } //---------------------------------------------------------------------------// // Check the assignment operator FRENSIE_UNIT_TEST( AdjointPhotoatomCore, assignment_operator ) { MonteCarlo::AdjointPhotoatomCore core_copy = *adjoint_photoatom_core; const MonteCarlo::PhotoatomicReaction& total_forward_reaction = core_copy.getTotalForwardReaction(); FRENSIE_CHECK_EQUAL( total_forward_reaction.getReactionType(), MonteCarlo::TOTAL_PHOTOATOMIC_REACTION ); FRENSIE_CHECK_FLOATING_EQUALITY( total_forward_reaction.getThresholdEnergy(), 1e-3, 1e-15 ); const MonteCarlo::AdjointPhotoatomCore::ConstReactionMap& scattering_reactions = core_copy.getScatteringReactions(); FRENSIE_CHECK_EQUAL( scattering_reactions.size(), 2 ); FRENSIE_CHECK( scattering_reactions.count( MonteCarlo::TOTAL_INCOHERENT_ADJOINT_PHOTOATOMIC_REACTION ) ); FRENSIE_CHECK( scattering_reactions.count( MonteCarlo::COHERENT_ADJOINT_PHOTOATOMIC_REACTION ) ); const MonteCarlo::AdjointPhotoatomCore::ConstReactionMap& absorption_reactions = core_copy.getAbsorptionReactions(); FRENSIE_CHECK_EQUAL( absorption_reactions.size(), 0 ); const MonteCarlo::AdjointPhotoatomCore::ConstLineEnergyReactionMap& line_energy_reactions = core_copy.getLineEnergyReactions(); FRENSIE_CHECK_EQUAL( line_energy_reactions.size(), 1 ); FRENSIE_CHECK( line_energy_reactions.count( Utility::PhysicalConstants::electron_rest_mass_energy ) ); const MonteCarlo::AdjointPhotoatomCore::ConstReactionMap& me_line_energy_reactions = line_energy_reactions.find( Utility::PhysicalConstants::electron_rest_mass_energy )->second; FRENSIE_CHECK_EQUAL( me_line_energy_reactions.size(), 2 ); FRENSIE_CHECK( me_line_energy_reactions.count( MonteCarlo::PAIR_PRODUCTION_ADJOINT_PHOTOATOMIC_REACTION ) ); FRENSIE_CHECK( me_line_energy_reactions.count( MonteCarlo::TRIPLET_PRODUCTION_ADJOINT_PHOTOATOMIC_REACTION ) ); } //---------------------------------------------------------------------------// // Custom Setup //---------------------------------------------------------------------------// FRENSIE_CUSTOM_UNIT_TEST_SETUP_BEGIN(); std::string test_native_file_name; FRENSIE_CUSTOM_UNIT_TEST_COMMAND_LINE_OPTIONS() { ADD_STANDARD_OPTION_AND_ASSIGN_VALUE( "test_native_file", test_native_file_name, "", "Test Native file name" ); } FRENSIE_CUSTOM_UNIT_TEST_INIT() { // Create the native data file container Data::AdjointElectronPhotonRelaxationDataContainer data_container( test_native_file_name ); // Create the union energy grid std::shared_ptr<std::vector<double> > energy_grid( new std::vector<double> ); MonteCarlo::AdjointPhotoatomicReactionNativeFactory::createUnionEnergyGrid( data_container, *energy_grid, 20.0 ); // Create the hash based grid searcher std::shared_ptr<const Utility::HashBasedGridSearcher<double> > grid_searcher( new Utility::StandardHashBasedGridSearcher<std::vector<double>,false>( energy_grid, 100 ) ); // Create the total forward reaction std::shared_ptr<const MonteCarlo::PhotoatomicReaction> total_forward_reaction; MonteCarlo::AdjointPhotoatomicReactionNativeFactory::createTotalForwardReaction( data_container, energy_grid, grid_searcher, MonteCarlo::WH_INCOHERENT_ADJOINT_MODEL, total_forward_reaction ); // Create the scattering reactions MonteCarlo::AdjointPhotoatomCore::ConstReactionMap scattering_reactions; std::shared_ptr<std::vector<double> > critical_line_energies( new std::vector<double>(2) ); (*critical_line_energies)[0] = Utility::PhysicalConstants::electron_rest_mass_energy; (*critical_line_energies)[1] = 20.0; { std::vector<std::shared_ptr<const MonteCarlo::AdjointPhotoatomicReaction> > incoherent_reactions; MonteCarlo::AdjointPhotoatomicReactionNativeFactory::createIncoherentReactions( data_container, energy_grid, grid_searcher, incoherent_reactions, MonteCarlo::WH_INCOHERENT_ADJOINT_MODEL, MonteCarlo::THREE_BRANCH_INVERSE_MIXED_ADJOINT_KN_SAMPLING, critical_line_energies ); scattering_reactions[incoherent_reactions[0]->getReactionType()] = incoherent_reactions[0]; } { std::shared_ptr<const MonteCarlo::AdjointPhotoatomicReaction> coherent_reaction; MonteCarlo::AdjointPhotoatomicReactionNativeFactory::createCoherentReaction( data_container, energy_grid, grid_searcher, coherent_reaction ); scattering_reactions[coherent_reaction->getReactionType()] = coherent_reaction; } // Create the line energy reactions MonteCarlo::AdjointPhotoatomCore::ConstLineEnergyReactionMap line_energy_reactions; { MonteCarlo::AdjointPhotoatomCore::ConstReactionMap& me_line_energy_reactions = line_energy_reactions[Utility::PhysicalConstants::electron_rest_mass_energy]; std::shared_ptr<const MonteCarlo::LineEnergyAdjointPhotoatomicReaction> reaction; MonteCarlo::AdjointPhotoatomicReactionNativeFactory::createPairProductionReaction( data_container, energy_grid, grid_searcher, reaction, critical_line_energies ); me_line_energy_reactions[reaction->getReactionType()] = reaction; MonteCarlo::AdjointPhotoatomicReactionNativeFactory::createTripletProductionReaction( data_container, energy_grid, grid_searcher, reaction, critical_line_energies ); me_line_energy_reactions[reaction->getReactionType()] = reaction; } // Construct the core adjoint_photoatom_core.reset( new MonteCarlo::AdjointPhotoatomCore( energy_grid, grid_searcher, critical_line_energies, total_forward_reaction, scattering_reactions, MonteCarlo::AdjointPhotoatomCore::ConstReactionMap(), line_energy_reactions, false, Utility::LinLin() ) ); // Initialize the random number generator Utility::RandomNumberGenerator::createStreams(); } FRENSIE_CUSTOM_UNIT_TEST_SETUP_END(); //---------------------------------------------------------------------------// // end tstAdjointPhotoatomCore.cpp //---------------------------------------------------------------------------//
43.513216
120
0.650468
[ "vector" ]
3a50ae652a4c8c2a5ca9d5961bc4cc1a8a3e8941
2,552
cpp
C++
Core/CLI/src/cli_alias.cpp
emamanto/Soar
72d2bc095068dd87ac78dad4f48938f6edc0353a
[ "BSD-2-Clause" ]
2
2019-11-21T14:40:00.000Z
2020-10-25T15:44:53.000Z
Core/CLI/src/cli_alias.cpp
emamanto/Soar
72d2bc095068dd87ac78dad4f48938f6edc0353a
[ "BSD-2-Clause" ]
null
null
null
Core/CLI/src/cli_alias.cpp
emamanto/Soar
72d2bc095068dd87ac78dad4f48938f6edc0353a
[ "BSD-2-Clause" ]
2
2019-12-23T05:06:28.000Z
2020-01-16T12:57:55.000Z
#include "portability.h" #include "cli_CommandLineInterface.h" #include "cli_Aliases.h" #include "sml_AgentSML.h" #include "sml_Names.h" #include "sml_Utils.h" #include "agent.h" #include "output_manager.h" using namespace cli; using namespace sml; bool CommandLineInterface::DoAlias(std::vector< std::string >* argv, bool doRemove) { agent* thisAgent = m_pAgentSML->GetSoarAgent(); if (doRemove) { m_Parser.GetAliases().SetAlias(*argv); return true; } if (!argv || argv->size() == 1) { std::map< std::string, std::vector< std::string > >::const_iterator iter = m_Parser.GetAliases().Begin(); if (iter == m_Parser.GetAliases().End()) { m_Result << "No aliases found."; return true; } Output_Manager* outputManager = thisAgent->outputManager; if (!argv) PrintCLIMessage_Header("Soar Aliases", 43); outputManager->reset_column_indents(); outputManager->set_column_indent(0, 28); outputManager->set_column_indent(1, 43); std::string lStr; while (iter != m_Parser.GetAliases().End()) { if (!argv || argv->front() == iter->first) { std::string expansion; for (std::vector<std::string>::const_iterator j = iter->second.begin(); j != iter->second.end(); ++j) { expansion += *j; expansion += ' '; } expansion = expansion.substr(0, expansion.length() - 1); if (m_RawOutput) { lStr.clear(); if (!argv) { outputManager->sprinta_sf(thisAgent, lStr, "%s %-%-= %s\n", iter->first.c_str(), expansion.c_str()); m_Result << lStr; } else { m_Result << iter->first << " = \"" << expansion << "\"\n"; } } else { AppendArgTagFast(sml_Names::kParamAlias, sml_Names::kTypeString, iter->first); AppendArgTagFast(sml_Names::kParamAliasedCommand, sml_Names::kTypeString, expansion); } if (argv) { return true; } } ++iter; } return true; } m_Parser.GetAliases().SetAlias(*argv); return true; }
30.023529
124
0.487461
[ "vector" ]
3a52fb587a4220eae61fe552e6cbbba63581abb3
111,481
cpp
C++
SDK/ARKSurvivalEvolved_Tropeognathus_Character_BP_functions.cpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
10
2020-02-17T19:08:46.000Z
2021-07-31T11:07:19.000Z
SDK/ARKSurvivalEvolved_Tropeognathus_Character_BP_functions.cpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
9
2020-02-17T18:15:41.000Z
2021-06-06T19:17:34.000Z
SDK/ARKSurvivalEvolved_Tropeognathus_Character_BP_functions.cpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
3
2020-07-22T17:42:07.000Z
2021-06-19T17:16:13.000Z
// ARKSurvivalEvolved (329.9) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_Tropeognathus_Character_BP_parameters.hpp" namespace sdk { //--------------------------------------------------------------------------- //Functions //--------------------------------------------------------------------------- // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.GetHudData // () // Parameters: // bool HasSaddle (Parm, OutParm, ZeroConstructor, IsPlainOldData) // class UPrimalInventoryComponent* InventoryComponent (Parm, OutParm, ZeroConstructor, IsPlainOldData) // class UClass* SaddleFuelItem (Parm, OutParm, ZeroConstructor, IsPlainOldData) // class UClass* FlakCannonAmmoItem (Parm, OutParm, ZeroConstructor, IsPlainOldData) // bool IsUsingSuperFlight (Parm, OutParm, ZeroConstructor, IsPlainOldData) // bool IsUsingSuperFlightBoost (Parm, OutParm, ZeroConstructor, IsPlainOldData) // float FuelPercent (Parm, OutParm, ZeroConstructor, IsPlainOldData) // float CannonCooldownPercent (Parm, OutParm, ZeroConstructor, IsPlainOldData) // float SpeedPercent (Parm, OutParm, ZeroConstructor, IsPlainOldData) void ATropeognathus_Character_BP_C::GetHudData(bool* HasSaddle, class UPrimalInventoryComponent** InventoryComponent, class UClass** SaddleFuelItem, class UClass** FlakCannonAmmoItem, bool* IsUsingSuperFlight, bool* IsUsingSuperFlightBoost, float* FuelPercent, float* CannonCooldownPercent, float* SpeedPercent) { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.GetHudData"); ATropeognathus_Character_BP_C_GetHudData_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; if (HasSaddle != nullptr) *HasSaddle = params.HasSaddle; if (InventoryComponent != nullptr) *InventoryComponent = params.InventoryComponent; if (SaddleFuelItem != nullptr) *SaddleFuelItem = params.SaddleFuelItem; if (FlakCannonAmmoItem != nullptr) *FlakCannonAmmoItem = params.FlakCannonAmmoItem; if (IsUsingSuperFlight != nullptr) *IsUsingSuperFlight = params.IsUsingSuperFlight; if (IsUsingSuperFlightBoost != nullptr) *IsUsingSuperFlightBoost = params.IsUsingSuperFlightBoost; if (FuelPercent != nullptr) *FuelPercent = params.FuelPercent; if (CannonCooldownPercent != nullptr) *CannonCooldownPercent = params.CannonCooldownPercent; if (SpeedPercent != nullptr) *SpeedPercent = params.SpeedPercent; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.BPGetHUDElements // (Exec, Static, NetMulticast, Public, Private, Protected, HasDefaults, DLLImport, NetValidate) // Parameters: // class APlayerController** ForPC (Parm, ZeroConstructor, IsPlainOldData) // TArray<struct FHUDElement> OutElements (Parm, OutParm, ZeroConstructor) void ATropeognathus_Character_BP_C::STATIC_BPGetHUDElements(class APlayerController** ForPC, TArray<struct FHUDElement>* OutElements) { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.BPGetHUDElements"); ATropeognathus_Character_BP_C_BPGetHUDElements_Params params; params.ForPC = ForPC; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; if (OutElements != nullptr) *OutElements = params.OutElements; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.ReceiveBeginPlay // () void ATropeognathus_Character_BP_C::ReceiveBeginPlay() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.ReceiveBeginPlay"); ATropeognathus_Character_BP_C_ReceiveBeginPlay_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.IsUsingWindGust // () // Parameters: // bool Ret (Parm, OutParm, ZeroConstructor, IsPlainOldData) // double StartTime (Parm, OutParm, ZeroConstructor, IsPlainOldData) void ATropeognathus_Character_BP_C::IsUsingWindGust(bool* Ret, double* StartTime) { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.IsUsingWindGust"); ATropeognathus_Character_BP_C_IsUsingWindGust_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; if (Ret != nullptr) *Ret = params.Ret; if (StartTime != nullptr) *StartTime = params.StartTime; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.IsUsingForwardInput // () // Parameters: // bool Ret (Parm, OutParm, ZeroConstructor, IsPlainOldData) void ATropeognathus_Character_BP_C::IsUsingForwardInput(bool* Ret) { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.IsUsingForwardInput"); ATropeognathus_Character_BP_C_IsUsingForwardInput_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; if (Ret != nullptr) *Ret = params.Ret; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.BPUnsetupDinoTameable // () void ATropeognathus_Character_BP_C::BPUnsetupDinoTameable() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.BPUnsetupDinoTameable"); ATropeognathus_Character_BP_C_BPUnsetupDinoTameable_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.BSetupDinoTameable // () void ATropeognathus_Character_BP_C::BSetupDinoTameable() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.BSetupDinoTameable"); ATropeognathus_Character_BP_C_BSetupDinoTameable_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.UpdateRiderSocket // () void ATropeognathus_Character_BP_C::UpdateRiderSocket() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.UpdateRiderSocket"); ATropeognathus_Character_BP_C_UpdateRiderSocket_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.GetOverrideSocket // () // Parameters: // struct FName* From (Parm, ZeroConstructor, IsPlainOldData) // struct FName ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) struct FName ATropeognathus_Character_BP_C::GetOverrideSocket(struct FName* From) { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.GetOverrideSocket"); ATropeognathus_Character_BP_C_GetOverrideSocket_Params params; params.From = From; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.AllowWakingTame // () // Parameters: // class APlayerController** ForPC (Parm, ZeroConstructor, IsPlainOldData) // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) bool ATropeognathus_Character_BP_C::AllowWakingTame(class APlayerController** ForPC) { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.AllowWakingTame"); ATropeognathus_Character_BP_C_AllowWakingTame_Params params; params.ForPC = ForPC; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.OwningClientTryFlakCannonFire // () void ATropeognathus_Character_BP_C::OwningClientTryFlakCannonFire() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.OwningClientTryFlakCannonFire"); ATropeognathus_Character_BP_C_OwningClientTryFlakCannonFire_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.InterceptInputEvent // () // Parameters: // class FString* InputName (Parm, ZeroConstructor) void ATropeognathus_Character_BP_C::InterceptInputEvent(class FString* InputName) { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.InterceptInputEvent"); ATropeognathus_Character_BP_C_InterceptInputEvent_Params params; params.InputName = InputName; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.AllowPlayMontage // () // Parameters: // class UAnimMontage** AnimMontage (Parm, ZeroConstructor, IsPlainOldData) // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) bool ATropeognathus_Character_BP_C::AllowPlayMontage(class UAnimMontage** AnimMontage) { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.AllowPlayMontage"); ATropeognathus_Character_BP_C_AllowPlayMontage_Params params; params.AnimMontage = AnimMontage; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.GetDinoLevelUpAnimation // () // Parameters: // class UAnimMontage* ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) class UAnimMontage* ATropeognathus_Character_BP_C::GetDinoLevelUpAnimation() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.GetDinoLevelUpAnimation"); ATropeognathus_Character_BP_C_GetDinoLevelUpAnimation_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.UpdateTaming // () void ATropeognathus_Character_BP_C::UpdateTaming() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.UpdateTaming"); ATropeognathus_Character_BP_C_UpdateTaming_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.BPShowTamingPanel // () // Parameters: // bool* currentVisibility (Parm, ZeroConstructor, IsPlainOldData) // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) bool ATropeognathus_Character_BP_C::BPShowTamingPanel(bool* currentVisibility) { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.BPShowTamingPanel"); ATropeognathus_Character_BP_C_BPShowTamingPanel_Params params; params.currentVisibility = currentVisibility; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.GetTamingBuff // () // Parameters: // bool IsValid (Parm, OutParm, ZeroConstructor, IsPlainOldData) // class APrimalBuff* Buff (Parm, OutParm, ZeroConstructor, IsPlainOldData) void ATropeognathus_Character_BP_C::GetTamingBuff(bool* IsValid, class APrimalBuff** Buff) { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.GetTamingBuff"); ATropeognathus_Character_BP_C_GetTamingBuff_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; if (IsValid != nullptr) *IsValid = params.IsValid; if (Buff != nullptr) *Buff = params.Buff; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.BPOverrideTamingDescriptionLabel // (Net, NetReliable, NetRequest, Exec, Native, NetResponse, Public, Protected, HasDefaults, DLLImport, NetValidate) // Parameters: // struct FSlateColor TextColor (Parm, OutParm, ReferenceParm) // class FString ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm) class FString ATropeognathus_Character_BP_C::BPOverrideTamingDescriptionLabel(struct FSlateColor* TextColor) { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.BPOverrideTamingDescriptionLabel"); ATropeognathus_Character_BP_C_BPOverrideTamingDescriptionLabel_Params params; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; if (TextColor != nullptr) *TextColor = params.TextColor; return params.ReturnValue; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.BlueprintCanAttack // () // Parameters: // int* AttackIndex (Parm, ZeroConstructor, IsPlainOldData) // float* Distance (Parm, ZeroConstructor, IsPlainOldData) // float* attackRangeOffset (Parm, ZeroConstructor, IsPlainOldData) // class AActor** OtherTarget (Parm, ZeroConstructor, IsPlainOldData) // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) bool ATropeognathus_Character_BP_C::BlueprintCanAttack(int* AttackIndex, float* Distance, float* attackRangeOffset, class AActor** OtherTarget) { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.BlueprintCanAttack"); ATropeognathus_Character_BP_C_BlueprintCanAttack_Params params; params.AttackIndex = AttackIndex; params.Distance = Distance; params.attackRangeOffset = attackRangeOffset; params.OtherTarget = OtherTarget; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.BPAdjustDamage // () // Parameters: // float* IncomingDamage (Parm, ZeroConstructor, IsPlainOldData) // struct FDamageEvent* TheDamageEvent (Parm) // class AController** EventInstigator (Parm, ZeroConstructor, IsPlainOldData) // class AActor** DamageCauser (Parm, ZeroConstructor, IsPlainOldData) // bool* bIsPointDamage (Parm, ZeroConstructor, IsPlainOldData) // struct FHitResult* PointHitInfo (Parm) // float ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) float ATropeognathus_Character_BP_C::BPAdjustDamage(float* IncomingDamage, struct FDamageEvent* TheDamageEvent, class AController** EventInstigator, class AActor** DamageCauser, bool* bIsPointDamage, struct FHitResult* PointHitInfo) { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.BPAdjustDamage"); ATropeognathus_Character_BP_C_BPAdjustDamage_Params params; params.IncomingDamage = IncomingDamage; params.TheDamageEvent = TheDamageEvent; params.EventInstigator = EventInstigator; params.DamageCauser = DamageCauser; params.bIsPointDamage = bIsPointDamage; params.PointHitInfo = PointHitInfo; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.Get Replicated Control Rotation Public // () // Parameters: // struct FRotator ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) struct FRotator ATropeognathus_Character_BP_C::Get_Replicated_Control_Rotation_Public() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.Get Replicated Control Rotation Public"); ATropeognathus_Character_BP_C_Get_Replicated_Control_Rotation_Public_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.IsPlayingBlockingAnim // () // Parameters: // bool ReturnVal (Parm, OutParm, ZeroConstructor, IsPlainOldData) void ATropeognathus_Character_BP_C::IsPlayingBlockingAnim(bool* ReturnVal) { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.IsPlayingBlockingAnim"); ATropeognathus_Character_BP_C_IsPlayingBlockingAnim_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; if (ReturnVal != nullptr) *ReturnVal = params.ReturnVal; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.Is Using Drafting Public // () // Parameters: // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) // bool DraftAcked (Parm, OutParm, ZeroConstructor, IsPlainOldData) bool ATropeognathus_Character_BP_C::Is_Using_Drafting_Public(bool* DraftAcked) { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.Is Using Drafting Public"); ATropeognathus_Character_BP_C_Is_Using_Drafting_Public_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; if (DraftAcked != nullptr) *DraftAcked = params.DraftAcked; return params.ReturnValue; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.IsUsingDrafting // () // Parameters: // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) // bool DraftAcked (Parm, OutParm, ZeroConstructor, IsPlainOldData) bool ATropeognathus_Character_BP_C::IsUsingDrafting(bool* DraftAcked) { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.IsUsingDrafting"); ATropeognathus_Character_BP_C_IsUsingDrafting_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; if (DraftAcked != nullptr) *DraftAcked = params.DraftAcked; return params.ReturnValue; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.BPGetRiderSocket // () // Parameters: // struct FName ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) struct FName ATropeognathus_Character_BP_C::BPGetRiderSocket() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.BPGetRiderSocket"); ATropeognathus_Character_BP_C_BPGetRiderSocket_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.IsJumpHeld // (Net, NetRequest, Exec, Native, Event, NetResponse, Public, Protected, HasDefaults, DLLImport, NetValidate) // Parameters: // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) bool ATropeognathus_Character_BP_C::IsJumpHeld() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.IsJumpHeld"); ATropeognathus_Character_BP_C_IsJumpHeld_Params params; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.BPOnDinoCheat // () // Parameters: // struct FName* CheatName (Parm, ZeroConstructor, IsPlainOldData) // bool* bSetValue (Parm, ZeroConstructor, IsPlainOldData) // float* Value (Parm, ZeroConstructor, IsPlainOldData) void ATropeognathus_Character_BP_C::BPOnDinoCheat(struct FName* CheatName, bool* bSetValue, float* Value) { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.BPOnDinoCheat"); ATropeognathus_Character_BP_C_BPOnDinoCheat_Params params; params.CheatName = CheatName; params.bSetValue = bSetValue; params.Value = Value; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.GetReplicatedControlRotation // () // Parameters: // struct FRotator ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) struct FRotator ATropeognathus_Character_BP_C::GetReplicatedControlRotation() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.GetReplicatedControlRotation"); ATropeognathus_Character_BP_C_GetReplicatedControlRotation_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.ReceiveTick // () // Parameters: // float* DeltaSeconds (Parm, ZeroConstructor, IsPlainOldData) void ATropeognathus_Character_BP_C::ReceiveTick(float* DeltaSeconds) { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.ReceiveTick"); ATropeognathus_Character_BP_C_ReceiveTick_Params params; params.DeltaSeconds = DeltaSeconds; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.BPDoAttack // () // Parameters: // int* AttackIndex (Parm, ZeroConstructor, IsPlainOldData) void ATropeognathus_Character_BP_C::BPDoAttack(int* AttackIndex) { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.BPDoAttack"); ATropeognathus_Character_BP_C_BPDoAttack_Params params; params.AttackIndex = AttackIndex; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.BPGetCrosshairAlpha // () // Parameters: // float ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) float ATropeognathus_Character_BP_C::BPGetCrosshairAlpha() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.BPGetCrosshairAlpha"); ATropeognathus_Character_BP_C_BPGetCrosshairAlpha_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.IsFlakCannonOnCooldown // () // Parameters: // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) bool ATropeognathus_Character_BP_C::IsFlakCannonOnCooldown() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.IsFlakCannonOnCooldown"); ATropeognathus_Character_BP_C_IsFlakCannonOnCooldown_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.BPGetCrosshairLocation // () // Parameters: // float* CanvasClipX (Parm, ZeroConstructor, IsPlainOldData) // float* CanvasClipY (Parm, ZeroConstructor, IsPlainOldData) // float OutX (Parm, OutParm, ZeroConstructor, IsPlainOldData) // float OutY (Parm, OutParm, ZeroConstructor, IsPlainOldData) void ATropeognathus_Character_BP_C::BPGetCrosshairLocation(float* CanvasClipX, float* CanvasClipY, float* OutX, float* OutY) { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.BPGetCrosshairLocation"); ATropeognathus_Character_BP_C_BPGetCrosshairLocation_Params params; params.CanvasClipX = CanvasClipX; params.CanvasClipY = CanvasClipY; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; if (OutX != nullptr) *OutX = params.OutX; if (OutY != nullptr) *OutY = params.OutY; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.ConsumeItem // () // Parameters: // class UClass* Item (Parm, ZeroConstructor, IsPlainOldData) void ATropeognathus_Character_BP_C::ConsumeItem(class UClass* Item) { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.ConsumeItem"); ATropeognathus_Character_BP_C_ConsumeItem_Params params; params.Item = Item; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.HasAmmo // () // Parameters: // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) // int Quantity (Parm, OutParm, ZeroConstructor, IsPlainOldData) bool ATropeognathus_Character_BP_C::HasAmmo(int* Quantity) { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.HasAmmo"); ATropeognathus_Character_BP_C_HasAmmo_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; if (Quantity != nullptr) *Quantity = params.Quantity; return params.ReturnValue; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.BPOnStopJump // () // Parameters: // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) bool ATropeognathus_Character_BP_C::BPOnStopJump() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.BPOnStopJump"); ATropeognathus_Character_BP_C_BPOnStopJump_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.Fire Flak Cannon // (NetRequest, Exec, Native, Event, NetResponse, Static, Public, Private, Protected, HasDefaults, DLLImport, NetValidate) // Parameters: // struct FVector Dir (Parm, ZeroConstructor, IsPlainOldData) // struct FVector Loc (Parm, ZeroConstructor, IsPlainOldData) void ATropeognathus_Character_BP_C::STATIC_Fire_Flak_Cannon(const struct FVector& Dir, const struct FVector& Loc) { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.Fire Flak Cannon"); ATropeognathus_Character_BP_C_Fire_Flak_Cannon_Params params; params.Dir = Dir; params.Loc = Loc; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.Has Saddle Public // () // Parameters: // bool Ret (Parm, OutParm, ZeroConstructor, IsPlainOldData) // bool RetIsSuperSaddle (Parm, OutParm, ZeroConstructor, IsPlainOldData) void ATropeognathus_Character_BP_C::Has_Saddle_Public(bool* Ret, bool* RetIsSuperSaddle) { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.Has Saddle Public"); ATropeognathus_Character_BP_C_Has_Saddle_Public_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; if (Ret != nullptr) *Ret = params.Ret; if (RetIsSuperSaddle != nullptr) *RetIsSuperSaddle = params.RetIsSuperSaddle; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.OnInventoryItemGrind // () void ATropeognathus_Character_BP_C::OnInventoryItemGrind() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.OnInventoryItemGrind"); ATropeognathus_Character_BP_C_OnInventoryItemGrind_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.UpdateWindGustCooldownVFX // () void ATropeognathus_Character_BP_C::UpdateWindGustCooldownVFX() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.UpdateWindGustCooldownVFX"); ATropeognathus_Character_BP_C_UpdateWindGustCooldownVFX_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.BPOverrideGetAttackAnimationIndex // () // Parameters: // int* AttackIndex (Parm, ZeroConstructor, IsPlainOldData) // TArray<class UAnimMontage*> AnimationArray (Parm, OutParm, ZeroConstructor, ReferenceParm) // int ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) int ATropeognathus_Character_BP_C::BPOverrideGetAttackAnimationIndex(int* AttackIndex, TArray<class UAnimMontage*>* AnimationArray) { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.BPOverrideGetAttackAnimationIndex"); ATropeognathus_Character_BP_C_BPOverrideGetAttackAnimationIndex_Params params; params.AttackIndex = AttackIndex; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; if (AnimationArray != nullptr) *AnimationArray = params.AnimationArray; return params.ReturnValue; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.TryInterruptLanding // () // Parameters: // TEnumAsByte<EMovementMode> Selection (Parm, ZeroConstructor, IsPlainOldData) void ATropeognathus_Character_BP_C::TryInterruptLanding(TEnumAsByte<EMovementMode> Selection) { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.TryInterruptLanding"); ATropeognathus_Character_BP_C_TryInterruptLanding_Params params; params.Selection = Selection; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.OnRep_SuperFlight // () void ATropeognathus_Character_BP_C::OnRep_SuperFlight() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.OnRep_SuperFlight"); ATropeognathus_Character_BP_C_OnRep_SuperFlight_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.SetSuperFlight // () // Parameters: // bool Value (Parm, ZeroConstructor, IsPlainOldData) // bool TriggerVFX (Parm, ZeroConstructor, IsPlainOldData) void ATropeognathus_Character_BP_C::SetSuperFlight(bool Value, bool TriggerVFX) { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.SetSuperFlight"); ATropeognathus_Character_BP_C_SetSuperFlight_Params params; params.Value = Value; params.TriggerVFX = TriggerVFX; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.Get Current Percent Of Max Fly Speed Public // () // Parameters: // float ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) float ATropeognathus_Character_BP_C::Get_Current_Percent_Of_Max_Fly_Speed_Public() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.Get Current Percent Of Max Fly Speed Public"); ATropeognathus_Character_BP_C_Get_Current_Percent_Of_Max_Fly_Speed_Public_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.Is Using Super Flight Public // () // Parameters: // bool Ret (Parm, OutParm, ZeroConstructor, IsPlainOldData) // double StartedEndingTime (Parm, OutParm, ZeroConstructor, IsPlainOldData) void ATropeognathus_Character_BP_C::Is_Using_Super_Flight_Public(bool* Ret, double* StartedEndingTime) { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.Is Using Super Flight Public"); ATropeognathus_Character_BP_C_Is_Using_Super_Flight_Public_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; if (Ret != nullptr) *Ret = params.Ret; if (StartedEndingTime != nullptr) *StartedEndingTime = params.StartedEndingTime; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.IsUsingSuperFlight // () // Parameters: // bool Ret (Parm, OutParm, ZeroConstructor, IsPlainOldData) // double StartedEndingTime (Parm, OutParm, ZeroConstructor, IsPlainOldData) void ATropeognathus_Character_BP_C::IsUsingSuperFlight(bool* Ret, double* StartedEndingTime) { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.IsUsingSuperFlight"); ATropeognathus_Character_BP_C_IsUsingSuperFlight_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; if (Ret != nullptr) *Ret = params.Ret; if (StartedEndingTime != nullptr) *StartedEndingTime = params.StartedEndingTime; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.UpdateSuperFlightBoost // () void ATropeognathus_Character_BP_C::UpdateSuperFlightBoost() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.UpdateSuperFlightBoost"); ATropeognathus_Character_BP_C_UpdateSuperFlightBoost_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.Is Using Super Flight Boost Public // () // Parameters: // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) bool ATropeognathus_Character_BP_C::Is_Using_Super_Flight_Boost_Public() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.Is Using Super Flight Boost Public"); ATropeognathus_Character_BP_C_Is_Using_Super_Flight_Boost_Public_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.IsUsingSuperFlightBoost // () // Parameters: // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) // double StartTime (Parm, OutParm, ZeroConstructor, IsPlainOldData) bool ATropeognathus_Character_BP_C::IsUsingSuperFlightBoost(double* StartTime) { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.IsUsingSuperFlightBoost"); ATropeognathus_Character_BP_C_IsUsingSuperFlightBoost_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; if (StartTime != nullptr) *StartTime = params.StartTime; return params.ReturnValue; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.BPGetDragSocketName // () // Parameters: // class APrimalCharacter** DraggingChar (Parm, ZeroConstructor, IsPlainOldData) // struct FName ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) struct FName ATropeognathus_Character_BP_C::BPGetDragSocketName(class APrimalCharacter** DraggingChar) { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.BPGetDragSocketName"); ATropeognathus_Character_BP_C_BPGetDragSocketName_Params params; params.DraggingChar = DraggingChar; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.OnCarriedStruggle // () void ATropeognathus_Character_BP_C::OnCarriedStruggle() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.OnCarriedStruggle"); ATropeognathus_Character_BP_C_OnCarriedStruggle_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.IsUsingWingGust // () // Parameters: // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) bool ATropeognathus_Character_BP_C::IsUsingWingGust() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.IsUsingWingGust"); ATropeognathus_Character_BP_C_IsUsingWingGust_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.Update Jet FX // () void ATropeognathus_Character_BP_C::Update_Jet_FX() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.Update Jet FX"); ATropeognathus_Character_BP_C_Update_Jet_FX_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.HasFuel // () // Parameters: // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) // int Quantity (Parm, OutParm, ZeroConstructor, IsPlainOldData) bool ATropeognathus_Character_BP_C::HasFuel(int* Quantity) { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.HasFuel"); ATropeognathus_Character_BP_C_HasFuel_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; if (Quantity != nullptr) *Quantity = params.Quantity; return params.ReturnValue; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.UpdateFuel // () void ATropeognathus_Character_BP_C::UpdateFuel() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.UpdateFuel"); ATropeognathus_Character_BP_C_UpdateFuel_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.BPDidSetCarriedCharacter // () // Parameters: // class APrimalCharacter** PreviousCarriedCharacter (Parm, ZeroConstructor, IsPlainOldData) void ATropeognathus_Character_BP_C::BPDidSetCarriedCharacter(class APrimalCharacter** PreviousCarriedCharacter) { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.BPDidSetCarriedCharacter"); ATropeognathus_Character_BP_C_BPDidSetCarriedCharacter_Params params; params.PreviousCarriedCharacter = PreviousCarriedCharacter; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.HasSaddle // () // Parameters: // bool Ret (Parm, OutParm, ZeroConstructor, IsPlainOldData) // bool RetIsSuperSaddle (Parm, OutParm, ZeroConstructor, IsPlainOldData) void ATropeognathus_Character_BP_C::HasSaddle(bool* Ret, bool* RetIsSuperSaddle) { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.HasSaddle"); ATropeognathus_Character_BP_C_HasSaddle_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; if (Ret != nullptr) *Ret = params.Ret; if (RetIsSuperSaddle != nullptr) *RetIsSuperSaddle = params.RetIsSuperSaddle; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.UpdateDrafting // () void ATropeognathus_Character_BP_C::UpdateDrafting() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.UpdateDrafting"); ATropeognathus_Character_BP_C_UpdateDrafting_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.BPGetDragSocketDinoName // () // Parameters: // class APrimalDinoCharacter** aGrabbedDino (Parm, ZeroConstructor, IsPlainOldData) // struct FName ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) struct FName ATropeognathus_Character_BP_C::BPGetDragSocketDinoName(class APrimalDinoCharacter** aGrabbedDino) { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.BPGetDragSocketDinoName"); ATropeognathus_Character_BP_C_BPGetDragSocketDinoName_Params params; params.aGrabbedDino = aGrabbedDino; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.UpdateSuperFlightStateData // () void ATropeognathus_Character_BP_C::UpdateSuperFlightStateData() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.UpdateSuperFlightStateData"); ATropeognathus_Character_BP_C_UpdateSuperFlightStateData_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.UpdateAcceleration // () void ATropeognathus_Character_BP_C::UpdateAcceleration() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.UpdateAcceleration"); ATropeognathus_Character_BP_C_UpdateAcceleration_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.UpdateRotationRate // () void ATropeognathus_Character_BP_C::UpdateRotationRate() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.UpdateRotationRate"); ATropeognathus_Character_BP_C_UpdateRotationRate_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.UpdateAllyAOE // () void ATropeognathus_Character_BP_C::UpdateAllyAOE() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.UpdateAllyAOE"); ATropeognathus_Character_BP_C_UpdateAllyAOE_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.GetWindGustEpicenter // () // Parameters: // struct FVector ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) struct FVector ATropeognathus_Character_BP_C::GetWindGustEpicenter() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.GetWindGustEpicenter"); ATropeognathus_Character_BP_C_GetWindGustEpicenter_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.DoWing GustAOE // (NetRequest, Exec, Native, Event, NetResponse, MulticastDelegate, Public, Protected, HasDefaults, DLLImport, NetValidate) void ATropeognathus_Character_BP_C::DoWing_GustAOE() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.DoWing GustAOE"); ATropeognathus_Character_BP_C_DoWing_GustAOE_Params params; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.Is Diving Public // () // Parameters: // bool Ret (Parm, OutParm, ZeroConstructor, IsPlainOldData) // double TimeDiveStart (Parm, OutParm, ZeroConstructor, IsPlainOldData) void ATropeognathus_Character_BP_C::Is_Diving_Public(bool* Ret, double* TimeDiveStart) { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.Is Diving Public"); ATropeognathus_Character_BP_C_Is_Diving_Public_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; if (Ret != nullptr) *Ret = params.Ret; if (TimeDiveStart != nullptr) *TimeDiveStart = params.TimeDiveStart; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.BPNotifySetRider // () // Parameters: // class AShooterCharacter** RiderSetting (Parm, ZeroConstructor, IsPlainOldData) void ATropeognathus_Character_BP_C::BPNotifySetRider(class AShooterCharacter** RiderSetting) { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.BPNotifySetRider"); ATropeognathus_Character_BP_C_BPNotifySetRider_Params params; params.RiderSetting = RiderSetting; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.UpdateTPVOffset // () void ATropeognathus_Character_BP_C::UpdateTPVOffset() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.UpdateTPVOffset"); ATropeognathus_Character_BP_C_UpdateTPVOffset_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.UpdateCheckQuickTurn // () void ATropeognathus_Character_BP_C::UpdateCheckQuickTurn() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.UpdateCheckQuickTurn"); ATropeognathus_Character_BP_C_UpdateCheckQuickTurn_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.UpdateSpeed // () void ATropeognathus_Character_BP_C::UpdateSpeed() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.UpdateSpeed"); ATropeognathus_Character_BP_C_UpdateSpeed_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.UpdateDiving // () void ATropeognathus_Character_BP_C::UpdateDiving() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.UpdateDiving"); ATropeognathus_Character_BP_C_UpdateDiving_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.IsDiving // () // Parameters: // bool Ret (Parm, OutParm, ZeroConstructor, IsPlainOldData) // double TimeDiveStart (Parm, OutParm, ZeroConstructor, IsPlainOldData) // double TimeStoppedDiving (Parm, OutParm, ZeroConstructor, IsPlainOldData) void ATropeognathus_Character_BP_C::IsDiving(bool* Ret, double* TimeDiveStart, double* TimeStoppedDiving) { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.IsDiving"); ATropeognathus_Character_BP_C_IsDiving_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; if (Ret != nullptr) *Ret = params.Ret; if (TimeDiveStart != nullptr) *TimeDiveStart = params.TimeDiveStart; if (TimeStoppedDiving != nullptr) *TimeStoppedDiving = params.TimeStoppedDiving; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.GetAnimBP // () // Parameters: // class UTropeognathus_AnimBP_C* Ret (Parm, OutParm, ZeroConstructor, IsPlainOldData) void ATropeognathus_Character_BP_C::GetAnimBP(class UTropeognathus_AnimBP_C** Ret) { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.GetAnimBP"); ATropeognathus_Character_BP_C_GetAnimBP_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; if (Ret != nullptr) *Ret = params.Ret; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.GetCurrentPercentOfMaxFlySpeed // () // Parameters: // float ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) float ATropeognathus_Character_BP_C::GetCurrentPercentOfMaxFlySpeed() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.GetCurrentPercentOfMaxFlySpeed"); ATropeognathus_Character_BP_C_GetCurrentPercentOfMaxFlySpeed_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.GetCDO // () // Parameters: // class ATropeognathus_Character_BP_C* AsTropeognathus_Character_BP_C (Parm, OutParm, ZeroConstructor, IsPlainOldData) void ATropeognathus_Character_BP_C::GetCDO(class ATropeognathus_Character_BP_C** AsTropeognathus_Character_BP_C) { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.GetCDO"); ATropeognathus_Character_BP_C_GetCDO_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; if (AsTropeognathus_Character_BP_C != nullptr) *AsTropeognathus_Character_BP_C = params.AsTropeognathus_Character_BP_C; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.Is Quick Turning // () // Parameters: // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) bool ATropeognathus_Character_BP_C::Is_Quick_Turning() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.Is Quick Turning"); ATropeognathus_Character_BP_C_Is_Quick_Turning_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.EndQuickTurn // () void ATropeognathus_Character_BP_C::EndQuickTurn() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.EndQuickTurn"); ATropeognathus_Character_BP_C_EndQuickTurn_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.StartSuperFlightQuickTurn // () void ATropeognathus_Character_BP_C::StartSuperFlightQuickTurn() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.StartSuperFlightQuickTurn"); ATropeognathus_Character_BP_C_StartSuperFlightQuickTurn_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.OnRep_LastSuperFlightQuickTurn // () void ATropeognathus_Character_BP_C::OnRep_LastSuperFlightQuickTurn() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.OnRep_LastSuperFlightQuickTurn"); ATropeognathus_Character_BP_C_OnRep_LastSuperFlightQuickTurn_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.UpdateSuperFlightRoll // () void ATropeognathus_Character_BP_C::UpdateSuperFlightRoll() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.UpdateSuperFlightRoll"); ATropeognathus_Character_BP_C_UpdateSuperFlightRoll_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.BP_InterceptMoveRight // () // Parameters: // float* AxisValue (Parm, ZeroConstructor, IsPlainOldData) // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) bool ATropeognathus_Character_BP_C::BP_InterceptMoveRight(float* AxisValue) { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.BP_InterceptMoveRight"); ATropeognathus_Character_BP_C_BP_InterceptMoveRight_Params params; params.AxisValue = AxisValue; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.UpdateTrails // () void ATropeognathus_Character_BP_C::UpdateTrails() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.UpdateTrails"); ATropeognathus_Character_BP_C_UpdateTrails_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.ActivateTrails // () void ATropeognathus_Character_BP_C::ActivateTrails() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.ActivateTrails"); ATropeognathus_Character_BP_C_ActivateTrails_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.DeactivateTrails // () void ATropeognathus_Character_BP_C::DeactivateTrails() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.DeactivateTrails"); ATropeognathus_Character_BP_C_DeactivateTrails_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.RidingTick // () // Parameters: // float* DeltaSeconds (Parm, ZeroConstructor, IsPlainOldData) void ATropeognathus_Character_BP_C::RidingTick(float* DeltaSeconds) { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.RidingTick"); ATropeognathus_Character_BP_C_RidingTick_Params params; params.DeltaSeconds = DeltaSeconds; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.BP_OnStartLandingNotify // () void ATropeognathus_Character_BP_C::BP_OnStartLandingNotify() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.BP_OnStartLandingNotify"); ATropeognathus_Character_BP_C_BP_OnStartLandingNotify_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.BPOverrideFlyingVelocity // () // Parameters: // struct FVector InitialVelocity (Parm, OutParm, ZeroConstructor, ReferenceParm, IsPlainOldData) // struct FVector Gravity (Parm, OutParm, ZeroConstructor, ReferenceParm, IsPlainOldData) // float* DeltaTime (Parm, ZeroConstructor, IsPlainOldData) // struct FVector ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) struct FVector ATropeognathus_Character_BP_C::BPOverrideFlyingVelocity(float* DeltaTime, struct FVector* InitialVelocity, struct FVector* Gravity) { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.BPOverrideFlyingVelocity"); ATropeognathus_Character_BP_C_BPOverrideFlyingVelocity_Params params; params.DeltaTime = DeltaTime; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; if (InitialVelocity != nullptr) *InitialVelocity = params.InitialVelocity; if (Gravity != nullptr) *Gravity = params.Gravity; return params.ReturnValue; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.K2_OnMovementModeChanged // () // Parameters: // TEnumAsByte<EMovementMode>* PrevMovementMode (Parm, ZeroConstructor, IsPlainOldData) // TEnumAsByte<EMovementMode>* NewMovementMode (Parm, ZeroConstructor, IsPlainOldData) // unsigned char* PrevCustomMode (Parm, ZeroConstructor, IsPlainOldData) // unsigned char* NewCustomMode (Parm, ZeroConstructor, IsPlainOldData) void ATropeognathus_Character_BP_C::K2_OnMovementModeChanged(TEnumAsByte<EMovementMode>* PrevMovementMode, TEnumAsByte<EMovementMode>* NewMovementMode, unsigned char* PrevCustomMode, unsigned char* NewCustomMode) { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.K2_OnMovementModeChanged"); ATropeognathus_Character_BP_C_K2_OnMovementModeChanged_Params params; params.PrevMovementMode = PrevMovementMode; params.NewMovementMode = NewMovementMode; params.PrevCustomMode = PrevCustomMode; params.NewCustomMode = NewCustomMode; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.BP_InterceptMoveForward // () // Parameters: // float* AxisValue (Parm, ZeroConstructor, IsPlainOldData) // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) bool ATropeognathus_Character_BP_C::BP_InterceptMoveForward(float* AxisValue) { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.BP_InterceptMoveForward"); ATropeognathus_Character_BP_C_BP_InterceptMoveForward_Params params; params.AxisValue = AxisValue; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.BPOverrideCameraViewTarget // () // Parameters: // struct FName* CurrentCameraMode (Parm, ZeroConstructor, IsPlainOldData) // struct FVector* DesiredCameraLocation (Parm, ZeroConstructor, IsPlainOldData) // struct FRotator* DesiredCameraRotation (Parm, ZeroConstructor, IsPlainOldData) // float* DesiredFOV (Parm, ZeroConstructor, IsPlainOldData) // bool bOverrideCameraLocation (Parm, OutParm, ZeroConstructor, IsPlainOldData) // struct FVector CameraLocation (Parm, OutParm, ZeroConstructor, IsPlainOldData) // bool bOverrideCameraRotation (Parm, OutParm, ZeroConstructor, IsPlainOldData) // struct FRotator CameraRotation (Parm, OutParm, ZeroConstructor, IsPlainOldData) // bool bOverrideCameraFOV (Parm, OutParm, ZeroConstructor, IsPlainOldData) // float CameraFOV (Parm, OutParm, ZeroConstructor, IsPlainOldData) void ATropeognathus_Character_BP_C::BPOverrideCameraViewTarget(struct FName* CurrentCameraMode, struct FVector* DesiredCameraLocation, struct FRotator* DesiredCameraRotation, float* DesiredFOV, bool* bOverrideCameraLocation, struct FVector* CameraLocation, bool* bOverrideCameraRotation, struct FRotator* CameraRotation, bool* bOverrideCameraFOV, float* CameraFOV) { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.BPOverrideCameraViewTarget"); ATropeognathus_Character_BP_C_BPOverrideCameraViewTarget_Params params; params.CurrentCameraMode = CurrentCameraMode; params.DesiredCameraLocation = DesiredCameraLocation; params.DesiredCameraRotation = DesiredCameraRotation; params.DesiredFOV = DesiredFOV; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; if (bOverrideCameraLocation != nullptr) *bOverrideCameraLocation = params.bOverrideCameraLocation; if (CameraLocation != nullptr) *CameraLocation = params.CameraLocation; if (bOverrideCameraRotation != nullptr) *bOverrideCameraRotation = params.bOverrideCameraRotation; if (CameraRotation != nullptr) *CameraRotation = params.CameraRotation; if (bOverrideCameraFOV != nullptr) *bOverrideCameraFOV = params.bOverrideCameraFOV; if (CameraFOV != nullptr) *CameraFOV = params.CameraFOV; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.BP_OnSetRunning // () // Parameters: // bool* bNewIsRunning (Parm, ZeroConstructor, IsPlainOldData) void ATropeognathus_Character_BP_C::BP_OnSetRunning(bool* bNewIsRunning) { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.BP_OnSetRunning"); ATropeognathus_Character_BP_C_BP_OnSetRunning_Params params; params.bNewIsRunning = bNewIsRunning; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.BPNotifyClearRider // () // Parameters: // class AShooterCharacter** RiderClearing (Parm, ZeroConstructor, IsPlainOldData) void ATropeognathus_Character_BP_C::BPNotifyClearRider(class AShooterCharacter** RiderClearing) { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.BPNotifyClearRider"); ATropeognathus_Character_BP_C_BPNotifyClearRider_Params params; params.RiderClearing = RiderClearing; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.BPHandleOnStopTargeting // () // Parameters: // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) bool ATropeognathus_Character_BP_C::BPHandleOnStopTargeting() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.BPHandleOnStopTargeting"); ATropeognathus_Character_BP_C_BPHandleOnStopTargeting_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.BPHandleControllerInitiatedAttack // () // Parameters: // int* AttackIndex (Parm, ZeroConstructor, IsPlainOldData) // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) bool ATropeognathus_Character_BP_C::BPHandleControllerInitiatedAttack(int* AttackIndex) { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.BPHandleControllerInitiatedAttack"); ATropeognathus_Character_BP_C_BPHandleControllerInitiatedAttack_Params params; params.AttackIndex = AttackIndex; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.BPModifyDesiredRotation // () // Parameters: // float* DeltaTime (Parm, ZeroConstructor, IsPlainOldData) // struct FRotator InDesiredRotation (Parm, OutParm, ZeroConstructor, ReferenceParm, IsPlainOldData) // struct FRotator OutDesiredRotation (Parm, OutParm, ZeroConstructor, IsPlainOldData) // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) bool ATropeognathus_Character_BP_C::BPModifyDesiredRotation(float* DeltaTime, struct FRotator* InDesiredRotation, struct FRotator* OutDesiredRotation) { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.BPModifyDesiredRotation"); ATropeognathus_Character_BP_C_BPModifyDesiredRotation_Params params; params.DeltaTime = DeltaTime; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; if (InDesiredRotation != nullptr) *InDesiredRotation = params.InDesiredRotation; if (OutDesiredRotation != nullptr) *OutDesiredRotation = params.OutDesiredRotation; return params.ReturnValue; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.BPSetupTamed // () // Parameters: // bool* bWasJustTamed (Parm, ZeroConstructor, IsPlainOldData) void ATropeognathus_Character_BP_C::BPSetupTamed(bool* bWasJustTamed) { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.BPSetupTamed"); ATropeognathus_Character_BP_C_BPSetupTamed_Params params; params.bWasJustTamed = bWasJustTamed; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.BPOnStartJump // () // Parameters: // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) bool ATropeognathus_Character_BP_C::BPOnStartJump() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.BPOnStartJump"); ATropeognathus_Character_BP_C_BPOnStartJump_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.BPHandleUseButtonPress // () // Parameters: // class AShooterPlayerController** RiderController (Parm, ZeroConstructor, IsPlainOldData) // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) bool ATropeognathus_Character_BP_C::BPHandleUseButtonPress(class AShooterPlayerController** RiderController) { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.BPHandleUseButtonPress"); ATropeognathus_Character_BP_C_BPHandleUseButtonPress_Params params; params.RiderController = RiderController; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.DisableCameraInterpolation // () void ATropeognathus_Character_BP_C::DisableCameraInterpolation() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.DisableCameraInterpolation"); ATropeognathus_Character_BP_C_DisableCameraInterpolation_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.OnRep_LatchingSurfaceNormal // () void ATropeognathus_Character_BP_C::OnRep_LatchingSurfaceNormal() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.OnRep_LatchingSurfaceNormal"); ATropeognathus_Character_BP_C_OnRep_LatchingSurfaceNormal_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.UpdateLatchedDinoCamera // () void ATropeognathus_Character_BP_C::UpdateLatchedDinoCamera() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.UpdateLatchedDinoCamera"); ATropeognathus_Character_BP_C_UpdateLatchedDinoCamera_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.Controller Follow ActorRotation // () // Parameters: // float DeltaSeconds (Parm, ZeroConstructor, IsPlainOldData) void ATropeognathus_Character_BP_C::Controller_Follow_ActorRotation(float DeltaSeconds) { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.Controller Follow ActorRotation"); ATropeognathus_Character_BP_C_Controller_Follow_ActorRotation_Params params; params.DeltaSeconds = DeltaSeconds; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.ReferenceLatchingObjects // (NetReliable, NetRequest, Static, MulticastDelegate, Public, Protected, HasDefaults, DLLImport, NetValidate) void ATropeognathus_Character_BP_C::STATIC_ReferenceLatchingObjects() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.ReferenceLatchingObjects"); ATropeognathus_Character_BP_C_ReferenceLatchingObjects_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.LineTrace // (NetReliable, Event, NetMulticast, MulticastDelegate, Public, Protected, HasDefaults, DLLImport, NetValidate) // Parameters: // class UMeshComponent* Mesh (Parm, ZeroConstructor, IsPlainOldData) // struct FName SocketName (Parm, ZeroConstructor, IsPlainOldData) // class AActor* Actor (Parm, ZeroConstructor, IsPlainOldData) // struct FVector Offset (Parm, ZeroConstructor, IsPlainOldData) // bool BackwardLatching (Parm, ZeroConstructor, IsPlainOldData) // bool Hit_Somthing (Parm, OutParm, ZeroConstructor, IsPlainOldData) // struct FVector Location (Parm, OutParm, ZeroConstructor, IsPlainOldData) // struct FVector Normal (Parm, OutParm, ZeroConstructor, IsPlainOldData) // class AActor* Hit_Actor (Parm, OutParm, ZeroConstructor, IsPlainOldData) void ATropeognathus_Character_BP_C::LineTrace(class UMeshComponent* Mesh, const struct FName& SocketName, class AActor* Actor, const struct FVector& Offset, bool BackwardLatching, bool* Hit_Somthing, struct FVector* Location, struct FVector* Normal, class AActor** Hit_Actor) { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.LineTrace"); ATropeognathus_Character_BP_C_LineTrace_Params params; params.Mesh = Mesh; params.SocketName = SocketName; params.Actor = Actor; params.Offset = Offset; params.BackwardLatching = BackwardLatching; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; if (Hit_Somthing != nullptr) *Hit_Somthing = params.Hit_Somthing; if (Location != nullptr) *Location = params.Location; if (Normal != nullptr) *Normal = params.Normal; if (Hit_Actor != nullptr) *Hit_Actor = params.Hit_Actor; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.InterruptLatching // () void ATropeognathus_Character_BP_C::InterruptLatching() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.InterruptLatching"); ATropeognathus_Character_BP_C_InterruptLatching_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.ProcessLatching // () // Parameters: // float DeltaSeconds (Parm, ZeroConstructor, IsPlainOldData) void ATropeognathus_Character_BP_C::ProcessLatching(float DeltaSeconds) { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.ProcessLatching"); ATropeognathus_Character_BP_C_ProcessLatching_Params params; params.DeltaSeconds = DeltaSeconds; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.TryLatch // (Native, Event, NetResponse, NetMulticast, MulticastDelegate, Public, Protected, HasDefaults, DLLImport, NetValidate) // Parameters: // struct FVector Offset (Parm, ZeroConstructor, IsPlainOldData) // bool backwardsLatching (Parm, ZeroConstructor, IsPlainOldData) void ATropeognathus_Character_BP_C::TryLatch(const struct FVector& Offset, bool backwardsLatching) { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.TryLatch"); ATropeognathus_Character_BP_C_TryLatch_Params params; params.Offset = Offset; params.backwardsLatching = backwardsLatching; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.UserConstructionScript // () void ATropeognathus_Character_BP_C::UserConstructionScript() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.UserConstructionScript"); ATropeognathus_Character_BP_C_UserConstructionScript_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.InpActEvt_AltFire_K2Node_InputActionEvent_339 // () void ATropeognathus_Character_BP_C::InpActEvt_AltFire_K2Node_InputActionEvent_339() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.InpActEvt_AltFire_K2Node_InputActionEvent_339"); ATropeognathus_Character_BP_C_InpActEvt_AltFire_K2Node_InputActionEvent_339_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.InpActEvt_BrakeDino_K2Node_InputActionEvent_338 // () void ATropeognathus_Character_BP_C::InpActEvt_BrakeDino_K2Node_InputActionEvent_338() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.InpActEvt_BrakeDino_K2Node_InputActionEvent_338"); ATropeognathus_Character_BP_C_InpActEvt_BrakeDino_K2Node_InputActionEvent_338_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.InpActEvt_BrakeDino_K2Node_InputActionEvent_337 // () void ATropeognathus_Character_BP_C::InpActEvt_BrakeDino_K2Node_InputActionEvent_337() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.InpActEvt_BrakeDino_K2Node_InputActionEvent_337"); ATropeognathus_Character_BP_C_InpActEvt_BrakeDino_K2Node_InputActionEvent_337_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.InpActEvt_Crouch_K2Node_InputActionEvent_336 // () void ATropeognathus_Character_BP_C::InpActEvt_Crouch_K2Node_InputActionEvent_336() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.InpActEvt_Crouch_K2Node_InputActionEvent_336"); ATropeognathus_Character_BP_C_InpActEvt_Crouch_K2Node_InputActionEvent_336_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.InpActEvt_Prone_K2Node_InputActionEvent_335 // () void ATropeognathus_Character_BP_C::InpActEvt_Prone_K2Node_InputActionEvent_335() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.InpActEvt_Prone_K2Node_InputActionEvent_335"); ATropeognathus_Character_BP_C_InpActEvt_Prone_K2Node_InputActionEvent_335_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.InpActEvt_Gamepad_LeftStick_Down_K2Node_InputKeyEvent_72 // () void ATropeognathus_Character_BP_C::InpActEvt_Gamepad_LeftStick_Down_K2Node_InputKeyEvent_72() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.InpActEvt_Gamepad_LeftStick_Down_K2Node_InputKeyEvent_72"); ATropeognathus_Character_BP_C_InpActEvt_Gamepad_LeftStick_Down_K2Node_InputKeyEvent_72_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.InpActEvt_GamepadRightThumbstick_K2Node_InputActionEvent_334 // () void ATropeognathus_Character_BP_C::InpActEvt_GamepadRightThumbstick_K2Node_InputActionEvent_334() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.InpActEvt_GamepadRightThumbstick_K2Node_InputActionEvent_334"); ATropeognathus_Character_BP_C_InpActEvt_GamepadRightThumbstick_K2Node_InputActionEvent_334_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.InpActEvt_GamepadRightThumbstick_K2Node_InputActionEvent_333 // () void ATropeognathus_Character_BP_C::InpActEvt_GamepadRightThumbstick_K2Node_InputActionEvent_333() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.InpActEvt_GamepadRightThumbstick_K2Node_InputActionEvent_333"); ATropeognathus_Character_BP_C_InpActEvt_GamepadRightThumbstick_K2Node_InputActionEvent_333_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.InpActEvt_Gamepad_LeftTrigger_K2Node_InputKeyEvent_71 // () void ATropeognathus_Character_BP_C::InpActEvt_Gamepad_LeftTrigger_K2Node_InputKeyEvent_71() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.InpActEvt_Gamepad_LeftTrigger_K2Node_InputKeyEvent_71"); ATropeognathus_Character_BP_C_InpActEvt_Gamepad_LeftTrigger_K2Node_InputKeyEvent_71_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.InpActEvt_Gamepad_LeftTrigger_K2Node_InputKeyEvent_70 // () void ATropeognathus_Character_BP_C::InpActEvt_Gamepad_LeftTrigger_K2Node_InputKeyEvent_70() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.InpActEvt_Gamepad_LeftTrigger_K2Node_InputKeyEvent_70"); ATropeognathus_Character_BP_C_InpActEvt_Gamepad_LeftTrigger_K2Node_InputKeyEvent_70_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.Latch // () // Parameters: // bool backwardsLatching (Parm, ZeroConstructor, IsPlainOldData) void ATropeognathus_Character_BP_C::Latch(bool backwardsLatching) { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.Latch"); ATropeognathus_Character_BP_C_Latch_Params params; params.backwardsLatching = backwardsLatching; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.LatchStartAnimation // () void ATropeognathus_Character_BP_C::LatchStartAnimation() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.LatchStartAnimation"); ATropeognathus_Character_BP_C_LatchStartAnimation_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.UnLatch // () // Parameters: // bool LatchingInterrupted (Parm, ZeroConstructor, IsPlainOldData) void ATropeognathus_Character_BP_C::UnLatch(bool LatchingInterrupted) { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.UnLatch"); ATropeognathus_Character_BP_C_UnLatch_Params params; params.LatchingInterrupted = LatchingInterrupted; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.UnLatchStartAnimation // () void ATropeognathus_Character_BP_C::UnLatchStartAnimation() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.UnLatchStartAnimation"); ATropeognathus_Character_BP_C_UnLatchStartAnimation_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.BlueprintAnimNotifyCustomEvent // () // Parameters: // struct FName* CustomEventName (Parm, ZeroConstructor, IsPlainOldData) // class USkeletalMeshComponent** MeshComp (Parm, ZeroConstructor, IsPlainOldData) // class UAnimSequenceBase** Animation (Parm, ZeroConstructor, IsPlainOldData) // class UAnimNotify** AnimNotifyObject (ConstParm, Parm, ZeroConstructor, IsPlainOldData) void ATropeognathus_Character_BP_C::BlueprintAnimNotifyCustomEvent(struct FName* CustomEventName, class USkeletalMeshComponent** MeshComp, class UAnimSequenceBase** Animation, class UAnimNotify** AnimNotifyObject) { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.BlueprintAnimNotifyCustomEvent"); ATropeognathus_Character_BP_C_BlueprintAnimNotifyCustomEvent_Params params; params.CustomEventName = CustomEventName; params.MeshComp = MeshComp; params.Animation = Animation; params.AnimNotifyObject = AnimNotifyObject; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.MoveToUsingDirection // () // Parameters: // float DeltaTime (Parm, ZeroConstructor, IsPlainOldData) void ATropeognathus_Character_BP_C::MoveToUsingDirection(float DeltaTime) { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.MoveToUsingDirection"); ATropeognathus_Character_BP_C_MoveToUsingDirection_Params params; params.DeltaTime = DeltaTime; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.UnLatchMoveAndRotate // () void ATropeognathus_Character_BP_C::UnLatchMoveAndRotate() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.UnLatchMoveAndRotate"); ATropeognathus_Character_BP_C_UnLatchMoveAndRotate_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.LatchingStartEvent // () void ATropeognathus_Character_BP_C::LatchingStartEvent() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.LatchingStartEvent"); ATropeognathus_Character_BP_C_LatchingStartEvent_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.LatchingEndEvent // () void ATropeognathus_Character_BP_C::LatchingEndEvent() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.LatchingEndEvent"); ATropeognathus_Character_BP_C_LatchingEndEvent_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.StopMovement // () // Parameters: // float DeltaSeconds (Parm, ZeroConstructor, IsPlainOldData) void ATropeognathus_Character_BP_C::StopMovement(float DeltaSeconds) { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.StopMovement"); ATropeognathus_Character_BP_C_StopMovement_Params params; params.DeltaSeconds = DeltaSeconds; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.DisableFaceLatchingObjectRotation // () void ATropeognathus_Character_BP_C::DisableFaceLatchingObjectRotation() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.DisableFaceLatchingObjectRotation"); ATropeognathus_Character_BP_C_DisableFaceLatchingObjectRotation_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.SetPassengersSurfaceCamera // () // Parameters: // float Yaw (Parm, ZeroConstructor, IsPlainOldData) // float Pitch (Parm, ZeroConstructor, IsPlainOldData) // float Roll (Parm, ZeroConstructor, IsPlainOldData) void ATropeognathus_Character_BP_C::SetPassengersSurfaceCamera(float Yaw, float Pitch, float Roll) { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.SetPassengersSurfaceCamera"); ATropeognathus_Character_BP_C_SetPassengersSurfaceCamera_Params params; params.Yaw = Yaw; params.Pitch = Pitch; params.Roll = Roll; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.LocalFaceLatchingObject // () // Parameters: // float DeltaSeconds (Parm, ZeroConstructor, IsPlainOldData) void ATropeognathus_Character_BP_C::LocalFaceLatchingObject(float DeltaSeconds) { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.LocalFaceLatchingObject"); ATropeognathus_Character_BP_C_LocalFaceLatchingObject_Params params; params.DeltaSeconds = DeltaSeconds; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.StartedJump // () void ATropeognathus_Character_BP_C::StartedJump() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.StartedJump"); ATropeognathus_Character_BP_C_StartedJump_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.ServerToggleSuperFlight // () void ATropeognathus_Character_BP_C::ServerToggleSuperFlight() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.ServerToggleSuperFlight"); ATropeognathus_Character_BP_C_ServerToggleSuperFlight_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.ServerSuperFightRightInput // () // Parameters: // float AxisValue (Parm, ZeroConstructor, IsPlainOldData) void ATropeognathus_Character_BP_C::ServerSuperFightRightInput(float AxisValue) { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.ServerSuperFightRightInput"); ATropeognathus_Character_BP_C_ServerSuperFightRightInput_Params params; params.AxisValue = AxisValue; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.ServerRequestSuperFlightQuickTurn // () void ATropeognathus_Character_BP_C::ServerRequestSuperFlightQuickTurn() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.ServerRequestSuperFlightQuickTurn"); ATropeognathus_Character_BP_C_ServerRequestSuperFlightQuickTurn_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.UpdateQuickTurn // () void ATropeognathus_Character_BP_C::UpdateQuickTurn() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.UpdateQuickTurn"); ATropeognathus_Character_BP_C_UpdateQuickTurn_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.ServerRequestWindGust // () void ATropeognathus_Character_BP_C::ServerRequestWindGust() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.ServerRequestWindGust"); ATropeognathus_Character_BP_C_ServerRequestWindGust_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.AnimNotify_WindGust // () void ATropeognathus_Character_BP_C::AnimNotify_WindGust() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.AnimNotify_WindGust"); ATropeognathus_Character_BP_C_AnimNotify_WindGust_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.ClientWindGust // () // Parameters: // struct FVector Epicenter (Parm, ZeroConstructor, IsPlainOldData) void ATropeognathus_Character_BP_C::ClientWindGust(const struct FVector& Epicenter) { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.ClientWindGust"); ATropeognathus_Character_BP_C_ClientWindGust_Params params; params.Epicenter = Epicenter; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.AnimNotify_WindGustVFX // () void ATropeognathus_Character_BP_C::AnimNotify_WindGustVFX() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.AnimNotify_WindGustVFX"); ATropeognathus_Character_BP_C_AnimNotify_WindGustVFX_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.ServerRequestFireFlakCannon // () // Parameters: // struct FVector Dir (Parm, ZeroConstructor, IsPlainOldData) // struct FVector Loc (Parm, ZeroConstructor, IsPlainOldData) void ATropeognathus_Character_BP_C::ServerRequestFireFlakCannon(const struct FVector& Dir, const struct FVector& Loc) { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.ServerRequestFireFlakCannon"); ATropeognathus_Character_BP_C_ServerRequestFireFlakCannon_Params params; params.Dir = Dir; params.Loc = Loc; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.InpAxisEvt_MoveUp_K2Node_InputAxisEvent_181 // () // Parameters: // float AxisValue (Parm, ZeroConstructor, IsPlainOldData) void ATropeognathus_Character_BP_C::InpAxisEvt_MoveUp_K2Node_InputAxisEvent_181(float AxisValue) { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.InpAxisEvt_MoveUp_K2Node_InputAxisEvent_181"); ATropeognathus_Character_BP_C_InpAxisEvt_MoveUp_K2Node_InputAxisEvent_181_Params params; params.AxisValue = AxisValue; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.ServerUpdateLastForwardInputTime // () void ATropeognathus_Character_BP_C::ServerUpdateLastForwardInputTime() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.ServerUpdateLastForwardInputTime"); ATropeognathus_Character_BP_C_ServerUpdateLastForwardInputTime_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.DelayedSuperFlightEnd // () void ATropeognathus_Character_BP_C::DelayedSuperFlightEnd() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.DelayedSuperFlightEnd"); ATropeognathus_Character_BP_C_DelayedSuperFlightEnd_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.MultiSuperFlightEnd // () void ATropeognathus_Character_BP_C::MultiSuperFlightEnd() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.MultiSuperFlightEnd"); ATropeognathus_Character_BP_C_MultiSuperFlightEnd_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.ClientTagDraftee // () // Parameters: // class APrimalCharacter* Target (Parm, ZeroConstructor, IsPlainOldData) void ATropeognathus_Character_BP_C::ClientTagDraftee(class APrimalCharacter* Target) { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.ClientTagDraftee"); ATropeognathus_Character_BP_C_ClientTagDraftee_Params params; params.Target = Target; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.WindGust180End // () void ATropeognathus_Character_BP_C::WindGust180End() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.WindGust180End"); ATropeognathus_Character_BP_C_WindGust180End_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.WindGust180Tick // () void ATropeognathus_Character_BP_C::WindGust180Tick() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.WindGust180Tick"); ATropeognathus_Character_BP_C_WindGust180Tick_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.AnimNotify_WindGustCheckFor180 // () void ATropeognathus_Character_BP_C::AnimNotify_WindGustCheckFor180() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.AnimNotify_WindGustCheckFor180"); ATropeognathus_Character_BP_C_AnimNotify_WindGustCheckFor180_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.AnimNotify_WindGustBoost // () void ATropeognathus_Character_BP_C::AnimNotify_WindGustBoost() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.AnimNotify_WindGustBoost"); ATropeognathus_Character_BP_C_AnimNotify_WindGustBoost_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.ServerRequest180 // () void ATropeognathus_Character_BP_C::ServerRequest180() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.ServerRequest180"); ATropeognathus_Character_BP_C_ServerRequest180_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.GamepadRightStickPressed // () void ATropeognathus_Character_BP_C::GamepadRightStickPressed() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.GamepadRightStickPressed"); ATropeognathus_Character_BP_C_GamepadRightStickPressed_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.ServerSetLastTimePressedJump // () void ATropeognathus_Character_BP_C::ServerSetLastTimePressedJump() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.ServerSetLastTimePressedJump"); ATropeognathus_Character_BP_C_ServerSetLastTimePressedJump_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.ServerSetLastTimeReleasedJump // () void ATropeognathus_Character_BP_C::ServerSetLastTimeReleasedJump() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.ServerSetLastTimeReleasedJump"); ATropeognathus_Character_BP_C_ServerSetLastTimeReleasedJump_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.QueueLanding // () void ATropeognathus_Character_BP_C::QueueLanding() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.QueueLanding"); ATropeognathus_Character_BP_C_QueueLanding_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.ServerRequestLanding // () void ATropeognathus_Character_BP_C::ServerRequestLanding() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.ServerRequestLanding"); ATropeognathus_Character_BP_C_ServerRequestLanding_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.OnBola // () void ATropeognathus_Character_BP_C::OnBola() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.OnBola"); ATropeognathus_Character_BP_C_OnBola_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.ServerUpdateRunningStartTime // () void ATropeognathus_Character_BP_C::ServerUpdateRunningStartTime() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.ServerUpdateRunningStartTime"); ATropeognathus_Character_BP_C_ServerUpdateRunningStartTime_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.ServerUpdateRunningStopTime // () void ATropeognathus_Character_BP_C::ServerUpdateRunningStopTime() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.ServerUpdateRunningStopTime"); ATropeognathus_Character_BP_C_ServerUpdateRunningStopTime_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.MultiOnRunStarted // () void ATropeognathus_Character_BP_C::MultiOnRunStarted() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.MultiOnRunStarted"); ATropeognathus_Character_BP_C_MultiOnRunStarted_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.MultiOnRunStopped // () void ATropeognathus_Character_BP_C::MultiOnRunStopped() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.MultiOnRunStopped"); ATropeognathus_Character_BP_C_MultiOnRunStopped_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.MultiOnSuperFlightStart // () void ATropeognathus_Character_BP_C::MultiOnSuperFlightStart() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.MultiOnSuperFlightStart"); ATropeognathus_Character_BP_C_MultiOnSuperFlightStart_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.QueueGrabAttack // () void ATropeognathus_Character_BP_C::QueueGrabAttack() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.QueueGrabAttack"); ATropeognathus_Character_BP_C_QueueGrabAttack_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.MultiThrusterVFXBoost // () void ATropeognathus_Character_BP_C::MultiThrusterVFXBoost() { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.MultiThrusterVFXBoost"); ATropeognathus_Character_BP_C_MultiThrusterVFXBoost_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.ExecuteUbergraph_Tropeognathus_Character_BP // () // Parameters: // int EntryPoint (Parm, ZeroConstructor, IsPlainOldData) void ATropeognathus_Character_BP_C::ExecuteUbergraph_Tropeognathus_Character_BP(int EntryPoint) { static auto fn = UObject::FindObject<UFunction>("Function Tropeognathus_Character_BP.Tropeognathus_Character_BP_C.ExecuteUbergraph_Tropeognathus_Character_BP"); ATropeognathus_Character_BP_C_ExecuteUbergraph_Tropeognathus_Character_BP_Params params; params.EntryPoint = EntryPoint; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } } #ifdef _MSC_VER #pragma pack(pop) #endif
32.875553
364
0.77066
[ "mesh" ]
3a55fd871ebbdf2de7b8364d579006db13d997a4
4,129
cpp
C++
DinoLasers/SPOctree.cpp
QRayarch/DinoLasers
500f4144fad2a813cd140d6067b41a41f4573e8c
[ "MIT" ]
null
null
null
DinoLasers/SPOctree.cpp
QRayarch/DinoLasers
500f4144fad2a813cd140d6067b41a41f4573e8c
[ "MIT" ]
null
null
null
DinoLasers/SPOctree.cpp
QRayarch/DinoLasers
500f4144fad2a813cd140d6067b41a41f4573e8c
[ "MIT" ]
null
null
null
#include "SPOctree.h" SPOctree::SPOctree() { //size = 0.0f; //center = vector3(0.0f); root = new Octant(center, size); maxBOPerOctant = 4; } SPOctree::~SPOctree() { } std::vector<std::vector<ContactManifold>> SPOctree::CalculateColisions(std::vector<BoundingObject*> bos) { std::vector<std::vector<ContactManifold>> collInd; std::vector<uint> indexs = std::vector<uint>(bos.size()); for (int i = 0; i < bos.size(); i++) { indexs.push_back(i); collInd.push_back(std::vector<ContactManifold>()); } SetSize(bos); CalculateOctant(collInd,root,bos, indexs); //root->Display(REWHITE); return collInd; } void SPOctree::SetSize(std::vector<BoundingObject*> bos) { if (bos.size() == 0) return; min = bos[0]->GetMinGlobal(); max = bos[0]->GetMaxGlobal(); for (int i = 1; i < bos.size(); i++) { if (bos[i]->GetMinGlobal().x < min.x) { min.x = bos[i]->GetMinGlobal().x; } if (bos[i]->GetMinGlobal().y < min.y) { min.y = bos[i]->GetMinGlobal().y; } if (bos[i]->GetMinGlobal().z < min.z) { min.z = bos[i]->GetMinGlobal().z; } if (bos[i]->GetMaxGlobal().x > max.x) { max.x = bos[i]->GetMaxGlobal().x; } if (bos[i]->GetMaxGlobal().y > max.y) { max.y = bos[i]->GetMaxGlobal().y; } if (bos[i]->GetMaxGlobal().z > max.z) { max.z = bos[i]->GetMaxGlobal().z; } } //float dX = max.x - min.x; //float dY = max.y - min.y; //float dZ = max.z - min.z; // //if (dX > dY) size = dX; //if (dX > dZ) size = dX; //if (dY > dX) size = dY; //if (dY > dZ) size = dY; //if (dZ > dX) size = dZ; //if (dZ > dY) size = dZ; if (min.x < min.y) min.y = min.x; if (min.y < min.x) min.x = min.y; if (min.x < min.z) min.z = min.x; if (min.z < min.x) min.x = min.z; if (min.y < min.z) min.z = min.y; if (min.z < min.y) min.y = min.z; if (max.x > max.y) max.y = max.x; if (max.y > max.x) max.x = max.y; if (max.x > max.z) max.z = max.x; if (max.z > max.x) max.x = max.z; if (max.y > max.z) max.z = max.y; if (max.z > max.y) max.y = max.z; size = max.x - min.x;// ::distance(vector3(min.x, 0.0f, 0.0f), vector3(max.x, 0.0f, 0.0f)); //std::cout << "\n" << size << "\n"; center = min + size / 2.0f; root->SetSize(size/2); root->SetCenter(center); } void SPOctree::CalculateOctant(std::vector<std::vector<ContactManifold>>& collInd, Octant* octant, std::vector<BoundingObject*>& bos, std::vector<uint>& indexs) { if (octant == nullptr) return; if (octant->CanSubDivide() && indexs.size() > maxBOPerOctant) { octant->Subdivide(); for (int o = 0; o < 8; o++){ //std::vector<BoundingObject*> newBos = std::vector<BoundingObject*>(); std::vector<uint> newIndexs = std::vector<uint>(); vector3 octMax = vector3(octant->GetChild(o)->GetSize()) + octant->GetChild(o)->GetCenter(); vector3 octMin = vector3(-(octant->GetChild(o)->GetSize())) + octant->GetChild(o)->GetCenter(); //octant->GetChild(o)->Display(REMAGENTA); for (int b = 0; b < indexs.size(); b++) { if (bos[indexs[b]]->GetMinGlobal().x < octMax.x && bos[indexs[b]]->GetMaxGlobal().x > octMin.x && bos[indexs[b]]->GetMinGlobal().y < octMax.y && bos[indexs[b]]->GetMaxGlobal().y > octMin.y && bos[indexs[b]]->GetMinGlobal().z < octMax.z && bos[indexs[b]]->GetMaxGlobal().z > octMin.z) { newIndexs.push_back(indexs[b]); } } CalculateOctant(collInd, octant->GetChild(o), bos, newIndexs); } } else if(octant->IsLeaf()) { //Look for collisions for (int i = 0; i < indexs.size(); i++) { uint a = indexs[i]; for (int j = i + 1; j < indexs.size(); j++) { uint b = indexs[j]; if (b != a) { bool isNoDup = true; for (int c = 0; c < collInd[a].size(); c++) { if (collInd[a][c].index == b) { isNoDup = false; c = collInd[a].size(); } } if (isNoDup) { ContactManifold contact; if (bos[a]->IsColliding(bos[b], contact))//HOT { contact.index = b; collInd[a].push_back(contact); SpatialPartition::SendCollisionInfoBoth(bos[a], bos[b]); } else { SendCollisionInfoBothExit(bos[a], bos[b]); } } } } } } }
26.63871
160
0.571083
[ "vector" ]
3a5c86a9f1a11f5a51082d0f25e2ef43771a674d
24,299
cpp
C++
Code/Framework/AzCore/Tests/Math/Matrix3x3Tests.cpp
aaarsene/o3de
37e3b0226958974defd14dd6d808e8557dcd7345
[ "Apache-2.0", "MIT" ]
1
2021-09-13T00:01:12.000Z
2021-09-13T00:01:12.000Z
Code/Framework/AzCore/Tests/Math/Matrix3x3Tests.cpp
aaarsene/o3de
37e3b0226958974defd14dd6d808e8557dcd7345
[ "Apache-2.0", "MIT" ]
null
null
null
Code/Framework/AzCore/Tests/Math/Matrix3x3Tests.cpp
aaarsene/o3de
37e3b0226958974defd14dd6d808e8557dcd7345
[ "Apache-2.0", "MIT" ]
1
2021-07-20T11:07:25.000Z
2021-07-20T11:07:25.000Z
/* * Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #include <AzCore/Math/Matrix3x3.h> #include <AzCore/Math/Transform.h> #include <AzCore/Math/Quaternion.h> #include <AzCore/UnitTest/TestTypes.h> #include <AZTestShared/Math/MathTestHelpers.h> using namespace AZ; namespace UnitTest { static constexpr int32_t testIndices3x3[] = { 0, 1, 2, 3 }; float testFloats[] = { 1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f, 8.0f, 9.0f }; float testFloatsMtx[9]; TEST(MATH_Matrix3x3, TestCreateIdentity) { Matrix3x3 m1 = Matrix3x3::CreateIdentity(); AZ_TEST_ASSERT(m1.GetRow(0) == Vector3(1.0f, 0.0f, 0.0f)); AZ_TEST_ASSERT(m1.GetRow(1) == Vector3(0.0f, 1.0f, 0.0f)); AZ_TEST_ASSERT(m1.GetRow(2) == Vector3(0.0f, 0.0f, 1.0f)); } TEST(MATH_Matrix3x3, TestCreateZero) { Matrix3x3 m1 = Matrix3x3::CreateZero(); AZ_TEST_ASSERT(m1.GetRow(0) == Vector3(0.0f)); AZ_TEST_ASSERT(m1.GetRow(1) == Vector3(0.0f)); AZ_TEST_ASSERT(m1.GetRow(2) == Vector3(0.0f)); } TEST(MATH_Matrix3x3, TestCreateFromValue) { Matrix3x3 m1 = Matrix3x3::CreateFromValue(2.0f); AZ_TEST_ASSERT(m1.GetRow(0) == Vector3(2.0f)); AZ_TEST_ASSERT(m1.GetRow(1) == Vector3(2.0f)); AZ_TEST_ASSERT(m1.GetRow(2) == Vector3(2.0f)); } TEST(MATH_Matrix3x3, TestCreateFromRowMajorFloat9) { Matrix3x3 m1 = Matrix3x3::CreateFromRowMajorFloat9(testFloats); AZ_TEST_ASSERT(m1.GetRow(0) == Vector3(1.0f, 2.0f, 3.0f)); AZ_TEST_ASSERT(m1.GetRow(1) == Vector3(4.0f, 5.0f, 6.0f)); AZ_TEST_ASSERT(m1.GetRow(2) == Vector3(7.0f, 8.0f, 9.0f)); m1.StoreToRowMajorFloat9(testFloatsMtx); AZ_TEST_ASSERT(memcmp(testFloatsMtx, testFloats, sizeof(testFloatsMtx)) == 0); } TEST(MATH_Matrix3x3, TestCreateFromColumnMajorFloat9) { Matrix3x3 m1 = Matrix3x3::CreateFromColumnMajorFloat9(testFloats); AZ_TEST_ASSERT(m1.GetRow(0) == Vector3(1.0f, 4.0f, 7.0f)); AZ_TEST_ASSERT(m1.GetRow(1) == Vector3(2.0f, 5.0f, 8.0f)); AZ_TEST_ASSERT(m1.GetRow(2) == Vector3(3.0f, 6.0f, 9.0f)); m1.StoreToColumnMajorFloat9(testFloatsMtx); AZ_TEST_ASSERT(memcmp(testFloatsMtx, testFloats, sizeof(testFloatsMtx)) == 0); } TEST(MATH_Matrix3x3, TestCreateRotationX) { Matrix3x3 m1 = Matrix3x3::CreateRotationX(DegToRad(30.0f)); AZ_TEST_ASSERT(m1.GetRow(0).IsClose(Vector3(1.0f, 0.0f, 0.0f))); AZ_TEST_ASSERT(m1.GetRow(1).IsClose(Vector3(0.0f, 0.866f, -0.5f))); AZ_TEST_ASSERT(m1.GetRow(2).IsClose(Vector3(0.0f, 0.5f, 0.866f))); } TEST(MATH_Matrix3x3, TestCreateRotationY) { Matrix3x3 m1 = Matrix3x3::CreateRotationY(DegToRad(30.0f)); AZ_TEST_ASSERT(m1.GetRow(0).IsClose(Vector3(0.866f, 0.0f, 0.5f))); AZ_TEST_ASSERT(m1.GetRow(1).IsClose(Vector3(0.0f, 1.0f, 0.0f))); AZ_TEST_ASSERT(m1.GetRow(2).IsClose(Vector3(-0.5f, 0.0f, 0.866f))); } TEST(MATH_Matrix3x3, TestCreateRotationZ) { Matrix3x3 m1 = Matrix3x3::CreateRotationZ(DegToRad(30.0f)); AZ_TEST_ASSERT(m1.GetRow(0).IsClose(Vector3(0.866f, -0.5f, 0.0f))); AZ_TEST_ASSERT(m1.GetRow(1).IsClose(Vector3(0.5f, 0.866f, 0.0f))); AZ_TEST_ASSERT(m1.GetRow(2).IsClose(Vector3(0.0f, 0.0f, 1.0f))); } TEST(MATH_Matrix3x3, TestCreateFromTransform) { Matrix3x3 m1 = Matrix3x3::CreateFromTransform(Transform::CreateRotationX(DegToRad(30.0f))); AZ_TEST_ASSERT(m1.GetRow(0).IsClose(Vector3(1.0f, 0.0f, 0.0f))); AZ_TEST_ASSERT(m1.GetRow(1).IsClose(Vector3(0.0f, 0.866f, -0.5f))); AZ_TEST_ASSERT(m1.GetRow(2).IsClose(Vector3(0.0f, 0.5f, 0.866f))); } TEST(MATH_Matrix3x3, TestCreateFromMatrix4x4) { Matrix3x3 m1 = Matrix3x3::CreateFromMatrix4x4(Matrix4x4::CreateRotationX(DegToRad(30.0f))); AZ_TEST_ASSERT(m1.GetRow(0).IsClose(Vector3(1.0f, 0.0f, 0.0f))); AZ_TEST_ASSERT(m1.GetRow(1).IsClose(Vector3(0.0f, 0.866f, -0.5f))); AZ_TEST_ASSERT(m1.GetRow(2).IsClose(Vector3(0.0f, 0.5f, 0.866f))); } TEST(MATH_Matrix3x3, TestCreateFromQuaternion) { Matrix3x3 m1 = Matrix3x3::CreateFromQuaternion(AZ::Quaternion::CreateRotationX(DegToRad(30.0f))); AZ_TEST_ASSERT(m1.GetRow(0).IsClose(Vector3(1.0f, 0.0f, 0.0f))); AZ_TEST_ASSERT(m1.GetRow(1).IsClose(Vector3(0.0f, 0.866f, -0.5f))); AZ_TEST_ASSERT(m1.GetRow(2).IsClose(Vector3(0.0f, 0.5f, 0.866f))); } TEST(MATH_Matrix3x3, TestCreateScale) { Matrix3x3 m1 = Matrix3x3::CreateScale(Vector3(1.0f, 2.0f, 3.0f)); AZ_TEST_ASSERT(m1.GetRow(0) == Vector3(1.0f, 0.0f, 0.0f)); AZ_TEST_ASSERT(m1.GetRow(1) == Vector3(0.0f, 2.0f, 0.0f)); AZ_TEST_ASSERT(m1.GetRow(2) == Vector3(0.0f, 0.0f, 3.0f)); } TEST(MATH_Matrix3x3, TestCreateDiagonal) { Matrix3x3 m1 = Matrix3x3::CreateDiagonal(Vector3(2.0f, 3.0f, 4.0f)); AZ_TEST_ASSERT(m1.GetRow(0) == Vector3(2.0f, 0.0f, 0.0f)); AZ_TEST_ASSERT(m1.GetRow(1) == Vector3(0.0f, 3.0f, 0.0f)); AZ_TEST_ASSERT(m1.GetRow(2) == Vector3(0.0f, 0.0f, 4.0f)); } TEST(MATH_Matrix3x3, TestCreateCrossProduct) { Matrix3x3 m1 = Matrix3x3::CreateCrossProduct(Vector3(1.0f, 2.0f, 3.0f)); AZ_TEST_ASSERT(m1.GetRow(0) == Vector3(0.0f, -3.0f, 2.0f)); AZ_TEST_ASSERT(m1.GetRow(1) == Vector3(3.0f, 0.0f, -1.0f)); AZ_TEST_ASSERT(m1.GetRow(2) == Vector3(-2.0f, 1.0f, 0.0f)); } TEST(MATH_Matrix3x3, TestElementAccess) { Matrix3x3 m1 = Matrix3x3::CreateRotationX(DegToRad(30.0f)); AZ_TEST_ASSERT_FLOAT_CLOSE(m1.GetElement(1, 2), -0.5f); AZ_TEST_ASSERT_FLOAT_CLOSE(m1.GetElement(2, 2), 0.866f); m1.SetElement(2, 1, 5.0f); AZ_TEST_ASSERT(m1.GetElement(2, 1) == 5.0f); AZ_TEST_ASSERT_FLOAT_CLOSE(m1(1, 2), -0.5f); AZ_TEST_ASSERT_FLOAT_CLOSE(m1(2, 2), 0.866f); m1.SetElement(2, 1, 15.0f); AZ_TEST_ASSERT(m1(2, 1) == 15.0f); } TEST(MATH_Matrix3x3, TestRowAccess) { Matrix3x3 m1 = Matrix3x3::CreateRotationX(DegToRad(30.0f)); AZ_TEST_ASSERT(m1.GetRow(2).IsClose(Vector3(0.0f, 0.5f, 0.866f))); m1.SetRow(0, 1.0f, 2.0f, 3.0f); AZ_TEST_ASSERT(m1.GetRow(0).IsClose(Vector3(1.0f, 2.0f, 3.0f))); m1.SetRow(1, Vector3(4.0f, 5.0f, 6.0f)); AZ_TEST_ASSERT(m1.GetRow(1).IsClose(Vector3(4.0f, 5.0f, 6.0f))); m1.SetRow(2, Vector3(7.0f, 8.0f, 9.0f)); AZ_TEST_ASSERT(m1.GetRow(2).IsClose(Vector3(7.0f, 8.0f, 9.0f))); // test GetRow with non-constant, we have different implementations for constants and variables AZ_TEST_ASSERT(m1.GetRow(testIndices3x3[0]).IsClose(Vector3(1.0f, 2.0f, 3.0f))); AZ_TEST_ASSERT(m1.GetRow(testIndices3x3[1]).IsClose(Vector3(4.0f, 5.0f, 6.0f))); AZ_TEST_ASSERT(m1.GetRow(testIndices3x3[2]).IsClose(Vector3(7.0f, 8.0f, 9.0f))); Vector3 row0, row1, row2; m1.GetRows(&row0, &row1, &row2); AZ_TEST_ASSERT(row0.IsClose(Vector3(1.0f, 2.0f, 3.0f))); AZ_TEST_ASSERT(row1.IsClose(Vector3(4.0f, 5.0f, 6.0f))); AZ_TEST_ASSERT(row2.IsClose(Vector3(7.0f, 8.0f, 9.0f))); m1.SetRows(Vector3(10.0f, 11.0f, 12.0f), Vector3(13.0f, 14.0f, 15.0f), Vector3(16.0f, 17.0f, 18.0f)); AZ_TEST_ASSERT(m1.GetRow(0).IsClose(Vector3(10.0f, 11.0f, 12.0f))); AZ_TEST_ASSERT(m1.GetRow(1).IsClose(Vector3(13.0f, 14.0f, 15.0f))); AZ_TEST_ASSERT(m1.GetRow(2).IsClose(Vector3(16.0f, 17.0f, 18.0f))); } TEST(MATH_Matrix3x3, TestColumnAccess) { Matrix3x3 m1 = Matrix3x3::CreateRotationX(DegToRad(30.0f)); AZ_TEST_ASSERT(m1.GetColumn(1).IsClose(Vector3(0.0f, 0.866f, 0.5f))); m1.SetColumn(2, 1.0f, 2.0f, 3.0f); AZ_TEST_ASSERT(m1.GetColumn(2).IsClose(Vector3(1.0f, 2.0f, 3.0f))); AZ_TEST_ASSERT(m1.GetRow(0).IsClose(Vector3(1.0f, 0.0f, 1.0f))); // checking all components in case others get messed up with the shuffling AZ_TEST_ASSERT(m1.GetRow(1).IsClose(Vector3(0.0f, 0.866f, 2.0f))); AZ_TEST_ASSERT(m1.GetRow(2).IsClose(Vector3(0.0f, 0.5f, 3.0f))); m1.SetColumn(0, Vector3(2.0f, 3.0f, 4.0f)); AZ_TEST_ASSERT(m1.GetColumn(0).IsClose(Vector3(2.0f, 3.0f, 4.0f))); AZ_TEST_ASSERT(m1.GetRow(0).IsClose(Vector3(2.0f, 0.0f, 1.0f))); AZ_TEST_ASSERT(m1.GetRow(1).IsClose(Vector3(3.0f, 0.866f, 2.0f))); AZ_TEST_ASSERT(m1.GetRow(2).IsClose(Vector3(4.0f, 0.5f, 3.0f))); // test GetColumn with non-constant, we have different implementations for constants and variables AZ_TEST_ASSERT(m1.GetColumn(testIndices3x3[0]).IsClose(Vector3(2.0f, 3.0f, 4.0f))); AZ_TEST_ASSERT(m1.GetColumn(testIndices3x3[1]).IsClose(Vector3(0.0f, 0.866f, 0.5f))); AZ_TEST_ASSERT(m1.GetColumn(testIndices3x3[2]).IsClose(Vector3(1.0f, 2.0f, 3.0f))); Vector3 col0, col1, col2; m1.GetColumns(&col0, &col1, &col2); AZ_TEST_ASSERT(col0.IsClose(Vector3(2.0f, 3.0f, 4.0f))); AZ_TEST_ASSERT(col1.IsClose(Vector3(0.0f, 0.866f, 0.5f))); AZ_TEST_ASSERT(col2.IsClose(Vector3(1.0f, 2.0f, 3.0f))); m1.SetColumns(Vector3(10.0f, 11.0f, 12.0f), Vector3(13.0f, 14.0f, 15.0f), Vector3(16.0f, 17.0f, 18.0f)); AZ_TEST_ASSERT(m1.GetColumn(0).IsClose(Vector3(10.0f, 11.0f, 12.0f))); AZ_TEST_ASSERT(m1.GetColumn(1).IsClose(Vector3(13.0f, 14.0f, 15.0f))); AZ_TEST_ASSERT(m1.GetColumn(2).IsClose(Vector3(16.0f, 17.0f, 18.0f))); } TEST(MATH_Matrix3x3, TestBasisAccess) { Matrix3x3 m1 = Matrix3x3::CreateRotationX(DegToRad(30.0f)); AZ_TEST_ASSERT(m1.GetBasisX().IsClose(Vector3(1.0f, 0.0f, 0.0f))); AZ_TEST_ASSERT(m1.GetBasisY().IsClose(Vector3(0.0f, 0.866f, 0.5f))); AZ_TEST_ASSERT(m1.GetBasisZ().IsClose(Vector3(0.0f, -0.5f, 0.866f))); m1.SetBasisX(1.0f, 2.0f, 3.0f); AZ_TEST_ASSERT(m1.GetBasisX().IsClose(Vector3(1.0f, 2.0f, 3.0f))); m1.SetBasisY(4.0f, 5.0f, 6.0f); AZ_TEST_ASSERT(m1.GetBasisY().IsClose(Vector3(4.0f, 5.0f, 6.0f))); m1.SetBasisZ(7.0f, 8.0f, 9.0f); AZ_TEST_ASSERT(m1.GetBasisZ().IsClose(Vector3(7.0f, 8.0f, 9.0f))); m1.SetBasisX(Vector3(10.0f, 11.0f, 12.0f)); AZ_TEST_ASSERT(m1.GetBasisX().IsClose(Vector3(10.0f, 11.0f, 12.0f))); m1.SetBasisY(Vector3(13.0f, 14.0f, 15.0f)); AZ_TEST_ASSERT(m1.GetBasisY().IsClose(Vector3(13.0f, 14.0f, 15.0f))); m1.SetBasisZ(Vector3(16.0f, 17.0f, 18.0f)); AZ_TEST_ASSERT(m1.GetBasisZ().IsClose(Vector3(16.0f, 17.0f, 18.0f))); Vector3 basis0, basis1, basis2; m1.GetBasis(&basis0, &basis1, &basis2); AZ_TEST_ASSERT(basis0.IsClose(Vector3(10.0f, 11.0f, 12.0f))); AZ_TEST_ASSERT(basis1.IsClose(Vector3(13.0f, 14.0f, 15.0f))); AZ_TEST_ASSERT(basis2.IsClose(Vector3(16.0f, 17.0f, 18.0f))); m1.SetBasis(Vector3(1.0f, 2.0f, 3.0f), Vector3(4.0f, 5.0f, 6.0f), Vector3(7.0f, 8.0f, 9.0f)); AZ_TEST_ASSERT(m1.GetBasisX().IsClose(Vector3(1.0f, 2.0f, 3.0f))); AZ_TEST_ASSERT(m1.GetBasisY().IsClose(Vector3(4.0f, 5.0f, 6.0f))); AZ_TEST_ASSERT(m1.GetBasisZ().IsClose(Vector3(7.0f, 8.0f, 9.0f))); } TEST(MATH_Matrix3x3, TestMatrixMultiplication) { Matrix3x3 m1; m1.SetRow(0, 1.0f, 2.0f, 3.0f); m1.SetRow(1, 4.0f, 5.0f, 6.0f); m1.SetRow(2, 7.0f, 8.0f, 9.0f); Matrix3x3 m2; m2.SetRow(0, 7.0f, 8.0f, 9.0f); m2.SetRow(1, 10.0f, 11.0f, 12.0f); m2.SetRow(2, 13.0f, 14.0f, 15.0f); Matrix3x3 m3 = m1 * m2; EXPECT_THAT(m3.GetRow(0), IsClose(Vector3(66.0f, 72.0f, 78.0f))); EXPECT_THAT(m3.GetRow(1), IsClose(Vector3(156.0f, 171.0f, 186.0f))); EXPECT_THAT(m3.GetRow(2), IsClose(Vector3(246.0f, 270.0f, 294.0f))); Matrix3x3 m4 = m1; m4 *= m2; EXPECT_THAT(m4.GetRow(0), IsClose(Vector3(66.0f, 72.0f, 78.0f))); EXPECT_THAT(m4.GetRow(1), IsClose(Vector3(156.0f, 171.0f, 186.0f))); EXPECT_THAT(m4.GetRow(2), IsClose(Vector3(246.0f, 270.0f, 294.0f))); m3 = m1.TransposedMultiply(m2); EXPECT_THAT(m3.GetRow(0), IsClose(Vector3(138.0f, 150.0f, 162.0f))); EXPECT_THAT(m3.GetRow(1), IsClose(Vector3(168.0f, 183.0f, 198.0f))); EXPECT_THAT(m3.GetRow(2), IsClose(Vector3(198.0f, 216.0f, 234.0f))); } TEST(MATH_Matrix3x3, TestVectorMultiplication) { Matrix3x3 m1; m1.SetRow(0, 1.0f, 2.0f, 3.0f); m1.SetRow(1, 4.0f, 5.0f, 6.0f); m1.SetRow(2, 7.0f, 8.0f, 9.0f); Matrix3x3 m2; m2.SetRow(0, 7.0f, 8.0f, 9.0f); m2.SetRow(1, 10.0f, 11.0f, 12.0f); m2.SetRow(2, 13.0f, 14.0f, 15.0f); EXPECT_THAT((m1 * Vector3(1.0f, 2.0f, 3.0f)), IsClose(Vector3(14.0f, 32.0f, 50.0f))); Vector3 v1(1.0f, 2.0f, 3.0f); EXPECT_THAT((v1 * m1), IsClose(Vector3(30.0f, 36.0f, 42.0f))); v1 *= m1; EXPECT_THAT(v1, IsClose(Vector3(30.0f, 36.0f, 42.0f))); } TEST(MATH_Matrix3x3, TestSum) { Matrix3x3 m1; m1.SetRow(0, 1.0f, 2.0f, 3.0f); m1.SetRow(1, 4.0f, 5.0f, 6.0f); m1.SetRow(2, 7.0f, 8.0f, 9.0f); Matrix3x3 m2; m2.SetRow(0, 7.0f, 8.0f, 9.0f); m2.SetRow(1, 10.0f, 11.0f, 12.0f); m2.SetRow(2, 13.0f, 14.0f, 15.0f); Matrix3x3 m3 = m1 + m2; EXPECT_THAT(m3.GetRow(0), IsClose(Vector3(8.0f, 10.0f, 12.0f))); EXPECT_THAT(m3.GetRow(1), IsClose(Vector3(14.0f, 16.0f, 18.0f))); EXPECT_THAT(m3.GetRow(2), IsClose(Vector3(20.0f, 22.0f, 24.0f))); m3 = m1; m3 += m2; EXPECT_THAT(m3.GetRow(0), IsClose(Vector3(8.0f, 10.0f, 12.0f))); EXPECT_THAT(m3.GetRow(1), IsClose(Vector3(14.0f, 16.0f, 18.0f))); EXPECT_THAT(m3.GetRow(2), IsClose(Vector3(20.0f, 22.0f, 24.0f))); } TEST(MATH_Matrix3x3, TestDifference) { Matrix3x3 m1; m1.SetRow(0, 1.0f, 2.0f, 3.0f); m1.SetRow(1, 4.0f, 5.0f, 6.0f); m1.SetRow(2, 7.0f, 8.0f, 9.0f); Matrix3x3 m2; m2.SetRow(0, 7.0f, 8.0f, 9.0f); m2.SetRow(1, 10.0f, 11.0f, 12.0f); m2.SetRow(2, 13.0f, 14.0f, 15.0f); Matrix3x3 m3 = m1 - m2; EXPECT_THAT(m3.GetRow(0), IsClose(Vector3(-6.0f, -6.0f, -6.0f))); EXPECT_THAT(m3.GetRow(1), IsClose(Vector3(-6.0f, -6.0f, -6.0f))); EXPECT_THAT(m3.GetRow(2), IsClose(Vector3(-6.0f, -6.0f, -6.0f))); m3 = m1; m3 -= m2; EXPECT_THAT(m3.GetRow(0), IsClose(Vector3(-6.0f, -6.0f, -6.0f))); EXPECT_THAT(m3.GetRow(1), IsClose(Vector3(-6.0f, -6.0f, -6.0f))); EXPECT_THAT(m3.GetRow(2), IsClose(Vector3(-6.0f, -6.0f, -6.0f))); } TEST(MATH_Matrix3x3, TestScalarMultiplication) { Matrix3x3 m1; m1.SetRow(0, 1.0f, 2.0f, 3.0f); m1.SetRow(1, 4.0f, 5.0f, 6.0f); m1.SetRow(2, 7.0f, 8.0f, 9.0f); Matrix3x3 m2; m2.SetRow(0, 7.0f, 8.0f, 9.0f); m2.SetRow(1, 10.0f, 11.0f, 12.0f); m2.SetRow(2, 13.0f, 14.0f, 15.0f); Matrix3x3 m3 = m1 * 2.0f; EXPECT_THAT(m3.GetRow(0), IsClose(Vector3(2.0f, 4.0f, 6.0f))); EXPECT_THAT(m3.GetRow(1), IsClose(Vector3(8.0f, 10.0f, 12.0f))); EXPECT_THAT(m3.GetRow(2), IsClose(Vector3(14.0f, 16.0f, 18.0f))); m3 = m1; m3 *= 2.0f; EXPECT_THAT(m3.GetRow(0), IsClose(Vector3(2.0f, 4.0f, 6.0f))); EXPECT_THAT(m3.GetRow(1), IsClose(Vector3(8.0f, 10.0f, 12.0f))); EXPECT_THAT(m3.GetRow(2), IsClose(Vector3(14.0f, 16.0f, 18.0f))); m3 = 2.0f * m1; EXPECT_THAT(m3.GetRow(0), IsClose(Vector3(2.0f, 4.0f, 6.0f))); EXPECT_THAT(m3.GetRow(1), IsClose(Vector3(8.0f, 10.0f, 12.0f))); EXPECT_THAT(m3.GetRow(2), IsClose(Vector3(14.0f, 16.0f, 18.0f))); } TEST(MATH_Matrix3x3, TestScalarDivision) { Matrix3x3 m1; m1.SetRow(0, 1.0f, 2.0f, 3.0f); m1.SetRow(1, 4.0f, 5.0f, 6.0f); m1.SetRow(2, 7.0f, 8.0f, 9.0f); Matrix3x3 m2; m2.SetRow(0, 7.0f, 8.0f, 9.0f); m2.SetRow(1, 10.0f, 11.0f, 12.0f); m2.SetRow(2, 13.0f, 14.0f, 15.0f); Matrix3x3 m3 = m1 / 0.5f; EXPECT_THAT(m3.GetRow(0), IsClose(Vector3(2.0f, 4.0f, 6.0f))); EXPECT_THAT(m3.GetRow(1), IsClose(Vector3(8.0f, 10.0f, 12.0f))); EXPECT_THAT(m3.GetRow(2), IsClose(Vector3(14.0f, 16.0f, 18.0f))); m3 = m1; m3 /= 0.5f; EXPECT_THAT(m3.GetRow(0), IsClose(Vector3(2.0f, 4.0f, 6.0f))); EXPECT_THAT(m3.GetRow(1), IsClose(Vector3(8.0f, 10.0f, 12.0f))); EXPECT_THAT(m3.GetRow(2), IsClose(Vector3(14.0f, 16.0f, 18.0f))); } TEST(MATH_Matrix3x3, TestNegation) { Matrix3x3 m1; m1.SetRow(0, 1.0f, 2.0f, 3.0f); m1.SetRow(1, 4.0f, 5.0f, 6.0f); m1.SetRow(2, 7.0f, 8.0f, 9.0f); EXPECT_THAT(-(-m1), IsClose(m1)); EXPECT_THAT(-Matrix3x3::CreateZero(), IsClose(Matrix3x3::CreateZero())); Matrix3x3 m2 = -m1; EXPECT_THAT(m2.GetRow(0), IsClose(Vector3(-1.0f, -2.0f, -3.0f))); EXPECT_THAT(m2.GetRow(1), IsClose(Vector3(-4.0f, -5.0f, -6.0f))); EXPECT_THAT(m2.GetRow(2), IsClose(Vector3(-7.0f, -8.0f, -9.0f))); Matrix3x3 m3 = m1 + (-m1); EXPECT_THAT(m3, IsClose(Matrix3x3::CreateZero())); } TEST(MATH_Matrix3x3, TestTranspose) { Matrix3x3 m1; m1.SetRow(0, 1.0f, 2.0f, 3.0f); m1.SetRow(1, 4.0f, 5.0f, 6.0f); m1.SetRow(2, 7.0f, 8.0f, 9.0f); Matrix3x3 m2 = m1.GetTranspose(); AZ_TEST_ASSERT(m2.GetRow(0).IsClose(Vector3(1.0f, 4.0f, 7.0f))); AZ_TEST_ASSERT(m2.GetRow(1).IsClose(Vector3(2.0f, 5.0f, 8.0f))); AZ_TEST_ASSERT(m2.GetRow(2).IsClose(Vector3(3.0f, 6.0f, 9.0f))); m2 = m1; m2.Transpose(); AZ_TEST_ASSERT(m2.GetRow(0).IsClose(Vector3(1.0f, 4.0f, 7.0f))); AZ_TEST_ASSERT(m2.GetRow(1).IsClose(Vector3(2.0f, 5.0f, 8.0f))); AZ_TEST_ASSERT(m2.GetRow(2).IsClose(Vector3(3.0f, 6.0f, 9.0f))); } TEST(MATH_Matrix3x3, TestFastInverse) { // orthogonal matrix only Matrix3x3 m1 = Matrix3x3::CreateRotationX(1.0f); AZ_TEST_ASSERT((m1 * m1.GetInverseFast()).IsClose(Matrix3x3::CreateIdentity(), 0.02f)); Matrix3x3 m2 = Matrix3x3::CreateRotationZ(2.0f) * Matrix3x3::CreateRotationX(1.0f); Matrix3x3 m3 = m2.GetInverseFast(); // allow a little bigger threshold, because of the 2 rot matrices (sin,cos differences) AZ_TEST_ASSERT((m2 * m3).IsClose(Matrix3x3::CreateIdentity(), 0.1f)); AZ_TEST_ASSERT(m3.GetRow(0).IsClose(Vector3(-0.420f, 0.909f, 0.0f), 0.06f)); AZ_TEST_ASSERT(m3.GetRow(1).IsClose(Vector3(-0.493f, -0.228f, 0.841f), 0.06f)); AZ_TEST_ASSERT(m3.GetRow(2).IsClose(Vector3(0.765f, 0.353f, 0.542f), 0.06f)); } TEST(MATH_Matrix3x3, TestFullInverse) { Matrix3x3 m1; m1.SetRow(0, -1.0f, 2.0f, 3.0f); m1.SetRow(1, 4.0f, 5.0f, 6.0f); m1.SetRow(2, 7.0f, 8.0f, -9.0f); AZ_TEST_ASSERT((m1 * m1.GetInverseFull()).IsClose(Matrix3x3::CreateIdentity())); } TEST(MATH_Matrix3x3, TestScaleAccess) { Matrix3x3 m1 = Matrix3x3::CreateRotationX(DegToRad(40.0f)) * Matrix3x3::CreateScale(Vector3(2.0f, 3.0f, 4.0f)); EXPECT_THAT(m1.RetrieveScale(), IsClose(Vector3(2.0f, 3.0f, 4.0f))); EXPECT_THAT(m1.ExtractScale(), IsClose(Vector3(2.0f, 3.0f, 4.0f))); EXPECT_THAT(m1.RetrieveScale(), IsClose(Vector3::CreateOne())); m1.MultiplyByScale(Vector3(3.0f, 4.0f, 5.0f)); EXPECT_THAT(m1.RetrieveScale(), IsClose(Vector3(3.0f, 4.0f, 5.0f))); } TEST(MATH_Matrix3x3, TestScaleSqAccess) { Matrix3x3 m1 = Matrix3x3::CreateRotationX(DegToRad(40.0f)) * Matrix3x3::CreateScale(Vector3(2.0f, 3.0f, 4.0f)); EXPECT_THAT(m1.RetrieveScaleSq(), IsClose(Vector3(4.0f, 9.0f, 16.0f))); m1.ExtractScale(); EXPECT_THAT(m1.RetrieveScaleSq(), IsClose(Vector3::CreateOne())); m1.MultiplyByScale(Vector3(3.0f, 4.0f, 5.0f)); EXPECT_THAT(m1.RetrieveScaleSq(), IsClose(Vector3(9.0f, 16.0f, 25.0f))); } TEST(MATH_Matrix3x3, TestReciprocalScaled) { Matrix3x3 orthogonalMatrix = Matrix3x3::CreateRotationX(DegToRad(40.0f)); EXPECT_THAT(orthogonalMatrix.GetReciprocalScaled(), IsClose(orthogonalMatrix)); const AZ::Vector3 scale(2.8f, 0.7f, 1.3f); AZ::Matrix3x3 scaledMatrix = orthogonalMatrix; scaledMatrix.MultiplyByScale(scale); AZ::Matrix3x3 reciprocalScaledMatrix = orthogonalMatrix; reciprocalScaledMatrix.MultiplyByScale(scale.GetReciprocal()); EXPECT_THAT(scaledMatrix.GetReciprocalScaled(), IsClose(reciprocalScaledMatrix)); } TEST(MATH_Matrix3x3, TestPolarDecomposition) { Matrix3x3 m1 = Matrix3x3::CreateRotationX(DegToRad(30.0f)); Matrix3x3 m2 = Matrix3x3::CreateScale(Vector3(5.0f, 6.0f, 7.0f)); Matrix3x3 m3 = m1 * m2; AZ_TEST_ASSERT(m3.GetPolarDecomposition().IsClose(m1)); Matrix3x3 m4, m5; m3.GetPolarDecomposition(&m4, &m5); AZ_TEST_ASSERT((m4 * m5).IsClose(m3)); AZ_TEST_ASSERT(m4.IsClose(m1)); AZ_TEST_ASSERT(m5.IsClose(m2, 0.01f)); } TEST(MATH_Matrix3x3, TestOrthogonalize) { Matrix3x3 m1 = Matrix3x3::CreateRotationX(AZ::DegToRad(30.0f)) * Matrix3x3::CreateScale(Vector3(2.0f, 3.0f, 4.0f)); m1.SetElement(0, 1, 0.2f); Matrix3x3 m2 = m1.GetOrthogonalized(); AZ_TEST_ASSERT(AZ::IsClose(m2.GetRow(0).GetLength(), 1.0f)); AZ_TEST_ASSERT(AZ::IsClose(m2.GetRow(1).GetLength(), 1.0f)); AZ_TEST_ASSERT(AZ::IsClose(m2.GetRow(2).GetLength(), 1.0f)); AZ_TEST_ASSERT(AZ::IsClose(m2.GetRow(0).Dot(m2.GetRow(1)), 0.0f)); AZ_TEST_ASSERT(AZ::IsClose(m2.GetRow(0).Dot(m2.GetRow(2)), 0.0f)); AZ_TEST_ASSERT(AZ::IsClose(m2.GetRow(1).Dot(m2.GetRow(2)), 0.0f)); AZ_TEST_ASSERT(m2.GetRow(0).Cross(m2.GetRow(1)).IsClose(m2.GetRow(2))); AZ_TEST_ASSERT(m2.GetRow(1).Cross(m2.GetRow(2)).IsClose(m2.GetRow(0))); AZ_TEST_ASSERT(m2.GetRow(2).Cross(m2.GetRow(0)).IsClose(m2.GetRow(1))); m1.Orthogonalize(); AZ_TEST_ASSERT(m1.IsClose(m2)); } TEST(MATH_Matrix3x3, TestOrthogonal) { Matrix3x3 m1 = Matrix3x3::CreateRotationX(AZ::DegToRad(30.0f)); AZ_TEST_ASSERT(m1.IsOrthogonal(0.05f)); m1.SetRow(1, m1.GetRow(1) * 2.0f); AZ_TEST_ASSERT(!m1.IsOrthogonal(0.05f)); m1 = Matrix3x3::CreateRotationX(AZ::DegToRad(30.0f)); m1.SetRow(1, Vector3(0.0f, 1.0f, 0.0f)); AZ_TEST_ASSERT(!m1.IsOrthogonal(0.05f)); } TEST(MATH_Matrix3x3, TestIsClose) { Matrix3x3 m1 = Matrix3x3::CreateRotationX(DegToRad(30.0f)); Matrix3x3 m2 = m1; AZ_TEST_ASSERT(m1.IsClose(m2)); m2.SetElement(0, 0, 2.0f); AZ_TEST_ASSERT(!m1.IsClose(m2)); m2 = m1; m2.SetElement(0, 2, 2.0f); AZ_TEST_ASSERT(!m1.IsClose(m2)); } TEST(MATH_Matrix3x3, TestGetDiagonal) { Matrix3x3 m1; m1.SetRow(0, 1.0f, 2.0f, 3.0f); m1.SetRow(1, 4.0f, 5.0f, 6.0f); m1.SetRow(2, 7.0f, 8.0f, 9.0f); AZ_TEST_ASSERT(m1.GetDiagonal() == Vector3(1.0f, 5.0f, 9.0f)); } TEST(MATH_Matrix3x3, TestDeterminant) { Matrix3x3 m1; m1.SetRow(0, -1.0f, 2.0f, 3.0f); m1.SetRow(1, 4.0f, 5.0f, 6.0f); m1.SetRow(2, 7.0f, 8.0f, -9.0f); AZ_TEST_ASSERT(AZ::IsClose(m1.GetDeterminant(), 240.0f)); } TEST(MATH_Matrix3x3, TestAdjugate) { Matrix3x3 m1; m1.SetRow(0, 1.0f, 2.0f, 3.0f); m1.SetRow(1, 4.0f, 5.0f, 6.0f); m1.SetRow(2, 7.0f, 8.0f, 9.0f); Matrix3x3 m2 = m1.GetAdjugate(); AZ_TEST_ASSERT(m2.GetRow(0).IsClose(Vector3(-3.0f, 6.0f, -3.0f))); AZ_TEST_ASSERT(m2.GetRow(1).IsClose(Vector3(6.0f, -12.0f, 6.0f))); AZ_TEST_ASSERT(m2.GetRow(2).IsClose(Vector3(-3.0f, 6.0f, -3.0f))); } }
44.099819
158
0.611342
[ "transform", "3d" ]
3a5d88b73688e5a23b18c07801831cdda69077d1
10,899
cpp
C++
src/common/transformations/src/transformations/common_optimizations/binarize_weights.cpp
pfinashx/openvino
1d417e888b508415510fb0a92e4a9264cf8bdef7
[ "Apache-2.0" ]
1
2022-02-26T17:33:44.000Z
2022-02-26T17:33:44.000Z
src/common/transformations/src/transformations/common_optimizations/binarize_weights.cpp
pfinashx/openvino
1d417e888b508415510fb0a92e4a9264cf8bdef7
[ "Apache-2.0" ]
18
2022-01-21T08:42:58.000Z
2022-03-28T13:21:31.000Z
src/common/transformations/src/transformations/common_optimizations/binarize_weights.cpp
AlexRogalskiy/openvino
ac2e639ff8f9a607c3c682a4c4e165c238eb817f
[ "Apache-2.0" ]
1
2020-12-13T22:16:54.000Z
2020-12-13T22:16:54.000Z
// Copyright (C) 2018-2022 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include "transformations/common_optimizations/binarize_weights.hpp" #include "itt.hpp" #include <memory> #include <vector> #include <ngraph/opsets/opset5.hpp> #include <ngraph/pattern/op/wrap_type.hpp> #include <ngraph/rt_info.hpp> using namespace ngraph; NGRAPH_RTTI_DEFINITION(pass::BinarizeWeights, "BinarizeWeights", 0); static float quantize(float f, float input_low, float input_high, float output_low, float output_high) { if (f <= input_low) return output_low; if (f > input_high) return output_high; return std::round((f - input_low) / (input_high - input_low)) * (output_high - output_low) + output_low; } static std::vector<float> quantize_weights(const Shape& weights_shape, std::vector<float>& weights, Shape input_low_high_shape, const std::vector<float>& input_low, const std::vector<float>& input_high, Shape output_low_high_shape, const std::vector<float>& output_low, const std::vector<float>& output_high) { NGRAPH_CHECK(shape_size(input_low_high_shape) == 1 || shape_size(input_low_high_shape) == weights_shape[0]); NGRAPH_CHECK(shape_size(output_low_high_shape) == 1 || shape_size(output_low_high_shape) == weights_shape[0]); size_t out_feat_off = 1; for (size_t i = 1; i < weights_shape.size(); i++) out_feat_off *= weights_shape[i]; std::vector<float> out; out.reserve(shape_size(weights_shape)); auto get_idx = [out_feat_off] (size_t i, const Shape& shape) -> size_t { return (i / out_feat_off) % shape[0]; }; for (size_t i = 0; i < shape_size(weights_shape); i++) { size_t in_idx = get_idx(i, input_low_high_shape); size_t out_idx = get_idx(i, output_low_high_shape); out.push_back(quantize(weights[i], input_low[in_idx], input_high[in_idx], output_low[out_idx], output_high[out_idx])); } return out; } pass::BinarizeWeights::BinarizeWeights() { MATCHER_SCOPE(BinarizeWeights); auto activations_fq_pattern = pattern::wrap_type<opset5::FakeQuantize>( {pattern::any_input(), pattern::wrap_type<opset5::Constant>(), pattern::wrap_type<opset5::Constant>(), pattern::wrap_type<opset5::Constant>(), pattern::wrap_type<opset5::Constant>()}, pattern::consumers_count(1)); auto weights_fq_pattern = pattern::wrap_type<opset5::FakeQuantize>( {pattern::wrap_type<opset5::Constant>(), pattern::wrap_type<opset5::Constant>(), pattern::wrap_type<opset5::Constant>(), pattern::wrap_type<opset5::Constant>(), pattern::wrap_type<opset5::Constant>()}, pattern::consumers_count(1)); auto conv_pattern = pattern::wrap_type<opset5::Convolution>({activations_fq_pattern, weights_fq_pattern}); matcher_pass_callback callback = [=](pattern::Matcher &m) { auto conv = std::dynamic_pointer_cast<opset5::Convolution>(m.get_match_root()); if (!conv) return false; auto activations_fq = std::dynamic_pointer_cast<opset5::FakeQuantize>(conv->input_value(0).get_node_shared_ptr()); if (!activations_fq || activations_fq->get_levels() != 2) return false; auto weights_fq = std::dynamic_pointer_cast<opset5::FakeQuantize>(conv->input_value(1).get_node_shared_ptr()); if (!weights_fq || weights_fq->get_levels() != 2) return false; auto weights_const = std::dynamic_pointer_cast<opset5::Constant>(weights_fq->input_value(0).get_node_shared_ptr()); if (!weights_const) return false; auto check_output_low_high = [] (const std::vector<float>& output_low, const std::vector<float>& output_high) -> std::tuple<bool, bool> { bool output_low_is_zero = true; bool output_low_high_are_opposite = true; for (size_t i = 0; i < output_low.size(); i++) { output_low_is_zero = output_low_is_zero && output_low[i] == 0.0f; output_low_high_are_opposite = output_low_high_are_opposite && output_low[i] == -output_high[i]; } return std::tuple<bool, bool>{output_low_is_zero, output_low_high_are_opposite}; }; auto activations_output_low_const = std::dynamic_pointer_cast<opset5::Constant>(activations_fq->input_value(3).get_node_shared_ptr()); auto activations_output_high_const = std::dynamic_pointer_cast<opset5::Constant>(activations_fq->input_value(4).get_node_shared_ptr()); if (!activations_output_low_const || !activations_output_high_const) return false; // Check output low and high on activations FQ first bool act_out_low_is_zero = false; bool act_out_low_high_are_opposite = false; auto activations_output_low = activations_output_low_const->cast_vector<float>(); auto activations_output_high = activations_output_high_const->cast_vector<float>(); std::tie(act_out_low_is_zero, act_out_low_high_are_opposite) = check_output_low_high(activations_output_low, activations_output_high); if (!(act_out_low_high_are_opposite || act_out_low_is_zero)) return false; auto weights_input_low_const = std::dynamic_pointer_cast<opset5::Constant>(weights_fq->input_value(1).get_node_shared_ptr()); auto weights_input_high_const = std::dynamic_pointer_cast<opset5::Constant>(weights_fq->input_value(2).get_node_shared_ptr()); if (!weights_input_low_const || !weights_input_high_const) return false; auto weights_output_low_const = std::dynamic_pointer_cast<opset5::Constant>(weights_fq->input_value(3).get_node_shared_ptr()); auto weights_output_high_const = std::dynamic_pointer_cast<opset5::Constant>(weights_fq->input_value(4).get_node_shared_ptr()); if (!weights_output_low_const || !weights_output_high_const) return false; // Check output low and high on weights FQ bool weights_out_low_high_are_opposite = false; auto weights_output_low = weights_output_low_const->cast_vector<float>(); auto weights_output_high = weights_output_high_const->cast_vector<float>(); std::tie(std::ignore, weights_out_low_high_are_opposite) = check_output_low_high(weights_output_low, weights_output_high); if (!weights_out_low_high_are_opposite) return false; // Normalize output low and high to either (0, 1) or (-1, 1) auto normalize_output_low_high = [] (std::vector<float>& output_low, std::vector<float>& output_high) { for (size_t i = 0; i < output_low.size(); i++) { output_low[i] /= output_high[i]; output_high[i] = 1.0f; } }; normalize_output_low_high(activations_output_low, activations_output_high); normalize_output_low_high(weights_output_low, weights_output_high); // Choose additional normalization factor that has to be put after Convolution const std::shared_ptr<Node>& activations_norm_factor = activations_output_high_const; const std::shared_ptr<Node>& weights_norm_factor = weights_output_high_const; // Create new FQ on activations with new output low/high auto output_low_normalized = op::Constant::create(element::f32, activations_output_low_const->get_shape(), activations_output_low); output_low_normalized->set_friendly_name(activations_output_low_const->get_friendly_name()); auto output_high_normalized = op::Constant::create(element::f32, activations_output_high_const->get_shape(), activations_output_high); output_high_normalized->set_friendly_name(activations_output_high_const->get_friendly_name()); auto new_activations_fq = activations_fq->clone_with_new_inputs({activations_fq->input_value(0), activations_fq->input_value(1), activations_fq->input_value(2), output_low_normalized, output_high_normalized}); new_activations_fq->set_friendly_name(activations_fq->get_friendly_name()); // Quantize weights - here we get rid of FQ on weights and create a constant with quantized weights auto weights = weights_const->cast_vector<float>(); auto weights_input_low = weights_input_low_const->cast_vector<float>(); auto weights_input_high = weights_input_high_const->cast_vector<float>(); auto quantized_weights = quantize_weights(weights_const->get_shape(), weights, weights_input_low_const->get_shape(), weights_input_low, weights_input_high, weights_output_low_const->get_shape(), weights_output_low, weights_output_high); auto quantized_weights_const = op::Constant::create(element::f32, weights_const->get_shape(), quantized_weights); quantized_weights_const->set_friendly_name(weights_const->get_friendly_name()); auto new_conv = conv->clone_with_new_inputs({new_activations_fq, quantized_weights_const}); std::vector<int64_t> norm_factor_shape = {-1}; for (size_t i = 2; i < weights_const->get_shape().size(); i++) norm_factor_shape.push_back(1); auto norm_factor_shape_const = opset5::Constant::create(element::i64, Shape{norm_factor_shape.size()}, norm_factor_shape); auto activations_norm_factor_reshaped = std::make_shared<opset5::Reshape>(activations_norm_factor, norm_factor_shape_const, false); auto mul = std::make_shared<opset5::Multiply>(new_conv, activations_norm_factor_reshaped); auto weights_norm_factor_reshaped = std::make_shared<opset5::Reshape>(weights_norm_factor, norm_factor_shape_const, false); auto mul2 = std::make_shared<opset5::Multiply>(mul, weights_norm_factor_reshaped); copy_runtime_info({activations_fq, weights_fq, conv}, {new_activations_fq, new_conv, activations_norm_factor_reshaped, mul, weights_norm_factor_reshaped, mul2}); mul2->set_friendly_name(conv->get_friendly_name()); replace_node(conv, mul2); return true; }; auto m = std::make_shared<pattern::Matcher>(conv_pattern, matcher_name); this->register_matcher(m, callback); }
57.666667
150
0.666391
[ "shape", "vector" ]
3a5e1fbe5d58ae7a73d9b4cd4167b39143f1c428
2,355
cpp
C++
DS_a_Algo_in_CPP/ch2/maxSubSum3.cpp
frostRed/Exercises
c259baecbb24eb1ff22d92073ec6ce4cea822af6
[ "MIT" ]
null
null
null
DS_a_Algo_in_CPP/ch2/maxSubSum3.cpp
frostRed/Exercises
c259baecbb24eb1ff22d92073ec6ce4cea822af6
[ "MIT" ]
null
null
null
DS_a_Algo_in_CPP/ch2/maxSubSum3.cpp
frostRed/Exercises
c259baecbb24eb1ff22d92073ec6ce4cea822af6
[ "MIT" ]
null
null
null
// // Created by paysonl on 16-10-18. // #include <cassert> #include <vector> using std::vector; #include <iostream> using std::cout; using std::endl; #include <fstream> using std::ofstream; #include <random> using std::default_random_engine; using std::uniform_int_distribution; #include <chrono> using std::chrono::system_clock; using std::chrono::duration_cast; using std::chrono::microseconds; vector<int> randN(int n); int maxSumRec(const vector<int>& a, int left, int right); int max3(int, int, int); int maxSubSum3(const vector<int>& a) { return maxSumRec(a, 0, a.size() - 1); } int main(int argc, char** argv) { int N = std::stoi(argv[1]); int M = std::stoi(argv[2]); ofstream out("time3", ofstream::out); int sz = N; for (int i = 1; i <= M; ++i) { sz *= 2; vector<int> v = randN(sz); auto start = system_clock::now(); int result = maxSubSum3(v); auto end = system_clock::now(); auto duration = duration_cast<microseconds>(end - start); auto t = double(duration.count()) * microseconds::period::num / microseconds::period::den; out << t << std::endl; } return 0; } vector<int> randN(int n) { static default_random_engine e; static uniform_int_distribution<> u(-1000, 1000); vector<int> vi; for (int i = 0; i != n; ++i) vi.push_back(u(e)); return vi; } int maxSumRec(const vector<int>& a, int left, int right) { if (left == right) if (a[left] > 0) return a[left]; else return 0; int center = (left + right) / 2; int maxLeftSum = maxSumRec(a, left, center); int maxRightSum = maxSumRec(a, center + 1, right); int maxLeftBorderSum = 0, leftBorderSum = 0; for (int i = center; i >= left; --i) { leftBorderSum += a[i]; if (leftBorderSum > maxLeftBorderSum) maxLeftBorderSum = leftBorderSum; } int maxRightBorderSum = 0, rightBorderSum = 0; for (int i = center + 1; i <= right; ++i) { rightBorderSum += a[i]; if (rightBorderSum > maxRightBorderSum) maxRightBorderSum = rightBorderSum; } return max3(maxLeftSum, maxRightSum, maxLeftBorderSum + maxRightBorderSum); } int max3(int i1, int i2, int i3) { int max2 = i1 > i2 ? i1 : i2; return max2 > i3 ? max2 : i3; }
24.53125
98
0.604246
[ "vector" ]
3a6050d9d42c6bd3ea699b5e2997a71344dfb509
2,797
cpp
C++
codeforces/F - TorCoder/Wrong answer on test 8.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
1
2022-02-11T16:55:36.000Z
2022-02-11T16:55:36.000Z
codeforces/F - TorCoder/Wrong answer on test 8.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
codeforces/F - TorCoder/Wrong answer on test 8.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
/**************************************************************************************** * @author: kzvd4729 created: Nov/11/2020 22:21 * solution_verdict: Wrong answer on test 8 language: GNU C++14 * run_time: 46 ms memory_used: 88200 KB * problem: https://codeforces.com/contest/240/problem/F ****************************************************************************************/ #include<iostream> #include<vector> #include<cstring> #include<map> #include<bitset> #include<assert.h> #include<algorithm> #include<iomanip> #include<cmath> #include<set> #include<queue> #include<sstream> #include<unordered_map> #include<unordered_set> #include<chrono> #include<stack> #include<deque> #include<random> #define long long long using namespace std; const int N=1e5; int sg[26+2][N*4+8],lz[26+2][N*4+8]; void pushDown(int id,int nd,int lo,int hi) { if(lz[id][nd]==-1)return ; sg[id][nd]=(hi-lo+1)*lz[id][nd]; if(lo!=hi) { lz[id][nd*2]=lz[id][nd]; lz[id][nd*2+1]=lz[id][nd]; } lz[id][nd]=-1; } void assign(int id,int nd,int lo,int hi,int lt,int rt,int vl) { if(lo>rt||hi<lt||lt>rt)return ; if(lo>=lt&&hi<=rt) { lz[id][nd]=vl;pushDown(id,nd,lo,hi); return ; } pushDown(id,nd,lo,hi); int md=(lo+hi)/2; assign(id,nd*2,lo,md,lt,rt,vl); assign(id,nd*2+1,md+1,hi,lt,rt,vl); sg[id][nd]=sg[id][nd*2]+sg[id][nd*2+1]; } int get(int id,int nd,int lo,int hi,int lt,int rt) { pushDown(id,nd,lo,hi); if(lo>rt||hi<lt)return 0; if(lo>=lt&&hi<=rt)return sg[id][nd]; int md=(lo+hi)/2; return get(id,nd*2,lo,md,lt,rt)+get(id,nd*2+1,md+1,hi,lt,rt); } int cnt[N+2]; int main() { freopen("input.txt","r",stdin); freopen("output.txt","w",stdout); ios_base::sync_with_stdio(0);cin.tie(0); int n,q;cin>>n>>q;string s;cin>>s; memset(lz,-1,sizeof lz); for(int i=0;i<n;i++) { for(int j=0;j<26;j++) { bool f=((int)(s[i]-'a')==j); assign(j+1,1,1,n,i+1,i+1,f); } } while(q--) { int l,r;cin>>l>>r;int L=l,R=r; int f=0,j; for(int i=1;i<=26;i++) { cnt[i]=get(i,1,1,n,l,r); if(cnt[i]%2)f++,j=i; } //for(int i=1;i<=26;i++)cout<<cnt[i];cout<<endl; if(f>1)continue; for(int i=1;i<=26;i++) { if(cnt[i]==0)continue; assign(i,1,1,n,L,l-1,0);assign(i,1,1,n,r+1,R,0); assign(i,1,1,n,l,l+cnt[i]/2-1,1);l=l+cnt[i]/2; assign(i,1,1,n,r-cnt[i]/2+1,r,1);r=r-cnt[i]/2; assign(i,1,1,n,l,r,0); } if(f)assign(j,1,1,n,l,r,1); } for(int i=1;i<=n;i++) { for(int j=1;j<=26;j++) { if(get(j,1,1,n,i,i))cout<<(char)(j-1+'a'); } } cout<<endl; return 0; }
25.898148
111
0.496246
[ "vector" ]
3a6699bcee27b642a24cdbeb765b21c392946208
627
cpp
C++
knapsack_cpp/knapsack/problem.cpp
fpert041/KnapsackDFO
ffcba3e6dc78297d161846ca8544251edc90cfab
[ "JasPer-2.0" ]
1
2020-05-17T16:59:18.000Z
2020-05-17T16:59:18.000Z
knapsack_cpp/knapsack/problem.cpp
fpert041/KnapsackDFO
ffcba3e6dc78297d161846ca8544251edc90cfab
[ "JasPer-2.0" ]
null
null
null
knapsack_cpp/knapsack/problem.cpp
fpert041/KnapsackDFO
ffcba3e6dc78297d161846ca8544251edc90cfab
[ "JasPer-2.0" ]
null
null
null
// // problem.cpp // knapsack // // Created by Francesco Perticarari on 03/12/2017. // Copyright © 2017 agapeSoft. All rights reserved. // #include "problem.hpp" #include <math.h> #include <vector> #include <array> #include <numeric> using namespace std; double mean(vector<double>& v){ double sum = std::accumulate(std::begin(v), std::end(v), 0.0); return sum / v.size(); } double stDev(vector<double>& v){ double m = mean(v); double accum = 0.0; std::for_each (std::begin(v), std::end(v), [&](const double d) { accum += (d - m) * (d - m); }); return sqrt(accum / (v.size()-1)); }
20.225806
68
0.599681
[ "vector" ]
3a681ca36698d45d8d5aa586de5d5751e94f2017
5,521
cpp
C++
src/game/shared/dod/weapon_riflegrenade.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
6
2022-01-23T09:40:33.000Z
2022-03-20T20:53:25.000Z
src/game/shared/dod/weapon_riflegrenade.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
null
null
null
src/game/shared/dod/weapon_riflegrenade.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
1
2022-02-06T21:05:23.000Z
2022-02-06T21:05:23.000Z
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // //=============================================================================// #include "cbase.h" #include "fx_dod_shared.h" #include "weapon_riflegrenade.h" #ifdef CLIENT_DLL #include "prediction.h" #endif IMPLEMENT_NETWORKCLASS_ALIASED( WeaponBaseRifleGrenade, DT_WeaponBaseRifleGrenade ) BEGIN_NETWORK_TABLE( CWeaponBaseRifleGrenade, DT_WeaponBaseRifleGrenade ) END_NETWORK_TABLE() BEGIN_PREDICTION_DATA( CWeaponBaseRifleGrenade ) END_PREDICTION_DATA() CWeaponBaseRifleGrenade::CWeaponBaseRifleGrenade() { } void CWeaponBaseRifleGrenade::Spawn() { BaseClass::Spawn(); } void CWeaponBaseRifleGrenade::PrimaryAttack( void ) { CDODPlayer *pPlayer = ToDODPlayer( GetPlayerOwner() ); Assert( pPlayer ); // Out of ammo? if ( m_iClip1 <= 0 ) { if (m_bFireOnEmpty) { PlayEmptySound(); m_flNextPrimaryAttack = gpGlobals->curtime + 0.2; } return; } if( pPlayer->GetWaterLevel() > 2 ) { PlayEmptySound(); m_flNextPrimaryAttack = gpGlobals->curtime + 1.0; return; } // decrement before calling PlayPrimaryAttackAnim, so we can play the empty anim if necessary m_iClip1--; SendWeaponAnim( ACT_VM_PRIMARYATTACK ); // player "shoot" animation pPlayer->SetAnimation( PLAYER_ATTACK1 ); #ifdef CLIENT_DLL if( pPlayer && !pPlayer->IsDormant() ) pPlayer->DoAnimationEvent( PLAYERANIMEVENT_FIRE_GUN ); #else if( pPlayer ) pPlayer->DoAnimationEvent( PLAYERANIMEVENT_FIRE_GUN ); #endif #ifndef CLIENT_DLL ShootGrenade(); #endif WeaponSound( SINGLE ); DoFireEffects(); #ifdef CLIENT_DLL CDODPlayer *p = ToDODPlayer( GetPlayerOwner() ); if ( prediction->IsFirstTimePredicted() ) p->DoRecoil( GetWeaponID(), GetRecoil() ); #endif m_flNextPrimaryAttack = m_flNextSecondaryAttack = gpGlobals->curtime + GetFireDelay(); m_flTimeWeaponIdle = gpGlobals->curtime + m_pWeaponInfo->m_flTimeToIdleAfterFire; #ifndef CLIENT_DLL IGameEvent * event = gameeventmanager->CreateEvent( "dod_stats_weapon_attack" ); if ( event ) { event->SetInt( "attacker", pPlayer->GetUserID() ); event->SetInt( "weapon", GetStatsWeaponID() ); gameeventmanager->FireEvent( event ); } #endif //CLIENT_DLL } Activity CWeaponBaseRifleGrenade::GetDrawActivity( void ) { return ( (m_iClip1 <= 0 ) ? ACT_VM_DRAW_EMPTY : ACT_VM_DRAW ); } Activity CWeaponBaseRifleGrenade::GetIdleActivity( void ) { return ( (m_iClip1 <= 0 ) ? ACT_VM_IDLE_EMPTY : ACT_VM_IDLE ); } bool CWeaponBaseRifleGrenade::Holster( CBaseCombatWeapon *pSwitchingTo ) { #ifndef CLIENT_DLL // If they attempt to switch weapons before the throw animation is done, // allow it, but kill the weapon if we have to. CDODPlayer *pPlayer = ToDODPlayer( GetPlayerOwner() ); if( pPlayer && pPlayer->GetAmmoCount(m_iPrimaryAmmoType) <= 0 && m_iClip1 <= 0 ) { pPlayer->Weapon_Drop( this, NULL, NULL ); UTIL_Remove(this); return true; } #endif return BaseClass::Holster( pSwitchingTo ); } // weapon idle to destroy weapon if empty void CWeaponBaseRifleGrenade::WeaponIdle( void ) { #ifndef CLIENT_DLL CDODPlayer *pPlayer = ToDODPlayer( GetPlayerOwner() ); if (pPlayer->GetAmmoCount(m_iPrimaryAmmoType) <= 0 && m_iClip1 <= 0) { pPlayer->Weapon_Drop( this, NULL, NULL ); UTIL_Remove(this); return; } #endif BaseClass::WeaponIdle(); } #define DOD_RIFLEGRENADE_SPEED 2000 extern ConVar dod_grenadegravity; #ifndef CLIENT_DLL void CWeaponBaseRifleGrenade::ShootGrenade( void ) { CDODPlayer *pPlayer = ToDODPlayer( GetOwner() ); if ( !pPlayer ) { Assert( false ); return; } QAngle angThrow = pPlayer->LocalEyeAngles(); Vector vForward, vRight, vUp; AngleVectors( angThrow, &vForward, &vRight, &vUp ); Vector eyes = pPlayer->GetAbsOrigin() + pPlayer->GetViewOffset(); Vector vecSrc = eyes; Vector vecThrow = vForward * DOD_RIFLEGRENADE_SPEED; // raise origin enough so that you can't shoot it straight down through the world if ( pPlayer->m_Shared.IsProne() ) { vecSrc.z += 16; } SetCollisionGroup( COLLISION_GROUP_WEAPON ); QAngle angles; VectorAngles( -vecThrow, angles ); // estimate angular velocity based on initial conditions // uses a constant ang velocity instead of the derivative of the flight path, oh well. AngularImpulse angImpulse; angImpulse.Init(); if ( vecThrow.z > 0 ) angImpulse.y = -angles.x / ( sqrt( (-2 * vecThrow.z) / dod_grenadegravity.GetFloat() )); else angImpulse.y = -10; EmitGrenade( vecSrc, angles, vecThrow, angImpulse, pPlayer, RIFLEGRENADE_FUSE_LENGTH ); } void CWeaponBaseRifleGrenade::EmitGrenade( Vector vecSrc, QAngle vecAngles, Vector vecVel, AngularImpulse angImpulse, CBasePlayer *pPlayer, float flLifeTime ) { Assert( !"Deriving classes should define this" ); } #endif bool CWeaponBaseRifleGrenade::CanDeploy( void ) { // does the player own the weapon that fires this grenade? CBasePlayer *pPlayer = GetPlayerOwner(); if ( !pPlayer ) return false; CBaseCombatWeapon *pOwnedWeapon = pPlayer->Weapon_OwnsThisType( GetCompanionWeaponName() ); if ( pOwnedWeapon == NULL ) return false; return BaseClass::CanDeploy(); } const char *CWeaponBaseRifleGrenade::GetCompanionWeaponName( void ) { Assert( !"Should not call this version. Inheriting classes must implement." ); return ""; } float CWeaponBaseRifleGrenade::GetRecoil( void ) { CDODPlayer *p = ToDODPlayer( GetPlayerOwner() ); if( p && p->m_Shared.IsInMGDeploy() ) { return 0.0f; } return 10; }
23.695279
159
0.714726
[ "vector" ]
3a699cd5d9b17d09fffd5a161b71ab8772adea6e
2,757
cxx
C++
windows/core/ntgdi/gre/helpers.cxx
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
windows/core/ntgdi/gre/helpers.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
windows/core/ntgdi/gre/helpers.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/******************************Module*Header*******************************\ * Module Name: HELPERS.CXX * * * * Hydra routines * * For Display drivers * * * * Copyright (c) 1997-1999 Microsoft * \**************************************************************************/ #include "precomp.hxx" extern "C" { #include "pw32kevt.h" #include <ctxdd.h> } #include <winDDIts.h> #if !defined(_GDIPLUS_) /******************************Public*Routine******************************\ * EngGetTickCount * * Return the system tick count * \**************************************************************************/ DWORD APIENTRY EngGetTickCount() { return( NtGetTickCount()); } /******************************Public*Routine******************************\ * EngFileWrite * * Write to File Object * \**************************************************************************/ VOID APIENTRY EngFileWrite( HANDLE hFileObject, PVOID Buffer, ULONG BufferSize, PULONG pBytesWritten ) { NTSTATUS Status; Status = CtxWriteFile( (PFILE_OBJECT)hFileObject, Buffer, BufferSize, NULL, NULL, NULL ); if ( !NT_SUCCESS(Status) ) *pBytesWritten = 0; else *pBytesWritten = BufferSize; } /******************************Public*Routine******************************\ * EngFileIoControl * * IoControl to File Object * \**************************************************************************/ DWORD APIENTRY EngFileIoControl( HANDLE hFileObject, DWORD dwIoControlCode, LPVOID lpInBuffer, DWORD nInBufferSize, LPVOID lpOutBuffer, DWORD nOutBufferSize, LPDWORD lpBytesReturned ) { NTSTATUS Status; IO_STATUS_BLOCK Iosb; Status = CtxDeviceIoControlFile( (PFILE_OBJECT)hFileObject, dwIoControlCode, lpInBuffer, nInBufferSize, lpOutBuffer, nOutBufferSize, FALSE, NULL, &Iosb, NULL ); *lpBytesReturned = (DWORD) Iosb.Information; return Status; } #endif // !defined(_GDIPLUS_)
28.42268
94
0.357635
[ "object" ]
3a6c4ade9fc977ca29b7567377af4a7c8ee01387
9,599
cpp
C++
request/DhcpMessage.cpp
d-kozak/isa-proj
73c525914a985d631d593985d8f1bb4291f072f3
[ "MIT" ]
null
null
null
request/DhcpMessage.cpp
d-kozak/isa-proj
73c525914a985d631d593985d8f1bb4291f072f3
[ "MIT" ]
null
null
null
request/DhcpMessage.cpp
d-kozak/isa-proj
73c525914a985d631d593985d8f1bb4291f072f3
[ "MIT" ]
null
null
null
// // Created by david on 8.10.16. // #include "DhcpMessage.h" #include "../constants.h" #include <arpa/inet.h> #include <fstream> #include <iterator> /** * extracts given data type from the vector of chars, starting at index index */ #define getDataTypeFromCharVec(dataType, charVec, index) (*((dataType *) (&charVec[index]))) /** * extracts given data type from the vector of chars, starting at index index */ #define getElemAsType(type, vec, index) *((type *)(&vec[index])) /** * checks given option * @throws ParseException if the size is invalid */ void check_size_of_option(unsigned char realSize, unsigned char expectedSize, unsigned long currentIndex, unsigned long sizeOfMsg) { if (realSize != expectedSize) { stringstream ss; ss << "Wrong size of option... " << realSize << " vs " << expectedSize; throw ParseException(ss.str()); } unsigned long minimalPossibleSize = currentIndex + 1 + 1 + expectedSize; if (minimalPossibleSize > sizeOfMsg) { stringstream ss; ss << "Wrong size of message " << realSize << " vs at least " << minimalPossibleSize; throw ParseException(ss.str()); } } void saveDhcpMessage(vector<unsigned char> &vec, unsigned int xid, unsigned char type) { if(!DEBUG) return; string tmp; switch (type) { case DISCOVER: tmp = "DISCOVER"; break; case OFFER: tmp = "OFFER"; break; case REQUEST: tmp = "REQUEST"; break; case RELEASE: tmp = "RELEASE"; break; case ACK: tmp = "ACK"; break; case NACK: tmp = "NACK"; break; default: throw InvalidArgumentException("Default in type enum in save dhcp, this should never happen"); } stringstream ss; ss << tmp << "_" << xid << ".dhcp"; ofstream file(ss.str()); if(!file){ cerr << "Could not save message into file " + ss.str(); return; } copy(vec.begin(),vec.end(),ostream_iterator<unsigned char>(file)); file.close(); } DhcpMessage::DhcpMessage(vector<unsigned char> &msg) : ciaddr(0, 0, 0, 0), yiaddr(0, 0, 0, 0), siaddr(0, 0, 0, 0), giaddr(0, 0, 0, 0), chaddr(0, 0, 0, 0, 0, 0), subnetMask(0, 0, 0, 0), serverIdentifier(0, 0, 0, 0),requestedIpAddress(0,0,0,0) { if (msg.size() < MSG_SIZE) { stringstream ss; ss << "Message is too short" << msg.data(); throw ParseException(ss.str()); } this->op = msg[_op]; this->htype = msg[_htype]; this->hlen = msg[_hlen]; this->hops = msg[_hops]; this->xid = ntohl(getDataTypeFromCharVec(uint32_t, msg, _xid)); this->secs = ntohs(getDataTypeFromCharVec(uint16_t, msg, _secs)); this->flags = ntohs(getDataTypeFromCharVec(uint16_t, msg, _flags)); this->ciaddr = addressing::IpAddress(msg.data() + _ciaddr); this->yiaddr = addressing::IpAddress(msg.data() + _yiaddr); this->siaddr = addressing::IpAddress(msg.data() + _siaddr); this->giaddr = addressing::IpAddress(msg.data() + _giaddr); this->chaddr = addressing::MacAddress(msg.data() + _chaddr); memcpy(this->sname, msg.data() + _sname, _size_sname); memcpy(this->file, msg.data() + _file, _size_file); // now parse options unsigned long index = _options; unsigned char opId; if (msg.size() < MSG_SIZE + MAGIC_COOKIES_SIZE) { // message does not contain any options... return; } //first check magic cookies 99, 130, 83 and 99 if (msg[index] != 99 || msg[index + 1] != 130 || msg[index + 2] != 83 || msg[index + 3] != 99) { stringstream ss; ss << "Invalid magic cookies" << endl; throw ParseException(ss.str()); } index += 4; if (index >= msg.size()) { throw ParseException("Invalid size of dhcp message"); } while ((opId = msg[index]) != end) { if (msg[index] == pad) // skip pads continue; // check if we can read at leat option id and option size if (index + 1 >= msg.size()) { throw ParseException("Invalid size of dhcp message"); } switch (opId) { case subnetMaskID: { check_size_of_option(msg[index + 1], _size_subnet_mask, index, msg.size()); index += 2; this->subnetMask = addressing::IpAddress(msg.data() + index); index += _size_subnet_mask; break; } case leaseTimeID: { check_size_of_option(msg[index + 1], _size_lease_time, index, msg.size()); index += 2; this->leaseTime = ntohl(getDataTypeFromCharVec(uint32_t, msg, index)); index += _size_lease_time; break; } case messageTypeID: { check_size_of_option(msg[index + 1], _size_message_type, index, msg.size()); index += 2; this->messageType = msg[index]; index += _size_message_type; break; } case serverIdentifierID: { check_size_of_option(msg[index + 1], _size_server_identifier, index, msg.size()); index += 2; this->serverIdentifier = addressing::IpAddress(msg.data() + index); index += _size_server_identifier; break; } case requestedIpAddressID: { check_size_of_option(msg[index+1],_size_requested_ip_address,index,msg.size()); index += 2; this->requestedIpAddress = addressing::IpAddress(msg.data() + index); index += _size_requested_ip_address; } default: { stringstream ss; ss << "Unknown option id: " << (int) opId; index += 2 + msg[index + 1]; // 2 for option } } if (index >= msg.size()) { throw ParseException("Invalid size of dhcp message"); } } saveDhcpMessage(msg,xid,messageType); } DhcpMessage &DhcpMessage::operator=(DhcpMessage other) { this->setOp(other.getOP()); this->setHType(other.getHtype()); this->setHLen(other.getHlen()); this->setHOps(other.getHOps()); this->setXid(other.getXid()); this->setSecs(other.getSecs()); this->setFlags(other.getFlags()); this->setCiaddr(other.getCiaddr()); this->setYiaddr(other.getYiaddr()); this->setSiaddr(other.getSiaddr()); this->setGiaddr(other.getGiaddr()); this->setChaddr(other.getChaddr()); this->setSname(other.getSname()); this->setFile(other.getFile()); this->setMeesageType(other.getMeesageType()); this->setLeaseTime(other.getLeaseTime()); this->setSubnetMask(other.getSubnetMask()); this->setServerIdentifier(other.getServerIdentifier()); return *this; } vector<unsigned char> DhcpMessage::createMessageVector() const { vector<unsigned char> ret; ret.resize(MSG_SIZE_WITH_OPTIONS); ret[_op] = op; ret[_htype] = htype; ret[_hlen] = hlen; ret[_hops] = hops; getElemAsType(uint32_t, ret, _xid) = htonl(xid); getElemAsType(uint16_t, ret, _secs) = htons(secs); getElemAsType(uint16_t, ret, _flags) = htons(flags); getElemAsType(uint32_t, ret, _ciaddr) = htonl(ciaddr.getAddrForSocket()); getElemAsType(uint32_t, ret, _yiaddr) = htonl(yiaddr.getAddrForSocket()); getElemAsType(uint32_t, ret, _siaddr) = htonl(siaddr.getAddrForSocket()); getElemAsType(uint32_t, ret, _giaddr) = htonl(giaddr.getAddrForSocket()); // mac address for (int i = 0; i < MAC_SIZE; i++) { ret[_chaddr + i] = this->chaddr.getPart(i); } memcpy(ret.data() + _sname, sname, _size_sname); memcpy(ret.data() + _file, file, _size_file); int index = _options; // magic cookies ret[index++] = 99; ret[index++] = 130; ret[index++] = 83; ret[index++] = 99; // now options ret[index++] = messageTypeID; ret[index++] = _size_message_type; ret[index++] = messageType; if (this->messageType == NACK) { // NACK messages do not need any other options ret[index++] = end; // type ret[index++] = end; // size saveDhcpMessage(ret,xid,messageType); return ret; } ret[index++] = subnetMaskID; ret[index++] = _size_subnet_mask; getElemAsType(uint32_t, ret, index) = subnetMask.getAddrForSocket(); // htonl is not here on purpose because this address is generated in the network order index += _size_subnet_mask; ret[index++] = leaseTimeID; ret[index++] = _size_lease_time; getElemAsType(uint32_t, ret, index) = htonl(leaseTime); index += _size_lease_time; ret[index++] = serverIdentifierID; ret[index++] = _size_server_identifier; getElemAsType(uint32_t, ret, index) = htonl(serverIdentifier.getAddrForSocket()); index += _size_server_identifier; ret[index++] = end; // type ret[index++] = end; // size TODO probably not neccessary saveDhcpMessage(ret,xid,messageType); return ret; } string DhcpMessage::toString() const { stringstream ss; ss << this->_name + " -> " << "{" << endl; ss << this->createMessageVector().data() << endl; ss << "}"; return ss.str(); }
32.429054
144
0.577977
[ "vector" ]
b9232929039ad2cb94045b20a213873c5add95e5
6,161
cpp
C++
cslibs_plugins_data/test/plugins.cpp
doge-of-the-day/cslibs_plugins
9740883e5f93c5a74ea4a889067b25fb3f5cb6f0
[ "BSD-3-Clause" ]
null
null
null
cslibs_plugins_data/test/plugins.cpp
doge-of-the-day/cslibs_plugins
9740883e5f93c5a74ea4a889067b25fb3f5cb6f0
[ "BSD-3-Clause" ]
null
null
null
cslibs_plugins_data/test/plugins.cpp
doge-of-the-day/cslibs_plugins
9740883e5f93c5a74ea4a889067b25fb3f5cb6f0
[ "BSD-3-Clause" ]
null
null
null
#include <gtest/gtest.h> #include <ros/ros.h> #include <cslibs_math_ros/tf/tf_listener.hpp> #include <cslibs_plugins/plugin_loader.hpp> #include <cslibs_plugins/plugin_loader_v2.hpp> #include <cslibs_plugins_data/data_provider.hpp> using data_provider_t = cslibs_plugins_data::DataProvider; using tf_listener_t = cslibs_math_ros::tf::TFListener; TEST(Test_cslibs_plugins_data, testLoadProviders) { ros::NodeHandle nh{"~"}; const std::string package_name = "cslibs_plugins_data"; cslibs_plugins::PluginManager<data_provider_t> manager( data_provider_t::Type(), package_name); manager.load(); EXPECT_TRUE(manager.pluginsLoaded()); std::vector<std::string> class_names = { "cslibs_plugins_data::LaserProvider", "cslibs_plugins_data::LaserProvider_d", "cslibs_plugins_data::LaserProvider_f", "cslibs_plugins_data::Pointcloud3dProvider", "cslibs_plugins_data::Pointcloud3dProvider_d", "cslibs_plugins_data::Pointcloud3dProvider_f", "cslibs_plugins_data::Odometry2DProvider", "cslibs_plugins_data::Odometry2DProvider_d", "cslibs_plugins_data::Odometry2DProvider_f", "cslibs_plugins_data::Odometry2DProviderTF", "cslibs_plugins_data::Odometry2DProviderTF_d", "cslibs_plugins_data::Odometry2DProviderTF_f"}; for (const auto &class_name : class_names) { auto constructor = manager.getConstructor(class_name); data_provider_t::Ptr plugin; if (constructor) { plugin = constructor(); } EXPECT_TRUE(static_cast<bool>(constructor)); EXPECT_TRUE(plugin.get() != nullptr); } } TEST(Test_cslibs_plugins_data, testParseLaunchFile) { ros::NodeHandle nh{"~"}; cslibs_plugins::LaunchfileParser parser(nh); cslibs_plugins::LaunchfileParser::found_plugin_set_t plugins; parser.getNamesForBaseClass<cslibs_plugins_data::DataProvider>(plugins); cslibs_plugins::LaunchfileParser::found_plugin_set_t expected_plugins; expected_plugins.emplace("cslibs_plugins_data::LaserProvider", "laser"); EXPECT_EQ(1ul, expected_plugins.size()); expected_plugins.emplace("cslibs_plugins_data::LaserProvider_d", "laser_d"); EXPECT_EQ(2ul, expected_plugins.size()); expected_plugins.emplace("cslibs_plugins_data::LaserProvider_f", "laser_f"); EXPECT_EQ(3ul, expected_plugins.size()); expected_plugins.emplace("cslibs_plugins_data::Odometry2DProvider", "odometry"); EXPECT_EQ(4ul, expected_plugins.size()); expected_plugins.emplace("cslibs_plugins_data::Odometry2DProvider_d", "odometry_d"); EXPECT_EQ(5ul, expected_plugins.size()); expected_plugins.emplace("cslibs_plugins_data::Odometry2DProvider_f", "odometry_f"); EXPECT_EQ(6ul, expected_plugins.size()); expected_plugins.emplace("cslibs_plugins_data::Odometry2DProviderTF", "odometry_tf"); EXPECT_EQ(7ul, expected_plugins.size()); expected_plugins.emplace("cslibs_plugins_data::Odometry2DProviderTF_d", "odometry_tf_d"); EXPECT_EQ(8ul, expected_plugins.size()); expected_plugins.emplace("cslibs_plugins_data::Odometry2DProviderTF_f", "odometry_tf_f"); EXPECT_EQ(9ul, expected_plugins.size()); expected_plugins.emplace("cslibs_plugins_data::Pointcloud3dProvider", "pointcloud"); EXPECT_EQ(10ul, expected_plugins.size()); expected_plugins.emplace("cslibs_plugins_data::Pointcloud3dProvider_d", "pointcloud_d"); EXPECT_EQ(11ul, expected_plugins.size()); expected_plugins.emplace("cslibs_plugins_data::Pointcloud3dProvider_f", "pointcloud_f"); EXPECT_EQ(12ul, expected_plugins.size()); EXPECT_EQ(expected_plugins.size(), plugins.size()); for (auto plugin : plugins) { EXPECT_TRUE(expected_plugins.find(plugin) != expected_plugins.end()); } } TEST(Test_cslibs_plugins_data, testPluginLoaderV2) { ros::NodeHandle nh{"~"}; cslibs_math_ros::tf::TFProvider::Ptr tf_{new cslibs_math_ros::tf::TFListener}; cslibs_plugins::PluginLoaderV2 loader("cslibs_plugins_data", nh); cslibs_plugins::LaunchfileParser::found_plugin_set_t plugins; const auto &parser = loader.getLaunchFileParser(); parser->getNamesForBaseClass<cslibs_plugins_data::DataProvider>(plugins); cslibs_plugins::LaunchfileParser::found_plugin_set_t expected_plugins; expected_plugins.emplace("cslibs_plugins_data::LaserProvider", "laser"); expected_plugins.emplace("cslibs_plugins_data::LaserProvider_d", "laser_d"); expected_plugins.emplace("cslibs_plugins_data::LaserProvider_f", "laser_f"); expected_plugins.emplace("cslibs_plugins_data::Odometry2DProvider", "odometry"); expected_plugins.emplace("cslibs_plugins_data::Odometry2DProvider_d", "odometry_d"); expected_plugins.emplace("cslibs_plugins_data::Odometry2DProvider_f", "odometry_f"); expected_plugins.emplace("cslibs_plugins_data::Odometry2DProviderTF", "odometry_tf"); expected_plugins.emplace("cslibs_plugins_data::Odometry2DProviderTF_d", "odometry_tf_d"); expected_plugins.emplace("cslibs_plugins_data::Odometry2DProviderTF_f", "odometry_tf_f"); expected_plugins.emplace("cslibs_plugins_data::Pointcloud3dProvider", "pointcloud"); expected_plugins.emplace("cslibs_plugins_data::Pointcloud3dProvider_d", "pointcloud_d"); expected_plugins.emplace("cslibs_plugins_data::Pointcloud3dProvider_f", "pointcloud_f"); for (auto plugin : plugins) { EXPECT_TRUE(expected_plugins.find(plugin) != expected_plugins.end()); } std::map<std::string, cslibs_plugins_data::DataProvider::Ptr> loaded_plugins; loader.load<cslibs_plugins_data::DataProvider, decltype(tf_), decltype(nh)&>(loaded_plugins, tf_, nh); EXPECT_EQ(12ul, loaded_plugins.size()); } int main(int argc, char *argv[]) { ros::init(argc, argv, "test_load_plugins"); testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
42.784722
104
0.720338
[ "vector" ]
b925013e4b50504077cc921a5d6531d13bf0531b
7,338
cpp
C++
tests/particle_system/ParticleSystem.cpp
kan-xyz/Arc
da2272dabd6997ab4cc632fcebb68db4c40cc6ea
[ "Zlib" ]
4
2021-10-10T16:03:54.000Z
2022-02-09T02:09:45.000Z
tests/particle_system/ParticleSystem.cpp
kan-xyz/Arc
da2272dabd6997ab4cc632fcebb68db4c40cc6ea
[ "Zlib" ]
null
null
null
tests/particle_system/ParticleSystem.cpp
kan-xyz/Arc
da2272dabd6997ab4cc632fcebb68db4c40cc6ea
[ "Zlib" ]
null
null
null
#include "ParticleSystem.h" #include <Arc/QuadUtils.hpp> #include <SFML/Window/Event.hpp> #include <SFML/Graphics/RenderWindow.hpp> #include <SFML/System/Clock.hpp> #include <SFML/System/Vector2.hpp> #include <SFML/System/Time.hpp> #include <vector> #include <random> namespace Demo { // this defines the basic data // for a basic particle struct Particle { sf::Vector2f velocity, acceleration; float rotationSpeed = 0.0f, rotationAcceleration = 0.0f; sf::Time lifespan = sf::Time::Zero; bool isActive = false; }; // the details of the mechanics are laid out in comments class ParticleSystem { public: ParticleSystem() = default; // this is where we give the max number of particles void resize(const std::size_t size) { m_vertices.resize(4 * size); // this needs to have that 4 because quads have 4 vertices m_particleData.resize(size); } void emit(const sf::RenderWindow& window, std::mt19937& rng) { if (m_particleData[m_index].isActive == false) { std::uniform_real_distribution<float> randVelocity(100.0f, 300.0f); std::uniform_real_distribution<float> randAcceleration(200.0f, 600.0f); std::uniform_real_distribution<float> randAngle(0.0f, 360.0f); std::uniform_real_distribution<float> randRotationSpeed(-60.0f, 60.0f); std::uniform_real_distribution<float> randRotationAcceleration(-60.0f, 60.0f); std::uniform_real_distribution<float> randLifespan(3.0f, 6.0f); std::uniform_int_distribution<int> randColor(0, 255); // this is int because C++ does not have a specialization // for std::uniform_int_distribution<sf::Uint8> // basic properties of the particles float rotation = randAngle(rng); float omega = randRotationSpeed(rng); float alpha = randRotationAcceleration(rng); float speed = randVelocity(rng); sf::Color color = { static_cast<sf::Uint8>(randColor(rng)), static_cast<sf::Uint8>(randColor(rng)), static_cast<sf::Uint8>(randColor(rng)), 255 }; // below here is where we can see the basic usage of Arc's vertexArray utils. // the first parameter is the vertex array and the second is the quad index // note that Arc also has a shortcut function for this in the form of: // // Arc::MakeQuad(vertexArray, index, position, size, rotation, color, textureRect); // // there are also other functions such as: // // Arc::SetTextureRect(...); // Arc::SetSize(...); // Arc::SetPosition(...); // // among others // Arc::MakeQuad(m_vertices, m_index, sf::Vector2f(sf::Mouse::getPosition(window)), { 32.0f, 32.0f }); Arc::RotateQuad(m_vertices, m_index, rotation); Arc::SetQuadColor(m_vertices, m_index, color); float theta1 = randAngle(rng); float theta2 = randAngle(rng); // other particle data m_particleData[m_index].velocity = randVelocity(rng) * sf::Vector2f(std::cos(theta1), std::sin(theta1)); m_particleData[m_index].acceleration = randAcceleration(rng) * sf::Vector2f(std::cos(theta2), std::sin(theta2)); m_particleData[m_index].rotationSpeed = randRotationSpeed(rng); m_particleData[m_index].rotationAcceleration = randRotationAcceleration(rng); m_particleData[m_index].lifespan = sf::seconds(randLifespan(rng)); m_particleData[m_index].isActive = true; m_index = ++m_index % m_particleData.size(); } } void update(const sf::Time& timestep) { const float dt = timestep.asSeconds(); for (std::size_t i = 0; i < m_particleData.size(); ++i) { if (m_particleData[i].isActive == false) { continue; } m_particleData[i].lifespan -= timestep; if (m_particleData[i].lifespan < sf::Time::Zero) { // make the quad invisible Arc::SetQuadColor(m_vertices, i, sf::Color::Transparent); m_particleData[i].isActive = false; continue; } m_particleData[i].velocity += dt * m_particleData[i].acceleration; m_particleData[i].rotationSpeed += dt * m_particleData[i].rotationAcceleration; // here are some basic quad operations // other operations include // // Arc::TransformQuad(...); // Arc::SetQuadAngle(...) // // you can explore the arc header file // to find out what els Arc can do Arc::MoveQuad(m_vertices, i, dt * m_particleData[i].velocity); Arc::RotateQuad(m_vertices, i, dt * m_particleData[i].rotationSpeed); } } void draw(sf::RenderWindow& window) { window.draw(m_vertices.data(), m_vertices.size(), sf::Quads); } private: std::vector<sf::Vertex> m_vertices; // this is where we store the vertices for the particles. // in order to get the full benefit of batch rendering we need // to place everything in one vertex array std::vector<Particle> m_particleData; std::size_t m_index = 0; }; void ParticleSystemDemo() { printf("\nThis is the Arc Particle System Demo\nJust press the left mouse button to generate some particles\n"); sf::RenderWindow window({ 800, 600 }, "Particle System"); window.setFramerateLimit(60); std::mt19937 rng(std::random_device{}()); ParticleSystem particleSystem; particleSystem.resize(1000); sf::Clock cl; while (window.isOpen()) { sf::Event e; while (window.pollEvent(e)) { if (e.type == sf::Event::Closed) { window.close(); } } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Escape)) { window.close(); } if (sf::Mouse::isButtonPressed(sf::Mouse::Left)) { particleSystem.emit(window, rng); } particleSystem.update(cl.restart()); window.clear(); particleSystem.draw(window); window.display(); } } }
39.240642
129
0.52085
[ "vector" ]
b92a09d4af469c1c2eda4be9ef2c41e47cc322a9
47,025
cpp
C++
src/engines/ioda/src/ioda/Engines/HH/HH-variables.cpp
NOAA-EMC/ioda
366ce1aa4572dde7f3f15862a2970f3dd3c82369
[ "Apache-2.0" ]
null
null
null
src/engines/ioda/src/ioda/Engines/HH/HH-variables.cpp
NOAA-EMC/ioda
366ce1aa4572dde7f3f15862a2970f3dd3c82369
[ "Apache-2.0" ]
null
null
null
src/engines/ioda/src/ioda/Engines/HH/HH-variables.cpp
NOAA-EMC/ioda
366ce1aa4572dde7f3f15862a2970f3dd3c82369
[ "Apache-2.0" ]
null
null
null
/* * (C) Copyright 2017-2020 Ryan Honeyager (ryan@honeyager.info) * (C) Copyright 2020-2021 UCAR * * This software is licensed under the terms of the Apache Licence Version 2.0 * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. */ /*! \addtogroup ioda_internals_engines_hh * * @{ * \file HH-variables.cpp * \brief HDF5 engine implementation of Variable. */ #include "./HH/HH-variables.h" #include <hdf5_hl.h> #include <algorithm> #include <exception> #include <numeric> #include <set> #include "./HH/HH-Filters.h" #include "./HH/HH-attributes.h" #include "./HH/HH-hasattributes.h" #include "./HH/HH-hasvariables.h" #include "./HH/HH-types.h" #include "./HH/HH-util.h" #include "./HH/Handles.h" #include "ioda/Exception.h" #include "ioda/Misc/DimensionScales.h" #include "ioda/Misc/Dimensions.h" #include "ioda/Misc/StringFuncs.h" namespace ioda { namespace detail { namespace Engines { namespace HH { template <class T> std::vector<T> convertToH5Length(const std::vector<Dimensions_t>& in) { std::vector<T> res(in.size()); for (size_t i = 0; i < in.size(); ++i) res[i] = gsl::narrow<T>(in[i]); return res; } HH_Variable::HH_Variable() = default; HH_Variable::~HH_Variable() = default; HH_Variable::HH_Variable(HH_hid_t d, std::shared_ptr<const HH_HasVariables> container) : var_(d), container_(container) { atts = Has_Attributes(std::make_shared<HH_HasAttributes>(d)); // auto has_atts_backend = Variable_Backend::_getHasAttributesBackend(backend_->atts); // auto hh_atts_backend = std::dynamic_pointer_cast<HH_HasAttributes>(has_atts_backend); // atts = Has_Attributes(hh_atts_backend); // atts = Has_Attributes(std::make_shared<HH_HasAttributes>(backend_->atts)); } HH_hid_t HH_Variable::get() const { return var_; } bool HH_Variable::isVariable() const { H5I_type_t typ = H5Iget_type(var_()); if (typ == H5I_BADID) throw Exception("Cannot determine object type", ioda_Here()); return (typ == H5I_DATASET); } detail::Type_Provider* HH_Variable::getTypeProvider() const { return HH_Type_Provider::instance(); } HH_hid_t HH_Variable::internalType() const { return HH_hid_t(H5Dget_type(var_()), Handles::Closers::CloseHDF5Datatype::CloseP); } Type HH_Variable::getType() const { return Type{std::make_shared<HH_Type>(internalType()), typeid(HH_Type)}; } HH_hid_t HH_Variable::space() const { return HH_hid_t(H5Dget_space(var_()), Handles::Closers::CloseHDF5Dataspace::CloseP); } Dimensions HH_Variable::getDimensions() const { Dimensions ret; Options errOpts; // Used for tracking parameters that can show up in the error message. errOpts.add("variable", getNameFromIdentifier(var_())); std::vector<hsize_t> dims, dimsmax; htri_t isSimple = H5Sis_simple(space()()); if (isSimple < 0) throw Exception("Dimension space parameter is invalid.", ioda_Here(), errOpts); if (isSimple == 0) throw Exception("Dataspace is not simple. Unsupported case in code. " "Complex dataspace support was not available in HDF5 when this function was written.", ioda_Here(), errOpts); hssize_t numPoints = H5Sget_simple_extent_npoints(space()()); errOpts.add("numPoints", numPoints); if (numPoints < 0) throw Exception("H5Sget_simple_extent_npoints error.", ioda_Here(), errOpts); int dimensionality = H5Sget_simple_extent_ndims(space()()); errOpts.add("dimensionality", dimensionality); if (dimensionality < 0) throw Exception("H5Sget_simple_extent_ndims error.", ioda_Here(), errOpts); dims.resize(dimensionality); dimsmax.resize(dimensionality); if (H5Sget_simple_extent_dims(space()(), dims.data(), dimsmax.data()) < 0) throw Exception("H5Sget_simple_extent_dims error.", ioda_Here(), errOpts); ret.numElements = gsl::narrow<decltype(Dimensions::numElements)>(numPoints); ret.dimensionality = gsl::narrow<decltype(Dimensions::dimensionality)>(dimensionality); for (const auto& d : dims) ret.dimsCur.push_back(gsl::narrow<Dimensions_t>(d)); for (const auto& d : dimsmax) ret.dimsMax.push_back((d == H5S_UNLIMITED) ? ioda::Unlimited : gsl::narrow<Dimensions_t>(d)); return ret; } Variable HH_Variable::resize(const std::vector<Dimensions_t>& newDims) { std::vector<hsize_t> hdims = convertToH5Length<hsize_t>(newDims); if (H5Dset_extent(var_(), hdims.data()) < 0) throw Exception("Failure to resize a Variable with the HDF5 backend.", ioda_Here()) .add("variable", getNameFromIdentifier(var_())) .add("dimensionality", hdims.size()); return Variable{shared_from_this()}; } Variable HH_Variable::attachDimensionScale(unsigned int DimensionNumber, const Variable& scale) { Options errOpts; errOpts.add("variable", getNameFromIdentifier(var_())); errOpts.add("DimensionNumber", DimensionNumber); try { // We are extracting the backend object. auto scaleBackendBase = scale.get(); // If the backend object is an HH object, then we can attach this scale. // Otherwise, throw an error because you can't mix Variables from different // backends. auto scaleBackendDerived = std::dynamic_pointer_cast<HH_Variable>(scaleBackendBase); errOpts.add("scale", getNameFromIdentifier(scaleBackendDerived->var_())); const herr_t res = H5DSattach_scale(var_(), scaleBackendDerived->var_(), DimensionNumber); if (res != 0) throw Exception("Dimension scale attachment failed.", ioda_Here(), errOpts); return Variable{shared_from_this()}; } catch (std::bad_cast) { throw Exception("Cannot attach dimension scales across incompatible backends.", ioda_Here(), errOpts); } } Variable HH_Variable::detachDimensionScale(unsigned int DimensionNumber, const Variable& scale) { Options errOpts; errOpts.add("variable", getNameFromIdentifier(var_())); errOpts.add("DimensionNumber", DimensionNumber); try { // We are extracting the backend object. auto scaleBackendBase = scale.get(); // If the backend object is an HH object, then we can attach this scale. // Otherwise, throw an error because you can't mix Variables from different // backends. auto scaleBackendDerived = std::dynamic_pointer_cast<HH_Variable>(scaleBackendBase); errOpts.add("scale", getNameFromIdentifier(scaleBackendDerived->var_())); const herr_t res = H5DSdetach_scale(var_(), scaleBackendDerived->var_(), DimensionNumber); if (res != 0) throw Exception("Dimension scale detachment failed", ioda_Here(), errOpts); return Variable{shared_from_this()}; } catch (std::bad_cast) { throw Exception("Cannot detach dimension scales across incompatible backends.", ioda_Here(), errOpts); } } bool HH_Variable::isDimensionScale() const { const htri_t res = H5DSis_scale(var_()); if (res < 0) { Options errOpts; try { errOpts.add("variable", getNameFromIdentifier(var_())); } catch (...) { errOpts.add("variable", "unknown / bad id"); } throw Exception("Error returned from H5DSis_scale.", ioda_Here(), errOpts); } return (res > 0); } Variable HH_Variable::setIsDimensionScale(const std::string& dimensionScaleName) { const htri_t res = H5DSset_scale(var_(), dimensionScaleName.c_str()); if (res != 0) { Options errOpts; errOpts.add("dimensionScaleName", dimensionScaleName); try { errOpts.add("variable", getNameFromIdentifier(var_())); } catch (...) { errOpts.add("variable", "unknown / bad id"); } throw Exception( "Error returned from H5DSset_scale.", ioda_Here(), errOpts); } return Variable{shared_from_this()}; } Variable HH_Variable::getDimensionScaleName(std::string& res) const { constexpr size_t max_label_size = 1000; std::array<char, max_label_size> label{}; // Value-initialized to nulls. const ssize_t sz = H5DSget_scale_name(var_(), label.data(), max_label_size); if (sz < 0) { Options errOpts; try { errOpts.add("variable", getNameFromIdentifier(var_())); } catch (...) { errOpts.add("variable", "unknown / bad id"); } throw Exception("Error returned from H5DSget_scale_name.", ioda_Here(), errOpts); } // sz is the size of the label. The HDF5 documentation does not include whether the label is // null-terminated, so I am terminating it manually. label[max_label_size - 1] = '\0'; res = std::string(label.data()); return Variable{std::make_shared<HH_Variable>(*this)}; } /** \details This function is byzantine, it is performance-critical, and it cannot be split apart. * * It serves as the common calling point for both the regular getDimensionScaleMappings function and * isDimensionScaleAttached. They share a lot of complex code. * * The code is detailed because we are working around deficiencies in HDF5's dimension scales API. * The key problem is that dimension scale mappings are bi-directional, and H5DSis_attached * repeatedly re-opens the **scale's** list of variables that it acts as a dimension for. * It then has to de-reference and re-open each variable when verifying attachment, and this * performs horribly when you have hundreds or thousands of variables. * * So, the logic here simplifies H5DSis_attached to verify only a uni-directional mapping * so see if a Variable is attached to a scale (and not the other way around). * * Also note: different HDF5 versions use slightly different structs and function calls, * hence the #ifdefs. **/ std::vector<std::vector<Named_Variable>> HH_Variable::getDimensionScaleMappings( const std::vector<Named_Variable>& scalesToQueryAgainst, bool firstOnly, const std::vector<unsigned>& dimensionNumbers_) const { try { // Extract all of the scalesToQueryAgainst and convert them into the appropriate backend // objects. If the backend objects are not from this engine, then this is an error (no mixing // Variables and scales across different backends). std::vector<std::pair<std::string, std::shared_ptr<HH_Variable>>> scales; for (const auto& scale : scalesToQueryAgainst) { auto scaleBackendBase = scale.var.get(); auto scaleBackendDerived = std::dynamic_pointer_cast<HH_Variable>(scaleBackendBase); scales.push_back( {scale.name, scaleBackendDerived}); // NOLINT: macos oddly is missing emplace_back here. } // The logic here roughly follows H5DSis_attached, but with extra optimizations and added // loops to avoid variable repeated variable {open and close} operations. // Check that the dimensionality is sufficient to have a // DimensionNumber element. auto datadims = getDimensions(); std::vector<unsigned> dimensionNumbers = dimensionNumbers_; if (!dimensionNumbers.empty()) { auto max_elem_it = std::max_element(dimensionNumbers.cbegin(), dimensionNumbers.cend()); if (max_elem_it == dimensionNumbers.cend()) throw Exception(ioda_Here()); if (datadims.dimensionality <= *max_elem_it) throw Exception(ioda_Here()); } else { dimensionNumbers.resize(datadims.dimensionality); std::iota(dimensionNumbers.begin(), dimensionNumbers.end(), 0); } // The return value. Give it the correct size (the dimensionality of the variable). std::vector<std::vector<Named_Variable>> ret( gsl::narrow<size_t>(datadims.dimensionality)); // Iterate over all attributes to get the DIMENSION_LIST attribute. Then, // attempt to read the reference list inside the DIMENSION_LIST attribute and link // dimension references to dimension scales. // NOTE: This code does not use the regular atts.open("DIMENSION_LIST") call // for performance reasons on large IASI-like files where we have to repeat this // call for tens of thousands of variables. We instead do a creation-order-preferred // search. // Get search order H5_index_t iteration_type = getAttrCreationOrder(get()(), H5O_TYPE_DATASET); // H5Aiterate2 exists in v1.8 and up. hsize_t pos = 0; Iterator_find_attr_data_t search_data_opts; search_data_opts.search_for = "DIMENSION_LIST"; herr_t att_search_ret = H5Aiterate2(get()(), // Search on this dataset iteration_type, // Iterate by name or creation order H5_ITER_NATIVE, // Fastest ordering possible &pos, // Initial (and current) index iterate_find_attr, // C-style search function reinterpret_cast<void*>(&search_data_opts) // Data passed to/from the C-style search function ); if (att_search_ret < 0) throw Exception(ioda_Here()); if (!search_data_opts.success) return ret; // Fallthrough returning a vector of empty vectors. hid_t found_att = H5Aopen_by_idx(get()(), ".", iteration_type, H5_ITER_NATIVE, search_data_opts.idx, H5P_DEFAULT, H5P_DEFAULT); HH_Attribute aDims_HH( HH_hid_t(std::move(found_att), Handles::Closers::CloseHDF5Attribute::CloseP)); // Attempt to read the reference list for our variable's // DIMENSION_LIST attribute. //if (!atts.exists("DIMENSION_LIST")) // return ret; // Fallthrough returning a vector of empty vectors. //Attribute aDims = atts.open("DIMENSION_LIST"); //auto aDims_backend = _getAttributeBackend<ioda::detail::Attribute_Base<Attribute>>(aDims); //auto aDims_HH = std::dynamic_pointer_cast<HH_Attribute>(aDims_backend); auto vltyp = aDims_HH.internalType(); auto vldims = aDims_HH.getDimensions(); Vlen_data buf((size_t)datadims.dimensionality, vltyp, aDims_HH.space()); if (H5Aread(aDims_HH.get()(), vltyp.get(), reinterpret_cast<void*>(buf.buf.get())) < 0) throw Exception("Attribute read failure", ioda_Here()); // We now have the list of object references. // We need to query the scale information. // Get the information for all of the scales. #if H5_VERSION_GE(1, 12, 0) std::vector<H5O_info1_t> scale_infos(scales.size()); H5O_info1_t check_info; #else std::vector<H5O_info_t> scale_infos(scales.size()); H5O_info_t check_info; #endif for (size_t i = 0; i < scales.size(); ++i) { #if H5_VERSION_GE(1, 10, 3) if (H5Oget_info2(scales[i].second->get()(), &scale_infos[i], H5O_INFO_BASIC) < 0) throw Exception("H5Oget_info2 failure", ioda_Here()); #else if (H5Oget_info(scales[i].second->get()(), &scale_infos[i], H5O_INFO_BASIC) < 0) throw Exception("H5Oget_info failure", ioda_Here()); #endif } // Iterate over each dimension (in the set), and iterate along each scale. // See which scales are attached to which dimensions. // For each dimension. The remaining dimensions in the returned vector (i.e. entries not in // dimensionNumbers) are unfilled in the output. for (const auto& curDim : dimensionNumbers) { // For each *scale reference* listed in the variable along a particular dimension // Note well: this is NOT *each scale that the user passed*. for (size_t i = 0; i < buf.buf[curDim].len; ++i) { hobj_ref_t ref = ((hobj_ref_t*)buf.buf[curDim].p)[i]; // NOLINT: type conversions // Dereference the scale variable stored in DIMENSION_LIST. // This opens it. hid_t deref_scale_id = H5Rdereference2( // First parameter is any object id in the same file get()(), H5P_DEFAULT, H5R_OBJECT, &ref); Expects(deref_scale_id >= 0); // Die on failure. Would have to clean up memory otherwise. HH_hid_t encap_id(deref_scale_id, Handles::Closers::CloseHDF5Dataset::CloseP); HH_Variable deref_scale(encap_id, nullptr); // Move into managed memory // Get deref_scale's info and compare to scale_info. #if H5_VERSION_GE(1, 10, 3) if (H5Oget_info2(deref_scale.get()(), &check_info, H5O_INFO_BASIC) < 0) throw Exception("H5Oget_info2 failure", ioda_Here()); #else if (H5Oget_info(deref_scale.get()(), &check_info, H5O_INFO_BASIC) < 0) throw Exception("H5Oget_info failure", ioda_Here()); #endif // Iterate over each scalesToQueryAgainst // I.e. for each *scale that the user passed*. bool foundScale = false; for (size_t j = 0; j < scale_infos.size(); ++j) { if ((scale_infos[j].fileno == check_info.fileno) && (scale_infos[j].addr == check_info.addr)) { // Success! We matched a scale! ret[curDim].push_back(scalesToQueryAgainst[j]); foundScale = true; break; // No need to check this *scale reference* against the remaining known scales. } } // If we are asking for only the first matched scale in each dimension, // and if we just found the first match, then continue on to the next dimension. if (firstOnly && foundScale) break; } } return ret; } catch (...) { Options errOpts; try { errOpts.add("variable", getNameFromIdentifier(var_())); } catch (...) { errOpts.add("variable", "unknown / bad id"); } std::throw_with_nested(Exception("Caught an exception.", ioda_Here(), errOpts)); } } bool HH_Variable::isDimensionScaleAttached(unsigned int DimensionNumber, const Variable& scale) const { try { const std::vector<Named_Variable> scalesToQueryAgainst{{"unused_param", scale}}; auto res = getDimensionScaleMappings(scalesToQueryAgainst, true, {DimensionNumber}); return !res[DimensionNumber].empty(); } catch (...) { Options errOpts; try { errOpts.add("variable", getNameFromIdentifier(var_())); } catch (...) { errOpts.add("variable", "unknown / bad id"); } std::throw_with_nested(Exception("Caught an exception.", ioda_Here(), errOpts)); } } std::vector<std::vector<Named_Variable>> HH_Variable::getDimensionScaleMappings( const std::list<Named_Variable>& scalesToQueryAgainst, bool firstOnly) const { return getDimensionScaleMappings({scalesToQueryAgainst.begin(), scalesToQueryAgainst.end()}, firstOnly, {}); } Selections::SelectionBackend_t HH_Variable::instantiateSelection(const Selection& sel) const { auto res = std::make_shared<HH_Selection>(); res->sel = getSpaceWithSelection(sel); return res; } HH_hid_t HH_Variable::getSpaceWithSelection(const Selection& sel) const { if (sel.isConcretized()) { auto concretized = sel.concretize(); try { // Only return the concretized selection if this is the correct backend. auto csel = std::dynamic_pointer_cast<HH_Selection>(concretized); return csel->sel; } catch (std::bad_cast) { sel.invalidate(); } } if (sel.getDefault() == SelectionState::ALL) if (sel.getActions().empty()) return HH_hid_t(H5S_ALL); HH_hid_t spc(H5Scopy(space()()), Handles::Closers::CloseHDF5Dataspace::CloseP); if (spc() < 0) throw Exception("Cannot copy dataspace.", ioda_Here()); if (!sel.extent().empty()) { if (H5Sset_extent_simple(spc(), gsl::narrow<int>(sel.extent().size()), convertToH5Length<hsize_t>(sel.extent()).data(), convertToH5Length<hsize_t>(sel.extent()).data()) < 0) throw Exception("Cannot set dataspace extent.", ioda_Here()); } if (sel.getDefault() == SelectionState::ALL) { if (H5Sselect_all(spc()) < 0) throw Exception("Dataspace selection failed.", ioda_Here()); } else if (sel.getDefault() == SelectionState::NONE) { if (H5Sselect_none(spc()) < 0) throw Exception("Dataspace selection failed.", ioda_Here()); } static const std::map<SelectionOperator, H5S_seloper_t> op_map = {{SelectionOperator::SET, H5S_SELECT_SET}, {SelectionOperator::OR, H5S_SELECT_OR}, {SelectionOperator::AND, H5S_SELECT_AND}, {SelectionOperator::XOR, H5S_SELECT_XOR}, {SelectionOperator::NOT_B, H5S_SELECT_NOTB}, {SelectionOperator::NOT_A, H5S_SELECT_NOTA}, {SelectionOperator::APPEND, H5S_SELECT_APPEND}, {SelectionOperator::PREPEND, H5S_SELECT_PREPEND}}; bool first_action = true; for (const auto& s : sel.getActions()) { if (!op_map.count(s.op_)) throw Exception("Unimplemented map value.", ioda_Here()); herr_t chk = 0; // Is this a hyperslab or a single point selection? if (!s.points_.empty()) { // Single point selection size_t dimensionality = s.points_.at(0).size(); std::vector<hsize_t> elems(dimensionality * s.points_.size()); // Waiting for std::ranges in C++20 for (size_t i = 0; i < s.points_.size(); ++i) // const auto& p : s.points_) { if (s.points_[i].size() != dimensionality) throw Exception("Points have inconsistent dimensionalities.", ioda_Here()) .add("dimensionality", dimensionality) .add("s.points_[i].size()", s.points_[i].size()) .add("i", i); for (size_t j = 0; j < dimensionality; ++j) elems[j + (dimensionality * i)] = s.points_[i][j]; // std::copy_n(p.data(), dimensionality, elems.data() + (i * dimensionality)); } chk = H5Sselect_elements(spc(), op_map.at(s.op_), s.points_.size(), elems.data()); } else if (!s.dimension_indices_starts_.empty()) { // This is a variant of the hyperslab selection code. // We have index ranges, and we then convert to the usual // start and count. // SelectionOperator is a problem here, because the selections // that we are making are not commutative. So, we do a two-part selection. // First, clone the dataspace and select everything. // Then, apply this bulk selection to the actual space. #if H5_VERSION_GE(1, 12, 0) HH_hid_t cloned_space(H5Scopy(spc()), Handles::Closers::CloseHDF5Dataspace::CloseP); if(H5Sselect_none(cloned_space()) < 0) throw Exception("Cannot copy space", ioda_Here()); ioda::Dimensions dims = getDimensions(); Expects(s.dimension_ < (size_t)dims.dimensionality); const size_t numSlabs = s.dimension_indices_starts_.size(); for (size_t i = 0; i < numSlabs; ++i) { // Fill with zeros, and set the right starting dimension std::vector<hsize_t> hstart; if (sel.extent().empty()) { hstart.resize((size_t)dims.dimensionality, 0); } else { hstart.resize((size_t)sel.extent().size(), 0); } hstart[s.dimension_] = s.dimension_indices_starts_[i]; // Fill with the total size, and then set the right extent std::vector<hsize_t> hcount; if (sel.extent().empty()) { hcount = convertToH5Length<hsize_t>(dims.dimsCur); } else { hcount = convertToH5Length<hsize_t>(sel.extent()); } hcount[s.dimension_] = (i < s.dimension_indices_counts_.size()) ? s.dimension_indices_counts_[i] : 1; if (H5Sselect_hyperslab(cloned_space(), op_map.at(SelectionOperator::OR), hstart.data(), NULL, hcount.data(), NULL) < 0) throw Exception("Sub-space selection failed.", ioda_Here()); } // Once we have looped through then we apply the actual selection operator to our // compound data. If on the first action, space will be either an ALL or NONE // selection type, which will cause the H5Smodify_select to fail. H5Smodify_select // wants both spaces to be HYPERSLAB spaces. So, on the first action, do a select copy // instead of a select modify. if (first_action) { if (H5Sselect_copy(spc(), cloned_space()) < 0) throw Exception("Space copy selection failed", ioda_Here()); } else { if (H5Smodify_select(spc(), op_map.at(s.op_), cloned_space()) < 0) throw Exception("Space modify selection failed", ioda_Here()); } #else throw Exception( "The HDF5 engine needs to be backed by at least " "HDF5 1.12.0 to do the requested selection properly. Older HDF5 versions " "do not have the H5Smodify_select function.", ioda_Here()); #endif } else { // Hyperslab selection const auto hstart = convertToH5Length<hsize_t>(s.start_); const auto hstride = convertToH5Length<hsize_t>(s.stride_); const auto hcount = convertToH5Length<hsize_t>(s.count_); const auto hblock = convertToH5Length<hsize_t>(s.block_); chk = H5Sselect_hyperslab(spc(), op_map.at(s.op_), hstart.data(), (s.stride_.size()) ? hstride.data() : NULL, hcount.data(), (s.block_.size()) ? hblock.data() : NULL); } if (chk < 0) throw Exception("Space selection failed.", ioda_Here()); first_action = false; // NOLINT: Compilers inconsistently complain about use/unuse of // first_action. Not our bug. } if (!sel.getOffset().empty()) { if (H5Soffset_simple(spc(), convertToH5Length<hssize_t>(sel.getOffset()).data()) < 0) throw Exception("Problem applying offset to space.", ioda_Here()); } auto res = std::make_shared<HH_Selection>(); res->sel = spc; sel.concretize(res); return spc; } Variable HH_Variable::write(gsl::span<const char> data, const Type& in_memory_dataType, const Selection& mem_selection, const Selection& file_selection) { auto memTypeBackend = std::dynamic_pointer_cast<HH_Type>(in_memory_dataType.getBackend()); auto memSpace = getSpaceWithSelection(mem_selection); auto fileSpace = getSpaceWithSelection(file_selection); H5T_class_t memTypeClass = H5Tget_class(memTypeBackend->handle()); HH_hid_t varType(H5Dget_type(var_()), Handles::Closers::CloseHDF5Datatype::CloseP); H5T_class_t varTypeClass = H5Tget_class(varType()); if ((memTypeClass == H5T_STRING) && (varTypeClass == H5T_STRING)) { // Both memory and file types are strings. Need to check fixed vs variable length. // Variable-length strings (default) are packed as an array of pointers. // Fixed-length strings are just a sequence of characters. htri_t isMemStrVar = H5Tis_variable_str(memTypeBackend->handle()); htri_t isVarStrVar = H5Tis_variable_str(varType()); if (isMemStrVar < 0) throw Exception("H5Tis_variable_str failed on memory data type.", ioda_Here()); if (isVarStrVar < 0) throw Exception("H5Tis_variable_str failed on backend (file) variable data type.", ioda_Here()); if ((isMemStrVar && isVarStrVar) || (!isMemStrVar && !isVarStrVar)) { // No need to change anything. Pass through. // NOTE: Using varType instead of memTypeBackend->handle! This is because strings can have // different character sets (ASCII vs UTF-8), which is entirely unhandled in IODA. if (H5Dwrite(var_(), varType(), memSpace(), fileSpace(), H5P_DEFAULT, data.data()) < 0) throw Exception("H5Dwrite failed.", ioda_Here()); } else if (isMemStrVar) { // Variable-length in memory. Fixed-length in var. size_t strLen = H5Tget_size(varType()); size_t numStrs = getDimensions().numElements; std::vector<char> out_buf = convertVariableLengthToFixedLength(data, strLen, false); if (H5Dwrite(var_(), varType(), memSpace(), fileSpace(), H5P_DEFAULT, out_buf.data()) < 0) throw Exception("H5Dwrite failed.", ioda_Here()); } else if (isVarStrVar) { // Fixed-length in memory. Variable-length in file. // Rare conversion. Included for completeness. size_t strLen = H5Tget_size(memTypeBackend->handle()); size_t numStrs = getDimensions().numElements; size_t totalStrLen = strLen * numStrs; auto converted_data_holder = convertFixedLengthToVariableLength(data, strLen); char* converted_data = reinterpret_cast<char*>(converted_data_holder.DataPointers.data()); if (H5Dwrite(var_(), varType(), memSpace(), fileSpace(), H5P_DEFAULT, converted_data) < 0) throw Exception("H5Dwrite failed.", ioda_Here()); } } else { // Pass-through case auto ret = H5Dwrite(var_(), // dataset id memTypeBackend->handle(), // mem_type_id memSpace(), // mem_space_id fileSpace(), // file_space_id H5P_DEFAULT, // xfer_plist_id data.data() // data ); if (ret < 0) throw Exception("H5Dwrite failure.", ioda_Here()); } return Variable{shared_from_this()}; } Variable HH_Variable::read(gsl::span<char> data, const Type& in_memory_dataType, const Selection& mem_selection, const Selection& file_selection) const { auto memTypeBackend = std::dynamic_pointer_cast<HH_Type>(in_memory_dataType.getBackend()); auto memSpace = getSpaceWithSelection(mem_selection); auto fileSpace = getSpaceWithSelection(file_selection); H5T_class_t memTypeClass = H5Tget_class(memTypeBackend->handle()); HH_hid_t varType(H5Dget_type(var_()), Handles::Closers::CloseHDF5Datatype::CloseP); H5T_class_t varTypeClass = H5Tget_class(varType()); if ((memTypeClass == H5T_STRING) && (varTypeClass == H5T_STRING)) { // Both memory and file types are strings. Need to check fixed vs variable length. // Variable-length strings (default) are packed as an array of pointers. // Fixed-length strings are just a sequence of characters. htri_t isMemStrVar = H5Tis_variable_str(memTypeBackend->handle()); htri_t isVarStrVar = H5Tis_variable_str(varType()); if (isMemStrVar < 0) throw Exception("H5Tis_variable_str failed on memory data type.", ioda_Here()); if (isVarStrVar < 0) throw Exception("H5Tis_variable_str failed on backend (file) variable data type.", ioda_Here()); if ((isMemStrVar && isVarStrVar) || (!isMemStrVar && !isVarStrVar)) { // No need to change anything. Pass through. // NOTE: Using varType instead of memTypeBackend->handle! This is because strings can have // different character sets (ASCII vs UTF-8), which is entirely unhandled in IODA. if (H5Dread(var_(), varType(), memSpace(), fileSpace(), H5P_DEFAULT, data.data()) < 0) throw Exception("H5Dread failed.", ioda_Here()); } else if (isMemStrVar) { // Variable-length in memory. Fixed-length in file. size_t strLen = H5Tget_size(varType()); size_t numStrs = getDimensions().numElements; std::vector<char> in_buf(numStrs * strLen); if (H5Dread(var_(), varType(), memSpace(), fileSpace(), H5P_DEFAULT, in_buf.data()) < 0) throw Exception("H5Dread failed.", ioda_Here()); // This block of code is a bit of a kludge in that we are switching from a packed // structure of strings to a packed structure of pointers of strings. // The Marshaller code in ioda/Types/Marshalling.h expects this format. // In the future, the string read interface in the frontend should use the Marshalling // interface to pass these objects back and forth without excessive data element copies. char** reint_buf = reinterpret_cast<char**>(data.data()); // NOLINT: casting for (size_t i = 0; i < numStrs; ++i) { // The malloced strings will be released in Marshalling.h. reint_buf[i] = (char*)malloc(strLen + 1); // NOLINT: quite a deliberate call to malloc here. memset(reint_buf[i], 0, strLen+1); memcpy(reint_buf[i], in_buf.data() + (strLen * i), strLen); } } else if (isVarStrVar) { // Fixed-length in memory. Variable-length in file. // Rare conversion. Included for completeness. size_t strLen = H5Tget_size(memTypeBackend->handle()); size_t numStrs = getDimensions().numElements; // !!! size_t totalStrLen = strLen * numStrs; std::vector<char> in_buf(numStrs * sizeof(char*)); if (H5Dread(var_(), varType(), memSpace(), fileSpace(), H5P_DEFAULT, in_buf.data()) < 0) throw Exception("H5Dread failed.", ioda_Here()); // We could avoid using the temporary out_buf and write // directly to "data", but there is no strong need to do this, as // this is a very rare type conversion. C++ lacks a fixed-length string type! std::vector<char> out_buf = convertVariableLengthToFixedLength(in_buf, strLen, false); if (out_buf.size() != data.size()) throw Exception("Unexpected sizes.", ioda_Here()) .add("data.size()", data.size()).add("out_buf.size()", out_buf.size()); std::copy(out_buf.begin(), out_buf.end(), data.begin()); } } else { // Pass-through case auto ret = H5Dread( var_(), // dataset id memTypeBackend->handle(), // mem_type_id memSpace(), // mem_space_id fileSpace(), // file_space_id H5P_DEFAULT, // xfer_plist_id data.data() // data ); if (ret < 0) throw Exception("H5Dread failure.", ioda_Here()); } return Variable{std::make_shared<HH_Variable>(*this)}; } bool HH_Variable::isA(Type lhs) const { auto typeBackend = std::dynamic_pointer_cast<HH_Type>(lhs.getBackend()); // Override for old-format ioda files: // Unfortunately, v0 ioda files have an odd mixture // of ascii vs unicode strings, as well as // fixed and variable-length strings. // We try and fix a few of these issues here. // Do we expect a string of any type? // Is the object a string of any type? // If both are true, then we just return true. H5T_class_t cls_lhs = H5Tget_class(typeBackend->handle.get()); H5T_class_t cls_my = H5Tget_class(internalType()()); if (cls_lhs == H5T_STRING && cls_my == H5T_STRING) return true; // Another issue: are the types equivalent but not // exactly the same? This happens across platforms. Endianness // can change. if (cls_lhs != cls_my) return false; // Now the data are either both integers or floats. // For both, are the size (in bytes) the same? if (H5Tget_size(typeBackend->handle.get()) != H5Tget_size(internalType()())) return false; // For integers, are they both signed or unsigned? if (cls_lhs == H5T_INTEGER) if (H5Tget_sign(typeBackend->handle.get()) != H5Tget_sign(internalType()())) return false; // Ignored: // Are the precisions the same? // Are the offsets the same? // Is the padding the same? // Basically everything in https://support.hdfgroup.org/HDF5/doc/H5.user/Datatypes.html. return true; // return backend_.isOfType(typeBackend->handle); } bool HH_Variable::isExactlyA(HH_hid_t ttype) const { HH_hid_t otype = internalType(); auto ret = H5Tequal(ttype(), otype()); if (ret < 0) throw Exception(ioda_Here()); return (ret > 0) ? true : false; } bool HH_Variable::hasFillValue(HH_hid_t create_plist) { H5D_fill_value_t fvstatus; // NOLINT: HDF5 C interface if (H5Pfill_value_defined(create_plist.get(), &fvstatus) < 0) throw Exception(ioda_Here()); // if H5D_FILL_VALUE_UNDEFINED, return false. In all other cases, return true. return (fvstatus != H5D_FILL_VALUE_UNDEFINED); } bool HH_Variable::hasFillValue() const { HH_hid_t create_plist(H5Dget_create_plist(var_()), Handles::Closers::CloseHDF5PropertyList::CloseP); return hasFillValue(create_plist); } HH_Variable::FillValueData_t HH_Variable::getFillValue(HH_hid_t create_plist) const { try { HH_Variable::FillValueData_t res; H5D_fill_value_t fvstatus; // NOLINT: HDF5 C interface if (H5Pfill_value_defined(create_plist.get(), &fvstatus) < 0) throw Exception(ioda_Here()); // if H5D_FILL_VALUE_UNDEFINED, false. In all other cases, true. res.set_ = (fvstatus != H5D_FILL_VALUE_UNDEFINED); // There are two types of fill values that we encounter. // Those set to fixed values and those set to a "default" value. Unfortunately, // netCDF4-written files set the "default" value but use a default that does // not match HDF5, and this causes major problems with file compatability. // So, we have to override the behavior here to return the fill values expected by // either NetCDF4 or HDF5. // Query the containing HH_Has_Variables to get the policy. auto fvp = container_.lock()->getFillValuePolicy(); if ((fvstatus == H5D_FILL_VALUE_DEFAULT) && (fvp == FillValuePolicy::NETCDF4)) { // H5D_FILL_VALUE_DEFAULT with NETCDF4 fill value policy // // This is ugly but necessary since we can't use template magic at this level in this // direction. Catchall is to assign a zero which is the typical HDF5 default value. if (isA<std::string>()) assignFillValue<std::string>(res, FillValuePolicies::netCDF4_default<std::string>()); else if (isA<signed char>()) assignFillValue<signed char>(res, FillValuePolicies::netCDF4_default<signed char>()); else if (isA<char>()) assignFillValue<char>(res, FillValuePolicies::netCDF4_default<char>()); else if (isA<int16_t>()) assignFillValue<int16_t>(res, FillValuePolicies::netCDF4_default<int16_t>()); else if (isA<int32_t>()) assignFillValue<int32_t>(res, FillValuePolicies::netCDF4_default<int32_t>()); else if (isA<float>()) assignFillValue<float>(res, FillValuePolicies::netCDF4_default<float>()); else if (isA<double>()) assignFillValue<double>(res, FillValuePolicies::netCDF4_default<double>()); else if (isA<unsigned char>()) assignFillValue<unsigned char>(res, FillValuePolicies::netCDF4_default<unsigned char>()); else if (isA<uint16_t>()) assignFillValue<uint16_t>(res, FillValuePolicies::netCDF4_default<uint16_t>()); else if (isA<uint32_t>()) assignFillValue<uint32_t>(res, FillValuePolicies::netCDF4_default<uint32_t>()); else if (isA<int64_t>()) assignFillValue<int64_t>(res, FillValuePolicies::netCDF4_default<int64_t>()); else if (isA<uint64_t>()) assignFillValue<uint64_t>(res, FillValuePolicies::netCDF4_default<uint64_t>()); else assignFillValue<uint64_t>(res, 0); } else { // H5D_FILL_VALUE_DEFAULT with HDF5 fill value policy // H5D_FILL_VALUE_USER_DEFINED regardless of fill value policy auto hType = internalType(); // Get type as if (!hType.isValid()) throw Exception(ioda_Here()); H5T_class_t cls = H5Tget_class(hType()); // NOLINT: HDF5 C interface // Check types for support in this function const std::set<H5T_class_t> supported{H5T_INTEGER, H5T_FLOAT, H5T_STRING}; // Unsupported for now: H5T_BITFIELD, H5T_OPAQUE, H5T_COMPOUND, // H5T_REFERENCE, H5T_ENUM, H5T_VLEN, H5T_ARRAY. if (!supported.count(cls)) throw Exception( "HH's getFillValue function only supports " "basic numeric and string data types. Any other types " "will require enhancement to FillValueData_t::FillValueUnion_t.", ioda_Here()); size_t szType_inBytes = H5Tget_size(hType()); // Basic types and string pointers fit in the union. Fixed-length string // types do not, which is why we create a special buffer to accommodate. std::vector<char> fvbuf(szType_inBytes, 0); if (H5Pget_fill_value(create_plist.get(), hType(), reinterpret_cast<void*>(fvbuf.data())) < 0) throw Exception(ioda_Here()); // When recovering the fill value, we need to distinguish between // strings and the other types. // We do this by checking the type. if (cls == H5T_STRING) { // Need to distinguish between variable-length and fixed-width data types. htri_t str_type = H5Tis_variable_str(hType()); if (str_type < 0) throw Exception(ioda_Here()); if (str_type > 0) { // Variable-length string const char** ccp = (const char**)fvbuf.data(); // NOLINT: Casting with HDF5 // A fill value for a string should always be at the zero element. // It makes no sense to have a multidimensional fill. if (ccp[0]) { res.stringFillValue_ = std::string(ccp[0]); // Do proper deallocation of the HDF5-returned string array. if (H5free_memory(const_cast<void*>(reinterpret_cast<const void*>(ccp[0]))) < 0) throw Exception(ioda_Here()); } } else { // Fixed-length string res.stringFillValue_ = std::string(fvbuf.data(), fvbuf.size()); } } else { if (szType_inBytes > sizeof(res.fillValue_)) throw Exception( "The fill value in HDF5 is too large for the " "fillValue_ union. ioda-engines currently only supports fill " "values on fundamental types and strings.", ioda_Here()) .add("szType_inBytes", szType_inBytes) .add("sizeof(res.fillValue_)", sizeof(res.fillValue_)); // Copy the buffer to the fvdata object memcpy(&(res.fillValue_.ui64), fvbuf.data(), fvbuf.size()); // NOLINT: Accessing this union member deliberately. } } return res; } catch (...) { std::throw_with_nested(Exception("Caught an exception.", ioda_Here())); } } HH_Variable::FillValueData_t HH_Variable::getFillValue() const { HH_hid_t create_plist(H5Dget_create_plist(var_()), Handles::Closers::CloseHDF5PropertyList::CloseP); return getFillValue(create_plist); } std::vector<Dimensions_t> HH_Variable::getChunkSizes(HH_hid_t create_plist, const Dimensions &dims) { H5D_layout_t layout = H5Pget_layout(create_plist.get()); if (layout == H5D_CHUNKED) { int max_ndims = gsl::narrow<int>(dims.dimensionality); std::vector<hsize_t> chunks(max_ndims); if (H5Pget_chunk(create_plist.get(), max_ndims, chunks.data()) < 0) throw Exception(ioda_Here()); std::vector<Dimensions_t> res; res.reserve(chunks.size()); for (const auto& i : chunks) res.emplace_back(gsl::narrow<Dimensions_t>( i)); // NOLINT: 'res' has space reserved. No need to rewrite the loop. return res; } return {}; } std::vector<Dimensions_t> HH_Variable::getChunkSizes() const { HH_hid_t create_plist(H5Dget_create_plist(var_()), Handles::Closers::CloseHDF5PropertyList::CloseP); return getChunkSizes(create_plist, getDimensions()); } std::pair<bool, int> HH_Variable::getGZIPCompression(HH_hid_t create_plist) { int nfilters = H5Pget_nfilters(create_plist.get()); if (nfilters < 0) throw Exception(ioda_Here()); for (unsigned i = 0; i < (unsigned)nfilters; ++i) { // See https://support.hdfgroup.org/HDF5/doc/RM/RM_H5P.html#Property-GetFilter2 for the function // signature. unsigned flags = 0; // Unused. const size_t cd_nelems_init = 16; // Size of array size_t cd_nelems = cd_nelems_init; // Pass size of array to function. Overwritten with number // of values actually read. std::vector<unsigned> cd_values(cd_nelems_init); // Data for filter. const size_t namelen = 32; // Unused std::vector<char> name(namelen); // Unused unsigned filter_config = 0; // Unused H5Z_filter_t filt = H5Pget_filter2(create_plist.get(), i, &flags, &cd_nelems, cd_values.data(), namelen, name.data(), &filter_config); if (filt != H5Z_FILTER_DEFLATE) continue; if (!cd_nelems) throw Exception(ioda_Here()); return std::pair<bool, int>(true, gsl::narrow<int>(cd_values[0])); } // Fallthrough. No GZIP compression was specified. return std::pair<bool, int>(false, 0); } std::pair<bool, int> HH_Variable::getGZIPCompression() const { HH_hid_t create_plist(H5Dget_create_plist(var_()), Handles::Closers::CloseHDF5PropertyList::CloseP); return getGZIPCompression(create_plist); } std::tuple<bool, unsigned, unsigned> HH_Variable::getSZIPCompression(HH_hid_t create_plist) { int nfilters = H5Pget_nfilters(create_plist.get()); if (nfilters < 0) throw Exception(ioda_Here()); for (unsigned i = 0; i < (unsigned)nfilters; ++i) { // See https://support.hdfgroup.org/HDF5/doc/RM/RM_H5P.html#Property-GetFilter2 for the function // signature. unsigned flags = 0; // Unused. const size_t cd_nelems_init = 16; // Size of array size_t cd_nelems = cd_nelems_init; // Pass size of array to function. Overwritten with number // of values actually read. std::vector<unsigned> cd_values(cd_nelems_init); // Data for filter. const size_t namelen = 32; // Unused std::vector<char> name(namelen); // Unused unsigned filter_config = 0; // Unused H5Z_filter_t filt = H5Pget_filter2(create_plist.get(), i, &flags, &cd_nelems, cd_values.data(), namelen, name.data(), &filter_config); if (filt != H5Z_FILTER_SZIP) continue; if (cd_nelems < 2) throw Exception(ioda_Here()); // cd_nelems is actually 4, but the options do not match the H5Pset_szip flags! return std::tuple<bool, unsigned, unsigned>(true, cd_values[0], cd_values[1]); } // Fallthrough. No SZIP compression was specified. return std::tuple<bool, unsigned, unsigned>(false, 0, 0); } std::tuple<bool, unsigned, unsigned> HH_Variable::getSZIPCompression() const { HH_hid_t create_plist(H5Dget_create_plist(var_()), Handles::Closers::CloseHDF5PropertyList::CloseP); return getSZIPCompression(create_plist); } VariableCreationParameters HH_Variable::getCreationParameters(bool doAtts, bool doDims) const { HH_hid_t create_plist(H5Dget_create_plist(var_()), Handles::Closers::CloseHDF5PropertyList::CloseP); VariableCreationParameters res; // Get chunking auto chunkinfo = getChunkSizes(create_plist, getDimensions()); if (chunkinfo.size()) { res.chunk = true; res.chunks = chunkinfo; } // Get compression auto gz = getGZIPCompression(create_plist); if (gz.first) res.compressWithGZIP(gz.second); auto sz = getSZIPCompression(create_plist); if (std::get<0>(sz)) res.compressWithSZIP(std::get<1>(sz), std::get<2>(sz)); // Get fill value res.fillValue_ = getFillValue(create_plist); // Attributes (optional) if (doAtts) { throw Exception("Unimplemented doAtts", ioda_Here()); } // Dimensions (optional) if (doDims) { throw Exception("Unimplemented doDims", ioda_Here()); } return res; } HH_Selection::~HH_Selection() = default; } // namespace HH } // namespace Engines } // namespace detail } // namespace ioda /// @}
43.98971
102
0.667581
[ "object", "vector" ]
b92e66366811f64de6414a28b344786b2866d7aa
3,241
cpp
C++
test/test_xemd_xutils.cpp
rjsberry/xemd
b5373e18f601fa7d6b5cde76fe767c77115d6451
[ "BSD-2-Clause" ]
4
2018-06-25T07:43:48.000Z
2022-01-29T03:30:43.000Z
test/test_xemd_xutils.cpp
rjsberry/xemd
b5373e18f601fa7d6b5cde76fe767c77115d6451
[ "BSD-2-Clause" ]
null
null
null
test/test_xemd_xutils.cpp
rjsberry/xemd
b5373e18f601fa7d6b5cde76fe767c77115d6451
[ "BSD-2-Clause" ]
null
null
null
// xemd: https://github.com/rjsberry/xemd // // Copyright (C) 2018, Richard Berry <rjsberry@protonmail.com> // // Distributed under the terms of BSD 2-Clause "simplified" license. (See // accompanying file LICENSE, or copy at // https://github.com/rjsberry/xemd/blob/master/LICENSE) // #include "gtest/gtest.h" #include "xtensor/xrandom.hpp" #include "xtensor/xtensor.hpp" #include "xemd/xemd.hpp" const std::size_t ARRAY_LENGTH = 10; TEST(xutils, diff) { auto linear = xt::arange<int>({ARRAY_LENGTH}); auto linear_d = xemd::xutils::Diff<int>(linear); ASSERT_EQ(linear_d.size(), linear.size() - 1); for (std::size_t i = 0; i < linear.size() - 1; ++i) { ASSERT_EQ(linear_d[i], 1); ASSERT_EQ((linear[i + 1] - linear[i]), 1); } auto nonlinear = xt::arange<double>({ARRAY_LENGTH}); for (auto e : nonlinear) { e *= xt::random::rand<double>({1})[0]; } auto nonlinear_d = xemd::xutils::Diff<double>(linear); ASSERT_EQ(nonlinear_d.size(), nonlinear.size() - 1); for (std::size_t i = 0; i < linear.size() - 1; ++i) { ASSERT_EQ(nonlinear_d[i], (nonlinear[i + 1] - nonlinear[i])); } } TEST(xutils, row_insertion) { xt::xtensor<double, 1> x = xt::random::randn<double>({ARRAY_LENGTH}); xt::xarray<double> X = xt::zeros<double>({3, 10}); auto X_copy = X; xemd::xutils::InsertRow(X, 1, x); ASSERT_EQ(xt::view(X, xt::range(0, 1)), xt::view(X_copy, xt::range(0, 1))); //ASSERT_EQ(xt::view(X, xt::range(1, 2)), x); ASSERT_EQ(xt::view(X, xt::range(2, 3)), xt::view(X_copy, xt::range(2, 3))); } TEST(xutils, linear_extrapolation) { struct TestCase { int x0, y0, x1, y1, x2, y2; }; std::vector<TestCase> tests = { {0, 0, 1, 0, 2, 0}, {1, 0, 2, 0, 0, 0}, {2, 0, 1, 0, 0, 0}, {0, 0, 1, 1, 2, 2}, {1, 1, 0, 0, 2, 2}, {2, 2, 1, 1, 0, 0}, {0, 2, 1, 1, 2, 0}, {1, 1, 0, 2, 2, 0}, {2, 0, 1, 1, 0, 2}, }; for (const auto& t : tests) { ASSERT_EQ(xemd::xutils::Extrapolate<int>(t.x0, t.y0, t.x1, t.y1, t.x2), t.y2); } } TEST(xutils, num_imfs) { struct TestCase { std::size_t input_tensor_size; std::size_t expected_imfs; }; std::vector<TestCase> tests = { {1, 1}, {2, 1}, {3, 1}, {4, 2}, {7, 2}, {8, 3}, }; for (const auto& test : tests) { auto mock_array = xt::zeros<double>({test.input_tensor_size}); ASSERT_EQ(xemd::xutils::NumImfs<double>(mock_array), test.expected_imfs); } } TEST(xutils, endpoint_correction) { struct TestCase { xt::xtensor<int, 1> y; std::function<bool (int, int)> comparator; int expected_lhs; int expected_rhs; }; auto greater = [](int a, int b){ return a > b; }; auto less = [](int a, int b){ return a < b; }; std::vector<TestCase> tests = { {{0, 1, 3, 1, 0}, greater, 0, 0}, {{0, 3, 1, 3, 0}, greater, 5, 5}, {{0, -1, -3, -1, 0}, less, 0, 0}, {{0, -3, -1, -3, 0}, less, -5, -5} }; for (auto& test : tests) { xt::xtensor<int, 1> x = xt::arange<int>(test.y.size()); xemd::xutils::CorrectEndpoints<int>(x, test.y, test.comparator); ASSERT_EQ(test.y[0], test.expected_lhs); ASSERT_EQ(test.y[test.y.size()-1], test.expected_rhs); } }
26.785124
82
0.567417
[ "vector" ]
b93062bfe5669f7186a179de1b2548df12cfd1ea
2,061
cpp
C++
81_rotten_oranges.cpp
swapmali/Must-Do-Coding-Questions-For-Companies-GFG
b68340c150f572c0fad7311af87f79b684060fb9
[ "MIT" ]
1
2021-02-07T19:50:36.000Z
2021-02-07T19:50:36.000Z
81_rotten_oranges.cpp
swapmali/Must-Do-Coding-Questions-For-Companies-GFG
b68340c150f572c0fad7311af87f79b684060fb9
[ "MIT" ]
null
null
null
81_rotten_oranges.cpp
swapmali/Must-Do-Coding-Questions-For-Companies-GFG
b68340c150f572c0fad7311af87f79b684060fb9
[ "MIT" ]
1
2021-05-06T15:30:47.000Z
2021-05-06T15:30:47.000Z
// https://practice.geeksforgeeks.org/problems/rotten-oranges/0 #include <bits/stdc++.h> using namespace std; // to replace 3's with 2's void normalize(vector< vector<int> > &v) { for (int i = 0; i < v.size(); ++i) { for (int j = 0; j < v[i].size(); ++j) { if (v[i][j] == 3) v[i][j] = 2; } } } int main() { #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif ios_base::sync_with_stdio(false); cin.tie(NULL); int t; cin >> t; while (t--) { int r, c, last_dq_size; cin >> r >> c; last_dq_size = r * c; vector< vector<int> > v(r); deque < pair<int, int> > dq; stack < pair<int, int> > s; // taking input for (int i = 0; i < r; ++i) { v[i].resize(c); for (int j = 0; j < c; ++j) { cin >> v[i][j]; // maintaining dq for fresh oranges if (v[i][j] == 1) dq.push_back(make_pair(i, j)); } } int cnt = 1, x, y, flg = 0; while (!dq.empty() || !s.empty()) { pair <int, int> temp; if (dq.empty()) { // to replace 3's with 2's normalize(v); // insert all elements back to the dq from stack while (!s.empty()) { temp = s.top(); dq.push_back(temp); s.pop(); } // which means there are unreachable oranges if (dq.size() >= last_dq_size) { cout << -1 << endl; flg = 1; break; } last_dq_size = dq.size(); // increasing cnt after every iteration of emptying the dq cnt++; } pair <int, int> p = dq.front(); x = p.first; y = p.second; // for each of the fresh arr checking if it is in unique dist with rotten orange if ((x + 1 < r && v[x + 1][y] == 2) || (y + 1 < c && v[x][y + 1] == 2) || (x - 1 >= 0 && v[x - 1][y] == 2) || (y - 1 >= 0 && v[x][y - 1] == 2)) { // marking with 3 to indicate it is rotten in this iteration v[x][y] = 3; } else { // stack maintains fresh oranges which won't get rotten in this iteration s.push(p); } dq.pop_front(); } if (!flg) cout << cnt << endl; } return 0; }
19.817308
146
0.518195
[ "vector" ]
b930f14983a237ff04f7efa59b1eb154532d324a
3,511
cpp
C++
src/solvers/Exploration.cpp
sandysa/A-MultiObjective-Approach-to-Mitigate-Negative-Side-Effects
9d124078848dde7d03266982494f59cc27c007e0
[ "MIT" ]
null
null
null
src/solvers/Exploration.cpp
sandysa/A-MultiObjective-Approach-to-Mitigate-Negative-Side-Effects
9d124078848dde7d03266982494f59cc27c007e0
[ "MIT" ]
null
null
null
src/solvers/Exploration.cpp
sandysa/A-MultiObjective-Approach-to-Mitigate-Negative-Side-Effects
9d124078848dde7d03266982494f59cc27c007e0
[ "MIT" ]
null
null
null
#include <list> #include <climits> #include <cmath> #include <vector> #include <stdlib.h> #include <algorithm> #include <initializer_list> #include <iostream> #include <fstream> #include <sstream> #include <string> #include "../../include/solvers/Exploration.h" #include "../../include/MObjProblem.h" #include "../../include/MObjState.h" std::random_device rand_dev; std::mt19937 kRNG(rand_dev()); std::uniform_real_distribution<> kUnif_0_1(0, 1); using namespace std; Exploration::Exploration(mlmobj::MOProblem* problem, double epsilon, std::string sfile) { epsilon_ = epsilon; gamma_ = problem->gamma(); samples_file = sfile; problem_ = problem; } mlcore::Action* Exploration::getGreedyAction(mlmobj::MOProblem* problem, mlmobj::MOState* s, int index) { double max_val = std::numeric_limits<double>::infinity(); mlcore::Action* to_ret = nullptr; double rn = ((double)rand() / (RAND_MAX)); std::vector<mlcore::Action*> valid_ac; valid_ac.clear(); if (rn < epsilon_) { for(mlcore::Action* a: problem->actions()){ if(problem->applicable(s,a, index)){ valid_ac.push_back(a); } } int random_index = rand() % valid_ac.size(); return valid_ac.at(random_index); } if(s->bestAction() != nullptr) return s->bestAction(); else{ for(mlcore::Action* a: problem->actions()){ if(problem->applicable(s,a, index)){ return a; } } } return to_ret; } mlmobj::MOState* Exploration::getRandomSuccessor(mlmobj::MOProblem* problem, mlmobj::MOState* s, mlcore::Action* a){ if(problem->applicable(s,a)){ double acc = 0.0; double rn = kUnif_0_1(kRNG); for (mlcore::Successor sccr : problem->transition(s, a)) { acc += sccr.su_prob; if(acc >= rn){ mlmobj::MOState* mos = static_cast<mlmobj::MOState*> (sccr.su_state); return (mos); } } } return s; } /** Writes the samples (s,a,reward) to the samples_file**/ void Exploration::writeSamples(){ std::ofstream expfile; expfile.open(samples_file); expfile << learner_writer; expfile.close(); std::cout << "Sample generation complete. Check " << samples_file << "." << std::endl; } void Exploration::gatherFeedback(mlmobj::MOProblem* problem, mlmobj::MOState* s, int index) { mlmobj::MOState* current_state = s; int step = 0; while (step < max_steps && !problem->goal(current_state,0)) { step++; mlcore::Action* current_action = getGreedyAction(problem, current_state, index); mlmobj::MOState* succ = getRandomSuccessor(problem, current_state, current_action); double reward = problem->cost(current_state, current_action, index); if(generateSamples_){ std::ostringstream curr_s, curr_a; curr_s << current_state; curr_a << current_action; learner_writer += curr_s.str() + " " + curr_a.str() + " " + std::to_string(current_action->hashValue())+ " " + std::to_string(reward) +"\n"; } current_state = succ; } }
33.759615
156
0.559385
[ "vector" ]
b93513c29e2606c6adebb3135d8f3a1292cf38a3
4,276
cpp
C++
src/qt/marketmodel.cpp
canndrew/hivemind
147973cfe76867410578d91d6f0a8df105cab4e0
[ "MIT" ]
125
2015-10-03T02:25:01.000Z
2022-02-14T04:44:25.000Z
src/qt/marketmodel.cpp
canndrew/hivemind
147973cfe76867410578d91d6f0a8df105cab4e0
[ "MIT" ]
68
2015-11-17T04:26:48.000Z
2018-04-19T07:30:01.000Z
src/qt/marketmodel.cpp
canndrew/hivemind
147973cfe76867410578d91d6f0a8df105cab4e0
[ "MIT" ]
19
2015-10-22T22:25:25.000Z
2021-01-30T19:12:32.000Z
#include "marketmodel.h" #include <QHBoxLayout> #include <QList> #include <QWidget> #include <sstream> #include "marketgraphwidget.h" #include "txdb.h" #include "wallet.h" #include "walletmodel.h" extern CMarketTreeDB *pmarkettree; // Private implementation class MarketModelPriv { public: MarketModelPriv(CWallet *wallet, MarketModel *parent) : wallet(wallet), parent(parent) { } CWallet *wallet; MarketModel *parent; QList<const marketMarket *> cached; int size() { return cached.size(); } const marketMarket *index(int idx) { if(idx >= 0 && idx < cached.size()) return cached[idx]; return 0; } }; MarketModel::MarketModel(CWallet *wallet, WalletModel *parent) : QAbstractTableModel(parent), wallet(wallet), walletModel(parent), priv(new MarketModelPriv(wallet, this)) { } MarketModel::~MarketModel() { delete priv; } int MarketModel::rowCount(const QModelIndex & /*parent*/) const { return priv->size(); } int MarketModel::columnCount(const QModelIndex & /*parent*/) const { return 2; } QVariant MarketModel::data(const QModelIndex &index, int role) const { if (!index.isValid()) { return false; } int row = index.row(); int col = index.column(); const marketMarket *market = priv->index(row); switch(role) { case Qt::DisplayRole: { // Market Details if (col == 1) { std::stringstream sstream; sstream << "Title: " << market->title << std::endl; sstream << "Description: " << market->description << std::endl; sstream << "Tags: " << market->tags << std::endl; sstream << "Market ID: " << market->GetHash().GetHex() << std::endl; return QString::fromStdString(sstream.str()); } } case Qt::DecorationRole: { // Graph if (col == 0) { MarketGraphWidget graphWidget; return graphWidget.getTableGraphPixmap(QString::fromStdString(market->title), market); } } case Qt::SizeHintRole: { // Graph if (col == 0) { return QSize(480, 360); } } } return QVariant(); } const marketMarket *MarketModel::index(int row) const { return priv->index(row); } QVariant MarketModel::headerData(int section, Qt::Orientation orientation, int role) const { if (role == Qt::DisplayRole) { if (orientation == Qt::Horizontal) { switch(section) { case 0: return QString("Graph"); case 1: return QString("Market Info"); } } } return QVariant(); } void MarketModel::setBranch(uint256 branchID) { if (!priv) return; // Make sure the branch exists const marketBranch *branch = pmarkettree->GetBranch(branchID); if (!branch) return; // Erase / reset the cache resetModel(); // Get the list of decisions on the branch vector<marketDecision *> decisions = pmarkettree->GetDecisions(branchID); // Make a list of markets from every decision on the branch vector<marketMarket *> markets; for (unsigned int x = 0; x < decisions.size(); x++) { // Get the markets for this decision uint256 uDecision; uDecision.SetHex(decisions.at(x)->GetHash().GetHex()); vector<marketMarket* > decisionMarkets = pmarkettree->GetMarkets(uDecision); // Add the markets to the markets vector for (unsigned int y = 0; y < decisionMarkets.size(); y++) { markets.push_back(decisionMarkets.at(y)); } } // Add markets to the model if (markets.size()) { beginInsertRows(QModelIndex(), 0, markets.size()-1); for (unsigned int i = 0; i < markets.size(); i++) priv->cached.append(markets.at(i)); endInsertRows(); } } void MarketModel::resetModel() { beginResetModel(); if (priv->cached.size()) { beginRemoveRows(QModelIndex(), 0, priv->cached.size()-1); for (ssize_t i = 0; i < priv->cached.size(); i++) delete priv->cached.at(i); priv->cached.clear(); endRemoveRows(); } endResetModel(); }
22.744681
98
0.587933
[ "vector", "model" ]
b935c8a8d4722c7c9b5d1eaafb5d6682460733b4
1,883
cpp
C++
C-Plus-Plus/cp/Exactly_Four_Factors.cpp
Khushboo85277/NeoAlgo
784d7b06c385336425ed951918d1ab37b854d29f
[ "MIT" ]
897
2020-06-25T00:12:52.000Z
2022-03-24T00:49:31.000Z
C-Plus-Plus/cp/Exactly_Four_Factors.cpp
adarshnjena/NeoAlgo
77a92858d2bf970054ef31c2f55a6d79917a786a
[ "MIT" ]
5,707
2020-06-24T17:53:28.000Z
2022-01-22T05:03:15.000Z
C-Plus-Plus/cp/Exactly_Four_Factors.cpp
adarshnjena/NeoAlgo
77a92858d2bf970054ef31c2f55a6d79917a786a
[ "MIT" ]
1,817
2020-06-25T03:51:05.000Z
2022-03-29T05:14:07.000Z
/* A number has exactly 4 factors if below given any condition is satisfied 1.If the number is a cube of a prime number. 2.If the number is a product of two distinct prime numbers. */ #include <bits/stdc++.h> using namespace std; // maxi gives the range of numbers int maxi = 1000; //arr contain the 1 value for the numbers which has exactly 4 factors int arr[1000]={0}; void check() { //Implementing Sieve of Eratosthenes for checking prime numbers upto maxi int primeNumbers[maxi + 1]; for(int i=0;i<maxi+1;i++) primeNumbers[i]=1; for (int i = 2; i <= sqrt(maxi); i++) { if (primeNumbers[i]) { for (int j = i * 2; j <= maxi; j += i) primeNumbers[j] = 0; } } // Creating a array of dynamic size containing all prime numbers upto maxi vector<int> temp; for (int i = 2; i <= maxi; i++) if (primeNumbers[i]) temp.push_back(i); for (int i = 0; i < temp.size(); ++i) { int x = temp[i]; //If the number is a cube of a prime number, then it has exactly 4 factors if (1 *(pow(x, 3)) <= maxi) arr[x*x*x] = 1; //If the number is a product of two distinct prime numbers,then it has exactly 4 factors for (int j = i + 1; j < temp.size(); ++j) { int y = temp[j]; if (1 * x*y > maxi) break; arr[x*y] = 1; } } } int main() { int num; cout<<"Enter the number you want to check: "; cin>>num; check(); if(arr[num]) cout<<num<<" has exactly four factors\n"; else cout<<num<<" does not have exactly four factors\n"; return 0; } /* Sample Input/Output: Enter the number you want to check: Input: num=27 Output: 27 has exactly four factors Enter the number you want to check: Input: num=109 Output:109 does not have exactly four factors Time complexity-O(Nlog(log(N))) Space complexity-O(N) */
22.686747
95
0.603824
[ "vector" ]
b940bc613b7f9524ea9430c72fad62d11d9fc9c8
15,683
hpp
C++
tests/basic_operations_tests.hpp
devinmacalaladdt/Matrix
c0ea8eae74fe420c25488f7fe6b9ac3d34b6e1cf
[ "MIT" ]
null
null
null
tests/basic_operations_tests.hpp
devinmacalaladdt/Matrix
c0ea8eae74fe420c25488f7fe6b9ac3d34b6e1cf
[ "MIT" ]
null
null
null
tests/basic_operations_tests.hpp
devinmacalaladdt/Matrix
c0ea8eae74fe420c25488f7fe6b9ac3d34b6e1cf
[ "MIT" ]
null
null
null
#include "gtest/gtest.h" #include <Matrix.hpp> #include <cmath> namespace { class MatrixBasicOpTest : public ::testing::Test { protected: Matrix mat; MatrixBasicOpTest() { mat = matrix.genfromtxt("./tests/test_dataset.csv", ','); mat.to_double(); } }; TEST_F(MatrixBasicOpTest, AddingTwoMatrix) { Matrix add = mat + mat; std::vector<std::vector<double>> vec; std::vector<double> v; for (int i = 0; i < 2; i++) { for (int j = 0; j < 3; j++) v.push_back(2 * (3 * i + j + 1)); vec.push_back(v); v.clear(); } Matrix test_with = matrix.init(vec); EXPECT_EQ(add, test_with); } TEST_F(MatrixBasicOpTest, AddingTwoMatrixWithAssignment) { Matrix add = mat; add += mat; std::vector<std::vector<double>> vec; std::vector<double> v; for (int i = 0; i < 2; i++) { for (int j = 0; j < 3; j++) v.push_back(2 * (3 * i + j + 1)); vec.push_back(v); v.clear(); } Matrix test_with = matrix.init(vec); EXPECT_EQ(add, test_with); } TEST_F(MatrixBasicOpTest, AddingMatrixScalar) { Matrix add = mat + 1; std::vector<std::vector<double>> vec; std::vector<double> v; for (int i = 0; i < 2; i++) { for (int j = 0; j < 3; j++) v.push_back(3 * i + j + 2); vec.push_back(v); v.clear(); } Matrix test_with = matrix.init(vec); EXPECT_EQ(add, test_with); } TEST_F(MatrixBasicOpTest, AddingMatrixScalarWithAssignment) { Matrix add = mat; add += 1; std::vector<std::vector<double>> vec; std::vector<double> v; for (int i = 0; i < 2; i++) { for (int j = 0; j < 3; j++) v.push_back(3 * i + j + 2); vec.push_back(v); v.clear(); } Matrix test_with = matrix.init(vec); EXPECT_EQ(add, test_with); } TEST_F(MatrixBasicOpTest, AddingMatrixColumnVector) { Matrix add = mat + mat.slice(0, mat.row_length(), 0, 1); std::vector<std::vector<double>> vec; std::vector<double> v; for (int i = 0; i < 2; i++) { for (int j = 0; j < 3; j++) v.push_back(6 * i + j + 2); vec.push_back(v); v.clear(); } Matrix test_with = matrix.init(vec); EXPECT_EQ(add, test_with); } TEST_F(MatrixBasicOpTest, AddingMatrixColumnVectorWithAssignment) { Matrix add = mat; add += mat.slice(0, mat.row_length(), 0, 1); std::vector<std::vector<double>> vec; std::vector<double> v; for (int i = 0; i < 2; i++) { for (int j = 0; j < 3; j++) v.push_back(6 * i + j + 2); vec.push_back(v); v.clear(); } Matrix test_with = matrix.init(vec); EXPECT_EQ(add, test_with); } TEST_F(MatrixBasicOpTest, AddingMatrixRowVector) { Matrix add = mat + mat.slice(0, 1, 0, mat.col_length()); std::vector<std::vector<double>> vec; std::vector<double> v; for (int i = 0; i < 2; i++) { for (int j = 0; j < 3; j++) v.push_back(3 * i + 2 * j + 2); vec.push_back(v); v.clear(); } Matrix test_with = matrix.init(vec); EXPECT_EQ(add, test_with); } TEST_F(MatrixBasicOpTest, AddingMatrixRowVectorWithAssignment) { Matrix add = mat; add += mat.slice(0, 1, 0, mat.col_length()); std::vector<std::vector<double>> vec; std::vector<double> v; for (int i = 0; i < 2; i++) { for (int j = 0; j < 3; j++) v.push_back(3 * i + 2 * j + 2); vec.push_back(v); v.clear(); } Matrix test_with = matrix.init(vec); EXPECT_EQ(add, test_with); } TEST_F(MatrixBasicOpTest, SubtractingTwoMatrix) { Matrix sub = mat - mat; std::vector<double> v(3, 0); std::vector<std::vector<double>> vec(2, v); Matrix test_with = matrix.init(vec); EXPECT_EQ(sub, test_with); } TEST_F(MatrixBasicOpTest, SubtractingTwoMatrixWithAssignment) { Matrix sub = mat; sub -= mat; std::vector<double> v(3, 0); std::vector<std::vector<double>> vec(2, v); Matrix test_with = matrix.init(vec); EXPECT_EQ(sub, test_with); } TEST_F(MatrixBasicOpTest, SubtractingMatrixScalar) { Matrix sub = mat - 1; std::vector<std::vector<double>> vec; std::vector<double> v; for (int i = 0; i < 2; i++) { for (int j = 0; j < 3; j++) v.push_back(3 * i + j); vec.push_back(v); v.clear(); } Matrix test_with = matrix.init(vec); EXPECT_EQ(sub, test_with); } TEST_F(MatrixBasicOpTest, SubtractingMatrixScalarWithAssignment) { Matrix sub = mat; sub -= 1; std::vector<std::vector<double>> vec; std::vector<double> v; for (int i = 0; i < 2; i++) { for (int j = 0; j < 3; j++) v.push_back(3 * i + j); vec.push_back(v); v.clear(); } Matrix test_with = matrix.init(vec); EXPECT_EQ(sub, test_with); } TEST_F(MatrixBasicOpTest, SubtractingMatrixColumnVector) { Matrix sub = mat - mat.slice(0, mat.row_length(), 0, 1); std::vector<double> v; for (int i = 0; i < 3; i++) v.push_back(i); std::vector<std::vector<double>> vec; vec.push_back(v); vec.push_back(v); Matrix test_with = matrix.init(vec); EXPECT_EQ(sub, test_with); } TEST_F(MatrixBasicOpTest, SubtractingMatrixColumnVectorWithAssignment) { Matrix sub = mat; sub -= mat.slice(0, mat.row_length(), 0, 1); std::vector<double> v; for (int i = 0; i < 3; i++) v.push_back(i); std::vector<std::vector<double>> vec; vec.push_back(v); vec.push_back(v); Matrix test_with = matrix.init(vec); EXPECT_EQ(sub, test_with); } TEST_F(MatrixBasicOpTest, SubtractingMatrixRowVector) { Matrix sub = mat - mat.slice(0, 1, 0, mat.col_length()); std::vector<double> v1(3, 0); std::vector<double> v2(3, 3); std::vector<std::vector<double>> vec; vec.push_back(v1); vec.push_back(v2); Matrix test_with = matrix.init(vec); EXPECT_EQ(sub, test_with); } TEST_F(MatrixBasicOpTest, SubtractingMatrixRowVectorWithAssignment) { Matrix sub = mat; sub -= mat.slice(0, 1, 0, mat.col_length()); std::vector<double> v1(3, 0); std::vector<double> v2(3, 3); std::vector<std::vector<double>> vec; vec.push_back(v1); vec.push_back(v2); Matrix test_with = matrix.init(vec); EXPECT_EQ(sub, test_with); } TEST_F(MatrixBasicOpTest, MultiplyingTwoMatrix) { Matrix mult = mat * mat; std::vector<std::vector<double>> vec; std::vector<double> v; for (int i = 0; i < 2; i++) { for (int j = 0; j < 3; j++) v.push_back((3 * i + j + 1) * (3 * i + j + 1)); vec.push_back(v); v.clear(); } Matrix test_with = matrix.init(vec); EXPECT_EQ(mult, test_with); } TEST_F(MatrixBasicOpTest, MultiplyingTwoMatrixWithAssignment) { Matrix mult = mat; mult *= mat; std::vector<std::vector<double>> vec; std::vector<double> v; for (int i = 0; i < 2; i++) { for (int j = 0; j < 3; j++) v.push_back((3 * i + j + 1) * (3 * i + j + 1)); vec.push_back(v); v.clear(); } Matrix test_with = matrix.init(vec); EXPECT_EQ(mult, test_with); } TEST_F(MatrixBasicOpTest, MultiplyingMatrixScalar) { Matrix mult = mat * 2; std::vector<std::vector<double>> vec; std::vector<double> v; for (int i = 0; i < 2; i++) { for (int j = 0; j < 3; j++) v.push_back((3 * i + j + 1) * 2); vec.push_back(v); v.clear(); } Matrix test_with = matrix.init(vec); EXPECT_EQ(mult, test_with); } TEST_F(MatrixBasicOpTest, MultiplyingMatrixScalarWithAssignment) { Matrix mult = mat; mult *= 2; std::vector<std::vector<double>> vec; std::vector<double> v; for (int i = 0; i < 2; i++) { for (int j = 0; j < 3; j++) v.push_back((3 * i + j + 1) * 2); vec.push_back(v); v.clear(); } Matrix test_with = matrix.init(vec); EXPECT_EQ(mult, test_with); } TEST_F(MatrixBasicOpTest, MultiplyingMatrixColumnVector) { Matrix mult = mat * mat.slice(0, mat.row_length(), 0, 1); std::vector<std::vector<double>> vec; std::vector<double> v; for (int i = 0; i < 2; i++) { for (int j = 0; j < 3; j++) v.push_back((3 * i + j + 1) * (std::pow(4, i))); vec.push_back(v); v.clear(); } Matrix test_with = matrix.init(vec); EXPECT_EQ(mult, test_with); } TEST_F(MatrixBasicOpTest, MultiplyingMatrixColumnVectorWithAssignment) { Matrix mult = mat; mult *= mat.slice(0, mat.row_length(), 0, 1); std::vector<std::vector<double>> vec; std::vector<double> v; for (int i = 0; i < 2; i++) { for (int j = 0; j < 3; j++) v.push_back((3 * i + j + 1) * (std::pow(4, i))); vec.push_back(v); v.clear(); } Matrix test_with = matrix.init(vec); EXPECT_EQ(mult, test_with); } TEST_F(MatrixBasicOpTest, MultiplyingMatrixRowVector) { Matrix mult = mat * mat.slice(0, 1, 0, mat.col_length()); std::vector<std::vector<double>> vec; std::vector<double> v; for (int i = 0; i < 2; i++) { for (int j = 0; j < 3; j++) v.push_back((3 * i + j + 1) * (j + 1)); vec.push_back(v); v.clear(); } Matrix test_with = matrix.init(vec); EXPECT_EQ(mult, test_with); } TEST_F(MatrixBasicOpTest, MultiplyingMatrixRowVectorWithAssignment) { Matrix mult = mat; mult *= mat.slice(0, 1, 0, mat.col_length()); std::vector<std::vector<double>> vec; std::vector<double> v; for (int i = 0; i < 2; i++) { for (int j = 0; j < 3; j++) v.push_back((3 * i + j + 1) * (j + 1)); vec.push_back(v); v.clear(); } Matrix test_with = matrix.init(vec); EXPECT_EQ(mult, test_with); } TEST_F(MatrixBasicOpTest, DividingTwoMatrix) { Matrix div = mat / mat; std::vector<double> v(3, 1); std::vector<std::vector<double>> vec(2, v); Matrix test_with = matrix.init(vec); EXPECT_EQ(div, test_with); } TEST_F(MatrixBasicOpTest, DividingTwoMatrixWithAssignment) { Matrix div = mat; div /= mat; std::vector<double> v(3, 1); std::vector<std::vector<double>> vec(2, v); Matrix test_with = matrix.init(vec); EXPECT_EQ(div, test_with); } TEST_F(MatrixBasicOpTest, DividingMatrixScalar) { Matrix div = mat / 2; std::vector<std::vector<double>> vec; std::vector<double> v; for (int i = 0; i < 2; i++) { for (int j = 0; j < 3; j++) v.push_back((double)(3 * i + j + 1) / 2); vec.push_back(v); v.clear(); } Matrix test_with = matrix.init(vec); EXPECT_EQ(div, test_with); } TEST_F(MatrixBasicOpTest, DividingMatrixScalarWithAssignment) { Matrix div = mat; div /= 2; std::vector<std::vector<double>> vec; std::vector<double> v; for (int i = 0; i < 2; i++) { for (int j = 0; j < 3; j++) v.push_back((double)(3 * i + j + 1) / 2); vec.push_back(v); v.clear(); } Matrix test_with = matrix.init(vec); EXPECT_EQ(div, test_with); } TEST_F(MatrixBasicOpTest, DividingMatrixColumnVector) { Matrix div = mat / mat.slice(0, mat.row_length(), 0, 1); std::vector<std::vector<double>> vec; std::vector<double> v; for (int i = 0; i < 2; i++) { for (int j = 0; j < 3; j++) v.push_back((double)(3 * i + j + 1) / (std::pow(4, i))); vec.push_back(v); v.clear(); } Matrix test_with = matrix.init(vec); EXPECT_EQ(div, test_with); } TEST_F(MatrixBasicOpTest, DividingMatrixColumnVectorWithAssignment) { Matrix div = mat; div /= mat.slice(0, mat.row_length(), 0, 1); std::vector<std::vector<double>> vec; std::vector<double> v; for (int i = 0; i < 2; i++) { for (int j = 0; j < 3; j++) v.push_back((double)(3 * i + j + 1) / (std::pow(4, i))); vec.push_back(v); v.clear(); } Matrix test_with = matrix.init(vec); EXPECT_EQ(div, test_with); } TEST_F(MatrixBasicOpTest, DividingMatrixRowVector) { Matrix div = mat / mat.slice(0, 1, 0, mat.col_length()); std::vector<std::vector<double>> vec; std::vector<double> v; for (int i = 0; i < 2; i++) { for (int j = 0; j < 3; j++) v.push_back((double)(3 * i + j + 1) / (j + 1)); vec.push_back(v); v.clear(); } Matrix test_with = matrix.init(vec); EXPECT_EQ(div, test_with); } TEST_F(MatrixBasicOpTest, DividingMatrixRowVectorWithAssignment) { Matrix div = mat; div /= mat.slice(0, 1, 0, mat.col_length()); std::vector<std::vector<double>> vec; std::vector<double> v; for (int i = 0; i < 2; i++) { for (int j = 0; j < 3; j++) v.push_back((double)(3 * i + j + 1) / (j + 1)); vec.push_back(v); v.clear(); } Matrix test_with = matrix.init(vec); EXPECT_EQ(div, test_with); } TEST_F(MatrixBasicOpTest, DividingByZeroMatrix) { Matrix div = mat / matrix.zeros(2, 3); Matrix test_with = matrix.ones(2, 3) * std::numeric_limits<double>::infinity(); EXPECT_EQ(div, test_with); } TEST_F(MatrixBasicOpTest, DividingByZeroMatrixWithAssignment) { Matrix div = mat; div /= matrix.zeros(2, 3); Matrix test_with = matrix.ones(2, 3) * std::numeric_limits<double>::infinity(); EXPECT_EQ(div, test_with); } TEST_F(MatrixBasicOpTest, DividingByZero) { Matrix div = mat / 0; Matrix test_with = matrix.ones(2, 3) * std::numeric_limits<double>::infinity(); EXPECT_EQ(div, test_with); } TEST_F(MatrixBasicOpTest, DividingByZeroWithAssignment) { Matrix div = mat; div /= 0; Matrix test_with = matrix.ones(2, 3) * std::numeric_limits<double>::infinity(); EXPECT_EQ(div, test_with); } TEST_F(MatrixBasicOpTest, PreIncrement) { Matrix add = mat; ++add; std::vector<std::vector<double>> vec; std::vector<double> v; for (int i = 0; i < 2; i++) { for (int j = 0; j < 3; j++) v.push_back(3 * i + j + 2); vec.push_back(v); v.clear(); } Matrix test_with = matrix.init(vec); EXPECT_EQ(add, test_with); } TEST_F(MatrixBasicOpTest, PostIncrement) { Matrix add = mat; add++; std::vector<std::vector<double>> vec; std::vector<double> v; for (int i = 0; i < 2; i++) { for (int j = 0; j < 3; j++) v.push_back(3 * i + j + 2); vec.push_back(v); v.clear(); } Matrix test_with = matrix.init(vec); EXPECT_EQ(add, test_with); } TEST_F(MatrixBasicOpTest, PreDecrement) { Matrix sub = mat; --sub--; std::vector<std::vector<double>> vec; std::vector<double> v; for (int i = 0; i < 2; i++) { for (int j = 0; j < 3; j++) v.push_back(3 * i + j); vec.push_back(v); v.clear(); } Matrix test_with = matrix.init(vec); EXPECT_EQ(sub, test_with); } TEST_F(MatrixBasicOpTest, PostDecrement) { Matrix sub = mat; sub--; std::vector<std::vector<double>> vec; std::vector<double> v; for (int i = 0; i < 2; i++) { for (int j = 0; j < 3; j++) v.push_back(3 * i + j); vec.push_back(v); v.clear(); } Matrix test_with = matrix.init(vec); EXPECT_EQ(sub, test_with); } TEST_F(MatrixBasicOpTest, UnaryMinus) { Matrix minus = -mat; std::vector<std::vector<double>> vec; std::vector<double> v; for (int i = 0; i < 2; i++) { for (int j = 0; j < 3; j++) v.push_back(-(3 * i + j + 1)); vec.push_back(v); v.clear(); } Matrix test_with = matrix.init(vec); EXPECT_EQ(minus, test_with); } } // namespace
28.462795
83
0.565772
[ "vector" ]
b94e5df527d7df717972340db8b06bd0466bf494
40,154
cpp
C++
deps/spidermonkey/jslock.cpp
havocp/hwf
a99e9a0461983226717b278513cfd9f1e53ba0f1
[ "MIT" ]
1
2015-04-19T10:49:48.000Z
2015-04-19T10:49:48.000Z
deps/spidermonkey/jslock.cpp
havocp/hwf
a99e9a0461983226717b278513cfd9f1e53ba0f1
[ "MIT" ]
null
null
null
deps/spidermonkey/jslock.cpp
havocp/hwf
a99e9a0461983226717b278513cfd9f1e53ba0f1
[ "MIT" ]
null
null
null
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Mozilla Communicator client code, released * March 31, 1998. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * either of the GNU General Public License Version 2 or later (the "GPL"), * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #ifdef JS_THREADSAFE /* * JS locking stubs. */ #include <stdlib.h> #include <string.h> #include "jspubtd.h" #include "jsutil.h" /* Added by JSIFY */ #include "jstypes.h" #include "jsstdint.h" #include "jsbit.h" #include "jscntxt.h" #include "jsdtoa.h" #include "jsgc.h" #include "jslock.h" #include "jsscope.h" #include "jsstr.h" using namespace js; #define ReadWord(W) (W) #if !defined(__GNUC__) # define __asm__ asm # define __volatile__ volatile #endif /* Implement NativeCompareAndSwap. */ #if defined(_MSC_VER) && defined(_M_IX86) #pragma warning( disable : 4035 ) JS_BEGIN_EXTERN_C extern long __cdecl _InterlockedCompareExchange(long *volatile dest, long exchange, long comp); JS_END_EXTERN_C #pragma intrinsic(_InterlockedCompareExchange) JS_STATIC_ASSERT(sizeof(jsword) == sizeof(long)); static JS_ALWAYS_INLINE int NativeCompareAndSwapHelper(jsword *w, jsword ov, jsword nv) { _InterlockedCompareExchange((long*) w, nv, ov); __asm { sete al } } static JS_ALWAYS_INLINE int NativeCompareAndSwap(jsword *w, jsword ov, jsword nv) { return (NativeCompareAndSwapHelper(w, ov, nv) & 1); } #elif defined(_MSC_VER) && (defined(_M_AMD64) || defined(_M_X64)) JS_BEGIN_EXTERN_C extern long long __cdecl _InterlockedCompareExchange64(long long *volatile dest, long long exchange, long long comp); JS_END_EXTERN_C #pragma intrinsic(_InterlockedCompareExchange64) static JS_ALWAYS_INLINE int NativeCompareAndSwap(jsword *w, jsword ov, jsword nv) { return _InterlockedCompareExchange64(w, nv, ov) == ov; } #elif defined(XP_MACOSX) || defined(DARWIN) #include <libkern/OSAtomic.h> static JS_ALWAYS_INLINE int NativeCompareAndSwap(jsword *w, jsword ov, jsword nv) { /* Details on these functions available in the manpage for atomic */ return OSAtomicCompareAndSwapPtrBarrier(reinterpret_cast<void *>(ov), reinterpret_cast<void *>(nv), reinterpret_cast<void **>(w)); } #elif defined(__i386) && (defined(__GNUC__) || defined(__SUNPRO_CC)) /* Note: This fails on 386 cpus, cmpxchgl is a >= 486 instruction */ static JS_ALWAYS_INLINE int NativeCompareAndSwap(jsword *w, jsword ov, jsword nv) { unsigned int res; __asm__ __volatile__ ( "lock\n" "cmpxchgl %2, (%1)\n" "sete %%al\n" "andl $1, %%eax\n" : "=a" (res) #ifdef __SUNPRO_CC /* Different code for Sun Studio because of a bug of SS12U1 */ : "c" (w), "d" (nv), "a" (ov) #else : "r" (w), "r" (nv), "a" (ov) #endif : "cc", "memory"); return (int)res; } #elif defined(__x86_64) && (defined(__GNUC__) || defined(__SUNPRO_CC)) static JS_ALWAYS_INLINE int NativeCompareAndSwap(jsword *w, jsword ov, jsword nv) { unsigned int res; __asm__ __volatile__ ( "lock\n" "cmpxchgq %2, (%1)\n" "sete %%al\n" "movzbl %%al, %%eax\n" : "=a" (res) : "r" (w), "r" (nv), "a" (ov) : "cc", "memory"); return (int)res; } #elif defined(__sparc) #if defined(__GNUC__) static JS_ALWAYS_INLINE int NativeCompareAndSwap(jsword *w, jsword ov, jsword nv) { unsigned int res; __asm__ __volatile__ ( "membar #StoreLoad | #LoadLoad\n" #if JS_BITS_PER_WORD == 32 "cas [%1],%2,%3\n" #else "casx [%1],%2,%3\n" #endif "membar #StoreLoad | #LoadLoad\n" "cmp %2,%3\n" "be,a 1f\n" "mov 1,%0\n" "mov 0,%0\n" "1:" : "=r" (res) : "r" (w), "r" (ov), "r" (nv)); return (int)res; } #elif defined(__SUNPRO_CC) /* Implementation in lock_sparc*.il */ extern "C" int NativeCompareAndSwap(jsword *w, jsword ov, jsword nv); #endif #elif defined(AIX) #include <sys/atomic_op.h> static JS_ALWAYS_INLINE int NativeCompareAndSwap(jsword *w, jsword ov, jsword nv) { int res; JS_STATIC_ASSERT(sizeof(jsword) == sizeof(long)); res = compare_and_swaplp((atomic_l)w, &ov, nv); if (res) __asm__("isync"); return res; } #elif defined(USE_ARM_KUSER) /* See https://bugzilla.mozilla.org/show_bug.cgi?id=429387 for a * description of this ABI; this is a function provided at a fixed * location by the kernel in the memory space of each process. */ typedef int (__kernel_cmpxchg_t)(int oldval, int newval, volatile int *ptr); #define __kernel_cmpxchg (*(__kernel_cmpxchg_t *)0xffff0fc0) JS_STATIC_ASSERT(sizeof(jsword) == sizeof(int)); static JS_ALWAYS_INLINE int NativeCompareAndSwap(jsword *w, jsword ov, jsword nv) { volatile int *vp = (volatile int *) w; PRInt32 failed = 1; /* Loop until a __kernel_cmpxchg succeeds. See bug 446169 */ do { failed = __kernel_cmpxchg(ov, nv, vp); } while (failed && *vp == ov); return !failed; } #elif JS_HAS_NATIVE_COMPARE_AND_SWAP #error "JS_HAS_NATIVE_COMPARE_AND_SWAP should be 0 if your platform lacks a compare-and-swap instruction." #endif /* arch-tests */ #if JS_HAS_NATIVE_COMPARE_AND_SWAP JSBool js_CompareAndSwap(jsword *w, jsword ov, jsword nv) { return !!NativeCompareAndSwap(w, ov, nv); } #elif defined(NSPR_LOCK) # ifdef __GNUC__ # warning "js_CompareAndSwap is implemented using NSPR lock" # endif JSBool js_CompareAndSwap(jsword *w, jsword ov, jsword nv) { int result; static PRLock *CompareAndSwapLock = JS_NEW_LOCK(); JS_ACQUIRE_LOCK(CompareAndSwapLock); result = (*w == ov); if (result) *w = nv; JS_RELEASE_LOCK(CompareAndSwapLock); return result; } #else /* !defined(NSPR_LOCK) */ #error "NSPR_LOCK should be on when the platform lacks native compare-and-swap." #endif void js_AtomicSetMask(jsword *w, jsword mask) { jsword ov, nv; do { ov = *w; nv = ov | mask; } while (!js_CompareAndSwap(w, ov, nv)); } #ifndef NSPR_LOCK struct JSFatLock { int susp; PRLock *slock; PRCondVar *svar; JSFatLock *next; JSFatLock **prevp; }; typedef struct JSFatLockTable { JSFatLock *free; JSFatLock *taken; } JSFatLockTable; #define GLOBAL_LOCK_INDEX(id) (((uint32)(jsuword)(id)>>2) & global_locks_mask) static void js_Dequeue(JSThinLock *); static PRLock **global_locks; static uint32 global_lock_count = 1; static uint32 global_locks_log2 = 0; static uint32 global_locks_mask = 0; static void js_LockGlobal(void *id) { uint32 i = GLOBAL_LOCK_INDEX(id); PR_Lock(global_locks[i]); } static void js_UnlockGlobal(void *id) { uint32 i = GLOBAL_LOCK_INDEX(id); PR_Unlock(global_locks[i]); } #endif /* !NSPR_LOCK */ void js_InitLock(JSThinLock *tl) { #ifdef NSPR_LOCK tl->owner = 0; tl->fat = (JSFatLock*)JS_NEW_LOCK(); #else PodZero(tl); #endif } void js_FinishLock(JSThinLock *tl) { #ifdef NSPR_LOCK tl->owner = 0xdeadbeef; if (tl->fat) JS_DESTROY_LOCK(((JSLock*)tl->fat)); #else JS_ASSERT(tl->owner == 0); JS_ASSERT(tl->fat == NULL); #endif } #ifdef DEBUG_SCOPE_COUNT #include <stdio.h> #include "jsdhash.h" static FILE *logfp = NULL; static JSDHashTable logtbl; typedef struct logentry { JSDHashEntryStub stub; char op; const char *file; int line; } logentry; static void logit(JSTitle *title, char op, const char *file, int line) { logentry *entry; if (!logfp) { logfp = fopen("/tmp/scope.log", "w"); if (!logfp) return; setvbuf(logfp, NULL, _IONBF, 0); } fprintf(logfp, "%p %d %c %s %d\n", title, title->u.count, op, file, line); if (!logtbl.entryStore && !JS_DHashTableInit(&logtbl, JS_DHashGetStubOps(), NULL, sizeof(logentry), 100)) { return; } entry = (logentry *) JS_DHashTableOperate(&logtbl, title, JS_DHASH_ADD); if (!entry) return; entry->stub.key = title; entry->op = op; entry->file = file; entry->line = line; } void js_unlog_title(JSTitle *title) { if (!logtbl.entryStore) return; (void) JS_DHashTableOperate(&logtbl, title, JS_DHASH_REMOVE); } # define LOGIT(title,op) logit(title, op, __FILE__, __LINE__) #else # define LOGIT(title, op) /* nothing */ #endif /* DEBUG_SCOPE_COUNT */ /* * Return true if we would deadlock waiting in ClaimTitle on * rt->titleSharingDone until ownercx finishes its request and shares a title. * * (i) rt->gcLock held */ static bool WillDeadlock(JSContext *ownercx, JSThread *thread) { JS_ASSERT(CURRENT_THREAD_IS_ME(thread)); JS_ASSERT(ownercx->thread != thread); for (;;) { JS_ASSERT(ownercx->thread); JS_ASSERT(ownercx->thread->requestContext); JSTitle *title = ownercx->thread->titleToShare; if (!title || !title->ownercx) { /* * ownercx->thread doesn't wait or has just been notified that the * title became shared. */ return false; } /* * ownercx->thread is waiting in ClaimTitle for a context from some * thread to finish its request. If that thread is the current thread, * we would deadlock. Otherwise we must recursively check if that * thread waits for the current thread. */ if (title->ownercx->thread == thread) { JS_RUNTIME_METER(ownercx->runtime, deadlocksAvoided); return true; } ownercx = title->ownercx; } } static void FinishSharingTitle(JSContext *cx, JSTitle *title); /* * Make title multi-threaded, i.e. share its ownership among contexts in rt * using a "thin" or (if necessary due to contention) "fat" lock. Called only * from ClaimTitle, immediately below, when we detect deadlock were we to wait * for title's lock, because its ownercx is waiting on a title owned by the * calling cx. * * (i) rt->gcLock held */ static void ShareTitle(JSContext *cx, JSTitle *title) { JSRuntime *rt; JSTitle **todop; rt = cx->runtime; if (title->u.link) { for (todop = &rt->titleSharingTodo; *todop != title; todop = &(*todop)->u.link) { JS_ASSERT(*todop != NO_TITLE_SHARING_TODO); } *todop = title->u.link; title->u.link = NULL; /* null u.link for sanity ASAP */ JS_NOTIFY_ALL_CONDVAR(rt->titleSharingDone); } FinishSharingTitle(cx, title); } /* * FinishSharingTitle is the tail part of ShareTitle, split out to become a * subroutine of js_ShareWaitingTitles too. The bulk of the work here involves * making mutable strings in the title's object's slots be immutable. We have * to do this because such strings will soon be available to multiple threads, * so their buffers can't be realloc'd any longer in js_ConcatStrings, and * their members can't be modified by js_ConcatStrings, JSString::undepend, or * MinimizeDependentStrings. * * The last bit of work done by this function nulls title->ownercx and updates * rt->sharedTitles. */ static void FinishSharingTitle(JSContext *cx, JSTitle *title) { js_InitLock(&title->lock); title->u.count = 0; /* NULL may not pun as 0 */ JSScope *scope = TITLE_TO_SCOPE(title); JSObject *obj = scope->object; if (obj) { uint32 nslots = scope->freeslot; JS_ASSERT(nslots >= JSSLOT_START(obj->getClass())); for (uint32 i = JSSLOT_START(obj->getClass()); i != nslots; ++i) { Value v = obj->getSlot(i); if (v.isString() && !js_MakeStringImmutable(cx, v.toString())) { /* * FIXME bug 363059: The following error recovery changes * runtime execution semantics, arbitrarily and silently * ignoring errors except out-of-memory, which should have been * reported through JS_ReportOutOfMemory at this point. */ obj->setSlot(i, UndefinedValue()); } } } title->ownercx = NULL; /* NB: set last, after lock init */ JS_RUNTIME_METER(cx->runtime, sharedTitles); } /* * Given a title with apparently non-null ownercx different from cx, try to * set ownercx to cx, claiming exclusive (single-threaded) ownership of title. * If we claim ownership, return true. Otherwise, we wait for ownercx to be * set to null (indicating that title is multi-threaded); or if waiting would * deadlock, we set ownercx to null ourselves via ShareTitle. In any case, * once ownercx is null we return false. */ static JSBool ClaimTitle(JSTitle *title, JSContext *cx) { JSRuntime *rt = cx->runtime; JS_ASSERT_IF(!cx->thread->requestContext, cx->thread == rt->gcThread && rt->gcRunning); JS_RUNTIME_METER(rt, claimAttempts); AutoLockGC lock(rt); /* Reload in case ownercx went away while we blocked on the lock. */ while (JSContext *ownercx = title->ownercx) { /* * Avoid selflock if ownercx is dead, or is not running a request, or * has the same thread as cx, or cx->thread runs the GC (in which case * all other requests must be suspended), or ownercx->thread runs a GC * and the GC waits for all requests to finish. Set title->ownercx to * cx so that the matching JS_UNLOCK_SCOPE or JS_UNLOCK_OBJ macro call * will take the fast path around the corresponding js_UnlockTitle or * js_UnlockObj function call. * * If title->u.link is non-null, title has already been inserted on * the rt->titleSharingTodo list, because another thread's context * already wanted to lock title while ownercx was running a request. * That context must still be in request and cannot be dead. Moreover, * the GC can not run at this moment as it must wait until all the * titles are shared and the threads that want to lock them finish * their requests. Thus we can claim the title if its thread matches * ours. */ bool canClaim; if (title->u.link) { JS_ASSERT(js_ValidContextPointer(rt, ownercx)); JS_ASSERT(ownercx->thread->requestContext); JS_ASSERT(!rt->gcRunning); canClaim = (ownercx->thread == cx->thread); } else { canClaim = (!js_ValidContextPointer(rt, ownercx) || !ownercx->thread || !ownercx->thread->requestContext || cx->thread == ownercx->thread || cx->thread == rt->gcThread || ownercx->thread->gcWaiting); } if (canClaim) { title->ownercx = cx; JS_RUNTIME_METER(rt, claimedTitles); return JS_TRUE; } /* * Avoid deadlock if title's owner thread is waiting on a title that * the current thread owns, by revoking title's ownership. This * approach to deadlock avoidance works because the engine never nests * title locks. * * If cx->thread could hold locks on ownercx->thread->titleToShare, or * if ownercx->thread could hold locks on title, we would need to keep * reentrancy counts for all such "flyweight" (ownercx != NULL) locks, * so that control would unwind properly once these locks became * "thin" or "fat". The engine promotes a title from exclusive to * shared access only when locking, never when holding or unlocking. */ if (WillDeadlock(ownercx, cx->thread)) { ShareTitle(cx, title); break; } /* * Thanks to the non-zero NO_TITLE_SHARING_TODO link terminator, we * can decide whether title is on rt->titleSharingTodo with a single * non-null test, and avoid double-insertion bugs. */ if (!title->u.link) { title->u.link = rt->titleSharingTodo; rt->titleSharingTodo = title; } /* * We know that some other thread's context owns title, which is now * linked onto rt->titleSharingTodo, awaiting the end of that other * thread's request. So it is safe to wait on rt->titleSharingDone. * But before waiting, we force the operation callback for that other * thread so it can quickly suspend. */ JS_THREAD_DATA(ownercx)->triggerOperationCallback(); JS_ASSERT(!cx->thread->titleToShare); cx->thread->titleToShare = title; #ifdef DEBUG PRStatus stat = #endif PR_WaitCondVar(rt->titleSharingDone, PR_INTERVAL_NO_TIMEOUT); JS_ASSERT(stat != PR_FAILURE); cx->thread->titleToShare = NULL; } return JS_FALSE; } void js_ShareWaitingTitles(JSContext *cx) { JSTitle *title, **todop; bool shared; /* See whether cx has any single-threaded titles to start sharing. */ todop = &cx->runtime->titleSharingTodo; shared = false; while ((title = *todop) != NO_TITLE_SHARING_TODO) { if (title->ownercx->thread != cx->thread) { todop = &title->u.link; continue; } *todop = title->u.link; title->u.link = NULL; /* null u.link for sanity ASAP */ FinishSharingTitle(cx, title); /* set ownercx = NULL */ shared = true; } if (shared) JS_NOTIFY_ALL_CONDVAR(cx->runtime->titleSharingDone); } /* Exported to js.c, which calls it via OBJ_GET_* and JSVAL_IS_* macros. */ JS_FRIEND_API(jsval) js_GetSlotThreadSafe(JSContext *cx, JSObject *obj, uint32 slot) { jsval v; JSScope *scope; JSTitle *title; #ifndef NSPR_LOCK JSThinLock *tl; jsword me; #endif OBJ_CHECK_SLOT(obj, slot); /* * Native object locking is inlined here to optimize the single-threaded * and contention-free multi-threaded cases. */ scope = obj->scope(); title = &scope->title; JS_ASSERT(title->ownercx != cx); JS_ASSERT(slot < scope->freeslot); /* * Avoid locking if called from the GC. Also avoid locking an object * owning a sealed scope. If neither of those special cases applies, try * to claim scope's flyweight lock from whatever context may have had it in * an earlier request. */ if (CX_THREAD_IS_RUNNING_GC(cx) || scope->sealed() || (title->ownercx && ClaimTitle(title, cx))) { return Jsvalify(obj->getSlot(slot)); } #ifndef NSPR_LOCK tl = &title->lock; me = CX_THINLOCK_ID(cx); JS_ASSERT(CURRENT_THREAD_IS_ME(me)); if (NativeCompareAndSwap(&tl->owner, 0, me)) { /* * Got the lock with one compare-and-swap. Even so, someone else may * have mutated obj so it now has its own scope and lock, which would * require either a restart from the top of this routine, or a thin * lock release followed by fat lock acquisition. */ if (scope == obj->scope()) { v = Jsvalify(obj->getSlot(slot)); if (!NativeCompareAndSwap(&tl->owner, me, 0)) { /* Assert that scope locks never revert to flyweight. */ JS_ASSERT(title->ownercx != cx); LOGIT(title, '1'); title->u.count = 1; js_UnlockObj(cx, obj); } return v; } if (!NativeCompareAndSwap(&tl->owner, me, 0)) js_Dequeue(tl); } else if (Thin_RemoveWait(ReadWord(tl->owner)) == me) { return Jsvalify(obj->getSlot(slot)); } #endif js_LockObj(cx, obj); v = Jsvalify(obj->getSlot(slot)); /* * Test whether cx took ownership of obj's scope during js_LockObj. * * This does not mean that a given scope reverted to flyweight from "thin" * or "fat" -- it does mean that obj's map pointer changed due to another * thread setting a property, requiring obj to cease sharing a prototype * object's scope (whose lock was not flyweight, else we wouldn't be here * in the first place!). */ title = &obj->scope()->title; if (title->ownercx != cx) js_UnlockTitle(cx, title); return v; } void js_SetSlotThreadSafe(JSContext *cx, JSObject *obj, uint32 slot, jsval v) { JSTitle *title; JSScope *scope; #ifndef NSPR_LOCK JSThinLock *tl; jsword me; #endif OBJ_CHECK_SLOT(obj, slot); /* Any string stored in a thread-safe object must be immutable. */ if (JSVAL_IS_STRING(v) && !js_MakeStringImmutable(cx, JSVAL_TO_STRING(v))) { /* FIXME bug 363059: See comments in js_FinishSharingScope. */ v = JSVAL_NULL; } /* * Native object locking is inlined here to optimize the single-threaded * and contention-free multi-threaded cases. */ scope = obj->scope(); title = &scope->title; JS_ASSERT(title->ownercx != cx); JS_ASSERT(slot < scope->freeslot); /* * Avoid locking if called from the GC. Also avoid locking an object * owning a sealed scope. If neither of those special cases applies, try * to claim scope's flyweight lock from whatever context may have had it in * an earlier request. */ if (CX_THREAD_IS_RUNNING_GC(cx) || scope->sealed() || (title->ownercx && ClaimTitle(title, cx))) { obj->lockedSetSlot(slot, Valueify(v)); return; } #ifndef NSPR_LOCK tl = &title->lock; me = CX_THINLOCK_ID(cx); JS_ASSERT(CURRENT_THREAD_IS_ME(me)); if (NativeCompareAndSwap(&tl->owner, 0, me)) { if (scope == obj->scope()) { obj->lockedSetSlot(slot, Valueify(v)); if (!NativeCompareAndSwap(&tl->owner, me, 0)) { /* Assert that scope locks never revert to flyweight. */ JS_ASSERT(title->ownercx != cx); LOGIT(title, '1'); title->u.count = 1; js_UnlockObj(cx, obj); } return; } if (!NativeCompareAndSwap(&tl->owner, me, 0)) js_Dequeue(tl); } else if (Thin_RemoveWait(ReadWord(tl->owner)) == me) { obj->lockedSetSlot(slot, Valueify(v)); return; } #endif js_LockObj(cx, obj); obj->lockedSetSlot(slot, Valueify(v)); /* * Same drill as above, in js_GetSlotThreadSafe. */ title = &obj->scope()->title; if (title->ownercx != cx) js_UnlockTitle(cx, title); } #ifndef NSPR_LOCK static JSFatLock * NewFatlock() { JSFatLock *fl = (JSFatLock *)js_malloc(sizeof(JSFatLock)); /* for now */ if (!fl) return NULL; fl->susp = 0; fl->next = NULL; fl->prevp = NULL; fl->slock = PR_NewLock(); fl->svar = PR_NewCondVar(fl->slock); return fl; } static void DestroyFatlock(JSFatLock *fl) { PR_DestroyLock(fl->slock); PR_DestroyCondVar(fl->svar); js_free(fl); } static JSFatLock * ListOfFatlocks(int listc) { JSFatLock *m; JSFatLock *m0; int i; JS_ASSERT(listc>0); m0 = m = NewFatlock(); for (i=1; i<listc; i++) { m->next = NewFatlock(); m = m->next; } return m0; } static void DeleteListOfFatlocks(JSFatLock *m) { JSFatLock *m0; for (; m; m=m0) { m0 = m->next; DestroyFatlock(m); } } static JSFatLockTable *fl_list_table = NULL; static uint32 fl_list_table_len = 0; static uint32 fl_list_chunk_len = 0; static JSFatLock * GetFatlock(void *id) { JSFatLock *m; uint32 i = GLOBAL_LOCK_INDEX(id); if (fl_list_table[i].free == NULL) { #ifdef DEBUG if (fl_list_table[i].taken) printf("Ran out of fat locks!\n"); #endif fl_list_table[i].free = ListOfFatlocks(fl_list_chunk_len); } m = fl_list_table[i].free; fl_list_table[i].free = m->next; m->susp = 0; m->next = fl_list_table[i].taken; m->prevp = &fl_list_table[i].taken; if (fl_list_table[i].taken) fl_list_table[i].taken->prevp = &m->next; fl_list_table[i].taken = m; return m; } static void PutFatlock(JSFatLock *m, void *id) { uint32 i; if (m == NULL) return; /* Unlink m from fl_list_table[i].taken. */ *m->prevp = m->next; if (m->next) m->next->prevp = m->prevp; /* Insert m in fl_list_table[i].free. */ i = GLOBAL_LOCK_INDEX(id); m->next = fl_list_table[i].free; fl_list_table[i].free = m; } #endif /* !NSPR_LOCK */ JSBool js_SetupLocks(int listc, int globc) { #ifndef NSPR_LOCK uint32 i; if (global_locks) return JS_TRUE; #ifdef DEBUG if (listc > 10000 || listc < 0) /* listc == fat lock list chunk length */ printf("Bad number %d in js_SetupLocks()!\n", listc); if (globc > 100 || globc < 0) /* globc == number of global locks */ printf("Bad number %d in js_SetupLocks()!\n", listc); #endif global_locks_log2 = JS_CeilingLog2(globc); global_locks_mask = JS_BITMASK(global_locks_log2); global_lock_count = JS_BIT(global_locks_log2); global_locks = (PRLock **) js_malloc(global_lock_count * sizeof(PRLock*)); if (!global_locks) return JS_FALSE; for (i = 0; i < global_lock_count; i++) { global_locks[i] = PR_NewLock(); if (!global_locks[i]) { global_lock_count = i; js_CleanupLocks(); return JS_FALSE; } } fl_list_table = (JSFatLockTable *) js_malloc(i * sizeof(JSFatLockTable)); if (!fl_list_table) { js_CleanupLocks(); return JS_FALSE; } fl_list_table_len = global_lock_count; for (i = 0; i < global_lock_count; i++) fl_list_table[i].free = fl_list_table[i].taken = NULL; fl_list_chunk_len = listc; #endif /* !NSPR_LOCK */ return JS_TRUE; } void js_CleanupLocks() { #ifndef NSPR_LOCK uint32 i; if (global_locks) { for (i = 0; i < global_lock_count; i++) PR_DestroyLock(global_locks[i]); js_free(global_locks); global_locks = NULL; global_lock_count = 1; global_locks_log2 = 0; global_locks_mask = 0; } if (fl_list_table) { for (i = 0; i < fl_list_table_len; i++) { DeleteListOfFatlocks(fl_list_table[i].free); fl_list_table[i].free = NULL; DeleteListOfFatlocks(fl_list_table[i].taken); fl_list_table[i].taken = NULL; } js_free(fl_list_table); fl_list_table = NULL; fl_list_table_len = 0; } #endif /* !NSPR_LOCK */ } #ifdef NSPR_LOCK static JS_ALWAYS_INLINE void ThinLock(JSThinLock *tl, jsword me) { JS_ACQUIRE_LOCK((JSLock *) tl->fat); tl->owner = me; } static JS_ALWAYS_INLINE void ThinUnlock(JSThinLock *tl, jsword /*me*/) { tl->owner = 0; JS_RELEASE_LOCK((JSLock *) tl->fat); } #else /* * Fast locking and unlocking is implemented by delaying the allocation of a * system lock (fat lock) until contention. As long as a locking thread A * runs uncontended, the lock is represented solely by storing A's identity in * the object being locked. * * If another thread B tries to lock the object currently locked by A, B is * enqueued into a fat lock structure (which might have to be allocated and * pointed to by the object), and suspended using NSPR conditional variables * (wait). A wait bit (Bacon bit) is set in the lock word of the object, * signalling to A that when releasing the lock, B must be dequeued and * notified. * * The basic operation of the locking primitives (js_Lock, js_Unlock, * js_Enqueue, and js_Dequeue) is compare-and-swap. Hence, when locking into * the word pointed at by p, compare-and-swap(p, 0, A) success implies that p * is unlocked. Similarly, when unlocking p, if compare-and-swap(p, A, 0) * succeeds this implies that p is uncontended (no one is waiting because the * wait bit is not set). * * When dequeueing, the lock is released, and one of the threads suspended on * the lock is notified. If other threads still are waiting, the wait bit is * kept (in js_Enqueue), and if not, the fat lock is deallocated. * * The functions js_Enqueue, js_Dequeue, js_SuspendThread, and js_ResumeThread * are serialized using a global lock. For scalability, a hashtable of global * locks is used, which is indexed modulo the thin lock pointer. */ /* * Invariants: * (i) global lock is held * (ii) fl->susp >= 0 */ static int js_SuspendThread(JSThinLock *tl) { JSFatLock *fl; PRStatus stat; if (tl->fat == NULL) fl = tl->fat = GetFatlock(tl); else fl = tl->fat; JS_ASSERT(fl->susp >= 0); fl->susp++; PR_Lock(fl->slock); js_UnlockGlobal(tl); stat = PR_WaitCondVar(fl->svar, PR_INTERVAL_NO_TIMEOUT); JS_ASSERT(stat != PR_FAILURE); PR_Unlock(fl->slock); js_LockGlobal(tl); fl->susp--; if (fl->susp == 0) { PutFatlock(fl, tl); tl->fat = NULL; } return tl->fat == NULL; } /* * (i) global lock is held * (ii) fl->susp > 0 */ static void js_ResumeThread(JSThinLock *tl) { JSFatLock *fl = tl->fat; PRStatus stat; JS_ASSERT(fl != NULL); JS_ASSERT(fl->susp > 0); PR_Lock(fl->slock); js_UnlockGlobal(tl); stat = PR_NotifyCondVar(fl->svar); JS_ASSERT(stat != PR_FAILURE); PR_Unlock(fl->slock); } static void js_Enqueue(JSThinLock *tl, jsword me) { jsword o, n; js_LockGlobal(tl); for (;;) { o = ReadWord(tl->owner); n = Thin_SetWait(o); if (o != 0 && NativeCompareAndSwap(&tl->owner, o, n)) { if (js_SuspendThread(tl)) me = Thin_RemoveWait(me); else me = Thin_SetWait(me); } else if (NativeCompareAndSwap(&tl->owner, 0, me)) { js_UnlockGlobal(tl); return; } } } static void js_Dequeue(JSThinLock *tl) { jsword o; js_LockGlobal(tl); o = ReadWord(tl->owner); JS_ASSERT(Thin_GetWait(o) != 0); JS_ASSERT(tl->fat != NULL); if (!NativeCompareAndSwap(&tl->owner, o, 0)) /* release it */ JS_ASSERT(0); js_ResumeThread(tl); } static JS_ALWAYS_INLINE void ThinLock(JSThinLock *tl, jsword me) { JS_ASSERT(CURRENT_THREAD_IS_ME(me)); if (NativeCompareAndSwap(&tl->owner, 0, me)) return; if (Thin_RemoveWait(ReadWord(tl->owner)) != me) js_Enqueue(tl, me); #ifdef DEBUG else JS_ASSERT(0); #endif } static JS_ALWAYS_INLINE void ThinUnlock(JSThinLock *tl, jsword me) { JS_ASSERT(CURRENT_THREAD_IS_ME(me)); /* * Since we can race with the NativeCompareAndSwap in js_Enqueue, we need * to use a C_A_S here as well -- Arjan van de Ven 30/1/08 */ if (NativeCompareAndSwap(&tl->owner, me, 0)) return; JS_ASSERT(Thin_GetWait(tl->owner)); if (Thin_RemoveWait(ReadWord(tl->owner)) == me) js_Dequeue(tl); #ifdef DEBUG else JS_ASSERT(0); /* unbalanced unlock */ #endif } #endif /* !NSPR_LOCK */ void js_Lock(JSContext *cx, JSThinLock *tl) { ThinLock(tl, CX_THINLOCK_ID(cx)); } void js_Unlock(JSContext *cx, JSThinLock *tl) { ThinUnlock(tl, CX_THINLOCK_ID(cx)); } void js_LockRuntime(JSRuntime *rt) { PR_Lock(rt->rtLock); #ifdef DEBUG rt->rtLockOwner = js_CurrentThreadId(); #endif } void js_UnlockRuntime(JSRuntime *rt) { #ifdef DEBUG rt->rtLockOwner = NULL; #endif PR_Unlock(rt->rtLock); } void js_LockTitle(JSContext *cx, JSTitle *title) { jsword me = CX_THINLOCK_ID(cx); JS_ASSERT(CURRENT_THREAD_IS_ME(me)); JS_ASSERT(title->ownercx != cx); if (CX_THREAD_IS_RUNNING_GC(cx)) return; if (title->ownercx && ClaimTitle(title, cx)) return; if (Thin_RemoveWait(ReadWord(title->lock.owner)) == me) { JS_ASSERT(title->u.count > 0); LOGIT(scope, '+'); title->u.count++; } else { ThinLock(&title->lock, me); JS_ASSERT(title->u.count == 0); LOGIT(scope, '1'); title->u.count = 1; } } void js_UnlockTitle(JSContext *cx, JSTitle *title) { jsword me = CX_THINLOCK_ID(cx); /* We hope compilers use me instead of reloading cx->thread in the macro. */ if (CX_THREAD_IS_RUNNING_GC(cx)) return; if (cx->lockedSealedTitle == title) { cx->lockedSealedTitle = NULL; return; } /* * If title->ownercx is not null, it's likely that two contexts not using * requests nested locks for title. The first context, cx here, claimed * title; the second, title->ownercx here, re-claimed it because the first * was not in a request, or was on the same thread. We don't want to keep * track of such nesting, because it penalizes the common non-nested case. * Instead of asserting here and silently coping, we simply re-claim title * for cx and return. * * See http://bugzilla.mozilla.org/show_bug.cgi?id=229200 for a real world * case where an asymmetric thread model (Mozilla's main thread is known * to be the only thread that runs the GC) combined with multiple contexts * per thread has led to such request-less nesting. */ if (title->ownercx) { JS_ASSERT(title->u.count == 0); JS_ASSERT(title->lock.owner == 0); title->ownercx = cx; return; } JS_ASSERT(title->u.count > 0); if (Thin_RemoveWait(ReadWord(title->lock.owner)) != me) { JS_ASSERT(0); /* unbalanced unlock */ return; } LOGIT(title, '-'); if (--title->u.count == 0) ThinUnlock(&title->lock, me); } /* * NB: oldtitle may be null if our caller is js_GetMutableScope and it just * dropped the last reference to oldtitle. */ void js_DropAllEmptyScopeLocks(JSContext *cx, JSScope *scope) { JS_ASSERT(!CX_OWNS_SCOPE_TITLE(cx,scope)); JS_ASSERT(scope->isSharedEmpty()); JS_ASSERT(JS_IS_TITLE_LOCKED(cx, &scope->title)); /* * Shared empty scope cannot be sealed so we do not need to deal with * cx->lockedSealedTitle. */ JS_ASSERT(!scope->sealed()); JS_ASSERT(cx->lockedSealedTitle != &scope->title); /* * Special case in js_LockTitle and js_UnlockTitle for the GC calling * code that locks, unlocks, or mutates. Nothing to do in these cases, * because title and newtitle were "locked" by the GC thread, so neither * was actually locked. */ if (CX_THREAD_IS_RUNNING_GC(cx)) return; /* * The title cannot be owned at this point by another cx on this or * another thread as that would imply a missing JS_LOCK_OBJ call. */ JS_ASSERT(!scope->title.ownercx); LOGIT(&scope->title, '0'); scope->title.u.count = 0; ThinUnlock(&scope->title.lock, CX_THINLOCK_ID(cx)); } void js_LockObj(JSContext *cx, JSObject *obj) { JSScope *scope; JSTitle *title; JS_ASSERT(obj->isNative()); /* * We must test whether the GC is calling and return without mutating any * state, especially cx->lockedSealedScope. Note asymmetry with respect to * js_UnlockObj, which is a thin-layer on top of js_UnlockTitle. */ if (CX_THREAD_IS_RUNNING_GC(cx)) return; for (;;) { scope = obj->scope(); title = &scope->title; if (scope->sealed() && !cx->lockedSealedTitle) { cx->lockedSealedTitle = title; return; } js_LockTitle(cx, title); /* If obj still has this scope, we're done. */ if (scope == obj->scope()) return; /* Lost a race with a mutator; retry with obj's new scope. */ js_UnlockTitle(cx, title); } } void js_UnlockObj(JSContext *cx, JSObject *obj) { JS_ASSERT(obj->isNative()); js_UnlockTitle(cx, &obj->scope()->title); } void js_InitTitle(JSContext *cx, JSTitle *title) { #ifdef JS_THREADSAFE title->ownercx = cx; js_InitLock(&title->lock); /* * Set u.link = NULL, not u.count = 0, in case the target architecture's * null pointer has a non-zero integer representation. */ title->u.link = NULL; #ifdef JS_DEBUG_TITLE_LOCKS title->file[0] = title->file[1] = title->file[2] = title->file[3] = NULL; title->line[0] = title->line[1] = title->line[2] = title->line[3] = 0; #endif #endif } void js_FinishTitle(JSContext *cx, JSTitle *title) { #ifdef DEBUG_SCOPE_COUNT js_unlog_title(title); #endif #ifdef JS_THREADSAFE /* Title must be single-threaded at this point, so set ownercx. */ JS_ASSERT(title->u.count == 0); title->ownercx = cx; js_FinishLock(&title->lock); #endif } #ifdef DEBUG JSBool js_IsRuntimeLocked(JSRuntime *rt) { return js_CurrentThreadId() == rt->rtLockOwner; } JSBool js_IsObjLocked(JSContext *cx, JSObject *obj) { return js_IsTitleLocked(cx, &obj->scope()->title); } JSBool js_IsTitleLocked(JSContext *cx, JSTitle *title) { /* Special case: the GC locking any object's title, see js_LockTitle. */ if (CX_THREAD_IS_RUNNING_GC(cx)) return JS_TRUE; /* Special case: locked object owning a sealed scope, see js_LockObj. */ if (cx->lockedSealedTitle == title) return JS_TRUE; /* * General case: the title is either exclusively owned by some context, or * it has a thin or fat lock to cope with shared (concurrent) ownership. * * js_LockTitle(cx, title) must set ownercx to cx when claiming the title * from another context on the same thread. */ if (title->ownercx) return title->ownercx == cx; return js_CurrentThreadId() == ((JSThread *)Thin_RemoveWait(ReadWord(title->lock.owner)))->id; } #ifdef JS_DEBUG_TITLE_LOCKS void js_SetScopeInfo(JSScope *scope, const char *file, int line) { JSTitle *title = &scope->title; if (!title->ownercx) { jsrefcount count = title->u.count; JS_ASSERT_IF(!scope->sealed(), count > 0); JS_ASSERT(count <= 4); title->file[count - 1] = file; title->line[count - 1] = line; } } #endif /* JS_DEBUG_TITLE_LOCKS */ #endif /* DEBUG */ #endif /* JS_THREADSAFE */
28.377385
106
0.624819
[ "object", "model" ]
b9517e1cc863c1da5a02f798e1cb67e7b400b09c
6,271
cc
C++
paddle/fluid/operators/abs_op.cc
RangeKing/Paddle
2d87300809ae75d76f5b0b457d8112cb88dc3e27
[ "Apache-2.0" ]
8
2016-08-15T07:02:27.000Z
2016-08-24T09:34:00.000Z
paddle/fluid/operators/abs_op.cc
RangeKing/Paddle
2d87300809ae75d76f5b0b457d8112cb88dc3e27
[ "Apache-2.0" ]
1
2022-01-28T07:23:22.000Z
2022-01-28T07:23:22.000Z
paddle/fluid/operators/abs_op.cc
RangeKing/Paddle
2d87300809ae75d76f5b0b457d8112cb88dc3e27
[ "Apache-2.0" ]
null
null
null
// Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <memory> #include <string> #include <unordered_map> #include <vector> #include "paddle/fluid/framework/infershape_utils.h" #include "paddle/fluid/framework/op_registry.h" #include "paddle/phi/core/infermeta_utils.h" #include "paddle/phi/infermeta/unary.h" #ifdef PADDLE_WITH_MKLDNN #include "paddle/fluid/platform/mkldnn_helper.h" #endif namespace paddle { namespace operators { class AbsOp : public framework::OperatorWithKernel { public: using framework::OperatorWithKernel::OperatorWithKernel; framework::OpKernelType GetExpectedKernelType( const framework::ExecutionContext& ctx) const override { auto input_data_type = framework::OperatorWithKernel::IndicateVarDataType(ctx, "X"); #ifdef PADDLE_WITH_MKLDNN if (this->CanMKLDNNBeUsed(ctx, input_data_type)) { return framework::OpKernelType(input_data_type, ctx.GetPlace(), framework::DataLayout::kMKLDNN, framework::LibraryType::kMKLDNN); } #endif return framework::OpKernelType(input_data_type, ctx.GetPlace()); } }; class AbsOpMaker : public framework::OpProtoAndCheckerMaker { public: void Make() override { AddInput("X", "(Tensor), The input tensor of abs op."); AddOutput("Out", "(Tensor), The output tensor of abs op."); AddAttr<bool>("use_mkldnn", "(bool, default false) Only used in mkldnn kernel") .SetDefault(false) .AsExtra(); AddAttr<bool>("use_cudnn", "(bool, default false) Only used in cudnn kernel, need " "install cudnn") .SetDefault(false) .AsExtra(); AddComment(R"DOC( Abs Operator. This operator is used to perform elementwise abs for input $X$. $$out = |x|$$ )DOC"); } }; class AbsGradOp : public framework::OperatorWithKernel { public: using framework::OperatorWithKernel::OperatorWithKernel; void InferShape(framework::InferShapeContext* ctx) const override { OP_INOUT_CHECK(ctx->HasInput(framework::GradVarName("Out")), "Input", "Out@Grad", "AbsGrad"); OP_INOUT_CHECK(ctx->HasOutput(framework::GradVarName("X")), "Output", "X@Grad", "AbsGrad"); auto dout_dims = ctx->GetInputDim(framework::GradVarName("Out")); ctx->SetOutputDim(framework::GradVarName("X"), dout_dims); } protected: framework::OpKernelType GetExpectedKernelType( const framework::ExecutionContext& ctx) const override { auto input_data_type = framework::OperatorWithKernel::IndicateVarDataType(ctx, "X"); #ifdef PADDLE_WITH_MKLDNN if (this->CanMKLDNNBeUsed(ctx, input_data_type)) { return framework::OpKernelType(input_data_type, ctx.GetPlace(), framework::DataLayout::kMKLDNN, framework::LibraryType::kMKLDNN); } #endif return framework::OpKernelType(input_data_type, ctx.GetPlace()); } }; template <typename T> class AbsGradMaker : public framework::SingleGradOpMaker<T> { public: using framework::SingleGradOpMaker<T>::SingleGradOpMaker; void Apply(GradOpPtr<T> retv) const override { retv->SetType("abs_grad"); retv->SetInput(framework::GradVarName("Out"), this->OutputGrad("Out")); retv->SetInput("X", this->Input("X")); retv->SetAttrMap(this->Attrs()); retv->SetOutput(framework::GradVarName("X"), this->InputGrad("X")); } }; // AbsGrad: dx=dy if x >=0 else -dy // AbsDoubleGrad: ddy = ddx if x >=0 else -ddx template <typename T> class AbsDoubleGradMaker : public framework::SingleGradOpMaker<T> { public: using ::paddle::framework::SingleGradOpMaker<T>::SingleGradOpMaker; protected: void Apply(GradOpPtr<T> op) const override { op->SetType("abs_double_grad"); // input1: x op->SetInput("X", this->Input("X")); // input2: ddx op->SetInput("DDX", this->OutputGrad(framework::GradVarName("X"))); op->SetAttrMap(this->Attrs()); // output: ddy op->SetOutput("DDOut", this->InputGrad(framework::GradVarName("Out"))); } }; class AbsDoubleGradOp : public framework::OperatorWithKernel { public: using framework::OperatorWithKernel::OperatorWithKernel; void InferShape(framework::InferShapeContext* ctx) const override { if (ctx->HasOutput("DDOut")) { ctx->ShareDim("X", "DDOut"); ctx->ShareLoD("X", "DDOut"); } } protected: framework::OpKernelType GetExpectedKernelType( const framework::ExecutionContext& ctx) const override { auto dtype = OperatorWithKernel::IndicateVarDataType(ctx, "DDX"); return framework::OpKernelType(dtype, ctx.GetPlace()); } framework::OpKernelType GetKernelTypeForVar( const std::string& var_name, const framework::Tensor& tensor, const framework::OpKernelType& expected_kernel_type) const { return framework::OpKernelType( framework::TransToProtoVarType(tensor.dtype()), tensor.place(), tensor.layout()); } }; } // namespace operators } // namespace paddle DECLARE_INFER_SHAPE_FUNCTOR(abs, AbsInferShapeFunctor, PD_INFER_META(phi::RealAndImagInferMeta)); namespace ops = paddle::operators; REGISTER_OPERATOR(abs, ops::AbsOp, ops::AbsOpMaker, ops::AbsGradMaker<paddle::framework::OpDesc>, ops::AbsGradMaker<paddle::imperative::OpBase>, AbsInferShapeFunctor); REGISTER_OPERATOR(abs_grad, ops::AbsGradOp, ops::AbsDoubleGradMaker<paddle::framework::OpDesc>, ops::AbsDoubleGradMaker<paddle::imperative::OpBase>); REGISTER_OPERATOR(abs_double_grad, ops::AbsDoubleGradOp);
34.26776
75
0.681869
[ "vector" ]
b9583a001b45c371f3c626aae2626c3648f64945
16,835
cc
C++
test/test01.cc
efocht/vetfkernel
afd71347d6533cc71ff853c2252b3e546aa22de6
[ "BSD-2-Clause" ]
1
2019-12-12T09:44:17.000Z
2019-12-12T09:44:17.000Z
test/test01.cc
efocht/vetfkernel
afd71347d6533cc71ff853c2252b3e546aa22de6
[ "BSD-2-Clause" ]
null
null
null
test/test01.cc
efocht/vetfkernel
afd71347d6533cc71ff853c2252b3e546aa22de6
[ "BSD-2-Clause" ]
null
null
null
#include <string> #include <vector> #include <sstream> #include <cstdio> #include <cstdint> #include <cstdlib> // copy from src/binary_ops.cc struct _Tensor { int dtype; uint64_t addr; int32_t dims; int64_t nelems; int64_t dim_size[8]; std::string to_s() const { std::stringstream s; s << "[dtype=" << dtype << ",dims=" << dims << "["; for (int i = 0; i < dims; ++i) s << " " << dim_size[i]; s << " ],nelems=" << nelems << "]"; return s.str(); } }; struct BinaryOpArgs { _Tensor in0; _Tensor in1; _Tensor out; }; template<typename T> struct dypte_s {}; template<> struct dypte_s<float> { static const int type = 1; }; template <typename T> _Tensor makeTensor(size_t dims, std::vector<size_t> const& dim_size) { _Tensor t; t.dtype = dypte_s<T>::type; t.dims = dims; t.nelems = 1; for (int i = 0; i < dims; ++i) { t.dim_size[i] = dim_size[i]; t.nelems *= dim_size[i]; } t.addr = reinterpret_cast<uint64_t>(new T[t.nelems]); return t; } template<typename T> class Tensor { public: Tensor(std::vector<size_t> const& shape) { shape_ = shape; t = makeTensor<T>(shape.size(), shape); stride_.resize(shape.size()); size_t dim = t.dims; stride_[dim - 1] = 1; for (int i = dim - 2; i >= 0; --i) { stride_[i] = stride_[i + 1] * t.dim_size[i + 1]; } } ~Tensor() { delete[] reinterpret_cast<T*>(t.addr); } std::vector<size_t> const& shape() const { return shape_; } T* data() { return reinterpret_cast<T*>(t.addr); } T const* data() const { return reinterpret_cast<T const*>(t.addr); } size_t nelems() const { return t.nelems; } size_t dims() const { return t.dims; } size_t dim_size(size_t i) const { return t.dim_size[i]; } size_t stride(size_t i) const { return stride_[i]; } _Tensor tensor() const { return t; } private: _Tensor t; std::vector<size_t> stride_; std::vector<size_t> shape_; }; template<typename T> bool checkTensor(Tensor<T> const& a, Tensor<T> const& b) { if (a.nelems() != b.nelems()) return false; for (size_t i = 0; i < a.nelems(); ++i) if (a.data()[i] != b.data()[i]) return false; return true; } template<typename T> void printTensor(Tensor<T> const& t, std::string fmt = " %8.3f") { std::vector<size_t> s(t.dims() + 1); s[t.dims()] = 1; for (int i = t.dims() - 1; i >= 0; --i) s[i] = s[i + 1] * t.dim_size(i); #if 0 fprintf(stderr, "%d %d %d\n", t.dim_size(0), t.dim_size(1), t.dim_size(2)); fprintf(stderr, "%d %d %d\n", s[0], s[1], s[2]); #endif float const* p = t.data(); size_t n = t.dim_size(t.dims() - 1); // innermost for (size_t i = 0; i < t.nelems(); ++i) { if (i % n == 0) { for (int j = 0; j < t.dims(); ++j) { fprintf(stderr, "%c", i % s[j] == 0 ? '[' : ' '); } } fprintf(stderr, fmt.c_str(), p[i]); if ((i + 1) % n == 0) { fprintf(stderr, " "); for (int j = 0; j < t.dims(); ++j) { if ((i + 1) % s[j] == 0) fprintf(stderr, "]"); } fprintf(stderr, "\n"); } } } struct TestParam { int verbose; }; extern "C" { int op_Add(const void* args, size_t len); int op_Sub(const void* args, size_t len); int op_Mul(const void* args, size_t len); int op_SquaredDifference(const void* args, size_t len); } template<typename T> bool test_BinaryOp(TestParam const& param, Tensor<T>& out, Tensor<T> const& in0, Tensor<T> const& in1, Tensor<T> const& exp, int (*op)(const void* args, size_t len)) { BinaryOpArgs args; args.out = out.tensor(); args.in0 = in0.tensor(); args.in1 = in1.tensor(); int ret = op(&args, sizeof(args)); bool flag = false; if (ret == 0) flag = checkTensor(out, exp); if (param.verbose > 1 || (!flag && param.verbose > 0)) { fprintf(stderr, "in0 = \n"); printTensor(in0); fprintf(stderr, "in1 = \n"); printTensor(in1); fprintf(stderr, "in0 + in1 = \n"); printTensor(out); fprintf(stderr, "expected = \n"); printTensor(exp); } return flag; } template <typename T, typename F> int ref_Binop(Tensor<T>& X, Tensor<T> const& Y, Tensor<T> const& Z, F op, T* pX, T const* pY, T const* pZ, int dim) { //fprintf(stderr, "%s: dim=%d X.stride[%d]=%d\n", __FUNCTION__, dim, dim, X.stride(dim)); if (dim + 1 == X.dims()) { for (size_t i = 0; i < X.dim_size(dim); ++i) { T y = pY[i % Y.dim_size(dim)]; T z = pZ[i % Z.dim_size(dim)]; pX[i] = op(y, z); //fprintf(stderr, "%s: %8.3f = %8.3f op %8.3f\n", __FUNCTION__, pX[i], y, z); } } else { for (size_t i = 0; i < X.dim_size(dim); ++i) { #if 0 fprintf(stderr, "%s: dim=%d X.dim_size[%d]=%d i=%d %d %d\n", __FUNCTION__, dim, dim, X.dim_size(dim), i, Y.dim_size(dim), Y.stride(dim)); #endif T* pX0 = pX + i * X.stride(dim); T const* pY0 = pY + (i % Y.dim_size(dim)) * Y.stride(dim); T const* pZ0 = pZ + (i % Z.dim_size(dim)) * Z.stride(dim); ref_Binop(X, Y, Z, op, pX0, pY0, pZ0, dim + 1); } } return 0; } template <typename T, typename F> int ref_Binop(Tensor<T>& X, Tensor<T> const& Y, Tensor<T> const& Z, F op) { return ref_Binop(X, Y, Z, op, X.data(), Y.data(), Z.data(), 0); } template <typename T> int ref_Add(Tensor<T>& X, Tensor<T> const& Y, Tensor<T> const& Z) { return ref_Binop(X, Y, Z, [](T y, T z) -> T { return y + z; }, X.data(), Y.data(), Z.data(), 0); } template <typename T> int ref_Sub(Tensor<T>& X, Tensor<T> const& Y, Tensor<T> const& Z) { return ref_Binop(X, Y, Z, [](T y, T z) -> T { return y - z; }, X.data(), Y.data(), Z.data(), 0); } template <typename T> int ref_Mul(Tensor<T>& X, Tensor<T> const& Y, Tensor<T> const& Z) { return ref_Binop(X, Y, Z, [](T y, T z) -> T { return y * z; }, X.data(), Y.data(), Z.data(), 0); } template <typename T> int ref_SquaredDifference(Tensor<T>& X, Tensor<T> const& Y, Tensor<T> const& Z) { return ref_Binop(X, Y, Z, [](T y, T z) -> T { return (y - z) * (y - z); }, X.data(), Y.data(), Z.data(), 0); } bool test_Add_01(TestParam const& param) { Tensor<float> out({1, 5, 10}); Tensor<float> in0({1, 5, 10}); Tensor<float> in1({1, 1, 10}); Tensor<float> exp({1, 5, 10}); int c = 0; for (size_t i = 0; i < 5; ++i) { for (size_t j = 0; j < 10; ++j) { out.data()[i * 10 + j] = 0; in0.data()[i * 10 + j] = c; ++c; } } for (size_t i = 0; i < 1; ++i) { for (size_t j = 0; j < 10; ++j) { in1.data()[j] = j * 100; } } ref_Add(exp, in0, in1); return test_BinaryOp(param, out, in0, in1, exp, op_Add); } bool test_Add_02(TestParam const& param) { Tensor<float> out({1, 5, 10}); Tensor<float> in0({1, 5, 10}); Tensor<float> in1({1, 5, 1}); Tensor<float> exp({1, 5, 10}); int c = 0; for (size_t i = 0; i < 5; ++i) { for (size_t j = 0; j < 10; ++j) { out.data()[i * 10 + j] = 0; in0.data()[i * 10 + j] = c; //exp.data()[i * 10 + j] = c + i * 100; ++c; } } for (size_t i = 0; i < 5; ++i) { for (size_t j = 0; j < 1; ++j) { in1.data()[i] = i * 100; } } ref_Add(exp, in0, in1); return test_BinaryOp(param, out, in0, in1, exp, op_Add); } bool test_Add_03(TestParam const& param) { Tensor<float> out({2, 3, 10}); Tensor<float> in0({2, 1, 10}); Tensor<float> in1({1, 3, 1}); Tensor<float> exp({2, 3, 10}); for (size_t i = 0; i < out.nelems(); ++i) out.data()[i] = 0; int c = 0; for (size_t i = 0; i < 2; ++i) { for (size_t j = 0; j < 10; ++j) { in0.data()[i * 10 + j] = i * 10 + j; } } for (size_t i = 0; i < 3; ++i) { in1.data()[i] = i * 100; } ref_Add(exp, in0, in1); return test_BinaryOp(param, out, in0, in1, exp, op_Add); } template<typename T, typename F0, typename F1> bool test_BinaryOp_04(TestParam const& param, F0 f0, F1 f1) { Tensor<T> out({8, 16, 16, 32, 32}); Tensor<T> in0({8, 16, 16, 32, 32}); Tensor<T> in1({1, 16, 16, 1, 1}); Tensor<T> exp({8, 16, 16, 32, 32}); for (size_t i = 0; i < out.nelems(); ++i) out.data()[i] = 0; for (size_t i = 0; i < in0.nelems(); ++i) in0.data()[i] = (T)drand48(); for (size_t i = 0; i < in1.nelems(); ++i) in1.data()[i] = (T)drand48(); f0(exp, in0, in1); return test_BinaryOp(param, out, in0, in1, exp, f1); } template<typename T, typename F0, typename F1> bool test_BinaryOp_05(TestParam const& param, F0 f0, F1 f1) { Tensor<T> out({8, 16, 64, 8, 8}); Tensor<T> in0({8, 16, 64, 8, 8}); Tensor<T> in1({1, 16, 64, 1, 1}); Tensor<T> exp({8, 16, 64, 8, 8}); for (size_t i = 0; i < out.nelems(); ++i) out.data()[i] = 0; for (size_t i = 0; i < in0.nelems(); ++i) in0.data()[i] = (T)drand48(); for (size_t i = 0; i < in1.nelems(); ++i) in1.data()[i] = (T)drand48(); f0(exp, in0, in1); return test_BinaryOp(param, out, in0, in1, exp, f1); } template<typename T, typename F0, typename F1> bool test_BinaryOp_06(TestParam const& param, F0 f0, F1 f1) { Tensor<T> out({8, 16, 64, 8, 8}); Tensor<T> in0({8, 16, 64, 8, 8}); Tensor<T> in1({1, 1, 64, 1, 1}); Tensor<T> exp({8, 16, 64, 8, 8}); for (size_t i = 0; i < out.nelems(); ++i) out.data()[i] = 0; for (size_t i = 0; i < in0.nelems(); ++i) in0.data()[i] = (T)drand48(); for (size_t i = 0; i < in1.nelems(); ++i) in1.data()[i] = (T)drand48(); f0(exp, in0, in1); return test_BinaryOp(param, out, in0, in1, exp, f1); } template<typename T, typename F0, typename F1> bool test_BinaryOp_07(TestParam const& param, F0 f0, F1 f1) { Tensor<T> out({8, 16, 32, 16, 16}); Tensor<T> in0({8, 16, 32, 16, 16}); Tensor<T> in1({1, 16, 32, 1, 1}); Tensor<T> exp({8, 16, 32, 16, 16}); for (size_t i = 0; i < out.nelems(); ++i) out.data()[i] = 0; for (size_t i = 0; i < in0.nelems(); ++i) in0.data()[i] = (T)drand48(); for (size_t i = 0; i < in1.nelems(); ++i) in1.data()[i] = (T)drand48(); f0(exp, in0, in1); return test_BinaryOp(param, out, in0, in1, exp, f1); } template<typename T, typename F0, typename F1> bool test_BinaryOp_08(TestParam const& param, F0 f0, F1 f1) { Tensor<T> out({8, 16, 32, 16, 16}); Tensor<T> in0({8, 16, 32, 16, 16}); Tensor<T> in1({1, 1, 32, 1, 1}); Tensor<T> exp({8, 16, 32, 16, 16}); for (size_t i = 0; i < out.nelems(); ++i) out.data()[i] = 0; for (size_t i = 0; i < in0.nelems(); ++i) in0.data()[i] = (T)drand48(); for (size_t i = 0; i < in1.nelems(); ++i) in1.data()[i] = (T)drand48(); f0(exp, in0, in1); return test_BinaryOp(param, out, in0, in1, exp, f1); } template<typename T, typename F0, typename F1> bool test_BinaryOp_09(TestParam const& param, F0 f0, F1 f1) { Tensor<T> out({1, 16, 64, 1, 1}); Tensor<T> in0({1, 16, 64, 1, 1}); Tensor<T> in1({1, 1, 64, 1, 1}); Tensor<T> exp({1, 16, 64, 1, 1}); for (size_t i = 0; i < out.nelems(); ++i) out.data()[i] = 0; for (size_t i = 0; i < in0.nelems(); ++i) in0.data()[i] = (T)drand48(); for (size_t i = 0; i < in1.nelems(); ++i) in1.data()[i] = (T)drand48(); f0(exp, in0, in1); return test_BinaryOp(param, out, in0, in1, exp, f1); } template<typename T, typename F0, typename F1> bool test_BinaryOp_10(TestParam const& param, F0 f0, F1 f1) { Tensor<T> out({1, 16, 16, 1, 1}); Tensor<T> in0({1, 16, 16, 1, 1}); Tensor<T> in1({1, 1, 16, 1, 1}); Tensor<T> exp({1, 16, 16, 1, 1}); for (size_t i = 0; i < out.nelems(); ++i) out.data()[i] = 0; for (size_t i = 0; i < in0.nelems(); ++i) in0.data()[i] = (T)drand48(); for (size_t i = 0; i < in1.nelems(); ++i) in1.data()[i] = (T)drand48(); f0(exp, in0, in1); return test_BinaryOp(param, out, in0, in1, exp, f1); } template<typename T, typename F0, typename F1> bool test_BinaryOp_11(TestParam const& param, F0 f0, F1 f1) { Tensor<T> out({1, 16, 32, 1, 1}); Tensor<T> in0({1, 16, 32, 1, 1}); Tensor<T> in1({1, 1, 32, 1, 1}); Tensor<T> exp({1, 16, 32, 1, 1}); for (size_t i = 0; i < out.nelems(); ++i) out.data()[i] = 0; for (size_t i = 0; i < in0.nelems(); ++i) in0.data()[i] = (T)drand48(); for (size_t i = 0; i < in1.nelems(); ++i) in1.data()[i] = (T)drand48(); f0(exp, in0, in1); return test_BinaryOp(param, out, in0, in1, exp, f1); } template<typename T, typename F0, typename F1> bool test_BinaryOp_12(TestParam const& param, F0 f0, F1 f1) { Tensor<T> out({8, 16, 16, 32, 32}); Tensor<T> in0({8, 16, 16, 32, 32}); Tensor<T> in1({1, 1, 16, 1, 1}); Tensor<T> exp({8, 16, 16, 32, 32}); for (size_t i = 0; i < out.nelems(); ++i) out.data()[i] = 0; for (size_t i = 0; i < in0.nelems(); ++i) in0.data()[i] = (T)drand48(); for (size_t i = 0; i < in1.nelems(); ++i) in1.data()[i] = (T)drand48(); f0(exp, in0, in1); return test_BinaryOp(param, out, in0, in1, exp, f1); } bool test_Add_04(TestParam const& param) { return test_BinaryOp_04<float>(param, ref_Add<float>, op_Add); } bool test_Add_05(TestParam const& param) { return test_BinaryOp_05<float>(param, ref_Add<float>, op_Add); } bool test_Add_06(TestParam const& param) { return test_BinaryOp_06<float>(param, ref_Add<float>, op_Add); } bool test_Sub_04(TestParam const& param) { return test_BinaryOp_04<float>(param, ref_Sub<float>, op_Sub); } bool test_Sub_05(TestParam const& param) { return test_BinaryOp_05<float>(param, ref_Sub<float>, op_Sub); } bool test_Mul_04(TestParam const& param) { return test_BinaryOp_04<float>(param, ref_Mul<float>, op_Mul); } bool test_Mul_05(TestParam const& param) { return test_BinaryOp_05<float>(param, ref_Mul<float>, op_Mul); } bool test_Mul_06(TestParam const& param) { return test_BinaryOp_06<float>(param, ref_Mul<float>, op_Mul); } bool test_Mul_07(TestParam const& param) { return test_BinaryOp_07<float>(param, ref_Mul<float>, op_Mul); } bool test_Mul_08(TestParam const& param) { return test_BinaryOp_08<float>(param, ref_Mul<float>, op_Mul); } bool test_Mul_09(TestParam const& param) { return test_BinaryOp_09<float>(param, ref_Mul<float>, op_Mul); } bool test_Mul_10(TestParam const& param) { return test_BinaryOp_10<float>(param, ref_Mul<float>, op_Mul); } bool test_Mul_11(TestParam const& param) { return test_BinaryOp_11<float>(param, ref_Mul<float>, op_Mul); } bool test_Mul_12(TestParam const& param) { return test_BinaryOp_12<float>(param, ref_Mul<float>, op_Mul); } bool test_SquaredDifference_05(TestParam const& param) { return test_BinaryOp_05<float>(param, ref_SquaredDifference<float>, op_SquaredDifference); } struct Test { std::string name; bool (*func)(TestParam const&); }; extern "C" { int get_num_kernels(); } int main(int argc, char* argv[]) { fprintf(stderr, "num_kernels=%d\n", get_num_kernels()); Test tests[] = { "op_Add_01", test_Add_01, "op_Add_02", test_Add_02, "op_Add_03", test_Add_03, "op_Add_04", test_Add_04, "op_Add_05", test_Add_05, "op_Add_06", test_Add_06, "op_Sub_04", test_Sub_04, "op_Sub_05", test_Sub_05, "op_Mul_04", test_Mul_04, "op_Mul_05", test_Mul_05, "op_Mul_06", test_Mul_06, "op_Mul_07", test_Mul_07, "op_Mul_08", test_Mul_08, "op_Mul_09", test_Mul_09, "op_Mul_10", test_Mul_10, "op_Mul_11", test_Mul_11, "op_Mul_12", test_Mul_12, "op_SquaredDifference_05", test_SquaredDifference_05, }; TestParam param; param.verbose = 0; for (int i = 1; i < argc; ++i) { if (strcmp(argv[i], "-v") == 0) { ++param.verbose; } } int ntests = sizeof(tests) / sizeof(Test); int ok = 0; for (size_t i = 0; i < ntests; ++i) { bool flag = tests[i].func(param); fprintf(stderr, "%-20s %s\n", tests[i].name.c_str(), flag ? "OK" : "NG"); if (flag) ++ok; } fprintf(stderr, "%d tests failed\n", ntests - ok); return 0; }
25.74159
100
0.538462
[ "shape", "vector" ]
b95b8651b5c567aad85e24c1294b7cc76a0f7f6e
3,499
cpp
C++
CodeForces/Solutions/296E.cpp
Shefin-CSE16/Competitive-Programming
7c792081ae1d4b7060893165de34ffe7b9b7caed
[ "MIT" ]
5
2020-10-03T17:15:26.000Z
2022-03-29T21:39:22.000Z
CodeForces/Solutions/295C.cpp
Shefin-CSE16/Competitive-Programming
7c792081ae1d4b7060893165de34ffe7b9b7caed
[ "MIT" ]
null
null
null
CodeForces/Solutions/295C.cpp
Shefin-CSE16/Competitive-Programming
7c792081ae1d4b7060893165de34ffe7b9b7caed
[ "MIT" ]
1
2021-03-01T12:56:50.000Z
2021-03-01T12:56:50.000Z
// #pragma GCC optimize("Ofast,unroll-loops") // #pragma GCC target("avx,avx2,fma") #include <bits/stdc++.h> using namespace std; #define ll long long #define ull unsigned long long #define dd double #define ld long double #define sl(n) scanf("%lld", &n) #define si(n) scanf("%d", &n) #define sd(n) scanf("%lf", &n) #define pll pair <ll, ll> #define pii pair <int, int> #define mp make_pair #define pb push_back #define all(v) v.begin(), v.end() #define inf (1LL << 62) #define loop(i, start, stop, inc) for(ll i = start; i <= stop; i += inc) #define for1(i, stop) for(ll i = 1; i <= stop; i++) #define for0(i, stop) for(ll i = 0; i < stop; i++) #define rep1(i, start) for(ll i = start; i >= 1; i--) #define rep0(i, start) for(ll i = (start-1); i >= 0; i--) #define ms(n, i) memset(n, i, sizeof(n)) #define casep(n) printf("Case %lld:", ++n) #define pn printf("\n") #define pf printf #define EL '\n' #define fastio std::ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL); const ll sz = 52, mod = 1e9 + 7; ll lev[sz][sz][2], dp[sz][sz][2], nCr[sz][sz]; struct node { int one, two; bool side; }; vector <node> par[sz][sz][2]; ll one, two, n, k; ll bfs() { for0(i, sz) for0(j, sz) lev[i][j][0] = lev[i][j][1] = inf; queue <node> q; q.push({one, two, 0}); lev[one][two][0] = 0; while(!q.empty()) { node u = q.front(); q.pop(); ll none = u.one, ntwo = u.two, lv = lev[u.one][u.two][u.side]; if(u.side) none = one - none, ntwo = two - ntwo; for(ll i = 0; i <= none; i++) { if(i > k) break; for(ll j = 0; j <= ntwo; j++) { if(i == 0 && j == 0) continue; if(i + 2*j > k) break; ll nxone, nxtwo; if(u.side) nxone = u.one + i, nxtwo = u.two + j; else nxone = u.one - i, nxtwo = u.two - j; if(lev[nxone][nxtwo][u.side^1] > lv + 1) { q.push({nxone, nxtwo, u.side^1}); lev[nxone][nxtwo][u.side^1] = lv + 1; par[nxone][nxtwo][u.side^1].pb(u); } else if(lev[nxone][nxtwo][u.side^1] == lv + 1) { lev[nxone][nxtwo][u.side^1] = lv + 1; par[nxone][nxtwo][u.side^1].pb(u); } } } } if(lev[0][0][1] == inf) return -1; return lev[0][0][1]; } ll solve(ll on, ll tw, bool side) { if(par[on][tw][side].size() == 0) return 1; ll &ret = dp[on][tw][side]; if(ret != -1) return ret; ll rt = 0, none = on, ntwo = tw; if(side) none = one - none, ntwo = two - ntwo; for(node &nd : par[on][tw][side]) { ll way, passOne = abs(on - nd.one), passTwo = abs(tw - nd.two); way = (nCr[none][passOne] * nCr[ntwo][passTwo]) % mod; way = (way * solve(nd.one, nd.two, nd.side)) % mod; rt = (rt + way) % mod; } return ret = rt; } int main() { nCr[0][0] = 1; for(ll i = 1; i < sz; i++) { nCr[i][0] = nCr[i][i] = 1; for(ll j = 1; j < i; j++) nCr[i][j] = (nCr[i-1][j-1] + nCr[i-1][j]) % mod; } cin >> n >> k; k /= 50; for1(i, n) { ll w; sl(w); if(w == 50) one++; else two++; } ll ride = bfs(); if(ride == -1) { cout << -1 << EL << 0 << EL; return 0; } ms(dp, -1); cout << ride << EL; cout << solve(0, 0, 1) << EL; return 0; }
25.355072
82
0.468134
[ "vector" ]
b95cec47297aad04e6f95b731b28d7163a756129
2,658
hh
C++
include/WCSimLikelihoodDigit.hh
chipsneutrino/chips-reco
0d9e7e8a1dd749a2b0b0d64eabf0b32d895f19ba
[ "MIT" ]
null
null
null
include/WCSimLikelihoodDigit.hh
chipsneutrino/chips-reco
0d9e7e8a1dd749a2b0b0d64eabf0b32d895f19ba
[ "MIT" ]
null
null
null
include/WCSimLikelihoodDigit.hh
chipsneutrino/chips-reco
0d9e7e8a1dd749a2b0b0d64eabf0b32d895f19ba
[ "MIT" ]
null
null
null
/** * \class * This class holds hit information for a single PMT * such as its position, orientation, recorded charge * and hit time. WCSimAnalysis interfaces with hits * from WCSim using this class. */ #pragma once #include <vector> #include "WCSimDetectorParameters.hh" #include "WCSimRootEvent.hh" #include "TClonesArray.h" #include "TObject.h" #include "TVector3.h" #include "TString.h" class TGraph; class WCSimLikelihoodDigit : public TObject { public: /** * Constructor * @param x PMT x co-ordinate * @param y PMT y co-ordinate * @param z PMT x co-ordinate * @param t Time of hit * @param Q Recorded charge (P.E.) * @param tubeId Unique PMT ID number from WCSim * @param faceX x co-ordinate of PMT normal * @param faceY y co-ordinate of PMT normal * @param faceZ z co-ordinate of PMT normal */ WCSimLikelihoodDigit(); WCSimLikelihoodDigit(Double_t x, Double_t y, Double_t z, Double_t t, Double_t Q, Int_t tubeId, Double_t faceX, Double_t faceY, Double_t faceZ, TString name, TGraph *wlWeightedQE, Double_t wlWeightedRefIndex, double exposeHeight); /** * Constructor * @param myDigiHit Digitized Cherenkov hit object from WCSim */ WCSimLikelihoodDigit(WCSimRootCherenkovDigiHit *myDigiHit); /** * Copy Constructor */ WCSimLikelihoodDigit(const WCSimLikelihoodDigit &otherLikelihoodDigit); virtual ~WCSimLikelihoodDigit(); int GetTubeId() const; double GetQ() const; double GetT() const; TVector3 GetPos() const; double GetX() const; double GetY() const; double GetZ() const; TVector3 GetFace() const; double GetFaceX() const; double GetFaceY() const; double GetFaceZ() const; double GetAverageQE(const double &distanceToPMT) const; double GetAverageRefIndex() const; double GetExposeHeight() const; TString GetPMTName() const; void Print() const; bool operator==(const WCSimLikelihoodDigit &other) const; protected: private: Int_t fTubeId; ///< Unique PMT ID number from WCSim Double_t fQ; ///< Digitized charge (P.E.) Double_t fT; ///< Time of hit Double_t fPos[3]; ///< (x,y,z) co-ordinates of the PMT location Double_t fFace[3]; ///< (x,y,z) components of the direction normal to the PMT TString fPMTName; ///< Name of PMT type, e.g. 3_inch_HQE TGraph *fAverageQE; ///< Average QE of the PMT, from weighting QE(wavelength) by the average Cherenkov spectrum - as a function of photon travel distance double fAverageRefIndex; ///< Weight WCSim's refractive index by (wavelength * PMT QE(wavelength)) double fExposeHeight; ///< Height of PMT dome expose through the detector liner ClassDef(WCSimLikelihoodDigit, 1) };
28.891304
156
0.722724
[ "object", "vector" ]
b95d986e6e71b9d431ff4f6c0b26a3dcf60b0c55
4,953
cc
C++
src/tools/android/forwarder2/host_controller.cc
jxjnjjn/chromium
435c1d02fd1b99001dc9e1e831632c894523580d
[ "Apache-2.0" ]
9
2018-09-21T05:36:12.000Z
2021-11-15T15:14:36.000Z
src/tools/android/forwarder2/host_controller.cc
jxjnjjn/chromium
435c1d02fd1b99001dc9e1e831632c894523580d
[ "Apache-2.0" ]
null
null
null
src/tools/android/forwarder2/host_controller.cc
jxjnjjn/chromium
435c1d02fd1b99001dc9e1e831632c894523580d
[ "Apache-2.0" ]
3
2018-11-28T14:54:13.000Z
2020-07-02T07:36:07.000Z
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "tools/android/forwarder2/host_controller.h" #include <string> #include "base/logging.h" #include "base/memory/scoped_ptr.h" #include "tools/android/forwarder2/command.h" #include "tools/android/forwarder2/forwarder.h" #include "tools/android/forwarder2/socket.h" namespace forwarder2 { HostController::HostController(int device_port, const std::string& forward_to_host, int forward_to_host_port, int adb_port, int exit_notifier_fd) : device_port_(device_port), forward_to_host_(forward_to_host), forward_to_host_port_(forward_to_host_port), adb_port_(adb_port), exit_notifier_fd_(exit_notifier_fd), ready_(false) { adb_control_socket_.set_exit_notifier_fd(exit_notifier_fd); } HostController::~HostController() { } void HostController::StartForwarder( scoped_ptr<Socket> host_server_data_socket) { scoped_ptr<Socket> adb_data_socket(new Socket); if (!adb_data_socket->ConnectTcp("", adb_port_)) { LOG(ERROR) << "Could not connect AdbDataSocket on port: " << adb_port_; return; } // Open the Adb data connection, and send a command with the // |device_forward_port| as a way for the device to identify the connection. SendCommand(command::DATA_CONNECTION, device_port_, adb_data_socket.get()); // Check that the device received the new Adb Data Connection. Observe that // this check is done through the |adb_control_socket_| that is handled in the // DeviceListener thread just after the call to WaitForAdbDataSocket(). if (!ReceivedCommand(command::ADB_DATA_SOCKET_SUCCESS, &adb_control_socket_)) { LOG(ERROR) << "Device could not handle the new Adb Data Connection."; host_server_data_socket->Close(); adb_data_socket->Close(); return; } Forwarder* forwarder = new Forwarder(host_server_data_socket.Pass(), adb_data_socket.Pass()); // Forwarder object will self delete after returning. forwarder->Start(); } bool HostController::Connect() { if (!adb_control_socket_.ConnectTcp("", adb_port_)) { LOG(ERROR) << "Could not connect HostController socket on port: " << adb_port_; return false; } // Send the command to the device start listening to the "device_forward_port" bool send_command_success = SendCommand( command::LISTEN, device_port_, &adb_control_socket_); CHECK(send_command_success); int device_port_allocated; command::Type command; if (!ReadCommand(&adb_control_socket_, &device_port_allocated, &command) || command != command::BIND_SUCCESS) { LOG(ERROR) << "Device binding error using port " << device_port_; adb_control_socket_.Close(); return false; } // When doing dynamically allocation of port, we get the port from the // BIND_SUCCESS command we received above. device_port_ = device_port_allocated; ready_ = true; return true; } void HostController::Run() { CHECK(ready_) << "HostController not ready. Must call Connect() first."; while (true) { if (!ReceivedCommand(command::ACCEPT_SUCCESS, &adb_control_socket_)) { // TODO(pliard): This can also happen if device_forwarder was // intentionally killed before host_forwarder. In that case, // device_forwarder should send a notification to the host. Currently the // error message below is always emitted to the log file although this is // not necessarily an error. LOG(ERROR) << "Device socket error on accepting using port " << device_port_; break; } // Try to connect to host server. scoped_ptr<Socket> host_server_data_socket(new Socket); host_server_data_socket->set_exit_notifier_fd(exit_notifier_fd_); if (!host_server_data_socket->ConnectTcp( forward_to_host_, forward_to_host_port_)) { LOG(ERROR) << "Could not Connect HostServerData socket on port: " << forward_to_host_port_; SendCommand(command::HOST_SERVER_ERROR, device_port_, &adb_control_socket_); if (ReceivedCommand(command::ACK, &adb_control_socket_)) { // It can continue if the host forwarder could not connect to the host // server but the device acknowledged that, so that the device could // re-try later. continue; } else { break; } } SendCommand(command::HOST_SERVER_SUCCESS, device_port_, &adb_control_socket_); StartForwarder(host_server_data_socket.Pass()); } adb_control_socket_.Close(); } } // namespace forwarder2
37.80916
80
0.675752
[ "object" ]
b9624c2a3a80f46ad12356da8bf28627457913f1
3,695
cpp
C++
samples/_opengl/CubeMapping/src/CubeMappingApp.cpp
nselikoff/Cinder
54590aabdc3d74b0b078d43590dfad89e50e9c94
[ "BSD-2-Clause" ]
3,494
2015-01-02T08:42:09.000Z
2022-03-31T14:16:23.000Z
samples/_opengl/CubeMapping/src/CubeMappingApp.cpp
nselikoff/Cinder
54590aabdc3d74b0b078d43590dfad89e50e9c94
[ "BSD-2-Clause" ]
1,284
2015-01-02T07:31:47.000Z
2022-03-30T02:06:43.000Z
samples/_opengl/CubeMapping/src/CubeMappingApp.cpp
nselikoff/Cinder
54590aabdc3d74b0b078d43590dfad89e50e9c94
[ "BSD-2-Clause" ]
780
2015-01-02T22:14:29.000Z
2022-03-30T00:16:56.000Z
#include "cinder/app/App.h" #include "cinder/app/RendererGl.h" #include "cinder/FileWatcher.h" #include "cinder/ImageIo.h" #include "cinder/Log.h" #include "cinder/gl/gl.h" using namespace ci; using namespace ci::app; using namespace std; class CubeMappingApp : public App { public: void setup(); void resize(); void update(); void draw(); gl::TextureCubeMapRef mCubeMap; gl::BatchRef mTeapotBatch, mSkyBoxBatch; mat4 mObjectRotation; CameraPersp mCam; }; const int SKY_BOX_SIZE = 500; void CubeMappingApp::setup() { try { mCubeMap = gl::TextureCubeMap::create( loadImage( loadAsset( "env_map.jpg" ) ), gl::TextureCubeMap::Format().mipmap() ); } catch( const std::exception& e ) { CI_LOG_EXCEPTION( "error loading cube map image.", e ); } #if defined( CINDER_GL_ES ) try { auto envMapGlsl = gl::GlslProg::create( loadAsset( "env_map_es2.vert" ), loadAsset( "env_map_es2.frag" ) ); mTeapotBatch = gl::Batch::create( geom::Teapot().subdivisions( 7 ), envMapGlsl ); mTeapotBatch->getGlslProg()->uniform( "uCubeMapTex", 0 ); } catch( const std::exception& e ) { CI_LOG_EXCEPTION( "Shader Failed (env_map)", e ); } try { auto skyBoxGlsl = gl::GlslProg::create( loadAsset( "sky_box_es2.vert" ), loadAsset( "sky_box_es2.frag" ) ); mSkyBoxBatch = gl::Batch::create( geom::Cube(), skyBoxGlsl ); mSkyBoxBatch->getGlslProg()->uniform( "uCubeMapTex", 0 ); } catch( const std::exception& e ) { CI_LOG_EXCEPTION( "Shader Failed (sky_box)", e ); } #else // note: look in env_map.frag to optionally try out refraction instead of reflection. fs::path envMapVert = "env_map.vert"; fs::path envMapFrag = "env_map.frag"; vector<fs::path> teapotShaders = { "env_map.vert", "env_map.frag" }; FileWatcher::instance().watch( teapotShaders, [this, teapotShaders]( const WatchEvent &event ) { try { auto glsl = gl::GlslProg::create( loadAsset( teapotShaders[0] ), loadAsset( teapotShaders[1] ) ); mTeapotBatch = gl::Batch::create( geom::Teapot().subdivisions( 7 ), glsl ); mTeapotBatch->getGlslProg()->uniform( "uCubeMapTex", 0 ); CI_LOG_I( "loaded env_map shader" ); } catch( const std::exception &e ) { CI_LOG_EXCEPTION( "Shader Failed (env_map)", e ); } } ); try { auto skyBoxGlsl = gl::GlslProg::create( loadAsset( "sky_box.vert" ), loadAsset( "sky_box.frag" ) ); mSkyBoxBatch = gl::Batch::create( geom::Cube(), skyBoxGlsl ); mSkyBoxBatch->getGlslProg()->uniform( "uCubeMapTex", 0 ); } catch( const std::exception &e ) { CI_LOG_EXCEPTION( "Shader Failed (sky_box)", e ); } #endif gl::enableDepthRead(); gl::enableDepthWrite(); } void CubeMappingApp::resize() { mCam.setPerspective( 60, getWindowAspectRatio(), 1, 1000 ); } void CubeMappingApp::update() { // move the camera semi-randomly around based on time mCam.lookAt( vec3( 8 * sin( getElapsedSeconds() / 1 + 10 ), 7 * sin( getElapsedSeconds() / 2 ), 8 * cos( getElapsedSeconds() / 4 + 11 ) ), vec3( 0 ) ); // rotate the object (teapot) a bit each frame mObjectRotation *= rotate( 0.04f, normalize( vec3( 0.1f, 1, 0.1f ) ) ); } void CubeMappingApp::draw() { gl::clear( Color( 0, 0, 0 ) ); gl::setMatrices( mCam ); // bind the cube map for both drawing the teapot and sky box gl::ScopedTextureBind scopedTexBind( mCubeMap ); // draw teapot, using the cube map as an environment map if( mTeapotBatch ) { gl::ScopedModelMatrix modelScope; gl::multModelMatrix( mObjectRotation ); gl::scale( vec3( 4 ) ); mTeapotBatch->draw(); } // draw sky box { gl::ScopedModelMatrix modelScope; gl::scale( vec3( SKY_BOX_SIZE ) ); mSkyBoxBatch->draw(); } } CINDER_APP( CubeMappingApp, RendererGl( RendererGl::Options().msaa( 16 ) ) )
29.325397
152
0.679838
[ "object", "vector" ]
b963881617f7243a5b5b7ef695af3f86416a0add
21,836
cpp
C++
test-suite/batesmodel.cpp
sfondi/QuantLib
8a2449d2fb470a7d47a55d3e99c5dace749709c9
[ "BSD-3-Clause" ]
1
2017-07-19T11:17:48.000Z
2017-07-19T11:17:48.000Z
test-suite/batesmodel.cpp
sfondi/QuantLib
8a2449d2fb470a7d47a55d3e99c5dace749709c9
[ "BSD-3-Clause" ]
null
null
null
test-suite/batesmodel.cpp
sfondi/QuantLib
8a2449d2fb470a7d47a55d3e99c5dace749709c9
[ "BSD-3-Clause" ]
null
null
null
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* Copyright (C) 2005, 2008 Klaus Spanderen Copyright (C) 2007 StatPro Italia srl This file is part of QuantLib, a free-software/open-source library for financial quantitative analysts and developers - http://quantlib.org/ QuantLib is free software: you can redistribute it and/or modify it under the terms of the QuantLib license. You should have received a copy of the license along with this program; if not, please email <quantlib-dev@lists.sf.net>. The license is also available online at <http://quantlib.org/license.shtml>. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the license for more details. */ #include "batesmodel.hpp" #include "utilities.hpp" #include <ql/time/calendars/target.hpp> #include <ql/processes/batesprocess.hpp> #include <ql/processes/merton76process.hpp> #include <ql/instruments/europeanoption.hpp> #include <ql/time/daycounters/actualactual.hpp> #include <ql/termstructures/yield/flatforward.hpp> #include <ql/termstructures/yield/zerocurve.hpp> #include <ql/pricingengines/blackformula.hpp> #include <ql/math/optimization/levenbergmarquardt.hpp> #include <ql/pricingengines/vanilla/batesengine.hpp> #include <ql/pricingengines/vanilla/jumpdiffusionengine.hpp> #include <ql/pricingengines/vanilla/analyticeuropeanengine.hpp> #include <ql/pricingengines/vanilla/mceuropeanhestonengine.hpp> #include <ql/pricingengines/vanilla/fdbatesvanillaengine.hpp> #include <ql/models/equity/batesmodel.hpp> #include <ql/models/equity/hestonmodelhelper.hpp> #include <ql/time/period.hpp> #include <ql/quotes/simplequote.hpp> using namespace QuantLib; using namespace boost::unit_test_framework; namespace { Real getCalibrationError( std::vector<boost::shared_ptr<CalibrationHelper> > & options) { Real sse = 0; for (Size i = 0; i < options.size(); ++i) { const Real diff = options[i]->calibrationError()*100.0; sse += diff*diff; } return sse; } } void BatesModelTest::testAnalyticVsBlack() { BOOST_TEST_MESSAGE("Testing analytic Bates engine against Black formula..."); SavedSettings backup; Date settlementDate = Date::todaysDate(); Settings::instance().evaluationDate() = settlementDate; DayCounter dayCounter = ActualActual(); Date exerciseDate = settlementDate + 6*Months; boost::shared_ptr<StrikedTypePayoff> payoff( new PlainVanillaPayoff(Option::Put, 30)); boost::shared_ptr<Exercise> exercise(new EuropeanExercise(exerciseDate)); Handle<YieldTermStructure> riskFreeTS(flatRate(0.1, dayCounter)); Handle<YieldTermStructure> dividendTS(flatRate(0.04, dayCounter)); Handle<Quote> s0(boost::shared_ptr<Quote>(new SimpleQuote(32.0))); Real yearFraction = dayCounter.yearFraction(settlementDate, exerciseDate); Real forwardPrice = s0->value()*std::exp((0.1-0.04)*yearFraction); Real expected = blackFormula(payoff->optionType(), payoff->strike(), forwardPrice, std::sqrt(0.05*yearFraction)) * std::exp(-0.1*yearFraction); const Real v0 = 0.05; const Real kappa = 5.0; const Real theta = 0.05; const Real sigma = 1.0e-4; const Real rho = 0.0; const Real lambda = 0.0001; const Real nu = 0.0; const Real delta = 0.0001; VanillaOption option(payoff, exercise); boost::shared_ptr<BatesProcess> process( new BatesProcess(riskFreeTS, dividendTS, s0, v0, kappa, theta, sigma, rho, lambda, nu, delta)); boost::shared_ptr<PricingEngine> engine(new BatesEngine( boost::shared_ptr<BatesModel>(new BatesModel(process)), 64)); option.setPricingEngine(engine); Real calculated = option.NPV(); Real tolerance = 2.0e-7; Real error = std::fabs(calculated - expected); if (error > tolerance) { BOOST_ERROR("failed to reproduce Black price with BatesEngine" << QL_FIXED << "\n calculated: " << calculated << "\n expected: " << expected << QL_SCIENTIFIC << "\n error: " << error); } engine = boost::shared_ptr<PricingEngine>(new BatesDetJumpEngine( boost::shared_ptr<BatesDetJumpModel>( new BatesDetJumpModel( process, 1.0, 0.0001)), 64)); option.setPricingEngine(engine); calculated = option.NPV(); error = std::fabs(calculated - expected); if (error > tolerance) { BOOST_ERROR("failed to reproduce Black price with " \ "BatesDetJumpEngine" << QL_FIXED << "\n calculated: " << calculated << "\n expected: " << expected << QL_SCIENTIFIC << "\n error: " << error); } engine = boost::shared_ptr<PricingEngine>(new BatesDoubleExpEngine( boost::shared_ptr<BatesDoubleExpModel>( new BatesDoubleExpModel(process, 0.0001, 0.0001, 0.0001)), 64)); option.setPricingEngine(engine); calculated = option.NPV(); error = std::fabs(calculated - expected); if (error > tolerance) { BOOST_ERROR("failed to reproduce Black price with BatesDoubleExpEngine" << QL_FIXED << "\n calculated: " << calculated << "\n expected: " << expected << QL_SCIENTIFIC << "\n error: " << error); } engine = boost::shared_ptr<PricingEngine>(new BatesDoubleExpDetJumpEngine( boost::shared_ptr<BatesDoubleExpDetJumpModel>( new BatesDoubleExpDetJumpModel( process, 0.0001, 0.0001, 0.0001, 0.5, 1.0, 0.0001)), 64)); option.setPricingEngine(engine); calculated = option.NPV(); error = std::fabs(calculated - expected); if (error > tolerance) { BOOST_ERROR("failed to reproduce Black price with " \ "BatesDoubleExpDetJumpEngine" << QL_FIXED << "\n calculated: " << calculated << "\n expected: " << expected << QL_SCIENTIFIC << "\n error: " << error); } } void BatesModelTest::testAnalyticAndMcVsJumpDiffusion() { BOOST_TEST_MESSAGE("Testing analytic Bates engine against Merton-76 engine..."); SavedSettings backup; Date settlementDate = Date::todaysDate(); Settings::instance().evaluationDate() = settlementDate; DayCounter dayCounter = ActualActual(); boost::shared_ptr<StrikedTypePayoff> payoff( new PlainVanillaPayoff(Option::Put, 95)); Handle<YieldTermStructure> riskFreeTS(flatRate(0.1, dayCounter)); Handle<YieldTermStructure> dividendTS(flatRate(0.04, dayCounter)); Handle<Quote> s0(boost::shared_ptr<Quote>(new SimpleQuote(100))); Real v0 = 0.0433; // FLOATING_POINT_EXCEPTION boost::shared_ptr<SimpleQuote> vol(new SimpleQuote(std::sqrt(v0))); boost::shared_ptr<BlackVolTermStructure> volTS = flatVol(settlementDate, vol, dayCounter); const Real kappa = 0.5; const Real theta = v0; const Real sigma = 1.0e-4; const Real rho = 0.0; boost::shared_ptr<SimpleQuote> jumpIntensity(new SimpleQuote(2)); boost::shared_ptr<SimpleQuote> meanLogJump(new SimpleQuote(-0.2)); boost::shared_ptr<SimpleQuote> jumpVol(new SimpleQuote(0.2)); boost::shared_ptr<BatesProcess> batesProcess(new BatesProcess( riskFreeTS, dividendTS, s0, v0, kappa, theta, sigma, rho, jumpIntensity->value(), meanLogJump->value(), jumpVol->value())); boost::shared_ptr<Merton76Process> mertonProcess( new Merton76Process(s0, dividendTS, riskFreeTS, Handle<BlackVolTermStructure>(volTS), Handle<Quote>(jumpIntensity), Handle<Quote>(meanLogJump), Handle<Quote>(jumpVol))); boost::shared_ptr<PricingEngine> batesEngine(new BatesEngine( boost::shared_ptr<BatesModel>(new BatesModel(batesProcess)), 160)); const Real mcTol = 0.1; boost::shared_ptr<PricingEngine> mcBatesEngine = MakeMCEuropeanHestonEngine<PseudoRandom>(batesProcess) .withStepsPerYear(2) .withAntitheticVariate() .withAbsoluteTolerance(mcTol) .withSeed(1234); boost::shared_ptr<PricingEngine> mertonEngine( new JumpDiffusionEngine(mertonProcess, 1e-10, 1000)); for (Integer i=1; i<=5; i+=2) { Date exerciseDate = settlementDate + i*Years; boost::shared_ptr<Exercise> exercise( new EuropeanExercise(exerciseDate)); VanillaOption batesOption(payoff, exercise); batesOption.setPricingEngine(batesEngine); Real calculated = batesOption.NPV(); batesOption.setPricingEngine(mcBatesEngine); Real mcCalculated = batesOption.NPV(); EuropeanOption mertonOption(payoff, exercise); mertonOption.setPricingEngine(mertonEngine); Real expected = mertonOption.NPV(); Real tolerance = 2e-8; Real relError = std::fabs(calculated - expected)/expected; if (relError > tolerance) { BOOST_FAIL("failed to reproduce Merton76 price with semi " "analytic BatesEngine" << QL_FIXED << std::setprecision(8) << "\n calculated: " << calculated << "\n expected: " << expected << "\n rel. error: " << relError << "\n tolerance: " << tolerance); } Real mcError = std::fabs(expected - mcCalculated); if (mcError > 3*mcTol) { BOOST_FAIL("failed to reproduce Merton76 price with Monte-Carlo " "BatesEngine" << QL_FIXED << std::setprecision(8) << "\n calculated: " << mcCalculated << "\n expected: " << expected << "\n error: " << mcError << "\n tolerance: " << mcTol); } } } namespace { struct HestonModelData { const char* const name; Real v0; Real kappa; Real theta; Real sigma; Real rho; Real r; Real q; }; HestonModelData hestonModels[] = { // ADI finite difference schemes for option pricing in the // Heston model with correlation, K.J. in t'Hout and S. Foulon, {"'t Hout case 1", 0.04, 1.5, 0.04, 0.3, -0.9, 0.025, 0.0}, // Efficient numerical methods for pricing American options under // stochastic volatility, Samuli Ikonen and Jari Toivanen, {"Ikonen-Toivanen", 0.0625, 5, 0.16, 0.9, 0.1, 0.1, 0.0}, // Not-so-complex logarithms in the Heston model, // Christian Kahl and Peter Jäckel {"Kahl-Jaeckel", 0.16, 1.0, 0.16, 2.0, -0.8, 0.0, 0.0}, // self defined test cases {"Equity case", 0.07, 2.0, 0.04, 0.55, -0.8, 0.03, 0.035 }, }; } void BatesModelTest::testAnalyticVsMCPricing() { BOOST_TEST_MESSAGE("Testing analytic Bates engine against Monte-Carlo " "engine..."); SavedSettings backup; Date settlementDate(30, March, 2007); Settings::instance().evaluationDate() = settlementDate; DayCounter dayCounter = ActualActual(); Date exerciseDate(30, March, 2012); boost::shared_ptr<StrikedTypePayoff> payoff( new PlainVanillaPayoff(Option::Put, 100)); boost::shared_ptr<Exercise> exercise(new EuropeanExercise(exerciseDate)); for (Size i=0; i < LENGTH(hestonModels); ++i) { Handle<YieldTermStructure> riskFreeTS(flatRate(hestonModels[i].r, dayCounter)); Handle<YieldTermStructure> dividendTS(flatRate(hestonModels[i].q, dayCounter)); Handle<Quote> s0(boost::shared_ptr<Quote>(new SimpleQuote(100))); boost::shared_ptr<BatesProcess> batesProcess(new BatesProcess( riskFreeTS, dividendTS, s0, hestonModels[i].v0, hestonModels[i].kappa, hestonModels[i].theta, hestonModels[i].sigma, hestonModels[i].rho, 2.0, -0.2, 0.1)); const Real mcTolerance = 0.5; boost::shared_ptr<PricingEngine> mcEngine = MakeMCEuropeanHestonEngine<PseudoRandom>(batesProcess) .withStepsPerYear(20) .withAntitheticVariate() .withAbsoluteTolerance(mcTolerance) .withSeed(1234); boost::shared_ptr<BatesModel> batesModel(new BatesModel(batesProcess)); boost::shared_ptr<PricingEngine> fdEngine( new FdBatesVanillaEngine(batesModel, 50, 100, 30)); boost::shared_ptr<PricingEngine> analyticEngine( new BatesEngine(batesModel, 160)); VanillaOption option(payoff, exercise); option.setPricingEngine(mcEngine); const Real calculated = option.NPV(); option.setPricingEngine(analyticEngine); const Real expected = option.NPV(); option.setPricingEngine(fdEngine); const Real fdCalculated = option.NPV(); const Real mcError = std::fabs(calculated - expected); if (mcError > 3*mcTolerance) { BOOST_FAIL("failed to reproduce Monte-Carlo price for BatesEngine" << "\n parameter: " << hestonModels[i].name << QL_FIXED << std::setprecision(8) << "\n calculated: " << calculated << "\n expected: " << expected << "\n error: " << mcError << "\n tolerance: " << mcTolerance); } const Real fdTolerance = 0.2; const Real fdError = std::fabs(fdCalculated - expected); if (fdError > fdTolerance) { BOOST_FAIL("failed to reproduce PIDE price for BatesEngine" << "\n parameter: " << hestonModels[i].name << QL_FIXED << std::setprecision(8) << "\n calculated: " << fdCalculated << "\n expected: " << expected << "\n error: " << fdError << "\n tolerance: " << fdTolerance); } } } void BatesModelTest::testDAXCalibration() { /* this example is taken from A. Sepp Pricing European-Style Options under Jump Diffusion Processes with Stochstic Volatility: Applications of Fourier Transform http://math.ut.ee/~spartak/papers/stochjumpvols.pdf */ BOOST_TEST_MESSAGE( "Testing Bates model calibration using DAX volatility data..."); SavedSettings backup; Date settlementDate(5, July, 2002); Settings::instance().evaluationDate() = settlementDate; DayCounter dayCounter = Actual365Fixed(); Calendar calendar = TARGET(); Integer t[] = { 13, 41, 75, 165, 256, 345, 524, 703 }; Rate r[] = { 0.0357,0.0349,0.0341,0.0355,0.0359,0.0368,0.0386,0.0401 }; std::vector<Date> dates; std::vector<Rate> rates; dates.push_back(settlementDate); rates.push_back(0.0357); for (Size i = 0; i < 8; ++i) { dates.push_back(settlementDate + t[i]); rates.push_back(r[i]); } // FLOATING_POINT_EXCEPTION Handle<YieldTermStructure> riskFreeTS( boost::shared_ptr<YieldTermStructure>( new ZeroCurve(dates, rates, dayCounter))); Handle<YieldTermStructure> dividendTS( flatRate(settlementDate, 0.0, dayCounter)); Volatility v[] = { 0.6625,0.4875,0.4204,0.3667,0.3431,0.3267,0.3121,0.3121, 0.6007,0.4543,0.3967,0.3511,0.3279,0.3154,0.2984,0.2921, 0.5084,0.4221,0.3718,0.3327,0.3155,0.3027,0.2919,0.2889, 0.4541,0.3869,0.3492,0.3149,0.2963,0.2926,0.2819,0.2800, 0.4060,0.3607,0.3330,0.2999,0.2887,0.2811,0.2751,0.2775, 0.3726,0.3396,0.3108,0.2781,0.2788,0.2722,0.2661,0.2686, 0.3550,0.3277,0.3012,0.2781,0.2781,0.2661,0.2661,0.2681, 0.3428,0.3209,0.2958,0.2740,0.2688,0.2627,0.2580,0.2620, 0.3302,0.3062,0.2799,0.2631,0.2573,0.2533,0.2504,0.2544, 0.3343,0.2959,0.2705,0.2540,0.2504,0.2464,0.2448,0.2462, 0.3460,0.2845,0.2624,0.2463,0.2425,0.2385,0.2373,0.2422, 0.3857,0.2860,0.2578,0.2399,0.2357,0.2327,0.2312,0.2351, 0.3976,0.2860,0.2607,0.2356,0.2297,0.2268,0.2241,0.2320 }; Handle<Quote> s0(boost::shared_ptr<Quote>(new SimpleQuote(4468.17))); Real strike[] = { 3400,3600,3800,4000,4200,4400, 4500,4600,4800,5000,5200,5400,5600 }; Real v0 = 0.0433; boost::shared_ptr<SimpleQuote> vol(new SimpleQuote(std::sqrt(v0))); boost::shared_ptr<BlackVolTermStructure> volTS = flatVol(settlementDate, vol, dayCounter); const Real kappa = 1.0; const Real theta = v0; const Real sigma = 1.0; const Real rho = 0.0; const Real lambda = 1.1098; const Real nu = -0.1285; const Real delta = 0.1702; boost::shared_ptr<BatesProcess> process( new BatesProcess(riskFreeTS, dividendTS, s0, v0, kappa, theta, sigma, rho, lambda, nu, delta)); boost::shared_ptr<BatesModel> batesModel(new BatesModel(process)); boost::shared_ptr<PricingEngine> batesEngine( new BatesEngine(batesModel, 64)); std::vector<boost::shared_ptr<CalibrationHelper> > options; for (Size s = 0; s < 13; ++s) { for (Size m = 0; m < 8; ++m) { Handle<Quote> vol(boost::shared_ptr<Quote>( new SimpleQuote(v[s*8+m]))); Period maturity((int)((t[m]+3)/7.), Weeks); // round to weeks // this is the calibration helper for the bates models // FLOATING_POINT_EXCEPTION options.push_back(boost::shared_ptr<CalibrationHelper>( new HestonModelHelper(maturity, calendar, s0->value(), strike[s], vol, riskFreeTS, dividendTS, CalibrationHelper::ImpliedVolError))); options.back()->setPricingEngine(batesEngine); } } // check calibration engine LevenbergMarquardt om; batesModel->calibrate(options, om, EndCriteria(400, 40, 1.0e-8, 1.0e-8, 1.0e-8)); Real expected = 36.6; Real calculated = getCalibrationError(options); if (std::fabs(calculated - expected) > 2.5) BOOST_ERROR("failed to calibrate the bates model" << "\n calculated: " << calculated << "\n expected: " << expected); //check pricing of derived engines std::vector<boost::shared_ptr<PricingEngine> > pricingEngines; process = boost::shared_ptr<BatesProcess>( new BatesProcess(riskFreeTS, dividendTS, s0, v0, kappa, theta, sigma, rho, 1.0, -0.1, 0.1)); pricingEngines.push_back(boost::shared_ptr<PricingEngine>( new BatesDetJumpEngine( boost::shared_ptr<BatesDetJumpModel>( new BatesDetJumpModel(process)), 64)) ); boost::shared_ptr<HestonProcess> hestonProcess(new HestonProcess( riskFreeTS, dividendTS, s0, v0, kappa, theta, sigma, rho)); pricingEngines.push_back(boost::shared_ptr<PricingEngine>( new BatesDoubleExpEngine( boost::shared_ptr<BatesDoubleExpModel>( new BatesDoubleExpModel(hestonProcess, 1.0)), 64)) ); pricingEngines.push_back(boost::shared_ptr<PricingEngine>( new BatesDoubleExpDetJumpEngine( boost::shared_ptr<BatesDoubleExpDetJumpModel>( new BatesDoubleExpDetJumpModel(hestonProcess, 1.0)), 64)) ); Real expectedValues[] = { 5896.37, 5499.29, 6497.89}; Real tolerance=0.1; for (Size i = 0; i < pricingEngines.size(); ++i) { for (Size j = 0; j < options.size(); ++j) { options[j]->setPricingEngine(pricingEngines[i]); } Real calculated = std::fabs(getCalibrationError(options)); if (std::fabs(calculated - expectedValues[i]) > tolerance) BOOST_ERROR("failed to calculated prices for derived Bates models" << "\n calculated: " << calculated << "\n expected: " << expectedValues[i]); } } test_suite* BatesModelTest::suite() { test_suite* suite = BOOST_TEST_SUITE("Bates model tests"); suite->add(QUANTLIB_TEST_CASE(&BatesModelTest::testAnalyticVsBlack)); suite->add(QUANTLIB_TEST_CASE( &BatesModelTest::testAnalyticAndMcVsJumpDiffusion)); suite->add(QUANTLIB_TEST_CASE(&BatesModelTest::testAnalyticVsMCPricing)); // FLOATING_POINT_EXCEPTION suite->add(QUANTLIB_TEST_CASE(&BatesModelTest::testDAXCalibration)); return suite; }
39.701818
84
0.593882
[ "vector", "model", "transform" ]
b96a6ef5f02c540ce552d42c3befa2f341a7f870
21,299
cpp
C++
src/Core/TransactionBuilder.cpp
mygirl8893/evo
c90f69ad6132c426042749ff3fe4174d22aa63b2
[ "MIT" ]
1
2019-05-20T01:00:40.000Z
2019-05-20T01:00:40.000Z
src/Core/TransactionBuilder.cpp
mygirl8893/evo
c90f69ad6132c426042749ff3fe4174d22aa63b2
[ "MIT" ]
4
2018-05-07T07:15:53.000Z
2018-06-01T19:35:46.000Z
src/Core/TransactionBuilder.cpp
mygirl8893/evo
c90f69ad6132c426042749ff3fe4174d22aa63b2
[ "MIT" ]
10
2018-05-09T10:45:07.000Z
2020-01-11T17:21:28.000Z
#include "TransactionBuilder.hpp" #include <iostream> #include "BlockChain.hpp" #include "CryptoNoteTools.hpp" #include "Currency.hpp" #include "Wallet.hpp" #include "common/string.hpp" #include "crypto/crypto.hpp" #include "crypto/random.h" #include "http/JsonRpc.h" #include "seria/BinaryOutputStream.hpp" using namespace cryptonote; bool TransactionBuilder::derive_public_key(const AccountPublicAddress &to, const SecretKey &tx_key, size_t output_index, PublicKey &ephemeral_key) { KeyDerivation derivation; if (!generate_key_derivation(to.view_public_key, tx_key, derivation)) return false; return crypto::derive_public_key(derivation, output_index, to.spend_public_key, ephemeral_key); } TransactionBuilder::TransactionBuilder(const Currency &currency, UnlockMoment unlock_time) { m_transaction.version = currency.current_transaction_version; m_transaction.unlock_time = unlock_time; } void TransactionBuilder::set_payment_id(const Hash &hash) { BinaryArray payment_id_blob; set_payment_id_to_transaction_extra_nonce(payment_id_blob, reinterpret_cast<const Hash &>(hash)); set_extra_nonce(payment_id_blob); } void TransactionBuilder::set_extra_nonce(const BinaryArray &nonce) { TransactionExtraNonce extra_nonce = {nonce}; m_extra.set(extra_nonce); m_transaction.extra = m_extra.serialize(); } size_t TransactionBuilder::add_output(uint64_t amount, const AccountPublicAddress &to) { m_outputs_amount += amount; OutputDesc desc; desc.amount = amount; desc.addr = to; m_output_descs.push_back(std::move(desc)); return m_output_descs.size() - 1; } static bool APIOutputLessGlobalIndex(const api::Output &a, const api::Output &b) { return a.global_index < b.global_index; } bool TransactionBuilder::generate_key_image_helper(const AccountKeys &ack, const PublicKey &tx_public_key, size_t real_output_index, KeyPair &in_ephemeral, KeyImage &ki) { KeyDerivation recv_derivation; bool r = generate_key_derivation(tx_public_key, ack.view_secret_key, recv_derivation); if (!r) return false; r = crypto::derive_public_key( recv_derivation, real_output_index, ack.address.spend_public_key, in_ephemeral.public_key); if (!r) return false; crypto::derive_secret_key(recv_derivation, real_output_index, ack.spend_secret_key, in_ephemeral.secret_key); crypto::generate_key_image(in_ephemeral.public_key, in_ephemeral.secret_key, ki); return true; } std::vector<uint32_t> TransactionBuilder::absolute_output_offsets_to_relative(const std::vector<uint32_t> &off) { auto copy = off; for (size_t i = 1; i < copy.size(); ++i) { copy[i] = off[i] - off[i - 1]; } return copy; } size_t TransactionBuilder::add_input(const AccountKeys &sender_keys, api::Output real_output, const std::vector<api::Output> &mix_outputs) { m_inputs_amount += real_output.amount; InputDesc desc; desc.input.amount = real_output.amount; desc.outputs = mix_outputs; std::sort(desc.outputs.begin(), desc.outputs.end(), APIOutputLessGlobalIndex); desc.real_output_index = std::lower_bound(desc.outputs.begin(), desc.outputs.end(), real_output, APIOutputLessGlobalIndex) - desc.outputs.begin(); desc.outputs.insert(desc.outputs.begin() + desc.real_output_index, real_output); if (!generate_key_image_helper(sender_keys, real_output.transaction_public_key, real_output.index_in_transaction, desc.eph_keys, desc.input.key_image)) throw std::runtime_error("generating keyimage failed"); if (desc.input.key_image != real_output.key_image) throw std::runtime_error("generated keyimage does not match input"); // fill outputs array and use relative offsets for (const auto &out : desc.outputs) { if (out.amount != real_output.amount) // they are all zero as sent from node throw std::runtime_error("Mixin outputs with different amounts is not allowed"); desc.input.output_indexes.push_back(out.global_index); } desc.input.output_indexes = absolute_output_offsets_to_relative(desc.input.output_indexes); m_input_descs.push_back(std::move(desc)); return m_input_descs.size() - 1; } KeyPair TransactionBuilder::deterministic_keys_from_seed(const Hash &tx_inputs_hash, const Hash &tx_derivation_seed) { BinaryArray ba; common::append(ba, std::begin(tx_inputs_hash.data), std::end(tx_inputs_hash.data)); common::append(ba, std::begin(tx_derivation_seed.data), std::end(tx_derivation_seed.data)); KeyPair tx_keys{}; crypto::hash_to_scalar(ba.data(), ba.size(), tx_keys.secret_key); crypto::secret_key_to_public_key(tx_keys.secret_key, tx_keys.public_key); return tx_keys; } KeyPair TransactionBuilder::deterministic_keys_from_seed(const TransactionPrefix &tx, const Hash &tx_derivation_seed) { Hash tx_inputs_hash = get_transaction_inputs_hash(tx); return deterministic_keys_from_seed(tx_inputs_hash, tx_derivation_seed); } Transaction TransactionBuilder::sign(const Hash &tx_derivation_seed) { std::shuffle(m_output_descs.begin(), m_output_descs.end(), crypto::random_engine<size_t>{}); std::shuffle(m_input_descs.begin(), m_input_descs.end(), crypto::random_engine<size_t>{}); // Deterministic generation of tx private key. m_transaction.inputs.resize(m_input_descs.size()); for (size_t i = 0; i != m_input_descs.size(); ++i) m_transaction.inputs.at(i) = std::move(m_input_descs[i].input); KeyPair tx_keys = deterministic_keys_from_seed(m_transaction, tx_derivation_seed); TransactionExtraPublicKey pk = {tx_keys.public_key}; m_extra.set(pk); m_transaction.extra = m_extra.serialize(); // Now when we set tx keys we can derive output keys m_transaction.outputs.resize(m_output_descs.size()); for (size_t i = 0; i != m_output_descs.size(); ++i) { KeyOutput out_key; if (!derive_public_key(m_output_descs[i].addr, tx_keys.secret_key, i, out_key.key)) throw std::runtime_error("output keys detected as corrupted during output key derivation"); TransactionOutput out; // TODO - return {} initializer after NDK compiler upgrade out.amount = m_output_descs[i].amount; out.target = out_key; m_transaction.outputs.at(i) = out; } Hash hash = get_transaction_prefix_hash(m_transaction); m_transaction.signatures.resize(m_input_descs.size()); for (size_t i = 0; i != m_input_descs.size(); ++i) { const KeyInput &input = boost::get<KeyInput>(m_transaction.inputs.at(i)); const InputDesc &desc = m_input_descs[i]; std::vector<Signature> signatures; std::vector<const PublicKey *> keys_ptrs; for (const auto &o : desc.outputs) { keys_ptrs.push_back(&o.public_key); } signatures.resize(keys_ptrs.size(), Signature{}); if (!generate_ring_signature(hash, input.key_image, keys_ptrs, desc.eph_keys.secret_key, desc.real_output_index, signatures.data())) { throw std::runtime_error("output keys detected as corrupted during ring signing"); } m_transaction.signatures.at(i) = signatures; } return m_transaction; } UnspentSelector::UnspentSelector(const Currency &currency, Unspents &&unspents) : m_currency(currency), m_unspents(std::move(unspents)) {} void UnspentSelector::reset(Unspents &&unspents) { m_unspents = std::move(unspents); m_used_unspents.clear(); m_optimization_unspents.clear(); m_used_total = 0; m_inputs_count = 0; m_ra_amounts.clear(); } void UnspentSelector::add_mixed_inputs(const SecretKey &view_secret_key, const std::unordered_map<PublicKey, WalletRecord> &wallet_records, TransactionBuilder &builder, uint32_t anonymity, api::cryptonoted::GetRandomOutputs::Response &&ra_response) { for (auto uu : m_used_unspents) { std::vector<api::Output> mix_outputs; auto &our_ra_outputs = ra_response.outputs[uu.amount]; while (mix_outputs.size() < anonymity) { if (our_ra_outputs.empty()) throw std::runtime_error("Not enough anonymity for amount " + common::to_string(uu.amount)); // TODO - return error code to json_rpc api::Output out = std::move(our_ra_outputs.back()); our_ra_outputs.pop_back(); if (out.global_index != uu.global_index) // Protect against collisions mix_outputs.push_back(std::move(out)); } AccountKeys sender_keys; sender_keys.view_secret_key = view_secret_key; if (!m_currency.parse_account_address_string(uu.address, sender_keys.address)) throw json_rpc::Error(json_rpc::INVALID_PARAMS, "Could not parse address " + uu.address); auto rit = wallet_records.find(sender_keys.address.spend_public_key); if (rit == wallet_records.end() || rit->second.spend_public_key != sender_keys.address.spend_public_key) throw json_rpc::Error(json_rpc::INVALID_PARAMS, "No keys in wallet for address " + uu.address); sender_keys.spend_secret_key = rit->second.spend_secret_key; builder.add_input(sender_keys, uu, mix_outputs); } } constexpr Amount fake_large = 1000000000000000000; // optimize negative amounts // by adding this large // number to them constexpr size_t OPTIMIZATIONS_PER_TX = 50; constexpr size_t OPTIMIZATIONS_PER_TX_AGGRESSIVE = 200; constexpr size_t MEDIAN_PERCENT = 25; // make tx up to 25% of block constexpr size_t MEDIAN_PERCENT_AGGRESSIVE = 50; // make tx up to 50% of block constexpr size_t STACK_OPTIMIZATION_THRESHOLD = 20; // If any coin stack is larger, we will spend 10 coins. constexpr size_t TWO_THRESHOLD = 10; // if any of 2 coin stacks is larger, we // will use 2 coins to cover single digit // (e.g. 7 + 9 for 6) bool UnspentSelector::select_optimal_outputs(Height block_height, Timestamp block_time, Height confirmed_height, size_t effective_median_size, size_t anonymity, Amount total_amount, size_t total_outputs, Amount fee_per_byte, std::string optimization_level, Amount &change) { HaveCoins have_coins; size_t max_digits; DustCoins dust_coins; create_have_coins(block_height, block_time, confirmed_height, have_coins, dust_coins, max_digits); Amount fee = m_currency.minimum_fee; size_t optimizations = (optimization_level == "aggressive") ? OPTIMIZATIONS_PER_TX_AGGRESSIVE : (optimization_level == "minimal") ? 9 : OPTIMIZATIONS_PER_TX; // 9 allows some dust optimization, but never "stack of coins" optimization. // "Minimal" optimization does not mean no optimization size_t optimization_median_percent = (optimization_level == "aggressive") ? MEDIAN_PERCENT_AGGRESSIVE : MEDIAN_PERCENT; const size_t optimization_median = effective_median_size * optimization_median_percent / 100; while (true) { if (!select_optimal_outputs(have_coins, dust_coins, max_digits, total_amount + fee, anonymity, optimizations)) return false; Amount change_dust_fee = (m_used_total - total_amount - fee) % m_currency.default_dust_threshold; size_t tx_size = get_maximum_tx_size(m_inputs_count, total_outputs + 8, anonymity); // TODO - 8 is expected max change outputs if (tx_size > optimization_median && optimizations > 0) { unoptimize_amounts(have_coins, dust_coins); optimizations /= 2; if (optimizations < 10) optimizations = 0; // no point trying so many times for so few optimizations continue; } if (tx_size > effective_median_size) return false; // Out of size Amount size_fee = fee_per_byte * tx_size; if (fee + change_dust_fee >= size_fee) { change = m_used_total - total_amount - fee - change_dust_fee; combine_optimized_unspents(); return true; } fee = ((size_fee - change_dust_fee + m_currency.default_dust_threshold - 1) / m_currency.default_dust_threshold) * m_currency.default_dust_threshold; unoptimize_amounts(have_coins, dust_coins); } } void UnspentSelector::create_have_coins(Height block_height, Timestamp block_time, Height confirmed_height, HaveCoins &have_coins, DustCoins &dust_coins, size_t &max_digit) { max_digit = 0; for (auto uit = m_unspents.rbegin(); uit != m_unspents.rend(); ++uit) { api::Output &un = *uit; if (un.height >= confirmed_height) // unconfirmed continue; if (!m_currency.is_transaction_spend_time_unlocked(un.unlock_time, block_height, block_time)) continue; if (!Currency::is_dust(un.amount)) { Amount am = un.amount; size_t digit = 0; while (am > 9) { digit += 1; am /= 10; } max_digit = std::max(max_digit, digit); have_coins[digit][static_cast<size_t>(am)].push_back(un); } else dust_coins[un.amount].push_back(un); } } void UnspentSelector::combine_optimized_unspents() { for (auto &&un : m_optimization_unspents) { m_ra_amounts.push_back(un.amount); } m_used_unspents.insert(m_used_unspents.end(), m_optimization_unspents.begin(), m_optimization_unspents.end()); m_optimization_unspents.clear(); } void UnspentSelector::unoptimize_amounts(HaveCoins &have_coins, DustCoins &dust_coins) { // First remove all optimized coins. for (auto &&un : m_optimization_unspents) { m_used_total -= un.amount; m_inputs_count -= 1; if (!un.dust) { Amount am = un.amount; size_t digit = 0; while (am > 9) { digit += 1; am /= 10; } have_coins[digit][static_cast<size_t>(am)].push_back(un); } else dust_coins[un.amount].push_back(un); } m_optimization_unspents.clear(); } void UnspentSelector::optimize_amounts(HaveCoins &have_coins, size_t max_digit, Amount total_amount) { std::cout << "Sub optimizing am=" << fake_large + total_amount - m_used_total << std::endl; Amount digit_amount = 1; for (size_t digit = 0; digit != max_digit + 1; ++digit, digit_amount *= 10) { if (m_used_total >= total_amount && digit_amount > m_used_total) // No optimization far beyond requested sum break; Amount am = 10 - ((fake_large + total_amount + digit_amount - 1 - m_used_total) / digit_amount) % 10; auto dit = have_coins.find(digit); if (dit == have_coins.end()) // No coins for digit continue; size_t best_two_counts[2] = {}; size_t best_weight = 0; for (auto ait : dit->second) for (auto bit : dit->second) { if ((ait.first + bit.first + am) % 10 == 0 && (ait.second.size() >= TWO_THRESHOLD || bit.second.size() >= TWO_THRESHOLD) && (ait.second.size() + bit.second.size()) > best_weight) { best_weight = ait.second.size() + bit.second.size(); best_two_counts[0] = ait.first; best_two_counts[1] = bit.first; } } if (best_weight != 0) { std::cout << "Found pair for digit=" << digit << " am=" << am << " cc=(" << best_two_counts[0] << ", " << best_two_counts[1] << ") w=" << best_weight << std::endl; for (size_t i = 0; i != 2; ++i) { auto &uns = dit->second[best_two_counts[i]]; auto &un = uns.back(); m_optimization_unspents.push_back(un); m_used_total += un.amount; m_inputs_count += 1; uns.pop_back(); if (uns.empty()) dit->second.erase(best_two_counts[i]); if (dit->second.empty()) have_coins.erase(dit); } continue; } if (am == 10) continue; size_t best_single = 0; best_weight = 0; for (auto ait : dit->second) if ((ait.first + am) % 10 == 0) { best_single = ait.first; break; } else if (ait.first > 10 - am && ait.second.size() > best_weight) { best_weight = ait.second.size(); best_single = ait.first; } if (best_single != 0) { std::cout << "Found single for digit=" << digit << " am=" << am << " cc=" << best_single << std::endl; auto &uns = dit->second[best_single]; auto &un = uns.back(); m_optimization_unspents.push_back(un); m_used_total += un.amount; m_inputs_count += 1; uns.pop_back(); if (uns.empty()) dit->second.erase(best_single); if (dit->second.empty()) have_coins.erase(dit); continue; } std::cout << "Found nothing for digit=" << digit << std::endl; } std::cout << "Sub optimized used_total=" << m_used_total << " for total=" << total_amount << std::endl; } bool UnspentSelector::select_optimal_outputs(HaveCoins &have_coins, DustCoins &dust_coins, size_t max_digit, Amount total_amount, size_t anonymity, size_t optimization_count) { // Optimize for roundness of used_total - total_amount; // [digit:size:outputs] std::cout << "Optimizing am=" << fake_large + total_amount - m_used_total << std::endl; if (anonymity == 0) { if (m_used_total < total_amount) { // Find smallest dust coin >= total_amount - used_total, it can be very // large auto duit = dust_coins.lower_bound(total_amount - m_used_total); if (duit != dust_coins.end()) { auto &un = duit->second.back(); std::cout << "Found single large dust coin am=" << un.amount << std::endl; m_optimization_unspents.push_back(un); m_used_total += un.amount; m_inputs_count += 1; duit->second.pop_back(); if (duit->second.empty()) dust_coins.erase(duit); } } // Fill with dust coins, but no more than K coins. while (m_used_total < total_amount && !dust_coins.empty() && optimization_count >= 1) { auto duit = --dust_coins.end(); auto &un = duit->second.back(); m_optimization_unspents.push_back(un); m_used_total += un.amount; m_inputs_count += 1; optimization_count -= 1; duit->second.pop_back(); if (duit->second.empty()) dust_coins.erase(duit); std::cout << "Found optimization dust coin amount=" << un.amount << std::endl; } } // Add coins from large stacks, up to optimization_count while (optimization_count >= 10) { size_t best_weight = STACK_OPTIMIZATION_THRESHOLD; std::vector<api::Output> *best_stack = nullptr; for (auto &hit : have_coins) for (auto &ait : hit.second) if (ait.second.size() > best_weight) { best_weight = ait.second.size(); best_stack = &ait.second; } if (!best_stack) break; for (int i = 0; i != 10; ++i) { auto &un = best_stack->back(); std::cout << "Found optimization coin amount=" << un.amount << std::endl; m_optimization_unspents.push_back(un); m_used_total += un.amount; m_inputs_count += 1; optimization_count -= 1; best_stack->pop_back(); // Will never become empty because of threshold } } optimize_amounts(have_coins, max_digit, total_amount); if (m_used_total >= total_amount) return true; // Find smallest coin >= total_amount - used_total bool found = false; Amount digit_amount = 1; for (size_t digit = 0; !found && digit != max_digit + 1; ++digit, digit_amount *= 10) { auto dit = have_coins.find(digit); if (dit == have_coins.end()) // No coins for digit continue; for (auto ait = dit->second.begin(); ait != dit->second.end(); ++ait) if (!ait->second.empty() && ait->first * digit_amount >= total_amount - m_used_total) { std::cout << "Found single large coin for digit=" << digit << " cc=" << ait->first << std::endl; auto &uns = dit->second[ait->first]; auto &un = uns.back(); m_optimization_unspents.push_back(un); m_used_total += un.amount; m_inputs_count += 1; uns.pop_back(); if (uns.empty()) dit->second.erase(ait); if (dit->second.empty()) have_coins.erase(dit); found = true; break; } } if (m_used_total >= total_amount) return true; // Use largest coins (including dust if anonymity == 0) until amount satisfied unoptimize_amounts(have_coins, dust_coins); while (m_used_total < total_amount) { if (have_coins.empty() && (anonymity != 0 || dust_coins.empty())) return false; Amount ha_amount = 0; Amount du_amount = 0; if (!have_coins.empty()) { auto dit = --have_coins.end(); auto ait = --dit->second.end(); ha_amount = ait->second.back().amount; } if (anonymity == 0 && !dust_coins.empty()) { auto duit = --dust_coins.end(); du_amount = duit->second.back().amount; } if (ha_amount > du_amount) { auto dit = --have_coins.end(); auto ait = --dit->second.end(); auto &uns = ait->second; auto &un = uns.back(); std::cout << "Found filler coin amount=" << un.amount << std::endl; m_optimization_unspents.push_back(un); m_used_total += un.amount; m_inputs_count += 1; uns.pop_back(); if (uns.empty()) dit->second.erase(ait); if (dit->second.empty()) have_coins.erase(dit); } else { auto duit = --dust_coins.end(); auto &un = duit->second.back(); std::cout << "Found filler dust coin amount=" << un.amount << std::endl; m_optimization_unspents.push_back(un); m_used_total += un.amount; m_inputs_count += 1; duit->second.pop_back(); if (duit->second.empty()) dust_coins.erase(duit); } } optimize_amounts(have_coins, max_digit, total_amount); return true; }
41.117761
120
0.681534
[ "vector" ]
b974a99cee7206f6aec538d22d0233c08da84e27
8,280
cpp
C++
adaptors/generator/skeleton/advert/###suite###_###type###_advert.cpp
saga-project/saga-cpp
7376c0de0529e7d7b80cf08b94ec484c2e56d38e
[ "BSL-1.0" ]
5
2015-09-15T16:24:14.000Z
2021-08-12T11:05:55.000Z
adaptors/generator/skeleton/advert/###suite###_###type###_advert.cpp
saga-project/saga-cpp
7376c0de0529e7d7b80cf08b94ec484c2e56d38e
[ "BSL-1.0" ]
null
null
null
adaptors/generator/skeleton/advert/###suite###_###type###_advert.cpp
saga-project/saga-cpp
7376c0de0529e7d7b80cf08b94ec484c2e56d38e
[ "BSL-1.0" ]
3
2016-11-17T04:38:38.000Z
2021-04-10T17:23:52.000Z
// Copyright (c) 2005-2007 Hartmut Kaiser // Copyright (c) 2005-2007 Andre Merzky (andre@merzky.net) // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE or copy at // http://www.boost.org/LICENSE_1_0.txt) // saga includes #include <saga/saga.hpp> // adaptor includes #include "###suite###_###type###_advert.hpp" //////////////////////////////////////////////////////////////////////// namespace ###suite###_###type### { //////////////////////////////////////////////////////////////////////// // constructor advert_cpi_impl::advert_cpi_impl (proxy * p, cpi_info const & info, saga::ini::ini const & glob_ini, saga::ini::ini const & adap_ini, TR1::shared_ptr <saga::adaptor> adaptor) : saga::adaptors::v1_0::advert_cpi <advert_cpi_impl> (p, info, adaptor, cpi::Noflags) { SAGA_ADAPTOR_THROW ("Not Implemented", saga::NotImplemented); } //////////////////////////////////////////////////////////////////////// // destructor advert_cpi_impl::~advert_cpi_impl (void) { } //////////////////////////////////////////////////////////////////////// // SAGA CPI functions // //////////////////////////////////////////////////////////////////////// // // attribute functions // void advert_cpi_impl::sync_attribute_exists (bool & ret, // std::string key) // { // SAGA_ADAPTOR_THROW ("Not Implemented", saga::NotImplemented); // } // // void advert_cpi_impl::sync_attribute_is_readonly (bool & ret, // std::string key) // { // SAGA_ADAPTOR_THROW ("Not Implemented", saga::NotImplemented); // } // // void advert_cpi_impl::sync_attribute_is_writable (bool & ret, // std::string key) // { // SAGA_ADAPTOR_THROW ("Not Implemented", saga::NotImplemented); // } // // void advert_cpi_impl::sync_attribute_is_vector (bool & ret, // std::string key) // { // SAGA_ADAPTOR_THROW ("Not Implemented", saga::NotImplemented); // } // // void advert_cpi_impl::sync_attribute_is_extended (bool & ret, // std::string key) // { // SAGA_ADAPTOR_THROW ("Not Implemented", saga::NotImplemented); // } // // //////////////////////////////////////////////////////////////////////// // void advert_cpi_impl::sync_get_attribute (std::string & ret, // std::string key) // { // SAGA_ADAPTOR_THROW ("Not Implemented", saga::NotImplemented); // } // // //////////////////////////////////////////////////////////////////////// // void advert_cpi_impl::sync_get_vector_attribute (std::vector <std::string> & ret, // std::string key) // { // SAGA_ADAPTOR_THROW ("Not Implemented", saga::NotImplemented); // } // // //////////////////////////////////////////////////////////////////////// // void advert_cpi_impl::sync_set_attribute (saga::impl::void_t & ret, // std::string key, // std::string val) // { // SAGA_ADAPTOR_THROW ("Not Implemented", saga::NotImplemented); // } // // //////////////////////////////////////////////////////////////////////// // void advert_cpi_impl::sync_set_vector_attribute (saga::impl::void_t & ret, // std::string key, // std::vector <std::string> val) // { // SAGA_ADAPTOR_THROW ("Not Implemented", saga::NotImplemented); // } // // //////////////////////////////////////////////////////////////////////// // void advert_cpi_impl::sync_remove_attribute (saga::impl::void_t & ret, // std::string key) // { // SAGA_ADAPTOR_THROW ("Not Implemented", saga::NotImplemented); // } // // //////////////////////////////////////////////////////////////////////// // void advert_cpi_impl::sync_list_attributes (std::vector <std::string> & ret) // { // SAGA_ADAPTOR_THROW ("Not Implemented", saga::NotImplemented); // } // // //////////////////////////////////////////////////////////////////////// // void advert_cpi_impl::sync_find_attributes (std::vector<std::string> & ret, // std::string pattern) // { // SAGA_ADAPTOR_THROW ("Not Implemented", saga::NotImplemented); // } // // //////////////////////////////////////////////////////////////////////// // // namespace_entry functions // void advert_cpi_impl::sync_get_url (saga::url & url) // { // SAGA_ADAPTOR_THROW ("Not Implemented", saga::NotImplemented); // } // // void advert_cpi_impl::sync_get_cwd(saga::url& url) // { // SAGA_ADAPTOR_THROW ("Not Implemented", saga::NotImplemented); // } // // void advert_cpi_impl::sync_get_name (saga::url & url) // { // SAGA_ADAPTOR_THROW ("Not Implemented", saga::NotImplemented); // } // // void advert_cpi_impl::sync_read_link (saga::url & url) // { // SAGA_ADAPTOR_THROW ("Not Implemented", saga::NotImplemented); // } // // void advert_cpi_impl::sync_is_dir (bool & ret) // { // SAGA_ADAPTOR_THROW ("Not Implemented", saga::NotImplemented); // } // // void advert_cpi_impl::sync_is_entry (bool & ret) // { // SAGA_ADAPTOR_THROW ("Not Implemented", saga::NotImplemented); // } // // void advert_cpi_impl::sync_is_link (bool & ret) // { // SAGA_ADAPTOR_THROW ("Not Implemented", saga::NotImplemented); // } // // void advert_cpi_impl::sync_copy (saga::impl::void_t & ret, // saga::url target, // int flags) // { // SAGA_ADAPTOR_THROW ("Not Implemented", saga::NotImplemented); // } // // void advert_cpi_impl::sync_link (saga::impl::void_t & ret, // saga::url target, // int flags) // { // SAGA_ADAPTOR_THROW ("Not Implemented", saga::NotImplemented); // } // // void advert_cpi_impl::sync_move (saga::impl::void_t & ret, // saga::url target, // int flags) // { // SAGA_ADAPTOR_THROW ("Not Implemented", saga::NotImplemented); // } // // void advert_cpi_impl::sync_remove (saga::impl::void_t & ret, // int flags) // { // SAGA_ADAPTOR_THROW ("Not Implemented", saga::NotImplemented); // } // // void advert_cpi_impl::sync_close (saga::impl::void_t & ret, // double timeout) // { // SAGA_ADAPTOR_THROW ("Not Implemented", saga::NotImplemented); // } // // // //////////////////////////////////////////////////////////////////////// // // advert functions // void advert_cpi_impl::sync_store_object (saga::impl::void_t & ret, // saga::object obj) // { // SAGA_ADAPTOR_THROW ("Not Implemented", saga::NotImplemented); // } // // void advert_cpi_impl::sync_retrieve_object (saga::object & ret, // saga::session s) // { // SAGA_ADAPTOR_THROW ("Not Implemented", saga::NotImplemented); // } // // void advert_cpi_impl::sync_store_string (saga::impl::void_t & ret, // std::string str) // { // SAGA_ADAPTOR_THROW ("Not Implemented", saga::NotImplemented); // } // // void advert_cpi_impl::sync_retrieve_string (std::string & ret) // { // SAGA_ADAPTOR_THROW ("Not Implemented", saga::NotImplemented); // } } // namespace ###suite###_###type### //////////////////////////////////////////////////////////////////////////
36.8
90
0.450845
[ "object", "vector" ]
b9787ba0a397dd1635bbac73dd768759d1d4a84d
26,988
cpp
C++
tools/Vitis-AI-Runtime/VART/vart/dpu-runner/src/dpu_runner_base_imp.cpp
hito0512/Vitis-AI
996459fb96cb077ed2f7e789d515893b1cccbc95
[ "Apache-2.0" ]
1
2022-02-17T22:13:23.000Z
2022-02-17T22:13:23.000Z
tools/Vitis-AI-Runtime/VART/vart/dpu-runner/src/dpu_runner_base_imp.cpp
hito0512/Vitis-AI
996459fb96cb077ed2f7e789d515893b1cccbc95
[ "Apache-2.0" ]
null
null
null
tools/Vitis-AI-Runtime/VART/vart/dpu-runner/src/dpu_runner_base_imp.cpp
hito0512/Vitis-AI
996459fb96cb077ed2f7e789d515893b1cccbc95
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2019 Xilinx Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "dpu_runner_base_imp.hpp" #include <sys/stat.h> #include <algorithm> #include <filesystem> #include <iomanip> #include <limits> // std::numeric_limits #include <vitis/ai/dim_calc.hpp> #include <vitis/ai/env_config.hpp> #include <vitis/ai/trace.hpp> #include <vitis/ai/weak.hpp> #include <xir/util/tool_function.hpp> #include "../../runner/src/runner_helper.hpp" #include "./my_openssl_md5.hpp" #include "dpu_kernel.hpp" #include "my_tensor.hpp" DEF_ENV_PARAM(XLNX_ENABLE_DUMP, "0"); DEF_ENV_PARAM(DEBUG_DPU_RUNNER, "0"); DEF_ENV_PARAM(XLNX_ENABLE_UPLOAD, "0"); DEF_ENV_PARAM(XLNX_ENABLE_CLEAR, "0"); DEF_ENV_PARAM(XLNX_SHOW_DPU_COUNTER, "0"); DEF_ENV_PARAM_2(XLNX_GOLDEN_DIR, "", std::string); DEF_ENV_PARAM(XLNX_ENABLE_FINGERPRINT_CHECK, "1"); DEF_ENV_PARAM(DEBUG_DPU_RUNNER_DRY_RUN, "0"); static bool xlnx_enable_compare_mode() { return !ENV_PARAM(XLNX_GOLDEN_DIR).empty(); } static bool xlnx_enable_debug_dpu_data_mode() { return ENV_PARAM(XLNX_ENABLE_DUMP) || ENV_PARAM(XLNX_ENABLE_UPLOAD) || ENV_PARAM(XLNX_ENABLE_CLEAR) || !ENV_PARAM(XLNX_GOLDEN_DIR).empty(); } namespace vart { namespace dpu { DpuRunnerBaseImp::DpuRunnerBaseImp( // TODO clear input_tensors // output_tensors my_input_tensors // my_output_tensors my_all_tensors const std::vector<const xir::Tensor*> input_tensors, const std::vector<const xir::Tensor*> output_tensors, DpuSessionBaseImp* session) : vart::Runner(), // input_tensors_{input_tensors}, output_tensors_{output_tensors}, session_{session} { LOG_IF(INFO, ENV_PARAM(DEBUG_DPU_RUNNER)) << "create dpu runner " << (void*)this // << " device_core_id " << session_->get_device_core_id() << " " // ; } // DpuRunnerBaseImp::~DpuRunnerBaseImp() { LOG_IF(INFO, ENV_PARAM(DEBUG_DPU_RUNNER)) << "destroying dpu runner " << (void*)this // << " device_core_id " << session_->get_device_core_id() << " " // ; } std::vector<const xir::Tensor*> DpuRunnerBaseImp::get_input_tensors() { return input_tensors_; } std::vector<const xir::Tensor*> DpuRunnerBaseImp::get_output_tensors() { return output_tensors_; } std::vector<const xir::Tensor*> DpuRunnerBaseImp::get_input_tensor( const xir::Subgraph* subgraph) { auto xir_input_tensors = subgraph->get_input_tensors(); auto input_tensors = std::vector<const xir::Tensor*>(); for (auto tensor : xir_input_tensors) { input_tensors.push_back(find_tensor(tensor->get_name()).get_tensor()); } return input_tensors; } std::vector<const xir::Tensor*> DpuRunnerBaseImp::get_output_tensor( const xir::Subgraph* subgraph) { auto xir_output_tensors = subgraph->get_output_tensors(); auto output_tensors = std::vector<const xir::Tensor*>(); for (auto tensor : xir_output_tensors) { output_tensors.push_back(find_tensor(tensor->get_name()).get_tensor()); } return output_tensors; } static int get_reg_index(const std::string& reg_id) { CHECK(reg_id.size() >= 5 && // reg_id[0] == 'R' && // reg_id[1] == 'E' && // reg_id[2] == 'G' && // reg_id[3] == '_' && // reg_id[4] >= '0' && reg_id[4] <= '9') << "reg id is not support! reg_id = " << reg_id; return reg_id[4] - '0'; } static std::vector<uint64_t> build_gen_reg( const std::map<std::string, uint64_t>& pp, size_t num_of_batch, size_t NUM_OF_REGS) { // key: "REG_0", "REG_1", or "REG_2" etc // for pp auto ret = std::vector<uint64_t>(num_of_batch * NUM_OF_REGS, std::numeric_limits<uint64_t>::max()); for (const auto& reg_value : pp) { auto idx = get_reg_index(reg_value.first); auto value = reg_value.second; LOG_IF(INFO, ENV_PARAM(DEBUG_DPU_RUNNER)) << "build_gen_reg idx " << idx << " " // << "reg_value.first " << reg_value.first << " " // << "reg_value.second " << reg_value.second << " " // ; for (auto i = 0u; i < num_of_batch; ++i) { ret[i * NUM_OF_REGS + idx] = value; } } return ret; } static std::string layer_name(const std::string& name) { (void)layer_name; auto name_remove_xfix = xir::remove_xfix(name); std::string ret; ret.reserve(name_remove_xfix.size()); std::transform(name_remove_xfix.begin(), name_remove_xfix.end(), std::back_inserter(ret), [](char c) { bool ok = c >= '0' && c <= '9'; ok = ok || (c >= 'a' && c <= 'z'); ok = ok || (c >= 'A' && c <= 'Z'); // ok = ok || (c == // std::filesystem::path::preferred_separator); ok = ok || (c == '_'); return ok ? c : '_'; }); return ret; } static bool is_exist_file(const std::string& filename) { struct stat buffer; return (stat(filename.c_str(), &buffer) == 0); } static std::string get_dump_filename(const std::string& subgraph_name, const std::string& tensor_type_str, const int engine_id, const std::string& tensor_layer_name) { const auto dump = std::filesystem::path("dump"); const auto filename = std::filesystem::path(std::to_string(engine_id) + "." + tensor_layer_name + ".bin"); return (dump / subgraph_name / tensor_type_str / filename).string(); } template <typename T> static inline std::ostream& operator<<(std::ostream& out, const std::vector<T>& v) { int c = 0; out << "["; for (const auto x : v) { if (c++ != 0) { out << ","; } out << x; } out << "]"; return out; } static std::vector<size_t> get_shape(const xir::Tensor* tensor) { auto dims = tensor->get_shape(); std::vector<size_t> shape; std::transform(dims.begin(), dims.end(), std::back_inserter(shape), [](std::int32_t n) { return static_cast<size_t>(n); }); return shape; } static std::vector<size_t> get_strides(const xir::Tensor* tensor) { auto strides = tensor->get_attr<std::vector<std::int32_t>>("stride"); std::vector<size_t> shape; std::transform(strides.begin(), strides.end(), std::back_inserter(shape), [](std::int32_t n) { return static_cast<size_t>(n); }); return shape; } static std::unique_ptr<vitis::ai::DimCalc> create_dim_calc( const xir::Tensor* tensor) { auto dims = get_shape(tensor); if (tensor->has_attr("stride")) { auto strides = get_strides(tensor); LOG_IF(INFO, ENV_PARAM(DEBUG_DPU_RUNNER) >= 2) << tensor->get_name() << " dims :" << dims << " strides :" << strides; return std::make_unique<vitis::ai::DimCalc>(dims, strides); } else { return std::make_unique<vitis::ai::DimCalc>(dims); } } static void mkdir_minus_p(const std::string& dirname) { CHECK(std::filesystem::create_directories(dirname)) << "cannot create directories: " << dirname; } bool is_exist_path(const std::string& filename) { return std::filesystem::exists(filename); } static std::string get_full_filename(const std::string& filename) { if (filename[0] == std::filesystem::path::preferred_separator) { return filename; } return (std::filesystem::current_path() / filename).string(); } static std::string get_parent_path(const std::string& path) { return path.substr( 0, path.find_last_of(std::filesystem::path::preferred_separator)); } static void create_parent_path(const std::string& path) { if (is_exist_path(path)) { LOG_IF(INFO, ENV_PARAM(DEBUG_DPU_RUNNER)) << path << " is exist!" << std::endl; return; } auto parent_path = get_parent_path(path); if (!is_exist_path(parent_path)) { create_parent_path(parent_path); } mkdir_minus_p(path); } bool DpuRunnerBaseImp::update_tensor_data_by_stride(std::vector<char>& buf, const xir::Tensor* tensor, const size_t offset) { auto dim_calc = create_dim_calc(tensor); auto dims_size = tensor->get_shape().size(); auto idx = std::vector<size_t>(dims_size, 0u); auto next_idx = std::vector<size_t>(dims_size, 0u); auto sz = 0u; auto buf_idx = 0u; auto ok = true; for (std::tie(next_idx, sz) = dim_calc->next(idx); sz > 0 && ok; idx = next_idx, std::tie(next_idx, sz) = dim_calc->next(idx)) { ok = device_memory_->upload(&buf[buf_idx], offset + dim_calc->offset(idx), sz); buf_idx += sz; } return true; } bool DpuRunnerBaseImp::download_tensor_data_by_stride(std::vector<char>& buf, const xir::Tensor* tensor, const size_t offset) { auto dim_calc = create_dim_calc(tensor); auto dims_size = tensor->get_shape().size(); auto idx = std::vector<size_t>(dims_size, 0u); auto next_idx = std::vector<size_t>(dims_size, 0u); auto sz = 0u; auto buf_idx = 0u; auto ok = true; for (std::tie(next_idx, sz) = dim_calc->next(idx); sz > 0 && ok; idx = next_idx, std::tie(next_idx, sz) = dim_calc->next(idx)) { ok = device_memory_->download(&buf[buf_idx], offset + dim_calc->offset(idx), sz); buf_idx += sz; } return ok; } void DpuRunnerBaseImp::dump_tensor(const my_tensor_t& tensor) { if (tensor.get_location() != 1u) { return; } auto reg_id = tensor.get_reg_id(); // auto is_parameter = reg_id != 1; // dirty hack /*if (is_parameter) { // TODO: dump parameters; return; }*/ auto subgraph_name = layer_name(subgraph_->get_name()); auto tensor_offset = tensor.get_ddr_addr(); auto tensor_layer_name = layer_name(tensor.get_name()); auto num_of_engines = tensor.get_batch_size(); // const size_t tensor_size = tensor.size / num_of_engines; auto tensor_size = tensor.get_feature_map_size(); auto device_core_id = session_->get_device_core_id(); auto NUM_OF_DPU_REGS = const_cast<const xir::DpuController*>(session_->get_dpu_controller()) ->get_size_of_gen_regs(device_core_id); for (auto engine_id = 0u; engine_id < num_of_engines; ++engine_id) { auto base = regs_[engine_id * NUM_OF_DPU_REGS + reg_id]; auto offset = base + tensor_offset; CHECK_NE(base, std::numeric_limits<uint64_t>::max()) << "NUM_OF_DPU_REGS " << NUM_OF_DPU_REGS << " " // << "engine_id " << engine_id << " " // << "reg_id " << reg_id << " " // ; auto filename = get_dump_filename(subgraph_name, tensor_output_dir_, engine_id, tensor_layer_name); auto buf = std::vector<char>(tensor_size); CHECK_EQ(buf.size(), (unsigned)tensor_size); auto ok = download_tensor_data_by_stride(buf, tensor.get_xir_tensor(), offset); auto full_filename = get_full_filename(filename); auto parent_path = get_parent_path(full_filename); create_parent_path(parent_path); auto mode = std::ios_base::out | std::ios_base::binary | std::ios_base::trunc; CHECK(std::ofstream(full_filename, mode).write(&buf[0], tensor_size).good()) << " faild to write to " << filename; // auto ok = device_memory_->save(filename, offset, tensor_size); auto dump_ok = ok ? "success" : "fail"; LOG(INFO) << "dump " << " to " << filename // << " device_core_id " << session_->get_device_core_id() << " " // << "reg_id " << reg_id << " " // << "base " << base << " " // << "tensor_offset " << tensor_offset << " " // << "offset " << offset << " " // << "tensor_size " << tensor_size << " " // << "dump_ok " << dump_ok << " " // ; } } void DpuRunnerBaseImp::upload_tensor(const my_tensor_t& tensor) { if (tensor.get_location() != 1) { return; } // auto subgraph_name = layer_name(subgraph_->get_name()); auto reg_id = tensor.get_reg_id(); auto is_parameter = reg_id == 0; // dirty hack if (is_parameter) { return; } auto tensor_layer_name = layer_name(tensor.get_name()); auto tensor_offset = tensor.get_ddr_addr(); auto tensor_size = tensor.get_feature_map_size(); constexpr auto NUM_OF_DPU_REGS = 8; auto engine_id = 0u; // TODO: update for other tensors? auto base = regs_[engine_id * NUM_OF_DPU_REGS + reg_id]; auto offset = base + tensor_offset; auto golden_dirname = ENV_PARAM(XLNX_GOLDEN_DIR); std::string golden_filename = (std::filesystem::path(golden_dirname) / (tensor_layer_name + ".bin")) .string(); if (!is_exist_file(golden_filename)) { LOG(INFO) << "XLNX_GOLDEN_DIR: upload data fail ! golden file is not exist : " << "layer_name " << tensor_layer_name << " "; return; } auto input_data = std::vector<char>(tensor_size); CHECK(std::ifstream(golden_filename).read(&input_data[0], tensor_size).good()) << "fail to read! filename=" << golden_filename; // auto ok = device_memory_->upload(&input_data[0], offset, tensor_size); auto ok = update_tensor_data_by_stride(input_data, tensor.get_xir_tensor(), offset); auto upload_ok = ok ? "success" : "fail"; LOG(INFO) << "XLNX_GOLDEN_DIR: upload data " << upload_ok << " ! " << " layer_name " << tensor_layer_name << " " << "device_core_id " << session_->get_device_core_id() << " " // << "reg_id " << reg_id << " " // << "base " << base << " " // << "tensor_offset " << tensor_offset << " " // << "offset " << offset << " " // << "tensor_size " << tensor_size << " " // ; } void DpuRunnerBaseImp::clear_tensor(const my_tensor_t& tensor) { if (tensor.get_location() != 1) { return; } auto reg_id = tensor.get_reg_id(); auto is_parameter = reg_id == 0; // dirty hack if (is_parameter) { return; } auto tensor_offset = tensor.get_ddr_addr(); auto tensor_layer_name = layer_name(tensor.get_name()); auto num_of_engines = tensor.get_batch_size(); // const size_t tensor_size = tensor.size / num_of_engines; auto tensor_size = tensor.get_feature_map_size(); constexpr auto NUM_OF_DPU_REGS = 8; for (auto engine_id = 0u; engine_id < num_of_engines; ++engine_id) { auto base = regs_[engine_id * NUM_OF_DPU_REGS + reg_id]; auto offset = base + tensor_offset; auto buf = std::vector<char>(tensor_size); CHECK_EQ(buf.size(), (unsigned)tensor_size); for (auto i = 0u; i < tensor_size; i++) { buf[i] = (char)(i & 0xff); } // auto ok = device_memory_->upload(&buf[0], offset, tensor_size); auto ok = update_tensor_data_by_stride(buf, tensor.get_xir_tensor(), offset); auto clear_ok = ok ? "success" : "fail"; LOG(INFO) << "clear featuremap to layer_name" << tensor_layer_name << " " << "device_core_id " << session_->get_device_core_id() << " " // << "reg_id " << reg_id << " " // << "base " << base << " " // << "tensor_offset " << tensor_offset << " " // << "offset " << offset << " " // << "tensor_size " << tensor_size << " " // << "clear_ok " << clear_ok << " " // ; } } // namespace dpu void DpuRunnerBaseImp::compare_tensor(const my_tensor_t& tensor) { if (tensor.get_location() != 1) { return; } auto reg_id = tensor.get_reg_id(); auto is_parameter = reg_id == 0; // dirty hack if (is_parameter) { return; } auto tensor_offset = tensor.get_ddr_addr(); auto tensor_layer_name = layer_name(tensor.get_name()); // const size_t tensor_size = tensor.size / num_of_engines; auto tensor_size = tensor.get_feature_map_size(); constexpr auto NUM_OF_DPU_REGS = 8; auto engine_id = 0u; // TODO : compare other engine data auto base = regs_[engine_id * NUM_OF_DPU_REGS + reg_id]; auto offset = base + tensor_offset; auto buf = std::vector<char>(tensor_size); CHECK_EQ(buf.size(), (unsigned)tensor_size); auto ok = download_tensor_data_by_stride(buf, tensor.get_xir_tensor(), offset); // auto ok = device_memory_->download(&buf[0], offset, tensor_size); if (ok) { auto dump_md5 = md5sum((const char*)&buf[0], tensor_size); auto golden_dirname = ENV_PARAM(XLNX_GOLDEN_DIR); std::string golden_filename = (std::filesystem::path(golden_dirname) / std::filesystem::path(tensor_layer_name + ".bin")) .string(); if (!is_exist_file(golden_filename)) { LOG(INFO) << "XLNX_GOLDEN_DIR: compare data fail ! golden file is " "not exist : " << "layer_name " << tensor_layer_name << " " << dump_md5 << " "; return; } auto gloden_md5 = xir::get_md5_of_file(golden_filename); bool md5_ok = dump_md5 == gloden_md5; if (md5_ok) { LOG(INFO) << "XLNX_GOLDEN_DIR: compare data success !" << "layer_name " << tensor_layer_name << " " // << "dump_md5 " << dump_md5 << " " // ; } else { LOG(INFO) << "XLNX_GOLDEN_DIR: compare data fail ! " << "layer_name " << tensor_layer_name << " " // << "dump tensor data : " << dump_md5 << " " // << "golden file : " << golden_filename << " " << gloden_md5 << " "; } } else { LOG(INFO) << "XLNX_GOLDEN_DIR: download data fail ! " << "layer_name " << tensor_layer_name << " " // << "device_core_id " << session_->get_device_core_id() << " " // << "reg_id " << reg_id << " " // << "base " << base << " " // << "tensor_offset " << tensor_offset << " " // << "offset " << offset << " " // << "tensor_size " << tensor_size << " " // << " "; } } const my_tensor_t& DpuRunnerBaseImp::find_tensor(const std::string& name) { auto it = std::find_if( session_->my_all_tensors_.begin(), session_->my_all_tensors_.end(), [&name](const auto& tensor) { return tensor.get_name() == name; }); CHECK(it != session_->my_all_tensors_.end()) << "cannot find tensor: tensor name=" << name; return *it; } static std::string to_string(const std::vector<uint64_t>& regs, size_t NUM_OF_DPU_REGS) { std::ostringstream out; out << std::hex; for (auto i = 0u; i < regs.size() / NUM_OF_DPU_REGS; ++i) { out << "\n"; for (auto j = 0u; j < NUM_OF_DPU_REGS; ++j) { out << "\t0x" << regs[i * NUM_OF_DPU_REGS + j]; } } return out.str(); } void DpuRunnerBaseImp::for_each_tensor( const std::vector<const xir::Tensor*> tensors, tensor_fun_t f) { for (auto* t : tensors) { (this->*f)(find_tensor(t->get_name())); } } std::vector<const xir::Tensor*> DpuRunnerBaseImp::get_internal_tensor( const xir::Subgraph* subgraph) { auto output_tensors = get_output_tensor(subgraph); auto is_output_tensor = [&output_tensors](const std::string& name) { bool ret = false; for (auto t : output_tensors) { if (t->get_name() == name) { ret = true; break; } } return ret; }; auto internal_ops = subgraph->get_ops(); auto ret = std::vector<const xir::Tensor*>(); for (const auto* op : internal_ops) { auto tensor_name = op->get_output_tensor()->get_name(); if (is_output_tensor(tensor_name)) { continue; } if (op->get_type() == "const-fix" || op->get_type() == "const") { continue; } ret.push_back(find_tensor(tensor_name).get_tensor()); } return ret; } void DpuRunnerBaseImp::before_run_dpu() { if (ENV_PARAM(XLNX_ENABLE_DUMP)) { tensor_output_dir_ = "input"; for_each_tensor(get_input_tensor(subgraph_), &DpuRunnerBaseImp::dump_tensor); } if (xlnx_enable_compare_mode()) { for_each_tensor(get_input_tensor(subgraph_), &DpuRunnerBaseImp::compare_tensor); } if (xlnx_enable_compare_mode() && ENV_PARAM(XLNX_ENABLE_UPLOAD)) { for_each_tensor(get_input_tensor(subgraph_), &DpuRunnerBaseImp::upload_tensor); } if (ENV_PARAM(XLNX_ENABLE_CLEAR)) { for_each_tensor(get_internal_tensor(subgraph_), &DpuRunnerBaseImp::clear_tensor); for_each_tensor(get_output_tensor(subgraph_), &DpuRunnerBaseImp::clear_tensor); } } void DpuRunnerBaseImp::after_run_dpu() { if (ENV_PARAM(XLNX_ENABLE_DUMP)) { tensor_output_dir_ = "internal"; for_each_tensor(get_internal_tensor(subgraph_), &DpuRunnerBaseImp::dump_tensor); tensor_output_dir_ = "output"; for_each_tensor(get_output_tensor(subgraph_), &DpuRunnerBaseImp::dump_tensor); } if (xlnx_enable_compare_mode()) { for_each_tensor(get_internal_tensor(subgraph_), &DpuRunnerBaseImp::compare_tensor); for_each_tensor(get_output_tensor(subgraph_), &DpuRunnerBaseImp::compare_tensor); } } void DpuRunnerBaseImp::start_dpu2(size_t device_core_id) { if (ENV_PARAM(DEBUG_DPU_RUNNER_DRY_RUN) >= 3) { LOG(INFO) << "DEBUG_DPU_RUNNER_DRY_RUN = " << ENV_PARAM(DEBUG_DPU_RUNNER_DRY_RUN) << ", ignore running dpu"; return; } auto kernel = session_->kernel_.get(); auto sg_and_code = kernel->get_code(device_core_id); auto gen_reg = build_gen_reg( kernel->get_parameter(device_core_id), session_->get_num_of_engines(), const_cast<const xir::DpuController*>(session_->get_dpu_controller()) ->get_size_of_gen_regs(device_core_id)); fill_gen_reg(device_core_id, gen_reg); if (ENV_PARAM(DEBUG_DPU_RUNNER_DRY_RUN) >= 2) { LOG(INFO) << "DEBUG_DPU_RUNNER_DRY_RUN = " << ENV_PARAM(DEBUG_DPU_RUNNER_DRY_RUN) << ", ignore running dpu"; return; } for (auto idx = 0u; idx < sg_and_code.size(); ++idx) { auto code = sg_and_code[idx].code_addr; LOG_IF(INFO, ENV_PARAM(DEBUG_DPU_RUNNER)) << "@" << (void*)this << " device_core_id=" << device_core_id // << " DPU: " << session_->get_dpu_controller()->get_full_name(device_core_id) // << ":" << session_->get_dpu_controller()->get_device_id(device_core_id) // << " running dpu code " << std::hex << " 0x" << code << std::dec << " " << "gen_reg.size() " << gen_reg.size() << " " // << "gen_reg " << to_string(gen_reg, session_->get_dpu_controller()->get_size_of_gen_regs( device_core_id)) << " " // ; if (xlnx_enable_debug_dpu_data_mode()) { prepare_envirnment(sg_and_code[idx], gen_reg, device_core_id); before_run_dpu(); } LOG_IF(INFO, ENV_PARAM(XLNX_SHOW_DPU_COUNTER)) << "subgraph name : " << layer_name(sg_and_code[idx].subgraph->get_name()); if (vitis::ai::trace::is_enabled()) { auto workload = sg_and_code[idx].subgraph->get_attr<std::uint64_t>("workload"); auto depth = sg_and_code[idx].subgraph->get_depth(); auto name = sg_and_code[idx].subgraph->get_name(); auto batch = session_->get_num_of_engines(); // MSVC NOTE: it is not safe to call template function across DLL. #if !_WIN32 vitis::ai::trace::add_trace("dpu-runner", name, batch, workload, depth); #endif } LOG_IF(FATAL, ENV_PARAM(XLNX_ENABLE_FINGERPRINT_CHECK) && !check_fingerprint(session_->get_device_core_id())) << "fingerprint check failure."; if (!ENV_PARAM(DEBUG_DPU_RUNNER_DRY_RUN)) { session_->get_dpu_controller()->run(device_core_id, code, gen_reg); } if (xlnx_enable_debug_dpu_data_mode()) { after_run_dpu(); clear_environment(); } } } bool DpuRunnerBaseImp::check_fingerprint(size_t device_core_id) { auto model_fingerprint = session_->kernel_->get_fingerprint(); auto dpu_fingerprint = session_->get_dpu_controller()->get_fingerprint(device_core_id); auto ret = model_fingerprint == dpu_fingerprint; if (model_fingerprint == 0u) { // for elf file or debugging purpuse, if xmodel does not contain // a fingerprint, it is zero, and we ignore fingerprint // checkout. ret = true; } if (dpu_fingerprint == 0u) { // for vivado flow, we do not support finger print checking so disable it. return true; } if (!ret) { LOG_IF(WARNING, model_fingerprint != 0u && dpu_fingerprint != 0u) << "CHECK fingerprint fail ! model_fingerprint 0x" // << std::hex << model_fingerprint << std::dec << " " // << "dpu_fingerprint 0x" // << std::hex << dpu_fingerprint << std::dec << " " // ; } return ret; } void DpuRunnerBaseImp::prepare_envirnment( const DpuKernel::SubgraphCode& sg_and_code, const std::vector<uint64_t>& gen_reg, size_t device_core_id) { subgraph_ = sg_and_code.subgraph; regs_ = gen_reg; get_device_memory(); } void DpuRunnerBaseImp::clear_environment() { device_memory_ = nullptr; } xir::DeviceMemory* DpuRunnerBaseImp::get_device_memory() { if (!device_memory_) { auto device_id = session_->get_dpu_controller()->get_device_id( session_->get_device_core_id()); device_memory_ = vitis::ai::WeakStore<size_t, xir::DeviceMemory>::create( device_id, device_id); } return device_memory_.get(); } } // namespace dpu } // namespace vart
38.17256
80
0.598414
[ "shape", "vector", "transform" ]
b9792c2a38b458f6a85ddeac974deff9ef9db653
2,733
cc
C++
services/ui/ws/window_finder.cc
google-ar/chromium
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
777
2017-08-29T15:15:32.000Z
2022-03-21T05:29:41.000Z
services/ui/ws/window_finder.cc
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
66
2017-08-30T18:31:18.000Z
2021-08-02T10:59:35.000Z
services/ui/ws/window_finder.cc
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
123
2017-08-30T01:19:34.000Z
2022-03-17T22:55:31.000Z
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "services/ui/ws/window_finder.h" #include "base/containers/adapters.h" #include "services/ui/ws/server_window.h" #include "services/ui/ws/server_window_compositor_frame_sink_manager.h" #include "services/ui/ws/server_window_delegate.h" #include "services/ui/ws/window_coordinate_conversions.h" #include "ui/gfx/geometry/point.h" #include "ui/gfx/geometry/point_f.h" #include "ui/gfx/transform.h" namespace ui { namespace ws { bool IsValidWindowForEvents(ServerWindow* window) { ServerWindowCompositorFrameSinkManager* compositor_frame_sink_manager = window->compositor_frame_sink_manager(); // Valid windows have at least one of the two surface types. Only an underlay // is valid as we assume the window manager will likely get the event in this // case. return compositor_frame_sink_manager && compositor_frame_sink_manager->HasCompositorFrameSink(); } ServerWindow* FindDeepestVisibleWindowForEvents(ServerWindow* window, gfx::Point* location) { if (!window->can_accept_events()) return nullptr; const ServerWindow::Windows& children = window->children(); const gfx::Point original_location = *location; for (ServerWindow* child : base::Reversed(children)) { if (!child->visible() || !child->can_accept_events()) continue; // TODO(sky): support transform. gfx::Point location_in_child(original_location.x() - child->bounds().x(), original_location.y() - child->bounds().y()); gfx::Rect child_bounds(child->bounds().size()); child_bounds.Inset(-child->extended_hit_test_region().left(), -child->extended_hit_test_region().top(), -child->extended_hit_test_region().right(), -child->extended_hit_test_region().bottom()); if (!child_bounds.Contains(location_in_child) || (child->hit_test_mask() && !child->hit_test_mask()->Contains(location_in_child))) { continue; } *location = location_in_child; ServerWindow* result = FindDeepestVisibleWindowForEvents(child, location); if (result) return result; } return IsValidWindowForEvents(window) ? window : nullptr; } gfx::Transform GetTransformToWindow(ServerWindow* window) { gfx::Transform transform; ServerWindow* current = window; while (current->parent()) { transform.Translate(-current->bounds().x(), -current->bounds().y()); current = current->parent(); } return transform; } } // namespace ws } // namespace ui
36.932432
79
0.690816
[ "geometry", "transform" ]
b97b07b55f8b6374681af23cf977277aacfd4fb0
973
cpp
C++
examples/paths/raytest.cpp
gruni55/goat
754aca5c2f18436682d944958ab85a42b5230f22
[ "BSD-3-Clause" ]
1
2022-03-30T18:52:09.000Z
2022-03-30T18:52:09.000Z
examples/paths/raytest.cpp
gruni55/goat
754aca5c2f18436682d944958ab85a42b5230f22
[ "BSD-3-Clause" ]
null
null
null
examples/paths/raytest.cpp
gruni55/goat
754aca5c2f18436682d944958ab85a42b5230f22
[ "BSD-3-Clause" ]
null
null
null
#include <iostream> #include "ellipsoid.h" #include "lightsrc.h" #include "raytrace.h" #include "vector.h" #include <fstream> #include "surface.h" #include "octree.h" #include "detector.h" int main() { Scene S; // define object const int numberObjects = 1; Ellipsoid obj(Vector<double> (0,0,-10),Vector<double>(30,10,10),1.5); obj.setBeta(50.0 / 180.0 * M_PI); S.setr0(100); S.addObject(&obj); Ellipsoid obj2(Vector<double>(-60, 0, -20), Vector<double>(10, 10, 20), 1.6); obj2.setBeta(-30.0 / 180.0 * M_PI); S.addObject(&obj2); LightSrcPlane ls = LightSrcPlane(-50.0 * ez, 30, 1.0, 30.0 ); S.addLightSource(&ls); LightSrcGauss ls2(Vector<double>(-60.0, 0.0, 20.0), 20, 1.0, 0.1, Vector<double>(-60.0, 0.0, 0.0)); ls2.setNA(0.9); S.addLightSource(&ls2); Raytrace_Path rp; rp.setShowOutgoingRays(false); rp.setScene(S); rp.trace("test.dat"); }
24.325
104
0.5889
[ "object", "vector" ]
b97c2cf24b4cdb89c24d344ab577e9df0d1ed2c2
6,074
cpp
C++
src/steerableDetector_mex.cpp
francois-a/steerable
a740cbf06cb6b0e0ca3b30f0697beb1418de8ff6
[ "MIT" ]
1
2020-06-30T19:08:31.000Z
2020-06-30T19:08:31.000Z
src/steerableDetector_mex.cpp
francois-a/steerable
a740cbf06cb6b0e0ca3b30f0697beb1418de8ff6
[ "MIT" ]
null
null
null
src/steerableDetector_mex.cpp
francois-a/steerable
a740cbf06cb6b0e0ca3b30f0697beb1418de8ff6
[ "MIT" ]
1
2022-02-01T10:41:22.000Z
2022-02-01T10:41:22.000Z
/* steerableDetector: steerable filters for edge and ridge detection References: [1] Jacob and Unser, IEEE Trans. Pattern Anal. Mach. Intell. 26(8), 2004. Copyright (c) 2005-2017 Francois Aguet Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <string> #include "mex.h" #include "steerableDetector.h" void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { // check # inputs if (nrhs < 3 || nrhs > 5) mexErrMsgTxt("Required inputs arguments: image, filter order, sigma.\nOptional: # angles for rotations output; border condition (see help)."); if (nlhs > 4) mexErrMsgTxt("Too many output arguments."); // check image if (!mxIsDouble(prhs[0]) || mxGetNumberOfDimensions(prhs[0]) != 2) mexErrMsgTxt("Input image must be a 2-D array."); size_t nx = (size_t)mxGetN(prhs[0]); // cols size_t ny = (size_t)mxGetM(prhs[0]); int N = nx*ny; double* input = mxGetPr(prhs[0]); // check for NaNs in input, as these will result in a crash for (int i=0;i<N;++i) { if (mxIsNaN(input[i])) { mexErrMsgTxt("Input image contains NaNs."); break; } } // check order if (!mxIsDouble(prhs[1]) || mxGetNumberOfElements(prhs[1]) != 1 || *mxGetPr(prhs[1])<1 || *mxGetPr(prhs[1])>5) mexErrMsgTxt("The order 'M' must be an integer between 1 and 5."); int M = (int) *mxGetPr(prhs[1]); // check sigma if (!mxIsDouble(prhs[2]) || mxGetNumberOfElements(prhs[2]) != 1 || *mxGetPr(prhs[2]) <= 0.0) mexErrMsgTxt("Sigma must be a strictly positive scalar value."); double sigma = *mxGetPr(prhs[2]); // Set defaults for options int borderCondition = 3; size_t nt = 36; // check 1st option: angles or border condition if (nrhs >= 4) { for (int i=3;i<nrhs;++i) { if (mxIsDouble(prhs[i]) && *mxGetPr(prhs[i])>0) { // # angles nt = (size_t) *mxGetPr(prhs[i]); } else if (mxIsChar(prhs[i])) { // border condition size_t nchar = mxGetNumberOfElements(prhs[i])+1; char *ch = new char[nchar]; int f = mxGetString(prhs[i], ch, nchar); if (f!=0) { mexErrMsgTxt("Error parsing border condition."); } std::string str = ch; delete[] ch; int (*pf)(int) = tolower; transform(str.begin(), str.end(), str.begin(), pf); if (str.compare("mirror")==0) { borderCondition = 3; } else if (str.compare("periodic")==0) { borderCondition = 2; } else if (str.compare("replicate")==0) { borderCondition = 1; } else if (str.compare("zeros")==0) { borderCondition = 0; } else { mexErrMsgTxt("Unsupported border conditions."); } } else { mexErrMsgTxt("Allowed options: # angles (must be ? 1) or border condition."); } } } int L = 2*(int)(4.0*sigma)+1; // support of the Gaussian kernels if (L>nx || L>ny) { mexPrintf("Sigma must be smaller than %.2f\n", (std::min(nx,ny)-1)/8.0); mexErrMsgTxt("Sigma value results in filter support that is larger than image."); } double* pixels = new double[N]; // Process inputs // Switch matrix to row-major (Matlab uses column-major) div_t divRes; for (int i=0;i<N;++i) { divRes = div(i, ny); pixels[divRes.quot+divRes.rem*nx] = input[i]; } steerable::SteerableDetector sd = steerable::SteerableDetector(pixels, nx, ny, M, sigma, borderCondition); sd.filter(); // Process outputs // Switch outputs back to column-major format if (nlhs > 0) { for (int i=0;i<N;++i) { divRes = div(i, nx); pixels[divRes.quot+divRes.rem*ny] = sd.response_[i]; } plhs[0] = mxCreateDoubleMatrix(ny, nx, mxREAL); memcpy(mxGetPr(plhs[0]), pixels, N*sizeof(double)); } if (nlhs > 1) { // return orientation map for (int i=0;i<N;++i) { divRes = div(i, nx); pixels[divRes.quot+divRes.rem*ny] = sd.orientation_[i]; } plhs[1] = mxCreateDoubleMatrix(ny, nx, mxREAL); memcpy(mxGetPr(plhs[1]), pixels, N*sizeof(double)); } if (nlhs > 2) { // run NMS sd.runNMS(); for (int i=0;i<N;++i) { divRes = div(i, nx); pixels[divRes.quot+divRes.rem*ny] = sd.nms_response_[i]; } plhs[2] = mxCreateDoubleMatrix(ny, nx, mxREAL); memcpy(mxGetPr(plhs[2]), pixels, N*sizeof(double)); } if (nlhs > 3) { // return filterbank const mwSize dims[] = {ny, nx, nt}; plhs[3] = mxCreateNumericArray(3, dims, mxDOUBLE_CLASS, mxREAL); double* p = mxGetPr(plhs[3]); sd.getAngleResponse(p, nt); } // Free memory delete[] pixels; }
36.812121
150
0.585117
[ "transform" ]
b98233b59ed79c18ca333395c0935456d4e8b387
7,633
cpp
C++
src/lib/model/CrossoverModel.cpp
gerickson/openhlx
f23a825ca56ee226db393da14d81a7d4e9ae0b33
[ "Apache-2.0" ]
1
2021-05-21T21:10:09.000Z
2021-05-21T21:10:09.000Z
src/lib/model/CrossoverModel.cpp
gerickson/openhlx
f23a825ca56ee226db393da14d81a7d4e9ae0b33
[ "Apache-2.0" ]
12
2021-06-12T16:42:30.000Z
2022-02-01T18:44:42.000Z
src/lib/model/CrossoverModel.cpp
gerickson/openhlx
f23a825ca56ee226db393da14d81a7d4e9ae0b33
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2020-2021 Grant Erickson * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an "AS * IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language * governing permissions and limitations under the License. * */ /** * @file * This file implements an object for managing a HLX zone DSP sound * model high- or lowpass crossover data model. * */ #include "CrossoverModel.hpp" #include <utility> #include <errno.h> #include <LogUtilities/LogUtilities.hpp> #include <OpenHLX/Common/Errors.hpp> #include <OpenHLX/Utilities/Assert.hpp> using namespace HLX::Common; using namespace Nuovations; namespace HLX { namespace Model { static const CrossoverModel::FrequencyType kFrequencyDefault = 100; /** * @brief * This is a class constructor. * * @param[in] aFrequencyLimits An immutable reference to the * crossover frequency limits to * construct the model with. * * This constructions a crossover model with the specified frequency * limits. * */ CrossoverModel :: CrossoverModel(const FrequencyLimits &aFrequencyLimits) : mFrequencyLimits(aFrequencyLimits), mFrequencyIsNull(true), mFrequency(kFrequencyDefault) { return; } /** * @brief * This is the class default initializer. * * This initializes the model with a null filter crossover frequency. * * The frequency must be explicitly set with #SetFrequency before * #GetFrequency may be used successfully. * * @retval kStatus_Success If successful. * * @sa SetFrequency * */ Status CrossoverModel :: Init(void) { Status lRetval = kStatus_Success; mFrequency = kFrequencyDefault; mFrequencyIsNull = true; return (lRetval); } /** * @brief * This is a class initializer. * * This initializes the model with the specified crossover frequency. * * @param[in] aFrequency An immutable reference to the crossover * frequency to initialize the model with. * * @retval kStatus_Success If successful. * @retval -ERANGE The specified @a aFrequency value * is out of range. * */ Status CrossoverModel :: Init(const FrequencyType &aFrequency) { Status lRetval = kStatus_Success; lRetval = SetFrequency(aFrequency); nlREQUIRE(lRetval >= kStatus_Success, done); done: if (lRetval == kStatus_ValueAlreadySet) { lRetval = kStatus_Success; } return (lRetval); } /** * @brief * This is a class copy initializer. * * This initializes the class with the specified crossover model. * * @param[in] aCrossoverModel An immutable reference to the crossover * model to initialize with. * * @retval kStatus_Success If successful. * */ Status CrossoverModel :: Init(const CrossoverModel &aCrossoverModel) { Status lRetval = kStatus_Success; *this = aCrossoverModel; return (lRetval); } /** * @brief * This is a class assignment (copy) operator. * * This assigns (copies) the specified crossover model to this one. * * @param[in] aCrossoverModel An immutable reference to the crossover * model to assign (copy) to this one. * * * @returns * A reference to this crossover model after the assignment (copy) * is complete. * */ CrossoverModel & CrossoverModel :: operator =(const CrossoverModel &aCrossoverModel) { mFrequencyIsNull = aCrossoverModel.mFrequencyIsNull; mFrequency = aCrossoverModel.mFrequency; return (*this); } /** * @brief * Attempt to get the filter crossover frequency limits. * * This attempts to get the filter crossover frequency limits. * * @param[out] aFrequencyLimits A mutable reference to storage for the * filter crossover frequency limits. * * @retval kStatus_Success If successful. * */ Status CrossoverModel :: GetFrequencyLimits(FrequencyLimits &aFrequencyLimits) const { Status lRetval = kStatus_Success; aFrequencyLimits.mMin = mFrequencyLimits.mMin; aFrequencyLimits.mMax = mFrequencyLimits.mMax; return (lRetval); } /** * @brief * Attempt to get the filter crossover frequency. * * This attempts to get the filter crossover frequency, if it has * been previously initialized or set. * * @param[out] aFrequency A mutable reference to storage for the * filter crossover frequency, if * successful. * * @retval kStatus_Success If successful. * @retval kError_NotInitialized If the crossover model frequency * value has not been initialized * with a known value. * * @sa Init * @sa SetFrequency * */ Status CrossoverModel :: GetFrequency(FrequencyType &aFrequency) const { Status lRetval = ((mFrequencyIsNull) ? kError_NotInitialized : kStatus_Success); if (lRetval == kStatus_Success) { aFrequency = mFrequency; } return (lRetval); } /** * @brief * This sets the model filter crossover frequency. * * This initializes the model with the specified filter crossover * frequency. * * @param[in] aFrequency An immutable reference to the filter * crossover frequency to set. * * @retval kStatus_Success If successful. * @retval kStatus_ValueAlreadySet The specified @a aFrequency * value has already been set. * @retval -ERANGE The specified @a aFrequency * value is out of range. * */ Status CrossoverModel :: SetFrequency(const FrequencyType &aFrequency) { Status lRetval = kStatus_Success; nlREQUIRE_ACTION(aFrequency >= mFrequencyLimits.mMin, done, lRetval = -ERANGE); nlREQUIRE_ACTION(aFrequency <= mFrequencyLimits.mMax, done, lRetval = -ERANGE); if (mFrequency == aFrequency) { lRetval = ((mFrequencyIsNull) ? kStatus_Success : kStatus_ValueAlreadySet); } else { mFrequency = aFrequency; } mFrequencyIsNull = false; done: return (lRetval); } /** * @brief * This is a class equality operator. * * This compares the provided crossover model against this one to * determine if they are equal to one another. * * @param[in] aCrossoverModel An immutable reference to the * crossover model to compare * for equality. * * @returns * True if this crossover model is equal to the specified one; * otherwise, false. * */ bool CrossoverModel :: operator ==(const CrossoverModel &aCrossoverModel) const { return ((mFrequencyLimits.mMin == aCrossoverModel.mFrequencyLimits.mMin) && (mFrequencyLimits.mMax == aCrossoverModel.mFrequencyLimits.mMax) && (mFrequencyIsNull == aCrossoverModel.mFrequencyIsNull ) && (mFrequency == aCrossoverModel.mFrequency )); } }; // namespace Model }; // namespace HLX
25.787162
84
0.64326
[ "object", "model" ]
b9902363c7667b79e43a2cef698fe53e6784bfcf
15,479
cc
C++
gnuradio-3.7.13.4/gnuradio-runtime/lib/flowgraph.cc
v1259397/cosmic-gnuradio
64c149520ac6a7d44179c3f4a38f38add45dd5dc
[ "BSD-3-Clause" ]
1
2021-03-09T07:32:37.000Z
2021-03-09T07:32:37.000Z
gnuradio-3.7.13.4/gnuradio-runtime/lib/flowgraph.cc
v1259397/cosmic-gnuradio
64c149520ac6a7d44179c3f4a38f38add45dd5dc
[ "BSD-3-Clause" ]
null
null
null
gnuradio-3.7.13.4/gnuradio-runtime/lib/flowgraph.cc
v1259397/cosmic-gnuradio
64c149520ac6a7d44179c3f4a38f38add45dd5dc
[ "BSD-3-Clause" ]
null
null
null
/* -*- c++ -*- */ /* * Copyright 2007,2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <gnuradio/flowgraph.h> #include <stdexcept> #include <sstream> #include <iterator> namespace gr { #define FLOWGRAPH_DEBUG 0 edge::~edge() { } flowgraph_sptr make_flowgraph() { return flowgraph_sptr(new flowgraph()); } flowgraph::flowgraph() { } flowgraph::~flowgraph() { } template<class T> static std::vector<T> unique_vector(std::vector<T> v) { std::vector<T> result; std::insert_iterator<std::vector<T> > inserter(result, result.begin()); sort(v.begin(), v.end()); unique_copy(v.begin(), v.end(), inserter); return result; } void flowgraph::connect(const endpoint &src, const endpoint &dst) { check_valid_port(src.block()->output_signature(), src.port()); check_valid_port(dst.block()->input_signature(), dst.port()); check_dst_not_used(dst); check_type_match(src, dst); // Alles klar, Herr Kommissar d_edges.push_back(edge(src,dst)); } void flowgraph::disconnect(const endpoint &src, const endpoint &dst) { for(edge_viter_t p = d_edges.begin(); p != d_edges.end(); p++) { if(src == p->src() && dst == p->dst()) { d_edges.erase(p); return; } } std::stringstream msg; msg << "cannot disconnect edge " << edge(src, dst) << ", not found"; throw std::invalid_argument(msg.str()); } void flowgraph::validate() { d_blocks = calc_used_blocks(); for(basic_block_viter_t p = d_blocks.begin(); p != d_blocks.end(); p++) { std::vector<int> used_ports; int ninputs, noutputs; if(FLOWGRAPH_DEBUG) std::cout << "Validating block: " << (*p) << std::endl; used_ports = calc_used_ports(*p, true); // inputs ninputs = used_ports.size(); check_contiguity(*p, used_ports, true); // inputs used_ports = calc_used_ports(*p, false); // outputs noutputs = used_ports.size(); check_contiguity(*p, used_ports, false); // outputs if(!((*p)->check_topology(ninputs, noutputs))) { std::stringstream msg; msg << "check topology failed on " << (*p) << " using ninputs=" << ninputs << ", noutputs=" << noutputs; throw std::runtime_error(msg.str()); } } } void flowgraph::clear() { // Boost shared pointers will deallocate as needed d_blocks.clear(); d_edges.clear(); } void flowgraph::check_valid_port(gr::io_signature::sptr sig, int port) { std::stringstream msg; if(port < 0) { msg << "negative port number " << port << " is invalid"; throw std::invalid_argument(msg.str()); } int max = sig->max_streams(); if(max != io_signature::IO_INFINITE && port >= max) { msg << "port number " << port << " exceeds max of "; if(max == 0) msg << "(none)"; else msg << max-1; throw std::invalid_argument(msg.str()); } } void flowgraph::check_valid_port(const msg_endpoint &e) { if(FLOWGRAPH_DEBUG) std::cout << "check_valid_port( " << e.block() << ", " << e.port() << ")\n"; if(!e.block()->has_msg_port(e.port())) { const gr::basic_block::msg_queue_map_t& msg_map = e.block()->get_msg_map(); std::cout << "Could not find port: " << e.port() << " in:" << std::endl; for (gr::basic_block::msg_queue_map_t::const_iterator it = msg_map.begin(); it != msg_map.end(); ++it) std::cout << it->first << std::endl; std::cout << std::endl; throw std::invalid_argument("invalid msg port in connect() or disconnect()"); } } void flowgraph::check_dst_not_used(const endpoint &dst) { // A destination is in use if it is already on the edge list for(edge_viter_t p = d_edges.begin(); p != d_edges.end(); p++) if(p->dst() == dst) { std::stringstream msg; msg << "destination already in use by edge " << (*p); throw std::invalid_argument(msg.str()); } } void flowgraph::check_type_match(const endpoint &src, const endpoint &dst) { int src_size = src.block()->output_signature()->sizeof_stream_item(src.port()); int dst_size = dst.block()->input_signature()->sizeof_stream_item(dst.port()); if(src_size != dst_size) { std::stringstream msg; msg << "itemsize mismatch: " << src << " using " << src_size << ", " << dst << " using " << dst_size; throw std::invalid_argument(msg.str()); } } basic_block_vector_t flowgraph::calc_used_blocks() { basic_block_vector_t tmp; // make sure free standing message blocks are included for(msg_edge_viter_t p = d_msg_edges.begin(); p != d_msg_edges.end(); p++) { // all msg blocks need a thread context - otherwise start() will never be called! // even if it is a sender that never does anything tmp.push_back(p->src().block()); tmp.push_back(p->dst().block()); } // Collect all blocks in the edge list for(edge_viter_t p = d_edges.begin(); p != d_edges.end(); p++) { tmp.push_back(p->src().block()); tmp.push_back(p->dst().block()); } return unique_vector<basic_block_sptr>(tmp); } std::vector<int> flowgraph::calc_used_ports(basic_block_sptr block, bool check_inputs) { std::vector<int> tmp; // Collect all seen ports edge_vector_t edges = calc_connections(block, check_inputs); for(edge_viter_t p = edges.begin(); p != edges.end(); p++) { if(check_inputs == true) tmp.push_back(p->dst().port()); else tmp.push_back(p->src().port()); } return unique_vector<int>(tmp); } edge_vector_t flowgraph::calc_connections(basic_block_sptr block, bool check_inputs) { edge_vector_t result; for(edge_viter_t p = d_edges.begin(); p != d_edges.end(); p++) { if(check_inputs) { if(p->dst().block() == block) result.push_back(*p); } else { if(p->src().block() == block) result.push_back(*p); } } return result; // assumes no duplicates } void flowgraph::check_contiguity(basic_block_sptr block, const std::vector<int> &used_ports, bool check_inputs) { std::stringstream msg; gr::io_signature::sptr sig = check_inputs ? block->input_signature() : block->output_signature(); int nports = used_ports.size(); int min_ports = sig->min_streams(); int max_ports = sig->max_streams(); if(nports == 0 && min_ports == 0) return; if(nports < min_ports) { msg << block << ": insufficient connected " << (check_inputs ? "input ports " : "output ports ") << "(" << min_ports << " needed, " << nports << " connected)"; throw std::runtime_error(msg.str()); } if(nports > max_ports && max_ports != io_signature::IO_INFINITE) { msg << block << ": too many connected " << (check_inputs ? "input ports " : "output ports ") << "(" << max_ports << " allowed, " << nports << " connected)"; throw std::runtime_error(msg.str()); } if(used_ports[nports-1]+1 != nports) { for(int i = 0; i < nports; i++) { if(used_ports[i] != i) { msg << block << ": missing connection " << (check_inputs ? "to input port " : "from output port ") << i; throw std::runtime_error(msg.str()); } } } } basic_block_vector_t flowgraph::calc_downstream_blocks(basic_block_sptr block, int port) { basic_block_vector_t tmp; for(edge_viter_t p = d_edges.begin(); p != d_edges.end(); p++) if(p->src() == endpoint(block, port)) tmp.push_back(p->dst().block()); return unique_vector<basic_block_sptr>(tmp); } basic_block_vector_t flowgraph::calc_downstream_blocks(basic_block_sptr block) { basic_block_vector_t tmp; for(edge_viter_t p = d_edges.begin(); p != d_edges.end(); p++) if(p->src().block() == block) tmp.push_back(p->dst().block()); return unique_vector<basic_block_sptr>(tmp); } edge_vector_t flowgraph::calc_upstream_edges(basic_block_sptr block) { edge_vector_t result; for(edge_viter_t p = d_edges.begin(); p != d_edges.end(); p++) if(p->dst().block() == block) result.push_back(*p); return result; // Assume no duplicates } bool flowgraph::has_block_p(basic_block_sptr block) { basic_block_viter_t result; result = std::find(d_blocks.begin(), d_blocks.end(), block); return (result != d_blocks.end()); } edge flowgraph::calc_upstream_edge(basic_block_sptr block, int port) { edge result; for(edge_viter_t p = d_edges.begin(); p != d_edges.end(); p++) { if(p->dst() == endpoint(block, port)) { result = (*p); break; } } return result; } std::vector<basic_block_vector_t> flowgraph::partition() { std::vector<basic_block_vector_t> result; basic_block_vector_t blocks = calc_used_blocks(); basic_block_vector_t graph; while(blocks.size() > 0) { graph = calc_reachable_blocks(blocks[0], blocks); assert(graph.size()); result.push_back(topological_sort(graph)); for(basic_block_viter_t p = graph.begin(); p != graph.end(); p++) blocks.erase(find(blocks.begin(), blocks.end(), *p)); } return result; } basic_block_vector_t flowgraph::calc_reachable_blocks(basic_block_sptr block, basic_block_vector_t &blocks) { basic_block_vector_t result; // Mark all blocks as unvisited for(basic_block_viter_t p = blocks.begin(); p != blocks.end(); p++) (*p)->set_color(basic_block::WHITE); // Recursively mark all reachable blocks reachable_dfs_visit(block, blocks); // Collect all the blocks that have been visited for(basic_block_viter_t p = blocks.begin(); p != blocks.end(); p++) if((*p)->color() == basic_block::BLACK) result.push_back(*p); return result; } // Recursively mark all reachable blocks from given block and block list void flowgraph::reachable_dfs_visit(basic_block_sptr block, basic_block_vector_t &blocks) { // Mark the current one as visited block->set_color(basic_block::BLACK); // Recurse into adjacent vertices basic_block_vector_t adjacent = calc_adjacent_blocks(block, blocks); for(basic_block_viter_t p = adjacent.begin(); p != adjacent.end(); p++) if((*p)->color() == basic_block::WHITE) reachable_dfs_visit(*p, blocks); } // Return a list of block adjacent to a given block along any edge basic_block_vector_t flowgraph::calc_adjacent_blocks(basic_block_sptr block, basic_block_vector_t &blocks) { basic_block_vector_t tmp; // Find any blocks that are inputs or outputs for(edge_viter_t p = d_edges.begin(); p != d_edges.end(); p++) { if(p->src().block() == block) tmp.push_back(p->dst().block()); if(p->dst().block() == block) tmp.push_back(p->src().block()); } return unique_vector<basic_block_sptr>(tmp); } basic_block_vector_t flowgraph::topological_sort(basic_block_vector_t &blocks) { basic_block_vector_t tmp; basic_block_vector_t result; tmp = sort_sources_first(blocks); // Start 'em all white for(basic_block_viter_t p = tmp.begin(); p != tmp.end(); p++) (*p)->set_color(basic_block::WHITE); for(basic_block_viter_t p = tmp.begin(); p != tmp.end(); p++) { if((*p)->color() == basic_block::WHITE) topological_dfs_visit(*p, result); } reverse(result.begin(), result.end()); return result; } basic_block_vector_t flowgraph::sort_sources_first(basic_block_vector_t &blocks) { basic_block_vector_t sources, nonsources, result; for(basic_block_viter_t p = blocks.begin(); p != blocks.end(); p++) { if(source_p(*p)) sources.push_back(*p); else nonsources.push_back(*p); } for(basic_block_viter_t p = sources.begin(); p != sources.end(); p++) result.push_back(*p); for(basic_block_viter_t p = nonsources.begin(); p != nonsources.end(); p++) result.push_back(*p); return result; } bool flowgraph::source_p(basic_block_sptr block) { return (calc_upstream_edges(block).size() == 0); } void flowgraph::topological_dfs_visit(basic_block_sptr block, basic_block_vector_t &output) { block->set_color(basic_block::GREY); basic_block_vector_t blocks(calc_downstream_blocks(block)); for(basic_block_viter_t p = blocks.begin(); p != blocks.end(); p++) { switch((*p)->color()) { case basic_block::WHITE: topological_dfs_visit(*p, output); break; case basic_block::GREY: throw std::runtime_error("flow graph has loops!"); case basic_block::BLACK: continue; default: throw std::runtime_error("invalid color on block!"); } } block->set_color(basic_block::BLACK); output.push_back(block); } void flowgraph::connect(const msg_endpoint &src, const msg_endpoint &dst) { check_valid_port(src); check_valid_port(dst); for(msg_edge_viter_t p = d_msg_edges.begin(); p != d_msg_edges.end(); p++) { if(p->src() == src && p->dst() == dst){ throw std::runtime_error("connect called on already connected edge!"); } } d_msg_edges.push_back(msg_edge(src,dst)); } void flowgraph::disconnect(const msg_endpoint &src, const msg_endpoint &dst) { check_valid_port(src); check_valid_port(dst); for(msg_edge_viter_t p = d_msg_edges.begin(); p != d_msg_edges.end(); p++) { if(p->src() == src && p->dst() == dst){ d_msg_edges.erase(p); return; } } throw std::runtime_error("disconnect called on non-connected edge!"); } std::string dot_graph_fg(flowgraph_sptr fg) { basic_block_vector_t blocks = fg->calc_used_blocks(); edge_vector_t edges = fg->edges(); std::stringstream out; out << "digraph flowgraph {" << std::endl; // Define nodes and set labels for(basic_block_viter_t block = blocks.begin(); block != blocks.end(); ++block) { out << (*block)->unique_id() << " [ label=\"" << (*block)->name() << "\" ]" << std::endl; } // Define edges for(edge_viter_t edge = edges.begin(); edge != edges.end(); ++edge) { out << edge->src().block()->unique_id() << " -> " << edge->dst().block()->unique_id() << std::endl; } out << "}" << std::endl; return out.str(); } } /* namespace gr */
27.839928
108
0.616125
[ "vector" ]
b9945508710a14596554fad3438c3a39e09cc4ae
8,621
cpp
C++
src/reader_struct.cpp
glynnc/liblcf
301371de7d8e39f30c464ace355252b58beb71ee
[ "MIT" ]
null
null
null
src/reader_struct.cpp
glynnc/liblcf
301371de7d8e39f30c464ace355252b58beb71ee
[ "MIT" ]
null
null
null
src/reader_struct.cpp
glynnc/liblcf
301371de7d8e39f30c464ace355252b58beb71ee
[ "MIT" ]
null
null
null
/* * Copyright (c) 2014 liblcf authors * This file is released under the MIT License * http://opensource.org/licenses/MIT */ #include <cstring> #include <iostream> #include <iomanip> #include "ldb_reader.h" #include "lmt_reader.h" #include "lmu_reader.h" #include "lsd_reader.h" #include "reader_struct.h" #include "rpg_save.h" // Read/Write Struct template <class S> void Struct<S>::MakeFieldMap() { if (!field_map.empty()) return; for (int i = 0; fields[i] != NULL; i++) field_map[fields[i]->id] = fields[i]; } template <class S> void Struct<S>::MakeTagMap() { if (!tag_map.empty()) return; for (int i = 0; fields[i] != NULL; i++) tag_map[fields[i]->name] = fields[i]; } template <class S> void Struct<S>::ReadLcf(S& obj, LcfReader& stream) { MakeFieldMap(); LcfReader::Chunk chunk_info; while (!stream.Eof()) { chunk_info.ID = stream.ReadInt(); if (chunk_info.ID == 0) break; chunk_info.length = stream.ReadInt(); if (chunk_info.length == 0) continue; typename field_map_type::const_iterator it = field_map.find(chunk_info.ID); if (it != field_map.end()) { #ifdef LCF_DEBUG_TRACE printf("0x%02x (size: %d, pos: 0x%x): %s\n", chunk_info.ID, chunk_info.length, stream.Tell(), it->second->name); #endif it->second->ReadLcf(obj, stream, chunk_info.length); } else stream.Skip(chunk_info); } } template <class S> void Struct<S>::WriteLcf(const S& obj, LcfWriter& stream) { S ref = S(); int last = -1; for (int i = 0; fields[i] != NULL; i++) { const Field<S>* field = fields[i]; if (field->id < last) std::cerr << "field order mismatch: " << field->id << " after " << last << " in struct " << name << std::endl; //printf("\n%s", field->name); if (field->IsDefault(obj, ref)) { //printf(" -> default"); continue; } stream.WriteInt(field->id); stream.WriteInt(field->LcfSize(obj, stream)); field->WriteLcf(obj, stream); } stream.WriteInt(0); } template <> void Struct<RPG::Save>::WriteLcf(const RPG::Save& obj, LcfWriter& stream) { RPG::Save ref = RPG::Save(); int last = -1; for (int i = 0; fields[i] != NULL; i++) { const Field<RPG::Save>* field = fields[i]; if (field->id < last) std::cerr << "field order mismatch: " << field->id << " after " << last << " in struct " << name << std::endl; //printf("\n%s", field->name); if (field->IsDefault(obj, ref)) { //printf(" -> default"); continue; } stream.WriteInt(field->id); stream.WriteInt(field->LcfSize(obj, stream)); field->WriteLcf(obj, stream); } // stream.WriteInt(0); // This last byte broke savegames } template <class S> int Struct<S>::LcfSize(const S& obj, LcfWriter& stream) { int result = 0; S ref = S(); for (int i = 0; fields[i] != NULL; i++) { const Field<S>* field = fields[i]; //printf("%s\n", field->name); if (field->IsDefault(obj, ref)) continue; result += LcfReader::IntSize(field->id); int size = field->LcfSize(obj, stream); result += LcfReader::IntSize(size); result += size; } result += LcfReader::IntSize(0); return result; } template <class S> void Struct<S>::WriteXml(const S& obj, XmlWriter& stream) { IDReader::WriteXmlTag(obj, name, stream); for (int i = 0; fields[i] != NULL; i++) { const Field<S>* field = fields[i]; field->WriteXml(obj, stream); } stream.EndElement(name); } template <class S> class StructXmlHandler : public XmlHandler { public: StructXmlHandler(S& ref) : ref(ref), field(NULL) { Struct<S>::MakeTagMap(); } void StartElement(XmlReader& stream, const char* name, const char** /* atts */) { field = Struct<S>::tag_map[name]; field->BeginXml(ref, stream); } void EndElement(XmlReader& /* stream */, const char* /* name */) { field = NULL; } void CharacterData(XmlReader& /* stream */, const std::string& data) { if (field != NULL) field->ParseXml(ref, data); } private: S& ref; const Field<S>* field; }; template <class S> class StructFieldXmlHandler : public XmlHandler { public: StructFieldXmlHandler(S& ref) : ref(ref) {} void StartElement(XmlReader& stream, const char* name, const char** atts) { if (strcmp(name, Struct<S>::name) != 0) stream.Error("Expecting %s but got %s", Struct<S>::name, name); Struct<S>::IDReader::ReadIDXml(ref, atts); stream.SetHandler(new StructXmlHandler<S>(ref)); } private: S& ref; }; template <class S> void Struct<S>::BeginXml(S& obj, XmlReader& stream) { stream.SetHandler(new StructFieldXmlHandler<S>(obj)); } // Read/Write std::vector<Struct> template <class S> void Struct<S>::ReadLcf(std::vector<S>& vec, LcfReader& stream) { int count = stream.ReadInt(); vec.resize(count); for (int i = 0; i < count; i++) { IDReader::ReadID(vec[i], stream); TypeReader<S>::ReadLcf(vec[i], stream, 0); } } template <class S> void Struct<S>::WriteLcf(const std::vector<S>& vec, LcfWriter& stream) { int count = vec.size(); stream.WriteInt(count); for (int i = 0; i < count; i++) { IDReader::WriteID(vec[i], stream); TypeReader<S>::WriteLcf(vec[i], stream); } } template <class S> int Struct<S>::LcfSize(const std::vector<S>& vec, LcfWriter& stream) { int result = 0; int count = vec.size(); result += LcfReader::IntSize(count); for (int i = 0; i < count; i++) { result += IDReader::IDSize(vec[i]); result += TypeReader<S>::LcfSize(vec[i], stream); } return result; } template <class S> void Struct<S>::WriteXml(const std::vector<S>& vec, XmlWriter& stream) { int count = vec.size(); for (int i = 0; i < count; i++) TypeReader<S>::WriteXml(vec[i], stream); } template <class S> class StructVectorXmlHandler : public XmlHandler { public: StructVectorXmlHandler(std::vector<S>& ref) : ref(ref) {} void StartElement(XmlReader& stream, const char* name, const char** atts) { if (strcmp(name, Struct<S>::name) != 0) stream.Error("Expecting %s but got %s", Struct<S>::name, name); ref.resize(ref.size() + 1); S& obj = ref.back(); Struct<S>::IDReader::ReadIDXml(obj, atts); stream.SetHandler(new StructXmlHandler<S>(obj)); } private: std::vector<S>& ref; }; template <class S> void Struct<S>::BeginXml(std::vector<S>& obj, XmlReader& stream) { stream.SetHandler(new StructVectorXmlHandler<S>(obj)); } // Instantiate templates #ifdef _MSC_VER #pragma warning (disable : 4661) #endif template class Struct<RPG::Actor>; template class Struct<RPG::Animation>; template class Struct<RPG::AnimationCellData>; template class Struct<RPG::AnimationFrame>; template class Struct<RPG::AnimationTiming>; template class Struct<RPG::Attribute>; template class Struct<RPG::BattleCommand>; template class Struct<RPG::BattleCommands>; template class Struct<RPG::BattlerAnimation>; template class Struct<RPG::BattlerAnimationData>; template class Struct<RPG::BattlerAnimationExtension>; template class Struct<RPG::Chipset>; template class Struct<RPG::Class>; template class Struct<RPG::CommonEvent>; template class Struct<RPG::Database>; template class Struct<RPG::Encounter>; template class Struct<RPG::Enemy>; template class Struct<RPG::EnemyAction>; template class Struct<RPG::Event>; template class Struct<RPG::EventPage>; template class Struct<RPG::EventPageCondition>; template class Struct<RPG::Item>; template class Struct<RPG::ItemAnimation>; template class Struct<RPG::Learning>; template class Struct<RPG::Map>; template class Struct<RPG::MapInfo>; template class Struct<RPG::MoveRoute>; template class Struct<RPG::Music>; template class Struct<RPG::Save>; template class Struct<RPG::SaveActor>; template class Struct<RPG::SaveCommonEvent>; template class Struct<RPG::SaveEventCommands>; template class Struct<RPG::SaveEventData>; template class Struct<RPG::SaveEvents>; template class Struct<RPG::SaveInventory>; template class Struct<RPG::SaveMapEvent>; template class Struct<RPG::SaveMapInfo>; template class Struct<RPG::SavePartyLocation>; template class Struct<RPG::SavePicture>; template class Struct<RPG::SaveScreen>; template class Struct<RPG::SaveSystem>; template class Struct<RPG::SaveTarget>; template class Struct<RPG::SaveTitle>; template class Struct<RPG::SaveVehicleLocation>; template class Struct<RPG::Skill>; template class Struct<RPG::Sound>; template class Struct<RPG::Start>; template class Struct<RPG::State>; template class Struct<RPG::Switch>; template class Struct<RPG::System>; template class Struct<RPG::Terms>; template class Struct<RPG::Terrain>; template class Struct<RPG::TestBattler>; template class Struct<RPG::Troop>; template class Struct<RPG::TroopMember>; template class Struct<RPG::TroopPage>; template class Struct<RPG::TroopPageCondition>; template class Struct<RPG::Variable>;
28.081433
115
0.686927
[ "vector" ]
b9986c9ebc2081d080d6cb3040396999cc4ed847
1,420
cc
C++
chrome/browser/ui/autofill/country_combobox_model_unittest.cc
halton/chromium-crosswalk
bfcca582b723b9535907f0b410b920ef99911b70
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/ui/autofill/country_combobox_model_unittest.cc
halton/chromium-crosswalk
bfcca582b723b9535907f0b410b920ef99911b70
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/ui/autofill/country_combobox_model_unittest.cc
halton/chromium-crosswalk
bfcca582b723b9535907f0b410b920ef99911b70
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/autofill/country_combobox_model.h" #include "components/autofill/core/browser/autofill_country.h" #include "components/autofill/core/browser/test_personal_data_manager.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/libaddressinput/chromium/cpp/include/libaddressinput/address_ui.h" #include "third_party/libaddressinput/chromium/cpp/include/libaddressinput/address_ui_component.h" namespace autofill { TEST(CountryComboboxModel, RespectsManagerDefaultCountry) { const std::string test_country = "AQ"; TestPersonalDataManager manager; manager.set_timezone_country_code(test_country); CountryComboboxModel model(manager); EXPECT_EQ(test_country, model.GetDefaultCountryCode()); } TEST(CountryComboboxModel, AllCountriesHaveComponents) { TestPersonalDataManager manager; CountryComboboxModel model(manager); for (int i = 0; i < model.GetItemCount(); ++i) { if (model.IsItemSeparatorAt(i)) continue; std::string country_code = model.countries()[i]->country_code(); std::vector< ::i18n::addressinput::AddressUiComponent> components = ::i18n::addressinput::BuildComponents(country_code); EXPECT_FALSE(components.empty()); } } } // namespace autofill
35.5
98
0.778873
[ "vector", "model" ]
b99e07ad265dcc140bee57068a72baacb76a506f
7,334
cc
C++
src/ChcGraph.cc
usi-verification-and-security/golem
4ea1a531a59575a9c0c0254201d90d52547152ff
[ "MIT" ]
6
2021-08-16T09:57:38.000Z
2021-12-02T11:06:23.000Z
src/ChcGraph.cc
usi-verification-and-security/golem
4ea1a531a59575a9c0c0254201d90d52547152ff
[ "MIT" ]
null
null
null
src/ChcGraph.cc
usi-verification-and-security/golem
4ea1a531a59575a9c0c0254201d90d52547152ff
[ "MIT" ]
null
null
null
// // Created by Martin Blicha on 17.07.20. // #include "ChcGraph.h" #include <iostream> std::unique_ptr<ChcDirectedHyperGraph> ChcGraphBuilder::buildGraph(NormalizedChcSystem const & system) { std::vector<Vertex> vertices; std::vector<DirectedHyperEdge> edges; std::size_t id = 0; auto getOrCreateVertex = [&vertices, &id](SymRef sym) { auto vertexIt = std::find_if(vertices.begin(), vertices.end(), [&sym](Vertex const& v) { return v.predicateSymbol == sym; }); if (vertexIt == vertices.end()) { vertexIt = vertices.insert(vertexIt, Vertex{.predicateSymbol = sym, .id = id++}); } return vertexIt->id; }; ChcSystem const & chcSystem = *system.normalizedSystem; // Special case to cover initial clauses, we are adding artificial "TRUE" starting predicate VId init = getOrCreateVertex(logic.getSym_true()); // Special vertex representing error location, we assume it is represented by FALSE predicate in the system VId error = getOrCreateVertex(logic.getSym_false()); for (auto const & clause : chcSystem.getClauses()) { auto const& head = clause.head; auto const& body = clause.body; auto toVertex = getOrCreateVertex(logic.getSymRef(head.predicate.predicate)); std::vector<VId> from; for (auto const& bodyPredicate : body.uninterpretedPart) { from.push_back(getOrCreateVertex(logic.getSymRef(bodyPredicate.predicate))); } if (from.empty()) { from.push_back(init); } edges.push_back(DirectedHyperEdge{.from = std::move(from), .to = toVertex, .fla = body.interpretedPart}); } return std::unique_ptr<ChcDirectedHyperGraph>( new ChcDirectedHyperGraph(std::move(vertices), std::move(edges), system.canonicalPredicateRepresentation, init, error )); } bool ChcDirectedHyperGraph::isNormalGraph() const { return std::all_of(edges.begin(), edges.end(), [](const DirectedHyperEdge& edge) { assert(not edge.from.empty()); return edge.from.size() == 1; }); } std::unique_ptr<ChcDirectedGraph> ChcDirectedHyperGraph::toNormalGraph() const { std::vector<DirectedEdge> normalEdges; std::transform(this->edges.begin(), this->edges.end(), std::back_inserter(normalEdges), [](DirectedHyperEdge const& edge) { return DirectedEdge{.from = edge.from[0], .to = edge.to, .fla = edge.fla}; }); return std::unique_ptr<ChcDirectedGraph>( new ChcDirectedGraph(vertices, std::move(normalEdges), predicates, entry, exit)); } void ChcDirectedGraph::toDot(ostream & out, Logic const& logic) const { out << "digraph proof {" << endl; std::map<VId, std::string> dotIds; for (auto const & vertex : vertices) { auto id = vertex.id; auto pred = this->getStateVersion(id); dotIds.insert(std::make_pair(id, "n" + std::to_string(id.id))); std::string label = logic.printTerm(pred); out << dotIds[id] << "\t[label = \"" << label << "\"];\n"; } for (auto const& edge : edges) { out << dotIds[edge.from] << " -> " << dotIds[edge.to] << " [label = \"" << logic.printTerm(edge.fla.fla) << "\"];\n"; } out << "}" << std::endl; } DirectedEdge ChcDirectedGraph::reverseEdge(DirectedEdge const & edge, TermUtils & utils) const { VId rfrom = edge.to; VId rto = edge.from; PTRef ofla = edge.fla.fla; std::unordered_map<PTRef, PTRef, PTRefHash> subst; // variables from 'from' are expressed as state vars, they must be changed to next state utils.insertVarPairsFromPredicates(this->getStateVersion(edge.from), this->getNextStateVersion(edge.from), subst); // variables from 'to' are expressed as next state vars, they must be changed to state utils.insertVarPairsFromPredicates(this->getNextStateVersion(edge.to), this->getStateVersion(edge.to), subst); // simulataneous substitution PTRef rfla = utils.varSubstitute(ofla, subst); return DirectedEdge{.from = rfrom, .to = rto, .fla = InterpretedFla{rfla}}; } ChcDirectedGraph ChcDirectedGraph::reverse(Logic & logic) const { // same vertices, same canonical representation, switch entry and exit and reverse edges // NOTE: reversing edge means flipping state and next state variables assert(vertices[entry.id].predicateSymbol == logic.getSym_true() and vertices[exit.id].predicateSymbol == logic.getSym_false()); auto rvertices = vertices; std::swap(rvertices[entry.id].predicateSymbol, rvertices[exit.id].predicateSymbol); TermUtils utils(logic); std::vector<DirectedEdge> redges; for (auto const& edge : this->edges) { redges.push_back(reverseEdge(edge, utils)); } auto rentry = exit; auto rexit = entry; return ChcDirectedGraph(std::move(rvertices), std::move(redges), this->predicates, rentry, rexit); } AdjacencyListsGraphRepresentation AdjacencyListsGraphRepresentation::from(const ChcDirectedGraph & graph) { auto edges = graph.getEdges(); auto vertices = graph.getVertices(); std::vector<std::vector<EId>> incoming; std::vector<std::vector<EId>> outgoing; const std::size_t N = vertices.size(); incoming.resize(N); outgoing.resize(N); for (EId eid : edges) { incoming[graph.getTarget(eid).id].push_back(eid); outgoing[graph.getSource(eid).id].push_back(eid); } return AdjacencyListsGraphRepresentation(std::move(incoming), std::move(outgoing), [&graph](EId eid) { return graph.getEdge(eid); }); } class DFS { AdjacencyListsGraphRepresentation const * graph; std::vector<bool> marked; template<typename TPreorderAction, typename TPostorderAction> void runOnVertex(VId v, TPreorderAction const & preorder, TPostorderAction const & postorder) { if (marked[v.id]) { return; } marked[v.id] = true; preorder(v); for (EId outEdge : graph->getOutgoingEdgesFor(v)) { runOnVertex(graph->getEdge(outEdge).to, preorder, postorder); } postorder(v); } public: template<typename TPreorderAction, typename TPostorderAction> void run(TPreorderAction const & preorder, TPostorderAction const & postorder, AdjacencyListsGraphRepresentation const & graph) && { auto vertexCount = graph.getVertexNum(); marked.resize(vertexCount, false); this->graph = &graph; for (std::size_t i = 0; i < vertexCount; ++i) { runOnVertex(VId{i}, preorder, postorder); } } }; std::vector<VId> AdjacencyListsGraphRepresentation::reversePostOrder() const { std::vector<VId> order; DFS().run([](VId){}, [&order](VId v){ order.push_back(v); }, *this); std::reverse(order.begin(), order.end()); return order; } std::unique_ptr<ChcDirectedHyperGraph> ChcDirectedGraph::toHyperGraph() const { std::vector<DirectedHyperEdge> hyperEdges; std::transform(this->edges.begin(), this->edges.end(), std::back_inserter(hyperEdges), [](DirectedEdge const& edge) { return DirectedHyperEdge{.from = {edge.from}, .to = edge.to, .fla = edge.fla}; }); return std::unique_ptr<ChcDirectedHyperGraph>( new ChcDirectedHyperGraph(vertices, std::move(hyperEdges), predicates, entry, exit)); }
44.180723
151
0.663758
[ "vector", "transform" ]
b99eb3003dcfa5bab6e1115c1b1f55da6c0b82c0
1,676
cpp
C++
src/homework/04_vectors/main.cpp
acc-cosc-1337-spring-2020/acc-cosc-1337-spring-2020-mmacigewski
dcccbc63856b1ff95cc055c517141ba9677e151b
[ "MIT" ]
null
null
null
src/homework/04_vectors/main.cpp
acc-cosc-1337-spring-2020/acc-cosc-1337-spring-2020-mmacigewski
dcccbc63856b1ff95cc055c517141ba9677e151b
[ "MIT" ]
null
null
null
src/homework/04_vectors/main.cpp
acc-cosc-1337-spring-2020/acc-cosc-1337-spring-2020-mmacigewski
dcccbc63856b1ff95cc055c517141ba9677e151b
[ "MIT" ]
null
null
null
#include "vectors.h" #include <iostream> /* use a vector of int with values 8, 4, 20, 88, 66, 99 Prompt user for 1 for Get Max from vector and 2 for Get primes. Prompt user for a number and return max value or list of primes and display them to screen. Program continues until user decides to exit. */ int main() { auto iOption{ 0 }, iNum{ 0 }, iPrime{ 0 }; //initializes the varibales auto bIsRunning{ true }; auto cOption{ ' ' }; std::vector<int> iUserValues; while (bIsRunning) { std::cout << "1: Get Max from vector"; std::cout << "\n2: Get Primes"; std::cout << "\nPick an option: "; std::cin >> iOption; if (iOption == 1) { while (iNum > -1)//will populate a vector until user enters a negative number { std::cout << "Input number to be inserted into vector(negative # to stop): "; std::cin >> iNum; if (iNum > -1) //a check to make sure the vector doesn't populate with a negative { iUserValues.push_back(iNum); } } std::cout << "\nMax number you entered: " << get_max_from_vector(iUserValues); iNum = 0; //clears the values in case it gets run again iUserValues.clear(); } else if (iOption == 2) { std::cout << "Input a number: "; std::cin >> iPrime; std::vector<int> iPrimeVector = vector_of_primes(iPrime); //stores the files std::cout << "\nList of prime numbers: "; for (auto i : iPrimeVector) { std::cout << i << ", "; } } std::cout << "\n\nDo you want to continue(y/n)"; std::cin >> cOption; if (cOption == 'n') { std::cout << "Program Ending"; bIsRunning = false; } else { std::cout << "\n"; } //new line for formatting } return 0; }
23.277778
85
0.618138
[ "vector" ]
b9a04abd65ae611c22a7443eafa361a14999e1dc
28,040
cc
C++
src/imagebox.cc
TypicalFence/ahoviewer
3e83f81dc61322b449f35ddcc48a96e385464a97
[ "MIT" ]
null
null
null
src/imagebox.cc
TypicalFence/ahoviewer
3e83f81dc61322b449f35ddcc48a96e385464a97
[ "MIT" ]
null
null
null
src/imagebox.cc
TypicalFence/ahoviewer
3e83f81dc61322b449f35ddcc48a96e385464a97
[ "MIT" ]
null
null
null
#include "imagebox.h" using namespace AhoViewer; #include "imageboxnote.h" #include "mainwindow.h" #include "settings.h" #include "statusbar.h" #include <iostream> #ifdef HAVE_GSTREAMER #include <gst/audio/streamvolume.h> #include <gst/video/videooverlay.h> #if defined(GDK_WINDOWING_X11) #include <gdk/gdkx.h> #elif defined(GDK_WINDOWING_WIN32) #include <gdk/gdkwin32.h> #elif defined(GDK_WINDOWING_QUARTZ) #include <gdk/gdkquartz.h> #endif GstBusSyncReply ImageBox::create_window(GstBus* bus, GstMessage* msg, void* userp) { if (!gst_is_video_overlay_prepare_window_handle_message(msg)) return GST_BUS_PASS; auto* self = static_cast<ImageBox*>(userp); gst_video_overlay_set_window_handle(GST_VIDEO_OVERLAY(self->m_VideoSink), self->m_WindowHandle); gst_message_unref(msg); return GST_BUS_DROP; } gboolean ImageBox::bus_cb(GstBus*, GstMessage* msg, void* userp) { auto* self = static_cast<ImageBox*>(userp); switch (GST_MESSAGE_TYPE(msg)) { case GST_MESSAGE_EOS: gst_element_seek_simple(self->m_Playbin, GST_FORMAT_TIME, GST_SEEK_FLAG_FLUSH, 0); default: break; } return TRUE; } // Set volume based on Volume setting void ImageBox::on_set_volume() { // TODO: add a range widget that controls this value gst_stream_volume_set_volume( GST_STREAM_VOLUME(m_Playbin), GST_STREAM_VOLUME_FORMAT_CUBIC, std::min(static_cast<double>(Settings.get_int("Volume")) / 100, 1.0)); } void ImageBox::reset_gstreamer_pipeline() { gst_element_set_state(m_Playbin, GST_STATE_NULL); m_Playing = false; } // Attempts to create a GstElement of type @name, and prints a message if it fails GstElement* ImageBox::create_video_sink(const std::string& name) { GstElement* sink = gst_element_factory_make(name.c_str(), name.c_str()); if (!sink) std::cerr << "Failed to create videosink of type '" << name << "'" << std::endl; return sink; } #endif // HAVE_GSTREAMER Gdk::RGBA ImageBox::DefaultBGColor = Gdk::RGBA(); ImageBox::ImageBox(BaseObjectType* cobj, const Glib::RefPtr<Gtk::Builder>& bldr) : Gtk::ScrolledWindow{ cobj }, m_LeftPtrCursor{ Gdk::Cursor::create(Gdk::LEFT_PTR) }, m_FleurCursor{ Gdk::Cursor::create(Gdk::FLEUR) }, m_BlankCursor{ Gdk::Cursor::create(Gdk::BLANK_CURSOR) }, m_ZoomMode{ Settings.get_zoom_mode() }, m_RestoreScrollPos{ -1, -1, m_ZoomMode } { bldr->get_widget("ImageBox::Layout", m_Layout); bldr->get_widget("ImageBox::Overlay", m_Overlay); bldr->get_widget("ImageBox::Image", m_GtkImage); bldr->get_widget("ImageBox::NoteLayout", m_NoteLayout); bldr->get_widget("ImageBox::DrawingArea", m_DrawingArea); bldr->get_widget_derived("StatusBar", m_StatusBar); bldr->get_widget_derived("MainWindow", m_MainWindow); m_UIManager = Glib::RefPtr<Gtk::UIManager>::cast_static(bldr->get_object("UIManager")); #ifdef HAVE_GSTREAMER auto videosink = Settings.get_string("VideoSink"); if (!videosink.empty()) { m_VideoSink = create_video_sink(videosink.c_str()); if (!m_VideoSink) std::cerr << "Invalid VideoSink setting provided '" << videosink << "'" << std::endl; } #ifdef GDK_WINDOWING_X11 if (!m_VideoSink) { m_VideoSink = create_video_sink("xvimagesink"); // Make sure the X server has the X video extension enabled if (m_VideoSink) { bool have_xvideo{ false }; int nextens; char** extensions = XListExtensions( gdk_x11_display_get_xdisplay(Gdk::Display::get_default()->gobj()), &nextens); for (int i = 0; extensions != nullptr && i < nextens; ++i) { if (strcmp(extensions[i], "XVideo") == 0) { have_xvideo = true; break; } } if (extensions) XFreeExtensionList(extensions); if (!have_xvideo) { gst_object_unref(GST_OBJECT(m_VideoSink)); m_VideoSink = nullptr; std::cerr << "xvimagesink created, but X video extension not supported by X server!" << std::endl; } } } if (!m_VideoSink) m_VideoSink = create_video_sink("ximagesink"); #endif // GDK_WINDOWING_X11 #ifdef GDK_WINDOWING_WIN32 if (!m_VideoSink) m_VideoSink = create_video_sink("d3dvideosink"); #endif // GDK_WINDOWING_WIN32 // glimagesink should work on all platforms if (!m_VideoSink) m_VideoSink = create_video_sink("glimagesink"); if (m_VideoSink) { char* name = gst_element_get_name(m_VideoSink); std::cout << "Using videosink of type '" << name << "'" << std::endl; // Prevent the glimagesink from handling events so the right click menu // can be shown when clicking on the drawing area if (g_strcmp0(name, "glimagesink") == 0) g_object_set(m_VideoSink, "handle-events", false, NULL); if (name) g_free(name); // Store the window handle in order to use it in ::create_window m_DrawingArea->signal_realize().connect([&]() { #if defined(GDK_WINDOWING_X11) m_WindowHandle = GDK_WINDOW_XID(m_DrawingArea->get_window()->gobj()); #elif defined(GDK_WINDOWING_WIN32) m_WindowHandle = (guintptr)GDK_WINDOW_HWND(m_DrawingArea->get_window()->gobj()); #elif defined(GDK_WINDOWING_QUARTZ) m_WindowHandle = (guintptr)gdk_quartz_window_get_nsview(m_DrawingArea->get_window()->gobj()); #endif gst_element_set_state(m_Playbin, GST_STATE_READY); }); gst_object_ref(m_VideoSink); } m_Playbin = gst_element_factory_make("playbin", "playbin"); g_object_set(m_Playbin, // For now users can put // AudioSink = "autoaudiosink"; // into the config file and have sound if they have the correct gstreamer plugins // Can also set Volume = 0-100; in config to control it "audio-sink", gst_element_factory_make(Settings.get_string("AudioSink").c_str(), "audiosink"), // If sink is null it will fallback to autovideosink "video-sink", m_VideoSink, // draw_image takes care of it "force-aspect-ratio", false, NULL); GstBus* bus = gst_pipeline_get_bus(GST_PIPELINE(m_Playbin)); gst_bus_set_sync_handler(bus, &ImageBox::create_window, this, nullptr); gst_bus_add_watch(bus, &ImageBox::bus_cb, this); g_object_unref(bus); #endif // HAVE_GSTREAMER m_StyleUpdatedConn = m_Layout->signal_style_updated().connect( [&]() { m_Layout->get_style_context()->lookup_color("theme_bg_color", DefaultBGColor); }); } ImageBox::~ImageBox() { clear_image(); #ifdef HAVE_GSTREAMER gst_object_unref(GST_OBJECT(m_Playbin)); #endif // HAVE_GSTREAMER } void ImageBox::queue_draw_image(const bool scroll) { if (!get_realized() || !m_Image || (m_RedrawQueued && !(scroll || m_Loading))) return; m_DrawConn.disconnect(); m_RedrawQueued = true; m_DrawConn = Glib::signal_idle().connect( sigc::bind_return(sigc::bind(sigc::mem_fun(*this, &ImageBox::draw_image), scroll), false), Glib::PRIORITY_HIGH_IDLE); } void ImageBox::set_image(const std::shared_ptr<Image>& image) { if (!image) return; if (image != m_Image) { m_AnimConn.disconnect(); m_ImageConn.disconnect(); m_NotesConn.disconnect(); reset_slideshow(); clear_notes(); #ifdef HAVE_GSTREAMER reset_gstreamer_pipeline(); m_DrawingArea->hide(); #endif // HAVE_GSTREAMER // reset GIF stuff so if it stays cached and is viewed again it will // start from the first frame if (m_Image) m_Image->reset_gif_animation(); m_Image = image; m_FirstDraw = m_Loading = true; m_ImageConn = m_Image->signal_pixbuf_changed().connect( sigc::bind(sigc::mem_fun(*this, &ImageBox::queue_draw_image), false)); // Maybe the notes havent been downloaded yet if (m_Image->get_notes().empty()) m_NotesConn = m_Image->signal_notes_changed().connect( sigc::mem_fun(*this, &ImageBox::on_notes_changed)); queue_draw_image(true); } else { queue_draw_image(); } } void ImageBox::clear_image() { m_SlideshowConn.disconnect(); m_ImageConn.disconnect(); m_NotesConn.disconnect(); m_DrawConn.disconnect(); m_AnimConn.disconnect(); m_GtkImage->clear(); m_DrawingArea->hide(); m_Layout->set_size(0, 0); clear_notes(); #ifdef HAVE_GSTREAMER reset_gstreamer_pipeline(); #endif // HAVE_GSTREAMER m_StatusBar->clear_resolution(); m_Image = nullptr; } void ImageBox::update_background_color() { auto css = Gtk::CssProvider::create(); css->load_from_data(Glib::ustring::compose("scrolledwindow#ImageBox{background:%1;}", Settings.get_background_color().to_string())); get_style_context()->add_provider(css, GTK_STYLE_PROVIDER_PRIORITY_APPLICATION); } void ImageBox::cursor_timeout() { m_CursorConn.disconnect(); m_Layout->get_window()->set_cursor(m_LeftPtrCursor); if (Settings.get_int("CursorHideDelay") <= 0) return; m_CursorConn = Glib::signal_timeout().connect_seconds( sigc::mem_fun(*this, &ImageBox::on_cursor_timeout), Settings.get_int("CursorHideDelay")); } void ImageBox::reset_slideshow() { if (m_SlideshowConn) { m_SlideshowConn.disconnect(); toggle_slideshow(); } } void ImageBox::toggle_slideshow() { if (!m_SlideshowConn) { m_SlideshowConn = Glib::signal_timeout().connect_seconds( sigc::mem_fun(*this, &ImageBox::advance_slideshow), Settings.get_int("SlideshowDelay")); } else { m_SlideshowConn.disconnect(); } } void ImageBox::set_zoom_mode(const ZoomMode mode) { if (mode != m_ZoomMode) { Settings.set_zoom_mode(mode); m_ZoomMode = mode; queue_draw_image(true); } } void ImageBox::on_zoom_in() { zoom(m_ZoomPercent + 10); } void ImageBox::on_zoom_out() { zoom(m_ZoomPercent - 10); } void ImageBox::on_reset_zoom() { zoom(100); } void ImageBox::on_scroll_up() { scroll(0, -300); } void ImageBox::on_scroll_down() { scroll(0, 300); } void ImageBox::on_scroll_left() { scroll(-300, 0); } void ImageBox::on_scroll_right() { scroll(300, 0); } void ImageBox::on_realize() { m_PopupMenu = static_cast<Gtk::Menu*>(m_UIManager->get_widget("/PopupMenu")); Glib::RefPtr<Gtk::ActionGroup> action_group = static_cast<std::vector<Glib::RefPtr<Gtk::ActionGroup>>>( m_UIManager->get_action_groups())[0]; m_NextAction = action_group->get_action("NextImage"); m_PreviousAction = action_group->get_action("PreviousImage"); m_Layout->get_style_context()->lookup_color("theme_bg_color", DefaultBGColor); update_background_color(); Gtk::ScrolledWindow::on_realize(); } bool ImageBox::on_button_press_event(GdkEventButton* e) { grab_focus(); cursor_timeout(); // Ignore double/triple clicks if (e->type == GDK_BUTTON_PRESS) { switch (e->button) { case 1: case 2: m_PressX = m_PreviousX = e->x_root; m_PressY = m_PreviousY = e->y_root; return true; case 3: m_PopupMenu->popup_at_pointer(reinterpret_cast<GdkEvent*>(e)); m_CursorConn.disconnect(); return true; case 8: // Back m_PreviousAction->activate(); return true; case 9: // Forward m_NextAction->activate(); return true; } } return Gtk::ScrolledWindow::on_button_press_event(e); } bool ImageBox::on_button_release_event(GdkEventButton* e) { if (e->button == 1 || e->button == 2) { m_Layout->get_window()->set_cursor(m_LeftPtrCursor); if (e->button == 1 && m_PressX == m_PreviousX && m_PressY == m_PreviousY) { if (Settings.get_bool("SmartNavigation")) { int w, h, x, y, ww, wh; m_MainWindow->get_drawable_area_size(w, h); m_MainWindow->get_size(ww, wh); m_MainWindow->get_position(x, y); x += ww - w; if (e->x_root - x < w / 2) { m_PreviousAction->activate(); return true; } } m_NextAction->activate(); } return true; } return Gtk::ScrolledWindow::on_button_release_event(e); } bool ImageBox::on_motion_notify_event(GdkEventMotion* e) { if (m_Image && ((e->state & GDK_BUTTON1_MASK) == GDK_BUTTON1_MASK || (e->state & GDK_BUTTON2_MASK) == GDK_BUTTON2_MASK)) { m_Layout->get_window()->set_cursor(m_FleurCursor); scroll(m_PreviousX - e->x_root, m_PreviousY - e->y_root, true); m_PreviousX = e->x_root; m_PreviousY = e->y_root; return true; } else { cursor_timeout(); } return Gtk::ScrolledWindow::on_motion_notify_event(e); } bool ImageBox::on_scroll_event(GdkEventScroll* e) { grab_focus(); cursor_timeout(); GdkScrollDirection direction = GDK_SCROLL_SMOOTH; if (e->direction == GDK_SCROLL_SMOOTH) { if (e->delta_y >= 0) direction = GDK_SCROLL_DOWN; else if (e->delta_y < 0) direction = GDK_SCROLL_UP; else if (e->delta_x < 0) direction = GDK_SCROLL_LEFT; else if (e->delta_x >= 0) direction = GDK_SCROLL_RIGHT; } switch (direction) { case GDK_SCROLL_UP: if ((e->state & GDK_CONTROL_MASK) == GDK_CONTROL_MASK) on_zoom_in(); else scroll(0, -300); return true; case GDK_SCROLL_DOWN: if ((e->state & GDK_CONTROL_MASK) == GDK_CONTROL_MASK) on_zoom_out(); else scroll(0, 300); return true; case GDK_SCROLL_LEFT: scroll(-300, 0); return true; case GDK_SCROLL_RIGHT: scroll(300, 0); return true; case GDK_SCROLL_SMOOTH: return false; } return Gtk::ScrolledWindow::on_scroll_event(e); } // This must be called after m_Orig(Width/Height) are set // It sets the values of w, h to their scaled values, and x, y to center // coordinates for m_Layout to use void ImageBox::get_scale_and_position(int& w, int& h, int& x, int& y) { int ww, wh; m_MainWindow->get_drawable_area_size(ww, wh); w = m_OrigWidth; h = m_OrigHeight; double window_aspect = static_cast<double>(ww) / wh, image_aspect = static_cast<double>(w) / h; // These do not take the scrollbar size in to account, because I assume that // overlay scrollbars are enabled if (w > ww && (m_ZoomMode == ZoomMode::FIT_WIDTH || (m_ZoomMode == ZoomMode::AUTO_FIT && window_aspect <= image_aspect))) { w = ww; h = std::ceil(w / image_aspect); } else if (h > wh && (m_ZoomMode == ZoomMode::FIT_HEIGHT || (m_ZoomMode == ZoomMode::AUTO_FIT && window_aspect >= image_aspect))) { h = wh; w = std::ceil(h * image_aspect); } else if (m_ZoomMode == ZoomMode::MANUAL && m_ZoomPercent != 100) { w *= static_cast<double>(m_ZoomPercent) / 100; h *= static_cast<double>(m_ZoomPercent) / 100; } x = std::max(0, (ww - w) / 2); y = std::max(0, (wh - h) / 2); } void ImageBox::draw_image(bool scroll) { // Don't draw images that don't exist (obviously) // Don't draw loading animated GIFs // Don't draw loading images that haven't created a pixbuf yet // Don't draw loading webm files (only booru images can have a loading webm) // The pixbuf_changed signal will fire when the above images are ready to be drawn if (!m_Image || (m_Image->is_loading() && (m_Image->is_animated_gif() || !m_Image->get_pixbuf() || m_Image->is_webm()))) { m_RedrawQueued = false; return; } // Temporary pixbuf used when scaling is needed Glib::RefPtr<Gdk::Pixbuf> temp_pixbuf; bool error{ false }; // if the image is still loading we want to draw all requests // Only booru images will do this m_Loading = m_Image->is_loading(); #ifdef HAVE_GSTREAMER if (m_Image->is_webm()) { if (!m_Playing) { g_object_set( m_Playbin, "uri", Glib::filename_to_uri(m_Image->get_path()).c_str(), NULL); on_set_volume(); gst_element_set_state(m_Playbin, GST_STATE_PAUSED); // Wait for the above changes to actually happen gst_element_get_state(m_Playbin, nullptr, nullptr, GST_CLOCK_TIME_NONE); } GstPad* pad = nullptr; g_signal_emit_by_name(m_Playbin, "get-video-pad", 0, &pad, NULL); if (pad) { GstCaps* caps = gst_pad_get_current_caps(pad); GstStructure* s = gst_caps_get_structure(caps, 0); gst_structure_get_int(s, "width", &m_OrigWidth); gst_structure_get_int(s, "height", &m_OrigHeight); gst_caps_unref(caps); gst_object_unref(pad); } else { error = true; m_DrawingArea->hide(); } } else #endif // HAVE_GSTREAMER { // Start animation if this is a new animated GIF if (m_Image->is_animated_gif() && !m_Loading && !m_AnimConn) { m_AnimConn.disconnect(); if (!m_Image->get_gif_finished_looping()) m_AnimConn = Glib::signal_timeout().connect( sigc::mem_fun(*this, &ImageBox::update_animation), m_Image->get_gif_frame_delay()); } Glib::RefPtr<Gdk::Pixbuf> pixbuf = m_Image->get_pixbuf(); if (pixbuf) { // Set this here incase we dont need to scale temp_pixbuf = pixbuf; m_OrigWidth = pixbuf->get_width(); m_OrigHeight = pixbuf->get_height(); } else { error = true; } } if (error) { temp_pixbuf = Image::get_missing_pixbuf(); m_OrigWidth = temp_pixbuf->get_width(); m_OrigHeight = temp_pixbuf->get_height(); } int w, h, x, y; get_scale_and_position(w, h, x, y); m_Scale = m_ZoomMode == ZoomMode::MANUAL ? m_ZoomPercent : static_cast<double>(w) / m_OrigWidth * 100; if (!m_Image->is_webm() && !error && (w != m_OrigWidth || h != m_OrigHeight)) temp_pixbuf = m_Image->get_pixbuf()->scale_simple(w, h, Gdk::INTERP_BILINEAR); double h_adjust_val{ 0 }, v_adjust_val{ 0 }; // Used to keep the adjustments centered when manual zooming if (m_ZoomScroll) { h_adjust_val = get_hadjustment()->get_value() / std::max(get_hadjustment()->get_upper() - get_hadjustment()->get_page_size(), 1.0); v_adjust_val = get_vadjustment()->get_value() / std::max(get_vadjustment()->get_upper() - get_vadjustment()->get_page_size(), 1.0); } get_window()->freeze_updates(); m_Layout->set_size(w, h); if (temp_pixbuf) { m_Layout->move(*m_Overlay, x, y); m_GtkImage->set(temp_pixbuf); } #ifdef HAVE_GSTREAMER else { if (!m_Playing) { m_GtkImage->clear(); m_DrawingArea->show(); } m_Layout->move(*m_DrawingArea, x, y); m_DrawingArea->set_size_request(w, h); gst_video_overlay_set_render_rectangle(GST_VIDEO_OVERLAY(m_VideoSink), 0, 0, w, h); gst_video_overlay_expose(GST_VIDEO_OVERLAY(m_VideoSink)); } #endif // HAVE_GSTREAMER // Reset the scrollbar positions if (scroll || m_FirstDraw) { if (m_RestoreScrollPos.v != -1 && m_RestoreScrollPos.zoom == m_ZoomMode) { // Restore and reset stored scrollbar positions get_vadjustment()->set_value(m_RestoreScrollPos.v); get_hadjustment()->set_value(m_RestoreScrollPos.h); m_RestoreScrollPos = { -1, -1, m_ZoomMode }; } else { get_vadjustment()->set_value(0); if (Settings.get_bool("MangaMode")) // Start at the right side of the image get_hadjustment()->set_value(get_hadjustment()->get_upper() - get_hadjustment()->get_page_size()); else get_hadjustment()->set_value(0); } if (m_FirstDraw && !m_Image->get_notes().empty() && !m_NotesConn) on_notes_changed(); m_FirstDraw = false; } else if (m_ZoomScroll) { get_hadjustment()->set_value(std::max( h_adjust_val * (get_hadjustment()->get_upper() - get_hadjustment()->get_page_size()), 0.0)); get_vadjustment()->set_value(std::max( v_adjust_val * (get_vadjustment()->get_upper() - get_vadjustment()->get_page_size()), 0.0)); m_ZoomScroll = false; } #ifdef HAVE_GSTREAMER // Finally start playing the video if (!m_Playing && m_Image->is_webm()) { gst_element_set_state(m_Playbin, GST_STATE_PLAYING); m_Playing = true; } #endif // HAVE_GSTREAMER get_window()->thaw_updates(); m_RedrawQueued = false; m_StatusBar->set_resolution(m_OrigWidth, m_OrigHeight, m_Scale, m_ZoomMode); update_notes(); m_SignalImageDrawn(); } bool ImageBox::update_animation() { if (m_Image->is_loading()) return true; bool gif_finished = m_Image->gif_advance_frame(); if (!gif_finished) m_AnimConn = Glib::signal_timeout().connect( sigc::mem_fun(*this, &ImageBox::update_animation), m_Image->get_gif_frame_delay()); return false; } void ImageBox::scroll(const int x, const int y, const bool panning, const bool from_slideshow) { int adjust_upper_x = std::max(0, static_cast<int>((get_hadjustment()->get_upper()) - get_hadjustment()->get_page_size())), adjust_upper_y = std::max(0, static_cast<int>((get_vadjustment()->get_upper()) - get_vadjustment()->get_page_size())); if (!from_slideshow) reset_slideshow(); if (panning) { int n_x = get_hadjustment()->get_value() + x, n_y = get_vadjustment()->get_value() + y; if (n_x <= adjust_upper_x) get_hadjustment()->set_value(n_x); if (n_y <= adjust_upper_y) get_vadjustment()->set_value(n_y); #ifdef HAVE_GSTREAMER if (m_Playing && m_Image->is_webm()) gst_video_overlay_expose(GST_VIDEO_OVERLAY(m_VideoSink)); #endif // HAVE_GSTREAMER } else { // Rounds scroll amount up if the end/start of the adjustment is // within 50% of the initial scroll amount // adjv = adjustment value, adjmax = adjustment max value, v = scroll value static auto round_scroll = [](const int adjv, const int adjmax, const int v) { const int range = std::abs(v * 0.5); // Going down/right if (v > 0 && adjmax - (adjv + v) <= range) return adjmax - adjv; // Going up/left, and not already going to scroll to the end else if (adjv > std::abs(v) && adjv + v <= range) return -adjv; return v; }; // Scroll to next page if ((get_hadjustment()->get_value() == adjust_upper_x && x > 0) || (get_vadjustment()->get_value() == adjust_upper_y && y > 0)) { m_ScrollConn.disconnect(); if (m_SlideshowConn && !m_NextAction->is_sensitive()) m_SignalSlideshowEnded(); else m_NextAction->activate(); } // Scroll to previous page else if ((get_hadjustment()->get_value() == 0 && x < 0) || (get_vadjustment()->get_value() == 0 && y < 0)) { m_ScrollConn.disconnect(); m_PreviousAction->activate(); } else if (x != 0) { smooth_scroll(round_scroll(get_hadjustment()->get_value(), adjust_upper_x, x), get_hadjustment()); } else if (y != 0) { smooth_scroll(round_scroll(get_vadjustment()->get_value(), adjust_upper_y, y), get_vadjustment()); } } } void ImageBox::smooth_scroll(const int amount, const Glib::RefPtr<Gtk::Adjustment>& adj) { // Cancel current animation if we changed direction if ((amount < 0 && m_ScrollTarget > 0) || (amount > 0 && m_ScrollTarget < 0) || adj != m_ScrollAdjust || !m_ScrollConn) { m_ScrollConn.disconnect(); m_ScrollTarget = m_ScrollDuration = 0; m_ScrollAdjust = adj; } m_ScrollTime = 0; m_ScrollTarget += amount; m_ScrollStart = m_ScrollAdjust->get_value(); if (m_ScrollTarget > 0) { double upper_max = m_ScrollAdjust->get_upper() - m_ScrollAdjust->get_page_size() - m_ScrollAdjust->get_value(); m_ScrollTarget = std::min(upper_max, m_ScrollTarget); } else if (m_ScrollTarget < 0) { double lower_max = m_ScrollAdjust->get_lower() - m_ScrollAdjust->get_value(); m_ScrollTarget = std::max(lower_max, m_ScrollTarget); } m_ScrollDuration = std::ceil(std::min(500.0, std::abs(m_ScrollTarget)) / SmoothScrollStep) * SmoothScrollStep; if (!m_ScrollConn) m_ScrollConn = Glib::signal_timeout().connect( sigc::mem_fun(*this, &ImageBox::update_smooth_scroll), SmoothScrollStep); } bool ImageBox::update_smooth_scroll() { m_ScrollTime += SmoothScrollStep; // atan(1) * 4 = pi double val = m_ScrollTarget * std::sin(m_ScrollTime / m_ScrollDuration * (std::atan(1) * 4 / 2)) + m_ScrollStart; val = m_ScrollTarget < 0 ? std::floor(val) : std::ceil(val); m_ScrollAdjust->set_value(val); return m_ScrollAdjust->get_value() != m_ScrollStart + m_ScrollTarget; } void ImageBox::zoom(const std::uint32_t percent) { if (m_ZoomMode != ZoomMode::MANUAL || percent < 10 || percent > 400) return; m_ZoomScroll = m_ZoomPercent != percent; m_ZoomPercent = percent; queue_draw_image(); } bool ImageBox::advance_slideshow() { // TODO: Smart scrolling, as an option // e.g. Scroll the width of the image before scrolling down scroll(0, 300, false, true); return true; } bool ImageBox::on_cursor_timeout() { m_Layout->get_window()->set_cursor(m_BlankCursor); return false; } void ImageBox::on_notes_changed(/*notes*/) { double scale{ m_Scale / 100 }; for (auto& note : m_Image->get_notes()) { auto n{ Gtk::make_managed<ImageBoxNote>(note) }; m_Notes.push_back(n); n->set_scale(scale); m_NoteLayout->put(*n, n->get_x(), n->get_y()); n->show(); } } void ImageBox::clear_notes() { for (auto& note : m_Notes) m_NoteLayout->remove(*note); m_Notes.clear(); } void ImageBox::update_notes() { double scale{ m_Scale / 100 }; for (auto& note : m_Notes) { note->set_scale(scale); m_NoteLayout->move(*note, note->get_x(), note->get_y()); } }
29.609293
100
0.601961
[ "vector" ]
b9a7302ac5c41987fb6e0aeba49db5ba06f27fb0
27,788
cc
C++
src/Simulation.cc
OliWenman/geant4tomosim
663961933628eba678534bbe9bf099c6bcf5514b
[ "Apache-2.0" ]
4
2019-05-14T15:24:05.000Z
2022-01-28T19:29:23.000Z
src/Simulation.cc
OliWenman/geant4tomosim
663961933628eba678534bbe9bf099c6bcf5514b
[ "Apache-2.0" ]
1
2019-05-13T09:47:12.000Z
2019-05-13T09:47:12.000Z
src/Simulation.cc
OliWenman/geant4tomosim
663961933628eba678534bbe9bf099c6bcf5514b
[ "Apache-2.0" ]
3
2019-05-13T08:59:55.000Z
2021-09-15T18:16:18.000Z
//Own classes #include "Simulation.hh" #include "SimulationMessenger.hh" #include "SampleConstruction.hh" #include "DetectorConstruction.hh" #include "FluorescenceSD.hh" #include "PhysicsList.hh" #include "PrimaryGeneratorAction.hh" #include "StackingAction.hh" #include "SteppingAction.hh" #include "DefineMaterials.hh" //Output to console/write to file #include "SettingsLog.hh" //Geant4 managers for running the simulation #include "G4RunManager.hh" #include "G4UImanager.hh" #include "G4VisExecutive.hh" #include "G4UIcommandTree.hh" #include "G4UIcommand.hh" //Used for timing simulation and getting a random seed #include "G4Timer.hh" #include "time.h" #include "Randomize.hh" //Geant4 units #include "G4SystemOfUnits.hh" #include "G4UnitsTable.hh" #include "G4ThreeVector.hh" #include <list> #include <cstdlib> #include <ctime> #include <sys/types.h> #include <dirent.h> #include <xraylib.h> #include "PrintLines.hh" //#include "G4MPImanager.hh" //#include "G4MPIsession.hh" Simulation::Simulation(int verb, bool interactive) : runManager(0), detectorManager(0), physicsManager(0), beamManager(0), visManager(0), particleManager(0), stepManager(0)//, //g4MPI(0) { globalVerbose = verb; interactiveOn = interactive; simMessenger = new SimulationMessenger(this); materials = new DefineMaterials(); //Create the objects needed for the G4RunManager class runManager = new G4RunManager(); visManager = new G4VisExecutive("quiet"); detectorManager = new DetectorConstruction(); runManager -> SetUserInitialization(detectorManager); physicsManager = new PhysicsList(); runManager -> SetUserInitialization(physicsManager); beamManager = new PrimaryGeneratorAction(); runManager -> SetUserAction(beamManager); particleManager = new StackingAction(); particleManager -> SetKillElectrons(true); runManager -> SetUserAction(particleManager); stepManager = new SteppingAction(); runManager -> SetUserAction(stepManager); //Get the pointer to the User Interface manager, set all print info to 0 during events by default UImanager = G4UImanager::GetUIpointer(); UImanager -> ApplyCommand("/tracking/verbose 0"); //Gives information about particle UImanager -> ApplyCommand("/control/verbose 0"); UImanager -> ApplyCommand("/hits/verbose 0"); UImanager -> ApplyCommand("/process/em/verbose 0"); UImanager -> ApplyCommand("/process/verbose 0"); UImanager -> ApplyCommand("/run/verbose 0"); sampleconstruction = detectorManager->GetSampleConstruction(); //Set the seed engine CLHEP::HepRandom::setTheEngine(new CLHEP::RanecuEngine()); //UImanager->GetTree()->List(); } Simulation::~Simulation() { if (globalVerbose > 0) {G4cout << "\nClosing simulation..." << G4endl;} int showDeletion = 3; if(globalVerbose > showDeletion) {runManager -> SetVerboseLevel(showDeletion);} delete sampleconstruction; if(globalVerbose > showDeletion) {G4cout << "\nSampleConstrction deleted " << std::flush;} delete materials; if(globalVerbose > showDeletion) {G4cout << "\nDefineMaterials deleted " << std::flush;} delete simMessenger; if(globalVerbose > showDeletion) {G4cout << "\nSimulationMessenger deleted\n" << std::flush;} delete visManager; if(globalVerbose > showDeletion) {G4cout << "\nVisualizationManager deleted\n" << std::flush;} delete runManager; if(globalVerbose > showDeletion) {G4cout << "RunManager deleted" << std::flush;} delete CLHEP::HepRandom::getTheEngine(); if (globalVerbose > 0) {G4cout << "\nSimulation closed! \n" << G4endl;} } void Simulation::Execute_Macrolist_pyw(std::vector<std::string> macroFiles) { int nFiles = macroFiles.size(); for (int n = 0; n < nFiles ; n++) { Execute_Macro_pyw(macroFiles[n]); } macrofiles = macroFiles; } void Simulation::Execute_Macro_pyw(std::string macro) { //Read the macro file line by line and extract the commands from the file if (globalVerbose > 0) { PrintToEndOfTerminal('-'); G4cout << "Reading file '" << macro << "' " << G4endl; } std::ifstream readfile; //Try to open the macro file readfile.open(macro); if (!readfile) { G4cout << "\nERROR: Unable to open file " << macro << " to apply commands. " << G4endl; throw std::runtime_error("Invalid macrofile"); } //Read the file std::string command; int line = 0; while ((std::getline(readfile, command))) { ++line; // TAB-> ' ' conversion str_size nb = 0; while ((nb = command.find('\t', nb)) != G4String::npos) { command.replace(nb, 1, " "); } //Skips empty lines if(command.size() == 0) continue; size_t foundhash = command.find('#'); //If found '#' will remove it and everything after if(foundhash != std::string::npos) { command = command.substr(0, foundhash); } //Check if string isn't just spaces if (command.find_first_not_of(' ') != std::string::npos) { if (globalVerbose > 3) {G4cout << line << ")";} Execute_Command_pyw (command); } } readfile.close(); if (globalVerbose > 0) {G4cout << "done "<< G4endl;} } #include "G4UIcommandTree.hh" #include "G4UIcommand.hh" #include "strfunctions.hh" #include "CommandStatus.hh" void Simulation::Execute_Command_pyw (std::string command) { //Remove all spaces at the front of the parameters, at the back and any repeated spaces strfunctions::RemoveSpaces_repeated_front_back(command); //Apply the command G4int status = UImanager -> ApplyCommand(command); //Check the status of the command. If successful, continue with the simulation if (status == fCommandSucceeded) { if (globalVerbose > 3) {G4cout << command << " successful!" << G4endl;} } else { switch (status) { //Geant4 checks case fCommandNotFound: G4cout << "ERROR: command \"" << command << "\" not found! " << G4endl; break; case fIllegalApplicationState: G4cout << "ERROR: command \"" << command << "\" is applied at the wrong state! " << G4endl; break; case fParameterOutOfRange: G4cout << "ERROR: command \"" << command << "\" parameter out of range! " << G4endl; break; case fParameterUnreadable: G4cout << "ERROR: command \"" << command << "\" parameter is unreadable! " << G4endl; break; case fParameterOutOfCandidates: G4cout << "ERROR: command \"" << command << "\" parameter out of candidates! " << G4endl; break; case fAliasNotFound: G4cout << "ERROR: command \"" << command << "\" alias not found! " << G4endl; break; //My checks case fNotEnoughParameters: G4cout << "ERROR: command \"" << command << "\" incorrect parameters! " << G4endl; break; case fIncorrectUnit: G4cout << "ERROR: command \"" << command << "\" incorrect unit! " << G4endl; break; case fParameterNotADouble: G4cout << "ERROR: command \"" << command << "\" parameter not a double! " << G4endl; break; case fParameterNotAInteger: G4cout << "ERROR: command \"" << command << "\" parameter not a integer! " << G4endl; break; case fFlagNotFound: G4cout << "ERROR: command \"" << command << "\" flag not found! " << G4endl; break; case fParameterNotFound: G4cout << "ERROR: command \"" << command << "\" cannot find parameter! " << G4endl; break; case fParameterAlreadyExists: G4cout << "ERROR: command \"" << command << "\" parameter already exists! " << G4endl; break; default: G4cout << "ERROR: command \"" << command << "\" error code : " << status << G4endl; break; } //Remove the users input to get only the command path auto commandpath = command.substr(0, command.find(' ')); //Find the command pointer that corrosponds to the command path used G4UIcommand* commandptr = UImanager->GetTree()->FindPath(commandpath.c_str()); //If commandptr exists, print the guidance associated with that command to the user if (commandptr) {G4cout << "\nGuidance: \"" << commandptr->GetGuidanceLine(0) << "\"" << G4endl; } //If interactivtiy is on, give the user the chance to reapply the command if (interactiveOn) { bool breakLoop1 = false; G4cout << "\nWould you like to reapply the command?" "\n[y/n]" << G4endl; while (!breakLoop1) { std::string reapplycommand; getline(std::cin, reapplycommand); if (reapplycommand == "y") { breakLoop1 = true; G4cout << G4endl; getline(std::cin, reapplycommand); Execute_Command_pyw (reapplycommand); } else if (reapplycommand == "n") { breakLoop1 = true; bool breakLoop2 = false; G4cout << "\nContinue with the simulation? ""\n[y/n]" << G4endl; while (!breakLoop2) { std::string continueSimulation; getline(std::cin, continueSimulation); if (continueSimulation == "n") { breakLoop2 = true; G4cout << "\nExiting..." << G4endl; throw std::runtime_error("Invalid command"); } else if (continueSimulation == "y") { breakLoop2 = true; } else { G4cout << "\nPlease type [y] or [n]. " << G4endl; } } } else { G4cout << "\nPlease type [y] or [n]. " << G4endl; } } } else { throw std::runtime_error("Invalid command"); } } } #include "G4LogicalVolumeStore.hh" #include "G4LogicalVolume.hh" #include "G4GeometryManager.hh" #include "ProgressTracker.hh" int Simulation::Run_Tomography_pyw(unsigned long long int n_particles, std::vector<int> imageinfo, double rotation_angle, double zposition) { //Get image parameters from the imageinfo int n_projection = imageinfo[0]; int nDarkFlatFields = imageinfo[1]; int totalprojections = imageinfo[2]; //Set the seed for this image by calling the rand function (next number in the sequence) CLHEP::HepRandom::setTheSeed(rand()); bool darkflatfields; if (n_projection < totalprojections - nDarkFlatFields) {darkflatfields = false;} else if (n_projection >= totalprojections - nDarkFlatFields) {darkflatfields = true;} if(n_projection == 0) { int verbose; if (globalVerbose < 3){verbose = 3;} else {verbose = globalVerbose - 3;} //Let the PrimaryGeneratorAction class know where to position the start of the beam beamManager->SetNumberOfEvents(n_particles, totalprojections); runManager->Initialize(); runManager->SetNumberOfEventsToBeStored (0); physicsManager->ActivateUserPhysics(); if (globalVerbose > 0) { //Prints the time and date of the local time that the simulation started time_t now = time(0); //Convert now to tm struct for local timezone tm* localtm = localtime(&now); PrintToEndOfTerminal('='); G4cout << "STARTING SIMULATION... \n"; G4cout << "\n" << asctime(localtm); } else { beamManager->GetProgressTracker().print = false; } } //Construct the samples. If darkflatfields are on, then it will remove the samples G4VPhysicalVolume. //After it has been constructed, if the G4VPhysicalVolume still exists, apply the needed transformations //to the sample such as rotation and translation sampleconstruction->Construct(darkflatfields); sampleconstruction->ApplyTransforms(rotation_angle, zposition); //Prepare for next run. Check if energy or gun has changed beamManager -> ResetEvents(n_projection + 1); Initialise_dataSets(true); beamManager -> GetProgressTracker().rotationangle = rotation_angle; //Beam on to start the simulation BeamOn(n_particles); if (n_projection + 1 == totalprojections) { if (globalVerbose > 0) { G4cout << "\n================================================================================" "\n The simulation is finished! " "\n================================================================================" << G4endl; } //Reset needed variables for next run beamManager -> ResetEvents(1); sampleconstruction->SetLastRotation(0); } return 0; } int Simulation::Run_Projection_pyw (unsigned long long int n_particles, bool flatfield, double rotation_angle, double zposition, bool resetdata) { //globalVerbose = 0; beamManager->GetProgressTracker().print = false; //Set the seed for this image by calling the rand function (next number in the sequence) CLHEP::HepRandom::setTheSeed(rand()); //Let the PrimaryGeneratorAction class know where to position the start of the beam beamManager -> SetNumberOfEvents(n_particles, 1); runManager -> Initialize(); //runManager -> SetNumberOfEventsToBeStored(0); physicsManager -> ActivateUserPhysics(); //Construct the samples. If darkflatfields are on, then it will remove the samples G4VPhysicalVolume. //After it has been constructed, if the G4VPhysicalVolume still exists, apply the needed transformations //to the sample such as rotation and translation sampleconstruction->Construct(flatfield); sampleconstruction->ApplyTransforms(rotation_angle, zposition); //Prepare for next run. Check if energy or gun has changed beamManager -> ResetEvents(1); Initialise_dataSets(resetdata); beamManager -> GetProgressTracker().rotationangle = rotation_angle; //UImanager -> ApplyCommand("/process/em/verbose 0"); //UImanager -> ApplyCommand("/process/verbose 0"); //Beam on to start the simulation BeamOn(n_particles); sampleconstruction->ApplyTransforms(0, 0); sampleconstruction->SetLastRotation(0); return 0; } void Simulation::Setup_Visualization_pyw(std::string path, std::string filename) { if (globalVerbose > 0) { PrintToEndOfTerminal('-'); G4cout << "GRAPHICS TURNED ON!"; } runManager->Initialize(); visManager -> Initialize(); //If a different path is used, create a folder to store the visualization data path = path + "visualization_" + filename + "/"; const char *path_char = path.c_str(); //Check if the directory exists DIR* directory_exists = opendir(path_char); //If it doesn't exist, create it if (!directory_exists) { std::string mkdir = "mkdir " + path; const char *mkdir_char = mkdir.c_str(); system(mkdir_char); } //Setup the vis manager UImanager -> ApplyCommand("/world/visualization true"); UImanager -> ApplyCommand("/vis/open HepRepFile"); UImanager -> ApplyCommand("/vis/heprep/setFileDir " + path); UImanager -> ApplyCommand("/vis/heprep/setFileName " + filename); UImanager -> ApplyCommand("/vis/viewer/set/autoRefresh false"); //UImanager -> ApplyCommand("/vis/verbose errors"); UImanager -> ApplyCommand("/vis/viewer/flush"); UImanager -> ApplyCommand("/vis/drawVolume"); //Set the draw options UImanager -> ApplyCommand("/vis/viewer/set/style wireframe"); UImanager -> ApplyCommand("/vis/viewer/set/auxiliaryEdge true"); UImanager -> ApplyCommand("/vis/viewer/set/lineSegmentsPerCircle 100"); UImanager -> ApplyCommand("/vis/scene/add/trajectories smooth"); UImanager -> ApplyCommand("/vis/modeling/trajectories/create/drawByCharge"); UImanager -> ApplyCommand("/vis/modeling/trajectories/drawByCharge-0/default/setDrawStepPts true"); UImanager -> ApplyCommand("/vis/modeling/trajectories/drawByCharge-0/default/setStepPtsSize 2"); UImanager -> ApplyCommand("/vis/scene/add/axes 0 0 0 1 cm"); UImanager -> ApplyCommand("/vis/viewer/zoom 0.5 mm"); UImanager -> ApplyCommand("/vis/scene/add/hits"); UImanager -> ApplyCommand("/vis/scene/endOfEventAction accumulate"); UImanager -> ApplyCommand("/vis/viewer/set/autoRefresh true"); if (globalVerbose > 0) {G4cout << "\nSaving as " << path + filename + "N.heprep where N is an integer. "<< G4endl;} beamManager->GetProgressTracker().singleline = false; beamManager->GetProgressTracker().graphicsOn = true; } //Function to run the simulation, will repeat simulation if over max limit void Simulation::BeamOn(unsigned long long int nParticles) { //Max limit for an integer (for Geant4 BeamOn), must be unsigned long long int as well to compare it if input is above limit. unsigned long long int limit = 2147483647; //Checks to see if the input is above the limit if (nParticles > limit) { //Rounds up to the nearest number to do the correct number of loops int NumberOfLoops = std::ceil(nParticles/limit); for (int loop = 1 ; loop <= NumberOfLoops ; loop++) { if (nParticles > limit) { //Beam on to start the simulation with the max number limit runManager -> BeamOn(limit); //Subtract from the true number of inputted particles until it is within the limit nParticles = nParticles - limit; } else { //Once within the limit, fire the remaining particles that are left runManager -> BeamOn(nParticles); } } } else { //If the inputted number of particles is within the limit, fire that number of particles runManager -> BeamOn(nParticles); } } //Function to limit the number of particles if graphics is turned on unsigned long long int Simulation::LimitGraphics(unsigned long long int nParticles, int nImage, std::string Mode) { if (detectorManager -> GetVisualization() == true && nParticles > 5000) { int limit = 100; nParticles = limit; if (nImage == 0) { G4cout << "\n////////////////////////////////////////////////////////////////////////////////\n" "\n WARNING: " << nParticles << " PARTICLES IS TOO MANY TOO SIMULATE WITH GRAPHICS" "\n Reducing the number of particles to " << limit << "\n" "\n////////////////////////////////////////////////////////////////////////////////" << G4endl;; } } return nParticles; } //Function to log the inforimation about the simulation. Outputs to terminal depending on verbose level. Always outputs to _log.txt file void Simulation::Print_SimulationInfo_pyw(std::string filepath, unsigned long long int n_particles, int totalprojections, int nDarkFlatFields) { if (globalVerbose > 0) { std::ofstream SaveToFile; //Try to open the file SaveToFile.open(filepath); if( !SaveToFile ) { G4cout << "\nError: " << filepath << " file could not be opened from Simulation. " << "\n" << G4endl; exit(1); } //Create an instance of the log to output to terminal and file SettingsLog log(SaveToFile); PrintInformation(log); double particleperpixel = n_particles/(detectorManager->GetAbsorptionDetector()->GetxPixels() * detectorManager->GetAbsorptionDetector()->GetyPixels()); PrintToEndOfTerminal(log, '-'); log << "META DATA: " "\n- The seed used: " << seedCmd << "\n- Total number of projections being processed: " << totalprojections << "\n - Flat fields: " << nDarkFlatFields << "\n - Sample: " << totalprojections - nDarkFlatFields << "\n- Number of photons per image: " << n_particles << "\n- Number of particles per pixel on average: " << particleperpixel; SaveToFile.close(); CalculateStorageSpace(totalprojections); } } void Simulation::PrintInformation(SettingsLog log) { if (globalVerbose > 0) { log.terminalOn = false; //Loop through the macro files int nFiles = macrofiles.size(); for (int n = 0 ; n < nFiles ; n++) { std::ifstream readfile; PrintToEndOfTerminal(log, '-'); //Try to open the macro file readfile.open(macrofiles[n]); if (!readfile) { G4cout << "\nERROR: Unable to open " << macrofiles[n] << " for log output. " << G4endl; exit(1); } log << "Macro file " << n + 1 << ": " << macrofiles[n] << "\n" << G4endl; //Read the file std::string Line; while ((std::getline(readfile, Line))) { //if (Line.find('#') == std::string::npos) if(Line[1] != '/') {log << Line << G4endl;} } readfile.close(); } if (globalVerbose >= 1) {log.terminalOn = true;} else {log.terminalOn = false;} //Log the info from other classes detectorManager -> ReadOutInfo(log); beamManager -> ReadOutInfo(log); physicsManager -> ReadOutInfo(log); } } #include "G4PhysicalVolumeStore.hh" #include "G4LogicalVolumeStore.hh" #include "G4RegionStore.hh" #include "G4GeometryManager.hh" void Simulation::CleanGeometry() { //Clean old geometry if any G4GeometryManager::GetInstance()->OpenGeometry(); sampleconstruction->Reset(); G4PhysicalVolumeStore::GetInstance()->Clean(); G4LogicalVolumeStore::GetInstance()->Clean(); G4RegionStore::GetInstance()->Clean(); G4GeometryManager::GetInstance()->CloseGeometry(); //The geometry needs to be Reinitialised for the next run runManager -> ReinitializeGeometry(); } void Simulation::CalculateStorageSpace(int projections) { if (globalVerbose > 0) { double totalStorage = 0; std::string unit; int abs_xPixels = AbsorptionDetector_GetXPixels_pyw(); int abs_yPixels = AbsorptionDetector_GetYPixels_pyw(); int bins = FluorescenceDetector_GetNoEnergyBins_pyw(); PrintToEndOfTerminal('-'); G4cout << "DISK SPACE REQUIRED FOR DATA: "; //Absorption size_t absorpDataSize = sizeof(AbsorptionDetector_GetProjection_pyw()[0]); double absorpStorageSpace = abs_xPixels * abs_yPixels * absorpDataSize * projections; totalStorage += absorpStorageSpace; unit = GetStorageUnit(absorpStorageSpace); G4cout << "\n- Absorption: " << absorpStorageSpace << unit; //Beam energy size_t beam_ByteTypeSize = beamManager -> GetBeamEnergyByteTypeSize(); double beamStorageSpace = bins * beam_ByteTypeSize * projections; totalStorage += beamStorageSpace; unit = GetStorageUnit(beamStorageSpace); G4cout << "\n- Beam energy: " << beamStorageSpace << unit; //Fluorecence if (FluorescenceDetector_FullMappingActive_pyw()) { size_t FMfluoresenceDataSize = sizeof(FluorescenceDetector_GetEnergyBins_pyw()[0]); double fluorescenceStorageSpace = absorpStorageSpace*FluorescenceDetector_GetNoEnergyBins_pyw(); totalStorage += fluorescenceStorageSpace; unit = GetStorageUnit(fluorescenceStorageSpace); G4cout << "\n- Full mapping fluorescence: " << fluorescenceStorageSpace << unit; } /*//Diffraction if (data->DoFullMappingDiffraction() ) { size_t DiffractionDataSize = data -> GetDiffractionSizeType(); double diffractionStorageSpace = double(abs_xPixels) * double(abs_yPixels) *abs_xPixels * abs_yPixels * DiffractionDataSize * projections; totalStorage += diffractionStorageSpace; unit = GetStorageUnit(diffractionStorageSpace); G4cout << "\n- Full mapping diffraction: " << diffractionStorageSpace << unit; }*/ unit = GetStorageUnit(totalStorage); G4cout << "\n- Total: " << totalStorage << unit << std::flush; PrintToEndOfTerminal('-'); } } std::string Simulation::GetStorageUnit(double &storage) { double peta = 1.e15; double tera = 1.e12; double giga = 1.e9; double mega = 1.e6; double kilo = 1.e3; double byte = 1.; if (storage > kilo) { if (storage > mega) { if (storage > giga) { if(storage > tera) { if(storage > peta) { storage = storage/peta; return " pb"; } storage = storage/tera; return " tb"; } storage = storage/giga; return " gb"; } storage = storage/mega; return " mb"; } storage = storage/kilo; return " kb"; } storage = storage/byte; return " bytes"; } void Simulation::SetSeed(long int seedinput) { seedCmd = seedinput; if (seedinput == 0) { //Set random seed sequence with system time seedCmd = time(0); srand(seedCmd); randseed = true; } else { //Set the seed sequence using inputted seed srand(seedCmd); randseed = false; } } void Simulation::Initialise_dataSets(bool clean_data) { detectorManager->GetAbsorptionDetector()->GetSensitiveDetector()->InitialiseData(clean_data); detectorManager->GetFluorescenceDetector()->GetSensitiveDetector()->InitialiseData(clean_data); beamManager->SetupData(clean_data); }
37.001332
160
0.579135
[ "geometry", "vector" ]
b9a8f8856db478e17e62f8890bb998f0253c5027
29,364
cpp
C++
tests/test_jacobi.cpp
jewettaij/jacobi
d8df18ee6d10fda957a7da3fe688c290f1a39c51
[ "CC0-1.0" ]
19
2020-03-26T12:52:53.000Z
2022-03-25T09:25:21.000Z
tests/test_jacobi.cpp
jewettaij/jacobi
d8df18ee6d10fda957a7da3fe688c290f1a39c51
[ "CC0-1.0" ]
null
null
null
tests/test_jacobi.cpp
jewettaij/jacobi
d8df18ee6d10fda957a7da3fe688c290f1a39c51
[ "CC0-1.0" ]
8
2020-10-03T14:40:01.000Z
2022-01-03T16:09:43.000Z
// THIS FILE USED TO BE EASY TO READ until I added "#if defined" statements. // (They were added to test for many different kinds of array formats.) #include <iostream> #include <cmath> #include <cassert> #include <iomanip> #include <cstdlib> #include <chrono> #include <random> #include <algorithm> #include <vector> #include <array> #include "matrix_alloc_jpd.hpp" #include "jacobi_pd.hpp" using std::cout; using std::cerr; using std::endl; using std::setprecision; using std::vector; using std::array; using namespace matrix_alloc_jpd; using namespace jacobi_pd; // This code works with various types of C++ matrices (for example, // double **, vector<vector<double>> array<array<double,5>,5>). // I use "#if defined" statements to test different matrix types. // For some of these (eg. array<array<double,5>,5>), the size of the matrix // must be known at compile time. I specify that size now. #if defined USE_ARRAY_OF_ARRAYS const int NF=5; //(the array size must be known at compile time) #elif defined USE_C_FIXED_SIZE_ARRAYS const int NF=5; //(the array size must be known at compile time) #endif // @brief Are two numbers "similar"? template<typename Scalar> inline static bool Similar(Scalar a, Scalar b, Scalar eps=1.0e-06, Scalar ratio=1.0e-06, Scalar ratio_denom=1.0) { return ((std::abs(a-b)<=std::abs(eps)) || (std::abs(ratio_denom)*std::abs(a-b) <= std::abs(ratio)*0.5*(std::abs(a)+std::abs(b)))); } /// @brief Are two vectors (containing n numbers) similar? template<typename Scalar, typename Vector> inline static bool SimilarVec(Vector a, Vector b, int n, Scalar eps=1.0e-06, Scalar ratio=1.0e-06, Scalar ratio_denom=1.0) { for (int i = 0; i < n; i++) if (not Similar(a[i], b[i], eps, ratio, ratio_denom)) return false; return true; } /// @brief Are two vectors (or their reflections) similar? template<typename Scalar, typename Vector> inline static bool SimilarVecUnsigned(Vector a, Vector b, int n, Scalar eps=1.0e-06, Scalar ratio=1.0e-06, Scalar ratio_denom=1.0) { if (SimilarVec(a, b, n, eps)) return true; else { for (int i = 0; i < n; i++) if (not Similar(a[i], -b[i], eps, ratio, ratio_denom)) return false; return true; } } /// @brief Multiply two matrices A and B, store the result in C. (C = AB). template<typename Matrix, typename ConstMatrix> void mmult(ConstMatrix A, //<! input array ConstMatrix B, //<! input array Matrix C, //<! store result here int m, //<! number of rows of A int n=0, //<! optional: number of columns of B (=m by default) int K=0 //<! optional: number of columns of A = num rows of B (=m by default) ) { if (n == 0) n = m; // if not specified, then assume the matrices are square if (K == 0) K = m; // if not specified, then assume the matrices are square for (int i = 0; i < m; i++) for (int j = 0; j < n; j++) C[i][j] = 0.0; // perform matrix multiplication for (int i = 0; i < m; i++) for (int j = 0; j < n; j++) for (int k = 0; k < K; k++) C[i][j] += A[i][k] * B[k][j]; } /// @brief ///Sort the rows of a matrix "evec" by the numbers contained in "eval" ///(This is a simple O(n^2) sorting method, but O(n^2) is a lower bound anyway.) ///This is the same as the Jacobi::SortRows(), but that function is private. template<typename Scalar, typename Vector, typename Matrix> void SortRows(Vector eval, Matrix evec, int n, bool sort_decreasing=true, bool sort_abs=false) { for (int i = 0; i < n-1; i++) { int i_max = i; for (int j = i+1; j < n; j++) { if (sort_decreasing) { if (sort_abs) { //sort by absolute value? if (std::abs(eval[j]) > std::abs(eval[i_max])) i_max = j; } else if (eval[j] > eval[i_max]) i_max = j; } else { if (sort_abs) { //sort by absolute value? if (std::abs(eval[j]) < std::abs(eval[i_max])) i_max = j; } else if (eval[j] < eval[i_max]) i_max = j; } } std::swap(eval[i], eval[i_max]); // sort "eval" for (int k = 0; k < n; k++) std::swap(evec[i][k], evec[i_max][k]); // sort "evec" } } /// @brief Generate a random orthonormal n x n matrix template<typename Scalar, typename Matrix> void GenRandOrth(Matrix R, int n, std::default_random_engine &rand_generator) { std::normal_distribution<Scalar> gaussian_distribution(0,1); std::vector<Scalar> v(n); for (int i = 0; i < n; i++) { // Generate a vector, "v", in a random direction subject to the constraint // that it is orthogonal to the first i-1 rows-vectors of the R matrix. Scalar rsq = 0.0; while (rsq == 0.0) { // Generate a vector in a random direction // (This works because we are using a normal (Gaussian) distribution) for (int j = 0; j < n; j++) v[j] = gaussian_distribution(rand_generator); //Now subtract from v, the projection of v onto the first i-1 rows of R. //This will produce a vector which is orthogonal to these i-1 row-vectors. //(They are already normalized and orthogonal to each other.) for (int k = 0; k < i; k++) { Scalar v_dot_Rk = 0.0; for (int j = 0; j < n; j++) v_dot_Rk += v[j] * R[k][j]; for (int j = 0; j < n; j++) v[j] -= v_dot_Rk * R[k][j]; } // check if it is linearly independent of the other vectors and non-zero rsq = 0.0; for (int j = 0; j < n; j++) rsq += v[j]*v[j]; } // Now normalize the vector Scalar r_inv = 1.0 / std::sqrt(rsq); for (int j = 0; j < n; j++) v[j] *= r_inv; // Now copy this vector to the i'th row of R for (int j = 0; j < n; j++) R[i][j] = v[j]; } //for (int i = 0; i < n; i++) } //void GenRandOrth() /// @brief Generate a random symmetric n x n matrix, M. /// This function generates random numbers for the eigenvalues ("evals_known") /// as well as the eigenvectors ("evecs_known"), and uses them to generate M. /// The "eval_magnitude_range" argument specifies the the base-10 logarithm /// of the range of eigenvalues desired. The "n_degeneracy" argument specifies /// the number of repeated eigenvalues desired (if any). /// @returns This function does not return a value. However after it is /// invoked, the M matrix will be filled with random numbers. /// Additionally, the "evals" and "evecs" arguments will contain /// the eigenvalues and eigenvectors (one eigenvector per row) /// of the matrix. Later, they can be compared with the eigenvalues /// and eigenvectors calculated by Jacobi::Diagonalize() template <typename Scalar, typename Vector, typename Matrix> void GenRandSymm(Matrix M, //<! store the matrix here int n, //<! matrix size Vector evals, //<! store the eigenvalues of here Matrix evecs, //<! store the eigenvectors here std::default_random_engine &rand_generator,//<! makes random numbers Scalar min_eval_size=0.1, //<! minimum possible eigenvalue size Scalar max_eval_size=10.0,//<! maximum possible eigenvalue size int n_degeneracy=1//<!number of repeated eigevalues(1disables) ) { assert(n_degeneracy <= n); std::uniform_real_distribution<Scalar> random_real01; std::normal_distribution<Scalar> gaussian_distribution(0, max_eval_size); bool use_log_uniform_distribution = false; if (min_eval_size > 0.0) use_log_uniform_distribution = true; #if defined USE_VECTOR_OF_VECTORS vector<vector<Scalar> > D(n, vector<Scalar>(n)); vector<vector<Scalar> > tmp(n, vector<Scalar>(n)); #elif defined USE_ARRAY_OF_ARRAYS array<array<Scalar, NF>, NF> D; array<array<Scalar, NF>, NF> tmp; #elif defined USE_C_FIXED_SIZE_ARRAYS Scalar D[NF][NF], tmp[NF][NF]; #else #define USE_C_POINTER_TO_POINTERS Scalar **D, **tmp; Alloc2D(n, n, &D); Alloc2D(n, n, &tmp); #endif // Randomly generate the eigenvalues for (int i = 0; i < n; i++) { if (use_log_uniform_distribution) { // Use a "log-uniform distribution" (a.k.a. "reciprocal distribution") // (This is a way to specify numbers with a precise range of magnitudes.) assert((min_eval_size > 0.0) && (max_eval_size > 0.0)); Scalar log_min = std::log(std::abs(min_eval_size)); Scalar log_max = std::log(std::abs(max_eval_size)); Scalar log_eval = (log_min + random_real01(rand_generator)*(log_max-log_min)); evals[i] = std::exp(log_eval); // also consider both positive and negative eigenvalues: if (random_real01(rand_generator) < 0.5) evals[i] = -evals[i]; } else { evals[i] = gaussian_distribution(rand_generator); } } // Does the user want us to force some of the eigenvalues to be the same? if (n_degeneracy > 1) { int *permutation = new int[n]; //a random permutation from 0...n-1 for (int i = 0; i < n; i++) permutation[i] = i; std::shuffle(permutation, permutation+n, rand_generator); for (int i = 1; i < n_degeneracy; i++) //set the first n_degeneracy to same evals[permutation[i]] = evals[permutation[0]]; delete [] permutation; } // D is a diagonal matrix whose diagonal elements are the eigenvalues for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) D[i][j] = ((i == j) ? evals[i] : 0.0); // Now randomly generate the (transpose of) the "evecs" matrix GenRandOrth<Scalar, Matrix>(evecs, n, rand_generator); //(will transpose it later) // Construct the test matrix, M, where M = Rt * D * R // Original code: //mmult(evecs, D, tmp, n); // <--> tmp = Rt * D // Unfortunately, C++ guesses the types incorrectly. Must manually specify: // #ifdefs making the code ugly again: #if defined USE_VECTOR_OF_VECTORS mmult<vector<vector<Scalar> >&, const vector<vector<Scalar> >&> #elif defined USE_ARRAY_OF_ARRAYS mmult<array<array<Scalar,NF>,NF>&, const array<array<Scalar,NF>,NF>&> #elif defined USE_C_FIXED_SIZE_ARRAYS mmult<Scalar (*)[NF], Scalar (*)[NF]> #else mmult<Scalar**, Scalar const *const *> #endif (evecs, D, tmp, n); for (int i = 0; i < n-1; i++) for (int j = i+1; j < n; j++) std::swap(evecs[i][j], evecs[j][i]); //transpose "evecs" // Original code: //mmult(tmp, evecs, M, n); // Unfortunately, C++ guesses the types incorrectly. Must manually specify: // #ifdefs making the code ugly again: #if defined USE_VECTOR_OF_VECTORS mmult<vector<vector<Scalar> >&, const vector<vector<Scalar> >&> #elif defined USE_ARRAY_OF_ARRAYS mmult<array<array<Scalar,NF>,NF>&, const array<array<Scalar,NF>,NF>&> #elif defined USE_C_FIXED_SIZE_ARRAYS mmult<Scalar (*)[NF], Scalar (*)[NF]> #else mmult<Scalar**, Scalar const *const *> #endif (tmp, evecs, M, n); //at this point M = Rt*D*R (where "R"="evecs") #if defined USE_C_POINTER_TO_POINTERS Dealloc2D(&D); Dealloc2D(&tmp); #endif } // GenRandSymm() template <typename Scalar> void TestJacobi(int n, //<! matrix size int n_matrices=100, //<! number of matrices to test Scalar min_eval_size=0.1, //<! minimum possible eigenvalue sizw Scalar max_eval_size=10.0, //<! maximum possible eigenvalue size int n_tests_per_matrix=1, //<! repeat test for benchmarking? int n_degeneracy=1, //<! repeated eigenvalues? unsigned seed=0, //<! random seed (if 0 then use the clock) Scalar eps=1.0e-06 ) { bool test_code_coverage = false; if (n_tests_per_matrix < 1) { cout << "-- Testing code-coverage --" << endl; test_code_coverage = true; n_tests_per_matrix = 1; } cout << endl << "-- Diagonalization test (real symmetric) --" << endl; // construct a random generator engine using a time-based seed: if (seed == 0) // if the caller did not specify a seed, use the system clock seed = std::chrono::system_clock::now().time_since_epoch().count(); std::default_random_engine rand_generator(seed); // Create an instance of the Jacobi diagonalizer, and allocate the matrix // we will test it on, as well as the arrays that will store the resulting // eigenvalues and eigenvectors. // The way we do this depends on what version of the code we are using. // This is controlled by "#if defined" statements. #if defined USE_VECTOR_OF_VECTORS Jacobi<Scalar, vector<Scalar>&, vector<vector<Scalar> >&, const vector<vector<Scalar> >& > ecalc(n); // allocate the matrix, eigenvalues, eigenvectors vector<vector<Scalar> > M(n, vector<Scalar>(n)); vector<vector<Scalar> > evecs(n, vector<Scalar>(n)); vector<vector<Scalar> > evecs_known(n, vector<Scalar>(n)); vector<Scalar> evals(n); vector<Scalar> evals_known(n); vector<Scalar> test_evec(n); #elif defined USE_ARRAY_OF_ARRAYS n = NF; cout << "Testing std::array (fixed size).\n" "(Ignoring first argument, and setting matrix size to " << n << ")" << endl; Jacobi<Scalar, array<Scalar, NF>&, array<array<Scalar, NF>, NF>&, const array<array<Scalar, NF>, NF>&> ecalc(n); // allocate the matrix, eigenvalues, eigenvectors array<array<Scalar, NF>, NF> M; array<array<Scalar, NF>, NF> evecs; array<array<Scalar, NF>, NF> evecs_known; array<Scalar, NF> evals; array<Scalar, NF> evals_known; array<Scalar, NF> test_evec; #elif defined USE_C_FIXED_SIZE_ARRAYS n = NF; cout << "Testing C fixed size arrays.\n" "(Ignoring first argument, and setting matrix size to " << n << ")" << endl; Jacobi<Scalar, Scalar*, Scalar (*)[NF], Scalar const (*)[NF]> ecalc(n); // allocate the matrix, eigenvalues, eigenvectors Scalar M[NF][NF]; Scalar evecs[NF][NF]; Scalar evecs_known[NF][NF]; Scalar evals[NF]; Scalar evals_known[NF]; Scalar test_evec[NF]; #else #define USE_C_POINTER_TO_POINTERS // Note: Normally, you would just use this to instantiate Jacobi: // Jacobi<Scalar, Scalar*, Scalar**, Scalar const*const*> ecalc(n); // ------------------------- // ..but since Jacobi manages its own memory using new and delete, I also want // to test that the copy constructors, copy operators, and destructors work. // The following lines do this: Jacobi<Scalar, Scalar*, Scalar**, Scalar const*const*> ecalc_test_mem1; ecalc_test_mem1.SetSize(n); Jacobi<Scalar, Scalar*, Scalar**, Scalar const*const*> ecalc_test_mem2(2); // test the = operator ecalc_test_mem2 = ecalc_test_mem1; // test the copy constructor Jacobi<Scalar, Scalar*, Scalar**, Scalar const*const*> ecalc(ecalc_test_mem2); // allocate the matrix, eigenvalues, eigenvectors Scalar **M, **evecs, **evecs_known; Alloc2D(n, n, &M); Alloc2D(n, n, &evecs); Alloc2D(n, n, &evecs_known); Scalar *evals = new Scalar[n]; Scalar *evals_known = new Scalar[n]; Scalar *test_evec = new Scalar[n]; #endif // -------------------------------------------------------------------- // Now, generate random matrices and test Jacobi::Diagonalize() on them. // -------------------------------------------------------------------- for(int imat = 0; imat < n_matrices; imat++) { // Create a randomly generated symmetric matrix. //This function generates random numbers for the eigenvalues ("evals_known") //as well as the eigenvectors ("evecs_known"), and uses them to generate M. #if defined USE_VECTOR_OF_VECTORS GenRandSymm<Scalar, vector<Scalar>&, vector<vector<Scalar> >&> #elif defined USE_ARRAY_OF_ARRAYS GenRandSymm<Scalar, array<Scalar,NF>&, array<array<Scalar,NF>,NF>&> #elif defined USE_C_FIXED_SIZE_ARRAYS GenRandSymm<Scalar, Scalar*, Scalar (*)[NF]> #else GenRandSymm<Scalar, Scalar*, Scalar**> #endif (M, n, evals_known, evecs_known, rand_generator, min_eval_size, max_eval_size, n_degeneracy); // Sort the matrix evals and eigenvector rows: // Original code: //SortRows<Scalar>(evals_known, evecs_known, n); // Unfortunately, C++ guesses the types incorrectly. Must use #ifdefs again: #if defined USE_VECTOR_OF_VECTORS SortRows<Scalar, vector<Scalar>&, vector<vector<Scalar> >&> #elif defined USE_ARRAY_OF_ARRAYS SortRows<Scalar, array<Scalar,NF>&, array<array<Scalar,NF>,NF>&> #elif defined USE_C_FIXED_SIZE_ARRAYS SortRows<Scalar, Scalar*, Scalar (*)[NF]> #else SortRows<Scalar, Scalar*, Scalar**> #endif (evals_known, evecs_known, n); if (n_matrices == 1) { cout << "Matrix:\n"; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) cout << M[i][j] << " "; cout << "\n"; } cout << "Eigenvalues (after sorting):\n"; for (int i = 0; i < n; i++) cout << evals_known[i] << " "; cout << "\n"; cout << "Eigenvectors (rows) which are known in advance:\n"; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) cout << evecs_known[i][j] << " "; cout << "\n"; } cout << " (The eigenvectors calculated by Jacobi::Diagonalize() should match these.)\n"; } for (int i_test = 0; i_test < n_tests_per_matrix; i_test++) { if (test_code_coverage) { // test SORT_INCREASING_ABS_EVALS: #if defined USE_VECTOR_OF_VECTORS ecalc.Diagonalize(M, evals, evecs, Jacobi<Scalar, vector<Scalar>&, vector<vector<Scalar> >&, const vector<vector<Scalar> >& >::SORT_INCREASING_ABS_EVALS); #elif defined USE_ARRAY_OF_ARRAYS ecalc.Diagonalize(M, evals, evecs, Jacobi<Scalar, array<Scalar,NF>&, array<array<Scalar,NF>,NF>&, const array<array<Scalar,NF>,NF>&>::SORT_INCREASING_ABS_EVALS); #elif defined USE_C_FIXED_SIZE_ARRAYS ecalc.Diagonalize(M, evals, evecs, Jacobi<Scalar, Scalar*, Scalar (*)[NF], Scalar const (*)[NF]>::SORT_INCREASING_ABS_EVALS); #else ecalc.Diagonalize(M, evals, evecs, Jacobi<Scalar, Scalar*, Scalar**, Scalar const*const*>::SORT_INCREASING_ABS_EVALS); // Also make sure the code considers a scenario where convergence fails: ecalc.Diagonalize(M, evals, evecs, Jacobi<Scalar, Scalar*, Scalar**, Scalar const*const*>::SORT_INCREASING_ABS_EVALS, true, 0); //<-- set the maximum allowed iterations to 0 #endif for (int i = 1; i < n; i++) assert(std::abs(evals[i-1])<=std::abs(evals[i])); // test SORT_DECREASING_ABS_EVALS: #if defined USE_VECTOR_OF_VECTORS ecalc.Diagonalize(M, evals, evecs, Jacobi<Scalar, vector<Scalar>&, vector<vector<Scalar> >&, const vector<vector<Scalar> >& >::SORT_DECREASING_ABS_EVALS); #elif defined USE_ARRAY_OF_ARRAYS ecalc.Diagonalize(M, evals, evecs, Jacobi<Scalar, array<Scalar,NF>&, array<array<Scalar,NF>,NF>&, const array<array<Scalar,NF>,NF>&>::SORT_DECREASING_ABS_EVALS); #elif defined USE_C_FIXED_SIZE_ARRAYS ecalc.Diagonalize(M, evals, evecs, Jacobi<Scalar, Scalar*, Scalar (*)[NF], Scalar const (*)[NF]>::SORT_DECREASING_ABS_EVALS); #else ecalc.Diagonalize(M, evals, evecs, Jacobi<Scalar, Scalar*, Scalar**, Scalar const*const*>::SORT_DECREASING_ABS_EVALS); #endif for (int i = 1; i < n; i++) assert(std::abs(evals[i-1])>=std::abs(evals[i])); // test SORT_INCREASING_EVALS: #if defined USE_VECTOR_OF_VECTORS ecalc.Diagonalize(M, evals, evecs, Jacobi<Scalar, vector<Scalar>&, vector<vector<Scalar> >&, const vector<vector<Scalar> >& >::SORT_INCREASING_EVALS); #elif defined USE_ARRAY_OF_ARRAYS ecalc.Diagonalize(M, evals, evecs, Jacobi<Scalar, array<Scalar,NF>&, array<array<Scalar,NF>,NF>&, const array<array<Scalar,NF>,NF>&>::SORT_INCREASING_EVALS); #elif defined USE_C_FIXED_SIZE_ARRAYS ecalc.Diagonalize(M, evals, evecs, Jacobi<Scalar, Scalar*, Scalar (*)[NF], Scalar const (*)[NF]>::SORT_INCREASING_EVALS); #else ecalc.Diagonalize(M, evals, evecs, Jacobi<Scalar, Scalar*, Scalar**, Scalar const*const*>::SORT_INCREASING_EVALS); #endif for (int i = 1; i < n; i++) assert(evals[i-1] <= evals[i]); // test DO_NOT_SORT #if defined USE_VECTOR_OF_VECTORS ecalc.Diagonalize(M, evals, evecs, Jacobi<Scalar, vector<Scalar>&, vector<vector<Scalar> >&, const vector<vector<Scalar> >& >::DO_NOT_SORT); #elif defined USE_ARRAY_OF_ARRAYS ecalc.Diagonalize(M, evals, evecs, Jacobi<Scalar, array<Scalar,NF>&, array<array<Scalar,NF>,NF>&, const array<array<Scalar,NF>,NF>&>::DO_NOT_SORT); #elif defined USE_C_FIXED_SIZE_ARRAYS ecalc.Diagonalize(M, evals, evecs, Jacobi<Scalar, Scalar*, Scalar (*)[NF], Scalar const (*)[NF]>::DO_NOT_SORT); #else ecalc.Diagonalize(M, evals, evecs, Jacobi<Scalar, Scalar*, Scalar**, Scalar const*const*>::DO_NOT_SORT); #endif } //if (test_code_coverage) // Now (finally) calculate the eigenvalues and eigenvectors int n_sweeps = ecalc.Diagonalize(M, evals, evecs); if ((n_matrices == 1) && (i_test == 0)) { cout <<"Jacobi::Diagonalize() ran for "<<n_sweeps<<" iters (sweeps).\n"; cout << "Eigenvalues calculated by Jacobi::Diagonalize()\n"; for (int i = 0; i < n; i++) cout << evals[i] << " "; cout << "\n"; cout << "Eigenvectors (rows) calculated by Jacobi::Diagonalize()\n"; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) cout << evecs[i][j] << " "; cout << "\n"; } } assert(SimilarVec(evals, evals_known, n, eps*max_eval_size, eps)); //Check that each eigenvector satisfies Mv = λv // <--> Σ_b M[a][b]*evecs[i][b] = evals[i]*evecs[i][b] (for all a) for (int i = 0; i < n; i++) { for (int a = 0; a < n; a++) { test_evec[a] = 0.0; for (int b = 0; b < n; b++) test_evec[a] += M[a][b] * evecs[i][b]; assert(Similar(test_evec[a], evals[i] * evecs[i][a], eps, // tolerance (absolute difference) eps*max_eval_size, // tolerance ratio (numerator) evals_known[i] // tolerance ration (denominator) )); } } } //for (int i_test = 0; i_test < n_tests_per_matrix; i++) } //for(int imat = 0; imat < n_matrices; imat++) { #if defined USE_C_POINTER_TO_POINTERS Dealloc2D(&M); Dealloc2D(&evecs); Dealloc2D(&evecs_known); delete [] evals; delete [] evals_known; delete [] test_evec; #endif } //TestJacobi() int main(int argc, char **argv) { int n_size = 2; int n_matr = 1; double emin = 0.0; double emax = 1.0; int n_tests = 1; int n_degeneracy = 1; unsigned seed = 0; if (argc <= 1) { cerr << "Error: This program requires at least 1 argument.\n" "\n" "Description: Run Jacobi::Diagonalize() on randomly generated matrices.\n" "\n" "Arguments: n_size [n_matr emin emax n_degeneracy n_tests seed eps]\n" " n_size = the size of the matrices\n" " (NOTE: The remaining arguments are optional.)\n" " n_matr = the number of randomly generated matrices to test\n" " emin = the smallest possible eigenvalue magnitude (eg. 1e-05)\n" " emax = the largest possible eigenvalue magnitude (>0 eg. 1e+05)\n" " (NOTE: If emin=0, a normal distribution is used centered at 0.\n" " Otherwise a log-uniform distribution is used from emin to emax.)\n" " n_degeneracy = the number of repeated eigenvalues (1 disables, default)\n" " n_tests = the number of times the eigenvalues and eigenvectors\n" " are calculated for EACH matrix. By default this is 1.\n" " (Increase this to at least 20 if you plan to use this\n" " program for benchmarking (speed testing), because the time\n" " needed for generating a random matrix is not negligible.)\n" " (IF THIS NUMBER IS 0, it will test CODE-COVERAGE instead.)\n" " seed = the seed used by the random number \"rand_generator\".\n" " (If this number is 0, which is the default, the system\n" " clock is used to choose a random seed.)\n" " eps = the tolerance. The difference between eigenvalues and their\n" " true value, cannot exceed this (multiplied by the eigenvalue\n" " of maximum magnitude). Similarly, the difference between\n" " the eigenvectors after multiplication by the matrix and by\n" " and after multiplication by the eigenvalue, cannot exceed\n" " eps*maximum_eigenvalue/eigenvalue. The default value is\n" " 1.0e-06 (which works well for double precision numbers).\n" << endl; return 1; } n_size = std::stoi(argv[1]); if (argc > 2) n_matr = std::stoi(argv[2]); if (argc > 3) emin = std::stof(argv[3]); if (argc > 4) emax = std::stof(argv[4]); if (argc > 5) n_degeneracy = std::stoi(argv[5]); if (argc > 6) n_tests = std::stoi(argv[6]); if (argc > 7) seed = std::stoi(argv[7]); double eps = 1.0e-06; if (argc > 8) eps = std::stof(argv[8]); TestJacobi(n_size, n_matr, emin, emax, n_tests, n_degeneracy, seed, eps); cout << "test passed\n" << endl; return EXIT_SUCCESS; }
37.358779
96
0.542195
[ "vector" ]
b9a8fb5ce955780fab6f6ac4660daa503752d0bd
4,303
cpp
C++
addons/msalibs/MSAOpenCL/src/MSAOpenCLBuffer.cpp
k4rm/AscoGraph
9038ae785b6f4f144a3ab5c4c5520761c0cd08f2
[ "MIT" ]
18
2015-01-18T22:34:22.000Z
2020-09-06T20:30:30.000Z
addons/msalibs/MSAOpenCL/src/MSAOpenCLBuffer.cpp
k4rm/AscoGraph
9038ae785b6f4f144a3ab5c4c5520761c0cd08f2
[ "MIT" ]
2
2015-08-04T00:07:46.000Z
2017-05-10T15:53:51.000Z
addons/msalibs/MSAOpenCL/src/MSAOpenCLBuffer.cpp
k4rm/AscoGraph
9038ae785b6f4f144a3ab5c4c5520761c0cd08f2
[ "MIT" ]
10
2015-01-18T23:46:10.000Z
2019-08-25T12:10:04.000Z
/*********************************************************************** OpenCL Buffer Memory Object You can either instantiate this class directly. e.g.: OpenCLBuffer myBuffer; myImage.initFromGLObject(myVbo); or create it via Instead use OpenCL::createBufferXXXX. e.g.: OpenCLBuffer *myBuffer = openCL.createBufferFromGLObject(myVBO); (this method is here for backwards compatibility with previous versions of OpenCL) /*********************************************************************** Copyright (c) 2008, 2009, Memo Akten, www.memo.tv *** The Mega Super Awesome Visuals Company *** * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of MSA Visuals nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * * ***********************************************************************/ #include "MSAOpenCL.h" #include "MSAOpenCLBuffer.h" namespace MSA { OpenCLBuffer::OpenCLBuffer() { ofLog(OF_LOG_VERBOSE, "OpenCLBuffer::OpenCLBuffer"); } void OpenCLBuffer::initBuffer(int numberOfBytes, cl_mem_flags memFlags, void *dataPtr, bool blockingWrite) { ofLog(OF_LOG_VERBOSE, "OpenCLBuffer::initBuffer"); init(); cl_int err; clMemObject = clCreateBuffer(pOpenCL->getContext(), memFlags, numberOfBytes, memFlags & CL_MEM_USE_HOST_PTR ? dataPtr : NULL, &err); assert(err == CL_SUCCESS); assert(clMemObject); if(dataPtr) write(dataPtr, 0, numberOfBytes, blockingWrite); } void OpenCLBuffer::initFromGLObject(GLuint glBufferObject, cl_mem_flags memFlags) { ofLog(OF_LOG_VERBOSE, "OpenCLBuffer::initFromGLObject"); init(); cl_int err; clMemObject= clCreateFromGLBuffer(pOpenCL->getContext(), memFlags, glBufferObject, &err); assert(err != CL_INVALID_CONTEXT); assert(err != CL_INVALID_VALUE); assert(err != CL_INVALID_GL_OBJECT); assert(err != CL_OUT_OF_HOST_MEMORY); assert(err == CL_SUCCESS); assert(clMemObject); } void OpenCLBuffer::read(void *dataPtr, int startOffsetBytes, int numberOfBytes, bool blockingRead) { cl_int err = clEnqueueReadBuffer(pOpenCL->getQueue(), clMemObject, blockingRead, startOffsetBytes, numberOfBytes, dataPtr, 0, NULL, NULL); assert(err == CL_SUCCESS); } void OpenCLBuffer::write(void *dataPtr, int startOffsetBytes, int numberOfBytes, bool blockingWrite) { cl_int err = clEnqueueWriteBuffer(pOpenCL->getQueue(), clMemObject, blockingWrite, startOffsetBytes, numberOfBytes, dataPtr, 0, NULL, NULL); assert(err == CL_SUCCESS); } void OpenCLBuffer::copyFrom(OpenCLBuffer &srcBuffer, int srcOffsetBytes, int dstOffsetBytes, int numberOfBytes) { cl_int err = clEnqueueCopyBuffer(pOpenCL->getQueue(), srcBuffer.getCLMem(), clMemObject, srcOffsetBytes, dstOffsetBytes, numberOfBytes, 0, NULL, NULL); assert(err == CL_SUCCESS); } void OpenCLBuffer::init() { memoryObjectInit(); } }
38.765766
153
0.704625
[ "object" ]
b9afeb5f32eb22dc224d3be793708d06faa8bef4
4,837
cpp
C++
m2.cpp
StetsonMathCS/deadline
4dbf900f26780f2d37256666790065a3a7454876
[ "MIT" ]
null
null
null
m2.cpp
StetsonMathCS/deadline
4dbf900f26780f2d37256666790065a3a7454876
[ "MIT" ]
null
null
null
m2.cpp
StetsonMathCS/deadline
4dbf900f26780f2d37256666790065a3a7454876
[ "MIT" ]
1
2020-04-24T08:12:19.000Z
2020-04-24T08:12:19.000Z
#include <iostream> #include <vector> #include <map> #include <string> #include <algorithm> using namespace std; vector < map<string, string> > myPersonal; vector < map<string, string> > myClass; vector < map<string, string> > myPersonalHidden; vector < map<string, string> > myClassHidden; map<string, string> myMapPersonal; map<string, string> myMapClass; map<string, string> myMapPersonalHidden; map<string, string> myMapClassHidden; void addDeadline(string list, string name, string date) { map<string, string>::iterator it; vector <map <string, string> >::iterator it_out; if(list == "Class") { myMapClass.insert(make_pair(name, date)); myClass.push_back(myMapClass); for(it = myMapClass.begin(); it != myMapClass.end(); it++) { cout << it->first << " ---> " << it->second << endl; // this next line was to test if the info was being stored right cout << myClass.at(0)[it->first] << endl; } } else if(list == "Personal") { myMapPersonal.insert(make_pair(name, date)); myPersonal.push_back(myMapPersonal); for(it = myMapPersonal.begin(); it != myMapPersonal.end(); it++) { cout << it->first << " ---> " << it->second << endl; } } else if(list == "Personal Hidden") { myMapPersonalHidden.insert(make_pair(name, date)); myPersonalHidden.push_back(myMapPersonalHidden); for(it = myMapPersonalHidden.begin(); it != myMapPersonalHidden.end(); it++) { //cout << it->first << " ---> " << it->second << endl; } } else { if(list == "Class Hidden") { myMapClassHidden.insert(make_pair(name, date)); myClassHidden.push_back(myMapClassHidden); for(it = myMapClassHidden.begin(); it != myMapClassHidden.end(); it++) { //cout << it->first << " ---> " << it->second << endl; } } } } void removeDeadline(string list, string target) { map<string, string>::iterator it = myMapClass.find(target); vector <map <string, string> >::iterator it_out; if(list == "Class") { for(it_out = myClass.begin(); it_out != myClass.end(); it_out++) { for(it = myMapClass.begin(); it != myMapClass.end(); it++) { myMapClass.erase(it); if(it_out == target) { myClass.erase(it_out); } //myMapClass.clear(); //cout << it->first << " ---> " << it->second << endl; cout << myMapClass.size() << endl; //myClass.clear(); //cout << it->first << " ---> " << it->second << endl; cout << myClass.size() << endl; break; } break; } } else if(list == "Personal") { for(it_out = myPersonal.begin(); it_out != myPersonal.end(); it_out++) { for(it = myMapPersonal.begin(); it != myMapPersonal.end(); it++) { myMapPersonal.erase(it); myPersonal.erase(it_out); //myMapClass.clear(); //cout << it->first << " ---> " << it->second << endl; cout << myMapPersonal.size() << endl; //myClass.clear(); //cout << it->first << " ---> " << it->second << endl; cout << myPersonal.size() << endl; break; } break; } } else if(list == "Personal Hidden") { for(it_out = myPersonalHidden.begin(); it_out != myPersonalHidden.end(); it_out++) { for(it = myMapPersonalHidden.begin(); it != myMapPersonalHidden.end(); it++) { myMapPersonalHidden.erase(it); myPersonalHidden.erase(it_out); //myMapClass.clear(); //cout << it->first << " ---> " << it->second << endl; cout << myMapPersonalHidden.size() << endl; //myClass.clear(); //cout << it->first << " ---> " << it->second << endl; cout << myPersonalHidden.size() << endl; break; } break; } } else { if(list == "Class Hidden"){ for(it_out = myPersonal.begin(); it_out != myPersonal.end(); it_out++) { for(it = myMapPersonal.begin(); it != myMapPersonal.end(); it++) { myMapPersonal.erase(it); myPersonal.erase(it_out); //myMapClass.clear(); //cout << it->first << " ---> " << it->second << endl; cout << myMapPersonal.size() << endl; //myClass.clear(); //cout << it->first << " ---> " << it->second << endl; cout << myPersonal.size() << endl; break; } break; } } } } void updateDeadline(string name, string date, string update) { map<string, string>::iterator it; vector <map <string, string> >::iterator it_out; } int main() { addDeadline("Class", "CHEM EXAM", "2020-04-30"); addDeadline("Personal", "Cook dinner", "2020-05-01" ); addDeadline("Personal Hidden", "Gym 6:30pm", "2020-05-01"); addDeadline("Class Hidden", "Review C++ syntax", "2020-05-09"); removeDeadline("Class", "CHEM EXAM"); removeDeadline("Personal Hidden", "Gym 6:30pm"); return 0; }
25.457895
86
0.573703
[ "vector" ]
b9b16fc6bf211b8692b337b4730636dfdbd3b236
1,851
cpp
C++
examples/inverse-kinematics.cpp
thanhndv212/pinocchio
3b4d272bf4e8a231954b71201ee7e0963c944aef
[ "BSD-2-Clause-FreeBSD" ]
716
2015-03-30T16:26:45.000Z
2022-03-30T12:26:58.000Z
examples/inverse-kinematics.cpp
thanhndv212/pinocchio
3b4d272bf4e8a231954b71201ee7e0963c944aef
[ "BSD-2-Clause-FreeBSD" ]
1,130
2015-02-21T17:30:44.000Z
2022-03-30T09:06:22.000Z
examples/inverse-kinematics.cpp
thanhndv212/pinocchio
3b4d272bf4e8a231954b71201ee7e0963c944aef
[ "BSD-2-Clause-FreeBSD" ]
239
2015-02-05T14:15:14.000Z
2022-03-14T23:51:47.000Z
#include "pinocchio/parsers/sample-models.hpp" #include "pinocchio/spatial/explog.hpp" #include "pinocchio/algorithm/kinematics.hpp" #include "pinocchio/algorithm/jacobian.hpp" #include "pinocchio/algorithm/joint-configuration.hpp" int main(int /* argc */, char ** /* argv */) { pinocchio::Model model; pinocchio::buildModels::manipulator(model); pinocchio::Data data(model); const int JOINT_ID = 6; const pinocchio::SE3 oMdes(Eigen::Matrix3d::Identity(), Eigen::Vector3d(1., 0., 1.)); Eigen::VectorXd q = pinocchio::neutral(model); const double eps = 1e-4; const int IT_MAX = 1000; const double DT = 1e-1; const double damp = 1e-6; pinocchio::Data::Matrix6x J(6,model.nv); J.setZero(); bool success = false; typedef Eigen::Matrix<double, 6, 1> Vector6d; Vector6d err; Eigen::VectorXd v(model.nv); for (int i=0;;i++) { pinocchio::forwardKinematics(model,data,q); const pinocchio::SE3 dMi = oMdes.actInv(data.oMi[JOINT_ID]); err = pinocchio::log6(dMi).toVector(); if(err.norm() < eps) { success = true; break; } if (i >= IT_MAX) { success = false; break; } pinocchio::computeJointJacobian(model,data,q,JOINT_ID,J); pinocchio::Data::Matrix6 JJt; JJt.noalias() = J * J.transpose(); JJt.diagonal().array() += damp; v.noalias() = - J.transpose() * JJt.ldlt().solve(err); q = pinocchio::integrate(model,q,v*DT); if(!(i%10)) std::cout << i << ": error = " << err.transpose() << std::endl; } if(success) std::cout << "Convergence achieved!" << std::endl; else std::cout << "\nWarning: the iterative algorithm has not reached convergence to the desired precision" << std::endl; std::cout << "\nresult: " << q.transpose() << std::endl; std::cout << "\nfinal error: " << err.transpose() << std::endl; }
29.854839
120
0.633712
[ "model" ]
b9b186941d7f5ab4425caeeb5e92b7a8f747472e
1,881
cpp
C++
src/swagger/v1/model/BlockFile.cpp
gchagnotSpt/openperf
0ae14cb7a685b1b059f707379773fb3bcb421d40
[ "Apache-2.0" ]
20
2019-12-04T01:28:52.000Z
2022-03-17T14:09:34.000Z
src/swagger/v1/model/BlockFile.cpp
gchagnotSpt/openperf
0ae14cb7a685b1b059f707379773fb3bcb421d40
[ "Apache-2.0" ]
115
2020-02-04T21:29:54.000Z
2022-02-17T13:33:51.000Z
src/swagger/v1/model/BlockFile.cpp
gchagnotSpt/openperf
0ae14cb7a685b1b059f707379773fb3bcb421d40
[ "Apache-2.0" ]
16
2019-12-03T16:41:18.000Z
2021-11-06T04:44:11.000Z
/** * OpenPerf API * REST API interface for OpenPerf * * OpenAPI spec version: 1 * Contact: support@spirent.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ #include "BlockFile.h" namespace swagger { namespace v1 { namespace model { BlockFile::BlockFile() { m_Id = ""; m_Size = 0L; m_Init_percent_complete = 0; m_Path = ""; m_State = ""; } BlockFile::~BlockFile() { } void BlockFile::validate() { // TODO: implement validation } nlohmann::json BlockFile::toJson() const { nlohmann::json val = nlohmann::json::object(); val["id"] = ModelBase::toJson(m_Id); val["size"] = m_Size; val["init_percent_complete"] = m_Init_percent_complete; val["path"] = ModelBase::toJson(m_Path); val["state"] = ModelBase::toJson(m_State); return val; } void BlockFile::fromJson(nlohmann::json& val) { setId(val.at("id")); setSize(val.at("size")); setInitPercentComplete(val.at("init_percent_complete")); setPath(val.at("path")); setState(val.at("state")); } std::string BlockFile::getId() const { return m_Id; } void BlockFile::setId(std::string value) { m_Id = value; } int64_t BlockFile::getSize() const { return m_Size; } void BlockFile::setSize(int64_t value) { m_Size = value; } int32_t BlockFile::getInitPercentComplete() const { return m_Init_percent_complete; } void BlockFile::setInitPercentComplete(int32_t value) { m_Init_percent_complete = value; } std::string BlockFile::getPath() const { return m_Path; } void BlockFile::setPath(std::string value) { m_Path = value; } std::string BlockFile::getState() const { return m_State; } void BlockFile::setState(std::string value) { m_State = value; } } } }
16.5
75
0.660819
[ "object", "model" ]
b9b3e10d1c27837c901fb25feec6d17bdd295054
37,597
cpp
C++
samples/hellovr_vulkan/refactor_hellovr_vulkan.cpp
marijnfs/openvr
0cb1d00d2e034fcfdfea289ecc4dcd033c6de882
[ "BSD-3-Clause" ]
null
null
null
samples/hellovr_vulkan/refactor_hellovr_vulkan.cpp
marijnfs/openvr
0cb1d00d2e034fcfdfea289ecc4dcd033c6de882
[ "BSD-3-Clause" ]
null
null
null
samples/hellovr_vulkan/refactor_hellovr_vulkan.cpp
marijnfs/openvr
0cb1d00d2e034fcfdfea289ecc4dcd033c6de882
[ "BSD-3-Clause" ]
null
null
null
//========= Copyright Valve Corporation ============// #include <string> #include <cstdlib> #include <inttypes.h> #include <openvr.h> #include <deque> #include <iostream> #include <fstream> #include <algorithm> #include "shared/lodepng.h" #include "shared/Matrices.h" #include "shared/pathtools.h" #include "img.h" #include "util.h" #include "utilvr.h" #include "global.h" #include "vulkansystem.h" #include "vrsystem.h" #include "windowsystem.h" #include "flywheel.h" #include "learningsystem.h" #include "volumenetwork.h" #include "network.h" #include "trainer.h" using namespace std; enum Orientation { Horizontal = 0, Vertical = 1, Laying = 2 }; struct ExperimentStep { Orientation orientation = Horizontal; float xdir = 0; float ydir = 0; float zdir = 0; int n_clicks = 0; float long_side = 0; float short_side = 0; ExperimentStep(){} ExperimentStep(Orientation o, float xdir_, float ydir_, float zdir_, int n_clicks_, float long_side_, float short_side_) : orientation(o), xdir(xdir_), ydir(ydir_), zdir(zdir_), n_clicks(n_clicks_), long_side(long_side_), short_side(short_side_) {} }; struct FittsWorld { Scene &scene; int click = 0; int step = 0; int choice = 0; vector<ExperimentStep> steps; FittsWorld(Scene &scene_) : scene(scene_) { srand(123123); init_experiments(); init(); } void init_experiments() { //ExperimentStep(Orientation o, float xdir_, float ydir_, float zdir_, int n_clicks_, float long_side_, float short_side_) : vector<float> multipliers = {1.0, 2.0, 4.0}; int n_clicks(10); float long_side(.2); float short_side(.01); float dist(.02); for (auto m : multipliers) for (auto m2 : multipliers) steps.push_back(ExperimentStep(Vertical, dist * m + short_side * m2, 0, 0, n_clicks, long_side, short_side * m2)); for (auto m : multipliers) for (auto m2 : multipliers) steps.push_back(ExperimentStep(Vertical, 0., 0, dist * m + short_side * m2, n_clicks, long_side, short_side * m2)); for (auto m : multipliers) for (auto m2 : multipliers) steps.push_back(ExperimentStep(Vertical, dist * m + short_side * m2, 0, dist * m + short_side * m2, n_clicks, long_side, short_side * m2)); for (auto m : multipliers) for (auto m2 : multipliers) steps.push_back(ExperimentStep(Vertical, dist * m + short_side * m2, 0, -dist * m - short_side * m2, n_clicks, long_side, short_side * m2)); ////Horizontal for (auto m : multipliers) for (auto m2 : multipliers) steps.push_back(ExperimentStep(Horizontal, 0, dist * m + short_side * m2, 0, n_clicks, long_side, short_side * m2)); for (auto m : multipliers) for (auto m2 : multipliers) steps.push_back(ExperimentStep(Horizontal, 0., 0, dist * m + short_side * m2, n_clicks, long_side, short_side * m2)); for (auto m : multipliers) for (auto m2 : multipliers) steps.push_back(ExperimentStep(Horizontal, 0, dist * m + short_side * m2, dist * m + short_side * m2, n_clicks, long_side, short_side * m2)); for (auto m : multipliers) for (auto m2 : multipliers) steps.push_back(ExperimentStep(Horizontal, 0, dist * m + short_side * m2, -dist * m - short_side * m2, n_clicks, long_side, short_side * m2)); //Laying for (auto m : multipliers) for (auto m2 : multipliers) steps.push_back(ExperimentStep(Laying, dist * m + short_side * m2, 0, 0, n_clicks, long_side, short_side * m2)); for (auto m : multipliers) for (auto m2 : multipliers) steps.push_back(ExperimentStep(Laying, 0., dist * m + short_side * m2, 0, n_clicks, long_side, short_side * m2)); for (auto m : multipliers) for (auto m2 : multipliers) steps.push_back(ExperimentStep(Laying, dist * m + short_side * m2, dist * m + short_side * m2, 0, n_clicks, long_side, short_side * m2)); for (auto m : multipliers) for (auto m2 : multipliers) steps.push_back(ExperimentStep(Laying, dist * m + short_side * m2, -dist * m - short_side * m2, 0, n_clicks, long_side, short_side * m2)); random_shuffle(steps.begin(), steps.end()); steps.resize(steps.size() / 2);///TODO } void init() { cout << "Fitts World INIT" << endl; //scene.add_canvas("test"); scene.add_hmd(); scene.add_object("controller", new Controller(true)); //scene.set_pos("test", Pos(1, 1, 1)); scene.add_variable("step", new FreeVariable()); scene.add_variable("click", new FreeVariable()); scene.add_variable("orientation", new FreeVariable()); scene.add_variable("xdir", new FreeVariable()); scene.add_variable("ydir", new FreeVariable()); scene.add_variable("zdir", new FreeVariable()); scene.add_variable("long_side", new FreeVariable()); scene.add_variable("short_side", new FreeVariable()); scene.add_variable("choice", new FreeVariable()); scene.add_variable("start", new MarkVariable()); scene.add_variable("end", new MarkVariable()); scene.register_function("on_in_box", std::bind(&FittsWorld::on_in_box, *this)); scene.register_function("on_start", std::bind(&FittsWorld::on_start, *this)); scene.add_trigger(new ClickTrigger(scene("controller")), "on_start"); scene.add_box("startbox"); scene.set_pos("startbox", Pos(0, .9, -.05)); scene.find<Box>("startbox").set_dim(.05, .05, .05); scene.find<Box>("startbox").set_texture("white-checker.png"); cout << "Fitts World Done INIT" << endl; } void on_in_box() { //cout << "ON IN BOX" << endl; if (scene.find<Controller>("controller").clicked == true) { scene.clear_scene(); scene.set_reward(1); scene.add_trigger(new NextTrigger(), "on_start"); scene.variable<MarkVariable>("end").set_value(1); //scene.end_recording(); //scene.clear_objects(); //scene.clear_triggers(); //scene.add_trigger(new ClickTrigger(), "on_start"); } } void on_start() { click++; if (click >= steps[step].n_clicks) { step++; cout << step << "/" << steps.size() << endl; click = 0; } if (step >= steps.size()) { scene.stop = true; return; } ExperimentStep &cur_step(steps[step]); int new_choice = rand() % 3; while (new_choice == choice) new_choice = rand() % 3; choice = new_choice; //store experiment vars; scene.variable<FreeVariable>("step").set_value(step); scene.variable<FreeVariable>("click").set_value(click); scene.variable<FreeVariable>("orientation").set_value(cur_step.orientation); scene.variable<FreeVariable>("long_side").set_value(cur_step.long_side); scene.variable<FreeVariable>("short_side").set_value(cur_step.short_side); scene.variable<FreeVariable>("xdir").set_value(cur_step.xdir); scene.variable<FreeVariable>("ydir").set_value(cur_step.ydir); scene.variable<FreeVariable>("zdir").set_value(cur_step.zdir); scene.variable<FreeVariable>("choice").set_value(choice); scene.variable<MarkVariable>("start").set_value(1); //scene.variable<FreeVariable>("start").set_value(1); scene.set_reward(0); scene.clear_objects(); scene.clear_triggers(); vector<string> boxes = {"box1", "box2", "box3"}; float long_side(cur_step.long_side), short_side(cur_step.short_side); float x(0); float y(.9); float z(-.05); float box_width(cur_step.orientation == Horizontal ? long_side : short_side); float box_height(cur_step.orientation == Vertical ? long_side : short_side); float box_depth(cur_step.orientation == Laying ? long_side : short_side); scene.add_box("box1"); scene.set_pos("box1", Pos(x - cur_step.xdir, y - cur_step.ydir, z - cur_step.zdir)); scene.find<Box>("box1").set_dim(box_width, box_height, box_depth); scene.find<Box>("box1").set_texture("white-checker.png"); scene.add_box("box2"); scene.set_pos("box2", Pos(x, y, z)); scene.find<Box>("box2").set_dim(box_width, box_height, box_depth); scene.find<Box>("box2").set_texture("white-checker.png"); scene.add_box("box3"); scene.set_pos("box3", Pos(x + cur_step.xdir, y + cur_step.ydir, z + cur_step.zdir)); scene.find<Box>("box3").set_dim(box_width, box_height, box_depth); scene.find<Box>("box3").set_texture("white-checker.png"); scene.find<Box>(boxes[choice]).set_texture("blue-checker.png"); scene.add_trigger(new InBoxTrigger(scene(boxes[choice]), scene("controller")), "on_in_box"); scene.set_reward(0); scene.start_recording(); } }; int record(string filename) { if (exists(filename)) throw StringException("file already exists"); auto &ws = Global::ws(); auto &vr = Global::vr(); auto &vk = Global::vk(); vr.setup(); ws.setup(); vk.setup(); //preloading images ImageFlywheel::preload(); auto &scene = Global::scene(); //FittsWorld world(scene); Script world_script; world_script.run("fittsworld.lua"); vk.end_submit_cmd(); Timer a_timer(1./90); uint i(0); Recording recording; while (!scene.stop) { //cout << i << endl; vr.update_track_pose(); scene.step(); scene.snap(&recording); vr.render(scene); vr.wait_frame(); //cout << "elapsed: " << a_timer.elapsed() << endl; //if (a_timer.elapsed() > 60.) { // recording.save(filename, scene); // a_timer.start(); // } //vr.request_poses(); //a_timer.wait(); } cout << "writing: " << endl; recording.save(filename, scene); cout << "done: " << endl; recording.release(); Global::shutdown(); } int test() { auto img_data_vec = load_vec<float>("/home/marijnfs/data/allimg.data"); auto act_data_vec = load_vec<float>("/home/marijnfs/data/allact.data"); auto obs_data_vec = load_vec<float>("/home/marijnfs/data/allobs.data"); /* auto img_data_vec2 = img_data_vec; for (int n(0); n < 50; ++n) for (int c(0); c < 6; ++c) for (int x = 0; x < 1680 * 1512; ++x) img_data_vec[(n * 6 + c) * 1680 * 1512 + x] = img_data_vec2[n * 1680 * 1512 * 6 + x * 6 + c]; */ int act_dim = 13; int obs_dim = 6; int aggr_dim = 32; int vis_dim = 16; Volume img_data(VolumeShape{50, 6, VIVE_WIDTH, VIVE_HEIGHT}); Volume act_data(VolumeShape{50, act_dim, 1, 1}); Volume obs_data(VolumeShape{50, obs_dim, 1, 1}); cout << img_data_vec.size() << " " << img_data.size() << endl; cout << img_data_vec[0 * 6 * 1680 * 1512 + 450] << " " << img_data_vec[10 * 6 * 1680 * 1512 + 450] << " " << img_data_vec[20 * 6 * 1680 * 1512 + 450] << " " << endl; img_data.from_vector(img_data_vec); act_data.from_vector(act_data_vec); obs_data.from_vector(obs_data_vec); VolumeNetwork vis_net(VolumeShape{50, 6, VIVE_WIDTH, VIVE_HEIGHT}); auto base_pool = new PoolingOperation<F>(4, 4); cout << vis_net.output_shape().c << endl; auto conv1 = new ConvolutionOperation<F>(vis_net.output_shape().c, 8, 5, 5); cout << "bla" << endl; auto pool1 = new PoolingOperation<F>(4, 4); vis_net.add_slicewise(base_pool); vis_net.add_slicewise(conv1); //vis_net.add_tanh(); cout << vis_net.output_shape() << endl; vis_net.add_slicewise(pool1); cout << vis_net.output_shape().tensor_shape() << endl; auto squash = new SquashOperation<F>(vis_net.output_shape().tensor_shape(), vis_dim); vis_net.add_slicewise(squash); cout << "added slicewise" << endl; //vis_net.add_tanh(); vis_net.finish(); vis_net.init_normal(.0, .1); VolumeNetwork aggr_net(VolumeShape{50, 16, 1, 1}); aggr_net.add_univlstm(1, 1, act_dim); aggr_net.finish(); aggr_net.init_normal(.0, .1); cout << vis_net.volumes.size() << endl; float start_lr = .01; float end_lr = .00001; float half_time = 200; float clip_val = .1; float avg_set_time = 50; Trainer vis_trainer(vis_net.param_vec.n, start_lr, end_lr, half_time, clip_val, avg_set_time); while (true) { vis_net.input().from_volume(img_data); vis_net.forward(); //vis_net.volumes[2]->x.draw_slice("test1.png", 3, 2); //vis_net.volumes[2]->x.draw_slice("test2.png", 40, 2); copy_gpu_to_gpu(vis_net.output().data(), aggr_net.input().data(), vis_net.output().size()); aggr_net.forward(); float loss = aggr_net.calculate_loss(act_data); aggr_net.backward(); copy_gpu_to_gpu(aggr_net.input_grad().data(), vis_net.output_grad().data(), aggr_net.input_grad().size()); vis_net.backward(); /* auto v1 = aggr_net.output().to_vector(); auto v2 = act_data.to_vector(); for (int i(0); i < v1.size(); ++i) { if ( i % act_dim == 0) cout << endl; cout << v1[i] << ":" << v2[i] << " "; } */ //return -1; cout << endl; cout << "loss: " << loss << endl; aggr_net.grad_vec *= 1.0 / 50000; aggr_net.param_vec += aggr_net.grad_vec; vis_net.grad_vec *= 1.0 / 100000; vis_net.param_vec += vis_net.grad_vec; //vis_trainer.update(&vis_net.param_vec, vis_net.grad_vec); } } int replay(string filename) { if (!exists(filename)) throw StringException("file doesnt exist"); auto &ws = Global::ws(); auto &vr = Global::vr(); auto &vk = Global::vk(); vr.setup(); ws.setup(); vk.setup(); //preloading images ImageFlywheel::preload(); auto &scene = Global::scene(); //FittsWorld world(scene); Script world_script; world_script.run("fittsworld.lua"); vk.end_submit_cmd(); Pose cur_pose, last_pose; Timer a_timer(1./90); uint i(0); Recording recording; recording.load(filename, &scene); cout << "recording size: " << recording.size() << endl; /* for (auto o : scene.objects) cout << o.first << " " << scene.names[o.second->nameid] << endl; for (auto v : scene.variables) cout << v.first << " " << v.second->val << " " << scene.names[v.second->nameid] << endl; for (auto t : scene.triggers) cout << scene.names[t->function_nameid] << endl; */ int T(50); std::vector<float> nimg(3 * 2 * VIVE_WIDTH * VIVE_HEIGHT); std::vector<float> all_img(nimg.size() * T); std::vector<float> all_action((3 + 4 + 4 + 1 + 1) * T); std::vector<float> all_obs(6 * T); int t(0); //for (int i(1000); i < 1000+T; ++i, ++t) { for (int i(3000); i < recording.size(); ++i, ++t) { recording.load_scene(i, &scene); vr.hmd_pose = Matrix4(scene.find<HMD>("hmd").to_mat4()); cout << "scene " << i << " items: " << scene.objects.size() << endl; bool headless(true); // ////vr.render(scene, &img); ////vr.render(scene, headless); vr.render(scene, false); vr.wait_frame(); //std::vector<float> nimg(img.begin(), img.end()); //normalize_mt(&img); //cout << nimg.size() << endl; //write_img1c("bla2.png", VIVE_WIDTH, VIVE_HEIGHT, &nimg[0]); //copy(nimg.begin(), nimg.end(), all_img.begin() + nimg.size() * t); last_pose = cur_pose; cur_pose.from_scene(scene); if (t == 0) last_pose = cur_pose; Action action(last_pose, cur_pose); auto a_vec = action.to_vector(); auto o_vec = cur_pose.to_obs_vector(); //copy(a_vec.begin(), a_vec.end(), all_action.begin() + 13*t); //copy(o_vec.begin(), o_vec.end(), all_obs.begin() + 6*t); cout << a_vec << endl << o_vec << endl; } ofstream img_out("allimg.data", ios::binary); size_t s = all_img.size(); img_out.write((char*)&s, sizeof(s)); img_out.write((char*)&all_img[0], sizeof(float) * all_img.size()); ofstream act_out("allact.data", ios::binary); s = all_action.size(); act_out.write((char*)&s, sizeof(s)); act_out.write((char*)&all_action[0], sizeof(float) * all_action.size()); ofstream obs_out("allobs.data", ios::binary); s = all_obs.size(); obs_out.write((char*)&s, sizeof(s)); obs_out.write((char*)&all_obs[0], sizeof(float) * all_obs.size()); /* while (i < recording.size()) { //cout << i << endl; //vr.update_track_pose(); //scene.step(); //scene.snap(&recording); recording.load_scene(i, &scene); vr.hmd_pose = Matrix4(scene.find<HMD>("hmd").to_mat4()); cout << "scene " << i << " items: " << scene.objects.size() << endl; vr.render(scene); vr.wait_frame(); ++i; //vr.request_poses(); //a_timer.wait(); }*/ Global::shutdown(); } void test_setup_networks(VolumeNetwork &vis_net, VolumeNetwork &act_net, int vis_dim, int act_dim) { auto base_pool = new PoolingOperation<F>(2, 2, CUDNN_POOLING_AVERAGE_COUNT_EXCLUDE_PADDING); auto conv1 = new ConvolutionOperation<F>(vis_net.output_shape().c, 8, 5, 5); auto pool1 = new PoolingOperation<F>(4, 4, CUDNN_POOLING_AVERAGE_COUNT_EXCLUDE_PADDING); vis_net.add_slicewise(base_pool); vis_net.add_slicewise(conv1); vis_net.add_tanh(); vis_net.add_slicewise(pool1); vis_net.add_tanh(); auto conv2 = new ConvolutionOperation<F>(vis_net.output_shape().c, 16, 5, 5); auto pool2 = new PoolingOperation<F>(4, 4); vis_net.add_slicewise(conv2); vis_net.add_slicewise(pool2); vis_net.add_tanh(); auto conv3 = new ConvolutionOperation<F>(vis_net.output_shape().c, 16, 5, 5); vis_net.add_slicewise(conv3); vis_net.add_tanh(); vis_net.add_univlstm(5, 5, 16); //auto squash = new SquashOperation<F>(vis_net.output_shape().tensor_shape(), vis_dim); auto squash = new SquashOperation<F>(vis_net.output_shape().tensor_shape(), vis_dim); vis_net.add_slicewise(squash); vis_net.add_tanh(); vis_net.add_fc(vis_dim); //output should be {z, c, 1, 1} vis_net.finish(); act_net.add_fc(16); act_net.add_tanh(); act_net.add_univlstm(1, 1, 32); act_net.add_fc(act_dim); act_net.finish(); } void setup_networks(VolumeNetwork &vis_net, VolumeNetwork &aggr_net, Network<F> &actor_net, Network<F> &value_net, VolumeNetwork &q_net, int act_dim, int obs_dim, int vis_dim, int aggr_dim) { auto base_pool = new PoolingOperation<F>(2, 2, CUDNN_POOLING_AVERAGE_COUNT_EXCLUDE_PADDING); auto conv1 = new ConvolutionOperation<F>(vis_net.output_shape().c, 8, 5, 5); auto pool1 = new PoolingOperation<F>(4, 4, CUDNN_POOLING_AVERAGE_COUNT_EXCLUDE_PADDING); vis_net.add_slicewise(base_pool); vis_net.add_slicewise(conv1); vis_net.add_tanh(); vis_net.add_slicewise(pool1); vis_net.add_tanh(); auto conv2 = new ConvolutionOperation<F>(vis_net.output_shape().c, 16, 5, 5); auto pool2 = new PoolingOperation<F>(4, 4); vis_net.add_slicewise(conv2); vis_net.add_slicewise(pool2); //vis_net.add_univlstm(7, 7, 16); //auto squash = new SquashOperation<F>(vis_net.output_shape().tensor_shape(), vis_dim); auto squash = new SquashOperation<F>(vis_net.output_shape().tensor_shape(), vis_dim); vis_net.add_slicewise(squash); vis_net.add_tanh(); //output should be {z, c, 1, 1} vis_net.finish(); aggr_net.add_univlstm(1, 1, 32); aggr_net.add_univlstm(1, 1, aggr_dim); aggr_net.finish(); actor_net.add_conv(64, 1, 1); actor_net.add_relu(); actor_net.add_conv(64, 1, 1); actor_net.add_relu(); actor_net.add_conv(act_dim, 1, 1); actor_net.finish(); value_net.add_conv(64, 1, 1); value_net.add_relu(); value_net.add_conv(64, 1, 1); value_net.add_relu(); value_net.add_conv(1, 1, 1); value_net.finish(); q_net.add_univlstm(1, 1, 32); q_net.add_univlstm(1, 1, 32); q_net.add_fc(1); q_net.finish(); } void print_split(vector<float> &v, int dim) { int d(0); for (int i(0); i < v.size(); ++i, ++d) { if (d == dim) { cout << endl; d = 0; } cout << v[i] << " " ; } } int learn(string filename) { Global::inst().HEADLESS = true; if (!exists(filename)) throw StringException("file doesnt exist"); Handler::cudnn(); Handler::set_device(0); //auto &ws = Global::ws(); auto &vr = Global::vr(); auto &vk = Global::vk(); vr.setup(); //ws.setup(); vk.setup(); //preloading images ImageFlywheel::preload(); auto &scene = Global::scene(); //FittsWorld world(scene); Script world_script; world_script.run("fittsworld.lua"); vk.end_submit_cmd(); Timer a_timer(1./90); Recording recording; recording.load(filename, &scene); cout << "recording size: " << recording.size() << endl; int N = 64; int c = 3 * 2; //stereo rgb int h = 32; int act_dim = 13; int obs_dim = 6; int vis_dim = 8; int aggr_dim = 32; int width = VIVE_WIDTH; int height = VIVE_HEIGHT; VolumeShape img_input{N, c, width, height}; //VolumeShape network_output{N, h, 1, 1}; //Visual processing network, most cpu intensive bool first_grad = false; VolumeNetwork vis_net(img_input, first_grad); //Aggregation Network combining output of visual processing network and state vector VolumeShape aggr_input{N, vis_dim + obs_dim, 1, 1}; //VolumeShape aggr_input{N, vis_dim, 1, 1}; VolumeNetwork aggr_net(aggr_input); //TensorShape actor_in{N, aggr_dim, 1, 1}; TensorShape actor_in{N, vis_dim, 1, 1}; Network<F> actor_net(actor_in); TensorShape value_in{N, aggr_dim, 1, 1}; Network<F> value_net(actor_in); VolumeShape q_in{N, aggr_dim + act_dim, 1, 1}; //qnet, could be also advantage VolumeNetwork q_net(q_in); test_setup_networks(vis_net, aggr_net, vis_dim, act_dim); //setup_networks(vis_net, aggr_net, actor_net, value_net, q_net, act_dim, obs_dim, vis_dim, aggr_dim); //initialisation float stddev(.3); vis_net.init_uniform(stddev); aggr_net.init_uniform(stddev); ///q_net.init_uniform(std); // actor_net.init_uniform(std); //value_net.init_uniform(std); float vis_start_lr = .03; float aggr_start_lr = .03; float end_lr = .00001; float half_time = 200; float clip_val = .1; float avg_set_time = 50; Trainer vis_trainer(vis_net.param_vec.n, vis_start_lr, end_lr, half_time, clip_val, avg_set_time); Trainer aggr_trainer(aggr_net.param_vec.n, aggr_start_lr, end_lr, half_time, clip_val, avg_set_time); //Trainer actor_trainer(actor_net.param_vec.n, .001, .00001, 200); Volume action_targets_tensor(VolumeShape{N, act_dim, 1, 1}); //Tensor<F> action_targets_tensor(N, act_dim, 1, 1); vector<float> action_targets(N * act_dim); //load if applicable if (exists("vis.net")) vis_net.load("vis.net"); if (exists("aggr.net")) aggr_net.load("aggr.net"); if (exists("q.net")) q_net.load("q.net"); if (exists("actor.net")) actor_net.load("actor.net"); if (exists("value.net")) value_net.load("value.net"); int epoch(0); while (true) { int b = rand() % (recording.size() - N + 1); int e = b + N; Pose cur_pose, last_pose; //l2 adjustment float l2 = .0005; vis_net.param_vec *= 1.0 - l2; aggr_net.param_vec *= 1.0 - l2; //First setup all inputs for an episode int t(0); std::vector<float> nimg(3 * 2 * VIVE_WIDTH * VIVE_HEIGHT); for (int i(b); i < e; ++i, ++t) { recording.load_scene(i, &scene); vr.hmd_pose = Matrix4(scene.find<HMD>("hmd").to_mat4()); cout << "scene " << i << " items: " << scene.objects.size() << endl; bool headless(true); // ////vr.render(scene, &img); ////vr.render(scene, headless); vr.render(scene, true, &nimg); //vr.wait_frame(); //std::vector<float> nimg(img.begin(), img.end()); //normalize_mt(&img); //cout << nimg.size() << endl; //write_img1c("bla2.png", VIVE_WIDTH, VIVE_HEIGHT, &nimg[0]); //write_img1c("bla3.png", VIVE_WIDTH, VIVE_HEIGHT, &nimg[VIVE_WIDTH * VIVE_HEIGHT * 3]); //copy_cpu_to_gpu<float>(&nimg[0], vis_net.input().slice(t), nimg.size()); //cout << nimg << endl; //vis_net.input().draw_slice("bla.png", t, 0); //normalise_fast(vis_net.input().slice(t), nimg.size()); last_pose = cur_pose; cur_pose.from_scene(scene); if (t == 0) last_pose = cur_pose; Action action(last_pose, cur_pose); auto a_vec = action.to_vector(); auto o_vec = cur_pose.to_obs_vector(); //cout << "action: " << a_vec << " " << o_vec << endl; //if (t) //ignore first action copy(a_vec.begin(), a_vec.end(), action_targets.begin() + act_dim * t); copy_cpu_to_gpu(&o_vec[0], aggr_net.input().data(t, 0), o_vec.size()); } action_targets_tensor.from_vector(action_targets); //run visual network auto eval_func = [&]()->float { vis_net.forward(); //debug //cout << "vis output: " << vis_net.output().to_vector() << endl; //aggregator for (int t(0); t < N; ++t) //aggregator already has observation data, we add vis output after that copy_gpu_to_gpu(vis_net.output().data(t), aggr_net.input().data(t, obs_dim), vis_dim); //copy_gpu_to_gpu(vis_net.output().data(), aggr_net.input().data(), vis_net.output().size()); aggr_net.forward(); cout << "aggr output: " << aggr_net.output().to_vector() << endl; //copy aggr to nets //*copy_gpu_to_gpu(aggr_net.output().data(), actor_net.input().data, aggr_net.output().size()); //*copy_gpu_to_gpu(aggr_net.output().data(), value_net.input().data, aggr_net.output().size()); //*actor_net.forward(); //*value_net.forward(); //not for imitation auto pred_actions = aggr_net.output().to_vector(); auto p1 = pred_actions.begin(), p2 = action_targets.begin(); for (int i(0); i < N; ++i) { cout << "actor: "; for (int n(0); n < act_dim; ++n, ++p1, ++p2) cout << *p1 << " " << *p2 << endl; } //copy actions and aggr to q //not for imitation //HERE BE SEGFAULT? /*for (int t(0); t < N - 1; ++t) { copy_gpu_to_gpu(actor_net.output().ptr(t), q_net.input().data(t + 1, 0), act_dim); copy_gpu_to_gpu(aggr_net.output().data(t), q_net.input().data(t, act_dim), aggr_dim); } q_net.forward(); //not for imitation */ //====== Imitation backward: //* actor_net.calculate_loss(action_targets_tensor); //cout << "actor action: " << actor_net.output().to_vector() << endl; auto loss = aggr_net.calculate_loss(action_targets_tensor); cout << "actor loss: " << loss << endl; //cout << "actor loss: " << actor_net.loss() << endl; //* actor_net.backward(); aggr_net.backward(); //cout << aggr_net.param_vec.to_vector() << endl; //cout << aggr_net.grad_vec.to_vector() << endl; //return 1; //copy_gpu_to_gpu(actor_net.input_grad().data(), aggr_net.output_grad().data(), actor_net.input_grad().size()); //copy_gpu_to_gpu(actor_net.input_grad().data(), aggr_net.output_grad().data(), actor_net.input_grad().size()); //aggr_net.backward(); for (int t(0); t < N; ++t) copy_gpu_to_gpu(aggr_net.input_grad().data(t, obs_dim), vis_net.output_grad().data(t), vis_dim); vis_net.backward(); return loss; }; //vis_trainer.update(&vis_net.param_vec, vis_net.grad_vec); //aggr_trainer.update(&aggr_net.param_vec, aggr_net.grad_vec); CudaVec vis_param_back(vis_net.param_vec); CudaVec aggr_param_back(aggr_net.param_vec); for (int n(0); n < 4; ++n) { eval_func(); if (n != 0) { vis_net.param_vec = vis_param_back; aggr_net.param_vec = aggr_param_back; } vis_trainer.update(&vis_net.param_vec, vis_net.grad_vec); aggr_trainer.update(&aggr_net.param_vec, aggr_net.grad_vec); } //eval_func(); //auto &v = dynamic_cast<ConvolutionOperation<F>*>(dynamic_cast<SlicewiseOperation*>(vis_net.operations[3])->op)->filter_bank_grad; //auto &v2 = vis_net.volumes[3]->diff; //auto lstmv = vis_net.volumes[11]->x.to_vector(); //print_split(lstmv, vis_net.shapes[11].w * vis_net.shapes[11].h); cout << "vis:" << endl; auto av = vis_net.output().to_vector(); print_split(av, vis_dim); //cout << "vis net:" << v.to_vector() << endl;//to_vector() << endl; //aggr_net.grad_vec *= 1.0 / 50000; //aggr_net.param_vec += aggr_net.grad_vec; //vis_net.grad_vec *= 1.0 / 50000; //vis_net.param_vec += vis_net.grad_vec; //actor_net.grad_vec *= 1.0 / 50000; //actor_net.param_vec += actor_net.grad_vec; //actor_trainer.update(&actor_net.param_vec, actor_net.grad_vec); //set action targets //run backward //====== Qlearning backward: //run forward //calculate q targets //run backward q -> calculate action update //run backward rest if (epoch % 100 == 0 && epoch > 0) { vis_net.save("vis.net"); aggr_net.save("aggr.net"); //q_net.save("q.net"); //actor_net.save("actor.net"); //value_net.save("value.net"); } ++epoch; } return 1; Global::shutdown(); return 0; } int learn_old(string filename) { Global::inst().INVERT_CORRECTION = true; cerr << "Warning, Invert correction on!" << endl; learn(filename); } int rollout(string filename) { //Global::inst().HEADLESS = true; if (!exists(filename)) throw StringException("file doesnt exist"); Handler::cudnn(); Handler::set_device(0); auto &ws = Global::ws(); auto &vr = Global::vr(); auto &vk = Global::vk(); vr.setup(); ws.setup(); vk.setup(); //preloading images ImageFlywheel::preload(); auto &scene = Global::scene(); Script world_script; world_script.run("fittsworld.lua"); //FittsWorld world(scene); vk.end_submit_cmd(); Timer a_timer(1./90); Recording recording; recording.load(filename, &scene); cout << "recording size: " << recording.size() << endl; int N = 64; int c = 3 * 2; //stereo rgb int h = 32; int act_dim = 13; int obs_dim = 6; int vis_dim = 8; int aggr_dim = 32; int width = VIVE_WIDTH; int height = VIVE_HEIGHT; VolumeShape img_input{N, c, width, height}; //VolumeShape network_output{N, h, 1, 1}; //Visual processing network, most cpu intensive bool first_grad = false; VolumeNetwork vis_net(img_input, first_grad); //Aggregation Network combining output of visual processing network and state vector VolumeShape aggr_input{N, vis_dim + obs_dim, 1, 1}; //VolumeShape aggr_input{N, vis_dim, 1, 1}; VolumeNetwork aggr_net(aggr_input); //TensorShape actor_in{N, aggr_dim, 1, 1}; TensorShape actor_in{N, vis_dim, 1, 1}; Network<F> actor_net(actor_in); TensorShape value_in{N, aggr_dim, 1, 1}; Network<F> value_net(actor_in); VolumeShape q_in{N, aggr_dim + act_dim, 1, 1}; //qnet, could be also advantage VolumeNetwork q_net(q_in); test_setup_networks(vis_net, aggr_net, vis_dim, act_dim); //setup_networks(vis_net, aggr_net, actor_net, value_net, q_net, act_dim, obs_dim, vis_dim, aggr_dim); //initialisation float stddev(.3); //initialisation //load if applicable if (exists("vis.net")) vis_net.load("vis.net"); if (exists("aggr.net")) aggr_net.load("aggr.net"); if (exists("q.net")) q_net.load("q.net"); if (exists("actor.net")) actor_net.load("actor.net"); if (exists("value.net")) value_net.load("value.net"); /* recording.load_scene(1000, &scene); Pose p1(scene); recording.load_scene(1100, &scene); Pose p2(scene); Action a1(p1, p2); auto v = a1.to_vector(); Action a2(v); p1.apply(a2); cout << p1 << endl; cout << p2 << endl; return 1;*/ int epoch(0); while (true) { int b = rand() % (recording.size() - N + 1); int e = b + N; Pose cur_pose, last_pose; //First setup all inputs for an episode int t(0); std::vector<float> nimg(3 * 2 * VIVE_WIDTH * VIVE_HEIGHT); recording.load_scene(b, &scene); for (int i(b); i < e; ++i, ++t) { vr.hmd_pose = Matrix4(scene.find<HMD>("hmd").to_mat4()); cout << "scene " << i << " items: " << scene.objects.size() << endl; //bool headless(true); bool headless(false); ////vr.render(scene, &img); ////vr.render(scene, headless); vr.render(scene, headless, &nimg); //std::vector<float> nimg(img.begin(), img.end()); //normalize_mt(&img); //cout << nimg.size() << endl; //write_img1c("bla2.png", VIVE_WIDTH, VIVE_HEIGHT, &nimg[0]); copy_cpu_to_gpu<float>(&nimg[0], vis_net.input().slice(t), nimg.size()); //vis_net.input().draw_slice("bla.png", t, 0); //normalise_fast(vis_net.input().slice(t), nimg.size()); last_pose = cur_pose; cur_pose.from_scene(scene); if (t == 0) last_pose = cur_pose; //Action action(last_pose, cur_pose); auto o_vec = cur_pose.to_obs_vector(); copy_cpu_to_gpu(&o_vec[0], aggr_net.input().data(t, 0), o_vec.size()); //run visual network vis_net.forward(); //ostringstream oss; //oss << "test-" << t << ".png"; //vis_net.volumes[7]->x.draw_slice(oss.str(), t, 2); copy_gpu_to_gpu(vis_net.output().data(t), aggr_net.input().data(t, obs_dim), vis_dim); aggr_net.forward(); //cout << "agg output: " << aggr_net.output().to_vector() << endl; /* //copy aggr to value and actor nets copy_gpu_to_gpu(aggr_net.output().data(), actor_net.input().data, aggr_net.output().size()); copy_gpu_to_gpu(aggr_net.output().data(), value_net.input().data, aggr_net.output().size()); actor_net.forward(); //value_net.forward(); //not for imitation auto whole_action_vec = actor_net.output().to_vector(); auto action_vec = vector<float>(whole_action_vec.begin() + t * act_dim, whole_action_vec.begin() + (t+1) * act_dim); cout << "act vec: " << action_vec << endl; */ auto whole_action_vec = aggr_net.output().to_vector(); auto action_vec = vector<float>(whole_action_vec.begin() + t * act_dim, whole_action_vec.begin() + (t+1) * act_dim); Action act(action_vec); cout << action_vec << endl; //cout << "act: " << act.armq[0] << " " << act.arm_length << endl; //cout << cur_pose << endl; cur_pose.apply(act); //cout << cur_pose << endl; cur_pose.apply_to_scene(scene); } ++epoch; } Global::shutdown(); return 0; } int rollout_old(string filename) { Global::inst().INVERT_CORRECTION = true; cerr << "Warning, INvert correction on!" << endl; rollout(filename); } int analyse(string filename) { if (!exists(filename)) throw StringException("file doesnt exist"); auto &scene = Global::scene(); Script world_script; world_script.run("fittsworld.lua"); //FittsWorld world(scene); Timer a_timer(1./90); uint i(0); Recording recording; recording.load(filename, &scene); cout << "recording size: " << recording.size() << endl; /* for (auto o : scene.objects) cout << o.first << " " << scene.names[o.second->nameid] << endl; for (auto v : scene.variables) cout << v.first << " " << v.second->val << " " << scene.names[v.second->nameid] << endl; for (auto t : scene.triggers) cout << scene.names[t->function_nameid] << endl; */ int clicked(0); Pos start_pos; int start_frame(0); int start_clicks(0); ofstream datafile(filename + ".data"); datafile << "ORIENTATION WIDTH XDIR YDIR ZDIR STARTX STARTY STARTZ ENDX ENDY ENDZ NFRAMES" << endl; while (i < recording.size()) { //cout << i << endl; //vr.update_track_pose(); //scene.step(); //scene.snap(&recording); recording.load_scene(i, &scene); try { if (scene.find<Controller>("controller").clicked) clicked++; if (scene.variable<MarkVariable>("start").val > 0) { start_frame = i; start_clicks = clicked; start_pos = scene.find<Controller>("controller").p; } if (scene.variable<MarkVariable>("end").val > 0) { Pos cur_pos = scene.find<Controller>("controller").p; datafile << scene.variable<FreeVariable>("orientation").val << " " << scene.variable<FreeVariable>("short_side").val << " " << scene.variable<FreeVariable>("xdir").val << " " << scene.variable<FreeVariable>("ydir").val << " " << scene.variable<FreeVariable>("zdir").val << " " << start_pos.x << " " << start_pos.y << " " << start_pos.z << " " << cur_pos.x << " " << cur_pos.y << " " << cur_pos.z << " " << (i - start_frame) << endl; } } catch(...) {} //cout << "scene " << i << " items: " << scene.objects.size() << endl; ++i; //vr.request_poses(); //a_timer.wait(); } datafile.flush(); cout << "n clicks: " << clicked << endl; Global::shutdown(); } int main(int argc, char **argv) { vector<string> args; for (int i(1); i < argc; ++i) args.push_back(argv[i]); if (args.size() < 2) throw StringException("not enough args, use: record|replay filename"); if (args[0] == "record") return record(args[1]); if (args[0] == "replay") return replay(args[1]); if (args[0] == "analyse") return analyse(args[1]); if (args[0] == "learn") return learn(args[1]); if (args[0] == "learnold") //with invert correction return learn_old(args[1]); if (args[0] == "rollout") return rollout(args[1]); if (args[0] == "rolloutold") //with invert correction return rollout_old(args[1]); throw StringException("Call right arguments"); }
30.641402
191
0.623348
[ "render", "vector" ]
b9b445e3dc712eca730009ee04590ff70a7df061
918
cpp
C++
Online Judges/URI/2854/main.cpp
AnneLivia/URI-Online
02ff972be172a62b8abe25030c3676f6c04efd1b
[ "MIT" ]
64
2019-03-17T08:56:28.000Z
2022-01-14T02:31:21.000Z
Online Judges/URI/2854/main.cpp
AnneLivia/URI-Online
02ff972be172a62b8abe25030c3676f6c04efd1b
[ "MIT" ]
1
2020-12-24T07:16:30.000Z
2021-03-23T20:51:05.000Z
Online Judges/URI/2854/main.cpp
AnneLivia/URI-Online
02ff972be172a62b8abe25030c3676f6c04efd1b
[ "MIT" ]
19
2019-05-25T10:48:16.000Z
2022-01-07T10:07:46.000Z
#include <iostream> #include <vector> #include <map> using namespace std; vector<vector<int> >g; vector<int>vi; void dfs(int v) { vi[v] = true; for (int i = 0; i < (int)g[v].size(); i++) { if(!vi[g[v][i]]) dfs(g[v][i]); } } int main() { int n, m, index = 0, cont = 0; string v, relation, w; map<string,int>names; cin >> n >> m; g.assign(n, vector<int>()); while(m--) { cin >> v >> relation >> w; if(names.find(v) == names.end()) names.insert(make_pair(v, index++)); if(names.find(w) == names.end()) names.insert(make_pair(w, index++)); g[names.at(v)].push_back(names.at(w)); g[names.at(w)].push_back(names.at(v)); } vi.assign(n, 0); for (int i = 0; i < n; i++) { if(!vi[i]) { dfs(i); cont++; } } cout << cont << endl; return 0; }
20.863636
48
0.464052
[ "vector" ]
b9b71c7a3f512cc8628878acfc96617d7da846f2
10,008
cc
C++
syzygy/kasko/minidump_unittest.cc
StanMiller45/syzygy
2320676a260ab3713c6a4b793ebefa2837cb766c
[ "Apache-2.0" ]
1
2019-04-03T13:56:37.000Z
2019-04-03T13:56:37.000Z
syzygy/kasko/minidump_unittest.cc
StanMiller45/syzygy
2320676a260ab3713c6a4b793ebefa2837cb766c
[ "Apache-2.0" ]
null
null
null
syzygy/kasko/minidump_unittest.cc
StanMiller45/syzygy
2320676a260ab3713c6a4b793ebefa2837cb766c
[ "Apache-2.0" ]
1
2020-10-10T16:09:45.000Z
2020-10-10T16:09:45.000Z
// Copyright 2014 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "syzygy/kasko/minidump.h" #include <Windows.h> // NOLINT #include <Dbgeng.h> #include <DbgHelp.h> #include <cstring> #include <vector> #include "base/base_switches.h" #include "base/bind.h" #include "base/command_line.h" #include "base/macros.h" #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/files/memory_mapped_file.h" #include "base/files/scoped_temp_dir.h" #include "base/process/kill.h" #include "base/process/launch.h" #include "base/strings/string16.h" #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" #include "base/test/multiprocess_test.h" #include "gtest/gtest.h" #include "syzygy/kasko/minidump_request.h" #include "syzygy/kasko/testing/minidump_unittest_helpers.h" #include "syzygy/kasko/testing/safe_pipe_reader.h" #include "testing/multiprocess_func_list.h" // http://blogs.msdn.com/oldnewthing/archive/2004/10/25/247180.aspx extern "C" IMAGE_DOS_HEADER __ImageBase; namespace kasko { namespace { const char kPipeHandleSwitch[] = "pipe-handle"; // Signals an event named by kReadyEventSwitch, then blocks indefinitely. MULTIPROCESS_TEST_MAIN(MinidumpTestBlockingProcess) { // Read the caller-supplied parameters. base::CommandLine* cmd_line = base::CommandLine::ForCurrentProcess(); std::string pipe_handle_string = cmd_line->GetSwitchValueASCII(kPipeHandleSwitch); unsigned handle_value = 0; CHECK(base::StringToUint(pipe_handle_string, &handle_value)); base::win::ScopedHandle pipe(reinterpret_cast<HANDLE>(handle_value)); DWORD written = 0; uint32_t image_base = reinterpret_cast<uint32_t>(&__ImageBase); PCHECK(WriteFile(pipe.Get(), &image_base, sizeof(image_base), &written, nullptr)); CHECK_EQ(sizeof(void*), written); pipe.Close(); ::Sleep(INFINITE); return 0; } const char kGlobalString[] = "a global string"; const char kCustomStreamContents[] = "hello world"; uint32_t kCustomStreamType = LastReservedStream + 2468; void ValidateMinidump(IDebugClient4* debug_client, IDebugControl* debug_control, IDebugSymbols* debug_symbols) { ASSERT_HRESULT_SUCCEEDED( debug_symbols->GetModuleByModuleName("kasko_unittests", 0, NULL, NULL)); } } // namespace class MinidumpTest : public ::testing::Test { public: MinidumpTest() {} ~MinidumpTest() override {} // ::testing::Test implementation. virtual void SetUp() override { temp_dir_.CreateUniqueTempDir(); } // Launches a child process, waits until it has loaded, and then invokes // GenerateMinidump for the child. // The contents of |request().memory_ranges| must be within the current image // (kasko_unittests.exe). They will be adjusted so as to read the same offset // (from the image base) in the child process. void CallGenerateMinidump(const base::FilePath& dump_file_path, bool* result) { testing::SafePipeReader pipe_reader; base::CommandLine child_command_line = base::GetMultiProcessTestChildBaseCommandLine(); child_command_line.AppendSwitchASCII(switches::kTestChildProcess, "MinidumpTestBlockingProcess"); child_command_line.AppendSwitchASCII( kPipeHandleSwitch, base::UintToString(reinterpret_cast<unsigned>( pipe_reader.write_handle()))); base::LaunchOptions options; options.inherit_handles = true; base::Process child_process = base::LaunchProcess(child_command_line, options); ASSERT_TRUE(child_process.IsValid()); uint32_t child_image_base = 0; ASSERT_TRUE(pipe_reader.ReadData(base::TimeDelta::FromSeconds(15), sizeof(child_image_base), &child_image_base)); MinidumpRequest adjusted_request = request_; for (auto& range : request_.user_selected_memory_ranges) { range.base_address += child_image_base - reinterpret_cast<uint32_t>(&__ImageBase); } *result = kasko::GenerateMinidump(dump_file_path, base::GetProcId(child_process.Handle()), 0, adjusted_request); ASSERT_TRUE(child_process.Terminate(0, true)); } protected: base::FilePath temp_dir() { return temp_dir_.path(); } MinidumpRequest& request() { return request_; } private: MinidumpRequest request_; base::ScopedTempDir temp_dir_; DISALLOW_COPY_AND_ASSIGN(MinidumpTest); }; TEST_F(MinidumpTest, GenerateAndLoad) { // Generate a minidump for the current process. base::FilePath dump_file_path = temp_dir().Append(L"test.dump"); bool result = false; ASSERT_NO_FATAL_FAILURE(CallGenerateMinidump(dump_file_path, &result)); ASSERT_TRUE(result); ASSERT_HRESULT_SUCCEEDED( testing::VisitMinidump(dump_file_path, base::Bind(&ValidateMinidump))); } TEST_F(MinidumpTest, CustomStream) { // Generate a minidump for the current process. base::FilePath dump_file_path = temp_dir().Append(L"test.dump"); MinidumpRequest::CustomStream custom_stream = { kCustomStreamType, kCustomStreamContents, sizeof(kCustomStreamContents)}; request().custom_streams.push_back(custom_stream); bool result = false; ASSERT_NO_FATAL_FAILURE(CallGenerateMinidump(dump_file_path, &result)); ASSERT_TRUE(result); // Open the minidump file. base::MemoryMappedFile memory_mapped_file; ASSERT_TRUE(memory_mapped_file.Initialize(dump_file_path)); // Access the custom stream. MINIDUMP_DIRECTORY* dir = nullptr; void* stream = nullptr; ULONG stream_length = 0; ASSERT_TRUE(::MiniDumpReadDumpStream( const_cast<uint8*>(memory_mapped_file.data()), kCustomStreamType, &dir, &stream, &stream_length)); // Assert that the custom stream is what we expected. ASSERT_EQ(sizeof(kCustomStreamContents), stream_length); ASSERT_EQ(0, memcmp(stream, kCustomStreamContents, stream_length)); } TEST_F(MinidumpTest, MinidumpType) { // Generate a minidump for the current process. base::FilePath small_dump_file_path = temp_dir().Append(L"small.dump"); base::FilePath larger_dump_file_path = temp_dir().Append(L"larger.dump"); base::FilePath full_dump_file_path = temp_dir().Append(L"full.dump"); bool result = false; request().type = MinidumpRequest::SMALL_DUMP_TYPE; ASSERT_NO_FATAL_FAILURE(CallGenerateMinidump(small_dump_file_path, &result)); ASSERT_TRUE(result); request().type = MinidumpRequest::LARGER_DUMP_TYPE; ASSERT_NO_FATAL_FAILURE(CallGenerateMinidump(larger_dump_file_path, &result)); ASSERT_TRUE(result); request().type = MinidumpRequest::FULL_DUMP_TYPE; ASSERT_NO_FATAL_FAILURE(CallGenerateMinidump(full_dump_file_path, &result)); ASSERT_TRUE(result); // Use the relative file sizes to infer that the correct minidump type was // respected. // Other approaches (testing the memory ranges included in the dump) were // rejected due to the difficulty of deterministically knowing what should and // shouldn't be included in the various dump types. int64 small_dump_size = 0; int64 larger_dump_size = 0; int64 full_dump_size = 0; ASSERT_TRUE(base::GetFileSize(small_dump_file_path, &small_dump_size)); ASSERT_TRUE(base::GetFileSize(larger_dump_file_path, &larger_dump_size)); ASSERT_TRUE(base::GetFileSize(full_dump_file_path, &full_dump_size)); EXPECT_GT(full_dump_size, larger_dump_size); EXPECT_GT(larger_dump_size, small_dump_size); } TEST_F(MinidumpTest, MemoryRanges) { // Generate a minidump for the current process. base::FilePath default_dump_file_path = temp_dir().Append(L"default.dump"); base::FilePath dump_with_memory_range_file_path = temp_dir().Append(L"with_range.dump"); bool result = false; ASSERT_NO_FATAL_FAILURE( CallGenerateMinidump(default_dump_file_path, &result)); ASSERT_TRUE(result); MinidumpRequest::MemoryRange range = { reinterpret_cast<uint32_t>(kGlobalString), sizeof(kGlobalString)}; request().user_selected_memory_ranges.push_back(range); ASSERT_NO_FATAL_FAILURE( CallGenerateMinidump(dump_with_memory_range_file_path, &result)); ASSERT_TRUE(result); std::string default_dump; std::string dump_with_memory_range; ASSERT_TRUE(base::ReadFileToString(default_dump_file_path, &default_dump)); ASSERT_TRUE(base::ReadFileToString(dump_with_memory_range_file_path, &dump_with_memory_range)); ASSERT_EQ(std::string::npos, default_dump.find(kGlobalString)); ASSERT_NE(std::string::npos, dump_with_memory_range.find(kGlobalString)); } TEST_F(MinidumpTest, OverwriteExistingFile) { base::ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); base::FilePath dump_file_path; ASSERT_TRUE(base::CreateTemporaryFileInDir(temp_dir.path(), &dump_file_path)); bool result = false; ASSERT_NO_FATAL_FAILURE(CallGenerateMinidump(dump_file_path, &result)); ASSERT_TRUE(result); ASSERT_HRESULT_SUCCEEDED( testing::VisitMinidump(dump_file_path, base::Bind(&ValidateMinidump))); } TEST_F(MinidumpTest, NonexistantTargetDirectory) { base::ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); bool result = false; ASSERT_NO_FATAL_FAILURE(CallGenerateMinidump( temp_dir.path().Append(L"Foobar").Append(L"HelloWorld"), &result)); ASSERT_FALSE(result); } } // namespace kasko
37.62406
80
0.740208
[ "vector" ]
b9b8e869bc1baf53e6cccfc1c9968d12e5f7cbea
2,581
cpp
C++
src/RamTransformer.cpp
ohamel-softwaresecure/souffle
d4b9fe641f0c51d2a25408af45416a7e5123f866
[ "UPL-1.0" ]
null
null
null
src/RamTransformer.cpp
ohamel-softwaresecure/souffle
d4b9fe641f0c51d2a25408af45416a7e5123f866
[ "UPL-1.0" ]
null
null
null
src/RamTransformer.cpp
ohamel-softwaresecure/souffle
d4b9fe641f0c51d2a25408af45416a7e5123f866
[ "UPL-1.0" ]
null
null
null
/* * Souffle - A Datalog Compiler * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved * Licensed under the Universal Permissive License v 1.0 as shown at: * - https://opensource.org/licenses/UPL * - <souffle root>/licenses/SOUFFLE-UPL.txt */ /************************************************************************ * * @file RamTransformer.cpp * * Defines the interface for RAM transformation passes. * ***********************************************************************/ #include "RamTransformer.h" #include "DebugReport.h" #include "RamTranslationUnit.h" #include <algorithm> namespace souffle { bool RamTransformer::apply(RamTranslationUnit& translationUnit) { // take snapshot of alive analyses before invocation std::set<const RamAnalysis*> beforeInvocation = translationUnit.getAliveAnalyses(); // invoke the transformation bool changed = transform(translationUnit); // take snapshot of alive analyses after invocation std::set<const RamAnalysis*> afterInvocation = translationUnit.getAliveAnalyses(); // print newly invoked analyses (not for meta transformers) if (nullptr == dynamic_cast<RamMetaTransformer*>(this)) { for (const RamAnalysis* analysis : afterInvocation) { if (0 == beforeInvocation.count(analysis)) { std::stringstream ramAnalysisStr; analysis->print(ramAnalysisStr); if (!ramAnalysisStr.str().empty()) { translationUnit.getDebugReport().addSection( getName(), "RAM Analysis " + analysis->getName(), ramAnalysisStr.str()); } } } } if (changed) { translationUnit.invalidateAnalyses(); std::stringstream ramProgStr; ramProgStr << translationUnit.getProgram(); translationUnit.getDebugReport().addSection( getName(), "RAM Program after " + getName(), ramProgStr.str()); } else { translationUnit.getDebugReport().addSection( getName(), "After " + getName() + " " + " (unchanged)", ""); } /* Abort evaluation of the program if errors were encountered */ if (translationUnit.getErrorReport().getNumErrors() != 0) { std::cerr << translationUnit.getErrorReport(); std::cerr << std::to_string(translationUnit.getErrorReport().getNumErrors()) + " errors generated, evaluation aborted" << std::endl; exit(1); } return changed; } } // end of namespace souffle
35.356164
100
0.600155
[ "transform" ]
b9bd33bcc2c4c0237e18d2ddf489cb8eaa3e1e0a
1,350
cpp
C++
source/aufgabe2bis4.cpp
LS060598/programmiersprachen-aufgabenblatt-3
5d9af11f347d21b5c826620708601e3b064fcf50
[ "MIT" ]
null
null
null
source/aufgabe2bis4.cpp
LS060598/programmiersprachen-aufgabenblatt-3
5d9af11f347d21b5c826620708601e3b064fcf50
[ "MIT" ]
null
null
null
source/aufgabe2bis4.cpp
LS060598/programmiersprachen-aufgabenblatt-3
5d9af11f347d21b5c826620708601e3b064fcf50
[ "MIT" ]
null
null
null
#include <cstdlib> #include <vector> #include <list> #include <set> #include <map> #include <iostream> #include <iterator> #include <algorithm> #include <string> int main(){ // Aufgabe 3.2 std::list<unsigned int> l1(100); for (auto& l : l1) { l = std::rand() % 101; // Zahlen von 0-100 } std::vector<unsigned int> vec1(l1.size()); std::copy(std::begin(l1), std::end(l1), std::begin(vec1)); //3.3 wie viele Unterschiedliche Zahlen std::set<unsigned int> set_l1(std::begin(l1), std::end(l1)); std::cout << " Die Liste besteht aus " << set_l1.size() << " unterschiedlichen Zahlen \n"; //Welche zahlen nicht in Liste std::cout << "Diese Zahlen sind nicht in der Liste: " << std::endl; for(int x=0;x<=100;++x){ if(set_l1.count(x)==false){ // wenn Zahl nicht in Liste std::cout << x <<" "; } } //Häufigkeit jeder Zahl in Liste std::map<unsigned int, int> haufigkeiten; //Paare aus Zahl / Haufigkeit zu Map hinzufügen for (auto& key : set_l1){ int counter = 0; for(auto& value : l1){ if(key == value){ ++counter; } } haufigkeiten[key] = counter; } std::cout << "\nHaufigkeiten: \n"; //map ausgeben in form key : value for (auto& i : haufigkeiten){ //i ist pair (first, second) mit (key, value) std::cout << i.first << " : " << i.second << "\n"; } }
22.881356
92
0.599259
[ "vector" ]
b9bd905d8d4e317a087e99feade77de481c45996
28,908
cpp
C++
src/intermediate/TypeConversions.cpp
Mookel/VC4C
d72978253820e4175fa591206dedda6c586068b3
[ "MIT" ]
null
null
null
src/intermediate/TypeConversions.cpp
Mookel/VC4C
d72978253820e4175fa591206dedda6c586068b3
[ "MIT" ]
null
null
null
src/intermediate/TypeConversions.cpp
Mookel/VC4C
d72978253820e4175fa591206dedda6c586068b3
[ "MIT" ]
null
null
null
/* * Author: doe300 * * See the file "LICENSE" for the full license governing this code. */ #include "TypeConversions.h" #include "Helper.h" #include "VectorHelper.h" #include "operators.h" #include <cmath> using namespace vc4c; using namespace vc4c::intermediate; using namespace vc4c::operators; /* * Inserts a bit-cast where the destination element-type is larger than the source element-type, combining multiple * elements into a single one. * * This also means, the source vector has more elements (of smaller type-size) than the destination vector */ static NODISCARD InstructionWalker insertCombiningBitcast( InstructionWalker it, Method& method, const Value& src, const Value& dest) { // the number of source elements to combine in a single destination element unsigned sizeFactor = dest.type.getScalarBitCount() / src.type.getScalarBitCount(); // the number of bits to shift per element auto shift = src.type.getScalarBitCount(); /* * By shifting and ANDing whole source vector, we save a few instructions for sources with more than 1 element * * E.g. short4 -> int2 can be written as * (short4 & 0xFFFF) << 0 -> int2 (lower half-words in elements 0 and 2) * (short4 & 0xFFFF) << 16 -> int2 (upper half-words in element 1 and 3) * -> we only need 2 shifts and 2 ANDs instead of 4 (per element) */ Value truncatedSource = assign(it, src.type, "%bit_cast") = src & Value(Literal(src.type.getScalarWidthMask()), TYPE_INT32); std::vector<Value> shiftedTruncatedVectors; shiftedTruncatedVectors.reserve(sizeFactor); for(unsigned i = 0; i < sizeFactor; ++i) { shiftedTruncatedVectors.emplace_back( method.addNewLocal(dest.type.toVectorType(src.type.getVectorWidth()), "%bit_cast")); const Value& result = shiftedTruncatedVectors.back(); assign(it, result) = truncatedSource << Value(Literal(shift * i), TYPE_INT8); } /* * The up to 8 destination elements are now distributed across the shiftedTruncatedVectors (stvs) as follows: * * Size-factor of 2: * stv0[0] | stv1[1], stv0[2] | stv1[3], stv0[4] | stv1[5], ... * * Size-factor of 4; * stv0[0] | stv1[1] | stv2[2] | stv3[3], stv0[4] | stv1[5] | stv2[6] | stv3[7], ... * * To simplify the assembly of the destination, we rotate the vectors, so their element-numbers align */ std::vector<Value> rotatedVectors; rotatedVectors.reserve(shiftedTruncatedVectors.size()); for(unsigned i = 0; i < shiftedTruncatedVectors.size(); ++i) { if(i == 0) // no need to rotate rotatedVectors.emplace_back(shiftedTruncatedVectors.front()); else { rotatedVectors.emplace_back( method.addNewLocal(dest.type.toVectorType(src.type.getVectorWidth()), "%bit_cast")); const Value& result = rotatedVectors.back(); it = insertVectorRotation( it, shiftedTruncatedVectors[i], Value(Literal(i), TYPE_INT8), result, Direction::DOWN); } } /* * The up to 8 destination elements are now distributed across the rotatedVectors (rvs) as follows: * * Size-factor of 2: * rv0[0] | rv1[0], rv0[2] | rv1[2], rv0[4] | rv1[4], ... * * Size-factor of 4; * rv0[0] | rv1[0] | rv2[0] | rv3[0], rv0[4] | rv1[4] | rv2[4] | rv3[4], ... * * In the next step, we OR the separate vectors to a single one */ Value combinedVector = INT_ZERO; for(const Value& rv : rotatedVectors) { Value newCombinedVector = assign(it, dest.type.toVectorType(src.type.getVectorWidth()), "%bit_cast") = combinedVector | rv; combinedVector = newCombinedVector; } /* * Now, we have the destination elements as follows: * * Size-factor of 2: * cv[0], cv[2], cv[4], cv[6], ... * * Size-factor of 4; * cv[0], cv[4], cv[8], cv[12], ... * * Finally, we rotate the single elements to fit their position in the destination */ Value destination = method.addNewLocal(dest.type, "%bit_cast"); // initialize destination with zero so register-allocation finds unconditional assignment it.emplace(new MoveOperation(destination, INT_ZERO)); it.nextInBlock(); for(unsigned i = 0; i < dest.type.getVectorWidth(); ++i) { unsigned sourceIndex = i * sizeFactor; const Value tmp = method.addNewLocal(dest.type, "%bit_cast"); // the vector-rotation to element 0 and then to the destination element should be combined by optimization-step // #combineVectorRotations it = insertVectorExtraction(it, method, combinedVector, Value(Literal(sourceIndex), TYPE_INT8), tmp); it = insertVectorInsertion(it, method, destination, Value(Literal(i), TYPE_INT8), tmp); } it.emplace(new MoveOperation(dest, destination)); return it; } /* * Inserts a bit-cast where the destination element-type is smaller than the source element-type, splitting a single * element into several ones. * * This also means, the source vector has less elements (of larger type-size) than the destination vector */ static NODISCARD InstructionWalker insertSplittingBitcast( InstructionWalker it, Method& method, const Value& src, const Value& dest) { // the number of destination elements to extract from a single source element unsigned sizeFactor = src.type.getScalarBitCount() / dest.type.getScalarBitCount(); // the number of bits to shift per element auto shift = dest.type.getScalarBitCount(); /* * By shifting and ANDing whole source vector, we save a few instructions for sources with more than 1 element * * E.g. int2 -> short4 can be written as * (int2 >> 0) & 0xFFFF -> short4 (lower half-words) * (int2 >> 16) & 0xFFFF -> short4 (upper half-words) * -> we only need 2 shifts and 2 ANDs instead of 4 (per element) */ std::vector<Value> shiftedTruncatedVectors; shiftedTruncatedVectors.reserve(sizeFactor); auto srcLongData = Local::getLocalData<MultiRegisterData>(src.checkLocal()); for(unsigned i = 0; i < sizeFactor; ++i) { shiftedTruncatedVectors.emplace_back(method.addNewLocal(dest.type, "%bit_cast")); const Value& result = shiftedTruncatedVectors.back(); auto srcVal = src; if(srcLongData) // need to correctly take the lower or upper part for 64-bit locals srcVal = (i >= (sizeFactor / 2) ? srcLongData->upper : srcLongData->lower)->createReference(); Value tmp = assign(it, dest.type, "%bit_cast") = as_unsigned{srcVal} >> Value(Literal(shift * i), TYPE_INT8); assign(it, result) = tmp & Value(Literal(dest.type.getScalarWidthMask()), TYPE_INT32); } /* * The up to 16 destination elements are now distributed across the shiftedTruncatedVectors (stvs) as follows: * * Size-factor of 2: * stv0[0], stv1[0], stv0[1], stv1[1], stv0[2], ... * * Size-factor of 4; * stv0[0], stv1[0], stv2[0], stv3[0], stv0[1], ... * * So we need to assemble the destination vector from these vectors */ const Value destination = method.addNewLocal(dest.type, "%bit_cast"); // initialize destination with zero so register-allocation finds unconditional assignment it.emplace(new MoveOperation(destination, INT_ZERO)); it.nextInBlock(); for(unsigned i = 0; i < dest.type.getVectorWidth(); ++i) { const Value& stv = shiftedTruncatedVectors.at(i % shiftedTruncatedVectors.size()); unsigned sourceElement = static_cast<unsigned>(i / shiftedTruncatedVectors.size()); // need to fix-up the type to single element for vector insertion to handle it as such const Value tmp = method.addNewLocal(dest.type.getElementType(), "%bit_cast"); // the vector-rotation to element 0 and then to the destination element should be combined by optimization-step // #combineVectorRotations it = insertVectorExtraction(it, method, stv, Value(Literal(sourceElement), TYPE_INT8), tmp); it = insertVectorInsertion(it, method, destination, Value(Literal(i), TYPE_INT8), tmp); } it.emplace(new MoveOperation(dest, destination)); return it; } InstructionWalker intermediate::insertBitcast( InstructionWalker it, Method& method, const Value& src, const Value& dest, InstructionDecorations deco) { if(src.isUndefined()) it.emplace(new intermediate::MoveOperation(dest, UNDEFINED_VALUE)); else if(src.isZeroInitializer()) it.emplace(new intermediate::MoveOperation(dest, INT_ZERO)); else if(src.type.getVectorWidth() > dest.type.getVectorWidth()) it = insertCombiningBitcast(it, method, src, dest); else if(src.type.getVectorWidth() < dest.type.getVectorWidth()) it = insertSplittingBitcast(it, method, src, dest); else // bit-casts with types of same vector-size (and therefore same element-size) are simple moves it.emplace((new intermediate::MoveOperation(dest, src))->addDecorations(deco)); // last step: map destination to source (if bit-cast of pointers) if(dest.checkLocal() && src.checkLocal() && dest.type.getPointerType() && src.type.getPointerType()) // this helps recognizing lifetime-starts of bit-cast stack-allocations const_cast<Local*>(dest.local())->set(ReferenceData(*src.local(), 0)); it->addDecorations(deco); it.nextInBlock(); return it; } InstructionWalker intermediate::insertZeroExtension(InstructionWalker it, Method& method, const Value& src, const Value& dest, bool allowLiteral, const ConditionCode conditional, const SetFlag setFlags) { if(src.type.getScalarBitCount() == 32 && dest.type.getScalarBitCount() <= 32) { //"extend" to smaller type it.emplace(new MoveOperation(dest, src, conditional, setFlags)); switch(dest.type.getScalarBitCount()) { case 8: it.get<ExtendedInstruction>()->setPackMode(PACK_INT_TO_CHAR_TRUNCATE); break; case 16: it.get<ExtendedInstruction>()->setPackMode(PACK_INT_TO_SHORT_TRUNCATE); break; case 32: // no pack mode break; default: throw CompilationError( CompilationStep::GENERAL, "Invalid type-width for zero-extension", dest.type.to_string()); } } else if(dest.type.getScalarBitCount() > 32 && Local::getLocalData<MultiRegisterData>(dest.checkLocal())) { auto out = dest.local()->get<MultiRegisterData>(); if(src.type.getScalarBitCount() < 32) { // extend to 32-bit integer first it = insertZeroExtension( it, method, src, out->lower->createReference(), allowLiteral, conditional, setFlags); } else assign(it, out->lower->createReference()) = (src, conditional, setFlags); // set upper word to all zeros it.emplace(new MoveOperation(out->upper->createReference(), INT_ZERO)); it->addDecorations(InstructionDecorations::UNSIGNED_RESULT); } else if(dest.type.getScalarBitCount() >= 32 && src.type.getScalarBitCount() >= 32) { // do nothing, is just a move, since we truncate the 64-bit integers anyway it.emplace(new MoveOperation(dest, src, conditional, setFlags)); } else if(src.checkRegister() && (has_flag(src.reg().file, RegisterFile::PHYSICAL_A) || has_flag(src.reg().file, RegisterFile::ACCUMULATOR)) && src.type.getScalarBitCount() == 8) { // if we zero-extend from register-file A, use unpack-modes // this is applied e.g. for unpacking parameters in code-generation, since the source is UNIFORM it.emplace((new MoveOperation(dest, src, conditional, setFlags))->setUnpackMode(UNPACK_CHAR_TO_INT_ZEXT)); } else if(allowLiteral) { it.emplace(new Operation( OP_AND, dest, src, Value(Literal(src.type.getScalarWidthMask()), TYPE_INT32), conditional, setFlags)); } else { const Value tmp = method.addNewLocal(TYPE_INT32, "%zext"); it.emplace(new LoadImmediate(tmp, Literal(src.type.getScalarWidthMask()))); it.nextInBlock(); it.emplace(new Operation(OP_AND, dest, src, tmp, conditional, setFlags)); } it->addDecorations(InstructionDecorations::UNSIGNED_RESULT); auto writer = src.getSingleWriter(); if(writer) it->addDecorations(intermediate::forwardDecorations(writer->decoration)); it.nextInBlock(); return it; } InstructionWalker intermediate::insertSignExtension(InstructionWalker it, Method& method, const Value& src, const Value& dest, bool allowLiteral, const ConditionCode conditional, const SetFlag setFlags) { if(dest.type.getScalarBitCount() > 32 && Local::getLocalData<MultiRegisterData>(dest.checkLocal())) { auto out = dest.local()->get<MultiRegisterData>(); if(src.type.getScalarBitCount() < 32) { // extend to 32-bit integer first it = insertSignExtension( it, method, src, out->lower->createReference(), allowLiteral, conditional, SetFlag::DONT_SET); } else assign(it, out->lower->createReference()) = (src, conditional, setFlags); auto offset = 31_val; if(!allowLiteral) { offset = method.addNewLocal(TYPE_INT8, "%sext"); it.emplace(new LoadImmediate(offset, 31_lit)); it.nextInBlock(); } // replicate the high bit across the whole word to be written to the upper word assign(it, out->upper->createReference()) = (as_signed{out->lower->createReference()} >> offset, conditional, setFlags); it.previousInBlock(); } else if(dest.type.getScalarBitCount() >= 32 && src.type.getScalarBitCount() >= 32) { // do nothing, is just a move, since we truncate the 64-bit integers anyway it.emplace(new MoveOperation(dest, src, conditional, setFlags)); } else if(src.checkRegister() && (has_flag(src.reg().file, RegisterFile::PHYSICAL_A) || has_flag(src.reg().file, RegisterFile::ACCUMULATOR)) && src.type.getScalarBitCount() == 16) { // if we sign-extend from register-file A, use unpack-modes // this is applied e.g. for unpacking parameters in code-generation, since the source is UNIFORM it.emplace((new MoveOperation(dest, src, conditional, setFlags))->setUnpackMode(UNPACK_SHORT_TO_INT_SEXT)); } else { // out = asr(shl(in, bit_diff) bit_diff) // where bit_diff is the difference to full 32-bit Literal diffLit(static_cast<int32_t>(32 - src.type.getScalarBitCount())); Value widthDiff(diffLit, TYPE_INT8); if(!allowLiteral) { Value tmp = method.addNewLocal(TYPE_INT8, "%sext"); it.emplace(new LoadImmediate(tmp, diffLit)); it.nextInBlock(); widthDiff = tmp; } Value tmp = assign(it, TYPE_INT32, "%sext") = (src << widthDiff, conditional); it.emplace(new Operation(OP_ASR, dest, tmp, widthDiff, conditional, setFlags)); // we shifted the exact same number of bits to the left before, so all N trailing bits are zero it->addDecorations(InstructionDecorations::EXACT_OPERATION); } it.nextInBlock(); return it; } InstructionWalker intermediate::insertSaturation( InstructionWalker it, Method& method, const Value& src, const Value& dest, ConversionType type) { // saturation = clamping to min/max of type //-> dest = max(min(src, destType.max), destType.min) //-> or via pack-modes if(!dest.type.isSimpleType() || dest.type.isFloatingType()) throw CompilationError(CompilationStep::GENERAL, "Invalid target type for saturation", dest.type.to_string()); bool isInputSigned = type == ConversionType::SIGNED_TO_SIGNED || type == ConversionType::SIGNED_TO_UNSIGNED; bool isOutputSigned = type == ConversionType::UNSIGNED_TO_SIGNED || type == ConversionType::SIGNED_TO_SIGNED; if(auto lit = src.getLiteralValue()) { switch(dest.type.getScalarBitCount()) { case 8: return it.emplace((new MoveOperation(dest, Value(isOutputSigned ? Literal(saturate<int8_t>(lit->signedInt())) : Literal(saturate<uint8_t>(lit->unsignedInt())), dest.type))) ->addDecorations(isOutputSigned ? InstructionDecorations::NONE : InstructionDecorations::UNSIGNED_RESULT)); case 16: return it.emplace((new MoveOperation(dest, Value(isOutputSigned ? Literal(saturate<int16_t>(lit->signedInt())) : Literal(saturate<uint16_t>(lit->unsignedInt())), dest.type))) ->addDecorations(isOutputSigned ? InstructionDecorations::NONE : InstructionDecorations::UNSIGNED_RESULT)); case 32: return it.emplace((new MoveOperation(dest, Value(isOutputSigned ? Literal(saturate<int32_t>(lit->signedInt())) : Literal(saturate<uint32_t>(lit->unsignedInt())), dest.type))) ->addDecorations(isOutputSigned ? InstructionDecorations::NONE : InstructionDecorations::UNSIGNED_RESULT)); default: throw CompilationError( CompilationStep::GENERAL, "Invalid target type for saturation", dest.type.to_string()); } } else // saturation can be easily done via pack-modes { // FIXME does not handle 64-bit inputs correctly! if(dest.type.getScalarBitCount() == 8) { Value tmpSrc = src; if(!isInputSigned) // if unsigned and MSB is set, will interpret as negative signed -> mask off MSB tmpSrc = assign(it, src.type) = (src & 0x7FFFFFFF_val, InstructionDecorations::UNSIGNED_RESULT); if(isOutputSigned) { // dest = min(max(src, -128), 127) auto tmp = assign(it, src.type) = max(as_signed{tmpSrc}, as_signed{Value(Literal(std::numeric_limits<int8_t>::min()), TYPE_INT8)}); return it.emplace( new Operation(OP_MIN, dest, tmp, Value(Literal(std::numeric_limits<int8_t>::max()), TYPE_INT8))); } else return it.emplace((new MoveOperation(dest, tmpSrc)) ->setPackMode(PACK_INT_TO_UNSIGNED_CHAR_SATURATE) ->addDecorations(InstructionDecorations::UNSIGNED_RESULT)); } else if(dest.type.getScalarBitCount() == 16) { Value tmpSrc = src; if(!isInputSigned) // if unsigned and MSB is set, will interpret as negative signed -> mask off MSB tmpSrc = assign(it, src.type) = (src & 0x7FFFFFFF_val, InstructionDecorations::UNSIGNED_RESULT); if(isOutputSigned) return it.emplace((new MoveOperation(dest, tmpSrc))->setPackMode(PACK_INT_TO_SIGNED_SHORT_SATURATE)); else { auto tmp = assign(it, src.type) = max(as_signed{tmpSrc}, as_signed{Value(Literal(std::numeric_limits<uint16_t>::min()), TYPE_INT16)}); return it.emplace( new Operation(OP_MIN, dest, tmp, Value(Literal(std::numeric_limits<uint16_t>::max()), TYPE_INT16))); } } if(isOutputSigned == isInputSigned) // signed -> signed or unsigned -> unsigned => move return it.emplace((new MoveOperation(dest, src)) ->addDecorations(isOutputSigned ? InstructionDecorations::NONE : InstructionDecorations::UNSIGNED_RESULT)); if(isInputSigned && !isOutputSigned) // signed -> unsigned => dest = max(src, 0) return it.emplace( (new Operation(OP_MAX, dest, src, INT_ZERO))->addDecorations(InstructionDecorations::UNSIGNED_RESULT)); if(!isInputSigned && isOutputSigned) { // unsigned -> signed => dest = MSB(src) ? INT_MAX : src auto negativeCond = assignNop(it) = as_signed{src} < as_signed{INT_ZERO}; assign(it, dest) = (0x7FFFFFFF_val, negativeCond, InstructionDecorations::UNSIGNED_RESULT); return it.emplace((new MoveOperation(dest, src, negativeCond.invert())) ->addDecorations(InstructionDecorations::UNSIGNED_RESULT)); } throw CompilationError(CompilationStep::GENERAL, "Saturation to this type is not yet supported", "from " + src.type.to_string() + " to " + dest.type.to_string()); } } InstructionWalker intermediate::insertTruncate( InstructionWalker it, Method& method, const Value& src, const Value& dest) { if(dest.type.getScalarBitCount() >= src.type.getScalarBitCount()) //"truncate" to larger type, simply move assign(it, dest) = src; else assign(it, dest) = src & Value(Literal(dest.type.getScalarWidthMask()), TYPE_INT32); return it; } InstructionWalker intermediate::insertFloatingPointConversion( InstructionWalker it, Method& method, const Value& src, const Value& dest) { if(src.type.getScalarBitCount() == dest.type.getScalarBitCount()) it.emplace(new MoveOperation(dest, src)); else if(src.type.getScalarBitCount() == 16 && dest.type.getScalarBitCount() == 32) it.emplace((new Operation(OP_FMUL, dest, src, OP_FMUL.getRightIdentity().value())) ->setUnpackMode(UNPACK_HALF_TO_FLOAT)); else if(src.type.getScalarBitCount() == 32 && dest.type.getScalarBitCount() == 16) it.emplace((new intermediate::Operation(OP_FMUL, dest, src, OP_FMUL.getRightIdentity().value())) ->setPackMode(PACK_FLOAT_TO_HALF_TRUNCATE)); else // XXX conversion from/to double would not be that hard (extract exponent, deduct bias, add new bias, extract // mantissa, shift), but we cannot store the resulting 64-bit value... throw CompilationError(CompilationStep::GENERAL, "Unsupported floating-point conversion", src.to_string() + " to " + dest.to_string()); return it.nextInBlock(); } InstructionWalker intermediate::insertFloatToIntegerSaturation( InstructionWalker it, Method& method, const Value& src, const Value& dest, int32_t minInt, uint32_t maxInt) { auto maxFloat = Value(Literal(static_cast<float>(maxInt)), TYPE_FLOAT); auto maxInteger = Value(Literal(maxInt), dest.type); auto minFloat = Value(Literal(static_cast<float>(minInt)), TYPE_FLOAT); auto minInteger = Value(Literal(minInt), dest.type); // default -> dest = ftoi(src) it.emplace((new Operation(OP_FTOI, dest, src))); it.nextInBlock(); // src >= itof(max) -> dest = max auto overflowCond = assignNop(it) = as_float{src} >= as_float{maxFloat}; assign(it, dest) = (maxInteger, overflowCond); // src <= itof(min) -> dest = min auto underflowCond = assignNop(it) = as_float{src} <= as_float{minFloat}; assign(it, dest) = (minInteger, underflowCond); return it; } InstructionWalker intermediate::insertUnsignedToFloatConversion( InstructionWalker it, Method& method, const Value& src, const Value& dest) { if(src.type.getScalarBitCount() < 32) { // make sure, leading bits are zeroes const uint32_t mask = src.type.getScalarWidthMask(); auto tmp = assign(it, dest.type, "%uitofp") = (src & Value(Literal(mask), TYPE_INT32)); it.emplace(new Operation(OP_ITOF, dest, tmp)); it.nextInBlock(); } else if(src.type.getScalarBitCount() > 32) { auto parts = Local::getLocalData<MultiRegisterData>(src.checkLocal()); if(!parts) throw CompilationError(CompilationStep::NORMALIZER, "Can't convert long to floating value without having multi-register data", it->to_string()); auto upperPart = method.addNewLocal(dest.type); it = insertUnsignedToFloatConversion(it, method, parts->upper->createReference(), upperPart); auto lowerPart = method.addNewLocal(dest.type); it = insertUnsignedToFloatConversion(it, method, parts->lower->createReference(), lowerPart); auto tmp = assign(it, upperPart.type) = upperPart * Value(Literal(std::pow(2.0f, 32.0f)), TYPE_FLOAT); assign(it, dest) = tmp + lowerPart; } else // 32-bits { // TODO sometimes is off by 1 ULP, e.g. for 1698773569 gets 1698773504 instead of expected 1698773632 // uitof(x) = y * uitof(x/y) + uitof(x & |y|), where |y| is the bits for y auto tmpInt = assign(it, src.type) = src / 2_lit; auto tmpFloat = method.addNewLocal(dest.type); it.emplace(new Operation(OP_ITOF, tmpFloat, tmpInt)); it.nextInBlock(); auto tmpFloat2 = assign(it, tmpFloat.type) = tmpFloat * Value(Literal(2.0f), TYPE_FLOAT); auto tmpInt2 = assign(it, src.type) = src % 2_lit; auto tmpFloat3 = method.addNewLocal(dest.type); it.emplace(new Operation(OP_ITOF, tmpFloat3, tmpInt2)); it.nextInBlock(); assign(it, dest) = as_float{tmpFloat2} + as_float{tmpFloat3}; } return it; } InstructionWalker intermediate::insertSignedToFloatConversion( InstructionWalker it, Method& method, const Value& src, const Value& dest) { if(src.type.getScalarBitCount() > 32) { auto parts = Local::getLocalData<MultiRegisterData>(src.checkLocal()); if(!parts) throw CompilationError(CompilationStep::NORMALIZER, "Can't convert long to floating value without having multi-register data", it->to_string()); auto upperPart = method.addNewLocal(dest.type); it.emplace(new intermediate::Operation(OP_ITOF, upperPart, parts->upper->createReference())); it.nextInBlock(); upperPart = assign(it, upperPart.type) = upperPart * Value(Literal(std::pow(2.0f, 32.0f)), TYPE_FLOAT); /* * Case handling: * - Upper part positive -> normal flow (upper part to float * 2^32 + unsigned lower part to float) * - Upper part all zeroes -> normal flow (lower part is zero-extended and already handled as unsigned) * - Upper part negative -> inverted flow (upper part to float * 2^32 - |lower part| to float) * - Upper part all ones -> ignore upper part */ auto lowerAbs = method.addNewLocal(parts->lower->type); Value dummySign = UNDEFINED_VALUE; it = insertMakePositive(it, method, parts->lower->createReference(), lowerAbs, dummySign); auto lowerInput = assign(it, parts->lower->type) = parts->lower->createReference(); auto cond = assignNop(it) = as_signed{parts->upper->createReference()} < as_signed{0_val}; assign(it, lowerInput) = (lowerAbs, cond); // convert the actual (absolute value of the) lower part auto lowerPart = method.addNewLocal(dest.type); it = intermediate::insertUnsignedToFloatConversion(it, method, lowerInput, lowerPart); // if upper part was negative, subtract, otherwise add the parts together cond = assignNop(it) = as_signed{parts->upper->createReference()} < as_signed{0_val}; assign(it, lowerPart) = (-as_float{lowerPart}, cond); // if upper part is all ones, do not add it (since it is only the sign, no value) cond = assignNop(it) = as_signed{parts->upper->createReference()} == as_signed{0xFFFFFFFF_val}; assign(it, upperPart) = (FLOAT_ZERO, cond); it.emplace(new intermediate::Operation(OP_FADD, dest, upperPart, lowerPart)); it.nextInBlock(); return it; } // for non 32-bit types, need to sign-extend auto intValue = src; if(src.type.getScalarBitCount() < 32) { intValue = method.addNewLocal(TYPE_INT32, "%sitofp"); it = insertSignExtension(it, method, src, intValue, true); } it.emplace(new Operation(OP_ITOF, dest, intValue)); it.nextInBlock(); return it; }
46.625806
120
0.633077
[ "vector" ]