hexsha
stringlengths
40
40
size
int64
22
2.4M
ext
stringclasses
5 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
260
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
78
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
260
max_issues_repo_name
stringlengths
5
109
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
260
max_forks_repo_name
stringlengths
5
109
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
22
2.4M
avg_line_length
float64
5
169k
max_line_length
int64
5
786k
alphanum_fraction
float64
0.06
0.95
matches
listlengths
1
11
26bdd31d2a710554c581d8a1618e6921dcdd7476
5,082
h
C
inc/periodicBoundaryConditions.h
dbeller8/open-Qmin
502a651aef39e3fe56a4a14c7eba1dcaac41ecbb
[ "BSL-1.0" ]
7
2020-03-25T13:44:21.000Z
2022-02-06T05:16:15.000Z
inc/periodicBoundaryConditions.h
dbeller8/open-Qmin
502a651aef39e3fe56a4a14c7eba1dcaac41ecbb
[ "BSL-1.0" ]
1
2021-11-08T10:05:34.000Z
2021-11-26T17:32:56.000Z
inc/periodicBoundaryConditions.h
dbeller8/open-Qmin
502a651aef39e3fe56a4a14c7eba1dcaac41ecbb
[ "BSL-1.0" ]
13
2019-09-16T17:45:11.000Z
2022-03-08T03:12:29.000Z
#ifndef periodicBoundaryConditions_h #define periodicBoundaryConditions_h #include "std_include.h" #ifdef __NVCC__ #define HOSTDEVICE __host__ __device__ inline #else #define HOSTDEVICE inline __attribute__((always_inline)) #endif /*! \file periodicBoundaryConditions.h */ //!A simple box defining a hypercubic periodic domain /*! * gives access to Box.setBoxDimensions(vector<scalar> dimensions); Box.returnBoxDimensions(); //return a vector with box dimensions laid out in some way Box.movePoint(dvec &A, dvec disp); // A = putInBox(A +disp). i.e., move the particle by some amound and if necessary, e.g., wrap it back into the primary unit cell Box.minDist(dvec &A, dvec &B, dvec &result); // stores in "result" the minimum distance between A and B */ struct periodicBoundaryConditions { public: HOSTDEVICE periodicBoundaryConditions(){}; //!Construct a hyper-cubic box with side-lengths given by the specified value HOSTDEVICE periodicBoundaryConditions(scalar sideLength){setHyperCubic(sideLength);}; //!Get the dimensions of the box HOSTDEVICE void getBoxDims(dVec &boxDims) {for (int dd =0; dd < DIMENSION; ++dd) boxDims.x[dd] = boxDimensions.x[dd];}; //!Get the inverse of the box transformation matrix HOSTDEVICE void getBoxInvDims(dVec &iBoxDims) {for (int dd =0; dd < DIMENSION; ++dd) iBoxDims.x[dd] = inverseBoxDimensions.x[dd];}; //!Set the box to some new hypercube HOSTDEVICE void setHyperCubic(scalar sideLength); //!Set the box to some new rectangular specification HOSTDEVICE void setBoxDims(dVec &bDims); //! Take a point in the unit square and find its position in the box HOSTDEVICE void Transform(const dVec &p1, dVec &pans); //! Take a point in the box and find its position in the unit square HOSTDEVICE void invTransform(const dVec p1, dVec &pans); //!Take the point and put it back in the unit cell HOSTDEVICE void putInBoxReal(dVec &p1); //!Calculate the minimum distance between two points HOSTDEVICE void minDist(const dVec &p1, const dVec &p2, dVec &pans); //!Move p1 by the amount disp, then put it in the box HOSTDEVICE void move(dVec &p1, const dVec &disp); //!compute volume HOSTDEVICE scalar Volume() { scalar vol = 1.0; for (int dd = 0; dd < DIMENSION; ++dd) vol *= boxDimensions.x[dd]; return vol; }; /* HOSTDEVICE void operator=(periodicBoundaryConditions &other) { Dscalar b11,b12,b21,b22; other.getBoxDims(b11,b12,b21,b22); setGeneral(b11,b12,b21,b22); }; */ protected: dVec boxDimensions; dVec halfBoxDimensions; dVec inverseBoxDimensions; HOSTDEVICE void putInBox(dVec &vp); }; void periodicBoundaryConditions::setHyperCubic(scalar sideLength) { for (int dd = 0; dd < DIMENSION; ++dd) { boxDimensions.x[dd] = sideLength; halfBoxDimensions.x[dd] = 0.5*sideLength; inverseBoxDimensions.x[dd] = 1.0/sideLength; }; }; void periodicBoundaryConditions::setBoxDims(dVec &bDims) { for (int dd = 0; dd < DIMENSION; ++dd) { boxDimensions.x[dd] = bDims.x[dd];; halfBoxDimensions.x[dd] = 0.5*bDims.x[dd]; inverseBoxDimensions.x[dd] = 1.0/bDims.x[dd]; }; }; void periodicBoundaryConditions::Transform(const dVec &p1, dVec &pans) { for (int dd = 0; dd < DIMENSION; ++dd) pans.x[dd] = boxDimensions.x[dd]*p1.x[dd]; }; void periodicBoundaryConditions::invTransform(const dVec p1, dVec &pans) { for (int dd = 0; dd < DIMENSION; ++dd) pans.x[dd] = inverseBoxDimensions.x[dd]*p1.x[dd]; }; void periodicBoundaryConditions::putInBox(dVec &vp) {//acts on points in the virtual space for (int dd = 0; dd< DIMENSION; ++dd) { while(vp.x[dd] < 0) vp.x[dd] += 1.0; while(vp.x[dd] >= 1.0) vp.x[dd] -= 1.0; }; }; void periodicBoundaryConditions::putInBoxReal(dVec &p1) {//assume real space entries. Puts it back in box dVec virtualPosition; invTransform(p1,virtualPosition); putInBox(virtualPosition); Transform(virtualPosition,p1); }; void periodicBoundaryConditions::minDist(const dVec &p1, const dVec &p2, dVec &pans) { for (int dd = 0; dd< DIMENSION; ++dd) { pans.x[dd] = p1.x[dd]-p2.x[dd]; while(pans.x[dd] < halfBoxDimensions.x[dd]) pans.x[dd] += boxDimensions.x[dd]; while(pans.x[dd] > halfBoxDimensions.x[dd]) pans.x[dd] -= boxDimensions.x[dd]; }; }; void periodicBoundaryConditions::move(dVec &p1, const dVec &disp) {//assume real space entries. Moves p1 by disp, and puts it back in box for (int dd = 0; dd < DIMENSION; ++dd) p1.x[dd] += disp.x[dd]; putInBoxReal(p1); }; typedef shared_ptr<periodicBoundaryConditions> BoxPtr; #undef HOSTDEVICE #endif
34.808219
163
0.636757
[ "vector", "transform" ]
26c21be30940b03470f749bd6d0c1ea48aa6f00d
9,259
h
C
Examples/SDKLibrary/interface/common/portable/data_types/opcua_build_info_t.h
beeond/robot-examples
afc6b8b10809988b03663d703203625927e66e8f
[ "MIT" ]
1
2018-03-29T21:03:31.000Z
2018-03-29T21:03:31.000Z
Examples/SDKLibrary/interface/common/portable/data_types/opcua_build_info_t.h
JayeshThamke/robot-examples
afc6b8b10809988b03663d703203625927e66e8f
[ "MIT" ]
null
null
null
Examples/SDKLibrary/interface/common/portable/data_types/opcua_build_info_t.h
JayeshThamke/robot-examples
afc6b8b10809988b03663d703203625927e66e8f
[ "MIT" ]
4
2018-04-05T21:16:55.000Z
2019-10-15T19:01:46.000Z
/* ----------------------------------------------------------------------------------------------------------------- COPYRIGHT (c) 2009 - 2017 HONEYWELL INC., ALL RIGHTS RESERVED This software is a copyrighted work and/or information protected as a trade secret. Legal rights of Honeywell Inc. in this software are distinct from ownership of any medium in which the software is embodied. Copyright or trade secret notices included must be reproduced in any copies authorized by Honeywell Inc. The information in this software is subject to change without notice and should not be considered as a commitment by Honeywell Inc. ----------------------------------------------------------------------------------------------------------------- */ #ifndef _OPCUA_BUILD_INFO_T_ #define _OPCUA_BUILD_INFO_T_ #include "opcua_string_t.h" #include "opcua_localized_text_t.h" #include "opcua_application_type_t.h" #include "opcua_array_ua_t.h" #include "opcua_server_state_t.h" #include "opcua_date_time_t.h" #include "opcua_structure_t.h" namespace uasdk { /** \addtogroup grpDataType *@{*/ /*****************************************************************************/ /** \brief BuildInfo_t * * This class implements the Build Information data type * */ class BuildInfo_t : public Structure_t { public: UA_DECLARE_RUNTIME_TYPE(BuildInfo_t); private: /*****************************************************************************/ /* @var String_t productUri * Product URI */ String_t productUri; /*****************************************************************************/ /* @var String_t manufacturerName * Manufacturer name */ String_t manufacturerName; /*****************************************************************************/ /* @var String_t productName * Product Name */ String_t productName; /*****************************************************************************/ /* @var String_t softwareVersion * Software Version */ String_t softwareVersion; /*****************************************************************************/ /* @var String_t buildNumber * Build Number */ String_t buildNumber; /*****************************************************************************/ /* @var UtcTime_t buildDate * Build Date */ UtcTime_t buildDate; public: /*****************************************************************************/ /* @var uint32_t TYPE_ID * Data type ID */ static const uint32_t TYPE_ID = OpcUaId_BuildInfo; /*****************************************************************************/ /** Destructor for the class. * */ virtual ~BuildInfo_t(); /*****************************************************************************/ /** == operator overloading * * @param[in] BaseDataType_t const & obj * Object to be compared with * * @return * True - If the both the objects are same * False - If the both the objects are not same */ virtual bool operator==(BaseDataType_t const & obj) const; /*****************************************************************************/ /** == operator overloading * * @param[in] const & obj * Object to be compared with * * @return * True - If the both the objects are same * False - If the both the objects are not same */ bool operator==(BuildInfo_t const & obj) const; /*****************************************************************************/ /** > operator overloading * * @param[in] BaseDataType_t const & obj * Object to be compared with * * @return * True - If grater than RHS * False - If less than RHS */ virtual bool operator>(BaseDataType_t const & obj) const; /*****************************************************************************/ /** > operator overloading * * @param[in] BuildInfo_t const & obj * Object to be compared with * * @return * True indicates that the LHS BuildInfo_t object is greater than RHS BuildInfo_t object */ bool operator>(BuildInfo_t const & obj) const; /*****************************************************************************/ /** Copy to the destination * * @param[out] IntrusivePtr_t<BaseDataType_t>& destination * Destination data type * * @return * Status of the operation */ virtual Status_t CopyTo(IntrusivePtr_t<BaseDataType_t>& destination) const; /*****************************************************************************/ /** Copy from the source * * @param[in] const BuildInfo_t& source * Build Information source to copy from * * @return * Status of the operation */ Status_t CopyFrom(const BuildInfo_t& source); /*****************************************************************************/ /** Copy from the source * * @param[in] const BaseDataType_t& source * Source data type * * @return * Status of the operation */ virtual Status_t CopyFrom(const BaseDataType_t& source); /*****************************************************************************/ /** Get the Type ID * * @param[in] uint16_t& namespaceIndex * Reference to the name space index * * @return * Returns the Type ID */ virtual uint32_t TypeId(uint16_t& namespaceIndex) const; /*****************************************************************************/ /** Get the Binary Encoding Id * * @param[in] uint16_t& namespaceIndex * Reference to the name space index * * @return * Returns the Binary Encoding Id */ virtual uint32_t BinaryEncodingId(uint16_t& namespaceIndex) const; /*****************************************************************************/ /** Get the Product URI * * @return * Returns the Product URI */ const String_t& ProductUri(void) const; /*****************************************************************************/ /** Get the Product URI * * @return * Returns the Product URI */ String_t& ProductUri(void); /*****************************************************************************/ /** Get the manufacturer name * * @return * Returns the manufacturer name */ const String_t& ManufacturerName(void) const; /*****************************************************************************/ /** Get the manufacturer name * * @return * Returns the manufacturer name */ String_t& ManufacturerName(void); /*****************************************************************************/ /** Get the Product name * * @return * Returns the Product name */ const String_t& ProductName(void) const; /*****************************************************************************/ /** Get the Product name * * @return * Returns the Product name */ String_t& ProductName(void); /*****************************************************************************/ /** Get the Software version * * @return * Returns the Software version */ const String_t& SoftwareVersion(void) const; /*****************************************************************************/ /** Get the Software version * * @return * Returns the Software version */ String_t& SoftwareVersion(void); /*****************************************************************************/ /** Get the Build number * * @return * Returns the Build number */ const String_t& BuildNumber(void) const; /*****************************************************************************/ /** Get the Build number * * @return * Returns the Build number */ String_t& BuildNumber(void); /*****************************************************************************/ /** Get the Build Date * * @return * Returns the Build Date */ const UtcTime_t& BuildDate(void) const; /*****************************************************************************/ /** Get the Build Date * * @return * Returns the Build Date */ UtcTime_t& BuildDate(void); /*****************************************************************************/ /** Encode the buffer * * @param[in] ICodec_t& encoder * Reference to the encoder object * * @param[out] IBuffer_t& buffer * Encode buffer * * @return * Returns status of the operation */ virtual Status_t Encode(ICodec_t& encoder, IBuffer_t& buffer) const; /*****************************************************************************/ /** Decode the buffer * * @param[in] const IBuffer_t& buffer * Decode buffer * * @param[in] ICodec_t& decoder * Reference to the decoder object * * @param[out] BuildInfo_t& result * Decoded Build Information object * * @return * Returns status of the operation */ static Status_t Decode(const IBuffer_t& buffer, ICodec_t& decoder, BuildInfo_t& result); }; /** @} */ } // namespace uasdk #endif // _OPCUA_BUILD_INFO_T_
28.057576
116
0.445188
[ "object" ]
26c2f71597c5d9f0c49dd55be32634645d4fee84
4,419
c
C
DSP/TI-Header/csl_c6455_src/src/pwrdwn/csl_pwrdwnOpen.c
adildahlan/BE-thesis-Repo-McsDspRealtimeFeedback
fd61a78401bde72b0fb0d5df32f2fd1cbb631aeb
[ "BSD-2-Clause" ]
null
null
null
DSP/TI-Header/csl_c6455_src/src/pwrdwn/csl_pwrdwnOpen.c
adildahlan/BE-thesis-Repo-McsDspRealtimeFeedback
fd61a78401bde72b0fb0d5df32f2fd1cbb631aeb
[ "BSD-2-Clause" ]
null
null
null
DSP/TI-Header/csl_c6455_src/src/pwrdwn/csl_pwrdwnOpen.c
adildahlan/BE-thesis-Repo-McsDspRealtimeFeedback
fd61a78401bde72b0fb0d5df32f2fd1cbb631aeb
[ "BSD-2-Clause" ]
1
2020-05-14T00:50:50.000Z
2020-05-14T00:50:50.000Z
/* ============================================================================ * Copyright (c) Texas Instruments Inc 2002, 2003, 2004, 2005 * * Use of this software is controlled by the terms and conditions found in the * license agreement under which this software has been supplied. * ============================================================================ */ /** ============================================================================ * @file csl_pwrdwnOpen.c * * @path $(CSLPATH)\src\pwrdwn * * @desc File for functional layer of CSL API CSL_pwrdwnOpen () * */ /* ============================================================================= * Revision History * =============== * 16-Jul-2004 Ruchika Kharwar File Created * ============================================================================= */ #include <csl_pwrdwn.h> /** ============================================================================ * @b CSL_ pwrdwnOpen * * @b Description * @n This function populates the peripheral data object for the PWRDWN * instance and returns a handle to the instance. * The open call sets up the data structures for the particular instance * of PWRDWN device. The device can be re-opened anytime after it has been * normally closed if so required. The handle returned by this call is * input as an essential argument for rest of the APIs described * for this module. * * @b Arguments * @verbatim pwrdwnObj Pointer to PWRDWN object. pwrdwnNum Instance of pwrdwn CSL to be opened. There are three instance of the PWRDWN available. So, the value for this parameter will be based on the instance. pPwrdwnParam Module specific parameters. status Status of the function call @endverbatim * * <b> Return Value </b> CSL_pwrdwnHandle * @n Valid pwrdwn handle will be returned if * status value is equal to CSL_SOK. * * <b> Pre Condition </b> * @n CSL_pwrdwnInit(), CSL_pwrdwnOpen()must be opened prior to this call * * <b> Post Condition </b> * @n 1. The status is returned in the status variable. If status * returned is * @li CSL_SOK Valid pwrdwn handle is returned * @li CSL_ESYS_FAIL The pwrdwn instance is invalid * @li CSL_ESYS_INVPARAMS Invalid Parameters * * 2. pwrdwn object structure is populated * * @b Modifies * @n 1. The status variable * * 2. pwrdwn object structure * * @b Example @verbatim CSL_PwrdwnObj pwrObj; CSL_PwrdwnConfig pwrConfig; CSL_PwrdwnHandle hPwr; // Init Module ... if (CSL_pwrdwnInit(NULL) != CSL_SOK) exit; // Opening a handle for the Module hPwr = CSL_pwrdwnOpen (&pwrObj, CSL_PWRDWN, NULL, NULL); // Setup the arguments fof the Config structure ... @endverbatim * ============================================================================ */ #pragma CODE_SECTION (CSL_pwrdwnOpen, ".text:csl_section:pwrdwn"); CSL_PwrdwnHandle CSL_pwrdwnOpen ( CSL_PwrdwnObj *pPwrdwnObj, CSL_InstNum pwrdwnNum, CSL_PwrdwnParam *pPwrdwnParam, CSL_Status *pStatus ) { CSL_PwrdwnBaseAddress baseAddress; CSL_PwrdwnHandle hPwrdwn = (CSL_PwrdwnHandle)NULL; if (pStatus == NULL) { /* do nothing : already the module is initialized to NULL */ } else if (pPwrdwnObj == NULL) { *pStatus = CSL_ESYS_INVPARAMS; } else { *pStatus = CSL_pwrdwnGetBaseAddress(pwrdwnNum, pPwrdwnParam, &baseAddress); if (*pStatus == CSL_SOK) { pPwrdwnObj->pdcRegs = baseAddress.regs; pPwrdwnObj->l2pwrdwnRegs = baseAddress.l2pwrdwnRegs; pPwrdwnObj->instNum = (CSL_InstNum)pwrdwnNum; hPwrdwn = (CSL_PwrdwnHandle)pPwrdwnObj; } else { pPwrdwnObj->pdcRegs = (CSL_PdcRegsOvly)NULL; pPwrdwnObj->l2pwrdwnRegs = NULL; pPwrdwnObj->instNum = (CSL_InstNum)-1; } } return (hPwrdwn); }
34.795276
84
0.515049
[ "object" ]
26c39a96f5300d0056f79aa414a89e6133cc2198
6,263
h
C
src/edu/princeton/cs/algs4/diedge.h
goffersoft/algs4cc
009c65202472634514d6b7f6fd5fef852a5b239e
[ "MIT" ]
null
null
null
src/edu/princeton/cs/algs4/diedge.h
goffersoft/algs4cc
009c65202472634514d6b7f6fd5fef852a5b239e
[ "MIT" ]
null
null
null
src/edu/princeton/cs/algs4/diedge.h
goffersoft/algs4cc
009c65202472634514d6b7f6fd5fef852a5b239e
[ "MIT" ]
null
null
null
/****************************************************************************** * Dependencies: none * * code to represent a directed edge in a graph. * ******************************************************************************/ #ifndef __DIEDGE_H__ #define __DIEDGE_H__ #include <iostream> #include <sstream> #include <string> #include <stdexcept> #include "object.h" #include "edge.h" namespace edu { namespace princeton { namespace cs { namespace algs4 { using std::ostream; using std::istream; using std::cin; using std::endl; using std::string; using std::stringstream; using edu::princeton::cs::algs4::edge_base; using com::goffersoft::core::object; /** ** the diedge_base class represents a ** directed edge in a graph. Each edge consists of two integers ** (naming the two vertices). The data type ** provides methods for accessing the two endpoints of the edge ** cmp_by_<>_vertex methods compares 2 edges by ** ascending order of vertex. ** ** Memory <= sizeof(edge) (8 bytes) ** This is am immutable class. **/ class diedge_base { public : using diedge_type = diedge_base; using edge_type = edge_base; using vertex_type = edge_type::vertex_type; diedge_base(const vertex_type& v, const vertex_type& w) : e(v, w) {} diedge_base(const edge_type& e) : e(e) {} diedge_base(istream& is = cin) : e(is) {} const vertex_type get_from() const { return e.get_first(); } const vertex_type get_to() const { return e.get_second(); } operator edge_type() const { return e; } bool equals(const diedge_type& that) const { return e.equals(that.e); } operator string() const { stringstream ss; ss << e.get_first() << " -> " << e.get_second(); return ss.str(); } bool operator ==(const diedge_type& that) const { if(this == &that) return true; return (e == that.e); } bool operator !=(const diedge_type& that) const { return !(*this == that); } friend ostream& operator <<(ostream& os, const diedge_type& e) { return os << string(e); } static int32_t cmp_by_first_vertex( const diedge_type& lhs, const diedge_type& rhs) { return edge_type::cmp_by_first_vertex(lhs, rhs); } static int32_t cmp_by_second_vertex( const diedge_type& lhs, const diedge_type& rhs) { return edge_type::cmp_by_second_vertex(lhs, rhs); } protected : const edge_type& get_edge() const { return e; } private : edge_type e; }; /** ** The diedge class represents a directed edge as ** a set of 2 vertices. ** Each edge consists of two integers (naming the two vertices). ** The data type provides methods for accessing the two endpoints ** of the edge. ** the diedge class derives from the diedge_base ** class and the object class. ** the object class provides the =, !=, <, >, <=, >= string ** operators. ** the diedge_base class provides data related ** to the end-points. ** the diedge class allows you to change the compare by ** function that would then change the behavior of the <, >, ... ** operations. ** ** Memory <= sizeof(diedge_base)(8) + 8 + 8. **/ class diedge : public diedge_base, public object { public : using object::operator string; using object::equals; using object::operator ==; using object::operator !=; using diedge_type = diedge; using base_edge_type = diedge_base; using cmp_func_type = int32_t(const base_edge_type&, const base_edge_type&); diedge(const vertex_type& v, const vertex_type& w) : diedge_base(v, w) {} diedge(const edge_type& e) : diedge_base(e){} diedge(istream& is = cin) : diedge_base(is) {} cmp_func_type& get_cmp_func() const { return *cmp_func; } void set_cmp_func(cmp_func_type& cmp_func) { this->cmp_func = &cmp_func; } int32_t cmp(const diedge_type& that) const { return cmp_func(*this, that); } protected : bool is_equal(const object& obj) const override { const diedge_type& that = static_cast<const diedge_type&>(obj); return diedge_base::equals(that); } int32_t cmp(const object& obj) const override { const diedge_type& that = static_cast<const diedge_type&>(obj); return cmp(that); } string to_string() const override { return diedge_base::operator string(); } private : cmp_func_type* cmp_func = &cmp_by_first_vertex; }; } //edu } //princeton } //cs } //algs4 /****************************************************************************** * Copyright 2016, Prakash Easwar. * * This file is part of algs4.so, ported to c++ from java * * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne, * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X. * http://algs4.cs.princeton.edu * * algs4.so 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 of the License, or * (at your option) any later version. * * algs4.so 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 algs4.so. If not, see http://www.gnu.org/licenses. ******************************************************************************/ #endif /* __DIEDGE_H__ */
28.729358
80
0.563628
[ "object" ]
26c55de45ccf4b41f1bbe3ebf57f5c8a97f1fc57
439
h
C
system/include/test_manager.h
ivlaryushkin/testsystem
074f925b83282dc3e75f1dd337d379da21498593
[ "MIT" ]
3
2020-06-14T12:37:28.000Z
2021-02-21T21:59:09.000Z
system/include/test_manager.h
ivlaryushkin/testsystem
074f925b83282dc3e75f1dd337d379da21498593
[ "MIT" ]
null
null
null
system/include/test_manager.h
ivlaryushkin/testsystem
074f925b83282dc3e75f1dd337d379da21498593
[ "MIT" ]
1
2021-02-18T06:49:42.000Z
2021-02-18T06:49:42.000Z
#pragma once #include <vector> #include <string> #include "test.h" #include "test_set.h" class TestManager { public: TestManager(int argc, char** argv); void AddBenchmarkSetTest(TestSet set); void AddBenchmarkTest(Test test); void AddValidationSetTest(TestSet set); void AddValidationTest(Test test); void Run(); void ClearRun(); private: std::vector<TestSet> benchmark_sets_; std::vector<TestSet> validation_sets_; };
20.904762
41
0.740319
[ "vector" ]
26c785b94760de29c64e7f19bc0b87cee33f5bae
3,531
h
C
wrappers/7.0.0/vtkSelectionSourceWrap.h
axkibe/node-vtk
900ad7b5500f672519da5aa24c99aa5a96466ef3
[ "BSD-3-Clause" ]
6
2016-02-03T12:48:36.000Z
2020-09-16T15:07:51.000Z
wrappers/7.0.0/vtkSelectionSourceWrap.h
axkibe/node-vtk
900ad7b5500f672519da5aa24c99aa5a96466ef3
[ "BSD-3-Clause" ]
4
2016-02-13T01:30:43.000Z
2020-03-30T16:59:32.000Z
wrappers/7.0.0/vtkSelectionSourceWrap.h
axkibe/node-vtk
900ad7b5500f672519da5aa24c99aa5a96466ef3
[ "BSD-3-Clause" ]
null
null
null
/* this file has been autogenerated by vtkNodeJsWrap */ /* editing this might proof futile */ #ifndef NATIVE_EXTENSION_VTK_VTKSELECTIONSOURCEWRAP_H #define NATIVE_EXTENSION_VTK_VTKSELECTIONSOURCEWRAP_H #include <nan.h> #include <vtkSmartPointer.h> #include <vtkSelectionSource.h> #include "vtkSelectionAlgorithmWrap.h" #include "../../plus/plus.h" class VtkSelectionSourceWrap : public VtkSelectionAlgorithmWrap { public: using Nan::ObjectWrap::Wrap; static void Init(v8::Local<v8::Object> exports); static void InitPtpl(); static void ConstructorGetter( v8::Local<v8::String> property, const Nan::PropertyCallbackInfo<v8::Value>& info); VtkSelectionSourceWrap(vtkSmartPointer<vtkSelectionSource>); VtkSelectionSourceWrap(); ~VtkSelectionSourceWrap( ); static Nan::Persistent<v8::FunctionTemplate> ptpl; private: static void New(const Nan::FunctionCallbackInfo<v8::Value>& info); static void AddLocation(const Nan::FunctionCallbackInfo<v8::Value>& info); static void AddThreshold(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetArrayComponent(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetArrayName(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetClassName(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetCompositeIndex(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetContainingCells(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetContentType(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetFieldType(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetHierarchicalIndex(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetHierarchicalLevel(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetInverse(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetQueryString(const Nan::FunctionCallbackInfo<v8::Value>& info); static void IsA(const Nan::FunctionCallbackInfo<v8::Value>& info); static void NewInstance(const Nan::FunctionCallbackInfo<v8::Value>& info); static void RemoveAllBlocks(const Nan::FunctionCallbackInfo<v8::Value>& info); static void RemoveAllIDs(const Nan::FunctionCallbackInfo<v8::Value>& info); static void RemoveAllLocations(const Nan::FunctionCallbackInfo<v8::Value>& info); static void RemoveAllStringIDs(const Nan::FunctionCallbackInfo<v8::Value>& info); static void RemoveAllThresholds(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SafeDownCast(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetArrayComponent(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetArrayName(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetCompositeIndex(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetContainingCells(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetContentType(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetFieldType(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetHierarchicalIndex(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetHierarchicalLevel(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetInverse(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetQueryString(const Nan::FunctionCallbackInfo<v8::Value>& info); #ifdef VTK_NODE_PLUS_VTKSELECTIONSOURCEWRAP_CLASSDEF VTK_NODE_PLUS_VTKSELECTIONSOURCEWRAP_CLASSDEF #endif }; #endif
49.732394
85
0.788445
[ "object" ]
26daed9c8748b223278c6728344cd64a322a865c
358
h
C
src/guis/GuiRenderer.h
NoXeDev/NoxEngine
82e8832a85ebe3d4dd9526d33dd2c204e9746b17
[ "MIT" ]
3
2021-04-10T07:11:18.000Z
2021-06-10T13:27:17.000Z
src/guis/GuiRenderer.h
NoXeDev/NoxEngine
82e8832a85ebe3d4dd9526d33dd2c204e9746b17
[ "MIT" ]
null
null
null
src/guis/GuiRenderer.h
NoXeDev/NoxEngine
82e8832a85ebe3d4dd9526d33dd2c204e9746b17
[ "MIT" ]
null
null
null
#pragma once #include "../model/RawModel.h" #include "../renderEngine/Loader.h" #include "GuiTexture.h" #include "GuiShader.h" #include <vector> class GuiRenderer { private: RawModel *quad; GuiShader *shader; public: GuiRenderer(Loader* loader); void render(std::vector<GuiTexture*> *guis); void cleanUp(); };
22.375
52
0.636872
[ "render", "vector", "model" ]
c1595345b303cfae51cd8eeaefc54d9b55699069
3,232
h
C
src/gpe/gpe_tiles.h
jaymicrocode/Game-Pencil-Engine
28501fdf21ad7b3ff2ac7912e6f7a988a9ace7e4
[ "MIT" ]
null
null
null
src/gpe/gpe_tiles.h
jaymicrocode/Game-Pencil-Engine
28501fdf21ad7b3ff2ac7912e6f7a988a9ace7e4
[ "MIT" ]
null
null
null
src/gpe/gpe_tiles.h
jaymicrocode/Game-Pencil-Engine
28501fdf21ad7b3ff2ac7912e6f7a988a9ace7e4
[ "MIT" ]
null
null
null
/* gpe_tiles.h This file is part of: GAME PENCIL ENGINE https://www.pawbyte.com/gamepencilengine Copyright (c) 2014-2020 Nathan Hurde, Chase Lee. Copyright (c) 2014-2020 PawByte LLC. Copyright (c) 2014-2020 Game Pencil Engine contributors ( Contributors Page ) 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. -Game Pencil Engine <https://www.pawbyte.com/gamepencilengine> */ #ifndef gpe_tiles_h #define gpe_tiles_h #include "gpe_branch.h" #include "gpe_shapes.h" #include "gpe_runtime.h" namespace gpe { const int tile_default_width = 32; const int tile_default_height = 32; class layer_game_tile { private: gpe::shape_rect * tileBox; int xCoord; int yCoord; public: int tset; int tileIdNumb; int tSetPos ; int tileLayer; int tileType; bool isSolid; bool drewBefore; layer_game_tile(); ~layer_game_tile(); int get_type(); void update_box ( int xNew, int yNew, int wNew, int hNew); void render_self( gpe::shape_rect * cam ); void render_self_auto( gpe::shape_rect * cam ); }; class layer_tile_map { private: int gridWidth, gridHeight; int tileWidth, tileHeight; int tileAmountX; int tileAmountY; int prevTileAmountX; int prevTileAmountY; std::vector< layer_game_tile *> layerTiles; public: int xOffset, yOffset; layer_tile_map(); ~layer_tile_map(); void clear_tiles(); void create_new_map ( int newTX, int newTY); int find_tile ( int xPos, int yPos ); int find_tile_in_box( int x1, int y1, int x2, int y2 ); bool find_matching_tile ( int xPos, int yPos, int tileTypeToSearchFor ); bool find_matching_tile_in_box( int x1, int y1, int x2, int y2, int tileTypeToSearchFor); layer_game_tile * get_tile_at ( int xIn, int yIn ); int get_map_size(); }; } #endif //gpe_tiles
34.382979
106
0.638923
[ "vector" ]
c15af3933e8352d44bcfc76c90efdc06058510ca
1,398
h
C
include/navier_stokes.h
jerluebke/cp_navier_stokes
3ee57d6dd02c7fff51737b20252ef24907635aa8
[ "MIT" ]
1
2021-04-06T08:03:40.000Z
2021-04-06T08:03:40.000Z
include/navier_stokes.h
jerluebke/cp_navier_stokes
3ee57d6dd02c7fff51737b20252ef24907635aa8
[ "MIT" ]
null
null
null
include/navier_stokes.h
jerluebke/cp_navier_stokes
3ee57d6dd02c7fff51737b20252ef24907635aa8
[ "MIT" ]
1
2020-12-17T13:34:39.000Z
2020-12-17T13:34:39.000Z
#pragma once #include "fftw3.h" #define SQUARE(x) (x)*(x) #define REAL 0 #define IMAG 1 typedef struct Params { const size_t Nx, Ny; const double dt, nu; } Params; typedef struct PDE { size_t Nx, Ny, /* sizes of real and complex arrays */ Nkx, Nky, Ntot, ktot; double dt; /* time step */ double nu; /* viscosity parameter */ double *o, /* omega */ *kx, *ky, /* wave numbers, k-space */ *ksq, /* k spared, i.e. |kx|^2 + |ky|^2 */ *utmp, /* helper arrays for `double *rhs` */ *prop_full, /* helper array for propagator */ *prop_pos_half, *prop_neg_half; fftw_complex *ohat, /* fourier transform of omega */ *_ohat, /* backup of ohat, since reverse dft doesn't preserve input */ *uhat, /* fourier transform of utmp */ *res; /* helper array for `double *rhs` */ unsigned char *mask; /* mask array for anti-aliasing */ fftw_plan ohat_to_o, uhat_to_u, o_to_ohat, u_to_uhat; } PDE; PDE *init(const Params, const double *); void cleanup(PDE *); double *time_step(unsigned int, PDE *); double *linspace(double, double, size_t, double *);
31.066667
91
0.502146
[ "transform" ]
c161b73cb0cf5c01cdb7f144f45e2274036efb94
52,446
h
C
Configs/Repetier-091/Configuration.h
Nightfly1704/Gen7-_ExtensionBoard_LCD_SD_FAN
53ff89868b1a82e51155ed57c92ab5bb64ae3240
[ "Apache-2.0" ]
2
2015-09-24T17:11:34.000Z
2022-01-27T11:58:23.000Z
Configs/Repetier-091/Configuration.h
Nightfly1704/Gen7-_ExtensionBoard_LCD_SD_FAN
53ff89868b1a82e51155ed57c92ab5bb64ae3240
[ "Apache-2.0" ]
1
2021-04-13T13:12:12.000Z
2021-04-13T13:12:12.000Z
Configs/Repetier-091/Configuration.h
Nightfly1704/Gen7-_ExtensionBoard_LCD_SD_FAN
53ff89868b1a82e51155ed57c92ab5bb64ae3240
[ "Apache-2.0" ]
null
null
null
/* This file is part of Repetier-Firmware. Repetier-Firmware 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 of the License, or (at your option) any later version. Repetier-Firmware 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 Repetier-Firmware. If not, see <http://www.gnu.org/licenses/>. */ #ifndef CONFIGURATION_H #define CONFIGURATION_H /* Some words on units: From 0.80 onwards the units used are unified for easier configuration, watch out when transfering from older configs! Speed is in mm/s Acceleration in mm/s^2 Temperature is in degrees celsius ########################################################################################## ## IMPORTANT ## ########################################################################################## For easy configuration, the default settings enable parameter storage in EEPROM. This means, after the first upload many variables can only be changed using the special M commands as described in the documentation. Changing these values in the configuration.h file has no effect. Parameters overriden by EEPROM settings are calibartion values, extruder values except thermistor tables and some other parameter likely to change during usage like advance steps or ops mode. To override EEPROM settings with config settings, set EEPROM_MODE 0 */ // BASIC SETTINGS: select your board type, thermistor type, axis scaling, and endstop configuration /** Number of extruders. Maximum 6 extruders. */ #define NUM_EXTRUDER 1 //// The following define selects which electronics board you have. Please choose the one that matches your setup // Gen3 PLUS for RepRap Motherboard V1.2 = 21 // MEGA/RAMPS up to 1.2 = 3 // RAMPS 1.3/RAMPS 1.4 = 33 // Azteeg X3 = 34 // Gen6 = 5 // Gen6 deluxe = 51 // Sanguinololu up to 1.1 = 6 // Sanguinololu 1.2 and above = 62 // Melzi board = 63 // Define REPRAPPRO_HUXLEY if you have one for correct HEATER_1_PIN assignment! // Gen7 1.1 till 1.3.x = 7 // Gen7 1.4.1 and later = 71 // Sethi 3D_1 = 72 // Teensylu (at90usb) = 8 // requires Teensyduino // Printrboard (at90usb) = 9 // requires Teensyduino // Foltyn 3D Master = 12 // MegaTronics 1.0 = 70 // Megatronics 2.0 = 701 // RUMBA = 80 // Get it from reprapdiscount // FELIXprinters = 101 // Rambo = 301 // PiBot for Repetier V1.0-1.3= 314 // PiBot for Repetier V1.4 = 315 // Sanguish Beta = 501 #define MOTHERBOARD 71 #include "pins.h" // Override pin definions from pins.h //#define FAN_PIN 4 // Extruder 2 uses the default fan output, so move to an other pin //#define EXTERNALSERIAL use Arduino serial library instead of build in. Requires more ram, has only 63 byte input buffer. // Uncomment the following line if you are using arduino compatible firmware made for Arduino version earlier then 1.0 // If it is incompatible you will get compiler errors about write functions not beeing compatible! //#define COMPAT_PRE1 /* Define the type of axis movements needed for your printer. The typical case is a full cartesian system where x, y and z moves are handled by separate motors. 0 = full cartesian system, xyz have seperate motors. 1 = z axis + xy H-gantry (x_motor = x+y, y_motor = x-y) 2 = z axis + xy H-gantry (x_motor = x+y, y_motor = y-x) 3 = Delta printers (Rostock, Kossel, RostockMax, Cerberus, etc) 4 = Tuga printer (Scott-Russell mechanism) 5 = Bipod system (not implemented) Cases 1 and 2 cover all needed xy H gantry systems. If you get results mirrored etc. you can swap motor connections for x and y. If a motor turns in the wrong direction change INVERT_X_DIR or INVERT_Y_DIR. */ #define DRIVE_SYSTEM 0 // ########################################################################################## // ## Calibration ## // ########################################################################################## /** Drive settings for the Delta printers */ #if DRIVE_SYSTEM==3 // *************************************************** // *** These parameter are only for Delta printers *** // *************************************************** /** \brief Delta drive type: 0 - belts and pulleys, 1 - filament drive */ #define DELTA_DRIVE_TYPE 0 #if DELTA_DRIVE_TYPE == 0 /** \brief Pitch in mm of drive belt. GT2 = 2mm */ #define BELT_PITCH 2 /** \brief Number of teeth on X, Y and Z tower pulleys */ #define PULLEY_TEETH 20 #define PULLEY_CIRCUMFERENCE (BELT_PITCH * PULLEY_TEETH) #elif DELTA_DRIVE_TYPE == 1 /** \brief Filament pulley diameter in milimeters */ #define PULLEY_DIAMETER 10 #define PULLEY_CIRCUMFERENCE (PULLEY_DIAMETER * 3.1415927) #endif /** \brief Steps per rotation of stepper motor */ #define STEPS_PER_ROTATION 200 /** \brief Micro stepping rate of X, Y and Y tower stepper drivers */ #define MICRO_STEPS 16 // Calculations #define AXIS_STEPS_PER_MM ((float)(MICRO_STEPS * STEPS_PER_ROTATION) / PULLEY_CIRCUMFERENCE) #define XAXIS_STEPS_PER_MM AXIS_STEPS_PER_MM #define YAXIS_STEPS_PER_MM AXIS_STEPS_PER_MM #define ZAXIS_STEPS_PER_MM AXIS_STEPS_PER_MM #else // ******************************************************* // *** These parameter are for all other printer types *** // ******************************************************* /** Drive settings for printers with cartesian drive systems */ /** \brief Number of steps for a 1mm move in x direction. For xy gantry use 2*belt moved! Overridden if EEPROM activated. */ #define XAXIS_STEPS_PER_MM 80 /** \brief Number of steps for a 1mm move in y direction. For xy gantry use 2*belt moved! Overridden if EEPROM activated.*/ #define YAXIS_STEPS_PER_MM 80 /** \brief Number of steps for a 1mm move in z direction Overridden if EEPROM activated.*/ #define ZAXIS_STEPS_PER_MM 400 #endif // ########################################################################################## // ## Extruder configuration ## // ########################################################################################## // for each extruder, fan will stay on until extruder temperature is below this value #define EXTRUDER_FAN_COOL_TEMP 50 #define EXT0_X_OFFSET 0 #define EXT0_Y_OFFSET 0 // for skeinforge 40 and later, steps to pull the plasic 1 mm inside the extruder, not out. Overridden if EEPROM activated. #define EXT0_STEPS_PER_MM 380 //385 // What type of sensor is used? // 1 is 100k thermistor (Epcos B57560G0107F000 - RepRap-Fab.org and many other) // 2 is 200k thermistor // 3 is mendel-parts thermistor (EPCOS G550) // 4 is 10k thermistor // 8 is ATC Semitec 104GT-2 // 5 is userdefined thermistor table 0 // 6 is userdefined thermistor table 1 // 7 is userdefined thermistor table 2 // 50 is userdefined thermistor table 0 for PTC thermistors // 51 is userdefined thermistor table 0 for PTC thermistors // 52 is userdefined thermistor table 0 for PTC thermistors // 60 is AD8494, AD8495, AD8496 or AD8497 (5mV/degC and 1/4 the price of AD595 but only MSOT_08 package) // 97 Generic thermistor table 1 // 98 Generic thermistor table 2 // 99 Generic thermistor table 3 // 100 is AD595 // 101 is MAX6675 // 102 is MAX31855 #define EXT0_TEMPSENSOR_TYPE 1 // Analog input pin for reading temperatures or pin enabling SS for MAX6675 #define EXT0_TEMPSENSOR_PIN TEMP_0_PIN // Which pin enables the heater #define EXT0_HEATER_PIN HEATER_0_PIN #define EXT0_STEP_PIN E0_STEP_PIN #define EXT0_DIR_PIN E0_DIR_PIN // set to false/true for normal / inverse direction #define EXT0_INVERSE false #define EXT0_ENABLE_PIN E0_ENABLE_PIN // For Inverting Stepper Enable Pins (Active Low) use 0, Non Inverting (Active High) use 1 #define EXT0_ENABLE_ON false // The following speed settings are for skeinforge 40+ where e is the // length of filament pulled inside the heater. For repsnap or older // skeinforge use higher values. // Overridden if EEPROM activated. #define EXT0_MAX_FEEDRATE 30 // Feedrate from halted extruder in mm/s // Overridden if EEPROM activated. #define EXT0_MAX_START_FEEDRATE 10 // Acceleration in mm/s^2 // Overridden if EEPROM activated. #define EXT0_MAX_ACCELERATION 6000 /** Type of heat manager for this extruder. - 0 = Simply switch on/off if temperature is reached. Works always. - 1 = PID Temperature control. Is better but needs good PID values. Defaults are a good start for most extruder. - 3 = Dead-time control. PID_P becomes dead-time in seconds. Overridden if EEPROM activated. */ #define EXT0_HEAT_MANAGER 1 /** Wait x seconds, after reaching target temperature. Only used for M109. Overridden if EEPROM activated. */ #define EXT0_WATCHPERIOD 1 /** \brief The maximum value, I-gain can contribute to the output. A good value is slightly higher then the output needed for your temperature. Values for starts: 130 => PLA for temperatures from 170-180 deg C 180 => ABS for temperatures around 240 deg C The precise values may differ for different nozzle/resistor combination. Overridden if EEPROM activated. */ #define EXT0_PID_INTEGRAL_DRIVE_MAX 140 /** \brief lower value for integral part The I state should converge to the exact heater output needed for the target temperature. To prevent a long deviation from the target zone, this value limits the lower value. A good start is 30 lower then the optimal value. You need to leave room for cooling. Overridden if EEPROM activated. */ #define EXT0_PID_INTEGRAL_DRIVE_MIN 60 /** P-gain. Overridden if EEPROM activated. */ #define EXT0_PID_P 24 /** I-gain. Overridden if EEPROM activated. */ #define EXT0_PID_I 0.88 /** Dgain. Overridden if EEPROM activated.*/ #define EXT0_PID_D 80 // maximum time the heater is can be switched on. Max = 255. Overridden if EEPROM activated. #define EXT0_PID_MAX 255 /** \brief Faktor for the advance algorithm. 0 disables the algorithm. Overridden if EEPROM activated. K is the factor for the quadratic term, which is normally disabled in newer versions. If you want to use the quadratic factor make sure ENABLE_QUADRATIC_ADVANCE is defined. L is the linear factor and seems to be working better then the quadratic dependency. */ #define EXT0_ADVANCE_K 0.0f #define EXT0_ADVANCE_L 0.0f /* Motor steps to remove backlash for advance alorithm. These are the steps needed to move the motor cog in reverse direction until it hits the driving cog. Direct drive extruder need 0. */ #define EXT0_ADVANCE_BACKLASH_STEPS 0 /** \brief Temperature to retract filament when extruder is heating up. Overridden if EEPROM activated. */ #define EXT0_WAIT_RETRACT_TEMP 150 /** \brief Units (mm/inches) to retract filament when extruder is heating up. Overridden if EEPROM activated. Set to 0 to disable. */ #define EXT0_WAIT_RETRACT_UNITS 0 /** You can run any gcode command on extruder deselect/select. Seperate multiple commands with a new line \n. That way you can execute some mechanical components needed for extruder selection or retract filament or whatever you need. The codes are only executed for multiple extruder when changing the extruder. */ #define EXT0_SELECT_COMMANDS "M117 Extruder 1" #define EXT0_DESELECT_COMMANDS "" /** The extruder cooler is a fan to cool the extruder when it is heating. If you turn the etxruder on, the fan goes on. */ #define EXT0_EXTRUDER_COOLER_PIN -1 /** PWM speed for the cooler fan. 0=off 255=full speed */ #define EXT0_EXTRUDER_COOLER_SPEED 255 // =========================== Configuration for second extruder ======================== #define EXT1_X_OFFSET 10 #define EXT1_Y_OFFSET 0 // for skeinforge 40 and later, steps to pull the plasic 1 mm inside the extruder, not out. Overridden if EEPROM activated. #define EXT1_STEPS_PER_MM 373 // What type of sensor is used? // 1 is 100k thermistor (Epcos B57560G0107F000 - RepRap-Fab.org and many other) // 2 is 200k thermistor // 3 is mendel-parts thermistor (EPCOS G550) // 4 is 10k thermistor // 5 is userdefined thermistor table 0 // 6 is userdefined thermistor table 1 // 7 is userdefined thermistor table 2 // 8 is ATC Semitec 104GT-2 // 50 is userdefined thermistor table 0 for PTC thermistors // 51 is userdefined thermistor table 0 for PTC thermistors // 52 is userdefined thermistor table 0 for PTC thermistors // 60 is AD8494, AD8495, AD8496 or AD8497 (5mV/degC and 1/4 the price of AD595 but only MSOT_08 package) // 97 Generic thermistor table 1 // 98 Generic thermistor table 2 // 99 Generic thermistor table 3 // 100 is AD595 // 101 is MAX6675 #define EXT1_TEMPSENSOR_TYPE 3 // Analog input pin for reading temperatures or pin enabling SS for MAX6675 #define EXT1_TEMPSENSOR_PIN TEMP_2_PIN // Which pin enables the heater #define EXT1_HEATER_PIN HEATER_2_PIN #define EXT1_STEP_PIN E1_STEP_PIN #define EXT1_DIR_PIN E1_DIR_PIN // set to 0/1 for normal / inverse direction #define EXT1_INVERSE false #define EXT1_ENABLE_PIN E1_ENABLE_PIN // For Inverting Stepper Enable Pins (Active Low) use 0, Non Inverting (Active High) use 1 #define EXT1_ENABLE_ON false // The following speed settings are for skeinforge 40+ where e is the // length of filament pulled inside the heater. For repsnap or older // skeinforge use heigher values. // Overridden if EEPROM activated. #define EXT1_MAX_FEEDRATE 25 // Feedrate from halted extruder in mm/s // Overridden if EEPROM activated. #define EXT1_MAX_START_FEEDRATE 12 // Acceleration in mm/s^2 // Overridden if EEPROM activated. #define EXT1_MAX_ACCELERATION 10000 /** Type of heat manager for this extruder. - 0 = Simply switch on/off if temperature is reached. Works always. - 1 = PID Temperature control. Is better but needs good PID values. Defaults are a good start for most extruder. Overridden if EEPROM activated. */ #define EXT1_HEAT_MANAGER 1 /** Wait x seconds, after reaching target temperature. Only used for M109. Overridden if EEPROM activated. */ #define EXT1_WATCHPERIOD 1 /** \brief The maximum value, I-gain can contribute to the output. A good value is slightly higher then the output needed for your temperature. Values for starts: 130 => PLA for temperatures from 170-180 deg C 180 => ABS for temperatures around 240 deg C The precise values may differ for different nozzle/resistor combination. Overridden if EEPROM activated. */ #define EXT1_PID_INTEGRAL_DRIVE_MAX 130 /** \brief lower value for integral part The I state should converge to the exact heater output needed for the target temperature. To prevent a long deviation from the target zone, this value limits the lower value. A good start is 30 lower then the optimal value. You need to leave room for cooling. Overridden if EEPROM activated. */ #define EXT1_PID_INTEGRAL_DRIVE_MIN 60 /** P-gain. Overridden if EEPROM activated. */ #define EXT1_PID_P 24 /** I-gain. Overridden if EEPROM activated. */ #define EXT1_PID_I 0.88 /** D-gain. Overridden if EEPROM activated.*/ #define EXT1_PID_D 200 // maximum time the heater is can be switched on. Max = 255. Overridden if EEPROM activated. #define EXT1_PID_MAX 255 /** \brief Faktor for the advance algorithm. 0 disables the algorithm. Overridden if EEPROM activated. K is the factor for the quadratic term, which is normally disabled in newer versions. If you want to use the quadratic factor make sure ENABLE_QUADRATIC_ADVANCE is defined. L is the linear factor and seems to be working better then the quadratic dependency. */ #define EXT1_ADVANCE_K 0.0f #define EXT1_ADVANCE_L 0.0f /* Motor steps to remove backlash for advance alorithm. These are the steps needed to move the motor cog in reverse direction until it hits the driving cog. Direct drive extruder need 0. */ #define EXT1_ADVANCE_BACKLASH_STEPS 0 #define EXT1_WAIT_RETRACT_TEMP 150 #define EXT1_WAIT_RETRACT_UNITS 0 #define EXT1_SELECT_COMMANDS "M117 Extruder 2" #define EXT1_DESELECT_COMMANDS "" /** The extruder cooler is a fan to cool the extruder when it is heating. If you turn the etxruder on, the fan goes on. */ #define EXT1_EXTRUDER_COOLER_PIN -1 /** PWM speed for the cooler fan. 0=off 255=full speed */ #define EXT1_EXTRUDER_COOLER_SPEED 255 /** If enabled you can select the distance your filament gets retracted during a M140 command, after a given temperature is reached. */ #define RETRACT_DURING_HEATUP true /** PID control only works target temperature +/- PID_CONTROL_RANGE. If you get much overshoot at the first temperature set, because the heater is going full power too long, you need to increase this value. For one 6.8 Ohm heater 10 is ok. With two 6.8 Ohm heater use 15. */ #define PID_CONTROL_RANGE 20 /** Prevent extrusions longer then x mm for one command. This is especially important if you abort a print. Then the extrusion poistion might be at any value like 23344. If you then have an G1 E-2 it will roll back 23 meter! */ #define EXTRUDE_MAXLENGTH 100 /** Skip wait, if the extruder temperature is already within x degrees. Only fixed numbers, 0 = off */ #define SKIP_M109_IF_WITHIN 2 /** \brief Set PID scaling PID values assume a usable range from 0-255. This can be further limited to EXT0_PID_MAX by to methods. Set the value to 0: Normal computation, just clip output to EXT0_PID_MAX if computed value is too high. Set value to 1: Scale PID by EXT0_PID_MAX/256 and then clip to EXT0_PID_MAX. If your EXT0_PID_MAX is low, you should prefer the second method. */ #define SCALE_PID_TO_MAX 0 /** Temperature range for target temperature to hold in M109 command. 5 means +/-5 degC Uncomment define to force the temperature into the range for given watchperiod. */ //#define TEMP_HYSTERESIS 5 /** Userdefined thermistor table There are many different thermistors, which can be combined with different resistors. This result in unpredictable number of tables. As a resolution, the user can define one table here, that can be used as type 5 for thermister type in extruder/heated bed definition. Make sure, the number of entries matches the value in NUM_TEMPS_USERTHERMISTOR0. If you span definition over multiple lines, make sure to end each line, except the last, with a backslash. The table format is {{adc1,temp1},{adc2,temp2}...} with increasing adc values. For more informations, read http://hydraraptor.blogspot.com/2007/10/measuring-temperature-easy-way.html If you have a sprinter temperature table, you have to multiply the first value with 4 and the second with 8. This firmware works with increased precision, so the value reads go from 0 to 4095 and the temperature is temperature*8. If you have a PTC thermistor instead of a NTC thermistor, keep the adc values increasing and use themistor types 50-52 instead of 5-7! */ /** Number of entries in the user thermistor table 0. Set to 0 to disable it. */ #define NUM_TEMPS_USERTHERMISTOR0 28 #define USER_THERMISTORTABLE0 {\ {1*4,864*8},{21*4,300*8},{25*4,290*8},{29*4,280*8},{33*4,270*8},{39*4,260*8},{46*4,250*8},{54*4,240*8},{64*4,230*8},{75*4,220*8},\ {90*4,210*8},{107*4,200*8},{128*4,190*8},{154*4,180*8},{184*4,170*8},{221*4,160*8},{265*4,150*8},{316*4,140*8},{375*4,130*8},\ {441*4,120*8},{513*4,110*8},{588*4,100*8},{734*4,80*8},{856*4,60*8},{938*4,40*8},{986*4,20*8},{1008*4,0*8},{1018*4,-20*8} } /** Number of entries in the user thermistor table 1. Set to 0 to disable it. */ #define NUM_TEMPS_USERTHERMISTOR1 0 #define USER_THERMISTORTABLE1 {} /** Number of entries in the user thermistor table 2. Set to 0 to disable it. */ #define NUM_TEMPS_USERTHERMISTOR2 0 #define USER_THERMISTORTABLE2 {} /** If defined, creates a thermistor table at startup. If you don't feel like computing the table on your own, you can use this generic method. It is a simple approximation which may be not as accurate as a good table computed from the reference values in the datasheet. You can increase precision if you use a temperature/resistance for R0/T0, which is near your operating temperature. This will reduce precision for lower temperatures, which are not realy important. The resistors must fit the following schematic: @code VREF ---- R2 ---+--- Termistor ---+-- GND | | +------ R1 -------+ | | +---- Capacitor --+ | V measured @endcode If you don't have R1, set it to 0. The capacitor is for reducing noise from long thermistor cable. If you don't have one, it's OK. If you need the generic table, uncomment the following define. */ //#define USE_GENERIC_THERMISTORTABLE_1 /* Some examples for different thermistors: EPCOS B57560G104+ : R0 = 100000 T0 = 25 Beta = 4036 EPCOS 100K Thermistor (B57560G1104F) : R0 = 100000 T0 = 25 Beta = 4092 ATC Semitec 104GT-2 : R0 = 100000 T0 = 25 Beta = 4267 Honeywell 100K Thermistor (135-104LAG-J01) : R0 = 100000 T0 = 25 Beta = 3974 */ /** Reference Temperature */ #define GENERIC_THERM1_T0 25 /** Resistance at reference temperature */ #define GENERIC_THERM1_R0 100000 /** Beta value of thermistor You can use the beta from the datasheet or compute it yourself. See http://reprap.org/wiki/MeasuringThermistorBeta for more details. */ #define GENERIC_THERM1_BETA 4036 /** Start temperature for generated thermistor table */ #define GENERIC_THERM1_MIN_TEMP -20 /** End Temperature for generated thermistor table */ #define GENERIC_THERM1_MAX_TEMP 300 #define GENERIC_THERM1_R1 0 #define GENERIC_THERM1_R2 4700 // The same for table 2 and 3 if needed //#define USE_GENERIC_THERMISTORTABLE_2 #define GENERIC_THERM2_T0 170 #define GENERIC_THERM2_R0 1042.7 #define GENERIC_THERM2_BETA 4036 #define GENERIC_THERM2_MIN_TEMP -20 #define GENERIC_THERM2_MAX_TEMP 300 #define GENERIC_THERM2_R1 0 #define GENERIC_THERM2_R2 4700 //#define USE_GENERIC_THERMISTORTABLE_3 #define GENERIC_THERM3_T0 170 #define GENERIC_THERM3_R0 1042.7 #define GENERIC_THERM3_BETA 4036 #define GENERIC_THERM3_MIN_TEMP -20 #define GENERIC_THERM3_MAX_TEMP 300 #define GENERIC_THERM3_R1 0 #define GENERIC_THERM3_R2 4700 /** Supply voltage to ADC, can be changed by setting ANALOG_REF below to different value. */ #define GENERIC_THERM_VREF 5 /** Number of entries in generated table. One entry takes 4 bytes. Higher number of entries increase computation time too. Value is used for all generic tables created. */ #define GENERIC_THERM_NUM_ENTRIES 33 // uncomment the following line for MAX6675 support. //#define SUPPORT_MAX6675 // uncomment the following line for MAX31855 support. //#define SUPPORT_MAX31855 // ############# Heated bed configuration ######################## /** \brief Set true if you have a heated bed conected to your board, false if not */ #define HAVE_HEATED_BED true #define HEATED_BED_MAX_TEMP 115 /** Skip M190 wait, if heated bed is already within x degrees. Fixed numbers only, 0 = off. */ #define SKIP_M190_IF_WITHIN 3 // Select type of your heated bed. It's the same as for EXT0_TEMPSENSOR_TYPE // set to 0 if you don't have a heated bed #define HEATED_BED_SENSOR_TYPE 1 /** Analog pin of analog sensor to read temperature of heated bed. */ #define HEATED_BED_SENSOR_PIN TEMP_1_PIN /** \brief Pin to enable heater for bed. */ #define HEATED_BED_HEATER_PIN HEATER_1_PIN // How often the temperature of the heated bed is set (msec) #define HEATED_BED_SET_INTERVAL 5000 /** Heat manager for heated bed: 0 = Bang Bang, fast update 1 = PID controlled 2 = Bang Bang, limited check every HEATED_BED_SET_INTERVAL. Use this with relay-driven beds to save life time 3 = dead time control */ #define HEATED_BED_HEAT_MANAGER 1 /** \brief The maximum value, I-gain can contribute to the output. The precise values may differ for different nozzle/resistor combination. Overridden if EEPROM activated. */ #define HEATED_BED_PID_INTEGRAL_DRIVE_MAX 255 /** \brief lower value for integral part The I state should converge to the exact heater output needed for the target temperature. To prevent a long deviation from the target zone, this value limits the lower value. A good start is 30 lower then the optimal value. You need to leave room for cooling. Overridden if EEPROM activated. */ #define HEATED_BED_PID_INTEGRAL_DRIVE_MIN 80 /** P-gain. Overridden if EEPROM activated. */ #define HEATED_BED_PID_PGAIN 196 /** I-gain Overridden if EEPROM activated.*/ #define HEATED_BED_PID_IGAIN 33.02 /** Dgain. Overridden if EEPROM activated.*/ #define HEATED_BED_PID_DGAIN 290 // maximum time the heater can be switched on. Max = 255. Overridden if EEPROM activated. #define HEATED_BED_PID_MAX 255 // When temperature exceeds max temp, your heater will be switched off. // This feature exists to protect your hotend from overheating accidentally, but *NOT* from thermistor short/failure! #define MAXTEMP 260 /** Extreme values to detect defect thermistors. */ #define MIN_DEFECT_TEMPERATURE -10 #define MAX_DEFECT_TEMPERATURE 300 // ########################################################################################## // ## Endstop configuration ## // ########################################################################################## /* By default all endstops are pulled up to HIGH. You need a pullup if you use a mechanical endstop connected with GND. Set value to false for no pullup on this endstop. */ #define ENDSTOP_PULLUP_X_MIN false #define ENDSTOP_PULLUP_Y_MIN false #define ENDSTOP_PULLUP_Z_MIN true #define ENDSTOP_PULLUP_X_MAX true #define ENDSTOP_PULLUP_Y_MAX true #define ENDSTOP_PULLUP_Z_MAX false //set to true to invert the logic of the endstops #define ENDSTOP_X_MIN_INVERTING false #define ENDSTOP_Y_MIN_INVERTING false #define ENDSTOP_Z_MIN_INVERTING false #define ENDSTOP_X_MAX_INVERTING false #define ENDSTOP_Y_MAX_INVERTING false #define ENDSTOP_Z_MAX_INVERTING false // Set the values true where you have a hardware endstop. The Pin number is taken from pins.h. #define MIN_HARDWARE_ENDSTOP_X false #define MIN_HARDWARE_ENDSTOP_Y false #define MIN_HARDWARE_ENDSTOP_Z true #define MAX_HARDWARE_ENDSTOP_X true #define MAX_HARDWARE_ENDSTOP_Y true #define MAX_HARDWARE_ENDSTOP_Z false //If your axes are only moving in one direction, make sure the endstops are connected properly. //If your axes move in one direction ONLY when the endstops are triggered, set ENDSTOPS_INVERTING to true here //// ADVANCED SETTINGS - to tweak parameters // For Inverting Stepper Enable Pins (Active Low) use 0, Non Inverting (Active High) use 1 #define X_ENABLE_ON 0 #define Y_ENABLE_ON 0 #define Z_ENABLE_ON 0 // Disables axis when it's not being used. #define DISABLE_X false #define DISABLE_Y false #define DISABLE_Z false #define DISABLE_E false // Inverting axis direction #define INVERT_X_DIR false #define INVERT_Y_DIR false #define INVERT_Z_DIR false //// ENDSTOP SETTINGS: // Sets direction of endstops when homing; 1=MAX, -1=MIN #define X_HOME_DIR 1 #define Y_HOME_DIR 1 #define Z_HOME_DIR -1 // Delta robot radius endstop #define max_software_endstop_r false //If true, axis won't move to coordinates less than zero. #define min_software_endstop_x true #define min_software_endstop_y true #define min_software_endstop_z false //If true, axis won't move to coordinates greater than the defined lengths below. #define max_software_endstop_x false #define max_software_endstop_y false #define max_software_endstop_z true // If during homing the endstop is reached, ho many mm should the printer move back for the second try #define ENDSTOP_X_BACK_MOVE 5 #define ENDSTOP_Y_BACK_MOVE 5 #define ENDSTOP_Z_BACK_MOVE 2 // For higher precision you can reduce the speed for the second test on the endstop // during homing operation. The homing speed is divided by the value. 1 = same speed, 2 = half speed #define ENDSTOP_X_RETEST_REDUCTION_FACTOR 2 #define ENDSTOP_Y_RETEST_REDUCTION_FACTOR 2 #define ENDSTOP_Z_RETEST_REDUCTION_FACTOR 2 // When you have several endstops in one circuit you need to disable it after homing by moving a // small amount back. This is also the case with H-belt systems. #define ENDSTOP_X_BACK_ON_HOME 0 #define ENDSTOP_Y_BACK_ON_HOME 0 #define ENDSTOP_Z_BACK_ON_HOME 0 // You can disable endstop checking for print moves. This is needed, if you get sometimes // false signals from your endstops. If your endstops don't give false signals, you // can set it on for safety. #define ALWAYS_CHECK_ENDSTOPS true // maximum positions in mm - only fixed numbers! // For delta robot Z_MAX_LENGTH is the maximum travel of the towers and should be set to the distance between the hotend // and the platform when the printer is at its home position. // If EEPROM is enabled these values will be overidden with the values in the EEPROM #define X_MAX_LENGTH 217 #define Y_MAX_LENGTH 222 #define Z_MAX_LENGTH 220 // Coordinates for the minimum axis. Can also be negative if you want to have the bed start at 0 and the printer can go to the left side // of the bed. Maximum coordinate is given by adding the above X_MAX_LENGTH values. #define X_MIN_POS 0 #define Y_MIN_POS 0 #define Z_MIN_POS 0 // ########################################################################################## // ## Movement settings ## // ########################################################################################## // Microstep setting (Only functional when stepper driver microstep pins are connected to MCU. Currently only works for RAMBO boards #define MICROSTEP_MODES {8,8,8,8,8} // [1,2,4,8,16] // Motor Current setting (Only functional when motor driver current ref pins are connected to a digital trimpot on supported boards) #if MOTHERBOARD==301 #define MOTOR_CURRENT {135,135,135,135,135} // Values 0-255 (RAMBO 135 = ~0.75A, 185 = ~1A) #elif MOTHERBOARD==12 #define MOTOR_CURRENT {35713,35713,35713,35713,35713} // Values 0-65535 (3D Master 35713 = ~1A) #endif /** \brief Number of segments to generate for delta conversions per second of move */ #define DELTA_SEGMENTS_PER_SECOND_PRINT 180 // Move accurate setting for print moves #define DELTA_SEGMENTS_PER_SECOND_MOVE 70 // Less accurate setting for other moves // Delta settings #if DRIVE_SYSTEM==3 /** \brief Delta rod length */ #define DELTA_DIAGONAL_ROD 345 // mm /* =========== Parameter essential for delta calibration =================== C, Y-Axis | |___| CARRIAGE_HORIZONTAL_OFFSET | | \ |_________ X-axis | \ / \ | \ DELTA_DIAGONAL_ROD / \ \ / \ \ Carriage is at printer center! A B \_____/ |--| END_EFFECTOR_HORIZONTAL_OFFSET |----| DELTA_RADIUS |-----------| PRINTER_RADIUS Column angles are measured from X-axis counterclockwise "Standard" positions: alpha_A = 210, alpha_B = 330, alpha_C = 90 */ /** \brief column positions - change only to correct build imperfections! */ #define DELTA_ALPHA_A 210 #define DELTA_ALPHA_B 330 #define DELTA_ALPHA_C 90 /** Correct radius by this value for each column. Perfect builds have 0 everywhere. */ #define DELTA_RADIUS_CORRECTION_A 0 #define DELTA_RADIUS_CORRECTION_B 0 #define DELTA_RADIUS_CORRECTION_C 0 /** \brief Horizontal offset of the universal joints on the end effector (moving platform). */ #define END_EFFECTOR_HORIZONTAL_OFFSET 33 /** \brief Horizontal offset of the universal joints on the vertical carriages. */ #define CARRIAGE_HORIZONTAL_OFFSET 18 /** \brief Printer radius in mm, measured from the center of the print area to the vertical smooth rod. */ #define PRINTER_RADIUS 175 /** \brief Horizontal distance bridged by the diagonal push rod when the end effector is in the center. It is pretty close to 50% of the push rod length (250 mm). */ #define DELTA_RADIUS (PRINTER_RADIUS-END_EFFECTOR_HORIZONTAL_OFFSET-CARRIAGE_HORIZONTAL_OFFSET) /* ========== END Delta calibation data ==============*/ /** When true the delta will home to z max when reset/powered over cord. That way you start with well defined coordinates. If you don't do it, make sure to home first before your first move. */ #define DELTA_HOME_ON_POWER false /** To allow software correction of misaligned endstops, you can set the correction in steps here. If you have EEPROM enabled you can also change the values online and autoleveling will store the results here. */ #define DELTA_X_ENDSTOP_OFFSET_STEPS 0 #define DELTA_Y_ENDSTOP_OFFSET_STEPS 0 #define DELTA_Z_ENDSTOP_OFFSET_STEPS 0 /** \brief Experimental calibration utility for delta printers */ #define SOFTWARE_LEVELING #endif #if DRIVE_SYSTEM == 4 // ========== Tuga special settings ============= /* Radius of the long arm in mm. */ #define DELTA_DIAGONAL_ROD 240 #endif /** \brief Number of delta moves in each line. Moves that exceed this figure will be split into multiple lines. Increasing this figure can use a lot of memory since 7 bytes * size of line buffer * MAX_SELTA_SEGMENTS_PER_LINE will be allocated for the delta buffer. With defaults 7 * 16 * 22 = 2464 bytes. This leaves ~1K free RAM on an Arduino Mega. Used only for nonlinear systems like delta or tuga. */ #define MAX_DELTA_SEGMENTS_PER_LINE 22 /** After x seconds of inactivity, the stepper motors are disabled. Set to 0 to leave them enabled. This helps cooling the Stepper motors between two print jobs. Overridden if EEPROM activated. */ #define STEPPER_INACTIVE_TIME 3000 /** After x seconds of inactivity, the system will go down as far it can. It will at least disable all stepper motors and heaters. If the board has a power pin, it will be disabled, too. Set value to 0 for disabled. Overridden if EEPROM activated. */ #define MAX_INACTIVE_TIME 1800000 /** Maximum feedrate, the system allows. Higher feedrates are reduced to these values. The axis order in all axis related arrays is X, Y, Z Overridden if EEPROM activated. */ #define MAX_FEEDRATE_X 200 #define MAX_FEEDRATE_Y 200 #define MAX_FEEDRATE_Z 5 /** Home position speed in mm/s. Overridden if EEPROM activated. */ #define HOMING_FEEDRATE_X 50 #define HOMING_FEEDRATE_Y 50 #define HOMING_FEEDRATE_Z 4 /** Set order of axis homing. Use HOME_ORDER_XYZ and replace XYZ with your order. */ #define HOMING_ORDER HOME_ORDER_XYZ /* If you have a backlash in both z-directions, you can use this. For most printer, the bed will be pushed down by it's own weight, so this is nearly never needed. */ #define ENABLE_BACKLASH_COMPENSATION false #define Z_BACKLASH 0 #define X_BACKLASH 0 #define Y_BACKLASH 0 /** Comment this to disable ramp acceleration */ #define RAMP_ACCELERATION 1 /** If your stepper needs a longer high signal then given, you can add a delay here. The delay is realized as a simple loop wasting time, which is not available for other computations. So make it as low as possible. For the most common drivers no delay is needed, as the included delay is already enough. */ #define STEPPER_HIGH_DELAY 0 /** The firmware can only handle 16000Hz interrupt frequency cleanly. If you need higher speeds a faster solution is needed, and this is to double/quadruple the steps in one interrupt call. This is like reducing your 1/16th microstepping to 1/8 or 1/4. It is much cheaper then 1 or 3 additional stepper interrupts with all it's overhead. As a result you can go as high as 40000Hz. */ #define STEP_DOUBLER_FREQUENCY 12000 /** If you need frequencies off more then 30000 you definitely need to enable this. If you have only 1/8 stepping enabling this may cause to stall your moves when 20000Hz is reached. */ #define ALLOW_QUADSTEPPING true /** If you reach STEP_DOUBLER_FREQUENCY the firmware will do 2 or 4 steps with nearly no delay. That can be too fast for some printers causing an early stall. */ #define DOUBLE_STEP_DELAY 1 // time in microseconds /** The firmware supports trajectory smoothing. To achieve this, it divides the stepsize by 2, resulting in the double computation cost. For slow movements this is not an issue, but for really fast moves this is too much. The value specified here is the number of clock cycles between a step on the driving axis. If the interval at full speed is below this value, smoothing is disabled for that line.*/ #define MAX_HALFSTEP_INTERVAL 1999 //// Acceleration settings /** \brief X, Y, Z max acceleration in mm/s^2 for printing moves or retracts. Make sure your printer can go that high! Overridden if EEPROM activated. */ #define MAX_ACCELERATION_UNITS_PER_SQ_SECOND_X 1500 #define MAX_ACCELERATION_UNITS_PER_SQ_SECOND_Y 1500 #define MAX_ACCELERATION_UNITS_PER_SQ_SECOND_Z 100 /** \brief X, Y, Z max acceleration in mm/s^2 for travel moves. Overridden if EEPROM activated.*/ #define MAX_TRAVEL_ACCELERATION_UNITS_PER_SQ_SECOND_X 1500 #define MAX_TRAVEL_ACCELERATION_UNITS_PER_SQ_SECOND_Y 1500 #define MAX_TRAVEL_ACCELERATION_UNITS_PER_SQ_SECOND_Z 100 /** \brief Maximum allowable jerk. Caution: This is no real jerk in a physical meaning. The jerk determines your start speed and the maximum speed at the join of two segments. Its unit is mm/s. If the printer is standing still, the start speed is jerk/2. At the join of two segments, the speed difference is limited to the jerk value. Examples: For all examples jerk is assumed as 40. Segment 1: vx = 50, vy = 0 Segment 2: vx = 0, vy = 50 v_diff = sqrt((50-0)^2+(0-50)^2) = 70.71 v_diff > jerk => vx_1 = vy_2 = jerk/v_diff*vx_1 = 40/70.71*50 = 28.3 mm/s at the join Segment 1: vx = 50, vy = 0 Segment 2: vx = 35.36, vy = 35.36 v_diff = sqrt((50-35.36)^2+(0-35.36)^2) = 38.27 < jerk Corner can be printed with full speed of 50 mm/s Overridden if EEPROM activated. */ #define MAX_JERK 10.0 #define MAX_ZJERK 0.3 /** \brief Number of moves we can cache in advance. This number of moves can be cached in advance. If you wan't to cache more, increase this. Especially on many very short moves the cache may go empty. The minimum value is 5. */ #define MOVE_CACHE_SIZE 16 /** \brief Low filled cache size. If the cache contains less then MOVE_CACHE_LOW segments, the time per segment is limited to LOW_TICKS_PER_MOVE clock cycles. If a move would be shorter, the feedrate will be reduced. This should prevent buffer underflows. Set this to 0 if you don't care about empty buffers during print. */ #define MOVE_CACHE_LOW 10 /** \brief Cycles per move, if move cache is low. This value must be high enough, that the buffer has time to fill up. The problem only occurs at the beginning of a print or if you are printing many very short segments at high speed. Higher delays here allow higher values in PATH_PLANNER_CHECK_SEGMENTS. */ #define LOW_TICKS_PER_MOVE 250000 // ########################################################################################## // ## Extruder control ## // ########################################################################################## /* \brief Minimum temperature for extruder operation This is a saftey value. If your extruder temperature is below this temperature, no extruder steps are executed. This is to prevent your extruder to move unless the fiament is at least molten. After havong some complains that the extruder does not work, I leave it 0 as default. */ #define MIN_EXTRUDER_TEMP 160 /** \brief Enable advance algorithm. Without a correct adjusted advance algorithm, you get blobs at points, where acceleration changes. The effect increases with speed and acceleration difference. Using the advance method decreases this effect. For more informations, read the wiki. */ #define USE_ADVANCE /** \brief enables quadratic component. Uncomment to allow a quadratic advance dependency. Linear is the dominant value, so no real need to activate the quadratic term. Only adds lots of computations and storage usage. */ #define ENABLE_QUADRATIC_ADVANCE // ########################################################################################## // ## Communication configuration ## // ########################################################################################## //// AD595 THERMOCOUPLE SUPPORT UNTESTED... USE WITH CAUTION!!!! /** \brief Communication speed. - 250000 : Fastes with errorrate of 0% with 16 or 32 MHz - update wiring_serial.c in your board files. See boards/readme.txt - 115200 : Fast, but may produce communication errors on quite regular basis, Error rate -3,5% - 76800 : Best setting for Arduino with 16 MHz, Error rate 0,2% page 198 AVR1284 Manual. Result: Faster communication then 115200 - 57600 : Should produce nearly no errors, on my gen 6 it's faster than 115200 because there are no errors slowing down the connection - 38600 Overridden if EEPROM activated. */ //#define BAUDRATE 76800 #define BAUDRATE 115200 //#define BAUDRATE 250000 /** Some boards like Gen7 have a power on pin, to enable the atx power supply. If this is defined, the power will be turned on without the need to call M80 if initially started. */ #define ENABLE_POWER_ON_STARTUP /** If you use an ATX power supply you need the power pin to work non inverting. For some special boards you might need to make it inverting. */ #define POWER_INVERTING false /** What shall the printer do, when it receives an M112 emergency stop signal? 0 = Disable heaters/motors, wait forever until someone presses reset. 1 = restart by resetting the AVR controller. The USB connection will not reset if managed by a different chip! */ #define KILL_METHOD 1 /** \brief Cache size for incoming commands. There should be no reason to increase this cache. Commands are nearly immediately sent to execution. */ #define GCODE_BUFFER_SIZE 2 /** Appends the linenumber after every ok send, to acknowledge the received command. Uncomment for plain ok ACK if your host has problems with this */ #define ACK_WITH_LINENUMBER /** Communication errors can swollow part of the ok, which tells the host software to send the next command. Not receiving it will cause your printer to stop. Sending this string every second, if our queue is empty should prevent this. Comment it, if you don't wan't this feature. */ #define WAITING_IDENTIFIER "wait" /** \brief Sets time for echo debug You can set M111 1 which enables ECHO of commands sent. This define specifies the position, when it will be executed. In the original FiveD software, echo is done after receiving the command. With checksum you know, how it looks from the sending string. With this define uncommented, you will see the last command executed. To be more specific: It is written after execution. This helps tracking errors, because there may be 8 or more commands in the queue and it is elsewise difficult to know, what your reprap is currently doing. */ #define ECHO_ON_EXECUTE /** \brief EEPROM storage mode Set the EEPROM_MODE to 0 if you always want to use the settings in this configuration file. If not, set it to a value not stored in the first EEPROM-byte used. If you later want to overwrite your current EEPROM settings with configuration defaults, just select an other value. On the first call to epr_init() it will detect a mismatch of the first byte and copy default values into EEPROM. If the first byte matches, the stored values are used to overwrite the settings. IMPORTANT: With mode <>0 some changes in Configuration.h are not set any more, as they are taken from the EEPROM. */ #define EEPROM_MODE 1 /**************** duplicate motor driver *************** If you have an unused extruder stepper free, you could use it to drive the second z motor instead of driving both with a single stepper. The same works for the other axis if needed. */ #define FEATURE_TWO_XSTEPPER false #define X2_STEP_PIN E1_STEP_PIN #define X2_DIR_PIN E1_DIR_PIN #define X2_ENABLE_PIN E1_ENABLE_PIN #define FEATURE_TWO_YSTEPPER false #define Y2_STEP_PIN E1_STEP_PIN #define Y2_DIR_PIN E1_DIR_PIN #define Y2_ENABLE_PIN E1_ENABLE_PIN #define FEATURE_TWO_ZSTEPPER false #define Z2_STEP_PIN E1_STEP_PIN #define Z2_DIR_PIN E1_DIR_PIN #define Z2_ENABLE_PIN E1_ENABLE_PIN /* Ditto printing allows 2 extruders to do the same action. This effectively allows to print an object two times at the speed of one. Works only with dual extruder setup. */ #define FEATURE_DITTO_PRINTING false /* Servos If you need to control servos, enable this feature. You can control up to 4 servos. Control the servos with M340 P<servoId> S<pulseInUS> servoID = 0..3 Servos are controlled by a pulse width normally between 500 and 2500 with 1500ms in center position. 0 turns servo off. WARNING: Servos can draw a considerable amount of current. Make sure your system can handle this or you may risk your hardware! */ #define FEATURE_SERVO false // Servo pins on a RAMPS board are 11,6,5,4 #define SERVO0_PIN 11 #define SERVO1_PIN 6 #define SERVO2_PIN 5 #define SERVO3_PIN 4 /* A watchdog resets the printer, if a signal is not send within predifined time limits. That way we can be sure that the board is always running and is not hung up for some unknown reason. */ #define FEATURE_WATCHDOG true /* Z-Probing */ #define FEATURE_Z_PROBE false #define Z_PROBE_PIN 63 #define Z_PROBE_PULLUP true #define Z_PROBE_ON_HIGH true #define Z_PROBE_X_OFFSET 0 #define Z_PROBE_Y_OFFSET 0 // Waits for a signal to start. Valid signals are probe hit and ok button. // This is needful if you have the probe trigger by hand. #define Z_PROBE_WAIT_BEFORE_TEST true /** Speed of z-axis in mm/s when probing */ #define Z_PROBE_SPEED 2 #define Z_PROBE_XY_SPEED 150 /** The height is the difference between activated probe position and nozzle height. */ #define Z_PROBE_HEIGHT 39.91 /** These scripts are run before resp. after the z-probe is done. Add here code to activate/deactivate probe if needed. */ #define Z_PROBE_START_SCRIPT "" #define Z_PROBE_FINISHED_SCRIPT "" /* Autoleveling allows it to z-probe 3 points to compute the inclination and compensates the error for the print. This feature requires a working z-probe and you should have z-endstop at the top not at the bottom. The same 3 points are used for the G29 command. */ #define FEATURE_AUTOLEVEL false #define Z_PROBE_X1 100 #define Z_PROBE_Y1 20 #define Z_PROBE_X2 160 #define Z_PROBE_Y2 170 #define Z_PROBE_X3 20 #define Z_PROBE_Y3 170 /* Define a pin to tuen light on/off */ #define CASE_LIGHTS_PIN -1 /** Set to false to disable SD support: */ #ifndef SDSUPPORT // Some boards have sd support on board. These define the values already in pins.h #define SDSUPPORT true // Uncomment to enable or change card detection pin. With card detection the card is mounted on insertion. #define SDCARDDETECT 10 // Change to true if you get a inserted message on removal. #define SDCARDDETECTINVERTED false #endif /** Show extended directory including file length. Don't use this with Pronterface! */ #define SD_EXTENDED_DIR true // If you want support for G2/G3 arc commands set to true, otherwise false. #define ARC_SUPPORT true /** You can store the current position with M401 and go back to it with M402. This works only if feature is set to true. */ #define FEATURE_MEMORY_POSITION true /** If a checksum is sent, all future comamnds must also contain a checksum. Increases reliability especially for binary protocol. */ #define FEATURE_CHECKSUM_FORCED false /** Should support for fan control be compiled in. If you enable this make sure the FAN pin is not the same as for your second extruder. RAMPS e.g. has FAN_PIN in 9 which is also used for the heater if you have 2 extruders connected. */ #define FEATURE_FAN_CONTROL true /** For displays and keys there are too many permutations to handle them all in once. For the most common available combinations you can set the controller type here, so you don't need to configure uicong.h at all. Controller settings > 1 disable usage of uiconfig.h 0 = no display 1 = Manual definition of display and keys parameter in uiconfig.h The following settings override uiconfig.h! 2 = Smartcontroller from reprapdiscount on a RAMPS or RUMBA board 3 = Adafruit RGB controller 4 = Foltyn 3DMaster with display attached 5 = ViKi LCD - Check pin configuration in ui.h for feature controller 5!!! sd card disabled by default! 6 = ReprapWorld Keypad / LCD, predefined pins for Megatronics v2.0 and RAMPS 1.4. Please check if you have used the defined pin layout in ui.h. 7 = RADDS Extension Port 8 = PiBot Display/Controller extension with 20x4 character display 9 = PiBot Display/Controller extension with 16x2 character display 10 = Gadgets3D shield on RAMPS 1.4, see http://reprap.org/wiki/RAMPS_1.3/1.4_GADGETS3D_Shield_with_Panel 11 = RepRapDiscount Full Graphic Smart Controller */ #define FEATURE_CONTROLLER 1 /** Select the language to use. 0 = English 1 = German 2 = Dutch 3 = Brazilian portuguese 4 = Italian 5 = Spanish 6 = Swedish */ #define UI_LANGUAGE 1 // This is line 2 of the status display at startup. Change to your like. #define UI_PRINTER_NAME "Mendel90" #define UI_PRINTER_COMPANY "ABC-Design" /** Animate switches between menus etc. */ #define UI_ANIMATION true /** How many ms should a single page be shown, until it is switched to the next one.*/ #define UI_PAGES_DURATION 4000 /** Delay of start screen in milliseconds */ #define UI_START_SCREEN_DELAY 1000 /** Uncomment if you don't want automatic page switching. You can still switch the info pages with next/previous button/click-encoder */ #define UI_DISABLE_AUTO_PAGESWITCH true /** Time to return to info menu if x millisconds no key was pressed. Set to 0 to disable it. */ #define UI_AUTORETURN_TO_MENU_AFTER 120000 #define FEATURE_UI_KEYS 0 /* Normally cou want a next/previous actions with every click of your encoder. Unfotunately, the encoder have a different count of phase changes between clicks. Select an encoder speed from 0 = fastest to 2 = slowest that results in one menu move per click. */ #define UI_ENCODER_SPEED 1 /* There are 2 ways to change positions. You can move by increments of 1/0.1 mm resulting in more menu entries and requiring many turns on your encode. The alternative is to enable speed dependent positioning. It will change the move distance depending on the speed you turn the encoder. That way you can move very fast and very slow in the same setting. */ #define UI_SPEEDDEPENDENT_POSITIONING true /** \brief bounce time of keys in milliseconds */ #define UI_KEY_BOUNCETIME 10 /** \brief First time in ms until repeat of action. */ #define UI_KEY_FIRST_REPEAT 500 /** \brief Reduction of repeat time until next execution. */ #define UI_KEY_REDUCE_REPEAT 50 /** \brief Lowest repeat time. */ #define UI_KEY_MIN_REPEAT 50 #define FEATURE_BEEPER false /** Beeper sound definitions for short beeps during key actions and longer beeps for important actions. Parameter is delay in microseconds and the secons is the number of repetitions. Values must be in range 1..255 */ #define BEEPER_SHORT_SEQUENCE 2,2 #define BEEPER_LONG_SEQUENCE 8,8 // ############################################################################### // ## Values for menu settings ## // ############################################################################### // Values used for preheat #define UI_SET_PRESET_HEATED_BED_TEMP_PLA 60 #define UI_SET_PRESET_EXTRUDER_TEMP_PLA 180 #define UI_SET_PRESET_HEATED_BED_TEMP_ABS 110 #define UI_SET_PRESET_EXTRUDER_TEMP_ABS 240 // Extreme values #define UI_SET_MIN_HEATED_BED_TEMP 55 #define UI_SET_MAX_HEATED_BED_TEMP 120 #define UI_SET_MIN_EXTRUDER_TEMP 160 #define UI_SET_MAX_EXTRUDER_TEMP 270 #define UI_SET_EXTRUDER_FEEDRATE 2 // mm/sec #define UI_SET_EXTRUDER_RETRACT_DISTANCE 3 // mm #endif
42.227053
163
0.728826
[ "object", "3d" ]
c162ea834fe3e49f5c4f4df78f9476b050e9a151
7,896
c
C
ext/libxml/ruby_xml_attr.c
ziggo83/libxml-ruby
8ce80be58e0dfdd270be707658c31a91d9467ab5
[ "MIT" ]
1
2015-11-05T12:01:33.000Z
2015-11-05T12:01:33.000Z
ext/libxml/ruby_xml_attr.c
ziggo83/libxml-ruby
8ce80be58e0dfdd270be707658c31a91d9467ab5
[ "MIT" ]
null
null
null
ext/libxml/ruby_xml_attr.c
ziggo83/libxml-ruby
8ce80be58e0dfdd270be707658c31a91d9467ab5
[ "MIT" ]
null
null
null
/* Please see the LICENSE file for copyright and distribution information */ /* * Document-class: LibXML::XML::Attr * * Provides access to an attribute defined on an element. * * Basic Usage: * * require 'test_helper' * * doc = XML::Document.new(<some_file>) * attribute = doc.root.attributes.get_attribute_ns('http://www.w3.org/1999/xlink', 'href') * attribute.name == 'href' * attribute.value == 'http://www.mydocument.com' * attribute.remove! */ /* Attributes are owned and freed by their nodes. Thus, its easier for the ruby bindings to not manage attribute memory management. This does mean that accessing a particular attribute multiple times will return multiple different ruby objects. Since we are not using free or xnode->_private this works out fine. Previous versions of the bindings had a one to one mapping between ruby object and xml attribute, but that could result in segfaults because the ruby object could be gc'ed. In theory the mark method on the parent node could prevent that, but if an attribute is returned using an xpath statement then the node would never by surfaced to ruby and the mark method never called. */ #include "ruby_libxml.h" #include "ruby_xml_attr.h" VALUE cXMLAttr; void rxml_attr_mark(xmlAttrPtr xattr) { /* This can happen if Ruby does a GC run after creating the new attribute but before initializing it. */ if (xattr != NULL) rxml_node_mark((xmlNodePtr) xattr); } VALUE rxml_attr_wrap(xmlAttrPtr xattr) { return Data_Wrap_Struct(cXMLAttr, rxml_attr_mark, NULL, xattr); } static VALUE rxml_attr_alloc(VALUE klass) { return Data_Wrap_Struct(klass, rxml_attr_mark, NULL, NULL); } /* * call-seq: * attr.initialize(node, "name", "value") * * Creates a new attribute for the node. * * node: The XML::Node that will contain the attribute * name: The name of the attribute * value: The value of the attribute * * attr = XML::Attr.new(doc.root, 'name', 'libxml') */ static VALUE rxml_attr_initialize(int argc, VALUE *argv, VALUE self) { VALUE node = argv[0]; VALUE name = argv[1]; VALUE value = argv[2]; VALUE ns = (argc == 4 ? argv[3] : Qnil); xmlNodePtr xnode; xmlAttrPtr xattr; if (argc < 3 || argc > 4) rb_raise(rb_eArgError, "Wrong number of arguments (3 or 4)"); Check_Type(name, T_STRING); Check_Type(value, T_STRING); Data_Get_Struct(node, xmlNode, xnode); if (xnode->type != XML_ELEMENT_NODE) rb_raise(rb_eArgError, "Attributes can only be created on element nodes."); if (NIL_P(ns)) { xattr = xmlNewProp(xnode, (xmlChar*)StringValuePtr(name), (xmlChar*)StringValuePtr(value)); } else { xmlNsPtr xns; Data_Get_Struct(ns, xmlNs, xns); xattr = xmlNewNsProp(xnode, xns, (xmlChar*)StringValuePtr(name), (xmlChar*)StringValuePtr(value)); } if (!xattr) rb_raise(rb_eRuntimeError, "Could not create attribute."); DATA_PTR( self) = xattr; return self; } /* * call-seq: * attr.child -> node * * Obtain this attribute's child attribute(s). */ static VALUE rxml_attr_child_get(VALUE self) { xmlAttrPtr xattr; Data_Get_Struct(self, xmlAttr, xattr); if (xattr->children == NULL) return Qnil; else return rxml_node_wrap((xmlNodePtr) xattr->children); } /* * call-seq: * attr.doc -> XML::Document * * Returns this attribute's document. * * doc.root.attributes.get_attribute('name').doc == doc */ static VALUE rxml_attr_doc_get(VALUE self) { xmlAttrPtr xattr; Data_Get_Struct(self, xmlAttr, xattr); if (xattr->doc == NULL) return Qnil; else return rxml_document_wrap(xattr->doc); } /* * call-seq: * attr.last -> node * * Obtain the last attribute. */ static VALUE rxml_attr_last_get(VALUE self) { xmlAttrPtr xattr; Data_Get_Struct(self, xmlAttr, xattr); if (xattr->last == NULL) return Qnil; else return rxml_node_wrap(xattr->last); } /* * call-seq: * attr.name -> "name" * * Obtain this attribute's name. */ static VALUE rxml_attr_name_get(VALUE self) { xmlAttrPtr xattr; Data_Get_Struct(self, xmlAttr, xattr); if (xattr->name == NULL) return Qnil; else return rxml_new_cstr((const char*) xattr->name, NULL); } /* * call-seq: * attr.next -> node * * Obtain the next attribute. */ static VALUE rxml_attr_next_get(VALUE self) { xmlAttrPtr xattr; Data_Get_Struct(self, xmlAttr, xattr); if (xattr->next == NULL) return Qnil; else return rxml_attr_wrap(xattr->next); } /* * call-seq: * attr.node_type -> num * * Obtain this node's type identifier. */ static VALUE rxml_attr_node_type(VALUE self) { xmlAttrPtr xattr; Data_Get_Struct(self, xmlAttr, xattr); return INT2NUM(xattr->type); } /* * call-seq: * attr.ns -> namespace * * Obtain this attribute's associated XML::NS, if any. */ static VALUE rxml_attr_ns_get(VALUE self) { xmlAttrPtr xattr; Data_Get_Struct(self, xmlAttr, xattr); if (xattr->ns == NULL) return Qnil; else return rxml_namespace_wrap(xattr->ns); } /* * call-seq: * attr.parent -> node * * Obtain this attribute node's parent. */ static VALUE rxml_attr_parent_get(VALUE self) { xmlAttrPtr xattr; Data_Get_Struct(self, xmlAttr, xattr); if (xattr->parent == NULL) return Qnil; else return rxml_node_wrap(xattr->parent); } /* * call-seq: * attr.prev -> node * * Obtain the previous attribute. */ static VALUE rxml_attr_prev_get(VALUE self) { xmlAttrPtr xattr; Data_Get_Struct(self, xmlAttr, xattr); if (xattr->prev == NULL) return Qnil; else return rxml_attr_wrap(xattr->prev); } /* * call-seq: * attr.remove! -> nil * * Removes this attribute from it's parent. Note * the attribute and its content is freed and can * no longer be used. If you try to use it you * will get a segmentation fault. */ static VALUE rxml_attr_remove_ex(VALUE self) { xmlAttrPtr xattr; Data_Get_Struct(self, xmlAttr, xattr); xmlRemoveProp(xattr); RDATA(self)->data = NULL; RDATA(self)->dfree = NULL; RDATA(self)->dmark = NULL; return Qnil; } /* * call-seq: * attr.value -> "value" * * Obtain the value of this attribute. */ VALUE rxml_attr_value_get(VALUE self) { xmlAttrPtr xattr; xmlChar *value; VALUE result = Qnil; Data_Get_Struct(self, xmlAttr, xattr); value = xmlNodeGetContent((xmlNodePtr)xattr); if (value != NULL) { result = rxml_new_cstr((const char*) value, NULL); xmlFree(value); } return result; } /* * call-seq: * attr.value = "value" * * Sets the value of this attribute. */ VALUE rxml_attr_value_set(VALUE self, VALUE val) { xmlAttrPtr xattr; Check_Type(val, T_STRING); Data_Get_Struct(self, xmlAttr, xattr); if (xattr->ns) xmlSetNsProp(xattr->parent, xattr->ns, xattr->name, (xmlChar*) StringValuePtr(val)); else xmlSetProp(xattr->parent, xattr->name, (xmlChar*) StringValuePtr(val)); return (self); } void rxml_init_attr(void) { cXMLAttr = rb_define_class_under(mXML, "Attr", rb_cObject); rb_define_alloc_func(cXMLAttr, rxml_attr_alloc); rb_define_method(cXMLAttr, "initialize", rxml_attr_initialize, -1); rb_define_method(cXMLAttr, "child", rxml_attr_child_get, 0); rb_define_method(cXMLAttr, "doc", rxml_attr_doc_get, 0); rb_define_method(cXMLAttr, "last", rxml_attr_last_get, 0); rb_define_method(cXMLAttr, "name", rxml_attr_name_get, 0); rb_define_method(cXMLAttr, "next", rxml_attr_next_get, 0); rb_define_method(cXMLAttr, "node_type", rxml_attr_node_type, 0); rb_define_method(cXMLAttr, "ns", rxml_attr_ns_get, 0); rb_define_method(cXMLAttr, "parent", rxml_attr_parent_get, 0); rb_define_method(cXMLAttr, "prev", rxml_attr_prev_get, 0); rb_define_method(cXMLAttr, "remove!", rxml_attr_remove_ex, 0); rb_define_method(cXMLAttr, "value", rxml_attr_value_get, 0); rb_define_method(cXMLAttr, "value=", rxml_attr_value_set, 1); }
23.640719
102
0.693642
[ "object" ]
c16ba39c5175242c262ad3146ab0ece27c544b2c
2,309
h
C
euler/client/testing/mock_rpc_manager.h
lixusign/euler
c8ce1968367aec2807cc542fcdb5958e3b1b9295
[ "Apache-2.0" ]
1
2019-09-18T02:18:06.000Z
2019-09-18T02:18:06.000Z
euler/client/testing/mock_rpc_manager.h
DingXiye/euler
c45225119c5b991ca953174f06c2f223562f34c9
[ "Apache-2.0" ]
null
null
null
euler/client/testing/mock_rpc_manager.h
DingXiye/euler
c45225119c5b991ca953174f06c2f223562f34c9
[ "Apache-2.0" ]
1
2020-09-18T13:37:08.000Z
2020-09-18T13:37:08.000Z
/* Copyright 2018 Alibaba Group Holding Limited. 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. ==============================================================================*/ #ifndef EULER_CLIENT_TESTING_MOCK_RPC_MANAGER_H_ #define EULER_CLIENT_TESTING_MOCK_RPC_MANAGER_H_ #include <vector> #include <string> #include "gmock/gmock.h" #include "euler/client/rpc_manager.h" namespace euler { namespace client { namespace testing { struct MockRpcContext : public RpcContext { MockRpcContext(const std::string &method, google::protobuf::Message *response, std::function<void(const Status &)> done) : RpcContext(method, response, done) { } bool Initialize(const google::protobuf::Message &/*request*/) override { return true; } }; class MockRpcChannel : public RpcChannel { public: static std::vector<MockRpcChannel *> channels; explicit MockRpcChannel(const std::string &host_port) : RpcChannel(host_port) { channels.emplace_back(this); } ~MockRpcChannel() override { auto iter = std::find(channels.begin(), channels.end(), this); channels.erase(iter); } MOCK_METHOD1(IssueRpcCall, void(RpcContext *)); }; class MockRpcManager : public RpcManager { public: std::unique_ptr<RpcChannel> CreateChannel( const std::string &host_port, int /*tag*/) override { return std::unique_ptr<RpcChannel>(new MockRpcChannel(host_port)); } RpcContext *CreateContext(const std::string &method, google::protobuf::Message *respone, std::function<void(const Status &)> done) override { return new MockRpcContext(method, respone, done); } }; } // namespace testing } // namespace client } // namespace euler #endif // EULER_CLIENT_TESTING_MOCK_RPC_MANAGER_H_
29.987013
80
0.692508
[ "vector" ]
c16e6d2b94c4e93474ed890eb7ac1f1bcb093b4b
3,483
c
C
src/hud.c
Huitsi/ParallelOverhead
d12b0273ab5b66515c8130b300475010b5f96e20
[ "MIT" ]
null
null
null
src/hud.c
Huitsi/ParallelOverhead
d12b0273ab5b66515c8130b300475010b5f96e20
[ "MIT" ]
null
null
null
src/hud.c
Huitsi/ParallelOverhead
d12b0273ab5b66515c8130b300475010b5f96e20
[ "MIT" ]
null
null
null
/* Copyright © 2020 Linus Vanas <linus@vanas.fi> * SPDX-License-Identifier: MIT */ #include <math.h> #include "common.h" //Global struct for holding the number graphics and data. struct { SDL_Surface *surface; SDL_Rect rects[12]; } HUD; /** * Format and render the given time to the given surface. * @param target The surface to render to. * @param rect The area of the surface in which to render. * @param time_ms The time to render in milliseconds. */ void render_time(SDL_Surface *target, SDL_Rect rect, unsigned int time_ms) { int m = time_ms/60000; int s = (time_ms/1000) % 60; int ms = time_ms % 1000; if (m > 99) { m = 99; s = 99; ms = 999; } const unsigned char gap = 1; char render_nums[9]; render_nums[0] = m / 10; render_nums[1] = m % 10; render_nums[2] = 10; //: render_nums[3] = s / 10; render_nums[4] = s % 10; render_nums[5] = 11; //. render_nums[6] = ms / 100; render_nums[7] = (ms % 100) / 10; render_nums[8] = ms % 10; int cut = 0; if (!render_nums[0]) { cut = 1; if (!render_nums[1]) { cut = 3; if (!render_nums[3]) { cut = 4; } } } for (int i = cut; i < 9; i++) { unsigned char num = render_nums[i]; SDL_BlitSurface(HUD.surface, &HUD.rects[num], target, &rect); rect.x += HUD.rects[num].w + gap; rect.w -= HUD.rects[num].w + gap; } } /** * Render the given number to the given surface. * @param target The surface to render to. * @param rect The area of the surface in which to render. * @param distance The number to render. */ void render_distance(SDL_Surface *target, SDL_Rect rect, unsigned int distance) { if (distance > 9999999) { distance = 9999999; } const unsigned char gap = 1; int leading = 1; for (int i = 7; i > 0; i--) { unsigned char num = (distance % (int) pow(10,i+1)) / pow(10,i); if (leading && !num) { continue; } leading = 0; SDL_BlitSurface(HUD.surface, &HUD.rects[num], target, &rect); rect.x += HUD.rects[num].w + gap; rect.w -= HUD.rects[num].w + gap; } unsigned char num = distance % 10; SDL_BlitSurface(HUD.surface, &HUD.rects[num], target, &rect); } /** * Render the given time and distance to the given surface. * @param target The surface to render to. * @param time_ms The time to render in milliseconds. * @param distance The distance to render. */ void render_time_and_distance(SDL_Surface *target, unsigned int time_ms, unsigned int distance) { if (Settings.flags.hide_counters) { return; } SDL_Rect time_rect = {0,0,100,11}; SDL_Rect distance_rect = {0,12,100,11}; SDL_FillRect(target, NULL, 0); render_time(target, time_rect, time_ms); render_distance(target, distance_rect, distance); } /** * Load the number graphics. */ void init_hud() { if (Settings.flags.hide_counters) { return; } char nums_path[Settings.paths.data_dir_len + sizeof "nums.bmp"]; snprintf(nums_path, sizeof nums_path, "%s%s", Settings.paths.data_dir, "nums.bmp"); HUD.surface = SDL_LoadBMP(nums_path); if (!HUD.surface) { report_SDL_error("Loading data/nums.bmp"); //return RET_SDL_ERR; } // 0 1 2 3 4 5 6 7 8 9 : . const int widths[] = {7, 3, 7, 7, 7, 7, 7, 7, 7, 7, 3, 3}; int x = 0; for (int i = 0; i < 12; i++) { SDL_Rect rect = {x, 0, widths[i], 11}; x += rect.w; HUD.rects[i] = rect; } } /** * Free the memory used by the number graphics. */ void free_hud() { if (Settings.flags.hide_counters) { return; } SDL_FreeSurface(HUD.surface); }
20.609467
95
0.637956
[ "render" ]
c16fca4769290e0064a44017e1fb7beab835b9ed
4,499
h
C
src/const/gba.h
nicholatian/nichruby
62ec17027b4956b3f242ebf56624a9e35a377a98
[ "BSD-2-Clause" ]
8
2020-05-28T23:43:47.000Z
2021-06-08T06:03:09.000Z
src/const/gba.h
nicholatian/nichruby
62ec17027b4956b3f242ebf56624a9e35a377a98
[ "BSD-2-Clause" ]
2
2020-09-21T23:52:31.000Z
2020-11-05T12:25:22.000Z
src/const/gba.h
nicholatian/nichruby
62ec17027b4956b3f242ebf56624a9e35a377a98
[ "BSD-2-Clause" ]
null
null
null
/* -*- coding: utf-8 -*- */ /****************************************************************************\ * __ _ _____ _______ _ _ ______ _ _ ______ __ __ * * | \ | | | |_____| |_____/ | | |_____] \_/ * * | \_| __|__ |_____ | | | \_ |_____| |_____] | * * nichruby * * * * Copyright © 2020 Alexander Nicholi * * Released under BSD-2-Clause. * \****************************************************************************/ /* DEFINITION MODULE */ #ifndef INC__BASE_GBA_H #define INC__BASE_GBA_H #define D_IWRAM __attribute__( ( section( "iwram" ) ) ) #define D_EWRAM __attribute__( ( section( "ewram" ) ) ) enum { PSR_USR_MODE = 0x10, PSR_FIQ_MODE = 0x11, PSR_IRQ_MODE = 0x12, PSR_SVC_MODE = 0x13, PSR_ABT_MODE = 0x17, PSR_UND_MODE = 0x1B, PSR_SYS_MODE = 0x1F }; enum { PSR_MODE_MASK = 0x1F, PSR_T_BIT = 0x20, PSR_F_BIT = 0x40, PSR_I_BIT = 0x80 }; enum { EWRAM_SZ = 0x40000, IWRAM_SZ = 0x8000, PAL_SZ = 0x400, VRAM_SZ = 0x18000, SRAM_SZ = 0x10000 }; enum { OAM_SZ = 0x400 }; enum { /* Extended working RAM */ EWRAM = 0x2000000, /* Internal working RAM */ IWRAM = 0x3000000, /* Memory-mapped I/O */ IO = 0x4000000, /* Palette RAM */ PAL = 0x5000000, /* Video RAM */ VRAM = 0x6000000, /* “Object Attribute Memory” */ OAM = 0x7000000, /* Read only memory (Game pak) */ ROM = 0x8000000, /* Static RAM (save file) */ SRAM = 0xE000000 }; enum { /* Display control */ DISPCNT = IO + 0x0, /* “Green swap” (undocumented, unused) */ GREENSWAP = IO + 0x2, /* Display stat (?) */ DISPSTAT = IO + 0x4, /* Vertical counter for the currently drawn scanline */ VCOUNT = IO + 0x6, /* BG 0 control */ BG0CNT = IO + 0x8, /* BG 1 control */ BG1CNT = IO + 0xA, /* BG 2 control */ BG2CNT = IO + 0xC, /* BG 3 control */ BG3CNT = IO + 0xE, /* BG 0 horizontal offset */ BG0HOFS = IO + 0x10, /* BG 0 vertical offset */ BG0VOFS = IO + 0x12, /* BG 1 horizontal offset */ BG1HOFS = IO + 0x14, /* BG 1 vertical offset */ BG1VOFS = IO + 0x16, /* BG 2 horizontal offset */ BG2HOFS = IO + 0x18, /* BG 2 vertical offset */ BG2VOFS = IO + 0x1A, /* BG 3 horizontal offset */ BG3HOFS = IO + 0x1C, /* BG 3 vertical offset */ BG3VOFS = IO + 0x1E, /* BG 2 rotation/scaling parameter A (dx) */ BG2PA = IO + 0x20, /* BG 2 rotation/scaling parameter B (dmx) */ BG2PB = IO + 0x22, /* BG 2 rotation/scaling parameter C (dy) */ BG2PC = IO + 0x24, /* BG 2 rotation/scaling parameter D (dmy) */ BG2PD = IO + 0x26, /* BG 2 reference point X coordinate, lower 16 bits */ BG2X_L = IO + 0x28, /* BG 2 reference point X coordinate, upper 12 bits */ BG2X_H = IO + 0x2A, /* BG 2 reference point Y coordinate, lower 16 bits */ BG2Y_L = IO + 0x2C, /* BG 2 reference point Y coordinate, upper 12 bits */ BG2Y_H = IO + 0x2E, /* BG 3 rotation/scaling parameter A (dx) */ BG3PA = IO + 0x30, /* BG 3 rotation/scaling parameter B (dmx) */ BG3PB = IO + 0x32, /* BG 3 rotation/scaling parameter C (dy) */ BG3PC = IO + 0x34, /* BG 3 rotation/scaling parameter D (dmy) */ BG3PD = IO + 0x36, /* BG 3 reference point X coordinate, lower 16 bits */ BG3X_L = IO + 0x38, /* BG 3 reference point X coordinate, upper 12 bits */ BG3X_H = IO + 0x3A, /* BG 3 reference point Y coordinate, lower 16 bits */ BG3Y_L = IO + 0x3C, /* BG 3 reference point Y coordinate, upper 12 bits */ BG3Y_H = IO + 0x3E, /* Window 0 horizontal size */ WIN0H = IO + 0x40, /* Window 1 horizontal size */ WIN1H = IO + 0x42, /* Window 0 vertical size */ WIN0V = IO + 0x44, /* Window 1 vertical size */ WIN1V = IO + 0x46, /* Window inside control */ WININ = IO + 0x48, /* Window outside control */ WINOUT = IO + 0x4A, /* Mosaic control register */ MOSAIC = IO + 0x4C }; /* input keys */ enum { KEY_A = 0, KEY_B, KEY_START, KEY_SEL, KEY_UP, KEY_DOWN, KEY_LEFT, KEY_RIGHT, KEY_L, KEY_R, MAX_KEY }; /* bitmasks for keys */ enum { KEYMASK_A = 1 << KEY_A, KEYMASK_B = 1 << KEY_B, KEYMASK_START = 1 << KEY_START, KEYMASK_SEL = 1 << KEY_SEL, KEYMASK_UP = 1 << KEY_UP, KEYMASK_DOWN = 1 << KEY_DOWN, KEYMASK_LEFT = 1 << KEY_LEFT, KEYMASK_RIGHT = 1 << KEY_RIGHT, KEYMASK_L = 1 << KEY_L, KEYMASK_R = 1 << KEY_R }; #endif /* INC__BASE_GBA_H */
24.058824
78
0.560569
[ "object" ]
c177d233b1b4f1ee77f26eb4a12ad6ee54dd2be6
1,500
h
C
cc/CCAnimationCurve.h
quisquous/chromium
b25660e05cddc9d0c3053b3514f07037acc69a10
[ "BSD-3-Clause" ]
2
2020-06-10T07:15:26.000Z
2020-12-13T19:44:12.000Z
cc/CCAnimationCurve.h
quisquous/chromium
b25660e05cddc9d0c3053b3514f07037acc69a10
[ "BSD-3-Clause" ]
null
null
null
cc/CCAnimationCurve.h
quisquous/chromium
b25660e05cddc9d0c3053b3514f07037acc69a10
[ "BSD-3-Clause" ]
null
null
null
// Copyright 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. #ifndef CCAnimationCurve_h #define CCAnimationCurve_h #include <public/WebTransformationMatrix.h> #include <wtf/PassOwnPtr.h> namespace cc { class CCFloatAnimationCurve; class CCTransformAnimationCurve; class IntSize; class TransformOperations; // An animation curve is a function that returns a value given a time. // There are currently only two types of curve, float and transform. class CCAnimationCurve { public: enum Type { Float, Transform }; virtual ~CCAnimationCurve() { } virtual double duration() const = 0; virtual Type type() const = 0; virtual PassOwnPtr<CCAnimationCurve> clone() const = 0; const CCFloatAnimationCurve* toFloatAnimationCurve() const; const CCTransformAnimationCurve* toTransformAnimationCurve() const; }; class CCFloatAnimationCurve : public CCAnimationCurve { public: virtual ~CCFloatAnimationCurve() { } virtual float getValue(double t) const = 0; // Partial CCAnimation implementation. virtual Type type() const OVERRIDE; }; class CCTransformAnimationCurve : public CCAnimationCurve { public: virtual ~CCTransformAnimationCurve() { } virtual WebKit::WebTransformationMatrix getValue(double t) const = 0; // Partial CCAnimation implementation. virtual Type type() const OVERRIDE; }; } // namespace cc #endif // CCAnimation_h
26.315789
73
0.752
[ "transform" ]
c17c176bd6816e06bb4062713f343c1f7ecf5d18
43,235
c
C
release/src-ra-4300/linux/linux-2.6.36.x/arch/mips/softfloat/libgcc2.c
zhoutao0712/rtn11pb1
09e6b6c7ef4b91be0a9374daeacc3ac9f2fa3a05
[ "Apache-2.0" ]
1
2022-03-19T06:38:01.000Z
2022-03-19T06:38:01.000Z
release/src-ra-4300/linux/linux-2.6.36.x/arch/mips/softfloat/libgcc2.c
zhoutao0712/rtn11pb1
09e6b6c7ef4b91be0a9374daeacc3ac9f2fa3a05
[ "Apache-2.0" ]
null
null
null
release/src-ra-4300/linux/linux-2.6.36.x/arch/mips/softfloat/libgcc2.c
zhoutao0712/rtn11pb1
09e6b6c7ef4b91be0a9374daeacc3ac9f2fa3a05
[ "Apache-2.0" ]
1
2022-03-19T06:38:03.000Z
2022-03-19T06:38:03.000Z
/* More subroutines needed by GCC output code on some machines. */ /* Compile this one with gcc. */ /* Copyright (C) 1989, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002 Free Software Foundation, Inc. This file is part of GCC. GCC 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 2, or (at your option) any later version. In addition to the permissions in the GNU General Public License, the Free Software Foundation gives you unlimited permission to link the compiled version of this file into combinations with other programs, and to distribute those combinations without any restriction coming from the use of this file. (The General Public License restrictions do apply in other respects; for example, they cover modification of the file, and distribution when not linked into a combine executable.) GCC 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 GCC; see the file COPYING. If not, write to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ /* It is incorrect to include config.h here, because this file is being compiled for the target, and hence definitions concerning only the host do not apply. */ //#include <linux/config.h> //#include <linux/slab.h> //#include <linux/module.h> //#ifdef CONFIG_KMOD //#include <linux/kmod.h> //#endif #include <linux/module.h> #include <linux/kernel.h> #include "tconfig.h" //#include "tsystem.h" #include "stddef.h" #include "float.h" /* Don't use `fancy_abort' here even if config.h says to use it. */ #ifdef abort #undef abort #endif #define abort() printk("libgcc2 abort.") #include "libgcc2.h" #ifdef DECLARE_LIBRARY_RENAMES DECLARE_LIBRARY_RENAMES #endif #if defined (L_negdi2) DWtype __negdi2 (DWtype u) { DWunion w; DWunion uu; uu.ll = u; w.s.low = -uu.s.low; w.s.high = -uu.s.high - ((UWtype) w.s.low > 0); return w.ll; } #endif #ifdef L_addvsi3 Wtype __addvsi3 (Wtype a, Wtype b) { Wtype w; w = a + b; if (b >= 0 ? w < a : w > a) abort (); return w; } #endif #ifdef L_addvdi3 DWtype __addvdi3 (DWtype a, DWtype b) { DWtype w; w = a + b; if (b >= 0 ? w < a : w > a) abort (); return w; } #endif #ifdef L_subvsi3 Wtype __subvsi3 (Wtype a, Wtype b) { #ifdef L_addvsi3 return __addvsi3 (a, (-b)); #else DWtype w; w = a - b; if (b >= 0 ? w > a : w < a) abort (); return w; #endif } #endif #ifdef L_subvdi3 DWtype __subvdi3 (DWtype a, DWtype b) { #ifdef L_addvdi3 return (a, (-b)); #else DWtype w; w = a - b; if (b >= 0 ? w > a : w < a) abort (); return w; #endif } #endif #ifdef L_mulvsi3 Wtype __mulvsi3 (Wtype a, Wtype b) { DWtype w; w = a * b; if (((a >= 0) == (b >= 0)) ? w < 0 : w > 0) abort (); return w; } #endif #ifdef L_negvsi2 Wtype __negvsi2 (Wtype a) { Wtype w; w = -a; if (a >= 0 ? w > 0 : w < 0) abort (); return w; } #endif #ifdef L_negvdi2 DWtype __negvdi2 (DWtype a) { DWtype w; w = -a; if (a >= 0 ? w > 0 : w < 0) abort (); return w; } #endif #ifdef L_absvsi2 Wtype __absvsi2 (Wtype a) { Wtype w = a; if (a < 0) #ifdef L_negvsi2 w = __negvsi2 (a); #else w = -a; if (w < 0) abort (); #endif return w; } #endif #ifdef L_absvdi2 DWtype __absvdi2 (DWtype a) { DWtype w = a; if (a < 0) #ifdef L_negvsi2 w = __negvsi2 (a); #else w = -a; if (w < 0) abort (); #endif return w; } #endif #ifdef L_mulvdi3 DWtype __mulvdi3 (DWtype u, DWtype v) { DWtype w; w = u * v; if (((u >= 0) == (v >= 0)) ? w < 0 : w > 0) abort (); return w; } #endif /* Unless shift functions are defined whith full ANSI prototypes, parameter b will be promoted to int if word_type is smaller than an int. */ #ifdef L_lshrdi3 DWtype __lshrdi3 (DWtype u, word_type b) { DWunion w; word_type bm; DWunion uu; if (b == 0) return u; uu.ll = u; bm = (sizeof (Wtype) * BITS_PER_UNIT) - b; if (bm <= 0) { w.s.high = 0; w.s.low = (UWtype) uu.s.high >> -bm; } else { UWtype carries = (UWtype) uu.s.high << bm; w.s.high = (UWtype) uu.s.high >> b; w.s.low = ((UWtype) uu.s.low >> b) | carries; } return w.ll; } #endif #ifdef L_ashldi3 DWtype __ashldi3 (DWtype u, word_type b) { DWunion w; word_type bm; DWunion uu; if (b == 0) return u; uu.ll = u; bm = (sizeof (Wtype) * BITS_PER_UNIT) - b; if (bm <= 0) { w.s.low = 0; w.s.high = (UWtype) uu.s.low << -bm; } else { UWtype carries = (UWtype) uu.s.low >> bm; w.s.low = (UWtype) uu.s.low << b; w.s.high = ((UWtype) uu.s.high << b) | carries; } return w.ll; } #endif #ifdef L_ashrdi3 DWtype __ashrdi3 (DWtype u, word_type b) { DWunion w; word_type bm; DWunion uu; if (b == 0) return u; uu.ll = u; bm = (sizeof (Wtype) * BITS_PER_UNIT) - b; if (bm <= 0) { /* w.s.high = 1..1 or 0..0 */ w.s.high = uu.s.high >> (sizeof (Wtype) * BITS_PER_UNIT - 1); w.s.low = uu.s.high >> -bm; } else { UWtype carries = (UWtype) uu.s.high << bm; w.s.high = uu.s.high >> b; w.s.low = ((UWtype) uu.s.low >> b) | carries; } return w.ll; } #endif #ifdef L_ffsdi2 DWtype __ffsdi2 (DWtype u) { DWunion uu; UWtype word, count, add; uu.ll = u; if (uu.s.low != 0) word = uu.s.low, add = 0; else if (uu.s.high != 0) word = uu.s.high, add = BITS_PER_UNIT * sizeof (Wtype); else return 0; count_trailing_zeros (count, word); return count + add + 1; } #endif #ifdef L_muldi3 DWtype __muldi3 (DWtype u, DWtype v) { DWunion w; DWunion uu, vv; uu.ll = u, vv.ll = v; w.ll = __umulsidi3 (uu.s.low, vv.s.low); w.s.high += ((UWtype) uu.s.low * (UWtype) vv.s.high + (UWtype) uu.s.high * (UWtype) vv.s.low); return w.ll; } #endif #if (defined (L_udivdi3) || defined (L_divdi3) || \ defined (L_umoddi3) || defined (L_moddi3)) #if defined (sdiv_qrnnd) #define L_udiv_w_sdiv #endif #endif #ifdef L_udiv_w_sdiv #if defined (sdiv_qrnnd) #if (defined (L_udivdi3) || defined (L_divdi3) || \ defined (L_umoddi3) || defined (L_moddi3)) static inline __attribute__ ((__always_inline__)) #endif UWtype __udiv_w_sdiv (UWtype *rp, UWtype a1, UWtype a0, UWtype d) { UWtype q, r; UWtype c0, c1, b1; if ((Wtype) d >= 0) { if (a1 < d - a1 - (a0 >> (W_TYPE_SIZE - 1))) { /* dividend, divisor, and quotient are nonnegative */ sdiv_qrnnd (q, r, a1, a0, d); } else { /* Compute c1*2^32 + c0 = a1*2^32 + a0 - 2^31*d */ sub_ddmmss (c1, c0, a1, a0, d >> 1, d << (W_TYPE_SIZE - 1)); /* Divide (c1*2^32 + c0) by d */ sdiv_qrnnd (q, r, c1, c0, d); /* Add 2^31 to quotient */ q += (UWtype) 1 << (W_TYPE_SIZE - 1); } } else { b1 = d >> 1; /* d/2, between 2^30 and 2^31 - 1 */ c1 = a1 >> 1; /* A/2 */ c0 = (a1 << (W_TYPE_SIZE - 1)) + (a0 >> 1); if (a1 < b1) /* A < 2^32*b1, so A/2 < 2^31*b1 */ { sdiv_qrnnd (q, r, c1, c0, b1); /* (A/2) / (d/2) */ r = 2*r + (a0 & 1); /* Remainder from A/(2*b1) */ if ((d & 1) != 0) { if (r >= q) r = r - q; else if (q - r <= d) { r = r - q + d; q--; } else { r = r - q + 2*d; q -= 2; } } } else if (c1 < b1) /* So 2^31 <= (A/2)/b1 < 2^32 */ { c1 = (b1 - 1) - c1; c0 = ~c0; /* logical NOT */ sdiv_qrnnd (q, r, c1, c0, b1); /* (A/2) / (d/2) */ q = ~q; /* (A/2)/b1 */ r = (b1 - 1) - r; r = 2*r + (a0 & 1); /* A/(2*b1) */ if ((d & 1) != 0) { if (r >= q) r = r - q; else if (q - r <= d) { r = r - q + d; q--; } else { r = r - q + 2*d; q -= 2; } } } else /* Implies c1 = b1 */ { /* Hence a1 = d - 1 = 2*b1 - 1 */ if (a0 >= -d) { q = -1; r = a0 + d; } else { q = -2; r = a0 + 2*d; } } } *rp = r; return q; } #else /* If sdiv_qrnnd doesn't exist, define dummy __udiv_w_sdiv. */ UWtype __udiv_w_sdiv (UWtype *rp __attribute__ ((__unused__)), UWtype a1 __attribute__ ((__unused__)), UWtype a0 __attribute__ ((__unused__)), UWtype d __attribute__ ((__unused__))) { return 0; } #endif #endif #if (defined (L_udivdi3) || defined (L_divdi3) || \ defined (L_umoddi3) || defined (L_moddi3)) #define L_udivmoddi4 #endif #ifdef L_clz const UQItype __clz_tab[] = { 0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5, 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, }; #endif #ifdef L_udivmoddi4 #if (defined (L_udivdi3) || defined (L_divdi3) || \ defined (L_umoddi3) || defined (L_moddi3)) static inline __attribute__ ((__always_inline__)) #endif UDWtype __udivmoddi4 (UDWtype n, UDWtype d, UDWtype *rp) { DWunion ww; DWunion nn, dd; DWunion rr; UWtype d0, d1, n0, n1, n2; UWtype q0, q1; UWtype b, bm; nn.ll = n; dd.ll = d; d0 = dd.s.low; d1 = dd.s.high; n0 = nn.s.low; n1 = nn.s.high; #if !UDIV_NEEDS_NORMALIZATION if (d1 == 0) { if (d0 > n1) { /* 0q = nn / 0D */ udiv_qrnnd (q0, n0, n1, n0, d0); q1 = 0; /* Remainder in n0. */ } else { /* qq = NN / 0d */ if (d0 == 0) d0 = 1 / d0; /* Divide intentionally by zero. */ udiv_qrnnd (q1, n1, 0, n1, d0); udiv_qrnnd (q0, n0, n1, n0, d0); /* Remainder in n0. */ } if (rp != 0) { rr.s.low = n0; rr.s.high = 0; *rp = rr.ll; } } #else /* UDIV_NEEDS_NORMALIZATION */ if (d1 == 0) { if (d0 > n1) { /* 0q = nn / 0D */ count_leading_zeros (bm, d0); if (bm != 0) { /* Normalize, i.e. make the most significant bit of the denominator set. */ d0 = d0 << bm; n1 = (n1 << bm) | (n0 >> (W_TYPE_SIZE - bm)); n0 = n0 << bm; } udiv_qrnnd (q0, n0, n1, n0, d0); q1 = 0; /* Remainder in n0 >> bm. */ } else { /* qq = NN / 0d */ if (d0 == 0) d0 = 1 / d0; /* Divide intentionally by zero. */ count_leading_zeros (bm, d0); if (bm == 0) { /* From (n1 >= d0) /\ (the most significant bit of d0 is set), conclude (the most significant bit of n1 is set) /\ (the leading quotient digit q1 = 1). This special case is necessary, not an optimization. (Shifts counts of W_TYPE_SIZE are undefined.) */ n1 -= d0; q1 = 1; } else { /* Normalize. */ b = W_TYPE_SIZE - bm; d0 = d0 << bm; n2 = n1 >> b; n1 = (n1 << bm) | (n0 >> b); n0 = n0 << bm; udiv_qrnnd (q1, n1, n2, n1, d0); } /* n1 != d0... */ udiv_qrnnd (q0, n0, n1, n0, d0); /* Remainder in n0 >> bm. */ } if (rp != 0) { rr.s.low = n0 >> bm; rr.s.high = 0; *rp = rr.ll; } } #endif /* UDIV_NEEDS_NORMALIZATION */ else { if (d1 > n1) { /* 00 = nn / DD */ q0 = 0; q1 = 0; /* Remainder in n1n0. */ if (rp != 0) { rr.s.low = n0; rr.s.high = n1; *rp = rr.ll; } } else { /* 0q = NN / dd */ count_leading_zeros (bm, d1); if (bm == 0) { /* From (n1 >= d1) /\ (the most significant bit of d1 is set), conclude (the most significant bit of n1 is set) /\ (the quotient digit q0 = 0 or 1). This special case is necessary, not an optimization. */ /* The condition on the next line takes advantage of that n1 >= d1 (true due to program flow). */ if (n1 > d1 || n0 >= d0) { q0 = 1; sub_ddmmss (n1, n0, n1, n0, d1, d0); } else q0 = 0; q1 = 0; if (rp != 0) { rr.s.low = n0; rr.s.high = n1; *rp = rr.ll; } } else { UWtype m1, m0; /* Normalize. */ b = W_TYPE_SIZE - bm; d1 = (d1 << bm) | (d0 >> b); d0 = d0 << bm; n2 = n1 >> b; n1 = (n1 << bm) | (n0 >> b); n0 = n0 << bm; udiv_qrnnd (q0, n1, n2, n1, d1); umul_ppmm (m1, m0, q0, d0); if (m1 > n1 || (m1 == n1 && m0 > n0)) { q0--; sub_ddmmss (m1, m0, m1, m0, d1, d0); } q1 = 0; /* Remainder in (n1n0 - m1m0) >> bm. */ if (rp != 0) { sub_ddmmss (n1, n0, n1, n0, m1, m0); rr.s.low = (n1 << b) | (n0 >> bm); rr.s.high = n1 >> bm; *rp = rr.ll; } } } } ww.s.low = q0; ww.s.high = q1; return ww.ll; } #endif #ifdef L_divdi3 DWtype __divdi3 (DWtype u, DWtype v) { word_type c = 0; DWunion uu, vv; DWtype w; uu.ll = u; vv.ll = v; if (uu.s.high < 0) c = ~c, uu.ll = -uu.ll; if (vv.s.high < 0) c = ~c, vv.ll = -vv.ll; w = __udivmoddi4 (uu.ll, vv.ll, (UDWtype *) 0); if (c) w = -w; return w; } #endif #ifdef L_moddi3 DWtype __moddi3 (DWtype u, DWtype v) { word_type c = 0; DWunion uu, vv; DWtype w; uu.ll = u; vv.ll = v; if (uu.s.high < 0) c = ~c, uu.ll = -uu.ll; if (vv.s.high < 0) vv.ll = -vv.ll; (void) __udivmoddi4 (uu.ll, vv.ll, &w); if (c) w = -w; return w; } #endif #ifdef L_umoddi3 UDWtype __umoddi3 (UDWtype u, UDWtype v) { UDWtype w; (void) __udivmoddi4 (u, v, &w); return w; } #endif #ifdef L_udivdi3 UDWtype __udivdi3 (UDWtype n, UDWtype d) { return __udivmoddi4 (n, d, (UDWtype *) 0); } #endif #ifdef L_cmpdi2 word_type __cmpdi2 (DWtype a, DWtype b) { DWunion au, bu; au.ll = a, bu.ll = b; if (au.s.high < bu.s.high) return 0; else if (au.s.high > bu.s.high) return 2; if ((UWtype) au.s.low < (UWtype) bu.s.low) return 0; else if ((UWtype) au.s.low > (UWtype) bu.s.low) return 2; return 1; } #endif #ifdef L_ucmpdi2 word_type __ucmpdi2 (DWtype a, DWtype b) { DWunion au, bu; au.ll = a, bu.ll = b; if ((UWtype) au.s.high < (UWtype) bu.s.high) return 0; else if ((UWtype) au.s.high > (UWtype) bu.s.high) return 2; if ((UWtype) au.s.low < (UWtype) bu.s.low) return 0; else if ((UWtype) au.s.low > (UWtype) bu.s.low) return 2; return 1; } #endif #if defined(L_fixunstfdi) && (LIBGCC2_LONG_DOUBLE_TYPE_SIZE == 128) #define WORD_SIZE (sizeof (Wtype) * BITS_PER_UNIT) #define HIGH_WORD_COEFF (((UDWtype) 1) << WORD_SIZE) DWtype __fixunstfDI (TFtype a) { TFtype b; UDWtype v; if (a < 0) return 0; /* Compute high word of result, as a flonum. */ b = (a / HIGH_WORD_COEFF); /* Convert that to fixed (but not to DWtype!), and shift it into the high word. */ v = (UWtype) b; v <<= WORD_SIZE; /* Remove high part from the TFtype, leaving the low part as flonum. */ a -= (TFtype)v; /* Convert that to fixed (but not to DWtype!) and add it in. Sometimes A comes out negative. This is significant, since A has more bits than a long int does. */ if (a < 0) v -= (UWtype) (- a); else v += (UWtype) a; return v; } #endif #if defined(L_fixtfdi) && (LIBGCC2_LONG_DOUBLE_TYPE_SIZE == 128) DWtype __fixtfdi (TFtype a) { if (a < 0) return - __fixunstfDI (-a); return __fixunstfDI (a); } #endif #if defined(L_fixunsxfdi) && (LIBGCC2_LONG_DOUBLE_TYPE_SIZE == 96) #define WORD_SIZE (sizeof (Wtype) * BITS_PER_UNIT) #define HIGH_WORD_COEFF (((UDWtype) 1) << WORD_SIZE) DWtype __fixunsxfDI (XFtype a) { XFtype b; UDWtype v; if (a < 0) return 0; /* Compute high word of result, as a flonum. */ b = (a / HIGH_WORD_COEFF); /* Convert that to fixed (but not to DWtype!), and shift it into the high word. */ v = (UWtype) b; v <<= WORD_SIZE; /* Remove high part from the XFtype, leaving the low part as flonum. */ a -= (XFtype)v; /* Convert that to fixed (but not to DWtype!) and add it in. Sometimes A comes out negative. This is significant, since A has more bits than a long int does. */ if (a < 0) v -= (UWtype) (- a); else v += (UWtype) a; return v; } #endif #if defined(L_fixxfdi) && (LIBGCC2_LONG_DOUBLE_TYPE_SIZE == 96) DWtype __fixxfdi (XFtype a) { if (a < 0) return - __fixunsxfDI (-a); return __fixunsxfDI (a); } #endif #ifdef L_fixunsdfdi #define WORD_SIZE (sizeof (Wtype) * BITS_PER_UNIT) #define HIGH_WORD_COEFF (((UDWtype) 1) << WORD_SIZE) DWtype __fixunsdfDI (DFtype a) { DFtype b; UDWtype v; if (a < 0) return 0; /* Compute high word of result, as a flonum. */ b = (a / HIGH_WORD_COEFF); /* Convert that to fixed (but not to DWtype!), and shift it into the high word. */ v = (UWtype) b; v <<= WORD_SIZE; /* Remove high part from the DFtype, leaving the low part as flonum. */ a -= (DFtype)v; /* Convert that to fixed (but not to DWtype!) and add it in. Sometimes A comes out negative. This is significant, since A has more bits than a long int does. */ if (a < 0) v -= (UWtype) (- a); else v += (UWtype) a; return v; } #endif #ifdef L_fixdfdi DWtype __fixdfdi (DFtype a) { if (a < 0) return - __fixunsdfDI (-a); return __fixunsdfDI (a); } #endif #ifdef L_fixunssfdi #define WORD_SIZE (sizeof (Wtype) * BITS_PER_UNIT) #define HIGH_WORD_COEFF (((UDWtype) 1) << WORD_SIZE) DWtype __fixunssfDI (SFtype original_a) { /* Convert the SFtype to a DFtype, because that is surely not going to lose any bits. Some day someone else can write a faster version that avoids converting to DFtype, and verify it really works right. */ DFtype a = original_a; DFtype b; UDWtype v; if (a < 0) return 0; /* Compute high word of result, as a flonum. */ b = (a / HIGH_WORD_COEFF); /* Convert that to fixed (but not to DWtype!), and shift it into the high word. */ v = (UWtype) b; v <<= WORD_SIZE; /* Remove high part from the DFtype, leaving the low part as flonum. */ a -= (DFtype) v; /* Convert that to fixed (but not to DWtype!) and add it in. Sometimes A comes out negative. This is significant, since A has more bits than a long int does. */ if (a < 0) v -= (UWtype) (- a); else v += (UWtype) a; return v; } #endif #ifdef L_fixsfdi DWtype __fixsfdi (SFtype a) { if (a < 0) return - __fixunssfDI (-a); return __fixunssfDI (a); } #endif #if defined(L_floatdixf) && (LIBGCC2_LONG_DOUBLE_TYPE_SIZE == 96) #define WORD_SIZE (sizeof (Wtype) * BITS_PER_UNIT) #define HIGH_HALFWORD_COEFF (((UDWtype) 1) << (WORD_SIZE / 2)) #define HIGH_WORD_COEFF (((UDWtype) 1) << WORD_SIZE) XFtype __floatdixf (DWtype u) { XFtype d; d = (Wtype) (u >> WORD_SIZE); d *= HIGH_HALFWORD_COEFF; d *= HIGH_HALFWORD_COEFF; d += (UWtype) (u & (HIGH_WORD_COEFF - 1)); return d; } #endif #if defined(L_floatditf) && (LIBGCC2_LONG_DOUBLE_TYPE_SIZE == 128) #define WORD_SIZE (sizeof (Wtype) * BITS_PER_UNIT) #define HIGH_HALFWORD_COEFF (((UDWtype) 1) << (WORD_SIZE / 2)) #define HIGH_WORD_COEFF (((UDWtype) 1) << WORD_SIZE) TFtype __floatditf (DWtype u) { TFtype d; d = (Wtype) (u >> WORD_SIZE); d *= HIGH_HALFWORD_COEFF; d *= HIGH_HALFWORD_COEFF; d += (UWtype) (u & (HIGH_WORD_COEFF - 1)); return d; } #endif #ifdef L_floatdidf #define WORD_SIZE (sizeof (Wtype) * BITS_PER_UNIT) #define HIGH_HALFWORD_COEFF (((UDWtype) 1) << (WORD_SIZE / 2)) #define HIGH_WORD_COEFF (((UDWtype) 1) << WORD_SIZE) DFtype __floatdidf (DWtype u) { DFtype d; d = (Wtype) (u >> WORD_SIZE); d *= HIGH_HALFWORD_COEFF; d *= HIGH_HALFWORD_COEFF; d += (UWtype) (u & (HIGH_WORD_COEFF - 1)); return d; } #endif #ifdef L_floatundidf #define WORD_SIZE (sizeof (Wtype) * BITS_PER_UNIT) #define HIGH_HALFWORD_COEFF (((UDWtype) 1) << (WORD_SIZE / 2)) #define HIGH_WORD_COEFF (((UDWtype) 1) << WORD_SIZE) DFtype __floatundidf (UDWtype u) { DFtype d; d = (UWtype) (u >> WORD_SIZE); d *= HIGH_HALFWORD_COEFF; d *= HIGH_HALFWORD_COEFF; d += (UWtype) (u & (HIGH_WORD_COEFF - 1)); return d; } #endif #ifdef L_floatdisf #define WORD_SIZE (sizeof (Wtype) * BITS_PER_UNIT) #define HIGH_HALFWORD_COEFF (((UDWtype) 1) << (WORD_SIZE / 2)) #define HIGH_WORD_COEFF (((UDWtype) 1) << WORD_SIZE) #define DI_SIZE (sizeof (DWtype) * BITS_PER_UNIT) #define DF_SIZE DBL_MANT_DIG #define SF_SIZE FLT_MANT_DIG SFtype __floatdisf (DWtype u) { /* Do the calculation in DFmode so that we don't lose any of the precision of the high word while multiplying it. */ DFtype f; /* Protect against double-rounding error. Represent any low-order bits, that might be truncated in DFmode, by a bit that won't be lost. The bit can go in anywhere below the rounding position of the SFmode. A fixed mask and bit position handles all usual configurations. It doesn't handle the case of 128-bit DImode, however. */ if (DF_SIZE < DI_SIZE && DF_SIZE > (DI_SIZE - DF_SIZE + SF_SIZE)) { #define REP_BIT ((UDWtype) 1 << (DI_SIZE - DF_SIZE)) if (! (- ((DWtype) 1 << DF_SIZE) < u && u < ((DWtype) 1 << DF_SIZE))) { if ((UDWtype) u & (REP_BIT - 1)) { u &= ~ (REP_BIT - 1); u |= REP_BIT; } } } f = (Wtype) (u >> WORD_SIZE); f *= HIGH_HALFWORD_COEFF; f *= HIGH_HALFWORD_COEFF; f += (UWtype) (u & (HIGH_WORD_COEFF - 1)); return (SFtype) f; } #endif #if defined(L_fixunsxfsi) && LIBGCC2_LONG_DOUBLE_TYPE_SIZE == 96 /* Reenable the normal types, in case limits.h needs them. */ #undef char #undef short #undef int #undef long #undef unsigned #undef float #undef double #undef MIN #undef MAX #include <limits.h> UWtype __fixunsxfSI (XFtype a) { if (a >= - (DFtype) Wtype_MIN) return (Wtype) (a + Wtype_MIN) - Wtype_MIN; return (Wtype) a; } #endif #ifdef L_fixunsdfsi /* Reenable the normal types, in case limits.h needs them. */ #undef char #undef short #undef int #undef long #undef unsigned #undef float #undef double #undef MIN #undef MAX //#include <limits.h> UWtype __fixunsdfSI (DFtype a) { if (a >= - (DFtype) Wtype_MIN) return (Wtype) (a + Wtype_MIN) - Wtype_MIN; return (Wtype) a; } EXPORT_SYMBOL(__fixunsdfSI); #endif #ifdef L_fixunssfsi /* Reenable the normal types, in case limits.h needs them. */ #undef char #undef short #undef int #undef long #undef unsigned #undef float #undef double #undef MIN #undef MAX //#include <limits.h> UWtype __fixunssfSI (SFtype a) { if (a >= - (SFtype) Wtype_MIN) return (Wtype) (a + Wtype_MIN) - Wtype_MIN; return (Wtype) a; } EXPORT_SYMBOL(__fixunssfSI); #endif /* From here on down, the routines use normal data types. */ #define SItype bogus_type #define USItype bogus_type #define DItype bogus_type #define UDItype bogus_type #define SFtype bogus_type #define DFtype bogus_type #undef Wtype #undef UWtype #undef HWtype #undef UHWtype #undef DWtype #undef UDWtype #undef char #undef short #undef int #undef long #undef unsigned #undef float #undef double #ifdef L_divdi3 EXPORT_SYMBOL(__divdi3); #endif #ifdef L_moddi3 EXPORT_SYMBOL(__moddi3); #endif #ifdef L_udivdi3 EXPORT_SYMBOL(__udivdi3); #endif #ifdef L__gcc_bcmp /* Like bcmp except the sign is meaningful. Result is negative if S1 is less than S2, positive if S1 is greater, 0 if S1 and S2 are equal. */ int __gcc_bcmp (const unsigned char *s1, const unsigned char *s2, size_t size) { while (size > 0) { unsigned char c1 = *s1++, c2 = *s2++; if (c1 != c2) return c1 - c2; size--; } return 0; } #endif /* __eprintf used to be used by GCC's private version of <assert.h>. We no longer provide that header, but this routine remains in libgcc.a for binary backward compatibility. Note that it is not included in the shared version of libgcc. */ #ifdef L_eprintf #ifndef inhibit_libc #undef NULL /* Avoid errors if stdio.h and our stddef.h mismatch. */ #include <stdio.h> void __eprintf (const char *string, const char *expression, unsigned int line, const char *filename) { fprintf (stderr, string, expression, line, filename); fflush (stderr); abort (); } #endif #endif #ifdef L_bb struct bb_function_info { long checksum; int arc_count; const char *name; }; /* Structure emitted by --profile-arcs */ struct bb { long zero_word; const char *filename; gcov_type *counts; long ncounts; struct bb *next; /* Older GCC's did not emit these fields. */ long sizeof_bb; struct bb_function_info *function_infos; }; #ifndef inhibit_libc /* Arc profile dumper. Requires atexit and stdio. */ #undef NULL /* Avoid errors if stdio.h and our stddef.h mismatch. */ #include <stdio.h> #include "gcov-io.h" #include <string.h> #ifdef TARGET_HAS_F_SETLKW #include <fcntl.h> #include <errno.h> #endif /* Chain of per-object file bb structures. */ static struct bb *bb_head; /* Dump the coverage counts. We merge with existing counts when possible, to avoid growing the .da files ad infinitum. */ void __bb_exit_func (void) { struct bb *ptr; int i; gcov_type program_sum = 0; gcov_type program_max = 0; long program_arcs = 0; gcov_type merged_sum = 0; gcov_type merged_max = 0; long merged_arcs = 0; #if defined (TARGET_HAS_F_SETLKW) struct flock s_flock; s_flock.l_type = F_WRLCK; s_flock.l_whence = SEEK_SET; s_flock.l_start = 0; s_flock.l_len = 0; /* Until EOF. */ s_flock.l_pid = getpid (); #endif /* Non-merged stats for this program. */ for (ptr = bb_head; ptr; ptr = ptr->next) { for (i = 0; i < ptr->ncounts; i++) { program_sum += ptr->counts[i]; if (ptr->counts[i] > program_max) program_max = ptr->counts[i]; } program_arcs += ptr->ncounts; } for (ptr = bb_head; ptr; ptr = ptr->next) { FILE *da_file; gcov_type object_max = 0; gcov_type object_sum = 0; long object_functions = 0; int merging = 0; int error = 0; struct bb_function_info *fn_info; gcov_type *count_ptr; /* Open for modification */ da_file = fopen (ptr->filename, "r+b"); if (da_file) merging = 1; else { /* Try for appending */ da_file = fopen (ptr->filename, "ab"); /* Some old systems might not allow the 'b' mode modifier. Therefore, try to open without it. This can lead to a race condition so that when you delete and re-create the file, the file might be opened in text mode, but then, you shouldn't delete the file in the first place. */ if (!da_file) da_file = fopen (ptr->filename, "a"); } if (!da_file) { fprintf (stderr, "arc profiling: Can't open output file %s.\n", ptr->filename); ptr->filename = 0; continue; } #if defined (TARGET_HAS_F_SETLKW) /* After a fork, another process might try to read and/or write the same file simultanously. So if we can, lock the file to avoid race conditions. */ while (fcntl (fileno (da_file), F_SETLKW, &s_flock) && errno == EINTR) continue; #endif for (fn_info = ptr->function_infos; fn_info->arc_count != -1; fn_info++) object_functions++; if (merging) { /* Merge data from file. */ long tmp_long; gcov_type tmp_gcov; if (/* magic */ (__read_long (&tmp_long, da_file, 4) || tmp_long != -123l) /* functions in object file. */ || (__read_long (&tmp_long, da_file, 4) || tmp_long != object_functions) /* extension block, skipped */ || (__read_long (&tmp_long, da_file, 4) || fseek (da_file, tmp_long, SEEK_CUR))) { read_error:; fprintf (stderr, "arc profiling: Error merging output file %s.\n", ptr->filename); clearerr (da_file); } else { /* Merge execution counts for each function. */ count_ptr = ptr->counts; for (fn_info = ptr->function_infos; fn_info->arc_count != -1; fn_info++) { if (/* function name delim */ (__read_long (&tmp_long, da_file, 4) || tmp_long != -1) /* function name length */ || (__read_long (&tmp_long, da_file, 4) || tmp_long != (long) strlen (fn_info->name)) /* skip string */ || fseek (da_file, ((tmp_long + 1) + 3) & ~3, SEEK_CUR) /* function name delim */ || (__read_long (&tmp_long, da_file, 4) || tmp_long != -1)) goto read_error; if (/* function checksum */ (__read_long (&tmp_long, da_file, 4) || tmp_long != fn_info->checksum) /* arc count */ || (__read_long (&tmp_long, da_file, 4) || tmp_long != fn_info->arc_count)) goto read_error; for (i = fn_info->arc_count; i > 0; i--, count_ptr++) if (__read_gcov_type (&tmp_gcov, da_file, 8)) goto read_error; else *count_ptr += tmp_gcov; } } fseek (da_file, 0, SEEK_SET); } /* Calculate the per-object statistics. */ for (i = 0; i < ptr->ncounts; i++) { object_sum += ptr->counts[i]; if (ptr->counts[i] > object_max) object_max = ptr->counts[i]; } merged_sum += object_sum; if (merged_max < object_max) merged_max = object_max; merged_arcs += ptr->ncounts; /* Write out the data. */ if (/* magic */ __write_long (-123, da_file, 4) /* number of functions in object file. */ || __write_long (object_functions, da_file, 4) /* length of extra data in bytes. */ || __write_long ((4 + 8 + 8) + (4 + 8 + 8), da_file, 4) /* whole program statistics. If merging write per-object now, rewrite later */ /* number of instrumented arcs. */ || __write_long (merging ? ptr->ncounts : program_arcs, da_file, 4) /* sum of counters. */ || __write_gcov_type (merging ? object_sum : program_sum, da_file, 8) /* maximal counter. */ || __write_gcov_type (merging ? object_max : program_max, da_file, 8) /* per-object statistics. */ /* number of counters. */ || __write_long (ptr->ncounts, da_file, 4) /* sum of counters. */ || __write_gcov_type (object_sum, da_file, 8) /* maximal counter. */ || __write_gcov_type (object_max, da_file, 8)) { write_error:; fprintf (stderr, "arc profiling: Error writing output file %s.\n", ptr->filename); error = 1; } else { /* Write execution counts for each function. */ count_ptr = ptr->counts; for (fn_info = ptr->function_infos; fn_info->arc_count != -1; fn_info++) { if (__write_gcov_string (fn_info->name, strlen (fn_info->name), da_file, -1) || __write_long (fn_info->checksum, da_file, 4) || __write_long (fn_info->arc_count, da_file, 4)) goto write_error; for (i = fn_info->arc_count; i > 0; i--, count_ptr++) if (__write_gcov_type (*count_ptr, da_file, 8)) goto write_error; /* RIP Edsger Dijkstra */ } } if (fclose (da_file)) { fprintf (stderr, "arc profiling: Error closing output file %s.\n", ptr->filename); error = 1; } if (error || !merging) ptr->filename = 0; } /* Upate whole program statistics. */ for (ptr = bb_head; ptr; ptr = ptr->next) if (ptr->filename) { FILE *da_file; da_file = fopen (ptr->filename, "r+b"); if (!da_file) { fprintf (stderr, "arc profiling: Cannot reopen %s.\n", ptr->filename); continue; } #if defined (TARGET_HAS_F_SETLKW) while (fcntl (fileno (da_file), F_SETLKW, &s_flock) && errno == EINTR) continue; #endif if (fseek (da_file, 4 * 3, SEEK_SET) /* number of instrumented arcs. */ || __write_long (merged_arcs, da_file, 4) /* sum of counters. */ || __write_gcov_type (merged_sum, da_file, 8) /* maximal counter. */ || __write_gcov_type (merged_max, da_file, 8)) fprintf (stderr, "arc profiling: Error updating program header %s.\n", ptr->filename); if (fclose (da_file)) fprintf (stderr, "arc profiling: Error reclosing %s\n", ptr->filename); } } /* Add a new object file onto the bb chain. Invoked automatically when running an object file's global ctors. */ void __bb_init_func (struct bb *blocks) { if (blocks->zero_word) return; /* Initialize destructor and per-thread data. */ if (!bb_head) atexit (__bb_exit_func); /* Set up linked list. */ blocks->zero_word = 1; blocks->next = bb_head; bb_head = blocks; } /* Called before fork or exec - write out profile information gathered so far and reset it to zero. This avoids duplication or loss of the profile information gathered so far. */ void __bb_fork_func (void) { struct bb *ptr; __bb_exit_func (); for (ptr = bb_head; ptr != (struct bb *) 0; ptr = ptr->next) { long i; for (i = ptr->ncounts - 1; i >= 0; i--) ptr->counts[i] = 0; } } #endif /* not inhibit_libc */ #endif /* L_bb */ #ifdef L_clear_cache /* Clear part of an instruction cache. */ #define INSN_CACHE_PLANE_SIZE (INSN_CACHE_SIZE / INSN_CACHE_DEPTH) void __clear_cache (char *beg __attribute__((__unused__)), char *end __attribute__((__unused__))) { #ifdef CLEAR_INSN_CACHE CLEAR_INSN_CACHE (beg, end); #else #ifdef INSN_CACHE_SIZE static char array[INSN_CACHE_SIZE + INSN_CACHE_PLANE_SIZE + INSN_CACHE_LINE_WIDTH]; static int initialized; int offset; void *start_addr void *end_addr; typedef (*function_ptr) (void); #if (INSN_CACHE_SIZE / INSN_CACHE_LINE_WIDTH) < 16 /* It's cheaper to clear the whole cache. Put in a series of jump instructions so that calling the beginning of the cache will clear the whole thing. */ if (! initialized) { int ptr = (((int) array + INSN_CACHE_LINE_WIDTH - 1) & -INSN_CACHE_LINE_WIDTH); int end_ptr = ptr + INSN_CACHE_SIZE; while (ptr < end_ptr) { *(INSTRUCTION_TYPE *)ptr = JUMP_AHEAD_INSTRUCTION + INSN_CACHE_LINE_WIDTH; ptr += INSN_CACHE_LINE_WIDTH; } *(INSTRUCTION_TYPE *) (ptr - INSN_CACHE_LINE_WIDTH) = RETURN_INSTRUCTION; initialized = 1; } /* Call the beginning of the sequence. */ (((function_ptr) (((int) array + INSN_CACHE_LINE_WIDTH - 1) & -INSN_CACHE_LINE_WIDTH)) ()); #else /* Cache is large. */ if (! initialized) { int ptr = (((int) array + INSN_CACHE_LINE_WIDTH - 1) & -INSN_CACHE_LINE_WIDTH); while (ptr < (int) array + sizeof array) { *(INSTRUCTION_TYPE *)ptr = RETURN_INSTRUCTION; ptr += INSN_CACHE_LINE_WIDTH; } initialized = 1; } /* Find the location in array that occupies the same cache line as BEG. */ offset = ((int) beg & -INSN_CACHE_LINE_WIDTH) & (INSN_CACHE_PLANE_SIZE - 1); start_addr = (((int) (array + INSN_CACHE_PLANE_SIZE - 1) & -INSN_CACHE_PLANE_SIZE) + offset); /* Compute the cache alignment of the place to stop clearing. */ #if 0 /* This is not needed for gcc's purposes. */ /* If the block to clear is bigger than a cache plane, we clear the entire cache, and OFFSET is already correct. */ if (end < beg + INSN_CACHE_PLANE_SIZE) #endif offset = (((int) (end + INSN_CACHE_LINE_WIDTH - 1) & -INSN_CACHE_LINE_WIDTH) & (INSN_CACHE_PLANE_SIZE - 1)); #if INSN_CACHE_DEPTH > 1 end_addr = (start_addr & -INSN_CACHE_PLANE_SIZE) + offset; if (end_addr <= start_addr) end_addr += INSN_CACHE_PLANE_SIZE; for (plane = 0; plane < INSN_CACHE_DEPTH; plane++) { int addr = start_addr + plane * INSN_CACHE_PLANE_SIZE; int stop = end_addr + plane * INSN_CACHE_PLANE_SIZE; while (addr != stop) { /* Call the return instruction at ADDR. */ ((function_ptr) addr) (); addr += INSN_CACHE_LINE_WIDTH; } } #else /* just one plane */ do { /* Call the return instruction at START_ADDR. */ ((function_ptr) start_addr) (); start_addr += INSN_CACHE_LINE_WIDTH; } while ((start_addr % INSN_CACHE_SIZE) != offset); #endif /* just one plane */ #endif /* Cache is large */ #endif /* Cache exists */ #endif /* CLEAR_INSN_CACHE */ } #endif /* L_clear_cache */ #ifdef L_trampoline /* Jump to a trampoline, loading the static chain address. */ #if defined(WINNT) && ! defined(__CYGWIN__) && ! defined (_UWIN) long getpagesize (void) { #ifdef _ALPHA_ return 8192; #else return 4096; #endif } #ifdef __i386__ extern int VirtualProtect (char *, int, int, int *) __attribute__((stdcall)); #endif int mprotect (char *addr, int len, int prot) { int np, op; if (prot == 7) np = 0x40; else if (prot == 5) np = 0x20; else if (prot == 4) np = 0x10; else if (prot == 3) np = 0x04; else if (prot == 1) np = 0x02; else if (prot == 0) np = 0x01; if (VirtualProtect (addr, len, np, &op)) return 0; else return -1; } #endif /* WINNT && ! __CYGWIN__ && ! _UWIN */ #ifdef TRANSFER_FROM_TRAMPOLINE TRANSFER_FROM_TRAMPOLINE #endif #ifdef __sysV68__ #include <sys/signal.h> #include <errno.h> /* Motorola forgot to put memctl.o in the libp version of libc881.a, so define it here, because we need it in __clear_insn_cache below */ /* On older versions of this OS, no memctl or MCT_TEXT are defined; hence we enable this stuff only if MCT_TEXT is #define'd. */ #ifdef MCT_TEXT asm("\n\ global memctl\n\ memctl:\n\ movq &75,%d0\n\ trap &0\n\ bcc.b noerror\n\ jmp cerror%\n\ noerror:\n\ movq &0,%d0\n\ rts"); #endif /* Clear instruction cache so we can call trampolines on stack. This is called from FINALIZE_TRAMPOLINE in mot3300.h. */ void __clear_insn_cache (void) { #ifdef MCT_TEXT int save_errno; /* Preserve errno, because users would be surprised to have errno changing without explicitly calling any system-call. */ save_errno = errno; /* Keep it simple : memctl (MCT_TEXT) always fully clears the insn cache. No need to use an address derived from _start or %sp, as 0 works also. */ memctl(0, 4096, MCT_TEXT); errno = save_errno; #endif } #endif /* __sysV68__ */ #endif /* L_trampoline */ #ifndef __CYGWIN__ #ifdef L__main #include "gbl-ctors.h" /* Some systems use __main in a way incompatible with its use in gcc, in these cases use the macros NAME__MAIN to give a quoted symbol and SYMBOL__MAIN to give the same symbol without quotes for an alternative entry point. You must define both, or neither. */ #ifndef NAME__MAIN #define NAME__MAIN "__main" #define SYMBOL__MAIN __main #endif #ifdef INIT_SECTION_ASM_OP #undef HAS_INIT_SECTION #define HAS_INIT_SECTION #endif #if !defined (HAS_INIT_SECTION) || !defined (OBJECT_FORMAT_ELF) /* Some ELF crosses use crtstuff.c to provide __CTOR_LIST__, but use this code to run constructors. In that case, we need to handle EH here, too. */ #ifdef EH_FRAME_SECTION_NAME #include "unwind-dw2-fde.h" extern unsigned char __EH_FRAME_BEGIN__[]; #endif /* Run all the global destructors on exit from the program. */ void __do_global_dtors (void) { #ifdef DO_GLOBAL_DTORS_BODY DO_GLOBAL_DTORS_BODY; #else static func_ptr *p = __DTOR_LIST__ + 1; while (*p) { p++; (*(p-1)) (); } #endif #if defined (EH_FRAME_SECTION_NAME) && !defined (HAS_INIT_SECTION) { static int completed = 0; if (! completed) { completed = 1; __deregister_frame_info (__EH_FRAME_BEGIN__); } } #endif } #endif #ifndef HAS_INIT_SECTION /* Run all the global constructors on entry to the program. */ void __do_global_ctors (void) { #ifdef EH_FRAME_SECTION_NAME { static struct object object; __register_frame_info (__EH_FRAME_BEGIN__, &object); } #endif DO_GLOBAL_CTORS_BODY; atexit (__do_global_dtors); } #endif /* no HAS_INIT_SECTION */ #if !defined (HAS_INIT_SECTION) || defined (INVOKE__main) /* Subroutine called automatically by `main'. Compiling a global function named `main' produces an automatic call to this function at the beginning. For many systems, this routine calls __do_global_ctors. For systems which support a .init section we use the .init section to run __do_global_ctors, so we need not do anything here. */ void SYMBOL__MAIN () { /* Support recursive calls to `main': run initializers just once. */ static int initialized; if (! initialized) { initialized = 1; __do_global_ctors (); } } #endif /* no HAS_INIT_SECTION or INVOKE__main */ #endif /* L__main */ #endif /* __CYGWIN__ */ #ifdef L_ctors #include "gbl-ctors.h" /* Provide default definitions for the lists of constructors and destructors, so that we don't get linker errors. These symbols are intentionally bss symbols, so that gld and/or collect will provide the right values. */ /* We declare the lists here with two elements each, so that they are valid empty lists if no other definition is loaded. If we are using the old "set" extensions to have the gnu linker collect ctors and dtors, then we __CTOR_LIST__ and __DTOR_LIST__ must be in the bss/common section. Long term no port should use those extensions. But many still do. */ #if !defined(INIT_SECTION_ASM_OP) && !defined(CTOR_LISTS_DEFINED_EXTERNALLY) #if defined (TARGET_ASM_CONSTRUCTOR) || defined (USE_COLLECT2) func_ptr __CTOR_LIST__[2] = {0, 0}; func_ptr __DTOR_LIST__[2] = {0, 0}; #else func_ptr __CTOR_LIST__[2]; func_ptr __DTOR_LIST__[2]; #endif #endif /* no INIT_SECTION_ASM_OP and not CTOR_LISTS_DEFINED_EXTERNALLY */ #endif /* L_ctors */ #ifdef L_exit #include "gbl-ctors.h" #ifdef NEED_ATEXIT #ifndef ON_EXIT # include <errno.h> static func_ptr *atexit_chain = 0; static long atexit_chain_length = 0; static volatile long last_atexit_chain_slot = -1; int atexit (func_ptr func) { if (++last_atexit_chain_slot == atexit_chain_length) { atexit_chain_length += 32; if (atexit_chain) atexit_chain = (func_ptr *) realloc (atexit_chain, atexit_chain_length * sizeof (func_ptr)); else atexit_chain = (func_ptr *) malloc (atexit_chain_length * sizeof (func_ptr)); if (! atexit_chain) { atexit_chain_length = 0; last_atexit_chain_slot = -1; errno = ENOMEM; return (-1); } } atexit_chain[last_atexit_chain_slot] = func; return (0); } extern void _cleanup (void); extern void _exit (int) __attribute__ ((__noreturn__)); void exit (int status) { if (atexit_chain) { for ( ; last_atexit_chain_slot-- >= 0; ) { (*atexit_chain[last_atexit_chain_slot + 1]) (); atexit_chain[last_atexit_chain_slot + 1] = 0; } free (atexit_chain); atexit_chain = 0; } #ifdef EXIT_BODY EXIT_BODY; #else _cleanup (); #endif _exit (status); } #else /* ON_EXIT */ /* Simple; we just need a wrapper for ON_EXIT. */ int atexit (func_ptr func) { return ON_EXIT (func); } #endif /* ON_EXIT */ #endif /* NEED_ATEXIT */ #endif /* L_exit */
21.22484
85
0.612976
[ "object" ]
c195af1538c2a12d4ac1937d037ef5e5d6589b1d
20,432
h
C
src/Calculate.h
BGI-shenzhen/PopLDdecay
55123e0b00776a5bd3cb794bd969c6fc9d7ef6e9
[ "MIT" ]
151
2016-05-20T09:51:29.000Z
2022-03-17T08:47:54.000Z
src/Calculate.h
altingia/PopLDdecay
d9c63f4f812a44de4ab40e665d297a1020fa8cd4
[ "MIT" ]
14
2017-04-12T00:48:38.000Z
2022-03-30T19:09:21.000Z
src/Calculate.h
altingia/PopLDdecay
d9c63f4f812a44de4ab40e665d297a1020fa8cd4
[ "MIT" ]
45
2016-05-20T09:51:35.000Z
2022-01-17T04:47:05.000Z
#ifndef calculate_H_ #define calculate_H_ using namespace std; ///////////////////////// method1 ///////////////////////////////// int cal_RR_MA ( vector<BaseType> & Base1 , vector<BaseType> & Base2 , double & CalResult, statementVar & Var ) { Var.DDE[0][0]=0; Var.DDE[0][1]=0; Var.DDE[1][0]=0; Var.DDE[1][1]=0; for (Var.i=0 ;Var.i<Var.Asize ; (Var.i)++) { Var.DDE[(Base1[Var.i].Value)][(Base2[Var.i].Value)]++ ; } Var.tmpAA=(Var.DDE[1][1])+(Var.DDE[1][0]); if (Var.tmpAA==0) { return 0 ; } if ( (Var.DDE[1][1]+Var.DDE[0][1])==0) { return 0 ; } Var.ALL_count=Var.DDE[0][0]+Var.DDE[0][1]+Var.tmpAA; Var.probHaps[0]=((Var.DDE[0][0])/Var.ALL_count); Var.probHaps[1]=((Var.DDE[0][1])/Var.ALL_count); Var.probHaps[2]=((Var.DDE[1][0])/Var.ALL_count); Var.pA1 = Var.probHaps[0]+Var.probHaps[1]; Var.pA2 = Var.probHaps[0]+Var.probHaps[2]; Var.Cal_B=(Var.pA1)*(Var.pA2); Var.Cal_A = 1.0-(Var.pA1+Var.pA2)+Var.Cal_B ; if (Var.Cal_A==0 || Var.Cal_B==0 ) { if (Var.probHaps[0] < 1e-10) { Var.probHaps[0]=1e-10;} if (Var.probHaps[1] < 1e-10) { Var.probHaps[1]=1e-10;} if (Var.probHaps[2] < 1e-10) { Var.probHaps[2]=1e-10;} Var.pA1 = Var.probHaps[0]+Var.probHaps[1]; Var.pA2 = Var.probHaps[0]+Var.probHaps[2]; Var.Cal_B = (Var.pA1)*(Var.pA2); Var.Cal_A = 1.0-(Var.pA1+Var.pA2)+Var.Cal_B ; } Var.D_A = Var.probHaps[0]-Var.Cal_B ; CalResult = (Var.D_A*Var.D_A)/(Var.Cal_A*Var.Cal_B); return 1; } int cal_RR_D_MA(vector<BaseType> & Base1 , vector<BaseType> & Base2 , PairInfoV1 & CalResult, statementVar & Var) { Var.DDE[0][0]=0; Var.DDE[0][1]=0; Var.DDE[1][0]=0; Var.DDE[1][1]=0; for (Var.i=0 ;Var.i<Var.Asize ; (Var.i)++) { Var.DDE[(Base1[Var.i].Value)][(Base2[Var.i].Value)]++; } Var.tmpAA=Var.DDE[1][1]+Var.DDE[1][0]; if (Var.tmpAA==0) { return 0 ; } if ( (Var.DDE[1][1]+Var.DDE[0][1])==0) { return 0 ; } Var.ALL_count=Var.DDE[0][0]+Var.DDE[0][1]+Var.tmpAA; Var.probHaps[0]=((Var.DDE[0][0])/Var.ALL_count); Var.probHaps[1]=((Var.DDE[0][1])/Var.ALL_count); Var.probHaps[2]=((Var.DDE[1][0])/Var.ALL_count); Var.pA1 = Var.probHaps[0]+Var.probHaps[1]; Var.pB1 = 1.0-Var.pA1; Var.pA2 = Var.probHaps[0]+Var.probHaps[2]; Var.pB2 = 1.0-Var.pA2; Var.XpA1_pA2=Var.pA1*Var.pA2; Var.D_A = Var.probHaps[0]-Var.XpA1_pA2 ; if (Var.D_A>0) { Var.Cal_A=Var.pB1*Var.pA2; Var.Cal_B=Var.pA1*Var.pB2; } else { Var.D_A = 0.0-Var.D_A; Var.Cal_A = (Var.pB1)*(Var.pB2); Var.Cal_B = Var.XpA1_pA2 ; } Var.D_max=Var.Cal_A; if (Var.Cal_A>Var.Cal_B) { Var.D_max=Var.Cal_B; } if (Var.D_max==0) { if (Var.probHaps[0] < 1e-10) { Var.probHaps[0]=1e-10;} if (Var.probHaps[1] < 1e-10) { Var.probHaps[1]=1e-10;} if (Var.probHaps[2] < 1e-10) { Var.probHaps[2]=1e-10;} Var.pA1 = Var.probHaps[0]+Var.probHaps[1]; Var.pB1 = 1.0-Var.pA1; Var.pA2 = Var.probHaps[0]+Var.probHaps[2]; Var.pB2 = 1.0-Var.pA2; Var.XpA1_pA2=Var.pA1*Var.pA2; Var.D_A = Var.probHaps[0]-Var.XpA1_pA2 ; if (Var.D_A>0) { Var.Cal_A=Var.pB1*Var.pA2; Var.Cal_B=Var.pA1*Var.pB2; } else { Var.D_A = 0.0-Var.D_A; Var.Cal_A = (Var.pB1)*(Var.pB2); Var.Cal_B = Var.XpA1_pA2 ; } Var.D_max=Var.Cal_A; if (Var.Cal_A>Var.Cal_B) { Var.D_max=Var.Cal_B; } } CalResult.D = Var.D_A/Var.D_max; CalResult.RR = (Var.D_A/Var.Cal_A)*(Var.D_A/Var.Cal_B); return 1; } int cal_RR_D2_MA( vector<BaseType> & Base1 , vector<BaseType> & Base2 , PairInfoV2 & CalResult , statementVar & Var ) { Var.DDE[0][0]=0; Var.DDE[0][1]=0; Var.DDE[1][0]=0; Var.DDE[1][1]=0; for (Var.i=0 ;Var.i<Var.Asize ; (Var.i)++) { Var.DDE[(Base1[Var.i].Value)][(Base2[Var.i].Value)]++; } Var.known[0]=Var.DDE[0][0]; Var.known[1]=Var.DDE[0][1]; Var.known[2]=Var.DDE[1][0]; Var.known[3]=Var.DDE[1][1]; Var.tmpAA=Var.known[3]+Var.known[2]; if ( Var.tmpAA==0 ) { return 0 ; } else if ( (Var.known[3]+Var.known[1])==0) { return 0 ; } Var.ALL_count=Var.known[0]+Var.known[1]+Var.tmpAA; Var.probHaps[0]=(Var.known[0])/Var.ALL_count; Var.probHaps[1]=(Var.known[1])/Var.ALL_count; Var.probHaps[2]=(Var.known[2])/Var.ALL_count; Var.probHaps[3]=1-Var.probHaps[0]-Var.probHaps[1]-Var.probHaps[2]; if (Var.probHaps[0] < 1e-10) { Var.probHaps[0]=1e-10;} if (Var.probHaps[1] < 1e-10) { Var.probHaps[1]=1e-10;} if (Var.probHaps[2] < 1e-10) { Var.probHaps[2]=1e-10;} if (Var.probHaps[3] < 1e-10) { Var.probHaps[3]=1e-10;} Var.pA1 = Var.probHaps[0]+Var.probHaps[1]; Var.pB1 = 1.0-Var.pA1; Var.pA2 = Var.probHaps[0]+Var.probHaps[2]; Var.pB2 = 1.0-Var.pA2; Var.XpA1_pA2=Var.pA1*Var.pA2; Var.XpA1_pB2=Var.pA1*Var.pB2; Var.XpB1_pA2=Var.pB1*Var.pA2; Var.XpB1_pB2=Var.pB1*Var.pB2; Var.loglike1 =( Var.known[0]*log(Var.probHaps[0]) + Var.known[1]*log(Var.probHaps[1]) + Var.known[2]*log(Var.probHaps[2]) + Var.known[3]*log(Var.probHaps[3]))/Var.LN10; Var.loglike0 =( Var.known[0]*log(Var.XpA1_pA2) + Var.known[1]*log(Var.XpA1_pB2) + Var.known[2]*log(Var.XpB1_pA2) + Var.known[3]*log(Var.XpB1_pB2))/Var.LN10; Var.D_A = Var.probHaps[0]-Var.XpA1_pA2 ; if (Var.D_A < 0 ) { Var.D_A = 0.0-Var.D_A; Var.Cal_A = Var.XpB1_pB2; Var.Cal_B = Var.XpA1_pA2 ; } else { Var.Cal_A = Var.XpB1_pA2; Var.Cal_B = Var.XpA1_pB2; } //Var.D_max=min(Var.Cal_A,Var.Cal_B); Var.D_max=Var.Cal_A; if (Var.Cal_A>Var.Cal_B) { Var.D_max=Var.Cal_B; } CalResult.D = Var.D_A/Var.D_max; CalResult.RR = (Var.D_A/Var.Cal_A)*(Var.D_A/Var.Cal_B); CalResult.LOD=(Var.loglike1-Var.loglike0); return 1; } int cal_RR_D3_MA( vector<BaseType> & Base1 , vector<BaseType> & Base2 , PairInfoV3 & CalResult , statementVar & Var ) { Var.DDE[0][0]=0; Var.DDE[0][1]=0; Var.DDE[1][0]=0; Var.DDE[1][1]=0; for (Var.i=0 ;Var.i<Var.Asize ; (Var.i)++) { Var.DDE[(Base1[Var.i].Value)][(Base2[Var.i].Value)]++; } Var.known[0]=Var.DDE[0][0]; Var.known[1]=Var.DDE[0][1]; Var.known[2]=Var.DDE[1][0]; Var.known[3]=Var.DDE[1][1]; Var.tmpAA=Var.known[3]+Var.known[2]; if ( Var.tmpAA==0 ) { return 0 ; } else if ( (Var.known[3]+Var.known[1])==0) { return 0 ; } Var.ALL_count=Var.known[0]+Var.known[1]+Var.tmpAA; Var.probHaps[0]=(Var.known[0])/Var.ALL_count; Var.probHaps[1]=(Var.known[1])/Var.ALL_count; Var.probHaps[2]=(Var.known[2])/Var.ALL_count; Var.probHaps[3]=1-Var.probHaps[0]-Var.probHaps[1]-Var.probHaps[2]; if (Var.probHaps[0] < 1e-10) { Var.probHaps[0]=1e-10;} if (Var.probHaps[1] < 1e-10) { Var.probHaps[1]=1e-10;} if (Var.probHaps[2] < 1e-10) { Var.probHaps[2]=1e-10;} if (Var.probHaps[3] < 1e-10) { Var.probHaps[3]=1e-10;} Var.pA1 = Var.probHaps[0]+Var.probHaps[1]; Var.pB1 = 1.0-Var.pA1; Var.pA2 = Var.probHaps[0]+Var.probHaps[2]; Var.pB2 = 1.0-Var.pA2; Var.XpA1_pA2=Var.pA1*Var.pA2; Var.XpA1_pB2=Var.pA1*Var.pB2; Var.XpB1_pA2=Var.pB1*Var.pA2; Var.XpB1_pB2=Var.pB1*Var.pB2; // if (XpA1_pA2<1e-10 ){XpA1_pA2=1e-10;} if (XpA1_pB2<1e-10 ){XpA1_pB2=1e-10;} if (XpB1_pA2<1e-10 ){XpB1_pA2=1e-10;} if (XpB1_pB2<1e-10 ){XpB1_pB2=1e-10;} Var.loglike1 =( Var.known[0]*log(Var.probHaps[0]) + Var.known[1]*log(Var.probHaps[1]) + Var.known[2]*log(Var.probHaps[2]) + Var.known[3]*log(Var.probHaps[3]))/Var.LN10; Var.loglike0 =( Var.known[0]*log(Var.XpA1_pA2) + Var.known[1]*log(Var.XpA1_pB2) + Var.known[2]*log(Var.XpB1_pA2) + Var.known[3]*log(Var.XpB1_pB2))/Var.LN10; Var.D_A = Var.probHaps[0]-Var.XpA1_pA2 ; if (Var.D_A< 0 ) { // ALL_count is tmp Var.ALL_count=Var.probHaps[0]; Var.probHaps[0]=Var.probHaps[1]; Var.probHaps[1]=Var.ALL_count; Var.ALL_count=Var.probHaps[3]; Var.probHaps[3]=Var.probHaps[2]; Var.probHaps[2]=Var.ALL_count; Var.pA2 = Var.pA2 + Var.pB2; Var.pB2 = Var.pA2 - Var.pB2; Var.pA2 = Var.pA2 - Var.pB2; Var.D_A = 0.0-Var.D_A; Var.ALL_count=Var.known[0]; Var.known[0]=Var.known[1]; Var.known[1]=Var.ALL_count; Var.ALL_count=Var.known[3]; Var.known[3]=Var.known[2]; Var.known[2]=Var.ALL_count; Var.Cal_A = (Var.pA2)*(Var.pB1); Var.Cal_B = (Var.pA1)*(Var.pB2); } else { Var.Cal_A = Var.XpB1_pA2; Var.Cal_B = Var.XpA1_pB2; } //Var.D_max=min(Var.Cal_A,Var.Cal_B); Var.D_max=Var.Cal_A; if (Var.Cal_A>Var.Cal_B) { Var.D_max=Var.Cal_B; } CalResult.D = Var.D_A/Var.D_max; CalResult.RR = (Var.D_A/Var.Cal_A)*(Var.D_A/Var.Cal_B); CalResult.LOD=(Var.loglike1-Var.loglike0); Var.XpA1_pA2=Var.pA1*Var.pA2; for (Var.i=0; Var.i<100; Var.i++) { Var.dpr = (double)Var.i*0.01; Var.tmpAA = Var.dpr*Var.D_max + Var.XpA1_pA2 ; Var.tmpAB = Var.pA1-Var.tmpAA; Var.tmpBA = Var.pA2-Var.tmpAA; Var.tmpBB = Var.pB1-Var.tmpBA; Var.lsurface[Var.i] = (Var.known[0]*log(Var.tmpAA) + Var.known[1]*log(Var.tmpAB) + Var.known[2]*log(Var.tmpBA) + Var.known[3]*log(Var.tmpBB))/Var.LN10; } // i=100; Var.dpr = (double)100*0.01; Var.tmpAA = Var.dpr*Var.D_max + Var.XpA1_pA2; Var.tmpAB = Var.pA1-Var.tmpAA; Var.tmpBA = Var.pA2-Var.tmpAA; Var.tmpBB = Var.pB1-Var.tmpBA; /* one value will be 0 */ if (Var.tmpAA < 1e-10) { Var.tmpAA=1e-10;} if (Var.tmpAB < 1e-10) { Var.tmpAB=1e-10;} if (Var.tmpBA < 1e-10) { Var.tmpBA=1e-10;} if (Var.tmpBB < 1e-10) { Var.tmpBB=1e-10;} Var.lsurface[100] = (Var.known[0]*log(Var.tmpAA) + Var.known[1]*log(Var.tmpAB) + Var.known[2]*log(Var.tmpBA) + Var.known[3]*log(Var.tmpBB))/Var.LN10; Var.total_prob=0.0; Var.sum_prob=0.0; for (Var.i=0; Var.i<=100; Var.i++) { Var.lsurface[Var.i] -= Var.loglike1; Var.lsurface[Var.i] = pow(10.0,Var.lsurface[Var.i]); Var.total_prob += Var.lsurface[Var.i]; } Var.cut5off=Var.total_prob*0.05; for (Var.i=0; Var.i<=100; Var.i++) { Var.sum_prob += Var.lsurface[Var.i]; if (Var.sum_prob > Var.cut5off && Var.sum_prob-Var.lsurface[Var.i] < Var.cut5off ) { Var.low_i = Var.i-1; break; } } Var.sum_prob=0.0; for (Var.i=100; Var.i>=0; (Var.i)--) { Var.sum_prob += Var.lsurface[Var.i]; if (Var.sum_prob > Var.cut5off && Var.sum_prob-Var.lsurface[Var.i] < Var.cut5off ) { Var.high_i = Var.i+1; break; } } if (Var.high_i > 100){ Var.high_i = 100; } CalResult.low_i=Var.low_i; CalResult.high_i=Var.high_i; return 1; } ///////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////// ethod1 ///////////////////////////////// int cal_RR_MB(vector<BaseType> & Base1 , vector<BaseType> & Base2 , PairInfoV1 & CalResult, statementVar & Var ) { Var.DDE[0][0]=0; Var.DDE[0][1]=0; Var.DDE[1][0]=0; Var.DDE[1][1]=0; for (Var.i=0 ;Var.i<Var.Asize ; (Var.i)++) { Var.DDE[(Base1[Var.i].Value)][(Base2[Var.i].Value)]++ ; } Var.tmpAA=(Var.DDE[1][1])+(Var.DDE[1][0]); if (Var.tmpAA==0) { CalResult.D=-1; return 0 ; } if ( (Var.DDE[1][1]+Var.DDE[0][1])==0) { CalResult.D=-1; return 0 ; } Var.ALL_count=Var.DDE[0][0]+Var.DDE[0][1]+Var.tmpAA; Var.probHaps[0]=((Var.DDE[0][0])/Var.ALL_count); Var.probHaps[1]=((Var.DDE[0][1])/Var.ALL_count); Var.probHaps[2]=((Var.DDE[1][0])/Var.ALL_count); Var.pA1 = Var.probHaps[0]+Var.probHaps[1]; Var.pA2 = Var.probHaps[0]+Var.probHaps[2]; Var.Cal_B = (Var.pA1)*(Var.pA2); Var.Cal_A = 1- Var.pA1-Var.pA2+Var.Cal_B; if (Var.Cal_A==0 || Var.Cal_B==0 ) { if (Var.probHaps[0] < 1e-10) { Var.probHaps[0]=1e-10;} if (Var.probHaps[1] < 1e-10) { Var.probHaps[1]=1e-10;} if (Var.probHaps[2] < 1e-10) { Var.probHaps[2]=1e-10;} Var.pA1 = Var.probHaps[0]+Var.probHaps[1]; Var.pA2 = Var.probHaps[0]+Var.probHaps[2]; Var.Cal_B = (Var.pA1)*(Var.pA2); Var.Cal_A = 1- Var.pA1-Var.pA2+Var.Cal_B; } CalResult.D=1; Var.D_A = Var.probHaps[0]-Var.Cal_B ; CalResult.RR = (Var.D_A/Var.Cal_A)*(Var.D_A/Var.Cal_B); return 1; } int cal_RR_D_MB(vector<BaseType> & Base1 , vector<BaseType> & Base2 , PairInfoV1 & CalResult, statementVar & Var) { Var.DDE[0][0]=0; Var.DDE[0][1]=0; Var.DDE[1][0]=0; Var.DDE[1][1]=0; for (Var.i=0 ;Var.i<Var.Asize ; (Var.i)++) { Var.DDE[(Base1[Var.i].Value)][(Base2[Var.i].Value)]++; } Var.tmpAA=Var.DDE[1][1]+Var.DDE[1][0]; if (Var.tmpAA==0) { CalResult.D=-1; return 0 ; } else if ( (Var.DDE[1][1]+Var.DDE[0][1])==0) { CalResult.D=-1; return 0 ; } Var.ALL_count=Var.DDE[0][0]+Var.DDE[0][1]+Var.tmpAA; Var.probHaps[0]=((Var.DDE[0][0])/Var.ALL_count); Var.probHaps[1]=((Var.DDE[0][1])/Var.ALL_count); Var.probHaps[2]=((Var.DDE[1][0])/Var.ALL_count); Var.pA1 = Var.probHaps[0]+Var.probHaps[1]; Var.pB1 = 1.0-Var.pA1; Var.pA2 = Var.probHaps[0]+Var.probHaps[2]; Var.pB2 = 1.0-Var.pA2; Var.XpA1_pA2=Var.pA1*Var.pA2; Var.D_A = Var.probHaps[0]-Var.XpA1_pA2 ; if (Var.D_A>0) { Var.Cal_A=Var.pB1*Var.pA2; Var.Cal_B=Var.pA1*Var.pB2; } else { Var.D_A = 0.0-Var.D_A; Var.Cal_A = (Var.pB1)*(Var.pB2); Var.Cal_B = Var.XpA1_pA2 ; } Var.D_max=Var.Cal_A; if (Var.Cal_A>Var.Cal_B) { Var.D_max=Var.Cal_B; } if (Var.D_max==0) { if (Var.probHaps[0] < 1e-10) { Var.probHaps[0]=1e-10;} if (Var.probHaps[1] < 1e-10) { Var.probHaps[1]=1e-10;} if (Var.probHaps[2] < 1e-10) { Var.probHaps[2]=1e-10;} Var.pA1 = Var.probHaps[0]+Var.probHaps[1]; Var.pB1 = 1.0-Var.pA1; Var.pA2 = Var.probHaps[0]+Var.probHaps[2]; Var.pB2 = 1.0-Var.pA2; Var.XpA1_pA2=Var.pA1*Var.pA2; Var.D_A = Var.probHaps[0]-Var.XpA1_pA2 ; if (Var.D_A>0) { Var.Cal_A=Var.pB1*Var.pA2; Var.Cal_B=Var.pA1*Var.pB2; } else { Var.D_A = 0.0-Var.D_A; Var.Cal_A = (Var.pB1)*(Var.pB2); Var.Cal_B = Var.XpA1_pA2 ; } Var.D_max=Var.Cal_A; if (Var.Cal_A>Var.Cal_B) { Var.D_max=Var.Cal_B; } } CalResult.D = Var.D_A/Var.D_max; CalResult.RR = (Var.D_A/Var.Cal_A)*(Var.D_A/Var.Cal_B); return 1; } int cal_RR_D2_MB( vector<BaseType> & Base1 , vector<BaseType> & Base2 , PairInfoV2 & CalResult , statementVar & Var ) { Var.DDE[0][0]=0; Var.DDE[0][1]=0; Var.DDE[1][0]=0; Var.DDE[1][1]=0; for (Var.i=0 ;Var.i<Var.Asize ; (Var.i)++) { Var.DDE[(Base1[Var.i].Value)][(Base2[Var.i].Value)]++; } Var.known[0]=Var.DDE[0][0]; Var.known[1]=Var.DDE[0][1]; Var.known[2]=Var.DDE[1][0]; Var.known[3]=Var.DDE[1][1]; Var.tmpAA=Var.known[3]+Var.known[2]; if ( Var.tmpAA==0 ) { CalResult.D=-1; return 0 ; } else if ( (Var.known[3]+Var.known[1])==0) { CalResult.D=-1; return 0 ; } Var.ALL_count=Var.known[0]+Var.known[1]+Var.tmpAA; Var.probHaps[0]=(Var.known[0])/Var.ALL_count; Var.probHaps[1]=(Var.known[1])/Var.ALL_count; Var.probHaps[2]=(Var.known[2])/Var.ALL_count; Var.probHaps[3]=1-Var.probHaps[0]-Var.probHaps[1]-Var.probHaps[2]; if (Var.probHaps[0] < 1e-10) { Var.probHaps[0]=1e-10;} if (Var.probHaps[1] < 1e-10) { Var.probHaps[1]=1e-10;} if (Var.probHaps[2] < 1e-10) { Var.probHaps[2]=1e-10;} if (Var.probHaps[3] < 1e-10) { Var.probHaps[3]=1e-10;} Var.pA1 = Var.probHaps[0]+Var.probHaps[1]; Var.pB1 = 1.0-Var.pA1; Var.pA2 = Var.probHaps[0]+Var.probHaps[2]; Var.pB2 = 1.0-Var.pA2; Var.XpA1_pA2=Var.pA1*Var.pA2; Var.XpA1_pB2=Var.pA1*Var.pB2; Var.XpB1_pA2=Var.pB1*Var.pA2; Var.XpB1_pB2=Var.pB1*Var.pB2; Var.loglike1 =( Var.known[0]*log(Var.probHaps[0]) + Var.known[1]*log(Var.probHaps[1]) + Var.known[2]*log(Var.probHaps[2]) + Var.known[3]*log(Var.probHaps[3]))/Var.LN10; Var.loglike0 =( Var.known[0]*log(Var.XpA1_pA2) + Var.known[1]*log(Var.XpA1_pB2) + Var.known[2]*log(Var.XpB1_pA2) + Var.known[3]*log(Var.XpB1_pB2))/Var.LN10; Var.D_A = Var.probHaps[0]-Var.XpA1_pA2 ; if (Var.D_A < 0 ) { Var.D_A = 0.0-Var.D_A; Var.Cal_A = Var.XpB1_pB2; Var.Cal_B = Var.XpA1_pA2 ; } else { Var.Cal_A = Var.XpB1_pA2; Var.Cal_B = Var.XpA1_pB2; } //Var.D_max=min(Var.Cal_A,Var.Cal_B); Var.D_max=Var.Cal_A; if (Var.Cal_A>Var.Cal_B) { Var.D_max=Var.Cal_B; } CalResult.D = Var.D_A/Var.D_max; CalResult.RR = (Var.D_A/Var.Cal_A)*(Var.D_A/Var.Cal_B); CalResult.LOD=(Var.loglike1-Var.loglike0); return 1; } int cal_RR_D3_MB( vector<BaseType> & Base1 , vector<BaseType> & Base2 , PairInfoV3 & CalResult , statementVar & Var ) { Var.DDE[0][0]=0; Var.DDE[0][1]=0; Var.DDE[1][0]=0; Var.DDE[1][1]=0; for (Var.i=0 ;Var.i<Var.Asize ; (Var.i)++) { Var.DDE[(Base1[Var.i].Value)][(Base2[Var.i].Value)]++; } Var.known[0]=Var.DDE[0][0]; Var.known[1]=Var.DDE[0][1]; Var.known[2]=Var.DDE[1][0]; Var.known[3]=Var.DDE[1][1]; Var.tmpAA=Var.known[3]+Var.known[2]; if ( Var.tmpAA==0 ) { CalResult.D=-1; return 0 ; } else if ( (Var.known[3]+Var.known[1])==0) { CalResult.D=-1; return 0 ; } Var.ALL_count=Var.known[0]+Var.known[1]+Var.tmpAA; Var.probHaps[0]=(Var.known[0])/Var.ALL_count; Var.probHaps[1]=(Var.known[1])/Var.ALL_count; Var.probHaps[2]=(Var.known[2])/Var.ALL_count; Var.probHaps[3]=1-Var.probHaps[0]-Var.probHaps[1]-Var.probHaps[2]; if (Var.probHaps[0] < 1e-10) { Var.probHaps[0]=1e-10;} if (Var.probHaps[1] < 1e-10) { Var.probHaps[1]=1e-10;} if (Var.probHaps[2] < 1e-10) { Var.probHaps[2]=1e-10;} if (Var.probHaps[3] < 1e-10) { Var.probHaps[3]=1e-10;} Var.pA1 = Var.probHaps[0]+Var.probHaps[1]; Var.pB1 = 1.0-Var.pA1; Var.pA2 = Var.probHaps[0]+Var.probHaps[2]; Var.pB2 = 1.0-Var.pA2; Var.XpA1_pA2=Var.pA1*Var.pA2; Var.XpA1_pB2=Var.pA1*Var.pB2; Var.XpB1_pA2=Var.pB1*Var.pA2; Var.XpB1_pB2=Var.pB1*Var.pB2; // if (XpA1_pA2<1e-10 ){XpA1_pA2=1e-10;} if (XpA1_pB2<1e-10 ){XpA1_pB2=1e-10;} if (XpB1_pA2<1e-10 ){XpB1_pA2=1e-10;} if (XpB1_pB2<1e-10 ){XpB1_pB2=1e-10;} Var.loglike1 =( Var.known[0]*log(Var.probHaps[0]) + Var.known[1]*log(Var.probHaps[1]) + Var.known[2]*log(Var.probHaps[2]) + Var.known[3]*log(Var.probHaps[3]))/Var.LN10; Var.loglike0 =( Var.known[0]*log(Var.XpA1_pA2) + Var.known[1]*log(Var.XpA1_pB2) + Var.known[2]*log(Var.XpB1_pA2) + Var.known[3]*log(Var.XpB1_pB2))/Var.LN10; Var.D_A = Var.probHaps[0]-Var.XpA1_pA2 ; if (Var.D_A< 0 ) { // ALL_count is tmp Var.ALL_count=Var.probHaps[0]; Var.probHaps[0]=Var.probHaps[1]; Var.probHaps[1]=Var.ALL_count; Var.ALL_count=Var.probHaps[3]; Var.probHaps[3]=Var.probHaps[2]; Var.probHaps[2]=Var.ALL_count; Var.pA2 = Var.pA2 + Var.pB2; Var.pB2 = Var.pA2 - Var.pB2; Var.pA2 = Var.pA2 - Var.pB2; Var.D_A = 0.0-Var.D_A; Var.ALL_count=Var.known[0]; Var.known[0]=Var.known[1]; Var.known[1]=Var.ALL_count; Var.ALL_count=Var.known[3]; Var.known[3]=Var.known[2]; Var.known[2]=Var.ALL_count; Var.Cal_A = (Var.pA2)*(Var.pB1); Var.Cal_B = (Var.pA1)*(Var.pB2); } else { Var.Cal_A = Var.XpB1_pA2; Var.Cal_B = Var.XpA1_pB2; } //Var.D_max=min(Var.Cal_A,Var.Cal_B); Var.D_max=Var.Cal_A; if (Var.Cal_A>Var.Cal_B) { Var.D_max=Var.Cal_B; } CalResult.D = Var.D_A/Var.D_max; CalResult.RR = (Var.D_A/Var.Cal_A)*(Var.D_A/Var.Cal_B); CalResult.LOD=(Var.loglike1-Var.loglike0); Var.XpA1_pA2=Var.pA1*Var.pA2; for (Var.i=0; Var.i<100; Var.i++) { Var.dpr = (double)Var.i*0.01; Var.tmpAA = Var.dpr*Var.D_max + Var.XpA1_pA2 ; Var.tmpAB = Var.pA1-Var.tmpAA; Var.tmpBA = Var.pA2-Var.tmpAA; Var.tmpBB = Var.pB1-Var.tmpBA; Var.lsurface[Var.i] = (Var.known[0]*log(Var.tmpAA) + Var.known[1]*log(Var.tmpAB) + Var.known[2]*log(Var.tmpBA) + Var.known[3]*log(Var.tmpBB))/Var.LN10; } // i=100; Var.dpr = (double)100*0.01; Var.tmpAA = Var.dpr*Var.D_max + Var.XpA1_pA2; Var.tmpAB = Var.pA1-Var.tmpAA; Var.tmpBA = Var.pA2-Var.tmpAA; Var.tmpBB = Var.pB1-Var.tmpBA; /* one value will be 0 */ if (Var.tmpAA < 1e-10) { Var.tmpAA=1e-10;} if (Var.tmpAB < 1e-10) { Var.tmpAB=1e-10;} if (Var.tmpBA < 1e-10) { Var.tmpBA=1e-10;} if (Var.tmpBB < 1e-10) { Var.tmpBB=1e-10;} Var.lsurface[100] = (Var.known[0]*log(Var.tmpAA) + Var.known[1]*log(Var.tmpAB) + Var.known[2]*log(Var.tmpBA) + Var.known[3]*log(Var.tmpBB))/Var.LN10; Var.total_prob=0.0; Var.sum_prob=0.0; for (Var.i=0; Var.i<=100; Var.i++) { Var.lsurface[Var.i] -= Var.loglike1; Var.lsurface[Var.i] = pow(10.0,Var.lsurface[Var.i]); Var.total_prob += Var.lsurface[Var.i]; } Var.cut5off=Var.total_prob*0.05; for (Var.i=0; Var.i<=100; Var.i++) { Var.sum_prob += Var.lsurface[Var.i]; if (Var.sum_prob > Var.cut5off && Var.sum_prob-Var.lsurface[Var.i] < Var.cut5off ) { Var.low_i = Var.i-1; break; } } Var.sum_prob=0.0; for (Var.i=100; Var.i>=0; (Var.i)--) { Var.sum_prob += Var.lsurface[Var.i]; if (Var.sum_prob > Var.cut5off && Var.sum_prob-Var.lsurface[Var.i] < Var.cut5off ) { Var.high_i = Var.i+1; break; } } if (Var.high_i > 100){ Var.high_i = 100; } CalResult.low_i=Var.low_i; CalResult.high_i=Var.high_i; return 1; } ///////////////////////////////////////////////////////////////////////////////////////////////// #endif // calculate_H_ ;
25.994911
169
0.616484
[ "vector" ]
c1960fcb7e6ec06ab565099751d5cc01ccee5247
22,135
h
C
kiwi/solverimpl.h
qunaibit/kiwi
9c46f893ae3ac6f239d1a7bfccb8bf316ff02293
[ "BSD-3-Clause-Clear" ]
561
2015-01-27T01:20:32.000Z
2022-03-23T03:18:10.000Z
kiwi/solverimpl.h
qunaibit/kiwi
9c46f893ae3ac6f239d1a7bfccb8bf316ff02293
[ "BSD-3-Clause-Clear" ]
120
2015-03-18T16:06:39.000Z
2022-03-28T20:10:10.000Z
kiwi/solverimpl.h
qunaibit/kiwi
9c46f893ae3ac6f239d1a7bfccb8bf316ff02293
[ "BSD-3-Clause-Clear" ]
76
2015-01-14T02:08:15.000Z
2022-03-28T14:27:08.000Z
/*----------------------------------------------------------------------------- | Copyright (c) 2013-2017, Nucleic Development Team. | | Distributed under the terms of the Modified BSD License. | | The full license is in the file LICENSE, distributed with this software. |----------------------------------------------------------------------------*/ #pragma once #include <algorithm> #include <limits> #include <memory> #include <vector> #include "constraint.h" #include "errors.h" #include "expression.h" #include "maptype.h" #include "row.h" #include "symbol.h" #include "term.h" #include "util.h" #include "variable.h" namespace kiwi { namespace impl { class SolverImpl { friend class DebugHelper; struct Tag { Symbol marker; Symbol other; }; struct EditInfo { Tag tag; Constraint constraint; double constant; }; using VarMap = MapType<Variable, Symbol>; using RowMap = MapType<Symbol, Row*>; using CnMap = MapType<Constraint, Tag>; using EditMap = MapType<Variable, EditInfo>; struct DualOptimizeGuard { DualOptimizeGuard( SolverImpl& impl ) : m_impl( impl ) {} ~DualOptimizeGuard() { m_impl.dualOptimize(); } SolverImpl& m_impl; }; public: SolverImpl() : m_objective( new Row() ), m_id_tick( 1 ) {} SolverImpl( const SolverImpl& ) = delete; SolverImpl( SolverImpl&& ) = delete; ~SolverImpl() { clearRows(); } /* Add a constraint to the solver. Throws ------ DuplicateConstraint The given constraint has already been added to the solver. UnsatisfiableConstraint The given constraint is required and cannot be satisfied. */ void addConstraint( const Constraint& constraint ) { if( m_cns.find( constraint ) != m_cns.end() ) throw DuplicateConstraint( constraint ); // Creating a row causes symbols to be reserved for the variables // in the constraint. If this method exits with an exception, // then its possible those variables will linger in the var map. // Since its likely that those variables will be used in other // constraints and since exceptional conditions are uncommon, // i'm not too worried about aggressive cleanup of the var map. Tag tag; std::unique_ptr<Row> rowptr( createRow( constraint, tag ) ); Symbol subject( chooseSubject( *rowptr, tag ) ); // If chooseSubject could not find a valid entering symbol, one // last option is available if the entire row is composed of // dummy variables. If the constant of the row is zero, then // this represents redundant constraints and the new dummy // marker can enter the basis. If the constant is non-zero, // then it represents an unsatisfiable constraint. if( subject.type() == Symbol::Invalid && allDummies( *rowptr ) ) { if( !nearZero( rowptr->constant() ) ) throw UnsatisfiableConstraint( constraint ); else subject = tag.marker; } // If an entering symbol still isn't found, then the row must // be added using an artificial variable. If that fails, then // the row represents an unsatisfiable constraint. if( subject.type() == Symbol::Invalid ) { if( !addWithArtificialVariable( *rowptr ) ) throw UnsatisfiableConstraint( constraint ); } else { rowptr->solveFor( subject ); substitute( subject, *rowptr ); m_rows[ subject ] = rowptr.release(); } m_cns[ constraint ] = tag; // Optimizing after each constraint is added performs less // aggregate work due to a smaller average system size. It // also ensures the solver remains in a consistent state. optimize( *m_objective ); } /* Remove a constraint from the solver. Throws ------ UnknownConstraint The given constraint has not been added to the solver. */ void removeConstraint( const Constraint& constraint ) { auto cn_it = m_cns.find( constraint ); if( cn_it == m_cns.end() ) throw UnknownConstraint( constraint ); Tag tag( cn_it->second ); m_cns.erase( cn_it ); // Remove the error effects from the objective function // *before* pivoting, or substitutions into the objective // will lead to incorrect solver results. removeConstraintEffects( constraint, tag ); // If the marker is basic, simply drop the row. Otherwise, // pivot the marker into the basis and then drop the row. auto row_it = m_rows.find( tag.marker ); if( row_it != m_rows.end() ) { std::unique_ptr<Row> rowptr( row_it->second ); m_rows.erase( row_it ); } else { row_it = getMarkerLeavingRow( tag.marker ); if( row_it == m_rows.end() ) throw InternalSolverError( "failed to find leaving row" ); Symbol leaving( row_it->first ); std::unique_ptr<Row> rowptr( row_it->second ); m_rows.erase( row_it ); rowptr->solveFor( leaving, tag.marker ); substitute( tag.marker, *rowptr ); } // Optimizing after each constraint is removed ensures that the // solver remains consistent. It makes the solver api easier to // use at a small tradeoff for speed. optimize( *m_objective ); } /* Test whether a constraint has been added to the solver. */ bool hasConstraint( const Constraint& constraint ) const { return m_cns.find( constraint ) != m_cns.end(); } /* Add an edit variable to the solver. This method should be called before the `suggestValue` method is used to supply a suggested value for the given edit variable. Throws ------ DuplicateEditVariable The given edit variable has already been added to the solver. BadRequiredStrength The given strength is >= required. */ void addEditVariable( const Variable& variable, double strength ) { if( m_edits.find( variable ) != m_edits.end() ) throw DuplicateEditVariable( variable ); strength = strength::clip( strength ); if( strength == strength::required ) throw BadRequiredStrength(); Constraint cn( Expression( variable ), OP_EQ, strength ); addConstraint( cn ); EditInfo info; info.tag = m_cns[ cn ]; info.constraint = cn; info.constant = 0.0; m_edits[ variable ] = info; } /* Remove an edit variable from the solver. Throws ------ UnknownEditVariable The given edit variable has not been added to the solver. */ void removeEditVariable( const Variable& variable ) { auto it = m_edits.find( variable ); if( it == m_edits.end() ) throw UnknownEditVariable( variable ); removeConstraint( it->second.constraint ); m_edits.erase( it ); } /* Test whether an edit variable has been added to the solver. */ bool hasEditVariable( const Variable& variable ) const { return m_edits.find( variable ) != m_edits.end(); } /* Suggest a value for the given edit variable. This method should be used after an edit variable as been added to the solver in order to suggest the value for that variable. Throws ------ UnknownEditVariable The given edit variable has not been added to the solver. */ void suggestValue( const Variable& variable, double value ) { auto it = m_edits.find( variable ); if( it == m_edits.end() ) throw UnknownEditVariable( variable ); DualOptimizeGuard guard( *this ); EditInfo& info = it->second; double delta = value - info.constant; info.constant = value; // Check first if the positive error variable is basic. auto row_it = m_rows.find( info.tag.marker ); if( row_it != m_rows.end() ) { if( row_it->second->add( -delta ) < 0.0 ) m_infeasible_rows.push_back( row_it->first ); return; } // Check next if the negative error variable is basic. row_it = m_rows.find( info.tag.other ); if( row_it != m_rows.end() ) { if( row_it->second->add( delta ) < 0.0 ) m_infeasible_rows.push_back( row_it->first ); return; } // Otherwise update each row where the error variables exist. for (const auto & rowPair : m_rows) { double coeff = rowPair.second->coefficientFor( info.tag.marker ); if( coeff != 0.0 && rowPair.second->add( delta * coeff ) < 0.0 && rowPair.first.type() != Symbol::External ) m_infeasible_rows.push_back( rowPair.first ); } } /* Update the values of the external solver variables. */ void updateVariables() { auto row_end = m_rows.end(); for (auto &varPair : m_vars) { Variable& var = varPair.first; auto row_it = m_rows.find( varPair.second ); if( row_it == row_end ) var.setValue( 0.0 ); else var.setValue( row_it->second->constant() ); } } /* Reset the solver to the empty starting condition. This method resets the internal solver state to the empty starting condition, as if no constraints or edit variables have been added. This can be faster than deleting the solver and creating a new one when the entire system must change, since it can avoid unecessary heap (de)allocations. */ void reset() { clearRows(); m_cns.clear(); m_vars.clear(); m_edits.clear(); m_infeasible_rows.clear(); m_objective.reset( new Row() ); m_artificial.reset(); m_id_tick = 1; } SolverImpl& operator=( const SolverImpl& ) = delete; SolverImpl& operator=( SolverImpl&& ) = delete; private: struct RowDeleter { template<typename T> void operator()( T& pair ) { delete pair.second; } }; void clearRows() { std::for_each( m_rows.begin(), m_rows.end(), RowDeleter() ); m_rows.clear(); } /* Get the symbol for the given variable. If a symbol does not exist for the variable, one will be created. */ Symbol getVarSymbol( const Variable& variable ) { auto it = m_vars.find( variable ); if( it != m_vars.end() ) return it->second; Symbol symbol( Symbol::External, m_id_tick++ ); m_vars[ variable ] = symbol; return symbol; } /* Create a new Row object for the given constraint. The terms in the constraint will be converted to cells in the row. Any term in the constraint with a coefficient of zero is ignored. This method uses the `getVarSymbol` method to get the symbol for the variables added to the row. If the symbol for a given cell variable is basic, the cell variable will be substituted with the basic row. The necessary slack and error variables will be added to the row. If the constant for the row is negative, the sign for the row will be inverted so the constant becomes positive. The tag will be updated with the marker and error symbols to use for tracking the movement of the constraint in the tableau. */ std::unique_ptr<Row> createRow( const Constraint& constraint, Tag& tag ) { const Expression& expr( constraint.expression() ); std::unique_ptr<Row> row( new Row( expr.constant() ) ); // Substitute the current basic variables into the row. for (const auto &term : expr.terms()) { if( !nearZero( term.coefficient() ) ) { Symbol symbol( getVarSymbol( term.variable() ) ); auto row_it = m_rows.find( symbol ); if( row_it != m_rows.end() ) row->insert( *row_it->second, term.coefficient() ); else row->insert( symbol, term.coefficient() ); } } // Add the necessary slack, error, and dummy variables. switch( constraint.op() ) { case OP_LE: case OP_GE: { double coeff = constraint.op() == OP_LE ? 1.0 : -1.0; Symbol slack( Symbol::Slack, m_id_tick++ ); tag.marker = slack; row->insert( slack, coeff ); if( constraint.strength() < strength::required ) { Symbol error( Symbol::Error, m_id_tick++ ); tag.other = error; row->insert( error, -coeff ); m_objective->insert( error, constraint.strength() ); } break; } case OP_EQ: { if( constraint.strength() < strength::required ) { Symbol errplus( Symbol::Error, m_id_tick++ ); Symbol errminus( Symbol::Error, m_id_tick++ ); tag.marker = errplus; tag.other = errminus; row->insert( errplus, -1.0 ); // v = eplus - eminus row->insert( errminus, 1.0 ); // v - eplus + eminus = 0 m_objective->insert( errplus, constraint.strength() ); m_objective->insert( errminus, constraint.strength() ); } else { Symbol dummy( Symbol::Dummy, m_id_tick++ ); tag.marker = dummy; row->insert( dummy ); } break; } } // Ensure the row as a positive constant. if( row->constant() < 0.0 ) row->reverseSign(); return row; } /* Choose the subject for solving for the row. This method will choose the best subject for using as the solve target for the row. An invalid symbol will be returned if there is no valid target. The symbols are chosen according to the following precedence: 1) The first symbol representing an external variable. 2) A negative slack or error tag variable. If a subject cannot be found, an invalid symbol will be returned. */ Symbol chooseSubject( const Row& row, const Tag& tag ) const { for (const auto &cellPair : row.cells()) { if( cellPair.first.type() == Symbol::External ) return cellPair.first; } if( tag.marker.type() == Symbol::Slack || tag.marker.type() == Symbol::Error ) { if( row.coefficientFor( tag.marker ) < 0.0 ) return tag.marker; } if( tag.other.type() == Symbol::Slack || tag.other.type() == Symbol::Error ) { if( row.coefficientFor( tag.other ) < 0.0 ) return tag.other; } return Symbol(); } /* Add the row to the tableau using an artificial variable. This will return false if the constraint cannot be satisfied. */ bool addWithArtificialVariable( const Row& row ) { // Create and add the artificial variable to the tableau Symbol art( Symbol::Slack, m_id_tick++ ); m_rows[ art ] = new Row( row ); m_artificial.reset( new Row( row ) ); // Optimize the artificial objective. This is successful // only if the artificial objective is optimized to zero. optimize( *m_artificial ); bool success = nearZero( m_artificial->constant() ); m_artificial.reset(); // If the artificial variable is not basic, pivot the row so that // it becomes basic. If the row is constant, exit early. auto it = m_rows.find( art ); if( it != m_rows.end() ) { std::unique_ptr<Row> rowptr( it->second ); m_rows.erase( it ); if( rowptr->cells().empty() ) return success; Symbol entering( anyPivotableSymbol( *rowptr ) ); if( entering.type() == Symbol::Invalid ) return false; // unsatisfiable (will this ever happen?) rowptr->solveFor( art, entering ); substitute( entering, *rowptr ); m_rows[ entering ] = rowptr.release(); } // Remove the artificial variable from the tableau. for (auto &rowPair : m_rows) rowPair.second->remove(art); m_objective->remove( art ); return success; } /* Substitute the parametric symbol with the given row. This method will substitute all instances of the parametric symbol in the tableau and the objective function with the given row. */ void substitute( const Symbol& symbol, const Row& row ) { for( auto& rowPair : m_rows ) { rowPair.second->substitute( symbol, row ); if( rowPair.first.type() != Symbol::External && rowPair.second->constant() < 0.0 ) m_infeasible_rows.push_back( rowPair.first ); } m_objective->substitute( symbol, row ); if( m_artificial.get() ) m_artificial->substitute( symbol, row ); } /* Optimize the system for the given objective function. This method performs iterations of Phase 2 of the simplex method until the objective function reaches a minimum. Throws ------ InternalSolverError The value of the objective function is unbounded. */ void optimize( const Row& objective ) { while( true ) { Symbol entering( getEnteringSymbol( objective ) ); if( entering.type() == Symbol::Invalid ) return; auto it = getLeavingRow( entering ); if( it == m_rows.end() ) throw InternalSolverError( "The objective is unbounded." ); // pivot the entering symbol into the basis Symbol leaving( it->first ); Row* row = it->second; m_rows.erase( it ); row->solveFor( leaving, entering ); substitute( entering, *row ); m_rows[ entering ] = row; } } /* Optimize the system using the dual of the simplex method. The current state of the system should be such that the objective function is optimal, but not feasible. This method will perform an iteration of the dual simplex method to make the solution both optimal and feasible. Throws ------ InternalSolverError The system cannot be dual optimized. */ void dualOptimize() { while( !m_infeasible_rows.empty() ) { Symbol leaving( m_infeasible_rows.back() ); m_infeasible_rows.pop_back(); auto it = m_rows.find( leaving ); if( it != m_rows.end() && !nearZero( it->second->constant() ) && it->second->constant() < 0.0 ) { Symbol entering( getDualEnteringSymbol( *it->second ) ); if( entering.type() == Symbol::Invalid ) throw InternalSolverError( "Dual optimize failed." ); // pivot the entering symbol into the basis Row* row = it->second; m_rows.erase( it ); row->solveFor( leaving, entering ); substitute( entering, *row ); m_rows[ entering ] = row; } } } /* Compute the entering variable for a pivot operation. This method will return first symbol in the objective function which is non-dummy and has a coefficient less than zero. If no symbol meets the criteria, it means the objective function is at a minimum, and an invalid symbol is returned. */ Symbol getEnteringSymbol( const Row& objective ) const { for (const auto &cellPair : objective.cells()) { if( cellPair.first.type() != Symbol::Dummy && cellPair.second < 0.0 ) return cellPair.first; } return Symbol(); } /* Compute the entering symbol for the dual optimize operation. This method will return the symbol in the row which has a positive coefficient and yields the minimum ratio for its respective symbol in the objective function. The provided row *must* be infeasible. If no symbol is found which meats the criteria, an invalid symbol is returned. */ Symbol getDualEnteringSymbol( const Row& row ) const { Symbol entering; double ratio = std::numeric_limits<double>::max(); for (const auto &cellPair : row.cells()) { if( cellPair.second > 0.0 && cellPair.first.type() != Symbol::Dummy ) { double coeff = m_objective->coefficientFor( cellPair.first ); double r = coeff / cellPair.second; if( r < ratio ) { ratio = r; entering = cellPair.first; } } } return entering; } /* Get the first Slack or Error symbol in the row. If no such symbol is present, and Invalid symbol will be returned. */ Symbol anyPivotableSymbol( const Row& row ) const { for (const auto &cellPair : row.cells()) { const Symbol& sym( cellPair.first ); if( sym.type() == Symbol::Slack || sym.type() == Symbol::Error ) return sym; } return Symbol(); } /* Compute the row which holds the exit symbol for a pivot. This method will return an iterator to the row in the row map which holds the exit symbol. If no appropriate exit symbol is found, the end() iterator will be returned. This indicates that the objective function is unbounded. */ RowMap::iterator getLeavingRow( const Symbol& entering ) { double ratio = std::numeric_limits<double>::max(); auto end = m_rows.end(); auto found = m_rows.end(); for( auto it = m_rows.begin(); it != end; ++it ) { if( it->first.type() != Symbol::External ) { double temp = it->second->coefficientFor( entering ); if( temp < 0.0 ) { double temp_ratio = -it->second->constant() / temp; if( temp_ratio < ratio ) { ratio = temp_ratio; found = it; } } } } return found; } /* Compute the leaving row for a marker variable. This method will return an iterator to the row in the row map which holds the given marker variable. The row will be chosen according to the following precedence: 1) The row with a restricted basic varible and a negative coefficient for the marker with the smallest ratio of -constant / coefficient. 2) The row with a restricted basic variable and the smallest ratio of constant / coefficient. 3) The last unrestricted row which contains the marker. If the marker does not exist in any row, the row map end() iterator will be returned. This indicates an internal solver error since the marker *should* exist somewhere in the tableau. */ RowMap::iterator getMarkerLeavingRow( const Symbol& marker ) { const double dmax = std::numeric_limits<double>::max(); double r1 = dmax; double r2 = dmax; auto end = m_rows.end(); auto first = end; auto second = end; auto third = end; for( auto it = m_rows.begin(); it != end; ++it ) { double c = it->second->coefficientFor( marker ); if( c == 0.0 ) continue; if( it->first.type() == Symbol::External ) { third = it; } else if( c < 0.0 ) { double r = -it->second->constant() / c; if( r < r1 ) { r1 = r; first = it; } } else { double r = it->second->constant() / c; if( r < r2 ) { r2 = r; second = it; } } } if( first != end ) return first; if( second != end ) return second; return third; } /* Remove the effects of a constraint on the objective function. */ void removeConstraintEffects( const Constraint& cn, const Tag& tag ) { if( tag.marker.type() == Symbol::Error ) removeMarkerEffects( tag.marker, cn.strength() ); if( tag.other.type() == Symbol::Error ) removeMarkerEffects( tag.other, cn.strength() ); } /* Remove the effects of an error marker on the objective function. */ void removeMarkerEffects( const Symbol& marker, double strength ) { auto row_it = m_rows.find( marker ); if( row_it != m_rows.end() ) m_objective->insert( *row_it->second, -strength ); else m_objective->insert( marker, -strength ); } /* Test whether a row is composed of all dummy variables. */ bool allDummies( const Row& row ) const { for (const auto &rowPair : row.cells()) { if( rowPair.first.type() != Symbol::Dummy ) return false; } return true; } CnMap m_cns; RowMap m_rows; VarMap m_vars; EditMap m_edits; std::vector<Symbol> m_infeasible_rows; std::unique_ptr<Row> m_objective; std::unique_ptr<Row> m_artificial; Symbol::Id m_id_tick; }; } // namespace impl } // namespace kiwi
26.797821
80
0.672419
[ "object", "vector" ]
c19c7d22869f07c15d2c56801d58242f667a0561
1,824
h
C
modules/basic/stream/byte_stream.h
pwrliang/libvineyard
4d108b2c448d0093353a76e3de549e2db47b2979
[ "Apache-2.0" ]
null
null
null
modules/basic/stream/byte_stream.h
pwrliang/libvineyard
4d108b2c448d0093353a76e3de549e2db47b2979
[ "Apache-2.0" ]
null
null
null
modules/basic/stream/byte_stream.h
pwrliang/libvineyard
4d108b2c448d0093353a76e3de549e2db47b2979
[ "Apache-2.0" ]
null
null
null
/** Copyright 2020 Alibaba Group Holding Limited. 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 MODULES_BASIC_STREAM_BYTE_STREAM_H_ #define MODULES_BASIC_STREAM_BYTE_STREAM_H_ #include <memory> #include <string> #include <unordered_map> #include "basic/stream/byte_stream.vineyard.h" #include "client/client.h" namespace vineyard { /** * @brief ByteStreamBuilder is used for initiating byte streams * */ class ByteStreamBuilder : public ByteStreamBaseBuilder { public: explicit ByteStreamBuilder(Client& client) : ByteStreamBaseBuilder(client) {} void SetParam(std::string const& key, std::string const& value) { this->params_.emplace(key, value); } void SetParams( const std::unordered_multimap<std::string, std::string>& params) { for (auto const& kv : params) { this->params_.emplace(kv.first, kv.second); } } void SetParams(const std::unordered_map<std::string, std::string>& params) { for (auto const& kv : params) { this->params_.emplace(kv.first, kv.second); } } std::shared_ptr<Object> Seal(Client& client) { auto bstream = ByteStreamBaseBuilder::Seal(client); VINEYARD_CHECK_OK(client.CreateStream(bstream->id())); return std::static_pointer_cast<Object>(bstream); } }; } // namespace vineyard #endif // MODULES_BASIC_STREAM_BYTE_STREAM_H_
28.952381
79
0.739583
[ "object" ]
c19db77afe3ae122fa31826509553307b4995007
10,459
h
C
RecoVertex/KinematicFit/interface/KinematicConstrainedVertexFitterT.h
pasmuss/cmssw
566f40c323beef46134485a45ea53349f59ae534
[ "Apache-2.0" ]
null
null
null
RecoVertex/KinematicFit/interface/KinematicConstrainedVertexFitterT.h
pasmuss/cmssw
566f40c323beef46134485a45ea53349f59ae534
[ "Apache-2.0" ]
null
null
null
RecoVertex/KinematicFit/interface/KinematicConstrainedVertexFitterT.h
pasmuss/cmssw
566f40c323beef46134485a45ea53349f59ae534
[ "Apache-2.0" ]
null
null
null
#ifndef KinematicConstrainedVertexFitterT_H #define KinematicConstrainedVertexFitterT_H #include "RecoVertex/KinematicFitPrimitives/interface/RefCountedKinematicTree.h" #include "RecoVertex/KinematicFitPrimitives/interface/MultiTrackKinematicConstraintT.h" #include "RecoVertex/VertexTools/interface/LinearizationPointFinder.h" #include "RecoVertex/KinematicFit/interface/KinematicConstrainedVertexUpdatorT.h" #include "RecoVertex/KinematicFit/interface/VertexKinematicConstraintT.h" #include "RecoVertex/KinematicFit/interface/ConstrainedTreeBuilderT.h" #include "MagneticField/Engine/interface/MagneticField.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" /** * Class fitting the veretx out of set of tracks via usual LMS * with Lagrange multipliers. * Additional constraints can be applyed to the tracks during the vertex fit * (solves non-factorizabele cases). Since the vertex constraint is included by default, do not add a separate * VertexKinematicConstraint! * Example: Vertex fit with collinear tracks.. */ template < int nTrk, int nConstraint> class KinematicConstrainedVertexFitterT{ public: /** * Default constructor using LMSLinearizationPointFinder */ explicit KinematicConstrainedVertexFitterT(const MagneticField* ifield); /** * Constructor with user-provided LinearizationPointFinder */ KinematicConstrainedVertexFitterT(const MagneticField* ifield, const LinearizationPointFinder& fnd); ~KinematicConstrainedVertexFitterT(); /** * Configuration through PSet: number of iterations(maxDistance) and * stopping condition (maxNbrOfIterations) */ void setParameters(const edm::ParameterSet& pSet); /** * Without additional constraint, this will perform a simple * vertex fit using LMS with Lagrange multipliers method (by definition valid only if nConstraint=0) */ RefCountedKinematicTree fit(const std::vector<RefCountedKinematicParticle> &part) { return fit(part, 0, 0); } /** * LMS with Lagrange multipliers fit of vertex constraint and user-specified constraint. */ RefCountedKinematicTree fit(const std::vector<RefCountedKinematicParticle> &part, MultiTrackKinematicConstraintT< nTrk, nConstraint> * cs) { return fit(part, cs, 0); }; /** * LMS with Lagrange multipliers fit of vertex constraint, user-specified constraint and user-specified starting point. */ RefCountedKinematicTree fit(const std::vector<RefCountedKinematicParticle> &part, MultiTrackKinematicConstraintT< nTrk, nConstraint> * cs, GlobalPoint * pt); //return the number of iterations int getNit() const; //return the value of the constraint equation float getCSum() const; private: void defaultParameters(); const MagneticField* field; LinearizationPointFinder * finder; KinematicConstrainedVertexUpdatorT<nTrk,nConstraint> * updator; VertexKinematicConstraintT * vCons; ConstrainedTreeBuilderT * tBuilder; float theMaxDelta; //maximum (delta parameter)^2/(sigma parameter)^2 per iteration for convergence int theMaxStep; float theMaxReducedChiSq; //max of initial (after 2 iterations) chisq/dof value float theMinChiSqImprovement; //minimum required improvement in chisq to avoid fit termination for cases exceeding theMaxReducedChiSq int iterations; float csum; }; #include "RecoVertex/KinematicFit/interface/InputSort.h" #include "RecoVertex/LinearizationPointFinders/interface/DefaultLinearizationPointFinder.h" #include "RecoVertex/KinematicFitPrimitives/interface/KinematicVertexFactory.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" template < int nTrk, int nConstraint> KinematicConstrainedVertexFitterT< nTrk, nConstraint>::KinematicConstrainedVertexFitterT(const MagneticField* ifield) : field(ifield) { finder = new DefaultLinearizationPointFinder(); vCons = new VertexKinematicConstraintT(); updator = new KinematicConstrainedVertexUpdatorT<nTrk,nConstraint>(); tBuilder = new ConstrainedTreeBuilderT; defaultParameters(); iterations = -1; csum = -1000.0; } template < int nTrk, int nConstraint> KinematicConstrainedVertexFitterT< nTrk, nConstraint>::KinematicConstrainedVertexFitterT(const MagneticField* ifield, const LinearizationPointFinder& fnd) : field(ifield) { finder = fnd.clone(); vCons = new VertexKinematicConstraintT(); updator = new KinematicConstrainedVertexUpdatorT<nTrk,nConstraint>(); tBuilder = new ConstrainedTreeBuilderT; defaultParameters(); iterations = -1; csum = -1000.0; } template < int nTrk, int nConstraint> KinematicConstrainedVertexFitterT< nTrk, nConstraint>::~KinematicConstrainedVertexFitterT() { delete finder; delete vCons; delete updator; delete tBuilder; } template < int nTrk, int nConstraint> void KinematicConstrainedVertexFitterT< nTrk, nConstraint>::setParameters(const edm::ParameterSet& pSet) { theMaxDelta = pSet.getParameter<double>("maxDelta"); theMaxStep = pSet.getParameter<int>("maxNbrOfIterations"); theMaxReducedChiSq = pSet.getParameter<double>("maxReducedChiSq"); theMinChiSqImprovement = pSet.getParameter<double>("minChiSqImprovement"); } template < int nTrk, int nConstraint> void KinematicConstrainedVertexFitterT< nTrk, nConstraint>::defaultParameters() { theMaxDelta = 0.01; theMaxStep = 1000; theMaxReducedChiSq = 225.; theMinChiSqImprovement = 50.; } template < int nTrk, int nConstraint> RefCountedKinematicTree KinematicConstrainedVertexFitterT< nTrk, nConstraint>::fit(const std::vector<RefCountedKinematicParticle> &part, MultiTrackKinematicConstraintT< nTrk, nConstraint> * cs, GlobalPoint * pt) { assert( nConstraint==0 || cs!=0); if(part.size()!=nTrk) throw VertexException("KinematicConstrainedVertexFitterT::input states are not nTrk"); //sorting out the input particles InputSort iSort; std::pair<std::vector<RefCountedKinematicParticle>, std::vector<FreeTrajectoryState> > input = iSort.sort(part); const std::vector<RefCountedKinematicParticle> & particles = input.first; const std::vector<FreeTrajectoryState> & fStates = input.second; // linearization point: GlobalPoint linPoint = (pt!=0) ? *pt : finder->getLinearizationPoint(fStates); //initial parameters: ROOT::Math::SVector<double,3+7*nTrk> inPar; //3+ 7*ntracks ROOT::Math::SVector<double,3+7*nTrk> finPar; //3+ 7*ntracks ROOT::Math::SMatrix<double, 3+7*nTrk,3+7*nTrk ,ROOT::Math::MatRepSym<double,3+7*nTrk> > inCov; //making initial vector of parameters and initial particle-related covariance int nSt = 0; std::vector<KinematicState> lStates(nTrk); for(std::vector<RefCountedKinematicParticle>::const_iterator i = particles.begin(); i!=particles.end(); i++) { lStates[nSt] = (*i)->stateAtPoint(linPoint); KinematicState const & state = lStates[nSt]; if (!state.isValid()) { LogDebug("KinematicConstrainedVertexFitter") << "State is invalid at point: "<<linPoint<<std::endl; return ReferenceCountingPointer<KinematicTree>(new KinematicTree()); } inPar.Place_at(state.kinematicParameters().vector(),3+7*nSt); inCov.Place_at(state.kinematicParametersError().matrix(),3 + 7*nSt,3 + 7*nSt); ++nSt; } //initial vertex error matrix components (huge error method) //and vertex related initial vector components double in_er = 100.; inCov(0,0) = in_er; inCov(1,1) = in_er; inCov(2,2) = in_er; inPar(0) = linPoint.x(); inPar(1) = linPoint.y(); inPar(2) = linPoint.z(); //constraint equations value and number of iterations double eq; int nit = 0; iterations = 0; csum = 0.0; GlobalPoint lPoint = linPoint; RefCountedKinematicVertex rVtx; ROOT::Math::SMatrix<double, 3+7*nTrk,3+7*nTrk ,ROOT::Math::MatRepSym<double,3+7*nTrk> > refCCov = ROOT::Math::SMatrixNoInit(); double chisq = 1e6; bool convergence = false; //iterarions over the updator: each time updated parameters //are taken as new linearization point do{ eq = 0.; refCCov = inCov; std::vector<KinematicState> oldStates = lStates; GlobalVector mf = field->inInverseGeV(lPoint); rVtx = updator->update(inPar,refCCov,lStates,lPoint,mf,cs); if (particles.size() != lStates.size() || rVtx == 0) { LogDebug("KinematicConstrainedVertexFitter") << "updator failure\n"; return ReferenceCountingPointer<KinematicTree>(new KinematicTree()); } double newchisq = rVtx->chiSquared(); if ( nit>2 && newchisq > theMaxReducedChiSq*rVtx->degreesOfFreedom() && (newchisq-chisq) > (-theMinChiSqImprovement) ) { LogDebug("KinematicConstrainedVertexFitter") << "bad chisq and insufficient improvement, bailing\n"; return ReferenceCountingPointer<KinematicTree>(new KinematicTree()); } chisq = newchisq; const GlobalPoint &newPoint = rVtx->position(); double maxDelta = 0.0; double deltapos[3]; deltapos[0] = newPoint.x() - lPoint.x(); deltapos[1] = newPoint.y() - lPoint.y(); deltapos[2] = newPoint.z() - lPoint.z(); for (int i=0; i<3; ++i) { double delta = deltapos[i]*deltapos[i]/rVtx->error().matrix()(i,i); if (delta>maxDelta) maxDelta = delta; } for (std::vector<KinematicState>::const_iterator itold = oldStates.begin(), itnew = lStates.begin(); itnew!=lStates.end(); ++itold,++itnew) { for (int i=0; i<7; ++i) { double deltapar = itnew->kinematicParameters()(i) - itold->kinematicParameters()(i); double delta = deltapar*deltapar/itnew->kinematicParametersError().matrix()(i,i); if (delta>maxDelta) maxDelta = delta; } } lPoint = newPoint; nit++; convergence = maxDelta<theMaxDelta || (nit==theMaxStep && maxDelta<4.0*theMaxDelta); }while(nit<theMaxStep && !convergence); if (!convergence) { return ReferenceCountingPointer<KinematicTree>(new KinematicTree()); } // std::cout << "new full cov matrix" << std::endl; // std::cout << refCCov << std::endl; iterations = nit; csum = eq; return tBuilder->buildTree<nTrk>(particles, lStates, rVtx, refCCov); } template < int nTrk, int nConstraint> int KinematicConstrainedVertexFitterT< nTrk, nConstraint>::getNit() const { return iterations; } template < int nTrk, int nConstraint> float KinematicConstrainedVertexFitterT< nTrk, nConstraint>::getCSum() const { return csum; } #endif
34.863333
157
0.728177
[ "vector" ]
c1a20299bdda9140de2fb9eabfcde70a23844ce6
708
h
C
StiGame/sprites/IDirectionSprite.h
jordsti/stigame
6ac0ae737667b1c77da3ef5007f5c4a3a080045a
[ "MIT" ]
8
2015-02-03T20:23:49.000Z
2022-02-15T07:51:05.000Z
StiGame/sprites/IDirectionSprite.h
jordsti/stigame
6ac0ae737667b1c77da3ef5007f5c4a3a080045a
[ "MIT" ]
null
null
null
StiGame/sprites/IDirectionSprite.h
jordsti/stigame
6ac0ae737667b1c77da3ef5007f5c4a3a080045a
[ "MIT" ]
2
2017-02-13T18:04:00.000Z
2020-08-24T03:21:37.000Z
#ifndef IDIRECTIONSPRITE_H #define IDIRECTIONSPRITE_H #include "ISprite.h" namespace StiGame { enum SDirection { SD_UP = 1, SD_DOWN = 2, SD_LEFT = 4, SD_RIGHT = 8, SD_IDLE = 16 } ; class IDirectionSprite : public ISprite { public: IDirectionSprite(); virtual ~IDirectionSprite(); virtual SDirection getDirection(void) = 0; virtual void setDirection(SDirection m_direction) = 0; virtual void render(void) = 0; /// \brief Render Direction Sprite /// \param m_direction Sprite Direction /// \param m_frameTick Frame Tick virtual void render(SDirection m_direction, int m_frameTick) = 0; virtual void tick(void) = 0; }; } #endif // IDIRECTIONSPRITE_H
20.823529
88
0.693503
[ "render" ]
c1aaaccd2c1e8c5e0e05e7696adc58a1af3111af
84,179
c
C
src/sys/dev/qlnx/qlnxe/ecore_int.c
lastweek/source-freebsd
0821950b0c40cbc891a27964b342e0202a3859ec
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
src/sys/dev/qlnx/qlnxe/ecore_int.c
lastweek/source-freebsd
0821950b0c40cbc891a27964b342e0202a3859ec
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
src/sys/dev/qlnx/qlnxe/ecore_int.c
lastweek/source-freebsd
0821950b0c40cbc891a27964b342e0202a3859ec
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
/* * Copyright (c) 2017-2018 Cavium, 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: * * 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. * * 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. */ /* * File : ecore_int.c */ #include <sys/cdefs.h> __FBSDID("$FreeBSD$"); #include "bcm_osal.h" #include "ecore.h" #include "ecore_spq.h" #include "reg_addr.h" #include "ecore_gtt_reg_addr.h" #include "ecore_init_ops.h" #include "ecore_rt_defs.h" #include "ecore_int.h" #include "reg_addr.h" #include "ecore_hw.h" #include "ecore_sriov.h" #include "ecore_vf.h" #include "ecore_hw_defs.h" #include "ecore_hsi_common.h" #include "ecore_mcp.h" #include "ecore_dbg_fw_funcs.h" #ifdef DIAG /* This is nasty, but diag is using the drv_dbg_fw_funcs.c [non-ecore flavor], * and so the functions are lacking ecore prefix. * If there would be other clients needing this [or if the content that isn't * really optional there would increase], we'll need to re-think this. */ enum dbg_status dbg_read_attn(struct ecore_hwfn *dev, struct ecore_ptt *ptt, enum block_id block, enum dbg_attn_type attn_type, bool clear_status, struct dbg_attn_block_result *results); enum dbg_status dbg_parse_attn(struct ecore_hwfn *dev, struct dbg_attn_block_result *results); const char* dbg_get_status_str(enum dbg_status status); #define ecore_dbg_read_attn(hwfn, ptt, id, type, clear, results) \ dbg_read_attn(hwfn, ptt, id, type, clear, results) #define ecore_dbg_parse_attn(hwfn, results) \ dbg_parse_attn(hwfn, results) #define ecore_dbg_get_status_str(status) \ dbg_get_status_str(status) #endif struct ecore_pi_info { ecore_int_comp_cb_t comp_cb; void *cookie; /* Will be sent to the completion callback function */ }; struct ecore_sb_sp_info { struct ecore_sb_info sb_info; /* per protocol index data */ struct ecore_pi_info pi_info_arr[PIS_PER_SB_E4]; }; enum ecore_attention_type { ECORE_ATTN_TYPE_ATTN, ECORE_ATTN_TYPE_PARITY, }; #define SB_ATTN_ALIGNED_SIZE(p_hwfn) \ ALIGNED_TYPE_SIZE(struct atten_status_block, p_hwfn) struct aeu_invert_reg_bit { char bit_name[30]; #define ATTENTION_PARITY (1 << 0) #define ATTENTION_LENGTH_MASK (0x00000ff0) #define ATTENTION_LENGTH_SHIFT (4) #define ATTENTION_LENGTH(flags) (((flags) & ATTENTION_LENGTH_MASK) >> \ ATTENTION_LENGTH_SHIFT) #define ATTENTION_SINGLE (1 << ATTENTION_LENGTH_SHIFT) #define ATTENTION_PAR (ATTENTION_SINGLE | ATTENTION_PARITY) #define ATTENTION_PAR_INT ((2 << ATTENTION_LENGTH_SHIFT) | \ ATTENTION_PARITY) /* Multiple bits start with this offset */ #define ATTENTION_OFFSET_MASK (0x000ff000) #define ATTENTION_OFFSET_SHIFT (12) #define ATTENTION_BB_MASK (0x00700000) #define ATTENTION_BB_SHIFT (20) #define ATTENTION_BB(value) (value << ATTENTION_BB_SHIFT) #define ATTENTION_BB_DIFFERENT (1 << 23) #define ATTENTION_CLEAR_ENABLE (1 << 28) unsigned int flags; /* Callback to call if attention will be triggered */ enum _ecore_status_t (*cb)(struct ecore_hwfn *p_hwfn); enum block_id block_index; }; struct aeu_invert_reg { struct aeu_invert_reg_bit bits[32]; }; #define MAX_ATTN_GRPS (8) #define NUM_ATTN_REGS (9) static enum _ecore_status_t ecore_mcp_attn_cb(struct ecore_hwfn *p_hwfn) { u32 tmp = ecore_rd(p_hwfn, p_hwfn->p_dpc_ptt, MCP_REG_CPU_STATE); DP_INFO(p_hwfn->p_dev, "MCP_REG_CPU_STATE: %08x - Masking...\n", tmp); ecore_wr(p_hwfn, p_hwfn->p_dpc_ptt, MCP_REG_CPU_EVENT_MASK, 0xffffffff); return ECORE_SUCCESS; } #define ECORE_PSWHST_ATTENTION_DISABLED_PF_MASK (0x3c000) #define ECORE_PSWHST_ATTENTION_DISABLED_PF_SHIFT (14) #define ECORE_PSWHST_ATTENTION_DISABLED_VF_MASK (0x03fc0) #define ECORE_PSWHST_ATTENTION_DISABLED_VF_SHIFT (6) #define ECORE_PSWHST_ATTENTION_DISABLED_VALID_MASK (0x00020) #define ECORE_PSWHST_ATTENTION_DISABLED_VALID_SHIFT (5) #define ECORE_PSWHST_ATTENTION_DISABLED_CLIENT_MASK (0x0001e) #define ECORE_PSWHST_ATTENTION_DISABLED_CLIENT_SHIFT (1) #define ECORE_PSWHST_ATTENTION_DISABLED_WRITE_MASK (0x1) #define ECORE_PSWHST_ATTNETION_DISABLED_WRITE_SHIFT (0) #define ECORE_PSWHST_ATTENTION_VF_DISABLED (0x1) #define ECORE_PSWHST_ATTENTION_INCORRECT_ACCESS (0x1) #define ECORE_PSWHST_ATTENTION_INCORRECT_ACCESS_WR_MASK (0x1) #define ECORE_PSWHST_ATTENTION_INCORRECT_ACCESS_WR_SHIFT (0) #define ECORE_PSWHST_ATTENTION_INCORRECT_ACCESS_CLIENT_MASK (0x1e) #define ECORE_PSWHST_ATTENTION_INCORRECT_ACCESS_CLIENT_SHIFT (1) #define ECORE_PSWHST_ATTENTION_INCORRECT_ACCESS_VF_VALID_MASK (0x20) #define ECORE_PSWHST_ATTENTION_INCORRECT_ACCESS_VF_VALID_SHIFT (5) #define ECORE_PSWHST_ATTENTION_INCORRECT_ACCESS_VF_ID_MASK (0x3fc0) #define ECORE_PSWHST_ATTENTION_INCORRECT_ACCESS_VF_ID_SHIFT (6) #define ECORE_PSWHST_ATTENTION_INCORRECT_ACCESS_PF_ID_MASK (0x3c000) #define ECORE_PSWHST_ATTENTION_INCORRECT_ACCESS_PF_ID_SHIFT (14) #define ECORE_PSWHST_ATTENTION_INCORRECT_ACCESS_BYTE_EN_MASK (0x3fc0000) #define ECORE_PSWHST_ATTENTION_INCORRECT_ACCESS_BYTE_EN_SHIFT (18) static enum _ecore_status_t ecore_pswhst_attn_cb(struct ecore_hwfn *p_hwfn) { u32 tmp = ecore_rd(p_hwfn, p_hwfn->p_dpc_ptt, PSWHST_REG_VF_DISABLED_ERROR_VALID); /* Disabled VF access */ if (tmp & ECORE_PSWHST_ATTENTION_VF_DISABLED) { u32 addr, data; addr = ecore_rd(p_hwfn, p_hwfn->p_dpc_ptt, PSWHST_REG_VF_DISABLED_ERROR_ADDRESS); data = ecore_rd(p_hwfn, p_hwfn->p_dpc_ptt, PSWHST_REG_VF_DISABLED_ERROR_DATA); DP_INFO(p_hwfn->p_dev, "PF[0x%02x] VF [0x%02x] [Valid 0x%02x] Client [0x%02x] Write [0x%02x] Addr [0x%08x]\n", (u8)((data & ECORE_PSWHST_ATTENTION_DISABLED_PF_MASK) >> ECORE_PSWHST_ATTENTION_DISABLED_PF_SHIFT), (u8)((data & ECORE_PSWHST_ATTENTION_DISABLED_VF_MASK) >> ECORE_PSWHST_ATTENTION_DISABLED_VF_SHIFT), (u8)((data & ECORE_PSWHST_ATTENTION_DISABLED_VALID_MASK) >> ECORE_PSWHST_ATTENTION_DISABLED_VALID_SHIFT), (u8)((data & ECORE_PSWHST_ATTENTION_DISABLED_CLIENT_MASK) >> ECORE_PSWHST_ATTENTION_DISABLED_CLIENT_SHIFT), (u8)((data & ECORE_PSWHST_ATTENTION_DISABLED_WRITE_MASK) >> ECORE_PSWHST_ATTNETION_DISABLED_WRITE_SHIFT), addr); } tmp = ecore_rd(p_hwfn, p_hwfn->p_dpc_ptt, PSWHST_REG_INCORRECT_ACCESS_VALID); if (tmp & ECORE_PSWHST_ATTENTION_INCORRECT_ACCESS) { u32 addr, data, length; addr = ecore_rd(p_hwfn, p_hwfn->p_dpc_ptt, PSWHST_REG_INCORRECT_ACCESS_ADDRESS); data = ecore_rd(p_hwfn, p_hwfn->p_dpc_ptt, PSWHST_REG_INCORRECT_ACCESS_DATA); length = ecore_rd(p_hwfn, p_hwfn->p_dpc_ptt, PSWHST_REG_INCORRECT_ACCESS_LENGTH); DP_INFO(p_hwfn->p_dev, "Incorrect access to %08x of length %08x - PF [%02x] VF [%04x] [valid %02x] client [%02x] write [%02x] Byte-Enable [%04x] [%08x]\n", addr, length, (u8)((data & ECORE_PSWHST_ATTENTION_INCORRECT_ACCESS_PF_ID_MASK) >> ECORE_PSWHST_ATTENTION_INCORRECT_ACCESS_PF_ID_SHIFT), (u8)((data & ECORE_PSWHST_ATTENTION_INCORRECT_ACCESS_VF_ID_MASK) >> ECORE_PSWHST_ATTENTION_INCORRECT_ACCESS_VF_ID_SHIFT), (u8)((data & ECORE_PSWHST_ATTENTION_INCORRECT_ACCESS_VF_VALID_MASK) >> ECORE_PSWHST_ATTENTION_INCORRECT_ACCESS_VF_VALID_SHIFT), (u8)((data & ECORE_PSWHST_ATTENTION_INCORRECT_ACCESS_CLIENT_MASK) >> ECORE_PSWHST_ATTENTION_INCORRECT_ACCESS_CLIENT_SHIFT), (u8)((data & ECORE_PSWHST_ATTENTION_INCORRECT_ACCESS_WR_MASK) >> ECORE_PSWHST_ATTENTION_INCORRECT_ACCESS_WR_SHIFT), (u8)((data & ECORE_PSWHST_ATTENTION_INCORRECT_ACCESS_BYTE_EN_MASK) >> ECORE_PSWHST_ATTENTION_INCORRECT_ACCESS_BYTE_EN_SHIFT), data); } /* TODO - We know 'some' of these are legal due to virtualization, * but is it true for all of them? */ return ECORE_SUCCESS; } #define ECORE_GRC_ATTENTION_VALID_BIT (1 << 0) #define ECORE_GRC_ATTENTION_ADDRESS_MASK (0x7fffff << 0) #define ECORE_GRC_ATTENTION_RDWR_BIT (1 << 23) #define ECORE_GRC_ATTENTION_MASTER_MASK (0xf << 24) #define ECORE_GRC_ATTENTION_MASTER_SHIFT (24) #define ECORE_GRC_ATTENTION_PF_MASK (0xf) #define ECORE_GRC_ATTENTION_VF_MASK (0xff << 4) #define ECORE_GRC_ATTENTION_VF_SHIFT (4) #define ECORE_GRC_ATTENTION_PRIV_MASK (0x3 << 14) #define ECORE_GRC_ATTENTION_PRIV_SHIFT (14) #define ECORE_GRC_ATTENTION_PRIV_VF (0) static const char* grc_timeout_attn_master_to_str(u8 master) { switch(master) { case 1: return "PXP"; case 2: return "MCP"; case 3: return "MSDM"; case 4: return "PSDM"; case 5: return "YSDM"; case 6: return "USDM"; case 7: return "TSDM"; case 8: return "XSDM"; case 9: return "DBU"; case 10: return "DMAE"; default: return "Unkown"; } } static enum _ecore_status_t ecore_grc_attn_cb(struct ecore_hwfn *p_hwfn) { u32 tmp, tmp2; /* We've already cleared the timeout interrupt register, so we learn * of interrupts via the validity register */ tmp = ecore_rd(p_hwfn, p_hwfn->p_dpc_ptt, GRC_REG_TIMEOUT_ATTN_ACCESS_VALID); if (!(tmp & ECORE_GRC_ATTENTION_VALID_BIT)) goto out; /* Read the GRC timeout information */ tmp = ecore_rd(p_hwfn, p_hwfn->p_dpc_ptt, GRC_REG_TIMEOUT_ATTN_ACCESS_DATA_0); tmp2 = ecore_rd(p_hwfn, p_hwfn->p_dpc_ptt, GRC_REG_TIMEOUT_ATTN_ACCESS_DATA_1); DP_NOTICE(p_hwfn->p_dev, false, "GRC timeout [%08x:%08x] - %s Address [%08x] [Master %s] [PF: %02x %s %02x]\n", tmp2, tmp, (tmp & ECORE_GRC_ATTENTION_RDWR_BIT) ? "Write to" : "Read from", (tmp & ECORE_GRC_ATTENTION_ADDRESS_MASK) << 2, grc_timeout_attn_master_to_str((tmp & ECORE_GRC_ATTENTION_MASTER_MASK) >> ECORE_GRC_ATTENTION_MASTER_SHIFT), (tmp2 & ECORE_GRC_ATTENTION_PF_MASK), (((tmp2 & ECORE_GRC_ATTENTION_PRIV_MASK) >> ECORE_GRC_ATTENTION_PRIV_SHIFT) == ECORE_GRC_ATTENTION_PRIV_VF) ? "VF" : "(Irrelevant:)", (tmp2 & ECORE_GRC_ATTENTION_VF_MASK) >> ECORE_GRC_ATTENTION_VF_SHIFT); out: /* Regardles of anything else, clean the validity bit */ ecore_wr(p_hwfn, p_hwfn->p_dpc_ptt, GRC_REG_TIMEOUT_ATTN_ACCESS_VALID, 0); return ECORE_SUCCESS; } #define ECORE_PGLUE_ATTENTION_VALID (1 << 29) #define ECORE_PGLUE_ATTENTION_RD_VALID (1 << 26) #define ECORE_PGLUE_ATTENTION_DETAILS_PFID_MASK (0xf << 20) #define ECORE_PGLUE_ATTENTION_DETAILS_PFID_SHIFT (20) #define ECORE_PGLUE_ATTENTION_DETAILS_VF_VALID (1 << 19) #define ECORE_PGLUE_ATTENTION_DETAILS_VFID_MASK (0xff << 24) #define ECORE_PGLUE_ATTENTION_DETAILS_VFID_SHIFT (24) #define ECORE_PGLUE_ATTENTION_DETAILS2_WAS_ERR (1 << 21) #define ECORE_PGLUE_ATTENTION_DETAILS2_BME (1 << 22) #define ECORE_PGLUE_ATTENTION_DETAILS2_FID_EN (1 << 23) #define ECORE_PGLUE_ATTENTION_ICPL_VALID (1 << 23) #define ECORE_PGLUE_ATTENTION_ZLR_VALID (1 << 25) #define ECORE_PGLUE_ATTENTION_ILT_VALID (1 << 23) enum _ecore_status_t ecore_pglueb_rbc_attn_handler(struct ecore_hwfn *p_hwfn, struct ecore_ptt *p_ptt) { u32 tmp; tmp = ecore_rd(p_hwfn, p_ptt, PGLUE_B_REG_TX_ERR_WR_DETAILS2); if (tmp & ECORE_PGLUE_ATTENTION_VALID) { u32 addr_lo, addr_hi, details; addr_lo = ecore_rd(p_hwfn, p_ptt, PGLUE_B_REG_TX_ERR_WR_ADD_31_0); addr_hi = ecore_rd(p_hwfn, p_ptt, PGLUE_B_REG_TX_ERR_WR_ADD_63_32); details = ecore_rd(p_hwfn, p_ptt, PGLUE_B_REG_TX_ERR_WR_DETAILS); DP_NOTICE(p_hwfn, false, "Illegal write by chip to [%08x:%08x] blocked. Details: %08x [PFID %02x, VFID %02x, VF_VALID %02x] Details2 %08x [Was_error %02x BME deassert %02x FID_enable deassert %02x]\n", addr_hi, addr_lo, details, (u8)((details & ECORE_PGLUE_ATTENTION_DETAILS_PFID_MASK) >> ECORE_PGLUE_ATTENTION_DETAILS_PFID_SHIFT), (u8)((details & ECORE_PGLUE_ATTENTION_DETAILS_VFID_MASK) >> ECORE_PGLUE_ATTENTION_DETAILS_VFID_SHIFT), (u8)((details & ECORE_PGLUE_ATTENTION_DETAILS_VF_VALID) ? 1 : 0), tmp, (u8)((tmp & ECORE_PGLUE_ATTENTION_DETAILS2_WAS_ERR) ? 1 : 0), (u8)((tmp & ECORE_PGLUE_ATTENTION_DETAILS2_BME) ? 1 : 0), (u8)((tmp & ECORE_PGLUE_ATTENTION_DETAILS2_FID_EN) ? 1 : 0)); } tmp = ecore_rd(p_hwfn, p_ptt, PGLUE_B_REG_TX_ERR_RD_DETAILS2); if (tmp & ECORE_PGLUE_ATTENTION_RD_VALID) { u32 addr_lo, addr_hi, details; addr_lo = ecore_rd(p_hwfn, p_ptt, PGLUE_B_REG_TX_ERR_RD_ADD_31_0); addr_hi = ecore_rd(p_hwfn, p_ptt, PGLUE_B_REG_TX_ERR_RD_ADD_63_32); details = ecore_rd(p_hwfn, p_ptt, PGLUE_B_REG_TX_ERR_RD_DETAILS); DP_NOTICE(p_hwfn, false, "Illegal read by chip from [%08x:%08x] blocked. Details: %08x [PFID %02x, VFID %02x, VF_VALID %02x] Details2 %08x [Was_error %02x BME deassert %02x FID_enable deassert %02x]\n", addr_hi, addr_lo, details, (u8)((details & ECORE_PGLUE_ATTENTION_DETAILS_PFID_MASK) >> ECORE_PGLUE_ATTENTION_DETAILS_PFID_SHIFT), (u8)((details & ECORE_PGLUE_ATTENTION_DETAILS_VFID_MASK) >> ECORE_PGLUE_ATTENTION_DETAILS_VFID_SHIFT), (u8)((details & ECORE_PGLUE_ATTENTION_DETAILS_VF_VALID) ? 1 : 0), tmp, (u8)((tmp & ECORE_PGLUE_ATTENTION_DETAILS2_WAS_ERR) ? 1 : 0), (u8)((tmp & ECORE_PGLUE_ATTENTION_DETAILS2_BME) ? 1 : 0), (u8)((tmp & ECORE_PGLUE_ATTENTION_DETAILS2_FID_EN) ? 1 : 0)); } tmp = ecore_rd(p_hwfn, p_ptt, PGLUE_B_REG_TX_ERR_WR_DETAILS_ICPL); if (tmp & ECORE_PGLUE_ATTENTION_ICPL_VALID) DP_NOTICE(p_hwfn, false, "ICPL eror - %08x\n", tmp); tmp = ecore_rd(p_hwfn, p_ptt, PGLUE_B_REG_MASTER_ZLR_ERR_DETAILS); if (tmp & ECORE_PGLUE_ATTENTION_ZLR_VALID) { u32 addr_hi, addr_lo; addr_lo = ecore_rd(p_hwfn, p_ptt, PGLUE_B_REG_MASTER_ZLR_ERR_ADD_31_0); addr_hi = ecore_rd(p_hwfn, p_ptt, PGLUE_B_REG_MASTER_ZLR_ERR_ADD_63_32); DP_NOTICE(p_hwfn, false, "ICPL eror - %08x [Address %08x:%08x]\n", tmp, addr_hi, addr_lo); } tmp = ecore_rd(p_hwfn, p_ptt, PGLUE_B_REG_VF_ILT_ERR_DETAILS2); if (tmp & ECORE_PGLUE_ATTENTION_ILT_VALID) { u32 addr_hi, addr_lo, details; addr_lo = ecore_rd(p_hwfn, p_ptt, PGLUE_B_REG_VF_ILT_ERR_ADD_31_0); addr_hi = ecore_rd(p_hwfn, p_ptt, PGLUE_B_REG_VF_ILT_ERR_ADD_63_32); details = ecore_rd(p_hwfn, p_ptt, PGLUE_B_REG_VF_ILT_ERR_DETAILS); DP_NOTICE(p_hwfn, false, "ILT error - Details %08x Details2 %08x [Address %08x:%08x]\n", details, tmp, addr_hi, addr_lo); } /* Clear the indications */ ecore_wr(p_hwfn, p_ptt, PGLUE_B_REG_LATCHED_ERRORS_CLR, (1 << 2)); return ECORE_SUCCESS; } static enum _ecore_status_t ecore_pglueb_rbc_attn_cb(struct ecore_hwfn *p_hwfn) { return ecore_pglueb_rbc_attn_handler(p_hwfn, p_hwfn->p_dpc_ptt); } static enum _ecore_status_t ecore_fw_assertion(struct ecore_hwfn *p_hwfn) { DP_NOTICE(p_hwfn, false, "FW assertion!\n"); ecore_hw_err_notify(p_hwfn, ECORE_HW_ERR_FW_ASSERT); return ECORE_INVAL; } static enum _ecore_status_t ecore_general_attention_35(struct ecore_hwfn *p_hwfn) { DP_INFO(p_hwfn, "General attention 35!\n"); return ECORE_SUCCESS; } #define ECORE_DORQ_ATTENTION_REASON_MASK (0xfffff) #define ECORE_DORQ_ATTENTION_OPAQUE_MASK (0xffff) #define ECORE_DORQ_ATTENTION_OPAQUE_SHIFT (0x0) #define ECORE_DORQ_ATTENTION_SIZE_MASK (0x7f) #define ECORE_DORQ_ATTENTION_SIZE_SHIFT (16) #define ECORE_DB_REC_COUNT 10 #define ECORE_DB_REC_INTERVAL 100 /* assumes sticky overflow indication was set for this PF */ static enum _ecore_status_t ecore_db_rec_attn(struct ecore_hwfn *p_hwfn, struct ecore_ptt *p_ptt) { u8 count = ECORE_DB_REC_COUNT; u32 usage = 1; /* wait for usage to zero or count to run out. This is necessary since * EDPM doorbell transactions can take multiple 64b cycles, and as such * can "split" over the pci. Possibly, the doorbell drop can happen with * half an EDPM in the queue and other half dropped. Another EDPM * doorbell to the same address (from doorbell recovery mechanism or * from the doorbelling entity) could have first half dropped and second * half interperted as continuation of the first. To prevent such * malformed doorbells from reaching the device, flush the queue before * releaseing the overflow sticky indication. */ while (count-- && usage) { usage = ecore_rd(p_hwfn, p_ptt, DORQ_REG_PF_USAGE_CNT); OSAL_UDELAY(ECORE_DB_REC_INTERVAL); } /* should have been depleted by now */ if (usage) { DP_NOTICE(p_hwfn->p_dev, false, "DB recovery: doorbell usage failed to zero after %d usec. usage was %x\n", ECORE_DB_REC_INTERVAL * ECORE_DB_REC_COUNT, usage); return ECORE_TIMEOUT; } /* flush any pedning (e)dpm as they may never arrive */ ecore_wr(p_hwfn, p_ptt, DORQ_REG_DPM_FORCE_ABORT, 0x1); /* release overflow sticky indication (stop silently dropping everything) */ ecore_wr(p_hwfn, p_ptt, DORQ_REG_PF_OVFL_STICKY, 0x0); /* repeat all last doorbells (doorbell drop recovery) */ ecore_db_recovery_execute(p_hwfn, DB_REC_REAL_DEAL); return ECORE_SUCCESS; } static enum _ecore_status_t ecore_dorq_attn_cb(struct ecore_hwfn *p_hwfn) { u32 int_sts, first_drop_reason, details, address, overflow, all_drops_reason; struct ecore_ptt *p_ptt = p_hwfn->p_dpc_ptt; enum _ecore_status_t rc; int_sts = ecore_rd(p_hwfn, p_ptt, DORQ_REG_INT_STS); DP_NOTICE(p_hwfn->p_dev, false, "DORQ attention. int_sts was %x\n", int_sts); /* int_sts may be zero since all PFs were interrupted for doorbell * overflow but another one already handled it. Can abort here. If * This PF also requires overflow recovery we will be interrupted again. * The masked almost full indication may also be set. Ignoring. */ if (!(int_sts & ~DORQ_REG_INT_STS_DORQ_FIFO_AFULL)) return ECORE_SUCCESS; /* check if db_drop or overflow happened */ if (int_sts & (DORQ_REG_INT_STS_DB_DROP | DORQ_REG_INT_STS_DORQ_FIFO_OVFL_ERR)) { /* obtain data about db drop/overflow */ first_drop_reason = ecore_rd(p_hwfn, p_ptt, DORQ_REG_DB_DROP_REASON) & ECORE_DORQ_ATTENTION_REASON_MASK; details = ecore_rd(p_hwfn, p_ptt, DORQ_REG_DB_DROP_DETAILS); address = ecore_rd(p_hwfn, p_ptt, DORQ_REG_DB_DROP_DETAILS_ADDRESS); overflow = ecore_rd(p_hwfn, p_ptt, DORQ_REG_PF_OVFL_STICKY); all_drops_reason = ecore_rd(p_hwfn, p_ptt, DORQ_REG_DB_DROP_DETAILS_REASON); /* log info */ DP_NOTICE(p_hwfn->p_dev, false, "Doorbell drop occurred\n" "Address\t\t0x%08x\t(second BAR address)\n" "FID\t\t0x%04x\t\t(Opaque FID)\n" "Size\t\t0x%04x\t\t(in bytes)\n" "1st drop reason\t0x%08x\t(details on first drop since last handling)\n" "Sticky reasons\t0x%08x\t(all drop reasons since last handling)\n" "Overflow\t0x%x\t\t(a per PF indication)\n", address, GET_FIELD(details, ECORE_DORQ_ATTENTION_OPAQUE), GET_FIELD(details, ECORE_DORQ_ATTENTION_SIZE) * 4, first_drop_reason, all_drops_reason, overflow); /* if this PF caused overflow, initiate recovery */ if (overflow) { rc = ecore_db_rec_attn(p_hwfn, p_ptt); if (rc != ECORE_SUCCESS) return rc; } /* clear the doorbell drop details and prepare for next drop */ ecore_wr(p_hwfn, p_ptt, DORQ_REG_DB_DROP_DETAILS_REL, 0); /* mark interrupt as handeld (note: even if drop was due to a diffrent * reason than overflow we mark as handled) */ ecore_wr(p_hwfn, p_ptt, DORQ_REG_INT_STS_WR, DORQ_REG_INT_STS_DB_DROP | DORQ_REG_INT_STS_DORQ_FIFO_OVFL_ERR); /* if there are no indications otherthan drop indications, success */ if ((int_sts & ~(DORQ_REG_INT_STS_DB_DROP | DORQ_REG_INT_STS_DORQ_FIFO_OVFL_ERR | DORQ_REG_INT_STS_DORQ_FIFO_AFULL)) == 0) return ECORE_SUCCESS; } /* some other indication was present - non recoverable */ DP_INFO(p_hwfn, "DORQ fatal attention\n"); return ECORE_INVAL; } static enum _ecore_status_t ecore_tm_attn_cb(struct ecore_hwfn *p_hwfn) { #ifndef ASIC_ONLY if (CHIP_REV_IS_EMUL_B0(p_hwfn->p_dev)) { u32 val = ecore_rd(p_hwfn, p_hwfn->p_dpc_ptt, TM_REG_INT_STS_1); if (val & ~(TM_REG_INT_STS_1_PEND_TASK_SCAN | TM_REG_INT_STS_1_PEND_CONN_SCAN)) return ECORE_INVAL; if (val & (TM_REG_INT_STS_1_PEND_TASK_SCAN | TM_REG_INT_STS_1_PEND_CONN_SCAN)) DP_INFO(p_hwfn, "TM attention on emulation - most likely results of clock-ratios\n"); val = ecore_rd(p_hwfn, p_hwfn->p_dpc_ptt, TM_REG_INT_MASK_1); val |= TM_REG_INT_MASK_1_PEND_CONN_SCAN | TM_REG_INT_MASK_1_PEND_TASK_SCAN; ecore_wr(p_hwfn, p_hwfn->p_dpc_ptt, TM_REG_INT_MASK_1, val); return ECORE_SUCCESS; } #endif return ECORE_INVAL; } /* Instead of major changes to the data-structure, we have a some 'special' * identifiers for sources that changed meaning between adapters. */ enum aeu_invert_reg_special_type { AEU_INVERT_REG_SPECIAL_CNIG_0, AEU_INVERT_REG_SPECIAL_CNIG_1, AEU_INVERT_REG_SPECIAL_CNIG_2, AEU_INVERT_REG_SPECIAL_CNIG_3, AEU_INVERT_REG_SPECIAL_MAX, }; static struct aeu_invert_reg_bit aeu_descs_special[AEU_INVERT_REG_SPECIAL_MAX] = { {"CNIG port 0", ATTENTION_SINGLE, OSAL_NULL, BLOCK_CNIG}, {"CNIG port 1", ATTENTION_SINGLE, OSAL_NULL, BLOCK_CNIG}, {"CNIG port 2", ATTENTION_SINGLE, OSAL_NULL, BLOCK_CNIG}, {"CNIG port 3", ATTENTION_SINGLE, OSAL_NULL, BLOCK_CNIG}, }; /* Notice aeu_invert_reg must be defined in the same order of bits as HW; */ static struct aeu_invert_reg aeu_descs[NUM_ATTN_REGS] = { { { /* After Invert 1 */ {"GPIO0 function%d", (32 << ATTENTION_LENGTH_SHIFT), OSAL_NULL, MAX_BLOCK_ID}, } }, { { /* After Invert 2 */ {"PGLUE config_space", ATTENTION_SINGLE, OSAL_NULL, MAX_BLOCK_ID}, {"PGLUE misc_flr", ATTENTION_SINGLE, OSAL_NULL, MAX_BLOCK_ID}, {"PGLUE B RBC", ATTENTION_PAR_INT, ecore_pglueb_rbc_attn_cb, BLOCK_PGLUE_B}, {"PGLUE misc_mctp", ATTENTION_SINGLE, OSAL_NULL, MAX_BLOCK_ID}, {"Flash event", ATTENTION_SINGLE, OSAL_NULL, MAX_BLOCK_ID}, {"SMB event", ATTENTION_SINGLE, OSAL_NULL, MAX_BLOCK_ID}, {"Main Power", ATTENTION_SINGLE, OSAL_NULL, MAX_BLOCK_ID}, {"SW timers #%d", (8 << ATTENTION_LENGTH_SHIFT) | (1 << ATTENTION_OFFSET_SHIFT), OSAL_NULL, MAX_BLOCK_ID}, {"PCIE glue/PXP VPD %d", (16 << ATTENTION_LENGTH_SHIFT), OSAL_NULL, BLOCK_PGLCS}, } }, { { /* After Invert 3 */ {"General Attention %d", (32 << ATTENTION_LENGTH_SHIFT), OSAL_NULL, MAX_BLOCK_ID}, } }, { { /* After Invert 4 */ {"General Attention 32", ATTENTION_SINGLE | ATTENTION_CLEAR_ENABLE, ecore_fw_assertion, MAX_BLOCK_ID}, {"General Attention %d", (2 << ATTENTION_LENGTH_SHIFT) | (33 << ATTENTION_OFFSET_SHIFT), OSAL_NULL, MAX_BLOCK_ID}, {"General Attention 35", ATTENTION_SINGLE | ATTENTION_CLEAR_ENABLE, ecore_general_attention_35, MAX_BLOCK_ID}, {"NWS Parity", ATTENTION_PAR | ATTENTION_BB_DIFFERENT | ATTENTION_BB(AEU_INVERT_REG_SPECIAL_CNIG_0) , OSAL_NULL, BLOCK_NWS}, {"NWS Interrupt", ATTENTION_SINGLE | ATTENTION_BB_DIFFERENT | ATTENTION_BB(AEU_INVERT_REG_SPECIAL_CNIG_1), OSAL_NULL, BLOCK_NWS}, {"NWM Parity", ATTENTION_PAR | ATTENTION_BB_DIFFERENT | ATTENTION_BB(AEU_INVERT_REG_SPECIAL_CNIG_2), OSAL_NULL, BLOCK_NWM}, {"NWM Interrupt", ATTENTION_SINGLE | ATTENTION_BB_DIFFERENT | ATTENTION_BB(AEU_INVERT_REG_SPECIAL_CNIG_3), OSAL_NULL, BLOCK_NWM}, {"MCP CPU", ATTENTION_SINGLE, ecore_mcp_attn_cb, MAX_BLOCK_ID}, {"MCP Watchdog timer", ATTENTION_SINGLE, OSAL_NULL, MAX_BLOCK_ID}, {"MCP M2P", ATTENTION_SINGLE, OSAL_NULL, MAX_BLOCK_ID}, {"AVS stop status ready", ATTENTION_SINGLE, OSAL_NULL, MAX_BLOCK_ID}, {"MSTAT", ATTENTION_PAR_INT, OSAL_NULL, MAX_BLOCK_ID}, {"MSTAT per-path", ATTENTION_PAR_INT, OSAL_NULL, MAX_BLOCK_ID}, {"Reserved %d", (6 << ATTENTION_LENGTH_SHIFT), OSAL_NULL, MAX_BLOCK_ID }, {"NIG", ATTENTION_PAR_INT, OSAL_NULL, BLOCK_NIG}, {"BMB/OPTE/MCP", ATTENTION_PAR_INT, OSAL_NULL, BLOCK_BMB}, {"BTB", ATTENTION_PAR_INT, OSAL_NULL, BLOCK_BTB}, {"BRB", ATTENTION_PAR_INT, OSAL_NULL, BLOCK_BRB}, {"PRS", ATTENTION_PAR_INT, OSAL_NULL, BLOCK_PRS}, } }, { { /* After Invert 5 */ {"SRC", ATTENTION_PAR_INT, OSAL_NULL, BLOCK_SRC}, {"PB Client1", ATTENTION_PAR_INT, OSAL_NULL, BLOCK_PBF_PB1}, {"PB Client2", ATTENTION_PAR_INT, OSAL_NULL, BLOCK_PBF_PB2}, {"RPB", ATTENTION_PAR_INT, OSAL_NULL, BLOCK_RPB}, {"PBF", ATTENTION_PAR_INT, OSAL_NULL, BLOCK_PBF}, {"QM", ATTENTION_PAR_INT, OSAL_NULL, BLOCK_QM}, {"TM", ATTENTION_PAR_INT, ecore_tm_attn_cb, BLOCK_TM}, {"MCM", ATTENTION_PAR_INT, OSAL_NULL, BLOCK_MCM}, {"MSDM", ATTENTION_PAR_INT, OSAL_NULL, BLOCK_MSDM}, {"MSEM", ATTENTION_PAR_INT, OSAL_NULL, BLOCK_MSEM}, {"PCM", ATTENTION_PAR_INT, OSAL_NULL, BLOCK_PCM}, {"PSDM", ATTENTION_PAR_INT, OSAL_NULL, BLOCK_PSDM}, {"PSEM", ATTENTION_PAR_INT, OSAL_NULL, BLOCK_PSEM}, {"TCM", ATTENTION_PAR_INT, OSAL_NULL, BLOCK_TCM}, {"TSDM", ATTENTION_PAR_INT, OSAL_NULL, BLOCK_TSDM}, {"TSEM", ATTENTION_PAR_INT, OSAL_NULL, BLOCK_TSEM}, } }, { { /* After Invert 6 */ {"UCM", ATTENTION_PAR_INT, OSAL_NULL, BLOCK_UCM}, {"USDM", ATTENTION_PAR_INT, OSAL_NULL, BLOCK_USDM}, {"USEM", ATTENTION_PAR_INT, OSAL_NULL, BLOCK_USEM}, {"XCM", ATTENTION_PAR_INT, OSAL_NULL, BLOCK_XCM}, {"XSDM", ATTENTION_PAR_INT, OSAL_NULL, BLOCK_XSDM}, {"XSEM", ATTENTION_PAR_INT, OSAL_NULL, BLOCK_XSEM}, {"YCM", ATTENTION_PAR_INT, OSAL_NULL, BLOCK_YCM}, {"YSDM", ATTENTION_PAR_INT, OSAL_NULL, BLOCK_YSDM}, {"YSEM", ATTENTION_PAR_INT, OSAL_NULL, BLOCK_YSEM}, {"XYLD", ATTENTION_PAR_INT, OSAL_NULL, BLOCK_XYLD}, {"TMLD", ATTENTION_PAR_INT, OSAL_NULL, BLOCK_TMLD}, {"MYLD", ATTENTION_PAR_INT, OSAL_NULL, BLOCK_MULD}, {"YULD", ATTENTION_PAR_INT, OSAL_NULL, BLOCK_YULD}, {"DORQ", ATTENTION_PAR_INT, ecore_dorq_attn_cb, BLOCK_DORQ}, {"DBG", ATTENTION_PAR_INT, OSAL_NULL, BLOCK_DBG}, {"IPC", ATTENTION_PAR_INT, OSAL_NULL, BLOCK_IPC}, } }, { { /* After Invert 7 */ {"CCFC", ATTENTION_PAR_INT, OSAL_NULL, BLOCK_CCFC}, {"CDU", ATTENTION_PAR_INT, OSAL_NULL, BLOCK_CDU}, {"DMAE", ATTENTION_PAR_INT, OSAL_NULL, BLOCK_DMAE}, {"IGU", ATTENTION_PAR_INT, OSAL_NULL, BLOCK_IGU}, {"ATC", ATTENTION_PAR_INT, OSAL_NULL, MAX_BLOCK_ID}, {"CAU", ATTENTION_PAR_INT, OSAL_NULL, BLOCK_CAU}, {"PTU", ATTENTION_PAR_INT, OSAL_NULL, BLOCK_PTU}, {"PRM", ATTENTION_PAR_INT, OSAL_NULL, BLOCK_PRM}, {"TCFC", ATTENTION_PAR_INT, OSAL_NULL, BLOCK_TCFC}, {"RDIF", ATTENTION_PAR_INT, OSAL_NULL, BLOCK_RDIF}, {"TDIF", ATTENTION_PAR_INT, OSAL_NULL, BLOCK_TDIF}, {"RSS", ATTENTION_PAR_INT, OSAL_NULL, BLOCK_RSS}, {"MISC", ATTENTION_PAR_INT, OSAL_NULL, BLOCK_MISC}, {"MISCS", ATTENTION_PAR_INT, OSAL_NULL, BLOCK_MISCS}, {"PCIE", ATTENTION_PAR, OSAL_NULL, BLOCK_PCIE}, {"Vaux PCI core", ATTENTION_SINGLE, OSAL_NULL, BLOCK_PGLCS}, {"PSWRQ", ATTENTION_PAR_INT, OSAL_NULL, BLOCK_PSWRQ}, } }, { { /* After Invert 8 */ {"PSWRQ (pci_clk)", ATTENTION_PAR_INT, OSAL_NULL, BLOCK_PSWRQ2}, {"PSWWR", ATTENTION_PAR_INT, OSAL_NULL, BLOCK_PSWWR}, {"PSWWR (pci_clk)", ATTENTION_PAR_INT, OSAL_NULL, BLOCK_PSWWR2}, {"PSWRD", ATTENTION_PAR_INT, OSAL_NULL, BLOCK_PSWRD}, {"PSWRD (pci_clk)", ATTENTION_PAR_INT, OSAL_NULL, BLOCK_PSWRD2}, {"PSWHST", ATTENTION_PAR_INT, ecore_pswhst_attn_cb, BLOCK_PSWHST}, {"PSWHST (pci_clk)", ATTENTION_PAR_INT, OSAL_NULL, BLOCK_PSWHST2}, {"GRC", ATTENTION_PAR_INT, ecore_grc_attn_cb, BLOCK_GRC}, {"CPMU", ATTENTION_PAR_INT, OSAL_NULL, BLOCK_CPMU}, {"NCSI", ATTENTION_PAR_INT, OSAL_NULL, BLOCK_NCSI}, {"MSEM PRAM", ATTENTION_PAR, OSAL_NULL, MAX_BLOCK_ID}, {"PSEM PRAM", ATTENTION_PAR, OSAL_NULL, MAX_BLOCK_ID}, {"TSEM PRAM", ATTENTION_PAR, OSAL_NULL, MAX_BLOCK_ID}, {"USEM PRAM", ATTENTION_PAR, OSAL_NULL, MAX_BLOCK_ID}, {"XSEM PRAM", ATTENTION_PAR, OSAL_NULL, MAX_BLOCK_ID}, {"YSEM PRAM", ATTENTION_PAR, OSAL_NULL, MAX_BLOCK_ID}, {"pxp_misc_mps", ATTENTION_PAR, OSAL_NULL, BLOCK_PGLCS}, {"PCIE glue/PXP Exp. ROM", ATTENTION_SINGLE, OSAL_NULL, BLOCK_PGLCS}, {"PERST_B assertion", ATTENTION_SINGLE, OSAL_NULL, MAX_BLOCK_ID}, {"PERST_B deassertion", ATTENTION_SINGLE, OSAL_NULL, MAX_BLOCK_ID}, {"Reserved %d", (2 << ATTENTION_LENGTH_SHIFT), OSAL_NULL, MAX_BLOCK_ID }, } }, { { /* After Invert 9 */ {"MCP Latched memory", ATTENTION_PAR, OSAL_NULL, MAX_BLOCK_ID}, {"MCP Latched scratchpad cache", ATTENTION_SINGLE, OSAL_NULL, MAX_BLOCK_ID}, {"MCP Latched ump_tx", ATTENTION_PAR, OSAL_NULL, MAX_BLOCK_ID}, {"MCP Latched scratchpad", ATTENTION_PAR, OSAL_NULL, MAX_BLOCK_ID}, {"Reserved %d", (28 << ATTENTION_LENGTH_SHIFT), OSAL_NULL, MAX_BLOCK_ID }, } }, }; static struct aeu_invert_reg_bit * ecore_int_aeu_translate(struct ecore_hwfn *p_hwfn, struct aeu_invert_reg_bit *p_bit) { if (!ECORE_IS_BB(p_hwfn->p_dev)) return p_bit; if (!(p_bit->flags & ATTENTION_BB_DIFFERENT)) return p_bit; return &aeu_descs_special[(p_bit->flags & ATTENTION_BB_MASK) >> ATTENTION_BB_SHIFT]; } static bool ecore_int_is_parity_flag(struct ecore_hwfn *p_hwfn, struct aeu_invert_reg_bit *p_bit) { return !!(ecore_int_aeu_translate(p_hwfn, p_bit)->flags & ATTENTION_PARITY); } #define ATTN_STATE_BITS (0xfff) #define ATTN_BITS_MASKABLE (0x3ff) struct ecore_sb_attn_info { /* Virtual & Physical address of the SB */ struct atten_status_block *sb_attn; dma_addr_t sb_phys; /* Last seen running index */ u16 index; /* A mask of the AEU bits resulting in a parity error */ u32 parity_mask[NUM_ATTN_REGS]; /* A pointer to the attention description structure */ struct aeu_invert_reg *p_aeu_desc; /* Previously asserted attentions, which are still unasserted */ u16 known_attn; /* Cleanup address for the link's general hw attention */ u32 mfw_attn_addr; }; static u16 ecore_attn_update_idx(struct ecore_hwfn *p_hwfn, struct ecore_sb_attn_info *p_sb_desc) { u16 rc = 0, index; OSAL_MMIOWB(p_hwfn->p_dev); index = OSAL_LE16_TO_CPU(p_sb_desc->sb_attn->sb_index); if (p_sb_desc->index != index) { p_sb_desc->index = index; rc = ECORE_SB_ATT_IDX; } OSAL_MMIOWB(p_hwfn->p_dev); return rc; } /** * @brief ecore_int_assertion - handles asserted attention bits * * @param p_hwfn * @param asserted_bits newly asserted bits * @return enum _ecore_status_t */ static enum _ecore_status_t ecore_int_assertion(struct ecore_hwfn *p_hwfn, u16 asserted_bits) { struct ecore_sb_attn_info *sb_attn_sw = p_hwfn->p_sb_attn; u32 igu_mask; /* Mask the source of the attention in the IGU */ igu_mask = ecore_rd(p_hwfn, p_hwfn->p_dpc_ptt, IGU_REG_ATTENTION_ENABLE); DP_VERBOSE(p_hwfn, ECORE_MSG_INTR, "IGU mask: 0x%08x --> 0x%08x\n", igu_mask, igu_mask & ~(asserted_bits & ATTN_BITS_MASKABLE)); igu_mask &= ~(asserted_bits & ATTN_BITS_MASKABLE); ecore_wr(p_hwfn, p_hwfn->p_dpc_ptt, IGU_REG_ATTENTION_ENABLE, igu_mask); DP_VERBOSE(p_hwfn, ECORE_MSG_INTR, "inner known ATTN state: 0x%04x --> 0x%04x\n", sb_attn_sw->known_attn, sb_attn_sw->known_attn | asserted_bits); sb_attn_sw->known_attn |= asserted_bits; /* Handle MCP events */ if (asserted_bits & 0x100) { ecore_mcp_handle_events(p_hwfn, p_hwfn->p_dpc_ptt); /* Clean the MCP attention */ ecore_wr(p_hwfn, p_hwfn->p_dpc_ptt, sb_attn_sw->mfw_attn_addr, 0); } /* FIXME - this will change once we'll have GOOD gtt definitions */ DIRECT_REG_WR(p_hwfn, (u8 OSAL_IOMEM*)p_hwfn->regview + GTT_BAR0_MAP_REG_IGU_CMD + ((IGU_CMD_ATTN_BIT_SET_UPPER - IGU_CMD_INT_ACK_BASE) << 3), (u32)asserted_bits); DP_VERBOSE(p_hwfn, ECORE_MSG_INTR, "set cmd IGU: 0x%04x\n", asserted_bits); return ECORE_SUCCESS; } static void ecore_int_attn_print(struct ecore_hwfn *p_hwfn, enum block_id id, enum dbg_attn_type type, bool b_clear) { struct dbg_attn_block_result attn_results; enum dbg_status status; OSAL_MEMSET(&attn_results, 0, sizeof(attn_results)); status = ecore_dbg_read_attn(p_hwfn, p_hwfn->p_dpc_ptt, id, type, b_clear, &attn_results); #ifdef ATTN_DESC if (status != DBG_STATUS_OK) DP_NOTICE(p_hwfn, true, "Failed to parse attention information [status: %s]\n", ecore_dbg_get_status_str(status)); else ecore_dbg_parse_attn(p_hwfn, &attn_results); #else if (status != DBG_STATUS_OK) DP_NOTICE(p_hwfn, true, "Failed to parse attention information [status: %d]\n", status); else ecore_dbg_print_attn(p_hwfn, &attn_results); #endif } /** * @brief ecore_int_deassertion_aeu_bit - handles the effects of a single * cause of the attention * * @param p_hwfn * @param p_aeu - descriptor of an AEU bit which caused the attention * @param aeu_en_reg - register offset of the AEU enable reg. which configured * this bit to this group. * @param bit_index - index of this bit in the aeu_en_reg * * @return enum _ecore_status_t */ static enum _ecore_status_t ecore_int_deassertion_aeu_bit(struct ecore_hwfn *p_hwfn, struct aeu_invert_reg_bit *p_aeu, u32 aeu_en_reg, const char *p_bit_name, u32 bitmask) { enum _ecore_status_t rc = ECORE_INVAL; bool b_fatal = false; DP_INFO(p_hwfn, "Deasserted attention `%s'[%08x]\n", p_bit_name, bitmask); /* Call callback before clearing the interrupt status */ if (p_aeu->cb) { DP_INFO(p_hwfn, "`%s (attention)': Calling Callback function\n", p_bit_name); rc = p_aeu->cb(p_hwfn); } if (rc != ECORE_SUCCESS) b_fatal = true; /* Print HW block interrupt registers */ if (p_aeu->block_index != MAX_BLOCK_ID) ecore_int_attn_print(p_hwfn, p_aeu->block_index, ATTN_TYPE_INTERRUPT, !b_fatal); /* Reach assertion if attention is fatal */ if (b_fatal) { DP_NOTICE(p_hwfn, true, "`%s': Fatal attention\n", p_bit_name); ecore_hw_err_notify(p_hwfn, ECORE_HW_ERR_HW_ATTN); } /* Prevent this Attention from being asserted in the future */ if (p_aeu->flags & ATTENTION_CLEAR_ENABLE || p_hwfn->p_dev->attn_clr_en) { u32 val; u32 mask = ~bitmask; val = ecore_rd(p_hwfn, p_hwfn->p_dpc_ptt, aeu_en_reg); ecore_wr(p_hwfn, p_hwfn->p_dpc_ptt, aeu_en_reg, (val & mask)); DP_INFO(p_hwfn, "`%s' - Disabled future attentions\n", p_bit_name); } return rc; } /** * @brief ecore_int_deassertion_parity - handle a single parity AEU source * * @param p_hwfn * @param p_aeu - descriptor of an AEU bit which caused the parity * @param aeu_en_reg - address of the AEU enable register * @param bit_index */ static void ecore_int_deassertion_parity(struct ecore_hwfn *p_hwfn, struct aeu_invert_reg_bit *p_aeu, u32 aeu_en_reg, u8 bit_index) { u32 block_id = p_aeu->block_index, mask, val; DP_NOTICE(p_hwfn->p_dev, false, "%s parity attention is set [address 0x%08x, bit %d]\n", p_aeu->bit_name, aeu_en_reg, bit_index); if (block_id != MAX_BLOCK_ID) { ecore_int_attn_print(p_hwfn, block_id, ATTN_TYPE_PARITY, false); /* In A0, there's a single parity bit for several blocks */ if (block_id == BLOCK_BTB) { ecore_int_attn_print(p_hwfn, BLOCK_OPTE, ATTN_TYPE_PARITY, false); ecore_int_attn_print(p_hwfn, BLOCK_MCP, ATTN_TYPE_PARITY, false); } } /* Prevent this parity error from being re-asserted */ mask = ~(0x1 << bit_index); val = ecore_rd(p_hwfn, p_hwfn->p_dpc_ptt, aeu_en_reg); ecore_wr(p_hwfn, p_hwfn->p_dpc_ptt, aeu_en_reg, val & mask); DP_INFO(p_hwfn, "`%s' - Disabled future parity errors\n", p_aeu->bit_name); } /** * @brief - handles deassertion of previously asserted attentions. * * @param p_hwfn * @param deasserted_bits - newly deasserted bits * @return enum _ecore_status_t * */ static enum _ecore_status_t ecore_int_deassertion(struct ecore_hwfn *p_hwfn, u16 deasserted_bits) { struct ecore_sb_attn_info *sb_attn_sw = p_hwfn->p_sb_attn; u32 aeu_inv_arr[NUM_ATTN_REGS], aeu_mask, aeu_en, en; u8 i, j, k, bit_idx; enum _ecore_status_t rc = ECORE_SUCCESS; /* Read the attention registers in the AEU */ for (i = 0; i < NUM_ATTN_REGS; i++) { aeu_inv_arr[i] = ecore_rd(p_hwfn, p_hwfn->p_dpc_ptt, MISC_REG_AEU_AFTER_INVERT_1_IGU + i * 0x4); DP_VERBOSE(p_hwfn, ECORE_MSG_INTR, "Deasserted bits [%d]: %08x\n", i, aeu_inv_arr[i]); } /* Handle parity attentions first */ for (i = 0; i < NUM_ATTN_REGS; i++) { struct aeu_invert_reg *p_aeu = &sb_attn_sw->p_aeu_desc[i]; u32 parities; aeu_en = MISC_REG_AEU_ENABLE1_IGU_OUT_0 + i * sizeof(u32); en = ecore_rd(p_hwfn, p_hwfn->p_dpc_ptt, aeu_en); parities = sb_attn_sw->parity_mask[i] & aeu_inv_arr[i] & en; /* Skip register in which no parity bit is currently set */ if (!parities) continue; for (j = 0, bit_idx = 0; bit_idx < 32; j++) { struct aeu_invert_reg_bit *p_bit = &p_aeu->bits[j]; if (ecore_int_is_parity_flag(p_hwfn, p_bit) && !!(parities & (1 << bit_idx))) ecore_int_deassertion_parity(p_hwfn, p_bit, aeu_en, bit_idx); bit_idx += ATTENTION_LENGTH(p_bit->flags); } } /* Find non-parity cause for attention and act */ for (k = 0; k < MAX_ATTN_GRPS; k++) { struct aeu_invert_reg_bit *p_aeu; /* Handle only groups whose attention is currently deasserted */ if (!(deasserted_bits & (1 << k))) continue; for (i = 0; i < NUM_ATTN_REGS; i++) { u32 bits; aeu_en = MISC_REG_AEU_ENABLE1_IGU_OUT_0 + i * sizeof(u32) + k * sizeof(u32) * NUM_ATTN_REGS; en = ecore_rd(p_hwfn, p_hwfn->p_dpc_ptt, aeu_en); bits = aeu_inv_arr[i] & en; /* Skip if no bit from this group is currently set */ if (!bits) continue; /* Find all set bits from current register which belong * to current group, making them responsible for the * previous assertion. */ for (j = 0, bit_idx = 0; bit_idx < 32; j++) { long unsigned int bitmask; u8 bit, bit_len; /* Need to account bits with changed meaning */ p_aeu = &sb_attn_sw->p_aeu_desc[i].bits[j]; p_aeu = ecore_int_aeu_translate(p_hwfn, p_aeu); bit = bit_idx; bit_len = ATTENTION_LENGTH(p_aeu->flags); if (ecore_int_is_parity_flag(p_hwfn, p_aeu)) { /* Skip Parity */ bit++; bit_len--; } /* Find the bits relating to HW-block, then * shift so they'll become LSB. */ bitmask = bits & (((1 << bit_len) - 1) << bit); bitmask >>= bit; if (bitmask) { u32 flags = p_aeu->flags; char bit_name[30]; u8 num; num = (u8)OSAL_FIND_FIRST_BIT(&bitmask, bit_len); /* Some bits represent more than a * a single interrupt. Correctly print * their name. */ if (ATTENTION_LENGTH(flags) > 2 || ((flags & ATTENTION_PAR_INT) && ATTENTION_LENGTH(flags) > 1)) OSAL_SNPRINTF(bit_name, 30, p_aeu->bit_name, num); else OSAL_STRNCPY(bit_name, p_aeu->bit_name, 30); /* We now need to pass bitmask in its * correct position. */ bitmask <<= bit; /* Handle source of the attention */ ecore_int_deassertion_aeu_bit(p_hwfn, p_aeu, aeu_en, bit_name, bitmask); } bit_idx += ATTENTION_LENGTH(p_aeu->flags); } } } /* Clear IGU indication for the deasserted bits */ /* FIXME - this will change once we'll have GOOD gtt definitions */ DIRECT_REG_WR(p_hwfn, (u8 OSAL_IOMEM*)p_hwfn->regview + GTT_BAR0_MAP_REG_IGU_CMD + ((IGU_CMD_ATTN_BIT_CLR_UPPER - IGU_CMD_INT_ACK_BASE) << 3), ~((u32)deasserted_bits)); /* Unmask deasserted attentions in IGU */ aeu_mask = ecore_rd(p_hwfn, p_hwfn->p_dpc_ptt, IGU_REG_ATTENTION_ENABLE); aeu_mask |= (deasserted_bits & ATTN_BITS_MASKABLE); ecore_wr(p_hwfn, p_hwfn->p_dpc_ptt, IGU_REG_ATTENTION_ENABLE, aeu_mask); /* Clear deassertion from inner state */ sb_attn_sw->known_attn &= ~deasserted_bits; return rc; } static enum _ecore_status_t ecore_int_attentions(struct ecore_hwfn *p_hwfn) { struct ecore_sb_attn_info *p_sb_attn_sw = p_hwfn->p_sb_attn; struct atten_status_block *p_sb_attn = p_sb_attn_sw->sb_attn; u16 index = 0, asserted_bits, deasserted_bits; u32 attn_bits = 0, attn_acks = 0; enum _ecore_status_t rc = ECORE_SUCCESS; /* Read current attention bits/acks - safeguard against attentions * by guaranting work on a synchronized timeframe */ do { index = OSAL_LE16_TO_CPU(p_sb_attn->sb_index); attn_bits = OSAL_LE32_TO_CPU(p_sb_attn->atten_bits); attn_acks = OSAL_LE32_TO_CPU(p_sb_attn->atten_ack); } while (index != OSAL_LE16_TO_CPU(p_sb_attn->sb_index)); p_sb_attn->sb_index = index; /* Attention / Deassertion are meaningful (and in correct state) * only when they differ and consistent with known state - deassertion * when previous attention & current ack, and assertion when current * attention with no previous attention */ asserted_bits = (attn_bits & ~attn_acks & ATTN_STATE_BITS) & ~p_sb_attn_sw->known_attn; deasserted_bits = (~attn_bits & attn_acks & ATTN_STATE_BITS) & p_sb_attn_sw->known_attn; if ((asserted_bits & ~0x100) || (deasserted_bits & ~0x100)) DP_INFO(p_hwfn, "Attention: Index: 0x%04x, Bits: 0x%08x, Acks: 0x%08x, asserted: 0x%04x, De-asserted 0x%04x [Prev. known: 0x%04x]\n", index, attn_bits, attn_acks, asserted_bits, deasserted_bits, p_sb_attn_sw->known_attn); else if (asserted_bits == 0x100) DP_INFO(p_hwfn, "MFW indication via attention\n"); else DP_VERBOSE(p_hwfn, ECORE_MSG_INTR, "MFW indication [deassertion]\n"); if (asserted_bits) { rc = ecore_int_assertion(p_hwfn, asserted_bits); if (rc) return rc; } if (deasserted_bits) rc = ecore_int_deassertion(p_hwfn, deasserted_bits); return rc; } static void ecore_sb_ack_attn(struct ecore_hwfn *p_hwfn, void OSAL_IOMEM *igu_addr, u32 ack_cons) { struct igu_prod_cons_update igu_ack = { 0 }; igu_ack.sb_id_and_flags = ((ack_cons << IGU_PROD_CONS_UPDATE_SB_INDEX_SHIFT) | (1 << IGU_PROD_CONS_UPDATE_UPDATE_FLAG_SHIFT) | (IGU_INT_NOP << IGU_PROD_CONS_UPDATE_ENABLE_INT_SHIFT) | (IGU_SEG_ACCESS_ATTN << IGU_PROD_CONS_UPDATE_SEGMENT_ACCESS_SHIFT)); DIRECT_REG_WR(p_hwfn, igu_addr, igu_ack.sb_id_and_flags); /* Both segments (interrupts & acks) are written to same place address; * Need to guarantee all commands will be received (in-order) by HW. */ OSAL_MMIOWB(p_hwfn->p_dev); OSAL_BARRIER(p_hwfn->p_dev); } void ecore_int_sp_dpc(osal_int_ptr_t hwfn_cookie) { struct ecore_hwfn *p_hwfn = (struct ecore_hwfn *)hwfn_cookie; struct ecore_pi_info *pi_info = OSAL_NULL; struct ecore_sb_attn_info *sb_attn; struct ecore_sb_info *sb_info; int arr_size; u16 rc = 0; if (!p_hwfn) return; if (!p_hwfn->p_sp_sb) { DP_ERR(p_hwfn->p_dev, "DPC called - no p_sp_sb\n"); return; } sb_info = &p_hwfn->p_sp_sb->sb_info; arr_size = OSAL_ARRAY_SIZE(p_hwfn->p_sp_sb->pi_info_arr); if (!sb_info) { DP_ERR(p_hwfn->p_dev, "Status block is NULL - cannot ack interrupts\n"); return; } if (!p_hwfn->p_sb_attn) { DP_ERR(p_hwfn->p_dev, "DPC called - no p_sb_attn"); return; } sb_attn = p_hwfn->p_sb_attn; DP_VERBOSE(p_hwfn, ECORE_MSG_INTR, "DPC Called! (hwfn %p %d)\n", p_hwfn, p_hwfn->my_id); /* Disable ack for def status block. Required both for msix + * inta in non-mask mode, in inta does no harm. */ ecore_sb_ack(sb_info, IGU_INT_DISABLE, 0); /* Gather Interrupts/Attentions information */ if (!sb_info->sb_virt) { DP_ERR(p_hwfn->p_dev, "Interrupt Status block is NULL - cannot check for new interrupts!\n"); } else { u32 tmp_index = sb_info->sb_ack; rc = ecore_sb_update_sb_idx(sb_info); DP_VERBOSE(p_hwfn->p_dev, ECORE_MSG_INTR, "Interrupt indices: 0x%08x --> 0x%08x\n", tmp_index, sb_info->sb_ack); } if (!sb_attn || !sb_attn->sb_attn) { DP_ERR(p_hwfn->p_dev, "Attentions Status block is NULL - cannot check for new attentions!\n"); } else { u16 tmp_index = sb_attn->index; rc |= ecore_attn_update_idx(p_hwfn, sb_attn); DP_VERBOSE(p_hwfn->p_dev, ECORE_MSG_INTR, "Attention indices: 0x%08x --> 0x%08x\n", tmp_index, sb_attn->index); } /* Check if we expect interrupts at this time. if not just ack them */ if (!(rc & ECORE_SB_EVENT_MASK)) { ecore_sb_ack(sb_info, IGU_INT_ENABLE, 1); return; } /* Check the validity of the DPC ptt. If not ack interrupts and fail */ if (!p_hwfn->p_dpc_ptt) { DP_NOTICE(p_hwfn->p_dev, true, "Failed to allocate PTT\n"); ecore_sb_ack(sb_info, IGU_INT_ENABLE, 1); return; } if (rc & ECORE_SB_ATT_IDX) ecore_int_attentions(p_hwfn); if (rc & ECORE_SB_IDX) { int pi; /* Since we only looked at the SB index, it's possible more * than a single protocol-index on the SB incremented. * Iterate over all configured protocol indices and check * whether something happened for each. */ for (pi = 0; pi < arr_size; pi++) { pi_info = &p_hwfn->p_sp_sb->pi_info_arr[pi]; if (pi_info->comp_cb != OSAL_NULL) pi_info->comp_cb(p_hwfn, pi_info->cookie); } } if (sb_attn && (rc & ECORE_SB_ATT_IDX)) { /* This should be done before the interrupts are enabled, * since otherwise a new attention will be generated. */ ecore_sb_ack_attn(p_hwfn, sb_info->igu_addr, sb_attn->index); } ecore_sb_ack(sb_info, IGU_INT_ENABLE, 1); } static void ecore_int_sb_attn_free(struct ecore_hwfn *p_hwfn) { struct ecore_sb_attn_info *p_sb = p_hwfn->p_sb_attn; if (!p_sb) return; if (p_sb->sb_attn) { OSAL_DMA_FREE_COHERENT(p_hwfn->p_dev, p_sb->sb_attn, p_sb->sb_phys, SB_ATTN_ALIGNED_SIZE(p_hwfn)); } OSAL_FREE(p_hwfn->p_dev, p_sb); p_hwfn->p_sb_attn = OSAL_NULL; } static void ecore_int_sb_attn_setup(struct ecore_hwfn *p_hwfn, struct ecore_ptt *p_ptt) { struct ecore_sb_attn_info *sb_info = p_hwfn->p_sb_attn; OSAL_MEMSET(sb_info->sb_attn, 0, sizeof(*sb_info->sb_attn)); sb_info->index = 0; sb_info->known_attn = 0; /* Configure Attention Status Block in IGU */ ecore_wr(p_hwfn, p_ptt, IGU_REG_ATTN_MSG_ADDR_L, DMA_LO(p_hwfn->p_sb_attn->sb_phys)); ecore_wr(p_hwfn, p_ptt, IGU_REG_ATTN_MSG_ADDR_H, DMA_HI(p_hwfn->p_sb_attn->sb_phys)); } static void ecore_int_sb_attn_init(struct ecore_hwfn *p_hwfn, struct ecore_ptt *p_ptt, void *sb_virt_addr, dma_addr_t sb_phy_addr) { struct ecore_sb_attn_info *sb_info = p_hwfn->p_sb_attn; int i, j, k; sb_info->sb_attn = sb_virt_addr; sb_info->sb_phys = sb_phy_addr; /* Set the pointer to the AEU descriptors */ sb_info->p_aeu_desc = aeu_descs; /* Calculate Parity Masks */ OSAL_MEMSET(sb_info->parity_mask, 0, sizeof(u32) * NUM_ATTN_REGS); for (i = 0; i < NUM_ATTN_REGS; i++) { /* j is array index, k is bit index */ for (j = 0, k = 0; k < 32; j++) { struct aeu_invert_reg_bit *p_aeu; p_aeu = &aeu_descs[i].bits[j]; if (ecore_int_is_parity_flag(p_hwfn, p_aeu)) sb_info->parity_mask[i] |= 1 << k; k += ATTENTION_LENGTH(p_aeu->flags); } DP_VERBOSE(p_hwfn, ECORE_MSG_INTR, "Attn Mask [Reg %d]: 0x%08x\n", i, sb_info->parity_mask[i]); } /* Set the address of cleanup for the mcp attention */ sb_info->mfw_attn_addr = (p_hwfn->rel_pf_id << 3) + MISC_REG_AEU_GENERAL_ATTN_0; ecore_int_sb_attn_setup(p_hwfn, p_ptt); } static enum _ecore_status_t ecore_int_sb_attn_alloc(struct ecore_hwfn *p_hwfn, struct ecore_ptt *p_ptt) { struct ecore_dev *p_dev = p_hwfn->p_dev; struct ecore_sb_attn_info *p_sb; dma_addr_t p_phys = 0; void *p_virt; /* SB struct */ p_sb = OSAL_ALLOC(p_dev, GFP_KERNEL, sizeof(*p_sb)); if (!p_sb) { DP_NOTICE(p_dev, false, "Failed to allocate `struct ecore_sb_attn_info'\n"); return ECORE_NOMEM; } /* SB ring */ p_virt = OSAL_DMA_ALLOC_COHERENT(p_dev, &p_phys, SB_ATTN_ALIGNED_SIZE(p_hwfn)); if (!p_virt) { DP_NOTICE(p_dev, false, "Failed to allocate status block (attentions)\n"); OSAL_FREE(p_dev, p_sb); return ECORE_NOMEM; } /* Attention setup */ p_hwfn->p_sb_attn = p_sb; ecore_int_sb_attn_init(p_hwfn, p_ptt, p_virt, p_phys); return ECORE_SUCCESS; } /* coalescing timeout = timeset << (timer_res + 1) */ #define ECORE_CAU_DEF_RX_USECS 24 #define ECORE_CAU_DEF_TX_USECS 48 void ecore_init_cau_sb_entry(struct ecore_hwfn *p_hwfn, struct cau_sb_entry *p_sb_entry, u8 pf_id, u16 vf_number, u8 vf_valid) { struct ecore_dev *p_dev = p_hwfn->p_dev; u32 cau_state; u8 timer_res; OSAL_MEMSET(p_sb_entry, 0, sizeof(*p_sb_entry)); SET_FIELD(p_sb_entry->params, CAU_SB_ENTRY_PF_NUMBER, pf_id); SET_FIELD(p_sb_entry->params, CAU_SB_ENTRY_VF_NUMBER, vf_number); SET_FIELD(p_sb_entry->params, CAU_SB_ENTRY_VF_VALID, vf_valid); SET_FIELD(p_sb_entry->params, CAU_SB_ENTRY_SB_TIMESET0, 0x7F); SET_FIELD(p_sb_entry->params, CAU_SB_ENTRY_SB_TIMESET1, 0x7F); cau_state = CAU_HC_DISABLE_STATE; if (p_dev->int_coalescing_mode == ECORE_COAL_MODE_ENABLE) { cau_state = CAU_HC_ENABLE_STATE; if (!p_dev->rx_coalesce_usecs) p_dev->rx_coalesce_usecs = ECORE_CAU_DEF_RX_USECS; if (!p_dev->tx_coalesce_usecs) p_dev->tx_coalesce_usecs = ECORE_CAU_DEF_TX_USECS; } /* Coalesce = (timeset << timer-res), timeset is 7bit wide */ if (p_dev->rx_coalesce_usecs <= 0x7F) timer_res = 0; else if (p_dev->rx_coalesce_usecs <= 0xFF) timer_res = 1; else timer_res = 2; SET_FIELD(p_sb_entry->params, CAU_SB_ENTRY_TIMER_RES0, timer_res); if (p_dev->tx_coalesce_usecs <= 0x7F) timer_res = 0; else if (p_dev->tx_coalesce_usecs <= 0xFF) timer_res = 1; else timer_res = 2; SET_FIELD(p_sb_entry->params, CAU_SB_ENTRY_TIMER_RES1, timer_res); SET_FIELD(p_sb_entry->data, CAU_SB_ENTRY_STATE0, cau_state); SET_FIELD(p_sb_entry->data, CAU_SB_ENTRY_STATE1, cau_state); } static void _ecore_int_cau_conf_pi(struct ecore_hwfn *p_hwfn, struct ecore_ptt *p_ptt, u16 igu_sb_id, u32 pi_index, enum ecore_coalescing_fsm coalescing_fsm, u8 timeset) { struct cau_pi_entry pi_entry; u32 sb_offset, pi_offset; if (IS_VF(p_hwfn->p_dev)) return;/* @@@TBD MichalK- VF CAU... */ sb_offset = igu_sb_id * PIS_PER_SB_E4; OSAL_MEMSET(&pi_entry, 0, sizeof(struct cau_pi_entry)); SET_FIELD(pi_entry.prod, CAU_PI_ENTRY_PI_TIMESET, timeset); if (coalescing_fsm == ECORE_COAL_RX_STATE_MACHINE) SET_FIELD(pi_entry.prod, CAU_PI_ENTRY_FSM_SEL, 0); else SET_FIELD(pi_entry.prod, CAU_PI_ENTRY_FSM_SEL, 1); pi_offset = sb_offset + pi_index; if (p_hwfn->hw_init_done) { ecore_wr(p_hwfn, p_ptt, CAU_REG_PI_MEMORY + pi_offset * sizeof(u32), *((u32 *)&(pi_entry))); } else { STORE_RT_REG(p_hwfn, CAU_REG_PI_MEMORY_RT_OFFSET + pi_offset, *((u32 *)&(pi_entry))); } } void ecore_int_cau_conf_pi(struct ecore_hwfn *p_hwfn, struct ecore_ptt *p_ptt, struct ecore_sb_info *p_sb, u32 pi_index, enum ecore_coalescing_fsm coalescing_fsm, u8 timeset) { _ecore_int_cau_conf_pi(p_hwfn, p_ptt, p_sb->igu_sb_id, pi_index, coalescing_fsm, timeset); } void ecore_int_cau_conf_sb(struct ecore_hwfn *p_hwfn, struct ecore_ptt *p_ptt, dma_addr_t sb_phys, u16 igu_sb_id, u16 vf_number, u8 vf_valid) { struct cau_sb_entry sb_entry; ecore_init_cau_sb_entry(p_hwfn, &sb_entry, p_hwfn->rel_pf_id, vf_number, vf_valid); if (p_hwfn->hw_init_done) { /* Wide-bus, initialize via DMAE */ u64 phys_addr = (u64)sb_phys; ecore_dmae_host2grc(p_hwfn, p_ptt, (u64)(osal_uintptr_t)&phys_addr, CAU_REG_SB_ADDR_MEMORY + igu_sb_id * sizeof(u64), 2, OSAL_NULL /* default parameters */); ecore_dmae_host2grc(p_hwfn, p_ptt, (u64)(osal_uintptr_t)&sb_entry, CAU_REG_SB_VAR_MEMORY + igu_sb_id * sizeof(u64), 2, OSAL_NULL /* default parameters */); } else { /* Initialize Status Block Address */ STORE_RT_REG_AGG(p_hwfn, CAU_REG_SB_ADDR_MEMORY_RT_OFFSET+igu_sb_id*2, sb_phys); STORE_RT_REG_AGG(p_hwfn, CAU_REG_SB_VAR_MEMORY_RT_OFFSET+igu_sb_id*2, sb_entry); } /* Configure pi coalescing if set */ if (p_hwfn->p_dev->int_coalescing_mode == ECORE_COAL_MODE_ENABLE) { /* eth will open queues for all tcs, so configure all of them * properly, rather than just the active ones */ u8 num_tc = p_hwfn->hw_info.num_hw_tc; u8 timeset, timer_res; u8 i; /* timeset = (coalesce >> timer-res), timeset is 7bit wide */ if (p_hwfn->p_dev->rx_coalesce_usecs <= 0x7F) timer_res = 0; else if (p_hwfn->p_dev->rx_coalesce_usecs <= 0xFF) timer_res = 1; else timer_res = 2; timeset = (u8)(p_hwfn->p_dev->rx_coalesce_usecs >> timer_res); _ecore_int_cau_conf_pi(p_hwfn, p_ptt, igu_sb_id, RX_PI, ECORE_COAL_RX_STATE_MACHINE, timeset); if (p_hwfn->p_dev->tx_coalesce_usecs <= 0x7F) timer_res = 0; else if (p_hwfn->p_dev->tx_coalesce_usecs <= 0xFF) timer_res = 1; else timer_res = 2; timeset = (u8)(p_hwfn->p_dev->tx_coalesce_usecs >> timer_res); for (i = 0; i < num_tc; i++) { _ecore_int_cau_conf_pi(p_hwfn, p_ptt, igu_sb_id, TX_PI(i), ECORE_COAL_TX_STATE_MACHINE, timeset); } } } void ecore_int_sb_setup(struct ecore_hwfn *p_hwfn, struct ecore_ptt *p_ptt, struct ecore_sb_info *sb_info) { /* zero status block and ack counter */ sb_info->sb_ack = 0; OSAL_MEMSET(sb_info->sb_virt, 0, sizeof(*sb_info->sb_virt)); if (IS_PF(p_hwfn->p_dev)) ecore_int_cau_conf_sb(p_hwfn, p_ptt, sb_info->sb_phys, sb_info->igu_sb_id, 0, 0); } struct ecore_igu_block * ecore_get_igu_free_sb(struct ecore_hwfn *p_hwfn, bool b_is_pf) { struct ecore_igu_block *p_block; u16 igu_id; for (igu_id = 0; igu_id < ECORE_MAPPING_MEMORY_SIZE(p_hwfn->p_dev); igu_id++) { p_block = &p_hwfn->hw_info.p_igu_info->entry[igu_id]; if (!(p_block->status & ECORE_IGU_STATUS_VALID) || !(p_block->status & ECORE_IGU_STATUS_FREE)) continue; if (!!(p_block->status & ECORE_IGU_STATUS_PF) == b_is_pf) return p_block; } return OSAL_NULL; } static u16 ecore_get_pf_igu_sb_id(struct ecore_hwfn *p_hwfn, u16 vector_id) { struct ecore_igu_block *p_block; u16 igu_id; for (igu_id = 0; igu_id < ECORE_MAPPING_MEMORY_SIZE(p_hwfn->p_dev); igu_id++) { p_block = &p_hwfn->hw_info.p_igu_info->entry[igu_id]; if (!(p_block->status & ECORE_IGU_STATUS_VALID) || !p_block->is_pf || p_block->vector_number != vector_id) continue; return igu_id; } return ECORE_SB_INVALID_IDX; } u16 ecore_get_igu_sb_id(struct ecore_hwfn *p_hwfn, u16 sb_id) { u16 igu_sb_id; /* Assuming continuous set of IGU SBs dedicated for given PF */ if (sb_id == ECORE_SP_SB_ID) igu_sb_id = p_hwfn->hw_info.p_igu_info->igu_dsb_id; else if (IS_PF(p_hwfn->p_dev)) igu_sb_id = ecore_get_pf_igu_sb_id(p_hwfn, sb_id + 1); else igu_sb_id = ecore_vf_get_igu_sb_id(p_hwfn, sb_id); if (igu_sb_id == ECORE_SB_INVALID_IDX) DP_NOTICE(p_hwfn, true, "Slowpath SB vector %04x doesn't exist\n", sb_id); else if (sb_id == ECORE_SP_SB_ID) DP_VERBOSE(p_hwfn, ECORE_MSG_INTR, "Slowpath SB index in IGU is 0x%04x\n", igu_sb_id); else DP_VERBOSE(p_hwfn, ECORE_MSG_INTR, "SB [%04x] <--> IGU SB [%04x]\n", sb_id, igu_sb_id); return igu_sb_id; } enum _ecore_status_t ecore_int_sb_init(struct ecore_hwfn *p_hwfn, struct ecore_ptt *p_ptt, struct ecore_sb_info *sb_info, void *sb_virt_addr, dma_addr_t sb_phy_addr, u16 sb_id) { sb_info->sb_virt = sb_virt_addr; sb_info->sb_phys = sb_phy_addr; sb_info->igu_sb_id = ecore_get_igu_sb_id(p_hwfn, sb_id); if (sb_info->igu_sb_id == ECORE_SB_INVALID_IDX) return ECORE_INVAL; /* Let the igu info reference the client's SB info */ if (sb_id != ECORE_SP_SB_ID) { if (IS_PF(p_hwfn->p_dev)) { struct ecore_igu_info *p_info; struct ecore_igu_block *p_block; p_info = p_hwfn->hw_info.p_igu_info; p_block = &p_info->entry[sb_info->igu_sb_id]; p_block->sb_info = sb_info; p_block->status &= ~ECORE_IGU_STATUS_FREE; p_info->usage.free_cnt--; } else { ecore_vf_set_sb_info(p_hwfn, sb_id, sb_info); } } #ifdef ECORE_CONFIG_DIRECT_HWFN sb_info->p_hwfn = p_hwfn; #endif sb_info->p_dev = p_hwfn->p_dev; /* The igu address will hold the absolute address that needs to be * written to for a specific status block */ if (IS_PF(p_hwfn->p_dev)) { sb_info->igu_addr = (u8 OSAL_IOMEM*)p_hwfn->regview + GTT_BAR0_MAP_REG_IGU_CMD + (sb_info->igu_sb_id << 3); } else { sb_info->igu_addr = (u8 OSAL_IOMEM*)p_hwfn->regview + PXP_VF_BAR0_START_IGU + ((IGU_CMD_INT_ACK_BASE + sb_info->igu_sb_id) << 3); } sb_info->flags |= ECORE_SB_INFO_INIT; ecore_int_sb_setup(p_hwfn, p_ptt, sb_info); return ECORE_SUCCESS; } enum _ecore_status_t ecore_int_sb_release(struct ecore_hwfn *p_hwfn, struct ecore_sb_info *sb_info, u16 sb_id) { struct ecore_igu_info *p_info; struct ecore_igu_block *p_block; if (sb_info == OSAL_NULL) return ECORE_SUCCESS; /* zero status block and ack counter */ sb_info->sb_ack = 0; OSAL_MEMSET(sb_info->sb_virt, 0, sizeof(*sb_info->sb_virt)); if (IS_VF(p_hwfn->p_dev)) { ecore_vf_set_sb_info(p_hwfn, sb_id, OSAL_NULL); return ECORE_SUCCESS; } p_info = p_hwfn->hw_info.p_igu_info; p_block = &p_info->entry[sb_info->igu_sb_id]; /* Vector 0 is reserved to Default SB */ if (p_block->vector_number == 0) { DP_ERR(p_hwfn, "Do Not free sp sb using this function"); return ECORE_INVAL; } /* Lose reference to client's SB info, and fix counters */ p_block->sb_info = OSAL_NULL; p_block->status |= ECORE_IGU_STATUS_FREE; p_info->usage.free_cnt++; return ECORE_SUCCESS; } static void ecore_int_sp_sb_free(struct ecore_hwfn *p_hwfn) { struct ecore_sb_sp_info *p_sb = p_hwfn->p_sp_sb; if (!p_sb) return; if (p_sb->sb_info.sb_virt) { OSAL_DMA_FREE_COHERENT(p_hwfn->p_dev, p_sb->sb_info.sb_virt, p_sb->sb_info.sb_phys, SB_ALIGNED_SIZE(p_hwfn)); } OSAL_FREE(p_hwfn->p_dev, p_sb); p_hwfn->p_sp_sb = OSAL_NULL; } static enum _ecore_status_t ecore_int_sp_sb_alloc(struct ecore_hwfn *p_hwfn, struct ecore_ptt *p_ptt) { struct ecore_sb_sp_info *p_sb; dma_addr_t p_phys = 0; void *p_virt; /* SB struct */ p_sb = OSAL_ALLOC(p_hwfn->p_dev, GFP_KERNEL, sizeof(*p_sb)); if (!p_sb) { DP_NOTICE(p_hwfn, false, "Failed to allocate `struct ecore_sb_info'\n"); return ECORE_NOMEM; } /* SB ring */ p_virt = OSAL_DMA_ALLOC_COHERENT(p_hwfn->p_dev, &p_phys, SB_ALIGNED_SIZE(p_hwfn)); if (!p_virt) { DP_NOTICE(p_hwfn, false, "Failed to allocate status block\n"); OSAL_FREE(p_hwfn->p_dev, p_sb); return ECORE_NOMEM; } /* Status Block setup */ p_hwfn->p_sp_sb = p_sb; ecore_int_sb_init(p_hwfn, p_ptt, &p_sb->sb_info, p_virt, p_phys, ECORE_SP_SB_ID); OSAL_MEMSET(p_sb->pi_info_arr, 0, sizeof(p_sb->pi_info_arr)); return ECORE_SUCCESS; } enum _ecore_status_t ecore_int_register_cb(struct ecore_hwfn *p_hwfn, ecore_int_comp_cb_t comp_cb, void *cookie, u8 *sb_idx, __le16 **p_fw_cons) { struct ecore_sb_sp_info *p_sp_sb = p_hwfn->p_sp_sb; enum _ecore_status_t rc = ECORE_NOMEM; u8 pi; /* Look for a free index */ for (pi = 0; pi < OSAL_ARRAY_SIZE(p_sp_sb->pi_info_arr); pi++) { if (p_sp_sb->pi_info_arr[pi].comp_cb != OSAL_NULL) continue; p_sp_sb->pi_info_arr[pi].comp_cb = comp_cb; p_sp_sb->pi_info_arr[pi].cookie = cookie; *sb_idx = pi; *p_fw_cons = &p_sp_sb->sb_info.sb_virt->pi_array[pi]; rc = ECORE_SUCCESS; break; } return rc; } enum _ecore_status_t ecore_int_unregister_cb(struct ecore_hwfn *p_hwfn, u8 pi) { struct ecore_sb_sp_info *p_sp_sb = p_hwfn->p_sp_sb; if (p_sp_sb->pi_info_arr[pi].comp_cb == OSAL_NULL) return ECORE_NOMEM; p_sp_sb->pi_info_arr[pi].comp_cb = OSAL_NULL; p_sp_sb->pi_info_arr[pi].cookie = OSAL_NULL; return ECORE_SUCCESS; } u16 ecore_int_get_sp_sb_id(struct ecore_hwfn *p_hwfn) { return p_hwfn->p_sp_sb->sb_info.igu_sb_id; } void ecore_int_igu_enable_int(struct ecore_hwfn *p_hwfn, struct ecore_ptt *p_ptt, enum ecore_int_mode int_mode) { u32 igu_pf_conf = IGU_PF_CONF_FUNC_EN | IGU_PF_CONF_ATTN_BIT_EN; #ifndef ASIC_ONLY if (CHIP_REV_IS_FPGA(p_hwfn->p_dev)) { DP_INFO(p_hwfn, "FPGA - don't enable ATTN generation in IGU\n"); igu_pf_conf &= ~IGU_PF_CONF_ATTN_BIT_EN; } #endif p_hwfn->p_dev->int_mode = int_mode; switch (p_hwfn->p_dev->int_mode) { case ECORE_INT_MODE_INTA: igu_pf_conf |= IGU_PF_CONF_INT_LINE_EN; igu_pf_conf |= IGU_PF_CONF_SINGLE_ISR_EN; break; case ECORE_INT_MODE_MSI: igu_pf_conf |= IGU_PF_CONF_MSI_MSIX_EN; igu_pf_conf |= IGU_PF_CONF_SINGLE_ISR_EN; break; case ECORE_INT_MODE_MSIX: igu_pf_conf |= IGU_PF_CONF_MSI_MSIX_EN; break; case ECORE_INT_MODE_POLL: break; } ecore_wr(p_hwfn, p_ptt, IGU_REG_PF_CONFIGURATION, igu_pf_conf); } static void ecore_int_igu_enable_attn(struct ecore_hwfn *p_hwfn, struct ecore_ptt *p_ptt) { #ifndef ASIC_ONLY if (CHIP_REV_IS_FPGA(p_hwfn->p_dev)) { DP_INFO(p_hwfn, "FPGA - Don't enable Attentions in IGU and MISC\n"); return; } #endif /* Configure AEU signal change to produce attentions */ ecore_wr(p_hwfn, p_ptt, IGU_REG_ATTENTION_ENABLE, 0); ecore_wr(p_hwfn, p_ptt, IGU_REG_LEADING_EDGE_LATCH, 0xfff); ecore_wr(p_hwfn, p_ptt, IGU_REG_TRAILING_EDGE_LATCH, 0xfff); ecore_wr(p_hwfn, p_ptt, IGU_REG_ATTENTION_ENABLE, 0xfff); /* Flush the writes to IGU */ OSAL_MMIOWB(p_hwfn->p_dev); /* Unmask AEU signals toward IGU */ ecore_wr(p_hwfn, p_ptt, MISC_REG_AEU_MASK_ATTN_IGU, 0xff); } enum _ecore_status_t ecore_int_igu_enable(struct ecore_hwfn *p_hwfn, struct ecore_ptt *p_ptt, enum ecore_int_mode int_mode) { enum _ecore_status_t rc = ECORE_SUCCESS; ecore_int_igu_enable_attn(p_hwfn, p_ptt); if ((int_mode != ECORE_INT_MODE_INTA) || IS_LEAD_HWFN(p_hwfn)) { rc = OSAL_SLOWPATH_IRQ_REQ(p_hwfn); if (rc != ECORE_SUCCESS) { DP_NOTICE(p_hwfn, true, "Slowpath IRQ request failed\n"); return ECORE_NORESOURCES; } p_hwfn->b_int_requested = true; } /* Enable interrupt Generation */ ecore_int_igu_enable_int(p_hwfn, p_ptt, int_mode); p_hwfn->b_int_enabled = 1; return rc; } void ecore_int_igu_disable_int(struct ecore_hwfn *p_hwfn, struct ecore_ptt *p_ptt) { p_hwfn->b_int_enabled = 0; if (IS_VF(p_hwfn->p_dev)) return; ecore_wr(p_hwfn, p_ptt, IGU_REG_PF_CONFIGURATION, 0); } #define IGU_CLEANUP_SLEEP_LENGTH (1000) static void ecore_int_igu_cleanup_sb(struct ecore_hwfn *p_hwfn, struct ecore_ptt *p_ptt, u16 igu_sb_id, bool cleanup_set, u16 opaque_fid) { u32 cmd_ctrl = 0, val = 0, sb_bit = 0, sb_bit_addr = 0, data = 0; u32 pxp_addr = IGU_CMD_INT_ACK_BASE + igu_sb_id; u32 sleep_cnt = IGU_CLEANUP_SLEEP_LENGTH; u8 type = 0; /* FIXME MichalS type??? */ OSAL_BUILD_BUG_ON((IGU_REG_CLEANUP_STATUS_4 - IGU_REG_CLEANUP_STATUS_0) != 0x200); /* USE Control Command Register to perform cleanup. There is an * option to do this using IGU bar, but then it can't be used for VFs. */ /* Set the data field */ SET_FIELD(data, IGU_CLEANUP_CLEANUP_SET, cleanup_set ? 1 : 0); SET_FIELD(data, IGU_CLEANUP_CLEANUP_TYPE, type); SET_FIELD(data, IGU_CLEANUP_COMMAND_TYPE, IGU_COMMAND_TYPE_SET); /* Set the control register */ SET_FIELD(cmd_ctrl, IGU_CTRL_REG_PXP_ADDR, pxp_addr); SET_FIELD(cmd_ctrl, IGU_CTRL_REG_FID, opaque_fid); SET_FIELD(cmd_ctrl, IGU_CTRL_REG_TYPE, IGU_CTRL_CMD_TYPE_WR); ecore_wr(p_hwfn, p_ptt, IGU_REG_COMMAND_REG_32LSB_DATA, data); OSAL_BARRIER(p_hwfn->p_dev); ecore_wr(p_hwfn, p_ptt, IGU_REG_COMMAND_REG_CTRL, cmd_ctrl); /* Flush the write to IGU */ OSAL_MMIOWB(p_hwfn->p_dev); /* calculate where to read the status bit from */ sb_bit = 1 << (igu_sb_id % 32); sb_bit_addr = igu_sb_id / 32 * sizeof(u32); sb_bit_addr += IGU_REG_CLEANUP_STATUS_0 + (0x80 * type); /* Now wait for the command to complete */ while (--sleep_cnt) { val = ecore_rd(p_hwfn, p_ptt, sb_bit_addr); if ((val & sb_bit) == (cleanup_set ? sb_bit : 0)) break; OSAL_MSLEEP(5); } if (!sleep_cnt) DP_NOTICE(p_hwfn, true, "Timeout waiting for clear status 0x%08x [for sb %d]\n", val, igu_sb_id); } void ecore_int_igu_init_pure_rt_single(struct ecore_hwfn *p_hwfn, struct ecore_ptt *p_ptt, u16 igu_sb_id, u16 opaque, bool b_set) { struct ecore_igu_block *p_block; int pi, i; p_block = &p_hwfn->hw_info.p_igu_info->entry[igu_sb_id]; DP_VERBOSE(p_hwfn, ECORE_MSG_INTR, "Cleaning SB [%04x]: func_id= %d is_pf = %d vector_num = 0x%0x\n", igu_sb_id, p_block->function_id, p_block->is_pf, p_block->vector_number); /* Set */ if (b_set) ecore_int_igu_cleanup_sb(p_hwfn, p_ptt, igu_sb_id, 1, opaque); /* Clear */ ecore_int_igu_cleanup_sb(p_hwfn, p_ptt, igu_sb_id, 0, opaque); /* Wait for the IGU SB to cleanup */ for (i = 0; i < IGU_CLEANUP_SLEEP_LENGTH; i++) { u32 val; val = ecore_rd(p_hwfn, p_ptt, IGU_REG_WRITE_DONE_PENDING + ((igu_sb_id / 32) * 4)); if (val & (1 << (igu_sb_id % 32))) OSAL_UDELAY(10); else break; } if (i == IGU_CLEANUP_SLEEP_LENGTH) DP_NOTICE(p_hwfn, true, "Failed SB[0x%08x] still appearing in WRITE_DONE_PENDING\n", igu_sb_id); /* Clear the CAU for the SB */ for (pi = 0; pi < 12; pi++) ecore_wr(p_hwfn, p_ptt, CAU_REG_PI_MEMORY + (igu_sb_id * 12 + pi) * 4, 0); } void ecore_int_igu_init_pure_rt(struct ecore_hwfn *p_hwfn, struct ecore_ptt *p_ptt, bool b_set, bool b_slowpath) { struct ecore_igu_info *p_info = p_hwfn->hw_info.p_igu_info; struct ecore_igu_block *p_block; u16 igu_sb_id = 0; u32 val = 0; /* @@@TBD MichalK temporary... should be moved to init-tool... */ val = ecore_rd(p_hwfn, p_ptt, IGU_REG_BLOCK_CONFIGURATION); val |= IGU_REG_BLOCK_CONFIGURATION_VF_CLEANUP_EN; val &= ~IGU_REG_BLOCK_CONFIGURATION_PXP_TPH_INTERFACE_EN; ecore_wr(p_hwfn, p_ptt, IGU_REG_BLOCK_CONFIGURATION, val); /* end temporary */ for (igu_sb_id = 0; igu_sb_id < ECORE_MAPPING_MEMORY_SIZE(p_hwfn->p_dev); igu_sb_id++) { p_block = &p_info->entry[igu_sb_id]; if (!(p_block->status & ECORE_IGU_STATUS_VALID) || !p_block->is_pf || (p_block->status & ECORE_IGU_STATUS_DSB)) continue; ecore_int_igu_init_pure_rt_single(p_hwfn, p_ptt, igu_sb_id, p_hwfn->hw_info.opaque_fid, b_set); } if (b_slowpath) ecore_int_igu_init_pure_rt_single(p_hwfn, p_ptt, p_info->igu_dsb_id, p_hwfn->hw_info.opaque_fid, b_set); } int ecore_int_igu_reset_cam(struct ecore_hwfn *p_hwfn, struct ecore_ptt *p_ptt) { struct ecore_igu_info *p_info = p_hwfn->hw_info.p_igu_info; struct ecore_igu_block *p_block; int pf_sbs, vf_sbs; u16 igu_sb_id; u32 val, rval; if (!RESC_NUM(p_hwfn, ECORE_SB)) { /* We're using an old MFW - have to prevent any switching * of SBs between PF and VFs as later driver wouldn't be * able to tell which belongs to which. */ p_info->b_allow_pf_vf_change = false; } else { /* Use the numbers the MFW have provided - * don't forget MFW accounts for the default SB as well. */ p_info->b_allow_pf_vf_change = true; if (p_info->usage.cnt != RESC_NUM(p_hwfn, ECORE_SB) - 1) { DP_INFO(p_hwfn, "MFW notifies of 0x%04x PF SBs; IGU indicates of only 0x%04x\n", RESC_NUM(p_hwfn, ECORE_SB) - 1, p_info->usage.cnt); p_info->usage.cnt = RESC_NUM(p_hwfn, ECORE_SB) - 1; } /* TODO - how do we learn about VF SBs from MFW? */ if (IS_PF_SRIOV(p_hwfn)) { u16 vfs = p_hwfn->p_dev->p_iov_info->total_vfs; if (vfs != p_info->usage.iov_cnt) DP_VERBOSE(p_hwfn, ECORE_MSG_INTR, "0x%04x VF SBs in IGU CAM != PCI configuration 0x%04x\n", p_info->usage.iov_cnt, vfs); /* At this point we know how many SBs we have totally * in IGU + number of PF SBs. So we can validate that * we'd have sufficient for VF. */ if (vfs > p_info->usage.free_cnt + p_info->usage.free_cnt_iov - p_info->usage.cnt) { DP_NOTICE(p_hwfn, true, "Not enough SBs for VFs - 0x%04x SBs, from which %04x PFs and %04x are required\n", p_info->usage.free_cnt + p_info->usage.free_cnt_iov, p_info->usage.cnt, vfs); return ECORE_INVAL; } } } /* Cap the number of VFs SBs by the number of VFs */ if (IS_PF_SRIOV(p_hwfn)) p_info->usage.iov_cnt = p_hwfn->p_dev->p_iov_info->total_vfs; /* Mark all SBs as free, now in the right PF/VFs division */ p_info->usage.free_cnt = p_info->usage.cnt; p_info->usage.free_cnt_iov = p_info->usage.iov_cnt; p_info->usage.orig = p_info->usage.cnt; p_info->usage.iov_orig = p_info->usage.iov_cnt; /* We now proceed to re-configure the IGU cam to reflect the initial * configuration. We can start with the Default SB. */ pf_sbs = p_info->usage.cnt; vf_sbs = p_info->usage.iov_cnt; for (igu_sb_id = p_info->igu_dsb_id; igu_sb_id < ECORE_MAPPING_MEMORY_SIZE(p_hwfn->p_dev); igu_sb_id++) { p_block = &p_info->entry[igu_sb_id]; val = 0; if (!(p_block->status & ECORE_IGU_STATUS_VALID)) continue; if (p_block->status & ECORE_IGU_STATUS_DSB) { p_block->function_id = p_hwfn->rel_pf_id; p_block->is_pf = 1; p_block->vector_number = 0; p_block->status = ECORE_IGU_STATUS_VALID | ECORE_IGU_STATUS_PF | ECORE_IGU_STATUS_DSB; } else if (pf_sbs) { pf_sbs--; p_block->function_id = p_hwfn->rel_pf_id; p_block->is_pf = 1; p_block->vector_number = p_info->usage.cnt - pf_sbs; p_block->status = ECORE_IGU_STATUS_VALID | ECORE_IGU_STATUS_PF | ECORE_IGU_STATUS_FREE; } else if (vf_sbs) { p_block->function_id = p_hwfn->p_dev->p_iov_info->first_vf_in_pf + p_info->usage.iov_cnt - vf_sbs; p_block->is_pf = 0; p_block->vector_number = 0; p_block->status = ECORE_IGU_STATUS_VALID | ECORE_IGU_STATUS_FREE; vf_sbs--; } else { p_block->function_id = 0; p_block->is_pf = 0; p_block->vector_number = 0; } SET_FIELD(val, IGU_MAPPING_LINE_FUNCTION_NUMBER, p_block->function_id); SET_FIELD(val, IGU_MAPPING_LINE_PF_VALID, p_block->is_pf); SET_FIELD(val, IGU_MAPPING_LINE_VECTOR_NUMBER, p_block->vector_number); /* VF entries would be enabled when VF is initializaed */ SET_FIELD(val, IGU_MAPPING_LINE_VALID, p_block->is_pf); rval = ecore_rd(p_hwfn, p_ptt, IGU_REG_MAPPING_MEMORY + sizeof(u32) * igu_sb_id); if (rval != val) { ecore_wr(p_hwfn, p_ptt, IGU_REG_MAPPING_MEMORY + sizeof(u32) * igu_sb_id, val); DP_VERBOSE(p_hwfn, ECORE_MSG_INTR, "IGU reset: [SB 0x%04x] func_id = %d is_pf = %d vector_num = 0x%x [%08x -> %08x]\n", igu_sb_id, p_block->function_id, p_block->is_pf, p_block->vector_number, rval, val); } } return 0; } int ecore_int_igu_reset_cam_default(struct ecore_hwfn *p_hwfn, struct ecore_ptt *p_ptt) { struct ecore_sb_cnt_info *p_cnt = &p_hwfn->hw_info.p_igu_info->usage; /* Return all the usage indications to default prior to the reset; * The reset expects the !orig to reflect the initial status of the * SBs, and would re-calculate the originals based on those. */ p_cnt->cnt = p_cnt->orig; p_cnt->free_cnt = p_cnt->orig; p_cnt->iov_cnt = p_cnt->iov_orig; p_cnt->free_cnt_iov = p_cnt->iov_orig; p_cnt->orig = 0; p_cnt->iov_orig = 0; /* TODO - we probably need to re-configure the CAU as well... */ return ecore_int_igu_reset_cam(p_hwfn, p_ptt); } static void ecore_int_igu_read_cam_block(struct ecore_hwfn *p_hwfn, struct ecore_ptt *p_ptt, u16 igu_sb_id) { u32 val = ecore_rd(p_hwfn, p_ptt, IGU_REG_MAPPING_MEMORY + sizeof(u32) * igu_sb_id); struct ecore_igu_block *p_block; p_block = &p_hwfn->hw_info.p_igu_info->entry[igu_sb_id]; /* Fill the block information */ p_block->function_id = GET_FIELD(val, IGU_MAPPING_LINE_FUNCTION_NUMBER); p_block->is_pf = GET_FIELD(val, IGU_MAPPING_LINE_PF_VALID); p_block->vector_number = GET_FIELD(val, IGU_MAPPING_LINE_VECTOR_NUMBER); p_block->igu_sb_id = igu_sb_id; } enum _ecore_status_t ecore_int_igu_read_cam(struct ecore_hwfn *p_hwfn, struct ecore_ptt *p_ptt) { struct ecore_igu_info *p_igu_info; struct ecore_igu_block *p_block; u32 min_vf = 0, max_vf = 0; u16 igu_sb_id; p_hwfn->hw_info.p_igu_info = OSAL_ZALLOC(p_hwfn->p_dev, GFP_KERNEL, sizeof(*p_igu_info)); if (!p_hwfn->hw_info.p_igu_info) return ECORE_NOMEM; p_igu_info = p_hwfn->hw_info.p_igu_info; /* Distinguish between existent and onn-existent default SB */ p_igu_info->igu_dsb_id = ECORE_SB_INVALID_IDX; /* Find the range of VF ids whose SB belong to this PF */ if (p_hwfn->p_dev->p_iov_info) { struct ecore_hw_sriov_info *p_iov = p_hwfn->p_dev->p_iov_info; min_vf = p_iov->first_vf_in_pf; max_vf = p_iov->first_vf_in_pf + p_iov->total_vfs; } for (igu_sb_id = 0; igu_sb_id < ECORE_MAPPING_MEMORY_SIZE(p_hwfn->p_dev); igu_sb_id++) { /* Read current entry; Notice it might not belong to this PF */ ecore_int_igu_read_cam_block(p_hwfn, p_ptt, igu_sb_id); p_block = &p_igu_info->entry[igu_sb_id]; if ((p_block->is_pf) && (p_block->function_id == p_hwfn->rel_pf_id)) { p_block->status = ECORE_IGU_STATUS_PF | ECORE_IGU_STATUS_VALID | ECORE_IGU_STATUS_FREE; if (p_igu_info->igu_dsb_id != ECORE_SB_INVALID_IDX) p_igu_info->usage.cnt++; } else if (!(p_block->is_pf) && (p_block->function_id >= min_vf) && (p_block->function_id < max_vf)) { /* Available for VFs of this PF */ p_block->status = ECORE_IGU_STATUS_VALID | ECORE_IGU_STATUS_FREE; if (p_igu_info->igu_dsb_id != ECORE_SB_INVALID_IDX) p_igu_info->usage.iov_cnt++; } /* Mark the First entry belonging to the PF or its VFs * as the default SB [we'll reset IGU prior to first usage]. */ if ((p_block->status & ECORE_IGU_STATUS_VALID) && (p_igu_info->igu_dsb_id == ECORE_SB_INVALID_IDX)) { p_igu_info->igu_dsb_id = igu_sb_id; p_block->status |= ECORE_IGU_STATUS_DSB; } /* While this isn't suitable for all clients, limit number * of prints by having each PF print only its entries with the * exception of PF0 which would print everything. */ if ((p_block->status & ECORE_IGU_STATUS_VALID) || (p_hwfn->abs_pf_id == 0)) DP_VERBOSE(p_hwfn, ECORE_MSG_INTR, "IGU_BLOCK: [SB 0x%04x] func_id = %d is_pf = %d vector_num = 0x%x\n", igu_sb_id, p_block->function_id, p_block->is_pf, p_block->vector_number); } if (p_igu_info->igu_dsb_id == ECORE_SB_INVALID_IDX) { DP_NOTICE(p_hwfn, true, "IGU CAM returned invalid values igu_dsb_id=0x%x\n", p_igu_info->igu_dsb_id); return ECORE_INVAL; } /* All non default SB are considered free at this point */ p_igu_info->usage.free_cnt = p_igu_info->usage.cnt; p_igu_info->usage.free_cnt_iov = p_igu_info->usage.iov_cnt; DP_VERBOSE(p_hwfn, ECORE_MSG_INTR, "igu_dsb_id=0x%x, num Free SBs - PF: %04x VF: %04x [might change after resource allocation]\n", p_igu_info->igu_dsb_id, p_igu_info->usage.cnt, p_igu_info->usage.iov_cnt); return ECORE_SUCCESS; } enum _ecore_status_t ecore_int_igu_relocate_sb(struct ecore_hwfn *p_hwfn, struct ecore_ptt *p_ptt, u16 sb_id, bool b_to_vf) { struct ecore_igu_info *p_info = p_hwfn->hw_info.p_igu_info; struct ecore_igu_block *p_block = OSAL_NULL; u16 igu_sb_id = 0, vf_num = 0; u32 val = 0; if (IS_VF(p_hwfn->p_dev) || !IS_PF_SRIOV(p_hwfn)) return ECORE_INVAL; if (sb_id == ECORE_SP_SB_ID) return ECORE_INVAL; if (!p_info->b_allow_pf_vf_change) { DP_INFO(p_hwfn, "Can't relocate SBs as MFW is too old.\n"); return ECORE_INVAL; } /* If we're moving a SB from PF to VF, the client had to specify * which vector it wants to move. */ if (b_to_vf) { igu_sb_id = ecore_get_pf_igu_sb_id(p_hwfn, sb_id + 1); if (igu_sb_id == ECORE_SB_INVALID_IDX) return ECORE_INVAL; } /* If we're moving a SB from VF to PF, need to validate there isn't * already a line configured for that vector. */ if (!b_to_vf) { if (ecore_get_pf_igu_sb_id(p_hwfn, sb_id + 1) != ECORE_SB_INVALID_IDX) return ECORE_INVAL; } /* We need to validate that the SB can actually be relocated. * This would also handle the previous case where we've explicitly * stated which IGU SB needs to move. */ for (; igu_sb_id < ECORE_MAPPING_MEMORY_SIZE(p_hwfn->p_dev); igu_sb_id++) { p_block = &p_info->entry[igu_sb_id]; if (!(p_block->status & ECORE_IGU_STATUS_VALID) || !(p_block->status & ECORE_IGU_STATUS_FREE) || (!!(p_block->status & ECORE_IGU_STATUS_PF) != b_to_vf)) { if (b_to_vf) return ECORE_INVAL; else continue; } break; } if (igu_sb_id == ECORE_MAPPING_MEMORY_SIZE(p_hwfn->p_dev)) { DP_VERBOSE(p_hwfn, (ECORE_MSG_INTR | ECORE_MSG_IOV), "Failed to find a free SB to move\n"); return ECORE_INVAL; } if (p_block == OSAL_NULL) { DP_VERBOSE(p_hwfn, (ECORE_MSG_INTR | ECORE_MSG_IOV), "SB address (p_block) is NULL\n"); return ECORE_INVAL; } /* At this point, p_block points to the SB we want to relocate */ if (b_to_vf) { p_block->status &= ~ECORE_IGU_STATUS_PF; /* It doesn't matter which VF number we choose, since we're * going to disable the line; But let's keep it in range. */ vf_num = (u16)p_hwfn->p_dev->p_iov_info->first_vf_in_pf; p_block->function_id = (u8)vf_num; p_block->is_pf = 0; p_block->vector_number = 0; p_info->usage.cnt--; p_info->usage.free_cnt--; p_info->usage.iov_cnt++; p_info->usage.free_cnt_iov++; /* TODO - if SBs aren't really the limiting factor, * then it might not be accurate [in the since that * we might not need decrement the feature]. */ p_hwfn->hw_info.feat_num[ECORE_PF_L2_QUE]--; p_hwfn->hw_info.feat_num[ECORE_VF_L2_QUE]++; } else { p_block->status |= ECORE_IGU_STATUS_PF; p_block->function_id = p_hwfn->rel_pf_id; p_block->is_pf = 1; p_block->vector_number = sb_id + 1; p_info->usage.cnt++; p_info->usage.free_cnt++; p_info->usage.iov_cnt--; p_info->usage.free_cnt_iov--; p_hwfn->hw_info.feat_num[ECORE_PF_L2_QUE]++; p_hwfn->hw_info.feat_num[ECORE_VF_L2_QUE]--; } /* Update the IGU and CAU with the new configuration */ SET_FIELD(val, IGU_MAPPING_LINE_FUNCTION_NUMBER, p_block->function_id); SET_FIELD(val, IGU_MAPPING_LINE_PF_VALID, p_block->is_pf); SET_FIELD(val, IGU_MAPPING_LINE_VALID, p_block->is_pf); SET_FIELD(val, IGU_MAPPING_LINE_VECTOR_NUMBER, p_block->vector_number); ecore_wr(p_hwfn, p_ptt, IGU_REG_MAPPING_MEMORY + sizeof(u32) * igu_sb_id, val); ecore_int_cau_conf_sb(p_hwfn, p_ptt, 0, igu_sb_id, vf_num, p_block->is_pf ? 0 : 1); DP_VERBOSE(p_hwfn, ECORE_MSG_INTR, "Relocation: [SB 0x%04x] func_id = %d is_pf = %d vector_num = 0x%x\n", igu_sb_id, p_block->function_id, p_block->is_pf, p_block->vector_number); return ECORE_SUCCESS; } /** * @brief Initialize igu runtime registers * * @param p_hwfn */ void ecore_int_igu_init_rt(struct ecore_hwfn *p_hwfn) { u32 igu_pf_conf = IGU_PF_CONF_FUNC_EN; STORE_RT_REG(p_hwfn, IGU_REG_PF_CONFIGURATION_RT_OFFSET, igu_pf_conf); } #define LSB_IGU_CMD_ADDR (IGU_REG_SISR_MDPC_WMASK_LSB_UPPER - \ IGU_CMD_INT_ACK_BASE) #define MSB_IGU_CMD_ADDR (IGU_REG_SISR_MDPC_WMASK_MSB_UPPER - \ IGU_CMD_INT_ACK_BASE) u64 ecore_int_igu_read_sisr_reg(struct ecore_hwfn *p_hwfn) { u32 intr_status_hi = 0, intr_status_lo = 0; u64 intr_status = 0; intr_status_lo = REG_RD(p_hwfn, GTT_BAR0_MAP_REG_IGU_CMD + LSB_IGU_CMD_ADDR * 8); intr_status_hi = REG_RD(p_hwfn, GTT_BAR0_MAP_REG_IGU_CMD + MSB_IGU_CMD_ADDR * 8); intr_status = ((u64)intr_status_hi << 32) + (u64)intr_status_lo; return intr_status; } static void ecore_int_sp_dpc_setup(struct ecore_hwfn *p_hwfn) { OSAL_DPC_INIT(p_hwfn->sp_dpc, p_hwfn); p_hwfn->b_sp_dpc_enabled = true; } static enum _ecore_status_t ecore_int_sp_dpc_alloc(struct ecore_hwfn *p_hwfn) { p_hwfn->sp_dpc = OSAL_DPC_ALLOC(p_hwfn); if (!p_hwfn->sp_dpc) return ECORE_NOMEM; return ECORE_SUCCESS; } static void ecore_int_sp_dpc_free(struct ecore_hwfn *p_hwfn) { OSAL_FREE(p_hwfn->p_dev, p_hwfn->sp_dpc); p_hwfn->sp_dpc = OSAL_NULL; } enum _ecore_status_t ecore_int_alloc(struct ecore_hwfn *p_hwfn, struct ecore_ptt *p_ptt) { enum _ecore_status_t rc = ECORE_SUCCESS; rc = ecore_int_sp_dpc_alloc(p_hwfn); if (rc != ECORE_SUCCESS) { DP_ERR(p_hwfn->p_dev, "Failed to allocate sp dpc mem\n"); return rc; } rc = ecore_int_sp_sb_alloc(p_hwfn, p_ptt); if (rc != ECORE_SUCCESS) { DP_ERR(p_hwfn->p_dev, "Failed to allocate sp sb mem\n"); return rc; } rc = ecore_int_sb_attn_alloc(p_hwfn, p_ptt); if (rc != ECORE_SUCCESS) DP_ERR(p_hwfn->p_dev, "Failed to allocate sb attn mem\n"); return rc; } void ecore_int_free(struct ecore_hwfn *p_hwfn) { ecore_int_sp_sb_free(p_hwfn); ecore_int_sb_attn_free(p_hwfn); ecore_int_sp_dpc_free(p_hwfn); } void ecore_int_setup(struct ecore_hwfn *p_hwfn, struct ecore_ptt *p_ptt) { if (!p_hwfn || !p_hwfn->p_sp_sb || !p_hwfn->p_sb_attn) return; ecore_int_sb_setup(p_hwfn, p_ptt, &p_hwfn->p_sp_sb->sb_info); ecore_int_sb_attn_setup(p_hwfn, p_ptt); ecore_int_sp_dpc_setup(p_hwfn); } void ecore_int_get_num_sbs(struct ecore_hwfn *p_hwfn, struct ecore_sb_cnt_info *p_sb_cnt_info) { struct ecore_igu_info *p_igu_info = p_hwfn->hw_info.p_igu_info; if (!p_igu_info || !p_sb_cnt_info) return; OSAL_MEMCPY(p_sb_cnt_info, &p_igu_info->usage, sizeof(*p_sb_cnt_info)); } void ecore_int_disable_post_isr_release(struct ecore_dev *p_dev) { int i; for_each_hwfn(p_dev, i) p_dev->hwfns[i].b_int_requested = false; } void ecore_int_attn_clr_enable(struct ecore_dev *p_dev, bool clr_enable) { p_dev->attn_clr_en = clr_enable; } enum _ecore_status_t ecore_int_set_timer_res(struct ecore_hwfn *p_hwfn, struct ecore_ptt *p_ptt, u8 timer_res, u16 sb_id, bool tx) { struct cau_sb_entry sb_entry; enum _ecore_status_t rc; if (!p_hwfn->hw_init_done) { DP_ERR(p_hwfn, "hardware not initialized yet\n"); return ECORE_INVAL; } rc = ecore_dmae_grc2host(p_hwfn, p_ptt, CAU_REG_SB_VAR_MEMORY + sb_id * sizeof(u64), (u64)(osal_uintptr_t)&sb_entry, 2, OSAL_NULL /* default parameters */); if (rc != ECORE_SUCCESS) { DP_ERR(p_hwfn, "dmae_grc2host failed %d\n", rc); return rc; } if (tx) SET_FIELD(sb_entry.params, CAU_SB_ENTRY_TIMER_RES1, timer_res); else SET_FIELD(sb_entry.params, CAU_SB_ENTRY_TIMER_RES0, timer_res); rc = ecore_dmae_host2grc(p_hwfn, p_ptt, (u64)(osal_uintptr_t)&sb_entry, CAU_REG_SB_VAR_MEMORY + sb_id * sizeof(u64), 2, OSAL_NULL /* default parameters */); if (rc != ECORE_SUCCESS) { DP_ERR(p_hwfn, "dmae_host2grc failed %d\n", rc); return rc; } return rc; } enum _ecore_status_t ecore_int_get_sb_dbg(struct ecore_hwfn *p_hwfn, struct ecore_ptt *p_ptt, struct ecore_sb_info *p_sb, struct ecore_sb_info_dbg *p_info) { u16 sbid = p_sb->igu_sb_id; int i; if (IS_VF(p_hwfn->p_dev)) return ECORE_INVAL; if (sbid > NUM_OF_SBS(p_hwfn->p_dev)) return ECORE_INVAL; p_info->igu_prod = ecore_rd(p_hwfn, p_ptt, IGU_REG_PRODUCER_MEMORY + sbid * 4); p_info->igu_cons = ecore_rd(p_hwfn, p_ptt, IGU_REG_CONSUMER_MEM + sbid * 4); for (i = 0; i < PIS_PER_SB_E4; i++) p_info->pi[i] = (u16)ecore_rd(p_hwfn, p_ptt, CAU_REG_PI_MEMORY + sbid * 4 * PIS_PER_SB_E4 + i * 4); return ECORE_SUCCESS; }
31.188959
182
0.71999
[ "vector" ]
c1ae2d42820e441fb887b75a4481568d96dcaed1
4,637
h
C
src/Test/TestObject.h
ScottMastro/RVS
c9263e8e354c3edefff21aeb2badcdfd91e2ed80
[ "MIT" ]
2
2018-11-13T20:22:20.000Z
2019-06-26T01:26:51.000Z
src/Test/TestObject.h
AngelaQChen/VikNGS
c9263e8e354c3edefff21aeb2badcdfd91e2ed80
[ "MIT" ]
15
2017-11-02T16:27:33.000Z
2018-05-03T20:42:39.000Z
src/Test/TestObject.h
AngelaQChen/VikNGS
c9263e8e354c3edefff21aeb2badcdfd91e2ed80
[ "MIT" ]
2
2019-11-18T17:17:11.000Z
2020-06-26T17:22:13.000Z
#pragma once #include "../vikNGS.h" #include "../Math/Math.h" #include "Group.h" #include "Genotype.h" #include "Phenotype.h" class TestObject { Genotype& geno; Phenotype& pheno; Group& group; VectorXd Ycenter; VectorXd Ycenter_original; VectorXd MU; MatrixXd Xboot; VectorXd Yboot; MatrixXd Zboot; public: TestObject(Genotype& genotype, Phenotype& phenotype, Group& groups, bool rareVariant) : geno(genotype), pheno(phenotype), group(groups) { //Filter NAN VectorXi toRemove = whereNAN(*pheno.getY()); if(!rareVariant) toRemove = toRemove + whereNAN(*geno.getX()); if(pheno.hasCovariates()) toRemove = toRemove + whereNAN(*pheno.getZ()); geno.filterX(toRemove); group.filterG(toRemove); pheno.filterY(toRemove); if(pheno.hasCovariates()) pheno.filterZ(toRemove); Zboot = *pheno.getZ(); Ycenter = pheno.getYCenter(); //Replace NAN with 0 if rare if(rareVariant) geno.replaceNA(0); bootstrapped = false; groupVectorCache = false; XcenterCache = false; } inline VectorXd robustVarVector(){ return geno.robustVarVector(); } inline VectorXd mafWeightVector(){ return geno.mafWeightVector(); } inline MatrixXd* getX(){ return (bootstrapped) ? &Xboot : geno.getX(); } inline VectorXd* getY(){ return (bootstrapped) ? &Yboot : pheno.getY(); } inline MatrixXd* getZ(){ return (bootstrapped) ? &Zboot : pheno.getZ(); } inline Group* getGroup(){ return &group; } inline VectorXd* getMU(){ return pheno.getMu(); } inline VectorXd* getYcenter(){ return &Ycenter; } inline void bootstrap(TestSettings& test, Family family) { if(test.isExpectedGenotypes()){ calculateXcenter(); calculateGroupVector(); if(family == Family::NORMAL) normalBootstrap(); if(family == Family::BINOMIAL) binomialBootstrap(); } else permute(); bootstrapped = true; calculateYCenterBoot(); } //bootstrap functions private: bool bootstrapped; inline void permute() { if(!bootstrapped) Xboot = *geno.getX(); Yboot = shuffleWithoutReplacement(*pheno.getY()); //Xboot = shuffleColumnwiseWithoutReplacement(*geno.getX()); if(pheno.hasCovariates()) Zboot = shuffleColumnwiseWithoutReplacement(*pheno.getZ()); } void binomialBootstrap() { if(!bootstrapped) Yboot = *pheno.getY(); Xboot = groupwiseShuffleWithReplacement(Xcenter, *group.getG(), groupVector); //todo? if(pheno.hasCovariates()) Zboot = groupwiseShuffleWithReplacement(*pheno.getZ(), *group.getG(), groupVector); } void normalBootstrap() { if(pheno.hasCovariates()){ if(!bootstrapped){ Xboot = *geno.getX(); Zboot = *pheno.getZ(); Ycenter_original = Ycenter; } VectorXd residuals = groupwiseShuffleWithoutReplacement(Ycenter_original, *group.getG(), groupVector); Yboot = *pheno.getY() - Ycenter_original + residuals; } else{ Yboot = groupwiseShuffleWithoutReplacement(*pheno.getY(), *group.getG(), groupVector); if(!bootstrapped) Xboot = *geno.getX(); } } bool groupVectorCache; std::map<int, std::vector<int>> groupVector; inline void calculateGroupVector() { if(groupVectorCache) return; for(int i = 0; i < group.size(); i++){ if(groupVector.count(group[i]) < 1){ std::vector<int> v; v.push_back(i); groupVector[group[i]] = v; } else groupVector[group[i]].push_back(i); } groupVectorCache = true; } bool XcenterCache; MatrixXd Xcenter; inline void calculateXcenter() { if(XcenterCache) return; Xcenter = subtractGroupMean(*geno.getX(), *group.getG()); XcenterCache = true; } inline void calculateYCenterBoot() { if(pheno.hasCovariates()){ VectorXd beta = getBeta(Yboot, Zboot, pheno.getFamily()); this->MU = fitModel(beta, Zboot, pheno.getFamily()); } else{ double ybar = Yboot.mean(); this->MU = VectorXd::Constant(Yboot.rows(), ybar); } Ycenter = Yboot - MU; } };
25.064865
113
0.572137
[ "vector" ]
c1aebdfe6838dca8c5bd8414f57305781c9bead1
4,525
c
C
src/render/ui_stars.c
RAttab/legion
79c1d6dd76db31c8d765fefd034df911dc414e83
[ "BSD-2-Clause", "MIT" ]
4
2021-09-09T16:54:38.000Z
2021-12-01T20:21:19.000Z
src/render/ui_stars.c
RAttab/legion
79c1d6dd76db31c8d765fefd034df911dc414e83
[ "BSD-2-Clause", "MIT" ]
null
null
null
src/render/ui_stars.c
RAttab/legion
79c1d6dd76db31c8d765fefd034df911dc414e83
[ "BSD-2-Clause", "MIT" ]
null
null
null
/* ui_stars.c Rémi Attab (remi.attab@gmail.com), 16 Sep 2021 FreeBSD-style copyright and disclaimer apply */ #include "common.h" #include "render/ui.h" #include "ui/ui.h" // ----------------------------------------------------------------------------- // stars // ----------------------------------------------------------------------------- struct ui_stars { struct ui_panel panel; struct ui_tree tree; }; static struct font *ui_stars_font(void) { return font_mono6; } struct ui_stars *ui_stars_new(void) { struct font *font = ui_stars_font(); struct pos pos = make_pos(0, ui_topbar_height()); struct dim dim = make_dim( (symbol_cap + 4) * font->glyph_w, core.rect.h - pos.y - ui_status_height()); struct ui_stars *ui = calloc(1, sizeof(*ui)); *ui = (struct ui_stars) { .panel = ui_panel_title(pos, dim, ui_str_v(16)), .tree = ui_tree_new( make_dim(ui_layout_inf, ui_layout_inf), font, ui_str_v(symbol_cap)), }; ui_panel_hide(&ui->panel); return ui; } void ui_stars_free(struct ui_stars *ui) { ui_panel_free(&ui->panel); ui_tree_free(&ui->tree); free(ui); } static void ui_stars_update(struct ui_stars *ui) { ui_tree_reset(&ui->tree); ui_node_t parent = ui_node_nil; struct coord sector = coord_nil(); const struct vec64 *list = proxy_chunks(core.proxy); size_t count = 0; for (size_t i = 0; i < list->len; ++i) { struct coord star = coord_from_u64(list->vals[i]); if (!coord_eq(coord_sector(star), sector)) { sector = coord_sector(star); parent = ui_tree_index(&ui->tree); ui_str_setf(ui_tree_add(&ui->tree, ui_node_nil, coord_to_u64(sector)), "%02x.%02x x %02x.%02x", (sector.x >> (coord_sector_bits + coord_area_bits)), (sector.x >> coord_sector_bits) & 0xFF, (sector.y >> (coord_sector_bits + coord_area_bits)), (sector.y >> coord_sector_bits) & 0xFF); } ui_str_set_atom( ui_tree_add(&ui->tree, parent, coord_to_u64(star)), proxy_star_name(core.proxy, star)); count++; } ui_str_setf(&ui->panel.title.str, "stars (%zu)", count); } static bool ui_stars_event_user(struct ui_stars *ui, SDL_Event *ev) { switch (ev->user.code) { case EV_STATE_LOAD: { ui_stars_update(ui); ui_panel_show(&ui->panel); return false; } case EV_STATE_UPDATE: { if (!ui_panel_is_visible(&ui->panel)) return false; ui_stars_update(ui); return false; } case EV_STARS_TOGGLE: { if (ui_panel_is_visible(&ui->panel)) ui_panel_hide(&ui->panel); else { ui_stars_update(ui); ui_panel_show(&ui->panel); } return false; } case EV_STAR_SELECT: { struct coord coord = coord_from_u64((uintptr_t) ev->user.data1); ui_tree_select(&ui->tree, coord_to_u64(coord)); return false; } case EV_STAR_CLEAR: { ui_tree_clear(&ui->tree); return false; } case EV_TAPES_TOGGLE: case EV_TAPE_SELECT: case EV_MODS_TOGGLE: case EV_MOD_SELECT: case EV_LOG_TOGGLE: case EV_LOG_SELECT: { ui_panel_hide(&ui->panel); return false; } default: { return false; } } } bool ui_stars_event(struct ui_stars *ui, SDL_Event *ev) { if (ev->type == core.event && ui_stars_event_user(ui, ev)) return true; enum ui_ret ret = ui_nil; if ((ret = ui_panel_event(&ui->panel, ev))) return ret != ui_skip; if ((ret = ui_tree_event(&ui->tree, ev))) { if (ret != ui_action) return true; uint64_t user = ui->tree.selected; struct coord coord = coord_from_u64(user); if (user && !coord_eq(coord, coord_sector(coord))) { core_push_event(EV_STAR_SELECT, user, 0); if (map_active(core.ui.map)) core_push_event(EV_MAP_GOTO, user, 0); if (factory_active(core.ui.factory)) core_push_event(EV_FACTORY_SELECT, user, 0); } return true; } return ui_panel_event_consume(&ui->panel, ev); } void ui_stars_render(struct ui_stars *ui, SDL_Renderer *renderer) { struct ui_layout layout = ui_panel_render(&ui->panel, renderer); if (ui_layout_is_nil(&layout)) return; ui_tree_render(&ui->tree, &layout, renderer); }
27.424242
82
0.578122
[ "render" ]
c1b0b59f37c743448b379782850ca264e3237f1a
4,629
h
C
src/RcsCore/Rcs_utilsCPP.h
famura/Rcs
4f8b997d2649a2cd7a1945ea079e07a71ee215fc
[ "BSD-3-Clause" ]
37
2018-03-20T12:28:45.000Z
2022-02-28T08:39:32.000Z
src/RcsCore/Rcs_utilsCPP.h
famura/Rcs
4f8b997d2649a2cd7a1945ea079e07a71ee215fc
[ "BSD-3-Clause" ]
19
2018-04-19T08:49:53.000Z
2021-06-11T09:47:09.000Z
src/RcsCore/Rcs_utilsCPP.h
famura/Rcs
4f8b997d2649a2cd7a1945ea079e07a71ee215fc
[ "BSD-3-Clause" ]
15
2018-03-28T11:52:39.000Z
2022-02-04T19:34:01.000Z
/******************************************************************************* Copyright (c) 2017, Honda Research Institute Europe GmbH 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. Neither the name of the copyright holder 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. *******************************************************************************/ #ifndef RCS_UTILSCPP_H #define RCS_UTILSCPP_H #include <string> #include <vector> #include <list> #include <utility> #include <cstdarg> /*! \ingroup RcsUtilsFunctions * \brief Returns a list of string containing all file names of given directory * that end with a given extension. If returnFullPath is true (default) * then the full path including the provided directory name is returned */ std::list<std::string> getFilenamesInDirectory(const std::string& dirname, bool returnFullPath=true, const std::string& extension=""); /*! \ingroup RcsUtilsFunctions * \brief Returns the path and the filename of the currently executed binary * \param argv The argument list coming from the main() * \return A pair holding the path and the filename of the currently executed * binary */ std::pair<std::string, std::string> Rcs_getExecutablePathAndFilename(char* argv[]); /*! \ingroup RcsUtilsFunctions * \brief Method for formatting a std::string in the fprintf style * \param fmt Format string + variable arguments * \return String generated from format + arguments * * This function uses formatStdString(const char *fmt, va_list ap) */ std::string formatStdString(const char* fmt, ...); /*! \ingroup RcsUtilsFunctions * \brief Method for formatting a std::string in the fprintf style * \param fmt Format string * \param ap Variable argument list already started with va_start * \return String generated from format + arguments * * Note that call va_end is the responsibility of the user. */ std::string formatStdString(const char* fmt, va_list ap); /*! \ingroup RcsUtilsFunctions * \brief Checks if two files are equal. Thir binary content is compared. * \param file1 Filename 1 * \param file2 Filename 2 * \return True if files are equal */ bool File_isEqualCpp(const char* file1, const char* file2); /*! \ingroup RcsUtilsFunctions * \brief Splits the given string into pieces that are separated by the given * delimiter. * * \param stringToBeSplitted The string that is to be splitted. * \param delimiter Pattern that spearates the sub-strings * \return Vector of sub-strings without delimiter. */ std::vector<std::string> String_split(const std::string& stringToBeSplitted, const std::string& delimiter); /*! \ingroup RcsUtilsFunctions * \brief Checks if a given string ends with another string. Basically for * checking if a file has a given extension */ bool String_hasEnding(const std::string& fullString, const std::string& ending); /*! \ingroup RcsUtilsFunctions * \brief Checks if a given string starts with another string. */ bool String_startsWith(const std::string& fullString, const std::string& beginning); #endif // RCS_UTILSCPP_H
40.605263
83
0.701447
[ "vector" ]
c1b589e6bb14fa5d14a3edb5b2214142b143cdb3
9,447
c
C
alcs/src/dlcp_impl.c
iot-middleware/link-alcs
3008b8705d8f8445bfab4b7508aebe74e838c92c
[ "Apache-2.0" ]
null
null
null
alcs/src/dlcp_impl.c
iot-middleware/link-alcs
3008b8705d8f8445bfab4b7508aebe74e838c92c
[ "Apache-2.0" ]
null
null
null
alcs/src/dlcp_impl.c
iot-middleware/link-alcs
3008b8705d8f8445bfab4b7508aebe74e838c92c
[ "Apache-2.0" ]
null
null
null
#include <time.h> #include "alcs_api.h" #include "alcs_coap.h" #include "utils_hmac.h" #include "alcs_export_st.h" #include "alcs_export_st_ali.h" #include "linked_list.h" #include "CoAPPlatform.h" #include "json_parser.h" #include "alcs_export_dlcp.h" #include "alcs_export.h" #include "alcs_export_server.h" const char* KEY_AC = "key_authcode"; const char* KEY_AS = "key_authsecret"; char* DEFAULT_AC = "Xtau@iot"; char* DEFAULT_AS = "Yx3DdsyetbSezlvc"; static dlcp_receiver receiver_func = NULL; void dlcp_set_receiver (dlcp_receiver receiver) { receiver_func = receiver; } void alcs_service_cb_dev (alcs_service_cb_param_pt cb_param) { alcs_rsp_msg_param_t rsp_msg; alcs_rsp_msg_param_option_t option; char pk[PRODUCT_KEY_MAXLEN]; char dn[DEVICE_ID_MAXLEN]; char payload[200]; char ip_addr[24]; char* id; int idlen; COAP_DEBUG ("alcs_service_cb_dev"); if (!cb_param || !cb_param->payload || !cb_param->payload_len) { COAP_ERR ("alcs_service_cb_dev, invalid params"); HAL_Snprintf (payload, sizeof(payload), "{\"code\":400,\"msg\":\"Payload is empty\"}"); } else{ id = alcs_json_get_value_by_name((char*)cb_param->payload, cb_param->payload_len, "id", &idlen, (int*)NULL); HAL_GetProductModel(pk); HAL_GetDeviceID(dn); HAL_Wifi_Get_IP (ip_addr, NULL); HAL_Snprintf(payload, sizeof(payload), "{\"id\":\"%.*s\",\"version\":\"1.0\", \"code\":200,\"data\":{\"deviceModel\":{\"profile\":{\"pal\":\"dlcp-raw\",\"productKey\":\"%s\",\"deviceName\":\"%s\",\"addr\":\"%s\",\"port\":5683}}}}", idlen, id? id : "", pk, dn, ip_addr); } option.msg_code = ALCS_MSG_CODE_205_CONTENT; option.msg_type = ALCS_MSG_TYPE_CON; rsp_msg.payload = (unsigned char*)payload; rsp_msg.payload_len = strlen(payload); rsp_msg.msg_option = &option; iot_alcs_send_rsp(&rsp_msg, cb_param? cb_param->cb_ctx : NULL); } void alcs_service_cb_setup (alcs_service_cb_param_pt cb_param) { alcs_rsp_msg_param_t rsp_msg; alcs_rsp_msg_param_option_t option; char payload[128]; char* id = NULL, *p; int idlen = 0, len, authcodelen, authsecretlen; char* authcode = NULL, *authsecret = NULL; bool success = 0; char* err_msg = NULL; char ac[9]; char configValueBack; char *str_pos, *entry; int entry_len, type; alcs_svr_auth_param_t auth_param; COAP_DEBUG ("alcs_service_cb_setup"); do { if (!cb_param || !cb_param->payload || !cb_param->payload_len) { err_msg = "invalid package"; break; } id = alcs_json_get_value_by_name((char*)cb_param->payload, cb_param->payload_len, "id", &idlen, (int*)NULL); p = alcs_json_get_value_by_name((char*)cb_param->payload, cb_param->payload_len, "params", &len, (int*)NULL); if (!p || !len) { err_msg = "params is not found"; break; } p = alcs_json_get_value_by_name(p, len, "configValue", &len, (int*)NULL); if (!p || !len) { err_msg = "configValue is not found"; break; } backup_json_str_last_char (p, len, configValueBack); json_array_for_each_entry(p, len, str_pos, entry, entry_len, type) { COAP_DEBUG ("entry:%.*s", entry_len, entry); authcode = alcs_json_get_value_by_name(entry, entry_len, "authCode", &authcodelen, (int*)NULL); authsecret = alcs_json_get_value_by_name(entry, entry_len, "authSecret", &authsecretlen, (int*)NULL); break; } //end json_array_for_each_entry restore_json_str_last_char (p, len, configValueBack); if (!authcode || !authcodelen || !authsecret || !authsecretlen) { err_msg = "authinfo is not found"; break; } //save memset (&auth_param, 0, sizeof(alcs_svr_auth_param_t)); len = sizeof(ac); if (!HAL_Kv_Get (KEY_AC, ac, &len)) { auth_param.ac = DEFAULT_AC; auth_param.ac_len = strlen(auth_param.ac); } else { auth_param.ac = ac; auth_param.ac_len = len; } iot_alcs_remove_authkey (&auth_param); auth_param.ac = authcode; auth_param.as = authsecret; auth_param.ac_len = authcodelen; auth_param.as_len = authsecretlen; iot_alcs_add_and_update_authkey(&auth_param); COAP_DEBUG ("new ac:%.*s, as:%.*s", auth_param.ac_len, auth_param.ac, auth_param.as_len, auth_param.as); HAL_Kv_Set (KEY_AC, auth_param.ac, auth_param.ac_len); HAL_Kv_Set (KEY_AS, auth_param.as, auth_param.as_len); success = 1; } while (0); if (success) { HAL_Snprintf(payload, sizeof(payload), "{\"id\":\"%.*s\",\"code\":200}", idlen, id? id : ""); } else { HAL_Snprintf(payload, sizeof(payload), "{\"id\":\"%.*s\",\"code\":400,\"msg\":\"%s\"}", idlen, id? id : "", err_msg); COAP_ERR ("alcs_service_cb_setup, %s", err_msg); } option.msg_code = ALCS_MSG_CODE_205_CONTENT; option.msg_type = ALCS_MSG_TYPE_CON; rsp_msg.payload = (uint8_t*)payload; rsp_msg.payload_len = strlen(payload); rsp_msg.msg_option = &option; iot_alcs_send_rsp(&rsp_msg, cb_param? cb_param->cb_ctx : NULL); } void alcs_service_cb_up (alcs_service_cb_param_pt cb_param) { char* id = NULL; int idlen = 0; alcs_rsp_msg_param_t rsp_msg; alcs_rsp_msg_param_option_t option; char payload[64]; if (!cb_param) { return; } if (cb_param->payload && cb_param->payload_len) { id = alcs_json_get_value_by_name((char*)cb_param->payload, cb_param->payload_len, "id", &idlen, (int*)NULL); } HAL_Snprintf(payload, sizeof(payload), "{\"id\":\"%.*s\",\"code\":200}", idlen, id? id : ""); option.msg_code = ALCS_MSG_CODE_205_CONTENT; option.msg_type = ALCS_MSG_TYPE_CON; rsp_msg.payload = (uint8_t*)payload; rsp_msg.payload_len = strlen(payload); rsp_msg.msg_option = &option; iot_alcs_send_rsp(&rsp_msg, cb_param->cb_ctx); } void alcs_service_cb_down (alcs_service_cb_param_pt cb_param) { if (!cb_param|| !receiver_func) { return; } receiver_func ((char*)cb_param->payload, cb_param->payload_len, cb_param->cb_ctx); } int dlcp_init (void) { char pk[PRODUCT_KEY_MAXLEN]; char dn[DEVICE_ID_MAXLEN]; char buf1[120]; char buf2[9]; int rt, len1, len2; alcs_svr_auth_param_t auth_param; alcs_service_param_t service; if (HAL_GetProductModel(pk) <= 0 || HAL_GetDeviceID(dn) <= 0) { return DLCP_PKDNEMPTY; } if (iot_alcs_init (pk, dn, ALCS_ROLE_SERVER) != ALCS_RESULT_OK) { return DLCP_FAIL; } service.service = "/dev/core/service/dev"; service.pk = pk; service.dn = dn; service.perm = ALCS_MSG_PERM_GET; service.content_type = ALCS_MSG_CT_APP_JSON; service.maxage = 60; service.user_data = NULL; service.secure = 0; rt = iot_alcs_register_service (&service, alcs_service_cb_dev); HAL_Snprintf(buf1, sizeof(buf1), "/dev/%s/%s/core/service/setup", pk, dn); service.service = buf1; service.perm = ALCS_MSG_PERM_PUT; service.secure = 1; rt = iot_alcs_register_service (&service, alcs_service_cb_setup); HAL_Snprintf(buf1, sizeof(buf1), "/sys/%s/%s/thing/model/down_raw", pk, dn); service.service = buf1; service.perm = ALCS_MSG_PERM_PUT | ALCS_MSG_PERM_GET; rt = iot_alcs_register_service (&service, alcs_service_cb_down); HAL_Snprintf(buf1, sizeof(buf1), "/sys/%s/%s/thing/model/up_raw", pk, dn); service.perm = ALCS_MSG_PERM_GET; service.service = buf1; rt = iot_alcs_register_service (&service, alcs_service_cb_up); memset (&auth_param, 0, sizeof(alcs_svr_auth_param_t)); len1 = 120; len2 = 9; if (HAL_Kv_Get (KEY_AC, buf2, &len2) >= 0 && HAL_Kv_Get (KEY_AS, buf1, &len1) >= 0) { auth_param.ac = buf2; auth_param.ac_len = len2; auth_param.as = buf1; auth_param.as_len = len1; } else { auth_param.ac = DEFAULT_AC; auth_param.ac_len = strlen(auth_param.ac); auth_param.as = DEFAULT_AS; auth_param.as_len = strlen(auth_param.as); } COAP_DEBUG ("use ac:%s, as:%s", auth_param.ac, auth_param.as); iot_alcs_add_and_update_authkey(&auth_param); return rt; } void dlcp_deinit(void) { iot_alcs_deinit (); } int dlcp_sendrsp (const char* data, int len, void* ctx) { alcs_rsp_msg_param_t rsp_msg; alcs_rsp_msg_param_option_t option; rsp_msg.payload = (uint8_t*)data; rsp_msg.payload_len = len; option.msg_code = ALCS_MSG_CODE_205_CONTENT; option.msg_type = ALCS_MSG_TYPE_CON; rsp_msg.msg_option = &option; return iot_alcs_send_rsp (&rsp_msg, ctx); } void dlcp_start_loop () { iot_alcs_start_loop (1); } void dlcp_stop_loop () { iot_alcs_stop_loop (); } int dlcp_upload (const char* data, int len) { char pk[PRODUCT_KEY_MAXLEN]; char dn[DEVICE_ID_MAXLEN]; char method[120]; alcs_notify_param_t notice; if (HAL_GetProductModel(pk) <= 0 || HAL_GetDeviceID(dn) <= 0) { return DLCP_PKDNEMPTY; } HAL_Snprintf(method, sizeof(method), "/sys/%s/%s/thing/model/up_raw", pk, dn); notice.payload = (uint8_t*)data; notice.payload_len = len; notice.option = method; return iot_alcs_send_notify (&notice); }
31.701342
277
0.646131
[ "model" ]
c1b92775203e0d5d9177963d30ca7d987b7f72dd
4,910
c
C
src/renderer/window.c
thynnmas/slenderer
9f9fa9eed6c3c287ceed412031c4a13def5d0c63
[ "MIT" ]
null
null
null
src/renderer/window.c
thynnmas/slenderer
9f9fa9eed6c3c287ceed412031c4a13def5d0c63
[ "MIT" ]
null
null
null
src/renderer/window.c
thynnmas/slenderer
9f9fa9eed6c3c287ceed412031c4a13def5d0c63
[ "MIT" ]
null
null
null
/* * Slenderer - Thomas Martin Schmid, 2014. Public domain¹ * * ¹ If public domain is not legally valid in your legal jurisdiction * the MIT licence applies (see the LICENCE file) * * 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 "renderer/window.h" #include "slenderer.h" void sl_window_create( sl_window* win, unsigned int width, unsigned int height, const char *title, int fullscreen, int vsync, sl_window *context_share ) { win->handle = glfwCreateWindow( width, height, title, fullscreen ? glfwGetPrimaryMonitor( ) : NULL, /* <-- @TODO: Multimonitor support */ context_share == NULL ? NULL : context_share->handle ); if ( !win->handle ) { assert( SL_FALSE ); //Failed to create a GLFW window return; } if ( !fullscreen ) { // If window, make it non-resizable glfwWindowHint( GLFW_RESIZABLE, GL_FALSE ); } if( !vsync ) { // If no VSYNC, turn it off. glfwMakeContextCurrent( win->handle ); glfwSwapInterval( 0 ); } glfwSetWindowSizeCallback( win->handle, sl_window_size_callback ); } void sl_window_create_fbo( sl_window *win, unsigned int width, unsigned int height ) { GLenum status; /* Create the framebufferobject we render to before post */ glActiveTexture( GL_TEXTURE0 ); glGenTextures( 1, &win->fbo_texture ); glBindTexture( GL_TEXTURE_2D, win->fbo_texture ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE ); glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL ); glBindTexture( GL_TEXTURE_2D, 0 ); /* Depth buffer */ glGenRenderbuffers( 1, &win->rbo_depth ); glBindRenderbuffer( GL_RENDERBUFFER, win->rbo_depth ); glRenderbufferStorage( GL_RENDERBUFFER, GL_DEPTH_COMPONENT16, width, height ); glBindRenderbuffer( GL_RENDERBUFFER, 0 ); /* Link them */ glGenFramebuffers( 1, &win->fbo ); glBindFramebuffer( GL_FRAMEBUFFER, win->fbo ); glFramebufferTexture2D( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, win->fbo_texture, 0 ); glFramebufferRenderbuffer( GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, win->rbo_depth ); assert( ( status = glCheckFramebufferStatus( GL_FRAMEBUFFER ) ) == GL_FRAMEBUFFER_COMPLETE ); glBindFramebuffer( GL_FRAMEBUFFER, 0 ); } void sl_window_destroy_fbo( sl_window *win ) { glDeleteRenderbuffers( 1, &win->rbo_depth ); glDeleteTextures( 1, &win->fbo_texture); glDeleteFramebuffers( 1, &win->fbo ); } void sl_window_destroy( sl_window* win ) { #ifndef SL_LEGACY_OPENGL sl_window_destroy_fbo( win ); #endif glfwDestroyWindow( win->handle ); } void sl_window_bind_framebuffer_fbo( sl_window* win ) { int w, h; // Make the context current glfwMakeContextCurrent( win->handle ); // Set up viewport glfwGetFramebufferSize( win->handle, &w, &h ); glViewport( 0, 0, w, h ); // Select the FBO glBindFramebuffer( GL_FRAMEBUFFER, win->fbo ); // Clear the famebuffer glClearColor( 0.f, 0.f, 0.f, 1.f ); glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); } void sl_window_bind_framebuffer_post( sl_window* win ) { int w, h; // Make the context current glfwMakeContextCurrent( win->handle ); // Set up viewport glfwGetFramebufferSize( win->handle, &w, &h ); glViewport( 0, 0, w, h ); // Select the Window glBindFramebuffer( GL_FRAMEBUFFER, 0 ); // Clear the famebuffer glClearColor( 0.f, 0.f, 0.f, 1.f ); // @TODO: Make this black again I guess.. glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); } void sl_window_swap_buffers( sl_window *win ) { // Issue the command to swap buffers glfwSwapBuffers( win->handle ); // Poll events before we hand over the spotlight. glfwPollEvents( ); } void sl_window_size_callback( GLFWwindow* window, int width, int height ) { sl_window *win; // Change the size of the FBO // @TODO: Make this less "tear down the world"-y; less slow & horrible. // although resizing the window should be punished... #ifndef SL_LEGACY_OPENGL win = sl_renderer_get_window_by_handle( window ); // Tear it down sl_window_destroy_fbo( win ); // Recreate it sl_window_create_fbo( win, width, height ); #endif }
31.075949
153
0.709572
[ "render" ]
fcc4b64ad1906b8f312a58a44fa8d7d2c17a9faa
3,557
c
C
src/vppinfra/vector/toeplitz.c
xerothermic/vpp
25a52a2c9c3e77acaf06a68a98be46fae254083d
[ "Apache-2.0" ]
null
null
null
src/vppinfra/vector/toeplitz.c
xerothermic/vpp
25a52a2c9c3e77acaf06a68a98be46fae254083d
[ "Apache-2.0" ]
1
2022-03-18T17:20:54.000Z
2022-03-18T17:20:54.000Z
src/vppinfra/vector/toeplitz.c
xerothermic/vpp
25a52a2c9c3e77acaf06a68a98be46fae254083d
[ "Apache-2.0" ]
null
null
null
/* SPDX-License-Identifier: Apache-2.0 * Copyright(c) 2021 Cisco Systems, Inc. */ #include <vppinfra/clib.h> #include <vppinfra/mem.h> #include <vppinfra/vector/toeplitz.h> static u8 default_key[40] = { 0x6d, 0x5a, 0x56, 0xda, 0x25, 0x5b, 0x0e, 0xc2, 0x41, 0x67, 0x25, 0x3d, 0x43, 0xa3, 0x8f, 0xb0, 0xd0, 0xca, 0x2b, 0xcb, 0xae, 0x7b, 0x30, 0xb4, 0x77, 0xcb, 0x2d, 0xa3, 0x80, 0x30, 0xf2, 0x0c, 0x6a, 0x42, 0xb7, 0x3b, 0xbe, 0xac, 0x01, 0xfa, }; #ifdef __x86_64__ static_always_inline void clib_toeplitz_hash_key_expand_8 (u64x2 kv, u64x8u *m) { u64x8 kv4, a, b, shift = { 0, 1, 2, 3, 4, 5, 6, 7 }; kv4 = (u64x8){ kv[0], kv[1], kv[0], kv[1], kv[0], kv[1], kv[0], kv[1] }; /* clang-format off */ /* create 8 byte-swapped copies of the bytes 0 - 7 */ a = (u64x8) u8x64_shuffle (kv4, 0x7, 0x6, 0x5, 0x4, 0x3, 0x2, 0x1, 0x0, 0x7, 0x6, 0x5, 0x4, 0x3, 0x2, 0x1, 0x0, 0x7, 0x6, 0x5, 0x4, 0x3, 0x2, 0x1, 0x0, 0x7, 0x6, 0x5, 0x4, 0x3, 0x2, 0x1, 0x0, 0x7, 0x6, 0x5, 0x4, 0x3, 0x2, 0x1, 0x0, 0x7, 0x6, 0x5, 0x4, 0x3, 0x2, 0x1, 0x0, 0x7, 0x6, 0x5, 0x4, 0x3, 0x2, 0x1, 0x0, 0x7, 0x6, 0x5, 0x4, 0x3, 0x2, 0x1, 0x0); /* create 8 byte-swapped copies of the bytes 4 - 11 */ b = (u64x8) u8x64_shuffle (kv4, 0xb, 0xa, 0x9, 0x8, 0x7, 0x6, 0x5, 0x4, 0xb, 0xa, 0x9, 0x8, 0x7, 0x6, 0x5, 0x4, 0xb, 0xa, 0x9, 0x8, 0x7, 0x6, 0x5, 0x4, 0xb, 0xa, 0x9, 0x8, 0x7, 0x6, 0x5, 0x4, 0xb, 0xa, 0x9, 0x8, 0x7, 0x6, 0x5, 0x4, 0xb, 0xa, 0x9, 0x8, 0x7, 0x6, 0x5, 0x4, 0xb, 0xa, 0x9, 0x8, 0x7, 0x6, 0x5, 0x4, 0xb, 0xa, 0x9, 0x8, 0x7, 0x6, 0x5, 0x4); /* clang-format on */ /* shift each 64-bit element for 0 - 7 bits */ a <<= shift; b <<= shift; /* clang-format off */ /* construct eight 8x8 bit matrix used by gf2p8affine */ * m = (u64x8) u8x64_shuffle2 (a, b, 0x07, 0x0f, 0x17, 0x1f, 0x27, 0x2f, 0x37, 0x3f, 0x06, 0x0e, 0x16, 0x1e, 0x26, 0x2e, 0x36, 0x3e, 0x05, 0x0d, 0x15, 0x1d, 0x25, 0x2d, 0x35, 0x3d, 0x04, 0x0c, 0x14, 0x1c, 0x24, 0x2c, 0x34, 0x3c, 0x47, 0x4f, 0x57, 0x5f, 0x67, 0x6f, 0x77, 0x7f, 0x46, 0x4e, 0x56, 0x5e, 0x66, 0x6e, 0x76, 0x7e, 0x45, 0x4d, 0x55, 0x5d, 0x65, 0x6d, 0x75, 0x7d, 0x44, 0x4c, 0x54, 0x5c, 0x64, 0x6c, 0x74, 0x7c); /* clang-format on */ } void clib_toeplitz_hash_key_expand (u64 *matrixes, u8 *key, int size) { u64x8u *m = (u64x8u *) matrixes; u64x2 kv = {}, zero = {}; while (size >= 8) { kv = *(u64x2u *) key; clib_toeplitz_hash_key_expand_8 (kv, m); key += 8; m++; size -= 8; } kv = u64x2_shuffle2 (kv, zero, 1, 2); clib_toeplitz_hash_key_expand_8 (kv, m); } #endif __clib_export clib_toeplitz_hash_key_t * clib_toeplitz_hash_key_init (u8 *key, u32 keylen) { clib_toeplitz_hash_key_t *k; u32 size, gfni_size = 0; if (key == 0) { key = default_key; keylen = sizeof (default_key); } size = round_pow2 (sizeof (clib_toeplitz_hash_key_t) + round_pow2 (keylen, 16), CLIB_CACHE_LINE_BYTES); #ifdef __x86_64__ gfni_size = round_pow2 ((keylen + 1) * 8, CLIB_CACHE_LINE_BYTES); #endif k = clib_mem_alloc_aligned (size + gfni_size, CLIB_CACHE_LINE_BYTES); clib_memset_u8 (k, 0, size + gfni_size); k->key_length = keylen; k->gfni_offset = size; clib_memcpy_fast (k->data, key, keylen); #ifdef __x86_64__ clib_toeplitz_hash_key_expand ((u64 *) ((u8 *) k + k->gfni_offset), k->data, k->key_length); #endif return k; } __clib_export void clib_toeplitz_hash_key_free (clib_toeplitz_hash_key_t *k) { clib_mem_free (k); }
28.918699
78
0.623278
[ "vector" ]
fccb2371c92a3cd65b4a44a5e92640407ca7abb7
13,018
c
C
examples/omp/dijkstra_openmp.c
MateusAraujoBorges/abc
188337fb1711b1889a4dff83dd688d0ebc5c98dc
[ "BSD-3-Clause" ]
null
null
null
examples/omp/dijkstra_openmp.c
MateusAraujoBorges/abc
188337fb1711b1889a4dff83dd688d0ebc5c98dc
[ "BSD-3-Clause" ]
null
null
null
examples/omp/dijkstra_openmp.c
MateusAraujoBorges/abc
188337fb1711b1889a4dff83dd688d0ebc5c98dc
[ "BSD-3-Clause" ]
null
null
null
# include <stdlib.h> # include <stdio.h> # include <time.h> # include <omp.h> # define NV 6 int main ( int argc, char **argv ); int *dijkstra_distance ( int ohd[NV][NV] ); void find_nearest ( int s, int e, int mind[NV], int connected[NV], int *d, int *v ); void init ( int ohd[NV][NV] ); void timestamp ( void ); void update_mind ( int s, int e, int mv, int connected[NV], int ohd[NV][NV], int mind[NV] ); /******************************************************************************/ int main ( int argc, char **argv ) /******************************************************************************/ /* Purpose: MAIN runs an example of Dijkstra's minimum distance algorithm. Discussion: Given the distance matrix that defines a graph, we seek a list of the minimum distances between node 0 and all other nodes. This program sets up a small example problem and solves it. The correct minimum distances are: 0 35 15 45 49 41 Licensing: This code is distributed under the GNU LGPL license. Modified: 01 July 2010 Author: Original C version by Norm Matloff, CS Dept, UC Davis. This C version by John Burkardt. */ { int i; int i4_huge = 2147483647; int j; int *mind; int ohd[NV][NV]; timestamp ( ); fprintf ( stdout, "\n" ); fprintf ( stdout, "DIJKSTRA_OPENMP\n" ); fprintf ( stdout, " C version\n" ); fprintf ( stdout, " Use Dijkstra's algorithm to determine the minimum\n" ); fprintf ( stdout, " distance from node 0 to each node in a graph,\n" ); fprintf ( stdout, " given the distances between each pair of nodes.\n" ); fprintf ( stdout, "\n" ); fprintf ( stdout, " Although a very small example is considered, we\n" ); fprintf ( stdout, " demonstrate the use of OpenMP directives for\n" ); fprintf ( stdout, " parallel execution.\n" ); /* Initialize the problem data. */ init ( ohd ); /* Print the distance matrix. */ fprintf ( stdout, "\n" ); fprintf ( stdout, " Distance matrix:\n" ); fprintf ( stdout, "\n" ); for ( i = 0; i < NV; i++ ) { for ( j = 0; j < NV; j++ ) { if ( ohd[i][j] == i4_huge ) { fprintf ( stdout, " Inf" ); } else { fprintf ( stdout, " %3d", ohd[i][j] ); } } fprintf ( stdout, "\n" ); } /* Carry out the algorithm. */ mind = dijkstra_distance ( ohd ); /* Print the results. */ fprintf ( stdout, "\n" ); fprintf ( stdout, " Minimum distances from node 0:\n"); fprintf ( stdout, "\n" ); for ( i = 0; i < NV; i++ ) { fprintf ( stdout, " %2d %2d\n", i, mind[i] ); } /* Free memory. */ free ( mind ); /* Terminate. */ fprintf ( stdout, "\n" ); fprintf ( stdout, "DIJKSTRA_OPENMP\n" ); fprintf ( stdout, " Normal end of execution.\n" ); fprintf ( stdout, "\n" ); timestamp ( ); return 0; } /******************************************************************************/ int *dijkstra_distance ( int ohd[NV][NV] ) /******************************************************************************/ /* Purpose: DIJKSTRA_DISTANCE uses Dijkstra's minimum distance algorithm. Discussion: We essentially build a tree. We start with only node 0 connected to the tree, and this is indicated by setting CONNECTED[0] = 1. We initialize MIND[I] to the one step distance from node 0 to node I. Now we search among the unconnected nodes for the node MV whose minimum distance is smallest, and connect it to the tree. For each remaining unconnected node I, we check to see whether the distance from 0 to MV to I is less than that recorded in MIND[I], and if so, we can reduce the distance. After NV-1 steps, we have connected all the nodes to 0, and computed the correct minimum distances. Licensing: This code is distributed under the GNU LGPL license. Modified: 02 July 2010 Author: Original C version by Norm Matloff, CS Dept, UC Davis. This C version by John Burkardt. Parameters: Input, int OHD[NV][NV], the distance of the direct link between nodes I and J. Output, int DIJKSTRA_DISTANCE[NV], the minimum distance from node 0 to each node. */ { int *connected; int i; int i4_huge = 2147483647; int md; int *mind; int mv; int my_first; int my_id; int my_last; int my_md; int my_mv; int my_step; int nth; /* Start out with only node 0 connected to the tree. */ connected = ( int * ) malloc ( NV * sizeof ( int ) ); connected[0] = 1; for ( i = 1; i < NV; i++ ) { connected[i] = 0; } /* Initial estimate of minimum distance is the 1-step distance. */ mind = ( int * ) malloc ( NV * sizeof ( int ) ); for ( i = 0; i < NV; i++ ) { mind[i] = ohd[0][i]; } /* Begin the parallel region. */ # pragma omp parallel private ( my_first, my_id, my_last, my_md, my_mv, my_step ) \ shared ( connected, md, mind, mv, nth, ohd ) { my_id = omp_get_thread_num ( ); nth = omp_get_num_threads ( ); my_first = ( my_id * NV ) / nth; my_last = ( ( my_id + 1 ) * NV ) / nth - 1; /* The SINGLE directive means that the block is to be executed by only one thread, and that thread will be whichever one gets here first. */ # pragma omp single { printf ( "\n" ); printf ( " P%d: Parallel region begins with %d threads\n", my_id, nth ); printf ( "\n" ); } fprintf ( stdout, " P%d: First=%d Last=%d\n", my_id, my_first, my_last ); for ( my_step = 1; my_step < NV; my_step++ ) { /* Before we compare the results of each thread, set the shared variable MD to a big value. Only one thread needs to do this. */ # pragma omp single { md = i4_huge; mv = -1; } /* Each thread finds the nearest unconnected node in its part of the graph. Some threads might have no unconnected nodes left. */ find_nearest ( my_first, my_last, mind, connected, &my_md, &my_mv ); /* In order to determine the minimum of all the MY_MD's, we must insist that only one thread at a time execute this block! */ # pragma omp critical { if ( my_md < md ) { md = my_md; mv = my_mv; } } /* This barrier means that ALL threads have executed the critical block, and therefore MD and MV have the correct value. Only then can we proceed. */ # pragma omp barrier /* If MV is -1, then NO thread found an unconnected node, so we're done early. OpenMP does not like to BREAK out of a parallel region, so we'll just have to let the iteration run to the end, while we avoid doing any more updates. Otherwise, we connect the nearest node. */ # pragma omp single { if ( mv != - 1 ) { connected[mv] = 1; printf ( " P%d: Connecting node %d.\n", my_id, mv ); } } /* Again, we don't want any thread to proceed until the value of CONNECTED is updated. */ # pragma omp barrier /* Now each thread should update its portion of the MIND vector, by checking to see whether the trip from 0 to MV plus the step from MV to a node is closer than the current record. */ if ( mv != -1 ) { update_mind ( my_first, my_last, mv, connected, ohd, mind ); } /* Before starting the next step of the iteration, we need all threads to complete the updating, so we set a BARRIER here. */ #pragma omp barrier } /* Once all the nodes have been connected, we can exit. */ # pragma omp single { printf ( "\n" ); printf ( " P%d: Exiting parallel region.\n", my_id ); } } free ( connected ); return mind; } /******************************************************************************/ void find_nearest ( int s, int e, int mind[NV], int connected[NV], int *d, int *v ) /******************************************************************************/ /* Purpose: FIND_NEAREST finds the nearest unconnected node. Licensing: This code is distributed under the GNU LGPL license. Modified: 02 July 2010 Author: Original C version by Norm Matloff, CS Dept, UC Davis. This C version by John Burkardt. Parameters: Input, int S, E, the first and last nodes that are to be checked. Input, int MIND[NV], the currently computed minimum distance from node 0 to each node. Input, int CONNECTED[NV], is 1 for each connected node, whose minimum distance to node 0 has been determined. Output, int *D, the distance from node 0 to the nearest unconnected node in the range S to E. Output, int *V, the index of the nearest unconnected node in the range S to E. */ { int i; int i4_huge = 2147483647; *d = i4_huge; *v = -1; for ( i = s; i <= e; i++ ) { if ( !connected[i] && ( mind[i] < *d ) ) { *d = mind[i]; *v = i; } } return; } /******************************************************************************/ void init ( int ohd[NV][NV] ) /******************************************************************************/ /* Purpose: INIT initializes the problem data. Discussion: The graph uses 6 nodes, and has the following diagram and distance matrix: N0--15--N2-100--N3 0 40 15 Inf Inf Inf \ | / 40 0 20 10 25 6 \ | / 15 20 0 100 Inf Inf 40 20 10 Inf 10 100 0 Inf Inf \ | / Inf 25 Inf Inf 0 8 \ | / Inf 6 Inf Inf 8 0 N1 / \ / \ 6 25 / \ / \ N5----8-----N4 Licensing: This code is distributed under the GNU LGPL license. Modified: 02 July 2010 Author: Original C version by Norm Matloff, CS Dept, UC Davis. This C version by John Burkardt. Parameters: Output, int OHD[NV][NV], the distance of the direct link between nodes I and J. */ { int i; int i4_huge = 2147483647; int j; for ( i = 0; i < NV; i++ ) { for ( j = 0; j < NV; j++ ) { if ( i == j ) { ohd[i][i] = 0; } else { ohd[i][j] = i4_huge; } } } ohd[0][1] = ohd[1][0] = 40; ohd[0][2] = ohd[2][0] = 15; ohd[1][2] = ohd[2][1] = 20; ohd[1][3] = ohd[3][1] = 10; ohd[1][4] = ohd[4][1] = 25; ohd[2][3] = ohd[3][2] = 100; ohd[1][5] = ohd[5][1] = 6; ohd[4][5] = ohd[5][4] = 8; return; } /******************************************************************************/ void timestamp ( void ) /******************************************************************************/ /* Purpose: TIMESTAMP prints the current YMDHMS date as a time stamp. Example: 31 May 2001 09:45:54 AM Licensing: This code is distributed under the GNU LGPL license. Modified: 24 September 2003 Author: John Burkardt Parameters: None */ { # define TIME_SIZE 40 static char time_buffer[TIME_SIZE]; const struct tm *tm; size_t len; time_t now; now = time ( NULL ); tm = localtime ( &now ); len = strftime ( time_buffer, TIME_SIZE, "%d %B %Y %I:%M:%S %p", tm ); printf ( "%s\n", time_buffer ); return; # undef TIME_SIZE } /******************************************************************************/ void update_mind ( int s, int e, int mv, int connected[NV], int ohd[NV][NV], int mind[NV] ) /******************************************************************************/ /* Purpose: UPDATE_MIND updates the minimum distance vector. Discussion: We've just determined the minimum distance to node MV. For each unconnected node I in the range S to E, check whether the route from node 0 to MV to I is shorter than the currently known minimum distance. Licensing: This code is distributed under the GNU LGPL license. Modified: 02 July 2010 Author: Original C version by Norm Matloff, CS Dept, UC Davis. This C version by John Burkardt. Parameters: Input, int S, E, the first and last nodes that are to be checked. Input, int MV, the node whose minimum distance to node 0 has just been determined. Input, int CONNECTED[NV], is 1 for each connected node, whose minimum distance to node 0 has been determined. Input, int OHD[NV][NV], the distance of the direct link between nodes I and J. Input/output, int MIND[NV], the currently computed minimum distances from node 0 to each node. On output, the values for nodes S through E have been updated. */ { int i; int i4_huge = 2147483647; for ( i = s; i <= e; i++ ) { if ( !connected[i] ) { if ( ohd[mv][i] < i4_huge ) { if ( mind[mv] + ohd[mv][i] < mind[i] ) { mind[i] = mind[mv] + ohd[mv][i]; } } } } return; }
23.288014
85
0.544784
[ "vector", "3d" ]
fccd12af32ba8476b9b081043e11e9406c591087
7,261
h
C
common/basectx.h
adamgreig/nextpnr
edecc06fcfbedf23773cd8ba04f1eb6f5bd64358
[ "0BSD" ]
1
2021-05-12T21:42:04.000Z
2021-05-12T21:42:04.000Z
common/basectx.h
adamgreig/nextpnr
edecc06fcfbedf23773cd8ba04f1eb6f5bd64358
[ "0BSD" ]
8
2020-12-30T15:08:34.000Z
2021-05-07T10:24:16.000Z
common/basectx.h
adamgreig/nextpnr
edecc06fcfbedf23773cd8ba04f1eb6f5bd64358
[ "0BSD" ]
null
null
null
/* * nextpnr -- Next Generation Place and Route * * Copyright (C) 2018 Clifford Wolf <clifford@symbioticeda.com> * Copyright (C) 2018 Serge Bazanski <q3k@symbioticeda.com> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #ifndef BASECTX_H #define BASECTX_H #include <mutex> #include <unordered_map> #include <vector> #ifndef NPNR_DISABLE_THREADS #include <boost/thread.hpp> #endif #include "idstring.h" #include "nextpnr_namespaces.h" #include "nextpnr_types.h" #include "property.h" #include "str_ring_buffer.h" NEXTPNR_NAMESPACE_BEGIN struct Context; struct BaseCtx { #ifndef NPNR_DISABLE_THREADS // Lock to perform mutating actions on the Context. std::mutex mutex; boost::thread::id mutex_owner; // Lock to be taken by UI when wanting to access context - the yield() // method will lock/unlock it when its' released the main mutex to make // sure the UI is not starved. std::mutex ui_mutex; #endif // ID String database. mutable std::unordered_map<std::string, int> *idstring_str_to_idx; mutable std::vector<const std::string *> *idstring_idx_to_str; // Temporary string backing store for logging mutable StrRingBuffer log_strs; // Project settings and config switches std::unordered_map<IdString, Property> settings; // Placed nets and cells. std::unordered_map<IdString, std::unique_ptr<NetInfo>> nets; std::unordered_map<IdString, std::unique_ptr<CellInfo>> cells; // Hierarchical (non-leaf) cells by full path std::unordered_map<IdString, HierarchicalCell> hierarchy; // This is the root of the above structure IdString top_module; // Aliases for nets, which may have more than one name due to assignments and hierarchy std::unordered_map<IdString, IdString> net_aliases; // Top-level ports std::unordered_map<IdString, PortInfo> ports; std::unordered_map<IdString, CellInfo *> port_cells; // Floorplanning regions std::unordered_map<IdString, std::unique_ptr<Region>> region; // Context meta data std::unordered_map<IdString, Property> attrs; Context *as_ctx = nullptr; // Has the frontend loaded a design? bool design_loaded; BaseCtx() { idstring_str_to_idx = new std::unordered_map<std::string, int>; idstring_idx_to_str = new std::vector<const std::string *>; IdString::initialize_add(this, "", 0); IdString::initialize_arch(this); design_loaded = false; } virtual ~BaseCtx() { delete idstring_str_to_idx; delete idstring_idx_to_str; } // Must be called before performing any mutating changes on the Ctx/Arch. void lock(void) { #ifndef NPNR_DISABLE_THREADS mutex.lock(); mutex_owner = boost::this_thread::get_id(); #endif } void unlock(void) { #ifndef NPNR_DISABLE_THREADS NPNR_ASSERT(boost::this_thread::get_id() == mutex_owner); mutex.unlock(); #endif } // Must be called by the UI before rendering data. This lock will be // prioritized when processing code calls yield(). void lock_ui(void) { #ifndef NPNR_DISABLE_THREADS ui_mutex.lock(); mutex.lock(); #endif } void unlock_ui(void) { #ifndef NPNR_DISABLE_THREADS mutex.unlock(); ui_mutex.unlock(); #endif } // Yield to UI by unlocking the main mutex, flashing the UI mutex and // relocking the main mutex. Call this when you're performing a // long-standing action while holding a lock to let the UI show // visualization updates. // Must be called with the main lock taken. void yield(void) { #ifndef NPNR_DISABLE_THREADS unlock(); ui_mutex.lock(); ui_mutex.unlock(); lock(); #endif } IdString id(const std::string &s) const { return IdString(this, s); } IdString id(const char *s) const { return IdString(this, s); } Context *getCtx() { return as_ctx; } const Context *getCtx() const { return as_ctx; } const char *nameOf(IdString name) const { return name.c_str(this); } template <typename T> const char *nameOf(const T *obj) const { if (obj == nullptr) return ""; return obj->name.c_str(this); } const char *nameOfBel(BelId bel) const; const char *nameOfWire(WireId wire) const; const char *nameOfPip(PipId pip) const; const char *nameOfGroup(GroupId group) const; // Wrappers of arch functions that take a string and handle IdStringList parsing BelId getBelByNameStr(const std::string &str); WireId getWireByNameStr(const std::string &str); PipId getPipByNameStr(const std::string &str); GroupId getGroupByNameStr(const std::string &str); // -------------------------------------------------------------- bool allUiReload = true; bool frameUiReload = false; std::unordered_set<BelId> belUiReload; std::unordered_set<WireId> wireUiReload; std::unordered_set<PipId> pipUiReload; std::unordered_set<GroupId> groupUiReload; void refreshUi() { allUiReload = true; } void refreshUiFrame() { frameUiReload = true; } void refreshUiBel(BelId bel) { belUiReload.insert(bel); } void refreshUiWire(WireId wire) { wireUiReload.insert(wire); } void refreshUiPip(PipId pip) { pipUiReload.insert(pip); } void refreshUiGroup(GroupId group) { groupUiReload.insert(group); } // -------------------------------------------------------------- NetInfo *getNetByAlias(IdString alias) const { return nets.count(alias) ? nets.at(alias).get() : nets.at(net_aliases.at(alias)).get(); } // Intended to simplify Python API void addClock(IdString net, float freq); void createRectangularRegion(IdString name, int x0, int y0, int x1, int y1); void addBelToRegion(IdString name, BelId bel); void constrainCellToRegion(IdString cell, IdString region_name); // Helper functions for Python bindings NetInfo *createNet(IdString name); void connectPort(IdString net, IdString cell, IdString port); void disconnectPort(IdString cell, IdString port); void ripupNet(IdString name); void lockNetRouting(IdString name); CellInfo *createCell(IdString name, IdString type); void copyBelPorts(IdString cell, BelId bel); // Workaround for lack of wrappable constructors DecalXY constructDecalXY(DecalId decal, float x, float y); void archInfoToAttributes(); void attributesToArchInfo(); }; NEXTPNR_NAMESPACE_END #endif /* BASECTX_H */
30.380753
95
0.681862
[ "vector" ]
fcd2954372ae83c8b3da678cf4d9418e1b59c5cd
910
h
C
app42/libs/Shephertz_App42_iOS_API.framework/Versions/Current/Headers/CategoryData.h
saqsun/robovm-ios-bindings
dae85f2e573dbbc0973e40a730a22ce356f6a3c1
[ "Apache-2.0" ]
90
2015-01-01T21:20:50.000Z
2021-12-28T00:52:27.000Z
app42/libs/Shephertz_App42_iOS_API.framework/Versions/Current/Headers/CategoryData.h
saqsun/robovm-ios-bindings
dae85f2e573dbbc0973e40a730a22ce356f6a3c1
[ "Apache-2.0" ]
68
2015-01-02T00:22:36.000Z
2017-02-14T23:49:46.000Z
app42/libs/Shephertz_App42_iOS_API.framework/Versions/Current/Headers/CategoryData.h
saqsun/robovm-ios-bindings
dae85f2e573dbbc0973e40a730a22ce356f6a3c1
[ "Apache-2.0" ]
65
2015-01-11T23:53:12.000Z
2021-11-08T06:25:36.000Z
// // CategoryData.h // PAE_iOS_SDK // // Created by Shephertz Technology on 13/04/12. // Copyright (c) 2012 ShephertzTechnology PVT LTD. All rights reserved. // #import <Foundation/Foundation.h> #import "App42Response.h" @class Catalogue; /** * An inner class that contains the remaining properties of the Catalogue. * */ @interface CategoryData : App42Response{ } /*! *set and get the name of the Category. */ @property(nonatomic,retain)NSString *name; /*! *set and get the description of the Category. */ @property(nonatomic,retain)NSString *description; /*! *set and get the itemList of the Category. */ @property(nonatomic,retain)NSMutableArray *itemListArray; /*! *set and get the catalogueObject for CategoryData Object */ @property(nonatomic,retain)Catalogue *catalogueObject; - (id) init __attribute__((unavailable)); -(id)initWithCatalogue:(Catalogue*)catalogueObj; @end
20.222222
74
0.72967
[ "object" ]
fcd77bc95388b98c2e1270cf54ad45537c71fe21
4,224
h
C
tensorflow/compiler/plugin/poplar/driver/tools/isomorphic_functions_map.h
chenzhengda/tensorflow
8debb698097670458b5f21d728bc6f734a7b5a53
[ "Apache-2.0" ]
74
2020-07-06T17:11:39.000Z
2022-01-28T06:31:28.000Z
tensorflow/compiler/plugin/poplar/driver/tools/isomorphic_functions_map.h
chenzhengda/tensorflow
8debb698097670458b5f21d728bc6f734a7b5a53
[ "Apache-2.0" ]
9
2020-10-13T23:25:29.000Z
2022-02-10T06:54:48.000Z
tensorflow/compiler/plugin/poplar/driver/tools/isomorphic_functions_map.h
chenzhengda/tensorflow
8debb698097670458b5f21d728bc6f734a7b5a53
[ "Apache-2.0" ]
12
2020-07-08T07:27:17.000Z
2021-12-27T08:54:27.000Z
/* Copyright 2020 The TensorFlow 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. ==============================================================================*/ #ifndef TENSORFLOW_COMPILER_PLUGIN_POPLAR_DRIVER_TOOLS_ISOMORPHIC_FUNCTIONS_MAP_H_ #define TENSORFLOW_COMPILER_PLUGIN_POPLAR_DRIVER_TOOLS_ISOMORPHIC_FUNCTIONS_MAP_H_ #include <map> #include <unordered_map> #include <vector> #include "tensorflow/compiler/plugin/poplar/driver/tools/util.h" #include "tensorflow/compiler/xla/map_util.h" #include "tensorflow/compiler/xla/service/hlo_computation.h" #include "tensorflow/compiler/xla/service/hlo_instruction.h" #include "tensorflow/compiler/xla/shape_util.h" namespace xla { namespace poplarplugin { using Functions = HloInstructionSet; // A container for storing isomorphic functions which allows deterministic // iterating over the functions. template <bool is_sharding_sensitive, bool sort_by_increasing_size> class IsomorphicFunctionsMap { struct FunctionHash { size_t operator()(const HloInstruction* inst) const { return HloComputationHash()(inst->to_apply()); } }; struct FunctionEquals { bool operator()(const HloInstruction* a, const HloInstruction* b) const { return a->to_apply()->Equal(*b->to_apply(), /*is_layout_sensitive=*/false, is_sharding_sensitive); } }; using StorageMap = std::unordered_map<HloInstruction*, Functions, FunctionHash, FunctionEquals>; struct FunctionCompare { bool operator()(const HloInstruction* a, const HloInstruction* b) const { if (sort_by_increasing_size) { const int64 a_size = GetByteSizeOfTotalShape(a->shape()); const int64 b_size = GetByteSizeOfTotalShape(b->shape()); if (a_size != b_size) { return a_size < b_size; } } return HloPtrComparator()(a, b); } }; using AccessMap = std::map<HloInstruction*, Functions*, FunctionCompare>; public: void insert(HloInstruction* inst) { auto itr = storage_map_.find(inst); if (itr == storage_map_.end()) { itr = storage_map_.emplace(inst, Functions{inst}).first; // Add the reference to the storage map. CHECK(!ContainsKey(access_map_, inst)); access_map_[inst] = &itr->second; } else { itr->second.insert(inst); } } void erase(HloInstruction* inst) { auto itr = storage_map_.find(inst); if (itr != storage_map_.end()) { auto key = itr->first; CHECK(ContainsKey(access_map_, key)); access_map_.erase(key); storage_map_.erase(key); } } const Functions& at(HloInstruction* inst) const { return *access_map_.at(inst); } std::size_t size() const { return access_map_.size(); } bool empty() const { return access_map_.empty(); } typename AccessMap::const_iterator begin() const { return access_map_.begin(); } typename AccessMap::const_iterator end() const { return access_map_.end(); } private: // Note: access map stores references to storage map. The order matters. StorageMap storage_map_; AccessMap access_map_; }; using SingleShardIsomorphicFunctions = IsomorphicFunctionsMap<true, false>; using CrossShardIsomorphicFunctions = IsomorphicFunctionsMap<false, false>; // Variants where the iterator is sorted by function output size. using SingleShardIsomorphicFunctionsOutputSizeSorted = IsomorphicFunctionsMap<true, true>; using CrossShardIsomorphicFunctionsOutputSizeSorted = IsomorphicFunctionsMap<false, true>; } // namespace poplarplugin } // namespace xla #endif // TENSORFLOW_COMPILER_PLUGIN_POPLAR_DRIVER_TOOLS_ISOMORPHIC_FUNCTIONS_MAP_H_
33.259843
85
0.706913
[ "shape", "vector" ]
fcdc49657e7c6299a7a4d456bbb0bb8857ca244a
2,290
h
C
UAlbertaBot/Source/BuildingData.h
iali17/TheDon
f21cae2357835e7a21ebf351abb6bb175f67540c
[ "MIT" ]
null
null
null
UAlbertaBot/Source/BuildingData.h
iali17/TheDon
f21cae2357835e7a21ebf351abb6bb175f67540c
[ "MIT" ]
null
null
null
UAlbertaBot/Source/BuildingData.h
iali17/TheDon
f21cae2357835e7a21ebf351abb6bb175f67540c
[ "MIT" ]
null
null
null
#pragma once #include "Common.h" namespace UAlbertaBot { namespace BuildingStatus { enum { Unassigned = 0, Assigned = 1, UnderConstruction = 2, Size = 3 }; } class Building { public: BWAPI::TilePosition desiredPosition; BWAPI::TilePosition finalPosition; BWAPI::Position position; BWAPI::UnitType type; BWAPI::Unit buildingUnit; BWAPI::Unit builderUnit; size_t status; int lastOrderFrame; bool isGasSteal; bool buildCommandGiven; bool underConstruction; Building() : desiredPosition (0,0) , finalPosition (BWAPI::TilePositions::None) , position (0,0) , type (BWAPI::UnitTypes::Unknown) , buildingUnit (nullptr) , builderUnit (nullptr) , lastOrderFrame (0) , status (BuildingStatus::Unassigned) , buildCommandGiven (false) , underConstruction (false) , isGasSteal (false) {} // constructor we use most often Building(BWAPI::UnitType t, BWAPI::TilePosition desired) : desiredPosition (desired) , finalPosition (0,0) , position (0,0) , type (t) , buildingUnit (nullptr) , builderUnit (nullptr) , lastOrderFrame (0) , status (BuildingStatus::Unassigned) , buildCommandGiven (false) , underConstruction (false) , isGasSteal (false) {} // equals operator bool operator==(const Building & b) { // buildings are equal if their worker unit or building unit are equal return (b.buildingUnit == buildingUnit) || (b.builderUnit == builderUnit); } }; class BuildingData { public: BuildingData(); std::vector<Building> _buildings; std::vector<Building> & getBuildings(); void addBuilding(const Building & b); void removeBuilding(const Building & b); void removeBuildings(const std::vector<Building> & buildings); bool isBeingBuilt(BWAPI::UnitType type); }; }
27.926829
77
0.543231
[ "vector" ]
fcdd6d7514537454577c31624d8be9a9df59310c
95,741
h
C
cmts.h
MarcelPiNacy/cmts
ab19af35ac8ba9dcd8ac572f3c6d3b781501c170
[ "Apache-2.0" ]
3
2020-05-20T15:11:22.000Z
2021-06-08T03:40:29.000Z
cmts.h
MarcelPiNacy/cmts
ab19af35ac8ba9dcd8ac572f3c6d3b781501c170
[ "Apache-2.0" ]
null
null
null
cmts.h
MarcelPiNacy/cmts
ab19af35ac8ba9dcd8ac572f3c6d3b781501c170
[ "Apache-2.0" ]
null
null
null
/* Copyright 2021 Marcel Pi Nacy 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 cmts.h * Contains the core C api and implementation of CMTS. */ #ifndef CMTS_INCLUDED #define CMTS_INCLUDED #include <stdint.h> #include <stddef.h> #ifdef _WIN32 #define CMTS_WINDOWS #define CMTS_REQUIRES_TASK_ALLOCATOR 0 #else #error "CMTS: UNSUPPORTED OPERATING SYSTEM." #endif #ifndef CMTS_CALL /** * Used to override the calling convention of public CMTS functions. */ #define CMTS_CALL #endif #ifndef CMTS_ATTR /** * Used to add extra attributes to public CMTS functions. */ #define CMTS_ATTR #endif #ifndef CMTS_PTR /** * Used to override the calling convention of CMTS function pointers. */ #define CMTS_PTR #endif #ifdef __cplusplus #define CMTS_EXTERN_C_BEGIN extern "C" { #define CMTS_EXTERN_C_END } #else #define CMTS_EXTERN_C_BEGIN #define CMTS_EXTERN_C_END #endif #ifndef CMTS_NODISCARD #define CMTS_NODISCARD #ifdef __cplusplus #if __has_cpp_attribute(nodiscard) #undef CMTS_NODISCARD #define CMTS_NODISCARD [[nodiscard]] #endif #endif #endif #ifndef CMTS_NORETURN #define CMTS_NORETURN #ifdef __cplusplus #if __has_cpp_attribute(noreturn) #undef CMTS_NORETURN #define CMTS_NORETURN [[noreturn]] #endif #endif #endif #define CMTS_INVALID_TASK_ID UINT64_MAX #define CMTS_MAX_TASKS UINT32_MAX #ifndef CMTS_CACHE_LINE_SIZE #define CMTS_CACHE_LINE_SIZE 64 #endif #ifndef CMTS_MAX_PRIORITY /** * Used to override the number of queues per worker thread. */ #define CMTS_MAX_PRIORITY 3 #endif #if CMTS_MAX_PRIORITY >= 256 #error "Error, CMTS_MAX_PRIORITY must not exceed 256" #endif #ifndef CMTS_DEFAULT_TASKS_PER_THREAD /** * Used to override the number allocated tasks per worker thread (if cmts_init is called with NULL). */ #define CMTS_DEFAULT_TASKS_PER_THREAD 256 #endif #ifndef CMTS_SPIN_THRESHOLD /** * Used to override the maximum number of retries of a spin loop before switching to a long-term waiting strategy. */ #define CMTS_SPIN_THRESHOLD 8 #endif #define CMTS_FENCE_DATA_SIZE 4 #define CMTS_EVENT_DATA_SIZE 8 #define CMTS_COUNTER_DATA_SIZE 16 #define CMTS_MUTEX_DATA_SIZE 8 #ifndef CMTS_CHAR #define CMTS_CHAR char #endif #ifndef CMTS_TEXT #define CMTS_TEXT(TEXT) TEXT #endif CMTS_EXTERN_C_BEGIN #define CMTS_FALSE ((cmts_bool)0) #define CMTS_TRUE ((cmts_bool)1) #ifdef __cplusplus typedef bool cmts_bool; #else typedef _Bool cmts_bool; #endif typedef uint64_t cmts_task_id; typedef void(CMTS_PTR* cmts_fn_task)(void* parameter); typedef void* (CMTS_PTR* cmts_fn_allocate)(size_t size); typedef cmts_bool(CMTS_PTR* cmts_fn_deallocate)(void* memory, size_t size); typedef void(CMTS_PTR* cmts_fn_destructor)(void* object); typedef enum cmts_result { CMTS_OK = 0, CMTS_SYNC_OBJECT_EXPIRED = 1, CMTS_NOT_READY = 2, CMTS_ALREADY_INITIALIZED = 3, CMTS_INITIALIZATION_IN_PROGRESS = 4, CMTS_ERROR_MEMORY_ALLOCATION = -1, CMTS_ERROR_MEMORY_DEALLOCATION = -2, CMTS_ERROR_THREAD_CREATION = -3, CMTS_ERROR_THREAD_AFFINITY = -4, CMTS_ERROR_RESUME_THREAD = -5, CMTS_ERROR_SUSPEND_THREAD = -6, CMTS_ERROR_TERMINATE_THREAD = -7, CMTS_ERROR_AWAIT_THREAD = -8, CMTS_ERROR_TASK_POOL_CAPACITY = -9, CMTS_ERROR_AFFINITY = -10, CMTS_ERROR_TASK_ALLOCATION = -11, CMTS_ERROR_FUTEX = -12, CMTS_ERROR_LIBRARY_UNINITIALIZED = -13, CMTS_ERROR_OS_INIT = -14, CMTS_ERROR_INVALID_EXTENSION_TYPE = -15, CMTS_ERROR_UNSUPPORTED_EXTENSION = -16, CMTS_RESULT_BEGIN_ENUM = CMTS_ERROR_UNSUPPORTED_EXTENSION, CMTS_RESULT_END_ENUM = CMTS_INITIALIZATION_IN_PROGRESS + 1, } cmts_result; typedef enum cmts_sync_type { CMTS_SYNC_TYPE_NONE, CMTS_SYNC_TYPE_EVENT, CMTS_SYNC_TYPE_COUNTER, CMTS_SYNC_TYPE_BEGIN_ENUM = CMTS_SYNC_TYPE_NONE, CMTS_SYNC_TYPE_END_ENUM = CMTS_SYNC_TYPE_COUNTER + 1, } cmts_sync_type; typedef enum cmts_dispatch_flag_bits { CMTS_DISPATCH_FLAGS_FORCE = 1, } cmts_dispatch_flag_bits; typedef uint64_t cmts_dispatch_flags; typedef enum cmts_init_flag_bits { } cmts_init_flag_bits; typedef uint64_t cmts_init_flags; typedef enum cmts_ext_type { CMTS_EXT_TYPE_DEBUGGER, CMTS_EXT_TYPE_BEGIN_ENUM = CMTS_EXT_TYPE_DEBUGGER, CMTS_EXT_TYPE_END_ENUM = CMTS_EXT_TYPE_DEBUGGER + 1, } cmts_ext_type; typedef uint32_t cmts_fence; typedef uint64_t cmts_event; typedef struct cmts_counter { uint64_t low, high; } cmts_counter; typedef uint32_t cmts_mutex; typedef size_t cmts_hazard_context; /** Macro alternative to cmts_fence_init. * Mainly useful for compile-time initialization. */ #define CMTS_FENCE_INIT UINT32_MAX /** Macro alternative to cmts_event_init. * Mainly useful for compile-time initialization. */ #define CMTS_EVENT_INIT UINT64_MAX /** Macro alternative to cmts_counter_init. * Mainly useful for compile-time initialization. */ #define CMTS_COUNTER_INIT(VALUE) { UINT64_MAX, (VALUE) } /** Macro alternative to cmts_mutex_init. * Mainly useful for compile-time initialization. */ #define CMTS_MUTEX_INIT UINT32_MAX typedef struct cmts_task_allocator { // The memory allocation callback. cmts_fn_allocate allocate; // The memory deallocation callback. cmts_fn_deallocate deallocate; } cmts_task_allocator; typedef struct cmts_init_options { // Reserved, must be 0. cmts_init_flags flags; // A callback that will be used when allocating memory for the global state of CMTS. This function is currently called only once. cmts_fn_allocate allocate_function; // Either NULL or a pointer to an array of indices to use when assigning worker threads to CPU cores. const uint32_t* thread_affinities; // Either NULL or a valid pointer to a cmts_task_allocator record. In Windows platforms this value is ignored. const cmts_task_allocator* task_allocator; // The default size of the stack of a tasks. uint32_t task_stack_size; // The number of worker threads to launch. uint32_t thread_count; // The capacity of the global task pool uint32_t max_tasks; // Either NULL or a valid pointer to a record of type cmts_ext_*_init_options. cmts_ext_debug_init_options, for example. const void* next_ext; } cmts_init_options; typedef struct cmts_dispatch_options { // Flags that specify the behavior of cmts_dispatch. For example, CMTS_DISPATCH_FLAGS_FORCE makes this function block until a task is acquired. cmts_dispatch_flags flags; // Either NULL or a valid pointer to a cmts_task_id variable that receives the ID of the submitted task. cmts_task_id* out_task_id; // Either NULL or a valid pointer to a uint32_t variable that specifies the index of the worker thread to which the task will always run on. const uint32_t* locked_thread; // The parameter to pass to the task entry point. void* parameter; // Either NULL or a valid pointer to a synchronization object (only cmts_event or cmts_counter). void* sync_object; // The type of the object pointed to by sync_object. Ignored if it is NULL. cmts_sync_type sync_type; // The execution priority of the task. uint8_t priority; // Reserved, must be NULL. const void* next_ext; } cmts_dispatch_options; typedef struct cmts_memory_requirements { // The required buffer size. size_t size; // The base-2 log of the alignment of the buffer. uint8_t alignment_log2; } cmts_memory_requirements; typedef enum cmts_ext_debug_message_severity { CMTS_EXT_DEBUGGER_MESSAGE_SEVERITY_INFO, CMTS_EXT_DEBUGGER_MESSAGE_SEVERITY_WARNING, CMTS_EXT_DEBUGGER_MESSAGE_SEVERITY_ERROR, CMTS_EXT_DEBUGGER_MESSAGE_SEVERITY_BEGIN_ENUM = CMTS_EXT_DEBUGGER_MESSAGE_SEVERITY_INFO, CMTS_EXT_DEBUGGER_MESSAGE_SEVERITY_END_ENUM = CMTS_EXT_DEBUGGER_MESSAGE_SEVERITY_ERROR + 1, } cmts_ext_debug_message_severity; typedef struct cmts_ext_debug_message { // A pointer to a null-terminated string with the message text. const CMTS_CHAR* message; // The length of the message. size_t message_length; // The severity of the message. cmts_ext_debug_message_severity severity; // Reserved, must be NULL. const void* next_ext; } cmts_ext_debug_message; typedef void(CMTS_CALL* cmts_fn_debugger_message)(void* context, const cmts_ext_debug_message* message); typedef struct cmts_ext_debug_init_options { // Either NULL or a valid pointer to another record of type cmts_ext_*_init_options. const void* next; // Must be CMTS_EXT_TYPE_DEBUGGER. cmts_ext_type type; // Either NULL or a pointer that will be passed to cmts_ext_debug_write when invoked. void* context; // Either NULL or the callback to use when cmts_ext_debug_write is invoked. cmts_fn_debugger_message message_callback; } cmts_ext_debug_init_options; /** @brief Initializes the CMTS scheduler. * @param options An optional pointer to a @ref cmts_init_options record. * @return CMTS_OK on success. Possible error codes include: * @li CMTS_ALREADY_INITIALIZED * @li CMTS_INITIALIZATION_IN_PROGRESS * @li CMTS_ERROR_OS_INIT * @li CMTS_ERROR_MEMORY_ALLOCATION * @li CMTS_ERROR_INVALID_EXTENSION_TYPE */ CMTS_ATTR cmts_result CMTS_CALL cmts_init(const cmts_init_options* options); /** Pauses all worker threads. * @return CMTS_OK on success. Otherwise CMTS_ERROR_LIBRARY_UNINITIALIZED or CMTS_ERROR_SUSPEND_THREAD. */ CMTS_ATTR cmts_result CMTS_CALL cmts_pause(); /** Resumes all worker threads. * @return CMTS_OK on success. Otherwise CMTS_ERROR_LIBRARY_UNINITIALIZED or CMTS_ERROR_RESUME_THREAD. */ CMTS_ATTR cmts_result CMTS_CALL cmts_resume(); /** Begins the library cleanup process. * After this function is called, the worker threads will begin to exit once they reach an idle state. */ CMTS_ATTR void CMTS_CALL cmts_finalize_signal(); /** Blocks until all worker threads have quit and then handles library cleanup. * @param deallocate Either NULL or a callback to free the memory that was previously allocated by cmts_init_options::allocate_function at library startup. * @return CMTS_OK on success. Otherwise CMTS_ERROR_LIBRARY_UNINITIALIZED, CMTS_ERROR_AWAIT_THREAD or CMTS_ERROR_MEMORY_DEALLOCATION; */ CMTS_ATTR cmts_result CMTS_CALL cmts_finalize_await(cmts_fn_deallocate deallocate); /** Forcefully quits all worker threads and then handles library cleanup. * @param deallocate Either NULL or a callback to free the memory that was previously allocated by cmts_init_options::allocate_function at library startup. * @return CMTS_OK on success. Otherwise CMTS_ERROR_LIBRARY_UNINITIALIZED, CMTS_ERROR_TERMINATE_THREAD or CMTS_ERROR_MEMORY_DEALLOCATION; */ CMTS_ATTR cmts_result CMTS_CALL cmts_terminate(cmts_fn_deallocate deallocate); /** * @return Whether CMTS is initialized. */ CMTS_ATTR cmts_bool CMTS_CALL cmts_is_initialized(); /** * @return CMTS_TRUE if the library is initialized and cmts_finalize_signal has not yet been called. CMTS_FALSE otherwise. */ CMTS_ATTR cmts_bool CMTS_CALL cmts_is_online(); /** * @return Whether the worker threads are paused. */ CMTS_ATTR cmts_bool CMTS_CALL cmts_is_paused(); /** Frees cached tasks. * @params max_purged_tasks The maximum number of cached tasks to free. * @return The number of freed tasks. * @note This function is not thread-safe. */ CMTS_ATTR uint32_t CMTS_CALL cmts_purge(uint32_t max_purged_tasks); /** Frees all cached tasks. * @return The number of freed tasks. * @note This function is not thread-safe. */ CMTS_ATTR uint32_t CMTS_CALL cmts_purge_all(); /** * @return Whether the current thread is a CMTS worker thread. */ CMTS_ATTR cmts_bool CMTS_CALL cmts_is_worker_thread(); /** * @return If the current thread belongs to CMTS, the index of the worker thread. Otherwise returns the number of worker threads. */ CMTS_ATTR uint32_t CMTS_CALL cmts_worker_thread_index(); /** * @return The number of worker threads. */ CMTS_ATTR uint32_t CMTS_CALL cmts_worker_thread_count(); /** Submits a task to the CMTS scheduler with the specified entry point. * @param entry_point A callback to use as the entry point of the submitted task. * @param options Either NULL or a valid pointer to a cmts_dispatch_options record. * @return CMTS_OK on success. Otherwise CMTS_ERROR_TASK_POOL_CAPACITY or CMTS_ERROR_TASK_ALLOCATION. */ CMTS_ATTR cmts_result CMTS_CALL cmts_dispatch(cmts_fn_task entry_point, cmts_dispatch_options* options); /** Pauses execution of the current task, allowing another one to run on the current worker thread. */ CMTS_ATTR void CMTS_CALL cmts_yield(); /** Finishes execution of the current task, returning it to the global pool. * @remarks In C++ programs extra care must be taken to ensure that local objects have their resources freed, since calling cmts_exit does not invoke destructors automatically. */ CMTS_NORETURN CMTS_ATTR void CMTS_CALL cmts_exit(); /** * @return Whether this function is being called from within a task. */ CMTS_ATTR cmts_bool CMTS_CALL cmts_is_task(); /** * @return The ID of the current task. */ CMTS_ATTR cmts_task_id CMTS_CALL cmts_this_task_id(); /** Manually allocates a task from the global pool. * @return The ID of the allocated task. CMTS_INVALID_TASK_ID if the global pool has run out of tasks. */ CMTS_NODISCARD CMTS_ATTR cmts_task_id CMTS_CALL cmts_task_allocate(); /** Retrieves the priority of a task. * @param task_id The ID of the task. * @return The priority of the task. */ CMTS_ATTR uint8_t CMTS_CALL cmts_task_get_priority(cmts_task_id task_id); /** Sets the priority of a task. * @param task_id The ID of the task. * @param new_priority The desired priority of the task. * @note WARNING: Reading or writing task attributes is not thread-safe and if the task has been submitted it is UB. */ CMTS_ATTR void CMTS_CALL cmts_task_set_priority(cmts_task_id task_id, uint8_t new_priority); /** Retrieves the parameter of a task. * @param task_id The ID of the task. * @return The parameters of the task. * @note WARNING: Reading or writing task attributes is not thread-safe and if the task has been submitted it is UB. */ CMTS_ATTR void* CMTS_CALL cmts_task_get_parameter(cmts_task_id task_id); /** Sets the parameter of a task. * @param task_id The ID of the task. * @param new_parameter The desired parameter of the task. * @note WARNING: Reading or writing task attributes is not thread-safe and if the task has been submitted it is UB. */ CMTS_ATTR void CMTS_CALL cmts_task_set_parameter(cmts_task_id task_id, void* new_parameter); /** Retrieves the entry point of a task. * @param task_id The ID of the task. * @return The entry point of the task. * @note WARNING: Reading or writing task attributes is not thread-safe and if the task has been submitted it is UB. */ CMTS_ATTR cmts_fn_task CMTS_CALL cmts_task_get_function(cmts_task_id task_id); /** Sets the entry point of a task. * @param task_id The ID of the task. * @param new_function The desired entry point of the task. * @note WARNING: Reading or writing task attributes is not thread-safe and if the task has been submitted it is UB. */ CMTS_ATTR void CMTS_CALL cmts_task_set_function(cmts_task_id task_id, cmts_fn_task new_function); /** Attaches a cmts_event to a task. * @param task_id The ID of the task. * @param event A pointer to the event to attach. * @note WARNING: Reading or writing task attributes is not thread-safe and if the task has been submitted it is UB. */ CMTS_ATTR void CMTS_CALL cmts_task_attach_event(cmts_task_id task_id, cmts_event* event); /** Attaches a cmts_counter to a task. * @param task_id The ID of the task. * @param counter A pointer to the counter to attach. * @note WARNING: Reading or writing task attributes is not thread-safe and if the task has been submitted it is UB. */ CMTS_ATTR void CMTS_CALL cmts_task_attach_counter(cmts_task_id task_id, cmts_counter* counter); /** Pauses the execution of a task. * @param task_id The ID of the task. * @note WARNING: Reading or writing task attributes is not thread-safe and if the task has been submitted it is UB. */ CMTS_ATTR void CMTS_CALL cmts_task_sleep(cmts_task_id task_id); /** Resumes execution of a task. * @param task_id The ID of the task. * @note WARNING: Calling this function while the specified task is not currently sleeping is UB. */ CMTS_ATTR void CMTS_CALL cmts_task_resume(cmts_task_id task_id); /** Checks whether a task ID is valid. * @param task_id The ID of the task. * @return Whether the specified ID is valid. */ CMTS_ATTR cmts_bool CMTS_CALL cmts_is_valid_task_id(cmts_task_id task_id); /** Checks whether a task is sleeping. * @param task_id The ID of the task. * @return Whether the specified task is sleeping. */ CMTS_ATTR cmts_bool CMTS_CALL cmts_task_is_sleeping(cmts_task_id task_id); /** Checks whether a task is running. * @param task_id The ID of the task. * @return Whether the specified task is running. */ CMTS_ATTR cmts_bool CMTS_CALL cmts_task_is_running(cmts_task_id task_id); /** Submits a task to the scheduler. * @param task_id The ID of the task. */ CMTS_ATTR void CMTS_CALL cmts_task_dispatch(cmts_task_id task_id); /** Returns the specified task to the global pool. * @param task_id The ID of the task. * @note WARNING: Reading or writing task attributes is not thread-safe and if the task has been submitted it is UB. */ CMTS_ATTR void CMTS_CALL cmts_task_deallocate(cmts_task_id task_id); /** Initializes a fence. * @param fence A valid pointer to a cmts_fence object. * @note This function is not thread-safe. */ CMTS_ATTR void CMTS_CALL cmts_fence_init(cmts_fence* fence); /** Busy waits until a task is waiting on the fence, then resumes it. * @param fence A valid pointer to a cmts_fence object. */ CMTS_ATTR void CMTS_CALL cmts_fence_signal(cmts_fence* fence); /** Attempts to suspend execution of the current task until the fence is signaled. * @param fence A valid pointer to a cmts_fence object. * @return CMTS_TRUE if the wait succeeded. CMTS_FALSE if the fence was already being awaited on. */ CMTS_ATTR cmts_bool CMTS_CALL cmts_fence_try_await(cmts_fence* fence); /** Suspends execution of the current task until the fence is signaled. * [DEBUG ONLY] If the fence is being awaited on by another task, abort is called. * @param fence A valid pointer to a cmts_fence object. */ CMTS_ATTR void CMTS_CALL cmts_fence_await(cmts_fence* fence); /** Initializes an event object. * @param event A valid pointer to a cmts_event object. * @note This function is not thread-safe. */ CMTS_ATTR void CMTS_CALL cmts_event_init(cmts_event* event); /** Retrieves the state of an event. * @param event A valid pointer to a cmts_event object. * @return The state of the event. Possible results: * @li CMTS_OK if the event has already been signaled. * @li CMTS_SYNC_OBJECT_EXPIRED if the event has already been signaled. * @li CMTS_NOT_READY if no task is waiting for the event to become signaled. */ CMTS_ATTR cmts_result CMTS_CALL cmts_event_state(const cmts_event* event); /** Signals the event, resuming any tasks awaiting on it. * @param event A valid pointer to a cmts_event object. * @return CMTS_OK if the operation succeeded, CMTS_SYNC_OBJECT_EXPIRED if the event has already been signaled. */ CMTS_ATTR cmts_result CMTS_CALL cmts_event_signal(cmts_event* event); /** Waits for the event to become signaled, putting the current task to sleep. * @param event A valid pointer to a cmts_event object. * @return CMTS_OK if the operation succeeded, CMTS_SYNC_OBJECT_EXPIRED if the event had already been signaled. */ CMTS_ATTR cmts_result CMTS_CALL cmts_event_await(cmts_event* event); /** Attempts to reset the event, allowing new tasks to await on it. * @param event A valid pointer to a cmts_event object. * @return CMTS_OK if the operation succeeded, CMTS_NOT_READY if the event still has tasks waiting for it to become signaled. */ CMTS_ATTR cmts_result CMTS_CALL cmts_event_reset(cmts_event* event); /** Initializes a counter object. * @param counter A valid pointer to a cmts_counter object. * @param start_value The initial value of the counter. * @note This function is not thread-safe. */ CMTS_ATTR void CMTS_CALL cmts_counter_init(cmts_counter* counter, uint64_t start_value); /** Retrieves the value of a counter. * @param counter A valid pointer to a cmts_counter object. * @return The current value of the counter. */ CMTS_ATTR uint64_t CMTS_CALL cmts_counter_value(const cmts_counter* counter); /** Retrieves the state of a counter. * @param counter A valid pointer to a cmts_counter object. * @return The state of the counter. Possible results: * @li CMTS_OK if the counter has already reached zero (signaled). * @li CMTS_SYNC_OBJECT_EXPIRED if the event has already been signaled. * @li CMTS_NOT_READY if no task is waiting for the counter to become signaled. */ CMTS_ATTR cmts_result CMTS_CALL cmts_counter_state(const cmts_counter* counter); /** Atomically increments the value of the counter. * @param counter A valid pointer to a cmts_counter object. * @return CMTS_OK if the operation succeeded, CMTS_SYNC_OBJECT_EXPIRED if the counter has already reached zero. * @note WARNING: Incrementing a counter after it reached zero leads to UB. */ CMTS_ATTR cmts_result CMTS_CALL cmts_counter_increment(cmts_counter* counter); /** Atomically decrements the value of the counter. If it reaches zero all waiting tasks are resumed. * @param counter A valid pointer to a cmts_counter object. * @return CMTS_OK if the operation succeeded, CMTS_SYNC_OBJECT_EXPIRED if the counter has already reached zero. */ CMTS_ATTR cmts_result CMTS_CALL cmts_counter_decrement(cmts_counter* counter); /** Attempts to wait for the counter to reach zero, putting the current task to sleep. * @param counter A valid pointer to a cmts_counter object. * @return CMTS_OK if the operation succeeded, CMTS_SYNC_OBJECT_EXPIRED if the counter had already reached zero. */ CMTS_ATTR cmts_result CMTS_CALL cmts_counter_await(cmts_counter* counter); /** Attempts to reset the counter, allowing new tasks to await on it. * @param counter A valid pointer to a cmts_counter object. * @return CMTS_OK if the operation succeeded, CMTS_NOT_READY if the counter still has tasks waiting for it to reach zero. */ CMTS_ATTR cmts_result CMTS_CALL cmts_counter_reset(cmts_counter* counter, uint64_t new_start_value); /** Initializes a mutex object. * @param mutex A valid pointer to a cmts_mutex object. */ CMTS_ATTR void CMTS_CALL cmts_mutex_init(cmts_mutex* mutex); /** Checks whether a mutex is locked. * @param mutex A valid pointer to a cmts_mutex object. * @return Whether the mutex is locked. */ CMTS_ATTR cmts_bool CMTS_CALL cmts_mutex_is_locked(const cmts_mutex* mutex); /** Attempts to lock the mutex. * @param mutex A valid pointer to a cmts_mutex object. * @return Whether the mutex was successfully acquired. */ CMTS_ATTR cmts_bool CMTS_CALL cmts_mutex_try_lock(cmts_mutex* mutex); /** Attempts to lock the mutex, otherwise blocks until it becomes available. * @param mutex A valid pointer to a cmts_mutex object. */ CMTS_ATTR void CMTS_CALL cmts_mutex_lock(cmts_mutex* mutex); /** Releases a previously acquired mutex. * @param mutex A valid pointer to a cmts_mutex object. */ CMTS_ATTR void CMTS_CALL cmts_mutex_unlock(cmts_mutex* mutex); /** Begins a CMTS RCU reader critical section. * Until cmts_rcu_read_end is invoked, suspending execution of the current task is forbidden. * @note No-op in release mode. */ CMTS_ATTR void CMTS_CALL cmts_rcu_read_begin(); /** Ends a CMTS RCU reader critical section. * @note No-op in release mode. */ CMTS_ATTR void CMTS_CALL cmts_rcu_read_end(); /** Performs a relatively naive RCU synchronize step. * This function blocks until all RCU reader critical sections have ended. */ CMTS_ATTR void CMTS_CALL cmts_rcu_sync(); /** Retrieves the memory requirements of a CMTS RCU snapshot. * @param out_requirements A valid pointer to a cmts_memory_requirements record, which will be filled with the required size and alignment of an RCU snapshot. */ CMTS_ATTR void CMTS_CALL cmts_rcu_snapshot_requirements(cmts_memory_requirements* out_requirements); /** Fills a buffer with some information of the current state of the scheduler. * @param snapshot_buffer A pointer to the buffer to fill with snapshot information. This buffer must fulfill the requirements specified by cmts_rcu_snapshot_requirements. */ CMTS_ATTR void CMTS_CALL cmts_rcu_snapshot(void* snapshot_buffer); /** Attempts to synchronize using an RCU snaphost. * @param snapshot_buffer A pointer to a valid snapshot buffer. * @param prior_result 0 or the value that a prior invocation of cmts_rcu_try_snapshot_sync returned. * @return The number of worker threads that have finished executing an RCU critical section. If this value matches the number of worker threads then synchronization has finished. */ CMTS_ATTR uint32_t CMTS_CALL cmts_rcu_try_snapshot_sync(const void* snapshot_buffer, uint32_t prior_result); /** Synchronizes using an RCU snaphost. * @param snapshot_buffer A pointer to a valid snapshot buffer. */ CMTS_ATTR void CMTS_CALL cmts_rcu_snapshot_sync(const void* snapshot_buffer); /** Retrieves the memory requirements of a cmts_hazard_context. * @param out_requirements A valid pointer to a cmts_memory_requirements record, which will be filled with the required size and alignment of a cmts_hazard_context. */ CMTS_ATTR void CMTS_CALL cmts_hazard_ptr_requirements(cmts_memory_requirements* out_requirements); /** Initializes a cmts_hazard_context. * @param hctx A valid pointer to a cmts_hazard_context object. * @param buffer A pointer to a block of memory with the required size and alignment. */ CMTS_ATTR void CMTS_CALL cmts_hazard_ptr_init(cmts_hazard_context* hctx, void* buffer); /** Protects the specified pointer. * Until cmts_hazard_ptr_release is invoked, suspending execution of the current task is forbidden. * @param hctx A valid pointer to a cmts_hazard_context object. * @param ptr The pointer to protect. */ CMTS_ATTR void CMTS_CALL cmts_hazard_ptr_protect(cmts_hazard_context* hctx, void* ptr); /** Stops protecting the pointer that was previously passed to cmts_hazard_ptr_protect. * @param hctx A valid pointer to a cmts_hazard_context object. */ CMTS_ATTR void CMTS_CALL cmts_hazard_ptr_release(cmts_hazard_context* hctx); /** Retrieves the current hazard pointer. * @param hctx A valid pointer to a cmts_hazard_context object. */ CMTS_ATTR void* CMTS_CALL cmts_hazard_ptr_get(cmts_hazard_context* hctx); /** Checks whether a pointer is in use by other tasks. * @param hctx A valid pointer to a cmts_hazard_context object. * @param ptr The pointer to check. * @return Whether the specified pointer is reachable by other tasks. */ CMTS_ATTR cmts_bool CMTS_CALL cmts_hazard_ptr_is_unreachable(const cmts_hazard_context* hctx, const void* ptr); /** * @return The number of physical processors. */ CMTS_ATTR size_t CMTS_CALL cmts_processor_count(); /** * @return The index of the current physical processor. */ CMTS_ATTR size_t CMTS_CALL cmts_this_processor_index(); /** * @return The default size of the stack of a task */ CMTS_ATTR size_t CMTS_CALL cmts_default_task_stack_size(); #ifdef CMTS_FORMAT_RESULT /** Formats a CMTS error code. * @param result The error code. * @param out_size Either NULL or a valid pointer to a variable that receives the length of the returned string. * @return A pointer to a read-only null-terminated string with error code as text. */ CMTS_ATTR const CMTS_CHAR* CMTS_CALL cmts_format_result(cmts_result result, size_t* out_size); #endif /** Enables or disables the yield trap. * [DEBUG ONLY] If enabled, any operation that results in the current task being suspended will crash the program. * @param enable Whether to enable the trap. * @return The previous state of the trap. */ CMTS_ATTR cmts_bool CMTS_CALL cmts_ext_debug_enable_yield_trap(cmts_bool enable); /** * @return Whether the CMTS debugger is enabled. Always CMTS_FALSE in release mode. */ CMTS_ATTR cmts_bool CMTS_CALL cmts_ext_debug_enabled(); /** Prints a message to the debugger. * @param message The message information (text, length, severity, etc). */ CMTS_ATTR void CMTS_CALL cmts_ext_debug_write(const cmts_ext_debug_message* message); CMTS_EXTERN_C_END #endif #ifdef CMTS_IMPLEMENTATION #define CMTS_ROUND_CACHE_LINE_SIZE(VALUE) ((VALUE) + (CMTS_CACHE_LINE_SIZE - 1)) & (~(CMTS_CACHE_LINE_SIZE - 1)) #define CMTS_MAKE_HANDLE(INDEX, GENERATION) ((uint64_t)(INDEX) | ((uint64_t)(GENERATION) << 32)) #define CMTS_BREAK_HANDLE(H, OUT_INDEX, OUT_GENERATION) OUT_INDEX = (uint32_t)(H); OUT_GENERATION = (uint32_t)((H) >> 32) #define CMTS_ARRAY_SIZE(ARRAY) (sizeof((ARRAY)) / sizeof(CMTS_CHAR)) #define CMTS_STRING_SIZE(STRING) (CMTS_ARRAY_SIZE(STRING) - 1) #if defined(__GNUC__) || defined(__clang__) #define CMTS_GCC_OR_CLANG #ifdef __alpha__ #define CMTS_ARCH_ALPHA #elif defined(__x86_64__) #define CMTS_ARCH_X64 #elif defined(__arm__) #define CMTS_ARCH_ARM #ifdef __thumb__ #define CMTS_ARCH_ARM_THUMB #endif #elif defined(__i386__) #define CMTS_ARCH_X86 #elif defined(__ia64__) #define CMTS_ARCH_ITANIUM #elif defined(__powerpc__) #define CMTS_ARCH_POWERPC #endif #define CMTS_THREAD_LOCAL(TYPE) __thread TYPE #define CMTS_ALIGNAS(K) __attribute__((aligned(K))) #define CMTS_INLINE_ALWAYS __attribute__((always_inline)) #define CMTS_INLINE_NEVER __attribute__((noinline)) #define CMTS_LIKELY_IF(CONDITION) if (__builtin_expect((CONDITION), 1)) #define CMTS_UNLIKELY_IF(CONDITION) if (__builtin_expect((CONDITION), 0)) #define CMTS_ASSUME(CONDITION) __builtin_assume((CONDITION)) #ifdef CMTS_ARCH_ARM #define CMTS_SPIN_WAIT __yield() #elif defined(CMTS_ARCH_X86) || defined(CMTS_ARCH_X64) #define CMTS_SPIN_WAIT __builtin_ia32_pause() #else #define CMTS_SPIN_WAIT #endif #define CMTS_POPCNT32(MASK) ((uint8_t)__builtin_popcount((MASK))) #define CMTS_POPCNT64(MASK) ((uint8_t)__builtin_popcountll((MASK))) #define CMTS_CLZ32(MASK) ((uint8_t)__builtin_clz((MASK))) #define CMTS_CLZ64(MASK) ((uint8_t)__builtin_clzll((MASK))) #define CMTS_ROL32(MASK, COUNT) (((MASK) << (COUNT)) | ((MASK) >> (32 - (COUNT)))) #define CMTS_ROL64(MASK, COUNT) (((MASK) >> (COUNT)) | ((MASK) << (64 - (COUNT)))) #define CMTS_ROR32(MASK, COUNT) (((MASK) << (COUNT)) | ((MASK) >> (64 - (COUNT)))) #define CMTS_ROR64(MASK, COUNT) (((MASK) >> (COUNT)) | ((MASK) << (32 - (COUNT)))) #define CMTS_ATOMIC(TYPE) TYPE #define CMTS_ACQUIRE_FENCE __atomic_thread_fence(__ATOMIC_ACQUIRE) #define CMTS_RELEASE_FENCE __atomic_thread_fence(__ATOMIC_RELEASE) #define CMTS_ATOMIC_LOAD_RLX_U8(TARGET) (uint8_t)__atomic_load_n(((CMTS_ATOMIC(uint8_t)*)(TARGET)), __ATOMIC_RELAXED) #define CMTS_ATOMIC_LOAD_RLX_U32(TARGET) (uint32_t)__atomic_load_n(((CMTS_ATOMIC(uint32_t)*)(TARGET)), __ATOMIC_RELAXED) #define CMTS_ATOMIC_LOAD_RLX_U64(TARGET) (uint64_t)__atomic_load_n(((CMTS_ATOMIC(uint64_t)*)(TARGET)), __ATOMIC_RELAXED) #define CMTS_ATOMIC_LOAD_ACQ_U8(TARGET) (uint8_t)__atomic_load_n(((CMTS_ATOMIC(uint8_t)*)(TARGET)), __ATOMIC_ACQUIRE) #define CMTS_ATOMIC_LOAD_ACQ_U32(TARGET) (uint32_t)__atomic_load_n(((CMTS_ATOMIC(uint32_t)*)(TARGET)), __ATOMIC_ACQUIRE) #define CMTS_ATOMIC_LOAD_ACQ_U64(TARGET) (uint64_t)__atomic_load_n(((CMTS_ATOMIC(uint64_t)*)(TARGET)), __ATOMIC_ACQUIRE) #define CMTS_ATOMIC_STORE_REL_U8(TARGET, VALUE) __atomic_store_n(((CMTS_ATOMIC(uint8_t)*)(TARGET)), (VALUE), __ATOMIC_RELEASE) #define CMTS_ATOMIC_STORE_REL_U32(TARGET, VALUE) __atomic_store_n(((CMTS_ATOMIC(uint32_t)*)(TARGET)), (VALUE), __ATOMIC_RELEASE) #define CMTS_ATOMIC_STORE_REL_U64(TARGET, VALUE) __atomic_store_n(((CMTS_ATOMIC(uint64_t)*)(TARGET)), (VALUE), __ATOMIC_RELEASE) #define CMTS_ATOMIC_XCHG_ACQ_U32(TARGET, VALUE) (uint32_t)__atomic_exchange_n(((CMTS_ATOMIC(uint32_t)*)(TARGET)), (VALUE), __ATOMIC_ACQUIRE) #define CMTS_ATOMIC_XCHG_ACQ_U64(TARGET, VALUE) (uint64_t)__atomic_exchange_n(((CMTS_ATOMIC(uint64_t)*)(TARGET)), (VALUE), __ATOMIC_ACQUIRE) #define CMTS_ATOMIC_XCHG_REL_U32(TARGET, VALUE) (uint32_t)__atomic_exchange_n(((CMTS_ATOMIC(uint32_t)*)(TARGET)), (VALUE), __ATOMIC_RELEASE) #define CMTS_ATOMIC_XCHG_REL_U64(TARGET, VALUE) (uint64_t)__atomic_exchange_n(((CMTS_ATOMIC(uint64_t)*)(TARGET)), (VALUE), __ATOMIC_RELEASE) #define CMTS_ATOMIC_CMPXCHG_STRONG_ACQ_U8(TARGET, EXPECTED, VALUE) __atomic_compare_exchange_n(((CMTS_ATOMIC(uint8_t)*)(TARGET)), (EXPECTED), (VALUE), 0, __ATOMIC_ACQUIRE, __ATOMIC_RELAXED) #define CMTS_ATOMIC_CMPXCHG_STRONG_ACQ_U32(TARGET, EXPECTED, VALUE) __atomic_compare_exchange_n(((CMTS_ATOMIC(uint32_t)*)(TARGET)), (EXPECTED), (VALUE), 0, __ATOMIC_ACQUIRE, __ATOMIC_RELAXED) #define CMTS_ATOMIC_CMPXCHG_STRONG_ACQ_U64(TARGET, EXPECTED, VALUE) __atomic_compare_exchange_n(((CMTS_ATOMIC(uint64_t)*)(TARGET)), (EXPECTED), (VALUE), 0, __ATOMIC_ACQUIRE, __ATOMIC_RELAXED) #define CMTS_ATOMIC_CMPXCHG_STRONG_REL_U8(TARGET, EXPECTED, VALUE) __atomic_compare_exchange_n(((CMTS_ATOMIC(uint8_t)*)(TARGET)), (EXPECTED), (VALUE), 0, __ATOMIC_RELEASE, __ATOMIC_RELAXED) #define CMTS_ATOMIC_CMPXCHG_STRONG_REL_U32(TARGET, EXPECTED, VALUE) __atomic_compare_exchange_n(((CMTS_ATOMIC(uint32_t)*)(TARGET)), (EXPECTED), (VALUE), 0, __ATOMIC_RELEASE, __ATOMIC_RELAXED) #define CMTS_ATOMIC_CMPXCHG_STRONG_REL_U64(TARGET, EXPECTED, VALUE) __atomic_compare_exchange_n(((CMTS_ATOMIC(uint64_t)*)(TARGET)), (EXPECTED), (VALUE), 0, __ATOMIC_RELEASE, __ATOMIC_RELAXED) #define CMTS_ATOMIC_CMPXCHG_ACQ_U8(TARGET, EXPECTED, VALUE) __atomic_compare_exchange_n(((CMTS_ATOMIC(uint8_t)*)(TARGET)), (EXPECTED), (VALUE), 1, __ATOMIC_ACQUIRE, __ATOMIC_RELAXED) #define CMTS_ATOMIC_CMPXCHG_ACQ_U32(TARGET, EXPECTED, VALUE) __atomic_compare_exchange_n(((CMTS_ATOMIC(uint32_t)*)(TARGET)), (EXPECTED), (VALUE), 1, __ATOMIC_ACQUIRE, __ATOMIC_RELAXED) #define CMTS_ATOMIC_CMPXCHG_ACQ_U64(TARGET, EXPECTED, VALUE) __atomic_compare_exchange_n(((CMTS_ATOMIC(uint64_t)*)(TARGET)), (EXPECTED), (VALUE), 1, __ATOMIC_ACQUIRE, __ATOMIC_RELAXED) #define CMTS_ATOMIC_CMPXCHG_REL_U8(TARGET, EXPECTED, VALUE) __atomic_compare_exchange_n(((CMTS_ATOMIC(uint8_t)*)(TARGET)), (EXPECTED), (VALUE), 1, __ATOMIC_RELEASE, __ATOMIC_RELAXED) #define CMTS_ATOMIC_CMPXCHG_REL_U32(TARGET, EXPECTED, VALUE) __atomic_compare_exchange_n(((CMTS_ATOMIC(uint32_t)*)(TARGET)), (EXPECTED), (VALUE), 1, __ATOMIC_RELEASE, __ATOMIC_RELAXED) #define CMTS_ATOMIC_CMPXCHG_REL_U64(TARGET, EXPECTED, VALUE) __atomic_compare_exchange_n(((CMTS_ATOMIC(uint64_t)*)(TARGET)), (EXPECTED), (VALUE), 1, __ATOMIC_RELEASE, __ATOMIC_RELAXED) #define CMTS_ATOMIC_INCREMENT_ACQ_U32(TARGET) __atomic_fetch_add(((CMTS_ATOMIC(uint32_t)*)(TARGET)), UINT32_C(1), __ATOMIC_ACQUIRE) #define CMTS_ATOMIC_INCREMENT_ACQ_U64(TARGET) __atomic_fetch_add(((CMTS_ATOMIC(uint64_t)*)(TARGET)), UINT64_C(1), __ATOMIC_ACQUIRE) #define CMTS_ATOMIC_INCREMENT_REL_U32(TARGET) __atomic_fetch_add(((CMTS_ATOMIC(uint32_t)*)(TARGET)), UINT32_C(1), __ATOMIC_RELEASE) #define CMTS_ATOMIC_INCREMENT_REL_U64(TARGET) __atomic_fetch_add(((CMTS_ATOMIC(uint64_t)*)(TARGET)), UINT64_C(1), __ATOMIC_RELEASE) #define CMTS_ATOMIC_DECREMENT_ACQ_U32(TARGET) __atomic_fetch_sub(((CMTS_ATOMIC(uint32_t)*)(TARGET)), UINT32_C(1), __ATOMIC_ACQUIRE) #define CMTS_ATOMIC_DECREMENT_ACQ_U64(TARGET) __atomic_fetch_sub(((CMTS_ATOMIC(uint64_t)*)(TARGET)), UINT64_C(1), __ATOMIC_ACQUIRE) #define CMTS_ATOMIC_DECREMENT_REL_U32(TARGET) __atomic_fetch_sub(((CMTS_ATOMIC(uint32_t)*)(TARGET)), UINT32_C(1), __ATOMIC_RELEASE) #define CMTS_ATOMIC_DECREMENT_REL_U64(TARGET) __atomic_fetch_sub(((CMTS_ATOMIC(uint64_t)*)(TARGET)), UINT64_C(1), __ATOMIC_RELEASE) #elif defined(_MSC_VER) || defined(_MSVC_LANG) #define CMTS_MSVC #ifdef _M_ALPHA #define CMTS_ARCH_ALPHA #elif defined(_M_AMD64) #define CMTS_ARCH_X64 #elif defined(_M_ARM) || defined(_M_ARM64) #define CMTS_ARCH_ARM #ifdef _M_ARM64 #define CMTS_ARCH_ARM64 #endif #ifdef _M_ARMT #define CMTS_ARCH_ARM_THUMB #endif #elif defined(_M_IX86) #define CMTS_ARCH_X86 #elif defined(_M_IA64) #define CMTS_ARCH_ITANIUM #elif defined(_M_PPC) #define CMTS_ARCH_POWERPC #endif #include <intrin.h> #define CMTS_THREAD_LOCAL(TYPE) __declspec(thread) TYPE #define CMTS_ALIGNAS(K) __declspec(align(K)) #define CMTS_INLINE_ALWAYS __forceinline #define CMTS_INLINE_NEVER __declspec(noinline) #define CMTS_LIKELY_IF(CONDITION) if ((CONDITION)) #define CMTS_UNLIKELY_IF(CONDITION) if ((CONDITION)) #define CMTS_ASSUME(CONDITION) __assume((CONDITION)) #ifdef CMTS_ARCH_ARM #define CMTS_CLZ32(MASK) ((uint8_t)_CountLeadingZeros((MASK))) #define CMTS_CLZ64(MASK) ((uint8_t)_CountLeadingZeros64((MASK))) #ifndef CMTS_ARCH_ARM64 #define CMTS_POPCNT32(MASK) ((uint8_t)_CountOneBits((MASK))) #define CMTS_POPCNT64(MASK) ((uint8_t)_CountOneBits64((MASK))) #else #define CMTS_POPCNT32(MASK) ((uint8_t)(neon_cnt(__n64{(MASK)}).n64_u64[0])) #define CMTS_POPCNT64(MASK) ((uint8_t)(neon_cnt(__n64{(MASK)}).n64_u64[0])) #endif #else #define CMTS_CLZ32(MASK) ((uint8_t)__lzcnt((MASK))) #define CMTS_CLZ64(MASK) ((uint8_t)__lzcnt64((MASK))) #define CMTS_POPCNT32(MASK) ((uint8_t)__popcnt((MASK))) #define CMTS_POPCNT64(MASK) ((uint8_t)__popcnt64((MASK))) #endif #define CMTS_ROL32(MASK, COUNT) (uint32_t)_rotl((MASK), (COUNT)) #define CMTS_ROL64(MASK, COUNT) (uint64_t)_rotl64((MASK), (COUNT)) #define CMTS_ROR32(MASK, COUNT) (uint32_t)_rotr((MASK), (COUNT)) #define CMTS_ROR64(MASK, COUNT) (uint64_t)_rotr64((MASK), (COUNT)) #ifdef CMTS_ARCH_ARM #define CTMS_MEMORY_BARRIER __dmb(0xb) #else #define CTMS_MEMORY_BARRIER #endif #ifdef CMTS_ARCH_ARM #define CMTS_SPIN_WAIT __yield() #define CMTS_MSVC_ATOMIC_ACQ_SUFFIX(NAME) NAME##_acq #define CMTS_MSVC_ATOMIC_REL_SUFFIX(NAME) NAME##_acq #elif defined(CMTS_ARCH_X86) || defined(CMTS_ARCH_X64) #define CMTS_SPIN_WAIT _mm_pause() #define CMTS_MSVC_ATOMIC_ACQ_SUFFIX(NAME) NAME #define CMTS_MSVC_ATOMIC_REL_SUFFIX(NAME) NAME #else #define CMTS_SPIN_WAIT #define CMTS_MSVC_ATOMIC_ACQ_SUFFIX(NAME) NAME #define CMTS_MSVC_ATOMIC_REL_SUFFIX(NAME) NAME #endif #define CMTS_ATOMIC(TYPE) volatile TYPE CMTS_INLINE_ALWAYS static uint8_t cmts_msvc_atomic_load_u8(CMTS_ATOMIC(void)* source) { uint8_t r = (uint8_t)__iso_volatile_load8((const volatile char*)source); _ReadWriteBarrier(); return r; } CMTS_INLINE_ALWAYS static uint32_t cmts_msvc_atomic_load_u32(CMTS_ATOMIC(void)* source) { uint32_t r = (uint32_t)__iso_volatile_load32((const volatile int*)source); _ReadWriteBarrier(); return r; } CMTS_INLINE_ALWAYS static uint64_t cmts_msvc_atomic_load_u64(CMTS_ATOMIC(void)* source) { uint64_t r = (uint64_t)__iso_volatile_load64((const volatile long long*)source); _ReadWriteBarrier(); return r; } #define CMTS_ACQUIRE_FENCE CTMS_MEMORY_BARRIER; _ReadWriteBarrier() #define CMTS_RELEASE_FENCE CMTS_ACQUIRE_FENCE #define CMTS_ATOMIC_LOAD_RLX_U8(TARGET) (uint8_t)__iso_volatile_load8((const volatile char*)(TARGET)) #define CMTS_ATOMIC_LOAD_RLX_U32(TARGET) (uint32_t)__iso_volatile_load32((const volatile int*)(TARGET)) #define CMTS_ATOMIC_LOAD_RLX_U64(TARGET) (uint64_t)__iso_volatile_load64((const volatile long long*)(TARGET)) #define CMTS_ATOMIC_LOAD_ACQ_U8(TARGET) cmts_msvc_atomic_load_u8((TARGET)) #define CMTS_ATOMIC_LOAD_ACQ_U32(TARGET) cmts_msvc_atomic_load_u32((TARGET)) #define CMTS_ATOMIC_LOAD_ACQ_U64(TARGET) cmts_msvc_atomic_load_u64((TARGET)) #define CMTS_ATOMIC_STORE_REL_U8(TARGET, VALUE) CMTS_RELEASE_FENCE; __iso_volatile_store8((volatile char*)(TARGET), (char)(VALUE)) #define CMTS_ATOMIC_STORE_REL_U32(TARGET, VALUE) CMTS_RELEASE_FENCE; __iso_volatile_store32((volatile int*)(TARGET), (int)(VALUE)) #define CMTS_ATOMIC_STORE_REL_U64(TARGET, VALUE) CMTS_RELEASE_FENCE; __iso_volatile_store64((volatile long long*)(TARGET), (long long)(VALUE)) #define CMTS_ATOMIC_XCHG_ACQ_U32(TARGET, VALUE) (uint32_t)CMTS_MSVC_ATOMIC_ACQ_SUFFIX(_InterlockedExchange)((volatile long*)(TARGET), (long)(VALUE)) #define CMTS_ATOMIC_XCHG_ACQ_U64(TARGET, VALUE) (uint64_t)CMTS_MSVC_ATOMIC_ACQ_SUFFIX(_InterlockedExchange64)((volatile long long*)(TARGET), (long long)(VALUE)) #define CMTS_ATOMIC_XCHG_REL_U32(TARGET, VALUE) (uint32_t)CMTS_MSVC_ATOMIC_REL_SUFFIX(_InterlockedExchange)((volatile long*)(TARGET), (long)(VALUE)) #define CMTS_ATOMIC_XCHG_REL_U64(TARGET, VALUE) (uint64_t)CMTS_MSVC_ATOMIC_REL_SUFFIX(_InterlockedExchange64)((volatile long long*)(TARGET), (long long)(VALUE)) #define CMTS_ATOMIC_CMPXCHG_STRONG_ACQ_U8(TARGET, EXPECTED, VALUE) (CMTS_MSVC_ATOMIC_ACQ_SUFFIX(_InterlockedCompareExchange8)((volatile char*)(TARGET), (char)(VALUE), *(char*)(EXPECTED)) == *(char*)(EXPECTED)) #define CMTS_ATOMIC_CMPXCHG_STRONG_ACQ_U32(TARGET, EXPECTED, VALUE) (CMTS_MSVC_ATOMIC_ACQ_SUFFIX(_InterlockedCompareExchange)((volatile long*)(TARGET), (long)(VALUE), *(long*)(EXPECTED)) == *(long*)(EXPECTED)) #define CMTS_ATOMIC_CMPXCHG_STRONG_ACQ_U64(TARGET, EXPECTED, VALUE) (CMTS_MSVC_ATOMIC_ACQ_SUFFIX(_InterlockedCompareExchange64)((volatile long long*)(TARGET), (long long)(VALUE), *(long long*)(EXPECTED)) == *(long long*)(EXPECTED)) #define CMTS_ATOMIC_CMPXCHG_STRONG_REL_U8(TARGET, EXPECTED, VALUE) (CMTS_MSVC_ATOMIC_REL_SUFFIX(_InterlockedCompareExchange8)((volatile char*)(TARGET), (char)(VALUE), *(char*)(EXPECTED)) == *(char*)(EXPECTED)) #define CMTS_ATOMIC_CMPXCHG_STRONG_REL_U32(TARGET, EXPECTED, VALUE) (CMTS_MSVC_ATOMIC_REL_SUFFIX(_InterlockedCompareExchange)((volatile long*)(TARGET), (long)(VALUE), *(long*)(EXPECTED)) == *(long*)(EXPECTED)) #define CMTS_ATOMIC_CMPXCHG_STRONG_REL_U64(TARGET, EXPECTED, VALUE) (CMTS_MSVC_ATOMIC_REL_SUFFIX(_InterlockedCompareExchange64)((volatile long long*)(TARGET), (long long)(VALUE), *(long long*)(EXPECTED)) == *(long long*)(EXPECTED)) #define CMTS_ATOMIC_CMPXCHG_ACQ_U8(TARGET, EXPECTED, VALUE) (CMTS_MSVC_ATOMIC_ACQ_SUFFIX(_InterlockedCompareExchange8)((volatile char*)(TARGET), (char)(VALUE), *(char*)(EXPECTED)) == *(char*)(EXPECTED)) #define CMTS_ATOMIC_CMPXCHG_ACQ_U32(TARGET, EXPECTED, VALUE) (CMTS_MSVC_ATOMIC_ACQ_SUFFIX(_InterlockedCompareExchange)((volatile long*)(TARGET), (long)(VALUE), *(long*)(EXPECTED)) == *(long*)(EXPECTED)) #define CMTS_ATOMIC_CMPXCHG_ACQ_U64(TARGET, EXPECTED, VALUE) (CMTS_MSVC_ATOMIC_ACQ_SUFFIX(_InterlockedCompareExchange64)((volatile long long*)(TARGET), (long long)(VALUE), *(long long*)(EXPECTED)) == *(long long*)(EXPECTED)) #define CMTS_ATOMIC_CMPXCHG_REL_U8(TARGET, EXPECTED, VALUE) (CMTS_MSVC_ATOMIC_REL_SUFFIX(_InterlockedCompareExchange8)((volatile char*)(TARGET), (char)(VALUE), *(char*)(EXPECTED)) == *(char*)(EXPECTED)) #define CMTS_ATOMIC_CMPXCHG_REL_U32(TARGET, EXPECTED, VALUE) (CMTS_MSVC_ATOMIC_REL_SUFFIX(_InterlockedCompareExchange)((volatile long*)(TARGET), (long)(VALUE), *(long*)(EXPECTED)) == *(long*)(EXPECTED)) #define CMTS_ATOMIC_CMPXCHG_REL_U64(TARGET, EXPECTED, VALUE) (CMTS_MSVC_ATOMIC_REL_SUFFIX(_InterlockedCompareExchange64)((volatile long long*)(TARGET), (long long)(VALUE), *(long long*)(EXPECTED)) == *(long long*)(EXPECTED)) #define CMTS_ATOMIC_INCREMENT_ACQ_U32(TARGET) ((uint32_t)(CMTS_MSVC_ATOMIC_ACQ_SUFFIX(_InterlockedIncrement)((volatile long*)(TARGET))) - 1) #define CMTS_ATOMIC_INCREMENT_ACQ_U64(TARGET) ((uint64_t)(CMTS_MSVC_ATOMIC_ACQ_SUFFIX(_InterlockedIncrement64)((volatile long long*)(TARGET))) - 1) #define CMTS_ATOMIC_INCREMENT_REL_U32(TARGET) ((uint32_t)(CMTS_MSVC_ATOMIC_REL_SUFFIX(_InterlockedIncrement)((volatile long*)(TARGET))) - 1) #define CMTS_ATOMIC_INCREMENT_REL_U64(TARGET) ((uint64_t)(CMTS_MSVC_ATOMIC_REL_SUFFIX(_InterlockedIncrement64)((volatile long long*)(TARGET))) - 1) #define CMTS_ATOMIC_DECREMENT_ACQ_U32(TARGET) ((uint32_t)(CMTS_MSVC_ATOMIC_ACQ_SUFFIX(_InterlockedDecrement)((volatile long*)(TARGET))) + 1) #define CMTS_ATOMIC_DECREMENT_ACQ_U64(TARGET) ((uint64_t)(CMTS_MSVC_ATOMIC_ACQ_SUFFIX(_InterlockedDecrement64)((volatile long long*)(TARGET))) + 1) #define CMTS_ATOMIC_DECREMENT_REL_U32(TARGET) ((uint32_t)(CMTS_MSVC_ATOMIC_REL_SUFFIX(_InterlockedDecrement)((volatile long*)(TARGET))) + 1) #define CMTS_ATOMIC_DECREMENT_REL_U64(TARGET) ((uint64_t)(CMTS_MSVC_ATOMIC_REL_SUFFIX(_InterlockedDecrement64)((volatile long long*)(TARGET))) + 1) #endif #define CMTS_NON_ATOMIC_LOAD_U8(TARGET) *(const uint8_t*)(TARGET) #define CMTS_NON_ATOMIC_LOAD_U32(TARGET) *(const uint32_t*)(TARGET) #define CMTS_NON_ATOMIC_LOAD_U64(TARGET) *(const uint64_t*)(TARGET) #define CMTS_NON_ATOMIC_STORE_U8(TARGET, VALUE) (void)(*(uint8_t*)(TARGET) = (VALUE)) #define CMTS_NON_ATOMIC_STORE_U32(TARGET, VALUE) (void)(*(uint32_t*)(TARGET) = (VALUE)) #define CMTS_NON_ATOMIC_STORE_U64(TARGET, VALUE) (void)(*(uint64_t*)(TARGET) = (VALUE)) #if UINTPTR_MAX == UINT32_MAX #define CMTS_ATOMIC_LOAD_ACQ_UPTR CMTS_ATOMIC_LOAD_ACQ_U32 #define CMTS_ATOMIC_STORE_REL_UPTR CMTS_ATOMIC_STORE_REL_U32 #define CMTS_ATOMIC_XCHG_ACQ_UPTR CMTS_ATOMIC_XCHG_ACQ_U32 #define CMTS_ATOMIC_XCHG_REL_UPTR CMTS_ATOMIC_XCHG_REL_U32 #define CMTS_ATOMIC_CMPXCHG_STRONG_ACQ_UPTR CMTS_ATOMIC_CMPXCHG_STRONG_ACQ_U32 #define CMTS_ATOMIC_CMPXCHG_STRONG_REL_UPTR CMTS_ATOMIC_CMPXCHG_STRONG_REL_U32 #else #define CMTS_ATOMIC_LOAD_ACQ_UPTR CMTS_ATOMIC_LOAD_ACQ_U64 #define CMTS_ATOMIC_STORE_REL_UPTR CMTS_ATOMIC_STORE_REL_U64 #define CMTS_ATOMIC_XCHG_ACQ_UPTR CMTS_ATOMIC_XCHG_ACQ_U64 #define CMTS_ATOMIC_XCHG_REL_UPTR CMTS_ATOMIC_XCHG_REL_U64 #define CMTS_ATOMIC_CMPXCHG_STRONG_ACQ_UPTR CMTS_ATOMIC_CMPXCHG_STRONG_ACQ_U64 #define CMTS_ATOMIC_CMPXCHG_STRONG_REL_UPTR CMTS_ATOMIC_CMPXCHG_STRONG_REL_U64 #endif #define CMTS_SHARED_ATTR CMTS_ALIGNAS(CMTS_CACHE_LINE_SIZE) #define CMTS_SPIN_LOOP for (;; CMTS_SPIN_WAIT) #if defined(_DEBUG) || defined(NDEBUG) #define CMTS_DEBUG #include <assert.h> #define CMTS_ASSERT(CONDITION) assert(CONDITION) #define CMTS_INVARIANT(CONDITION) CMTS_ASSERT(CONDITION) #else #define CMTS_ASSERT(CONDITION) #define CMTS_INVARIANT(CONDITION) CMTS_ASSUME(CONDITION) #endif #ifdef CMTS_DEBUG static void* debugger_context; static cmts_fn_debugger_message debugger_callback; CMTS_INLINE_NEVER static void cmts_debug_message(cmts_ext_debug_message_severity severity, const CMTS_CHAR * text, size_t size) { CMTS_UNLIKELY_IF(debugger_callback == NULL) return; cmts_ext_debug_message message; message.next_ext = NULL; message.message = text; message.message_length = size; message.severity = severity; debugger_callback(debugger_context, &message); } #define CMTS_REPORT_INFO(MESSAGE) cmts_debug_message(CMTS_EXT_DEBUGGER_MESSAGE_SEVERITY_INFO, MESSAGE, CMTS_STRING_SIZE(MESSAGE)) #define CMTS_REPORT_WARNING(MESSAGE) cmts_debug_message(CMTS_EXT_DEBUGGER_MESSAGE_SEVERITY_WARNING, MESSAGE, CMTS_STRING_SIZE(MESSAGE)) #define CMTS_REPORT_ERROR(MESSAGE) cmts_debug_message(CMTS_EXT_DEBUGGER_MESSAGE_SEVERITY_ERROR, MESSAGE, CMTS_STRING_SIZE(MESSAGE)) #endif #ifdef _WIN32 #define CMTS_TARGET_WINDOWS #include <Windows.h> #include <bcrypt.h> typedef HANDLE thread_type; typedef DWORD thread_return_type; #define CMTS_THREAD_CALLING_CONVENTION __stdcall #if defined(CMTS_NO_BUSY_WAIT) || defined(CMTS_HYBRID_MUTEX) typedef BOOL (WINAPI *WaitOnAddress_t)(volatile VOID* Address, PVOID CompareAddress, SIZE_T AddressSize, DWORD dwMilliseconds); typedef VOID (WINAPI *WakeByAddressSingle_t)(PVOID Address); static HMODULE sync_library; static WaitOnAddress_t wait_on_address; static WakeByAddressSingle_t wake_by_address_single; #endif static uint64_t qpc_frequency; CMTS_INLINE_ALWAYS static cmts_bool cmts_os_init() { LARGE_INTEGER k; (void)QueryPerformanceFrequency(&k); qpc_frequency = k.QuadPart; #if defined(CMTS_NO_BUSY_WAIT) || defined(CMTS_HYBRID_MUTEX) sync_library = GetModuleHandle(TEXT("Synchronization.lib")); CMTS_UNLIKELY_IF(sync_library == NULL) { sync_library = GetModuleHandle(TEXT("API-MS-Win-Core-Synch-l1-2-0.dll")); CMTS_REPORT_ERROR("\"GetModuleHandle(\"Synchronization.lib\")\" returned NULL. Attempting the same with \"API-MS-Win-Core-Synch-l1-2-0.dll\"."); CMTS_UNLIKELY_IF(sync_library == NULL) { CMTS_REPORT_ERROR("\"GetModuleHandle(\"API-MS-Win-Core-Synch-l1-2-0.dll\")\" returned NULL. Library initialization failed."); return CMTS_FALSE; } wait_on_address = (WaitOnAddress_t)GetProcAddress(sync_library, "WaitOnAddress"); CMTS_UNLIKELY_IF(wait_on_address == NULL) return CMTS_FALSE; wake_by_address_single = (WakeByAddressSingle_t)GetProcAddress(sync_library, "WakeByAddressSingle"); CMTS_UNLIKELY_IF(wake_by_address_single == NULL) return CMTS_FALSE; } #endif return CMTS_TRUE; } CMTS_INLINE_ALWAYS static void* cmts_os_malloc(size_t size) { return VirtualAlloc(NULL, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); } CMTS_INLINE_ALWAYS static cmts_bool cmts_os_free(void* ptr, size_t size) { return VirtualFree(ptr, 0, MEM_RELEASE); } CMTS_INLINE_ALWAYS static cmts_result cmts_os_init_threads(thread_type* threads, size_t count, size_t stack_size, LPTHREAD_START_ROUTINE function) { GROUP_AFFINITY desired, prior; size_t i; (void)memset(desired.Reserved, 0, sizeof(desired.Reserved)); for (i = 0; i != count; ++i) { threads[i] = CreateThread(NULL, stack_size, function, (LPVOID)i, CREATE_SUSPENDED, NULL); CMTS_UNLIKELY_IF(threads[i] == NULL) return CMTS_ERROR_THREAD_CREATION; desired.Group = (WORD)(i >> 6); desired.Mask = 1ULL << ((uint8_t)i & 63); CMTS_UNLIKELY_IF(!SetThreadGroupAffinity(threads[i], &desired, &prior)) return CMTS_ERROR_THREAD_AFFINITY; CMTS_UNLIKELY_IF(ResumeThread(threads[i]) == MAXDWORD) return CMTS_ERROR_RESUME_THREAD; } return CMTS_OK; } CMTS_INLINE_ALWAYS static cmts_result cmts_os_init_threads_custom(thread_type* threads, uint_fast32_t count, size_t stack_size, LPTHREAD_START_ROUTINE function, const uint32_t* affinities) { GROUP_AFFINITY desired, prior; uint32_t i; (void)memset(desired.Reserved, 0, sizeof(desired.Reserved)); for (i = 0; i != count; ++i) { threads[i] = CreateThread(NULL, stack_size, function, (LPVOID)(size_t)i, CREATE_SUSPENDED, NULL); CMTS_UNLIKELY_IF(threads[i] == NULL) return CMTS_ERROR_THREAD_CREATION; desired.Group = affinities[i] >> 6; desired.Mask = 1ULL << (affinities[i] & 63); CMTS_UNLIKELY_IF(!SetThreadGroupAffinity(threads[i], &desired, &prior)) return CMTS_ERROR_THREAD_AFFINITY; CMTS_UNLIKELY_IF(ResumeThread(threads[i]) == MAXDWORD) return CMTS_ERROR_RESUME_THREAD; } return CMTS_OK; } CMTS_INLINE_ALWAYS static cmts_bool cmts_os_await_threads(thread_type* threads, uint_fast32_t count) { return (cmts_bool)(WaitForMultipleObjects(count, threads, TRUE, INFINITE) == WAIT_OBJECT_0); } CMTS_INLINE_ALWAYS static void cmts_os_exit_thread(uint_fast32_t code) { ExitThread(code); } CMTS_INLINE_ALWAYS static cmts_bool cmts_os_pause_threads(thread_type* threads, uint_fast32_t count) { size_t i; for (i = 0; i != count; ++i) CMTS_UNLIKELY_IF(SuspendThread(threads[i]) == MAXDWORD) return CMTS_FALSE; return CMTS_TRUE; } CMTS_INLINE_ALWAYS static cmts_bool cmts_os_resume_threads(thread_type* threads, uint_fast32_t count) { size_t i; for (i = 0; i != count; ++i) CMTS_UNLIKELY_IF(ResumeThread(threads[i]) == MAXDWORD) return CMTS_FALSE; return CMTS_TRUE; } CMTS_INLINE_ALWAYS static cmts_bool cmts_os_terminate_threads(thread_type* threads, uint_fast32_t count) { size_t i; for (i = 0; i != count; ++i) CMTS_UNLIKELY_IF(!TerminateThread(threads[i], MAXDWORD)) return CMTS_FALSE; return CMTS_TRUE; } CMTS_INLINE_ALWAYS static void cmts_os_futex_signal(volatile void* ptr) { #if defined(CMTS_NO_BUSY_WAIT) || defined(CMTS_HYBRID_MUTEX) wake_by_address_single((PVOID)ptr); #endif } CMTS_INLINE_ALWAYS static void cmts_os_futex_await(volatile void* ptr, void* prior, uint_fast8_t size) { #if defined(CMTS_NO_BUSY_WAIT) || defined(CMTS_HYBRID_MUTEX) (void)wait_on_address(ptr, prior, size, INFINITE); #endif } CMTS_INLINE_ALWAYS static uint64_t cmts_os_time() { LARGE_INTEGER k; (void)QueryPerformanceCounter(&k); return k.QuadPart; } CMTS_INLINE_ALWAYS static uint64_t cmts_os_time_ns(uint64_t timestamp) { return timestamp / qpc_frequency; } CMTS_INLINE_ALWAYS static cmts_bool cmts_os_csprng(void* out, size_t out_size) { typedef NTSTATUS(WINAPI* BCryptGenRandom_T)(BCRYPT_ALG_HANDLE, PUCHAR, ULONG, ULONG); HMODULE lib; lib = GetModuleHandle(TEXT("Bcrypt.lib")); CMTS_UNLIKELY_IF(lib == NULL) lib = GetModuleHandle(TEXT("Bcrypt.dll")); CMTS_UNLIKELY_IF(lib == NULL) return CMTS_FALSE; return BCRYPT_SUCCESS(((BCryptGenRandom_T)GetProcAddress(lib, "BCryptGenRandom"))(NULL, (PUCHAR)out, (ULONG)out_size, (ULONG)BCRYPT_USE_SYSTEM_PREFERRED_RNG)); } typedef PVOID cmts_context; CMTS_INLINE_ALWAYS static cmts_bool cmts_context_init(cmts_context* ctx, cmts_fn_task function, void* param, size_t stack_size) { CMTS_INVARIANT(function != NULL); CMTS_INVARIANT(param != NULL); *ctx = CreateFiberEx(stack_size, stack_size, FIBER_FLAG_FLOAT_SWITCH, (LPFIBER_START_ROUTINE)function, param); return *ctx != NULL; return *ctx != NULL; } CMTS_INLINE_ALWAYS static cmts_bool cmts_context_is_valid(cmts_context* ctx) { return *ctx != NULL; } CMTS_INLINE_ALWAYS static void cmts_context_switch(cmts_context* from, cmts_context* to) { SwitchToFiber(*to); } CMTS_INLINE_ALWAYS static void cmts_context_wipe(cmts_context* ctx) { *ctx = NULL; } CMTS_INLINE_ALWAYS static void cmts_context_delete(cmts_context* ctx) { CMTS_INVARIANT(*ctx != NULL); DeleteFiber(*ctx); cmts_context_wipe(ctx); } #endif enum { CMTS_TASK_STATE_INACTIVE, CMTS_TASK_STATE_RUNNING, CMTS_TASK_STATE_GOING_TO_SLEEP, CMTS_TASK_STATE_SLEEPING, }; typedef uint32_t(*cmts_fn_remainder)(uint32_t); typedef struct cmts_ext_header { const cmts_ext_header* next; cmts_ext_type type; } cmts_ext_header; typedef struct cmts_romu2jr { uint64_t x, y; } cmts_romu2jr; typedef struct cmts_index_generation_pair { uint32_t index, generation; } cmts_index_generation_pair; typedef union cmts_index_generation_pair_union { cmts_index_generation_pair pair; uint64_t packed; } cmts_index_generation_pair_union; typedef struct cmts_task_state { cmts_context ctx; cmts_fn_task fn; void* param; void* sync_object; uint32_t next; uint32_t generation; uint32_t thread_affinity; uint8_t priority; uint8_t sync_type; CMTS_ATOMIC(uint8_t) state; } cmts_task_state; typedef struct cmts_task_queue { uint32_t tail; CMTS_ATOMIC(uint32_t)* values; CMTS_SHARED_ATTR CMTS_ATOMIC(uint32_t) count; CMTS_SHARED_ATTR CMTS_ATOMIC(uint32_t) head; } cmts_task_queue; typedef struct cmts_wait_queue_data { uint32_t head, tail; } cmts_wait_queue_data; typedef union cmts_wait_queue_union { uint64_t packed; cmts_wait_queue_data queue; } cmts_wait_queue_union; typedef CMTS_ATOMIC(uint32_t) cmts_fence_data; typedef CMTS_ATOMIC(uint64_t) cmts_event_data; typedef CMTS_ATOMIC(uint32_t) cmts_mutex_data; typedef struct cmts_counter_data { CMTS_ATOMIC(uint64_t) queue; CMTS_ATOMIC(uint64_t) value; } cmts_counter_data; typedef struct cmts_cache_aligned_atomic_counter { CMTS_SHARED_ATTR CMTS_ATOMIC(uint32_t) value; } cmts_cache_aligned_atomic_counter; enum { CMTS_SCHEDULER_STATE_OFFLINE, CMTS_SCHEDULER_STATE_ONLINE, CMTS_SCHEDULER_STATE_PAUSED, }; CMTS_SHARED_ATTR static CMTS_ATOMIC(uint8_t) lib_lock; CMTS_SHARED_ATTR static CMTS_ATOMIC(uint8_t) init_state; CMTS_SHARED_ATTR static CMTS_ATOMIC(uint8_t) scheduler_state; CMTS_SHARED_ATTR static CMTS_ATOMIC(uint8_t) should_continue; CMTS_SHARED_ATTR static CMTS_ATOMIC(uint64_t) task_pool_flist; CMTS_SHARED_ATTR static CMTS_ATOMIC(uint32_t) task_pool_bump; static cmts_task_queue* queues[CMTS_MAX_PRIORITY]; static cmts_task_state* task_pool; static thread_type* threads; static cmts_cache_aligned_atomic_counter* thread_generation_counters; static uint32_t thread_count; static uint32_t queue_capacity; static uint32_t queue_capacity_mask; static uint32_t task_pool_capacity; static uint32_t thread_remainder_param; static uint32_t task_stack_size; static size_t thread_stack_size; static cmts_fn_remainder thread_remainder; #ifdef CMTS_DEBUG static CMTS_THREAD_LOCAL(uint8_t) yield_trap_flag; #endif static CMTS_THREAD_LOCAL(cmts_context) root_task; static CMTS_THREAD_LOCAL(size_t) yield_trap_depth; static CMTS_THREAD_LOCAL(uint32_t) thread_index; static CMTS_THREAD_LOCAL(uint32_t) task_index; static CMTS_THREAD_LOCAL(cmts_romu2jr) prng; static CMTS_THREAD_LOCAL(uint64_t) prng_last_seed; CMTS_INLINE_NEVER static void cmts_finalize_check_noinline() { if (cmts_is_task()) { if (cmts_context_is_valid(&task_pool[task_index].ctx)) cmts_context_wipe(&task_pool[task_index].ctx); cmts_os_exit_thread(0); } } CMTS_INLINE_ALWAYS static void cmts_finalize_check() { CMTS_UNLIKELY_IF(!CMTS_ATOMIC_LOAD_ACQ_U8(&should_continue)) cmts_finalize_check_noinline(); } CMTS_INLINE_ALWAYS static uint32_t cmts_remainder_range_reduce(uint32_t index, uint32_t range, uint8_t shift) { return (uint32_t)(((uint64_t)index * (uint64_t)range) >> 32); } CMTS_INLINE_ALWAYS static uint32_t cmts_thread_remainder_pow2(uint32_t index) { return index & thread_remainder_param; } CMTS_INLINE_ALWAYS static uint32_t cmts_thread_remainder_range_reduce(uint32_t index) { return cmts_remainder_range_reduce(index, thread_count, (uint8_t)thread_remainder_param); } CMTS_INLINE_ALWAYS static void cmts_romu2jr_reseed(cmts_romu2jr* state) { uint64_t buffer[2]; (void)memset(buffer, 0, 16); (void)cmts_os_csprng(buffer, 16); state->x ^= buffer[0]; state->y ^= buffer[1]; prng_last_seed = cmts_os_time(); } CMTS_INLINE_NEVER static void cmts_romu2jr_reseed_noinline(cmts_romu2jr* state) { cmts_romu2jr_reseed(state); } CMTS_INLINE_ALWAYS static void cmts_romu2jr_init(cmts_romu2jr* state, size_t seed) { // https://nullprogram.com/blog/2018/07/31/ #if UINTPTR_MAX == UINT32_MAX seed ^= seed >> 16; seed *= UINT32_C(0x7feb352d); seed ^= seed >> 15; seed *= UINT32_C(0x846ca68b); seed ^= seed >> 16; #else seed ^= seed >> 32; seed *= UINT64_C(0xd6e8feb86659fd93); seed ^= seed >> 32; seed *= UINT64_C(0xd6e8feb86659fd93); seed ^= seed >> 32; #endif state->x = state->y = seed; state->x ^= UINT64_C(0x9e3779b97f4a7c15); state->y ^= UINT64_C(0xd1b54a32d192ed03); cmts_romu2jr_reseed(state); } CMTS_INLINE_ALWAYS static uint64_t cmts_romu2jr_get(cmts_romu2jr* state) { uint64_t k, now; k = state->x; state->x = 15241094284759029579u * state->y; state->y = state->y - k; state->y = CMTS_ROL64(state->y, 27); now = cmts_os_time(); CMTS_UNLIKELY_IF(cmts_os_time_ns(now - prng_last_seed) >= UINT32_MAX) cmts_romu2jr_reseed_noinline(state); return k; } CMTS_INLINE_ALWAYS static uint_fast32_t cmts_pop_task() { cmts_task_queue* queue; #if defined(CMTS_NO_BUSY_WAIT) || defined(CMTS_HYBRID_MUTEX) uint32_t last; #endif uint_fast32_t index; uint_fast8_t i; for (;; cmts_finalize_check()) { #if defined(CMTS_NO_BUSY_WAIT) || defined(CMTS_HYBRID_MUTEX) last = CMTS_ATOMIC_LOAD_ACQ_U32(&thread_generation_counters[thread_index].value); #endif for (i = 0; i != CMTS_MAX_PRIORITY; ++i) { queue = queues[i] + thread_index; // https://github.com/dbittman/waitfree-mpsc-queue CMTS_UNLIKELY_IF(CMTS_ATOMIC_LOAD_ACQ_U32(&queue->count) == 0) continue; CMTS_UNLIKELY_IF(CMTS_ATOMIC_LOAD_ACQ_U32(&queue->values[queue->tail]) == UINT32_MAX) continue; index = CMTS_ATOMIC_XCHG_ACQ_U32(&queue->values[queue->tail], UINT32_MAX); CMTS_INVARIANT(index != UINT32_MAX); ++queue->tail; queue->tail &= queue_capacity_mask; (void)CMTS_ATOMIC_DECREMENT_REL_U32(&queue->count); return index; } #if defined(CMTS_NO_BUSY_WAIT) || defined(CMTS_HYBRID_MUTEX) cmts_os_futex_await(&thread_generation_counters[thread_index].value, &last, sizeof(uint32_t)); #endif } } CMTS_INLINE_ALWAYS static cmts_bool cmts_try_push_task_to(uint_fast32_t index, uint_fast8_t priority, size_t thread_index) { cmts_task_queue* queue; uint_fast32_t prior; queue = queues[priority] + thread_index; // https://github.com/dbittman/waitfree-mpsc-queue prior = CMTS_ATOMIC_LOAD_ACQ_U32(&queue->count); CMTS_UNLIKELY_IF(prior >= queue_capacity) return CMTS_FALSE; prior = CMTS_ATOMIC_INCREMENT_ACQ_U32(&queue->count); CMTS_UNLIKELY_IF(prior >= queue_capacity) { (void)CMTS_ATOMIC_DECREMENT_REL_U32(&queue->count); return CMTS_FALSE; } prior = CMTS_ATOMIC_INCREMENT_ACQ_U32(&queue->head); prior &= queue_capacity_mask; CMTS_ATOMIC_STORE_REL_U32(&queue->values[prior], index); (void)CMTS_ATOMIC_INCREMENT_REL_U32(&thread_generation_counters[thread_index].value); cmts_os_futex_signal(&thread_generation_counters[thread_index].value); return CMTS_TRUE; } CMTS_INLINE_ALWAYS static void cmts_push_task(uint_fast32_t index) { cmts_task_state* task; uint32_t i, target_thread; task = task_pool + index; for (;; cmts_finalize_check()) { for (i = 0; i != CMTS_SPIN_THRESHOLD; ++i) { target_thread = task->thread_affinity == thread_count ? thread_remainder((uint32_t)cmts_romu2jr_get(&prng)) : thread_index; CMTS_LIKELY_IF(cmts_try_push_task_to(index, task->priority, target_thread)) return; CMTS_SPIN_WAIT; } } } CMTS_INLINE_NEVER static void cmts_await_task_pool_futex() { cmts_index_generation_pair_union info; info.packed = CMTS_ATOMIC_LOAD_ACQ_U64(&task_pool_flist); CMTS_UNLIKELY_IF(info.pair.index == UINT32_MAX) cmts_os_futex_await(&task_pool_flist, &info.packed, 8); } CMTS_INLINE_ALWAYS static uint_fast32_t cmts_try_acquire_task() { uint_fast32_t k; cmts_index_generation_pair_union prior, desired; CMTS_SPIN_LOOP { prior.packed = CMTS_ATOMIC_LOAD_ACQ_U64(&task_pool_flist); CMTS_UNLIKELY_IF(prior.pair.index == UINT32_MAX) break; desired.pair.index = task_pool[prior.pair.index].next; desired.pair.generation = prior.pair.generation + 1; CMTS_LIKELY_IF(CMTS_ATOMIC_CMPXCHG_ACQ_U64(&task_pool_flist, &prior.packed, desired.packed)) return prior.pair.index; } CMTS_UNLIKELY_IF(CMTS_ATOMIC_LOAD_ACQ_U32(&task_pool_bump) >= task_pool_capacity) return UINT32_MAX; k = CMTS_ATOMIC_INCREMENT_ACQ_U32(&task_pool_bump); CMTS_LIKELY_IF(k < task_pool_capacity) return k; (void)CMTS_ATOMIC_DECREMENT_REL_U32(&task_pool_capacity); return UINT32_MAX; } CMTS_INLINE_ALWAYS static uint_fast32_t cmts_acquire_task() { typedef void (*cmts_fn_yield)(); size_t i; uint_fast32_t r; cmts_fn_yield yield_fn; yield_fn = cmts_is_task() ? cmts_yield : cmts_await_task_pool_futex; for (;; yield_fn()) { for (i = 0; i != CMTS_SPIN_THRESHOLD; ++i) { r = cmts_try_acquire_task(); CMTS_LIKELY_IF(r != UINT32_MAX) return r; } } } CMTS_INLINE_ALWAYS static void cmts_release_task(uint_fast32_t index) { cmts_index_generation_pair_union prior, desired; desired.pair.index = index; CMTS_SPIN_LOOP { prior.packed = CMTS_ATOMIC_LOAD_ACQ_U64(&task_pool_flist); task_pool[index].next = prior.pair.index; desired.pair.generation = prior.pair.generation + 1; CMTS_LIKELY_IF(CMTS_ATOMIC_CMPXCHG_REL_U64(&task_pool_flist, &prior.packed, desired.packed)) break; } } #define CMTS_YIELD_IMPL cmts_context_switch(&task_pool[task_index].ctx, &root_task) static void cmts_impl_sleep_task() { cmts_task_state* task; task = task_pool + task_index; CMTS_ATOMIC_STORE_REL_U8(&task->state, CMTS_TASK_STATE_GOING_TO_SLEEP); CMTS_YIELD_IMPL; } static void cmts_impl_wake_task(uint_fast32_t index) { cmts_task_state* task; task = task_pool + index; while (CMTS_ATOMIC_LOAD_RLX_U8(&task->state) != CMTS_TASK_STATE_SLEEPING) CMTS_SPIN_WAIT; CMTS_ACQUIRE_FENCE; CMTS_ATOMIC_STORE_REL_U8(&task->state, CMTS_TASK_STATE_INACTIVE); cmts_push_task(index); } static void cmts_wait_queue_init(CMTS_ATOMIC(uint64_t)* queue) { (void)memset((void*)queue, 0xff, 8); } static cmts_result cmts_wait_queue_state(cmts_wait_queue_data info) { if (info.head == UINT32_MAX) return CMTS_NOT_READY; if (info.tail == UINT32_MAX) return CMTS_SYNC_OBJECT_EXPIRED; return CMTS_OK; } static cmts_bool cmts_wait_queue_is_closed(cmts_wait_queue_data info) { return info.head != UINT32_MAX && info.tail == UINT32_MAX; } static cmts_result cmts_wait_queue_push_current(CMTS_ATOMIC(uint64_t)* queue) { cmts_wait_queue_union prior, desired; CMTS_SPIN_LOOP { prior.packed = CMTS_ATOMIC_LOAD_ACQ_U64(queue); CMTS_UNLIKELY_IF(prior.queue.head != UINT32_MAX && prior.queue.tail == UINT32_MAX) return CMTS_SYNC_OBJECT_EXPIRED; desired.queue.head = prior.queue.head == UINT32_MAX ? task_index : prior.queue.head; desired.queue.tail = task_index; CMTS_LIKELY_IF(CMTS_ATOMIC_CMPXCHG_REL_U64(queue, &prior.packed, desired.packed)) break; } CMTS_LIKELY_IF(prior.queue.tail != UINT32_MAX) { CMTS_INVARIANT(task_pool[prior.queue.tail].next == UINT32_MAX); task_pool[prior.queue.tail].next = task_index; } cmts_impl_sleep_task(); return CMTS_OK; } static cmts_bool cmts_wait_queue_pop_one(CMTS_ATOMIC(uint64_t)* queue) { cmts_wait_queue_union prior, desired; CMTS_SPIN_LOOP { prior.packed = CMTS_ATOMIC_LOAD_ACQ_U64(queue); CMTS_UNLIKELY_IF(prior.queue.head == UINT32_MAX) return CMTS_FALSE; desired.queue.head = task_pool[prior.queue.head].next; desired.queue.tail = prior.queue.tail; CMTS_LIKELY_IF(CMTS_ATOMIC_CMPXCHG_ACQ_U64(queue, &prior.packed, desired.packed)) break; } task_pool[prior.queue.head].next = UINT32_MAX; cmts_impl_wake_task(prior.queue.head); return CMTS_TRUE; } static cmts_result cmts_wait_queue_pop_all(CMTS_ATOMIC(uint64_t)* queue) { cmts_wait_queue_union prior, desired; uint_fast32_t n, next; desired.queue.head = 0; desired.queue.tail = UINT32_MAX; prior.packed = CMTS_ATOMIC_XCHG_ACQ_U64(queue, desired.packed); CMTS_UNLIKELY_IF(prior.queue.head != UINT32_MAX && prior.queue.tail == UINT32_MAX) return CMTS_SYNC_OBJECT_EXPIRED; CMTS_UNLIKELY_IF(prior.queue.head == UINT32_MAX) return CMTS_OK; n = prior.queue.head; for (;; n = next) { while (CMTS_ATOMIC_LOAD_RLX_U8(&task_pool[n].state) != CMTS_TASK_STATE_SLEEPING) CMTS_SPIN_WAIT; CMTS_ACQUIRE_FENCE; next = task_pool[n].next; task_pool[n].next = UINT32_MAX; CMTS_ATOMIC_STORE_REL_U8(&task_pool[n].state, CMTS_TASK_STATE_INACTIVE); cmts_push_task(n); CMTS_UNLIKELY_IF(n == prior.queue.tail) return CMTS_OK; } } static cmts_result cmts_wait_queue_reset(CMTS_ATOMIC(uint64_t)* queue) { cmts_wait_queue_union prior; prior.packed = CMTS_ATOMIC_LOAD_ACQ_U64(queue); CMTS_UNLIKELY_IF(prior.queue.head != UINT32_MAX && prior.queue.tail == UINT32_MAX) return CMTS_NOT_READY; (void)memset((void*)queue, 0xff, 8); return CMTS_OK; } static thread_return_type CMTS_THREAD_CALLING_CONVENTION cmts_thread_entry_point(void* param) { typedef cmts_result(CMTS_CALL *cmts_fn_sync_callback)(void*); cmts_task_state* task; void* sync_object; cmts_fn_sync_callback callback; uint_fast8_t k; thread_index = (uint32_t)(size_t)param; cmts_romu2jr_init(&prng, (size_t)cmts_os_time() ^ thread_index); #ifdef CMTS_WINDOWS root_task = ConvertThreadToFiberEx(NULL, FIBER_FLAG_FLOAT_SWITCH); #endif for (;; cmts_finalize_check()) { task_index = cmts_pop_task(); task = task_pool + task_index; CMTS_ATOMIC_STORE_REL_U8(&task->state, CMTS_TASK_STATE_RUNNING); #ifdef CMTS_WINDOWS CMTS_ASSERT(GetCurrentFiber() == root_task); #endif cmts_context_switch(&root_task, &task->ctx); #ifdef CMTS_WINDOWS CMTS_ASSERT(GetCurrentFiber() == root_task); #endif k = CMTS_ATOMIC_LOAD_ACQ_U8(&task->state); CMTS_UNLIKELY_IF(k == CMTS_TASK_STATE_GOING_TO_SLEEP) { CMTS_ATOMIC_STORE_REL_U8(&task->state, CMTS_TASK_STATE_SLEEPING); } if (task->fn != NULL) { CMTS_LIKELY_IF(k != CMTS_TASK_STATE_GOING_TO_SLEEP) cmts_push_task(task_index); } else { k = task->sync_type; sync_object = task->sync_object; cmts_release_task(task_index); CMTS_LIKELY_IF(k == CMTS_SYNC_TYPE_NONE) continue; callback = k != CMTS_SYNC_TYPE_COUNTER ? (cmts_fn_sync_callback)cmts_event_signal : (cmts_fn_sync_callback)cmts_counter_decrement; (void)callback(sync_object); } } } static void cmts_task_entry_point(void* ptr) { cmts_task_state* task; task = (cmts_task_state*)ptr; for (;; cmts_finalize_check()) { task->fn(task->param); task->fn = NULL; cmts_yield(); } } CMTS_INLINE_ALWAYS static size_t cmts_round_pow2(size_t value) { #if UINTPTR_MAX == UINT32_MAX return UINT32_C(1) << (32 - CMTS_CLZ32(value)); #else return UINT64_C(1) << (64 - CMTS_CLZ64(value)); #endif } static void cmts_lib_lock() { uint8_t i; uint32_t expected; for (;;) { for (i = 0; i != CMTS_SPIN_THRESHOLD; ++i) { expected = CMTS_ATOMIC_LOAD_ACQ_U8(&lib_lock); CMTS_LIKELY_IF(!expected && CMTS_ATOMIC_CMPXCHG_ACQ_U32(&lib_lock, &expected, 1)) return; } cmts_os_futex_await(&lib_lock, &expected, 1); } } static void cmts_lib_unlock() { CMTS_ATOMIC_STORE_REL_U32(&lib_lock, 0); cmts_os_futex_signal(&lib_lock); } CMTS_INLINE_ALWAYS static size_t cmts_required_memory_size() { size_t r = sizeof(thread_type) * thread_count; r += sizeof(cmts_task_state) * task_pool_capacity; size_t queues_count = (size_t)thread_count * CMTS_MAX_PRIORITY; r += sizeof(cmts_task_queue) * queues_count; r += sizeof(uint32_t) * cmts_round_pow2(task_pool_capacity / thread_count) * queues_count; #ifdef CMTS_NO_BUSY_WAIT r += sizeof(uint32_t) * thread_count; #endif return r; } static cmts_result cmts_handle_extension(const cmts_init_options* options, const cmts_ext_header* header) { switch (header->type) { case CMTS_EXT_TYPE_DEBUGGER: debugger_callback = ((const cmts_ext_debug_init_options*)header)->message_callback; debugger_context = ((const cmts_ext_debug_init_options*)header)->context; return CMTS_OK; default: return CMTS_ERROR_INVALID_EXTENSION_TYPE; } } CMTS_INLINE_ALWAYS static void cmts_common_init(uint8_t* buffer) { size_t i, j, thread_size, task_pool_size, queue_size, thread_generation_counters_size; cmts_task_queue* q; thread_size = CMTS_ROUND_CACHE_LINE_SIZE(sizeof(thread_type) * thread_count); task_pool_size = sizeof(cmts_task_state) * task_pool_capacity; queue_size = sizeof(uint32_t) * queue_capacity; thread_generation_counters_size = (size_t)CMTS_CACHE_LINE_SIZE * thread_count; threads = (thread_type*)buffer; buffer += thread_size; task_pool = (cmts_task_state*)buffer; buffer += task_pool_size; thread_generation_counters = (cmts_cache_aligned_atomic_counter*)buffer; buffer += thread_generation_counters_size; (void)memset(thread_generation_counters, 0, thread_generation_counters_size); for (i = 0; i != CMTS_MAX_PRIORITY; ++i) { queues[i] = (cmts_task_queue*)buffer; buffer += sizeof(cmts_task_queue) * thread_count; } for (i = 0; i != CMTS_MAX_PRIORITY; ++i) { for (j = 0; j != thread_count; ++j) { q = queues[i] + j; q->values = (CMTS_ATOMIC(uint32_t)*)buffer; (void)memset(buffer, 0xff, queue_size); buffer += queue_size; q->tail = 0; q->head = 0; q->count = 0; } } cmts_index_generation_pair flist; flist.index = UINT32_MAX; flist.generation = 0; (void)memcpy((void*)&task_pool_flist, &flist, 8); for (i = 0; i != task_pool_capacity; ++i) { (void)memset(task_pool + i, 0, sizeof(cmts_task_state)); task_pool[i].thread_affinity = thread_count; task_pool[i].next = UINT32_MAX; } CMTS_LIKELY_IF(CMTS_POPCNT32(thread_count) == 1) { thread_remainder = cmts_thread_remainder_pow2; thread_remainder_param = thread_count - 1; } else { thread_remainder = cmts_thread_remainder_range_reduce; thread_remainder_param = 32 - CMTS_CLZ32(thread_count); } } static cmts_result cmts_library_init_default() { size_t buffer_size; uint8_t* buffer; thread_count = (uint32_t)cmts_processor_count(); task_pool_capacity = CMTS_DEFAULT_TASKS_PER_THREAD * thread_count; queue_capacity = (uint32_t)cmts_round_pow2(task_pool_capacity / thread_count); queue_capacity_mask = queue_capacity - 1; task_stack_size = (uint32_t)cmts_default_task_stack_size(); buffer_size = cmts_required_memory_size(); buffer = (uint8_t*)cmts_os_malloc(buffer_size); CMTS_UNLIKELY_IF(buffer == NULL) return CMTS_ERROR_MEMORY_ALLOCATION; cmts_common_init(buffer); return cmts_os_init_threads(threads, thread_count, thread_stack_size, (LPTHREAD_START_ROUTINE)cmts_thread_entry_point); } static cmts_result cmts_library_init_custom(const cmts_init_options* options) { cmts_result r; size_t buffer_size; uint8_t* buffer; const cmts_ext_header* ext; thread_count = options->thread_count; task_pool_capacity = options->max_tasks; queue_capacity = (uint32_t)cmts_round_pow2(task_pool_capacity / options->thread_count); queue_capacity_mask = queue_capacity - 1; task_stack_size = (uint32_t)options->task_stack_size; buffer_size = (uint32_t)cmts_required_memory_size(); CMTS_LIKELY_IF(options->allocate_function == NULL) buffer = (uint8_t*)cmts_os_malloc(buffer_size); else buffer = (uint8_t*)options->allocate_function(buffer_size); CMTS_UNLIKELY_IF(buffer == NULL) return CMTS_ERROR_MEMORY_ALLOCATION; cmts_common_init(buffer); CMTS_UNLIKELY_IF(options->thread_affinities != NULL) r = cmts_os_init_threads_custom(threads, thread_count, thread_stack_size, (LPTHREAD_START_ROUTINE)cmts_thread_entry_point, options->thread_affinities); else r = cmts_os_init_threads(threads, thread_count, thread_stack_size, (LPTHREAD_START_ROUTINE)cmts_thread_entry_point); CMTS_UNLIKELY_IF(r != CMTS_OK) return r; for (ext = (const cmts_ext_header*)options->next_ext; ext != NULL; ext = ext->next) { r = cmts_handle_extension(options, ext); CMTS_UNLIKELY_IF(r != CMTS_OK) return r; } return CMTS_OK; } static cmts_result cmts_common_cleanup(cmts_fn_deallocate deallocate) { uint_fast32_t n; size_t i; n = CMTS_ATOMIC_LOAD_ACQ_U32(&task_pool_bump); CMTS_UNLIKELY_IF(n > task_pool_capacity) n = task_pool_capacity; for (i = 0; i != task_pool_bump; ++i) CMTS_LIKELY_IF(cmts_context_is_valid(&task_pool[i].ctx)) cmts_context_delete(&task_pool[i].ctx); i = cmts_required_memory_size(); CMTS_LIKELY_IF(deallocate == NULL) deallocate = cmts_os_free; CMTS_UNLIKELY_IF(!deallocate(threads, i)) return CMTS_ERROR_MEMORY_DEALLOCATION; CMTS_ATOMIC_STORE_REL_U8(&should_continue, 0); CMTS_ATOMIC_STORE_REL_U8(&init_state, 0); CMTS_ATOMIC_STORE_REL_U8(&scheduler_state, CMTS_SCHEDULER_STATE_OFFLINE); return CMTS_OK; } CMTS_EXTERN_C_BEGIN CMTS_ATTR cmts_result CMTS_CALL cmts_init(const cmts_init_options* options) { cmts_result r; uint8_t expected; expected = 0; CMTS_UNLIKELY_IF(cmts_is_initialized()) return CMTS_ALREADY_INITIALIZED; CMTS_UNLIKELY_IF(!CMTS_ATOMIC_CMPXCHG_STRONG_ACQ_U8(&init_state, &expected, 1)) return CMTS_INITIALIZATION_IN_PROGRESS; CMTS_ATOMIC_STORE_REL_U8(&should_continue, 1); CMTS_ATOMIC_STORE_REL_U8(&init_state, 2); CMTS_ATOMIC_STORE_REL_U8(&scheduler_state, CMTS_SCHEDULER_STATE_ONLINE); CMTS_UNLIKELY_IF(!cmts_os_init()) return CMTS_ERROR_OS_INIT; CMTS_UNLIKELY_IF(options == NULL) r = cmts_library_init_default(); else r = cmts_library_init_custom(options); CMTS_UNLIKELY_IF(r == CMTS_OK) return CMTS_OK; CMTS_ATOMIC_STORE_REL_U8(&should_continue, 0); CMTS_ATOMIC_STORE_REL_U8(&init_state, 0); CMTS_ATOMIC_STORE_REL_U8(&scheduler_state, CMTS_SCHEDULER_STATE_OFFLINE); return r; } CMTS_ATTR cmts_result CMTS_CALL cmts_pause() { uint8_t expected; expected = CMTS_SCHEDULER_STATE_ONLINE; CMTS_UNLIKELY_IF(!CMTS_ATOMIC_CMPXCHG_STRONG_ACQ_U8(&scheduler_state, &expected, CMTS_SCHEDULER_STATE_PAUSED)) return cmts_is_initialized() ? CMTS_OK : CMTS_ERROR_LIBRARY_UNINITIALIZED; CMTS_UNLIKELY_IF(cmts_os_pause_threads(threads, thread_count)) return CMTS_ERROR_SUSPEND_THREAD; return CMTS_OK; } CMTS_ATTR cmts_result CMTS_CALL cmts_resume() { uint8_t expected; expected = CMTS_SCHEDULER_STATE_PAUSED; CMTS_UNLIKELY_IF(!CMTS_ATOMIC_CMPXCHG_STRONG_ACQ_U8(&scheduler_state, &expected, CMTS_SCHEDULER_STATE_ONLINE)) return cmts_is_initialized() ? CMTS_OK : CMTS_ERROR_LIBRARY_UNINITIALIZED; CMTS_UNLIKELY_IF(cmts_os_resume_threads(threads, thread_count)) return CMTS_ERROR_RESUME_THREAD; return CMTS_OK; } CMTS_ATTR void CMTS_CALL cmts_finalize_signal() { #ifdef CMTS_NO_BUSY_WAIT size_t i; #endif CMTS_ATOMIC_STORE_REL_U8(&should_continue, 0); #ifdef CMTS_NO_BUSY_WAIT for (i = 0; i != thread_count; ++i) cmts_os_futex_signal(&thread_generation_counters[i].value); #endif if (cmts_is_task()) { if (cmts_context_is_valid(&task_pool[task_index].ctx)) cmts_context_wipe(&task_pool[task_index].ctx); cmts_os_exit_thread(0); } } CMTS_ATTR cmts_result CMTS_CALL cmts_finalize_await(cmts_fn_deallocate deallocate) { CMTS_UNLIKELY_IF(!cmts_is_initialized()) return CMTS_ERROR_LIBRARY_UNINITIALIZED; CMTS_UNLIKELY_IF(!cmts_os_await_threads(threads, thread_count)) return CMTS_ERROR_AWAIT_THREAD; return cmts_common_cleanup(deallocate); } CMTS_ATTR cmts_result CMTS_CALL cmts_terminate(cmts_fn_deallocate deallocate) { CMTS_UNLIKELY_IF(!cmts_is_initialized()) return CMTS_ERROR_LIBRARY_UNINITIALIZED; CMTS_UNLIKELY_IF(!cmts_os_terminate_threads(threads, thread_count)) return CMTS_ERROR_TERMINATE_THREAD; return cmts_common_cleanup(deallocate); } CMTS_ATTR cmts_bool CMTS_CALL cmts_is_initialized() { return CMTS_ATOMIC_LOAD_ACQ_U8(&init_state) == 2; } CMTS_ATTR cmts_bool CMTS_CALL cmts_is_online() { return cmts_is_initialized() && CMTS_ATOMIC_LOAD_ACQ_U8(&should_continue); } CMTS_ATTR cmts_bool CMTS_CALL cmts_is_paused() { return CMTS_ATOMIC_LOAD_ACQ_U8(&scheduler_state) == CMTS_SCHEDULER_STATE_PAUSED; } CMTS_ATTR uint32_t CMTS_CALL cmts_purge(uint32_t max_purged_tasks) { uint_fast32_t n, k, i; n = CMTS_ATOMIC_LOAD_ACQ_U32(&task_pool_bump); CMTS_UNLIKELY_IF(n > task_pool_capacity) n = task_pool_capacity; k = 0; for (i = 0; i != n && k != max_purged_tasks; ++i) CMTS_LIKELY_IF(cmts_context_is_valid(&task_pool[i].ctx)) cmts_context_delete(&task_pool[i].ctx); return k; } CMTS_ATTR uint32_t CMTS_CALL cmts_purge_all() { uint_fast32_t n, k, i; n = CMTS_ATOMIC_LOAD_ACQ_U32(&task_pool_bump); CMTS_UNLIKELY_IF(n > task_pool_capacity) n = task_pool_capacity; k = 0; for (i = 0; i != n; ++i) CMTS_LIKELY_IF(cmts_context_is_valid(&task_pool[i].ctx)) cmts_context_delete(&task_pool[i].ctx); return k; } CMTS_ATTR cmts_bool CMTS_CALL cmts_is_worker_thread() { return root_task != NULL; } CMTS_ATTR uint32_t CMTS_CALL cmts_worker_thread_index() { CMTS_UNLIKELY_IF(!cmts_is_worker_thread()) return thread_count; return thread_index; } CMTS_ATTR uint32_t CMTS_CALL cmts_worker_thread_count() { return thread_count; } CMTS_ATTR cmts_result CMTS_CALL cmts_dispatch(cmts_fn_task entry_point, cmts_dispatch_options* options) { cmts_dispatch_options o; cmts_task_state* task; uint_fast32_t index, generation; CMTS_UNLIKELY_IF(options == NULL) { (void)memset(&o, 0, sizeof(cmts_dispatch_options)); options = &o; } index = ((options->flags & CMTS_DISPATCH_FLAGS_FORCE) ? cmts_acquire_task : cmts_try_acquire_task)(); CMTS_UNLIKELY_IF(index == UINT32_MAX) return CMTS_ERROR_TASK_POOL_CAPACITY; task = task_pool + index; CMTS_UNLIKELY_IF(!cmts_context_is_valid(&task->ctx)) { CMTS_UNLIKELY_IF(!cmts_context_init(&task->ctx, cmts_task_entry_point, task, task_stack_size)) { cmts_release_task(index); return CMTS_ERROR_TASK_ALLOCATION; } } task->fn = entry_point; task->param = options->parameter; task->sync_object = options->sync_object; task->next = UINT32_MAX; generation = ++task->generation; task->thread_affinity = options->locked_thread != NULL ? *options->locked_thread : thread_count; task->priority = options->priority; task->sync_type = options->sync_type; CMTS_ASSERT(CMTS_NON_ATOMIC_LOAD_U8(&task->state) == CMTS_TASK_STATE_INACTIVE); cmts_push_task(index); CMTS_UNLIKELY_IF(options->out_task_id != NULL) *options->out_task_id = CMTS_MAKE_HANDLE(index, generation); return CMTS_OK; } CMTS_ATTR void CMTS_CALL cmts_yield() { CMTS_ASSERT(cmts_is_task()); CMTS_ATOMIC_STORE_REL_U8(&task_pool[task_index].state, CMTS_TASK_STATE_INACTIVE); CMTS_YIELD_IMPL; } CMTS_NORETURN CMTS_ATTR void CMTS_CALL cmts_exit() { cmts_task_state* task; task = task_pool + task_index; task->fn = NULL; CMTS_ATOMIC_STORE_REL_U8(&task->state, CMTS_TASK_STATE_INACTIVE); CMTS_YIELD_IMPL; } CMTS_ATTR cmts_bool CMTS_CALL cmts_is_task() { return root_task != NULL; } CMTS_ATTR cmts_task_id CMTS_CALL cmts_this_task_id() { CMTS_ASSERT(cmts_is_worker_thread()); return CMTS_MAKE_HANDLE(task_index, task_pool[task_index].generation); } CMTS_NODISCARD CMTS_ATTR cmts_task_id CMTS_CALL cmts_task_allocate() { uint_fast32_t index; cmts_task_state* task; index = cmts_try_acquire_task(); CMTS_UNLIKELY_IF(index == UINT32_MAX) return CMTS_INVALID_TASK_ID; task = task_pool + index; CMTS_INVARIANT(task->next == UINT32_MAX); CMTS_INVARIANT(task->fn == NULL); ++task->generation; return CMTS_MAKE_HANDLE(index, task->generation); } #define CMTS_TASK_COMMON_VARIABLES \ uint_fast32_t index, generation; \ cmts_task_state* task; \ CMTS_BREAK_HANDLE(task_id, index, generation); \ task = task_pool + index; \ CMTS_INVARIANT(task->next == UINT32_MAX); \ CMTS_INVARIANT(task->generation == generation); CMTS_ATTR uint8_t CMTS_CALL cmts_task_get_priority(cmts_task_id task_id) { CMTS_TASK_COMMON_VARIABLES; return task->priority; } CMTS_ATTR void CMTS_CALL cmts_task_set_priority(cmts_task_id task_id, uint8_t new_priority) { CMTS_TASK_COMMON_VARIABLES; task->priority = new_priority; } CMTS_ATTR void CMTS_CALL cmts_task_set_parameter(cmts_task_id task_id, void* new_parameter) { CMTS_TASK_COMMON_VARIABLES; task->param = new_parameter; } CMTS_ATTR void* CMTS_CALL cmts_task_get_parameter(cmts_task_id task_id) { CMTS_TASK_COMMON_VARIABLES; return task->param; } CMTS_ATTR void CMTS_CALL cmts_task_set_function(cmts_task_id task_id, cmts_fn_task new_function) { CMTS_TASK_COMMON_VARIABLES; task->fn = new_function; } CMTS_ATTR cmts_fn_task CMTS_CALL cmts_task_get_function(cmts_task_id task_id) { CMTS_TASK_COMMON_VARIABLES; return task->fn; } CMTS_ATTR void CMTS_CALL cmts_task_attach_event(cmts_task_id task_id, cmts_event* event) { CMTS_TASK_COMMON_VARIABLES; task->sync_type = CMTS_SYNC_TYPE_EVENT; task->sync_object = event; } CMTS_ATTR void CMTS_CALL cmts_task_attach_counter(cmts_task_id task_id, cmts_counter* counter) { CMTS_TASK_COMMON_VARIABLES; task->sync_type = CMTS_SYNC_TYPE_COUNTER; task->sync_object = counter; } CMTS_ATTR void CMTS_CALL cmts_task_sleep(cmts_task_id task_id) { CMTS_TASK_COMMON_VARIABLES; CMTS_ATOMIC_STORE_REL_U8(&task_pool[index].state, CMTS_TASK_STATE_GOING_TO_SLEEP); } CMTS_ATTR void CMTS_CALL cmts_task_resume(cmts_task_id task_id) { CMTS_TASK_COMMON_VARIABLES; cmts_impl_wake_task(index); } CMTS_ATTR cmts_bool CMTS_CALL cmts_is_valid_task_id(cmts_task_id task_id) { uint_fast32_t index, generation; cmts_task_state* task; CMTS_BREAK_HANDLE(task_id, index, generation); CMTS_UNLIKELY_IF(index >= task_pool_capacity) return CMTS_FALSE; CMTS_UNLIKELY_IF(index >= CMTS_ATOMIC_LOAD_ACQ_U32(&task_pool_bump)) return CMTS_FALSE; task = task_pool + index; return task->next == UINT32_MAX && task->generation == generation; } CMTS_ATTR cmts_bool CMTS_CALL cmts_task_is_sleeping(cmts_task_id task_id) { CMTS_TASK_COMMON_VARIABLES; return CMTS_ATOMIC_LOAD_ACQ_U8(&task_pool[index].state) == CMTS_TASK_STATE_SLEEPING; } CMTS_ATTR cmts_bool CMTS_CALL cmts_task_is_running(cmts_task_id task_id) { CMTS_TASK_COMMON_VARIABLES; return CMTS_ATOMIC_LOAD_ACQ_U8(&task_pool[index].state) == CMTS_TASK_STATE_RUNNING; } CMTS_ATTR void CMTS_CALL cmts_task_dispatch(cmts_task_id task_id) { CMTS_TASK_COMMON_VARIABLES; cmts_push_task(index); } CMTS_ATTR void CMTS_CALL cmts_task_deallocate(cmts_task_id task_id) { CMTS_TASK_COMMON_VARIABLES; cmts_release_task(index); } CMTS_ATTR void CMTS_CALL cmts_fence_init(cmts_fence* fence) { (void)memset(fence, 0xff, sizeof(cmts_fence)); } CMTS_ATTR void CMTS_CALL cmts_fence_signal(cmts_fence* fence) { cmts_fence_data* e; e = (cmts_fence_data*)fence; uint32_t index; CMTS_SPIN_LOOP { index = CMTS_ATOMIC_LOAD_ACQ_U32(e); CMTS_LIKELY_IF(index != UINT32_MAX) break; } cmts_impl_wake_task(index); } CMTS_ATTR cmts_bool CMTS_CALL cmts_fence_try_await(cmts_fence* fence) { cmts_fence_data* e; uint32_t prior, desired; e = (cmts_fence_data*)fence; prior = UINT32_MAX; desired = task_index; CMTS_UNLIKELY_IF(!CMTS_ATOMIC_CMPXCHG_ACQ_U32(e, &prior, desired)) return CMTS_FALSE; cmts_impl_sleep_task(); return CMTS_TRUE; } CMTS_ATTR void CMTS_CALL cmts_fence_await(cmts_fence* fence) { cmts_fence_data* e; e = (cmts_fence_data*)fence; #ifdef CMTS_DEBUG CMTS_ASSERT(CMTS_ATOMIC_XCHG_REL_U32(e, task_index) == UINT32_MAX); #else CMTS_ATOMIC_STORE_REL_U32(e, task_index); #endif cmts_impl_sleep_task(); } CMTS_ATTR void CMTS_CALL cmts_event_init(cmts_event* event) { cmts_wait_queue_init((CMTS_ATOMIC(uint64_t)*)event); } CMTS_ATTR cmts_result CMTS_CALL cmts_event_state(const cmts_event* event) { cmts_wait_queue_union info; cmts_event_data* e; e = (cmts_event_data*)event; info.packed = CMTS_ATOMIC_LOAD_ACQ_U64(e); return cmts_wait_queue_state(info.queue); } CMTS_ATTR cmts_result CMTS_CALL cmts_event_signal(cmts_event* event) { cmts_event_data* e; e = (cmts_event_data*)event; return cmts_wait_queue_pop_all(e); } CMTS_ATTR cmts_result CMTS_CALL cmts_event_await(cmts_event* event) { cmts_event_data* e; e = (cmts_event_data*)event; return cmts_wait_queue_push_current(e); } CMTS_ATTR cmts_result CMTS_CALL cmts_event_reset(cmts_event* event) { cmts_event_data* e; e = (cmts_event_data*)event; return cmts_wait_queue_reset(e); } CMTS_ATTR void CMTS_CALL cmts_counter_init(cmts_counter* counter, uint64_t start_value) { cmts_counter_data* c; c = (cmts_counter_data*)counter; cmts_wait_queue_init(&c->queue); *(uint64_t*)&c->value = start_value; } CMTS_ATTR uint64_t CMTS_CALL cmts_counter_value(const cmts_counter* counter) { cmts_counter_data* c; c = (cmts_counter_data*)counter; return CMTS_ATOMIC_LOAD_ACQ_U64(&c->value); } CMTS_ATTR cmts_result CMTS_CALL cmts_counter_state(const cmts_counter* counter) { cmts_counter_data* c; cmts_wait_queue_union info; c = (cmts_counter_data*)counter; info.packed = CMTS_ATOMIC_LOAD_ACQ_U64(&c->queue); return cmts_wait_queue_state(info.queue); } CMTS_ATTR cmts_result CMTS_CALL cmts_counter_increment(cmts_counter* counter) { cmts_counter_data* c; cmts_wait_queue_union info; uint64_t prior, desired; c = (cmts_counter_data*)counter; CMTS_SPIN_LOOP { info.packed = CMTS_ATOMIC_LOAD_ACQ_U64(&c->queue); CMTS_UNLIKELY_IF(cmts_wait_queue_is_closed(info.queue)) return CMTS_SYNC_OBJECT_EXPIRED; prior = CMTS_ATOMIC_LOAD_ACQ_U64(&c->value); desired = prior + 1; CMTS_LIKELY_IF(CMTS_ATOMIC_CMPXCHG_REL_U64(&c->value, &prior, desired)) break; } return CMTS_OK; } CMTS_ATTR cmts_result CMTS_CALL cmts_counter_decrement(cmts_counter* counter) { cmts_counter_data* c; cmts_wait_queue_union info; uint64_t k; c = (cmts_counter_data*)counter; info.packed = CMTS_ATOMIC_LOAD_ACQ_U64(&c->queue); CMTS_UNLIKELY_IF(cmts_wait_queue_is_closed(info.queue)) return CMTS_SYNC_OBJECT_EXPIRED; k = CMTS_ATOMIC_DECREMENT_ACQ_U64(&c->value); CMTS_INVARIANT(k != 0); CMTS_UNLIKELY_IF(k != 1) return CMTS_NOT_READY; return cmts_wait_queue_pop_all(&c->queue); } CMTS_ATTR cmts_result CMTS_CALL cmts_counter_await(cmts_counter* counter) { cmts_counter_data* c; c = (cmts_counter_data*)counter; return cmts_wait_queue_push_current(&c->queue); } CMTS_ATTR cmts_result CMTS_CALL cmts_counter_reset(cmts_counter* counter, uint64_t new_start_value) { cmts_counter_data* c; c = (cmts_counter_data*)counter; CMTS_ASSERT(cmts_wait_queue_is_closed(*(cmts_wait_queue_data*)c->queue)); *(uint64_t*)&c->value = new_start_value; return cmts_wait_queue_reset(&c->queue); } CMTS_ATTR void CMTS_CALL cmts_mutex_init(cmts_mutex* mutex) { (void)memset(mutex, 0xff, 4); } CMTS_ATTR cmts_bool CMTS_CALL cmts_mutex_is_locked(const cmts_mutex* mutex) { cmts_mutex_data* c; c = (cmts_mutex_data*)mutex; return CMTS_ATOMIC_LOAD_ACQ_U32(c) != UINT32_MAX; } CMTS_ATTR cmts_bool CMTS_CALL cmts_mutex_try_lock(cmts_mutex* mutex) { cmts_mutex_data* c; uint32_t prior, desired; CMTS_ASSERT(cmts_is_task()); c = (cmts_mutex_data*)mutex; prior = UINT32_MAX; desired = task_index; return CMTS_ATOMIC_CMPXCHG_ACQ_U32(c, &prior, desired); } CMTS_ATTR void CMTS_CALL cmts_mutex_lock(cmts_mutex* mutex) { cmts_mutex_data* c; uint32_t prior; CMTS_ASSERT(cmts_is_task()); c = (cmts_mutex_data*)mutex; prior = CMTS_ATOMIC_XCHG_ACQ_U32(c, task_index); CMTS_LIKELY_IF(prior == UINT32_MAX) return; task_pool[prior].next = task_index; cmts_impl_sleep_task(); } CMTS_ATTR void CMTS_CALL cmts_mutex_unlock(cmts_mutex* mutex) { cmts_mutex_data* c; uint32_t index; CMTS_ASSERT(cmts_is_task()); c = (cmts_mutex_data*)mutex; CMTS_LIKELY_IF(task_pool[task_index].next == UINT32_MAX) { index = task_index; CMTS_LIKELY_IF(CMTS_ATOMIC_CMPXCHG_STRONG_REL_U32(c, &index, UINT32_MAX)) return; CMTS_SPIN_LOOP { index = task_pool[task_index].next; if (index == UINT32_MAX) break; } } else { index = task_pool[task_index].next; } CMTS_INVARIANT(index != UINT32_MAX); task_pool[task_index].next = UINT32_MAX; cmts_impl_wake_task(index); } CMTS_ATTR void CMTS_CALL cmts_rcu_read_begin() { #ifdef CMTS_DEBUG CMTS_ASSERT(cmts_is_task()); CMTS_LIKELY_IF(yield_trap_depth == 0) cmts_ext_debug_enable_yield_trap(CMTS_TRUE); ++yield_trap_depth; #endif } CMTS_ATTR void CMTS_CALL cmts_rcu_read_end() { #ifdef CMTS_DEBUG CMTS_ASSERT(cmts_is_task()); --yield_trap_depth; CMTS_LIKELY_IF(yield_trap_depth == 0) cmts_ext_debug_enable_yield_trap(CMTS_FALSE); #endif } #define CMTS_RCU_SYNC_GROUP_SIZE (CMTS_CACHE_LINE_SIZE / sizeof(uint32_t)) CMTS_ATTR void CMTS_CALL cmts_rcu_sync() { uint32_t group[CMTS_RCU_SYNC_GROUP_SIZE]; uint32_t i, j, k, next; for (i = 0; i != thread_count; i = next) { next = i + CMTS_RCU_SYNC_GROUP_SIZE; CMTS_UNLIKELY_IF(next > thread_count) next = thread_count; for (j = i; j != next; ++j) { group[j - i] = CMTS_ATOMIC_LOAD_ACQ_U32(&thread_generation_counters[j].value); } cmts_yield(); for (j = i; j != next; ++j) { for (k = 0; group[j - i] == CMTS_ATOMIC_LOAD_ACQ_U32(&thread_generation_counters[j].value);) { CMTS_UNLIKELY_IF(++k == CMTS_SPIN_THRESHOLD) { cmts_yield(); k = 0; } } } } } CMTS_ATTR void CMTS_CALL cmts_rcu_snapshot_requirements(cmts_memory_requirements* out_requirements) { out_requirements->size = thread_count * sizeof(uint32_t); out_requirements->alignment_log2 = 2; } CMTS_ATTR void CMTS_CALL cmts_rcu_snapshot(void* snapshot_buffer) { uint32_t* out = (uint32_t*)snapshot_buffer; uint32_t i; for (i = 0; i != thread_count; ++i) { out[i] = CMTS_ATOMIC_LOAD_ACQ_U32(&thread_generation_counters[i].value); } } CMTS_ATTR uint32_t CMTS_CALL cmts_rcu_try_snapshot_sync(const void* snapshot_buffer, uint32_t prior_result) { uint32_t* e = (uint32_t*)snapshot_buffer; uint32_t i; for (i = prior_result; i != thread_count; ++i) { CMTS_UNLIKELY_IF(i == thread_index) continue; CMTS_LIKELY_IF(CMTS_ATOMIC_LOAD_ACQ_U32(&thread_generation_counters[i].value) == e[i]) break; } return i; } CMTS_ATTR void CMTS_CALL cmts_rcu_snapshot_sync(const void* snapshot_buffer) { CMTS_ASSERT(cmts_is_task()); uint32_t* e = (uint32_t*)snapshot_buffer; uint32_t i; for (i = 0; i != thread_count; ++i) { CMTS_UNLIKELY_IF(i == thread_index) continue; while (CMTS_ATOMIC_LOAD_ACQ_U32(&thread_generation_counters[i].value) == e[i]) cmts_yield(); } } CMTS_ATTR void CMTS_CALL cmts_hazard_ptr_requirements(cmts_memory_requirements* out_requirements) { out_requirements->size = (size_t)thread_count * sizeof(void*); #if UINTPTR_MAX == UINT32_MAX out_requirements->alignment_log2 = 2; #else out_requirements->alignment_log2 = 3; #endif } CMTS_ATTR void CMTS_CALL cmts_hazard_ptr_init(cmts_hazard_context* hctx, void* buffer) { (void)memset((void*)buffer, 0, (size_t)thread_count * sizeof(void*)); *hctx = (size_t)buffer; } CMTS_ATTR void CMTS_CALL cmts_hazard_ptr_protect(cmts_hazard_context* hctx, void* ptr) { CMTS_ASSERT(cmts_is_task()); cmts_rcu_read_begin(); #ifdef CMTS_DEBUG CMTS_ASSERT(CMTS_ATOMIC_XCHG_REL_UPTR((CMTS_ATOMIC(void*)*)hctx + thread_index, (size_t)ptr) == NULL); #else CMTS_ATOMIC_STORE_REL_UPTR((CMTS_ATOMIC(void*)*)hctx + thread_index, (size_t)ptr); #endif } CMTS_ATTR void CMTS_CALL cmts_hazard_ptr_release(cmts_hazard_context* hctx) { CMTS_ASSERT(cmts_is_task()); #ifdef CMTS_DEBUG CMTS_ASSERT(CMTS_ATOMIC_XCHG_REL_UPTR((CMTS_ATOMIC(void*)*)hctx + thread_index, 0) != NULL); #else CMTS_ATOMIC_STORE_REL_UPTR((CMTS_ATOMIC(void*)*)hctx + thread_index, 0); #endif cmts_rcu_read_end(); } CMTS_ATTR void* CMTS_CALL cmts_hazard_ptr_get(cmts_hazard_context* hctx) { CMTS_ASSERT(cmts_is_task()); return (void*)CMTS_ATOMIC_LOAD_ACQ_UPTR((CMTS_ATOMIC(void*)*)hctx + thread_index); } CMTS_ATTR cmts_bool CMTS_CALL cmts_hazard_ptr_is_unreachable(const cmts_hazard_context* hctx, const void* ptr) { uint8_t* i; uint8_t* end; end = (uint8_t*)hctx + thread_count * sizeof(void*); for (i = (uint8_t*)hctx; i != end; i += sizeof(void*)) CMTS_UNLIKELY_IF((void*)CMTS_ATOMIC_LOAD_ACQ_UPTR((CMTS_ATOMIC(void*)*)i) == ptr) return CMTS_FALSE; return CMTS_TRUE; } CMTS_ATTR size_t CMTS_CALL cmts_processor_count() { SYSTEM_INFO info; GetSystemInfo(&info); return info.dwNumberOfProcessors; } CMTS_ATTR size_t CMTS_CALL cmts_this_processor_index() { PROCESSOR_NUMBER k; GetCurrentProcessorNumberEx(&k); return ((size_t)k.Group << 6) | k.Number; } CMTS_ATTR size_t CMTS_CALL cmts_default_task_stack_size() { return 65536; } #ifdef CMTS_FORMAT_RESULT static const CMTS_CHAR* format_result_names[] = { "CMTS_ERROR_MEMORY_ALLOCATION", "CMTS_ERROR_MEMORY_DEALLOCATION", "CMTS_ERROR_THREAD_CREATION", "CMTS_ERROR_THREAD_AFFINITY", "CMTS_ERROR_RESUME_THREAD", "CMTS_ERROR_SUSPEND_THREAD", "CMTS_ERROR_TERMINATE_THREAD", "CMTS_ERROR_AWAIT_THREAD", "CMTS_ERROR_TASK_POOL_CAPACITY", "CMTS_ERROR_AFFINITY", "CMTS_ERROR_TASK_ALLOCATION", "CMTS_ERROR_FUTEX", "CMTS_ERROR_LIBRARY_UNINITIALIZED", "CMTS_ERROR_OS_INIT", "CMTS_OK", "CMTS_SYNC_OBJECT_EXPIRED", "CMTS_NOT_READY", "CMTS_ALREADY_INITIALIZED", "CMTS_INITIALIZATION_IN_PROGRESS" }; static const size_t format_result_sizes[] = { CMTS_STRING_SIZE("CMTS_ERROR_MEMORY_ALLOCATION"), CMTS_STRING_SIZE("CMTS_ERROR_MEMORY_DEALLOCATION"), CMTS_STRING_SIZE("CMTS_ERROR_THREAD_CREATION"), CMTS_STRING_SIZE("CMTS_ERROR_THREAD_AFFINITY"), CMTS_STRING_SIZE("CMTS_ERROR_RESUME_THREAD"), CMTS_STRING_SIZE("CMTS_ERROR_SUSPEND_THREAD"), CMTS_STRING_SIZE("CMTS_ERROR_TERMINATE_THREAD"), CMTS_STRING_SIZE("CMTS_ERROR_AWAIT_THREAD"), CMTS_STRING_SIZE("CMTS_ERROR_TASK_POOL_CAPACITY"), CMTS_STRING_SIZE("CMTS_ERROR_AFFINITY"), CMTS_STRING_SIZE("CMTS_ERROR_TASK_ALLOCATION"), CMTS_STRING_SIZE("CMTS_ERROR_FUTEX"), CMTS_STRING_SIZE("CMTS_ERROR_LIBRARY_UNINITIALIZED"), CMTS_STRING_SIZE("CMTS_ERROR_OS_INIT"), CMTS_STRING_SIZE("CMTS_OK"), CMTS_STRING_SIZE("CMTS_SYNC_OBJECT_EXPIRED"), CMTS_STRING_SIZE("CMTS_NOT_READY"), CMTS_STRING_SIZE("CMTS_ALREADY_INITIALIZED"), CMTS_STRING_SIZE("CMTS_INITIALIZATION_IN_PROGRESS") }; CMTS_ATTR const CMTS_CHAR* CMTS_CALL cmts_format_result(cmts_result result, size_t* out_size) { size_t i; i = (size_t)result; i += CMTS_RESULT_BEGIN_ENUM; CMTS_UNLIKELY_IF(i >= CMTS_ARRAY_SIZE(format_result_names)) return NULL; CMTS_LIKELY_IF(out_size != NULL) *out_size = format_result_sizes[i]; return format_result_names[i]; } #endif CMTS_ATTR cmts_bool CMTS_CALL cmts_ext_debug_enable_yield_trap(cmts_bool enable) { cmts_bool r; #ifdef CMTS_DEBUG r = yield_trap_flag; yield_trap_flag = enable; #else r = CMTS_FALSE; #endif return r; } CMTS_ATTR cmts_bool CMTS_CALL cmts_ext_debug_enabled() { #ifdef CMTS_DEBUG return debugger_callback != NULL; #else return 0; #endif } CMTS_ATTR void CMTS_CALL cmts_ext_debug_write(const cmts_ext_debug_message* message) { #ifdef CMTS_DEBUG CMTS_UNLIKELY_IF(debugger_callback != NULL) debugger_callback(debugger_context, message); #endif } CMTS_EXTERN_C_END #endif
35.817808
231
0.793234
[ "object" ]
fce6b20d0a663fe6cfd92883d7355a9b27909d42
190,621
c
C
api16/h5a.c
qsnake/h5py
45e77c3798032de2f740414a9e014fbca8c0ac18
[ "BSD-3-Clause" ]
null
null
null
api16/h5a.c
qsnake/h5py
45e77c3798032de2f740414a9e014fbca8c0ac18
[ "BSD-3-Clause" ]
null
null
null
api16/h5a.c
qsnake/h5py
45e77c3798032de2f740414a9e014fbca8c0ac18
[ "BSD-3-Clause" ]
8
2018-07-05T22:16:08.000Z
2021-08-19T06:07:45.000Z
/* Generated by Cython 0.12.1 on Tue Dec 21 22:31:51 2010 */ #define PY_SSIZE_T_CLEAN #include "Python.h" #include "structmember.h" #ifndef Py_PYTHON_H #error Python headers needed to compile C extensions, please install development version of Python. #else #ifndef PY_LONG_LONG #define PY_LONG_LONG LONG_LONG #endif #ifndef DL_EXPORT #define DL_EXPORT(t) t #endif #if PY_VERSION_HEX < 0x02040000 #define METH_COEXIST 0 #define PyDict_CheckExact(op) (Py_TYPE(op) == &PyDict_Type) #define PyDict_Contains(d,o) PySequence_Contains(d,o) #endif #if PY_VERSION_HEX < 0x02050000 typedef int Py_ssize_t; #define PY_SSIZE_T_MAX INT_MAX #define PY_SSIZE_T_MIN INT_MIN #define PY_FORMAT_SIZE_T "" #define PyInt_FromSsize_t(z) PyInt_FromLong(z) #define PyInt_AsSsize_t(o) PyInt_AsLong(o) #define PyNumber_Index(o) PyNumber_Int(o) #define PyIndex_Check(o) PyNumber_Check(o) #define PyErr_WarnEx(category, message, stacklevel) PyErr_Warn(category, message) #endif #if PY_VERSION_HEX < 0x02060000 #define Py_REFCNT(ob) (((PyObject*)(ob))->ob_refcnt) #define Py_TYPE(ob) (((PyObject*)(ob))->ob_type) #define Py_SIZE(ob) (((PyVarObject*)(ob))->ob_size) #define PyVarObject_HEAD_INIT(type, size) \ PyObject_HEAD_INIT(type) size, #define PyType_Modified(t) typedef struct { void *buf; PyObject *obj; Py_ssize_t len; Py_ssize_t itemsize; int readonly; int ndim; char *format; Py_ssize_t *shape; Py_ssize_t *strides; Py_ssize_t *suboffsets; void *internal; } Py_buffer; #define PyBUF_SIMPLE 0 #define PyBUF_WRITABLE 0x0001 #define PyBUF_FORMAT 0x0004 #define PyBUF_ND 0x0008 #define PyBUF_STRIDES (0x0010 | PyBUF_ND) #define PyBUF_C_CONTIGUOUS (0x0020 | PyBUF_STRIDES) #define PyBUF_F_CONTIGUOUS (0x0040 | PyBUF_STRIDES) #define PyBUF_ANY_CONTIGUOUS (0x0080 | PyBUF_STRIDES) #define PyBUF_INDIRECT (0x0100 | PyBUF_STRIDES) #endif #if PY_MAJOR_VERSION < 3 #define __Pyx_BUILTIN_MODULE_NAME "__builtin__" #else #define __Pyx_BUILTIN_MODULE_NAME "builtins" #endif #if PY_MAJOR_VERSION >= 3 #define Py_TPFLAGS_CHECKTYPES 0 #define Py_TPFLAGS_HAVE_INDEX 0 #endif #if (PY_VERSION_HEX < 0x02060000) || (PY_MAJOR_VERSION >= 3) #define Py_TPFLAGS_HAVE_NEWBUFFER 0 #endif #if PY_MAJOR_VERSION >= 3 #define PyBaseString_Type PyUnicode_Type #define PyString_Type PyUnicode_Type #define PyString_CheckExact PyUnicode_CheckExact #else #define PyBytes_Type PyString_Type #define PyBytes_CheckExact PyString_CheckExact #endif #if PY_MAJOR_VERSION >= 3 #define PyInt_Type PyLong_Type #define PyInt_Check(op) PyLong_Check(op) #define PyInt_CheckExact(op) PyLong_CheckExact(op) #define PyInt_FromString PyLong_FromString #define PyInt_FromUnicode PyLong_FromUnicode #define PyInt_FromLong PyLong_FromLong #define PyInt_FromSize_t PyLong_FromSize_t #define PyInt_FromSsize_t PyLong_FromSsize_t #define PyInt_AsLong PyLong_AsLong #define PyInt_AS_LONG PyLong_AS_LONG #define PyInt_AsSsize_t PyLong_AsSsize_t #define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask #define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) #else #define __Pyx_PyNumber_Divide(x,y) PyNumber_Divide(x,y) #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceDivide(x,y) #endif #if PY_MAJOR_VERSION >= 3 #define PyMethod_New(func, self, klass) PyInstanceMethod_New(func) #endif #if !defined(WIN32) && !defined(MS_WINDOWS) #ifndef __stdcall #define __stdcall #endif #ifndef __cdecl #define __cdecl #endif #ifndef __fastcall #define __fastcall #endif #else #define _USE_MATH_DEFINES #endif #if PY_VERSION_HEX < 0x02050000 #define __Pyx_GetAttrString(o,n) PyObject_GetAttrString((o),((char *)(n))) #define __Pyx_SetAttrString(o,n,a) PyObject_SetAttrString((o),((char *)(n)),(a)) #define __Pyx_DelAttrString(o,n) PyObject_DelAttrString((o),((char *)(n))) #else #define __Pyx_GetAttrString(o,n) PyObject_GetAttrString((o),(n)) #define __Pyx_SetAttrString(o,n,a) PyObject_SetAttrString((o),(n),(a)) #define __Pyx_DelAttrString(o,n) PyObject_DelAttrString((o),(n)) #endif #if PY_VERSION_HEX < 0x02050000 #define __Pyx_NAMESTR(n) ((char *)(n)) #define __Pyx_DOCSTR(n) ((char *)(n)) #else #define __Pyx_NAMESTR(n) (n) #define __Pyx_DOCSTR(n) (n) #endif #ifdef __cplusplus #define __PYX_EXTERN_C extern "C" #else #define __PYX_EXTERN_C extern #endif #include <math.h> #define __PYX_HAVE_API__h5py__h5a #include "stdlib.h" #include "string.h" #include "time.h" #include "unistd.h" #include "stdint.h" #include "compat.h" #include "lzf_filter.h" #include "hdf5.h" #include "numpy/arrayobject.h" #ifndef CYTHON_INLINE #if defined(__GNUC__) #define CYTHON_INLINE __inline__ #elif defined(_MSC_VER) #define CYTHON_INLINE __inline #else #define CYTHON_INLINE #endif #endif typedef struct {PyObject **p; char *s; const long n; const char* encoding; const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; /*proto*/ /* Type Conversion Predeclarations */ #if PY_MAJOR_VERSION < 3 #define __Pyx_PyBytes_FromString PyString_FromString #define __Pyx_PyBytes_FromStringAndSize PyString_FromStringAndSize #define __Pyx_PyBytes_AsString PyString_AsString #else #define __Pyx_PyBytes_FromString PyBytes_FromString #define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize #define __Pyx_PyBytes_AsString PyBytes_AsString #endif #define __Pyx_PyBytes_FromUString(s) __Pyx_PyBytes_FromString((char*)s) #define __Pyx_PyBytes_AsUString(s) ((unsigned char*) __Pyx_PyBytes_AsString(s)) #define __Pyx_PyBool_FromLong(b) ((b) ? (Py_INCREF(Py_True), Py_True) : (Py_INCREF(Py_False), Py_False)) static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*); static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x); #if !defined(T_PYSSIZET) #if PY_VERSION_HEX < 0x02050000 #define T_PYSSIZET T_INT #elif !defined(T_LONGLONG) #define T_PYSSIZET \ ((sizeof(Py_ssize_t) == sizeof(int)) ? T_INT : \ ((sizeof(Py_ssize_t) == sizeof(long)) ? T_LONG : -1)) #else #define T_PYSSIZET \ ((sizeof(Py_ssize_t) == sizeof(int)) ? T_INT : \ ((sizeof(Py_ssize_t) == sizeof(long)) ? T_LONG : \ ((sizeof(Py_ssize_t) == sizeof(PY_LONG_LONG)) ? T_LONGLONG : -1))) #endif #endif #if !defined(T_ULONGLONG) #define __Pyx_T_UNSIGNED_INT(x) \ ((sizeof(x) == sizeof(unsigned char)) ? T_UBYTE : \ ((sizeof(x) == sizeof(unsigned short)) ? T_USHORT : \ ((sizeof(x) == sizeof(unsigned int)) ? T_UINT : \ ((sizeof(x) == sizeof(unsigned long)) ? T_ULONG : -1)))) #else #define __Pyx_T_UNSIGNED_INT(x) \ ((sizeof(x) == sizeof(unsigned char)) ? T_UBYTE : \ ((sizeof(x) == sizeof(unsigned short)) ? T_USHORT : \ ((sizeof(x) == sizeof(unsigned int)) ? T_UINT : \ ((sizeof(x) == sizeof(unsigned long)) ? T_ULONG : \ ((sizeof(x) == sizeof(unsigned PY_LONG_LONG)) ? T_ULONGLONG : -1))))) #endif #if !defined(T_LONGLONG) #define __Pyx_T_SIGNED_INT(x) \ ((sizeof(x) == sizeof(char)) ? T_BYTE : \ ((sizeof(x) == sizeof(short)) ? T_SHORT : \ ((sizeof(x) == sizeof(int)) ? T_INT : \ ((sizeof(x) == sizeof(long)) ? T_LONG : -1)))) #else #define __Pyx_T_SIGNED_INT(x) \ ((sizeof(x) == sizeof(char)) ? T_BYTE : \ ((sizeof(x) == sizeof(short)) ? T_SHORT : \ ((sizeof(x) == sizeof(int)) ? T_INT : \ ((sizeof(x) == sizeof(long)) ? T_LONG : \ ((sizeof(x) == sizeof(PY_LONG_LONG)) ? T_LONGLONG : -1))))) #endif #define __Pyx_T_FLOATING(x) \ ((sizeof(x) == sizeof(float)) ? T_FLOAT : \ ((sizeof(x) == sizeof(double)) ? T_DOUBLE : -1)) #if !defined(T_SIZET) #if !defined(T_ULONGLONG) #define T_SIZET \ ((sizeof(size_t) == sizeof(unsigned int)) ? T_UINT : \ ((sizeof(size_t) == sizeof(unsigned long)) ? T_ULONG : -1)) #else #define T_SIZET \ ((sizeof(size_t) == sizeof(unsigned int)) ? T_UINT : \ ((sizeof(size_t) == sizeof(unsigned long)) ? T_ULONG : \ ((sizeof(size_t) == sizeof(unsigned PY_LONG_LONG)) ? T_ULONGLONG : -1))) #endif #endif static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*); static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t); static CYTHON_INLINE size_t __Pyx_PyInt_AsSize_t(PyObject*); #define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x)) #ifdef __GNUC__ /* Test for GCC > 2.95 */ #if __GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95)) #define likely(x) __builtin_expect(!!(x), 1) #define unlikely(x) __builtin_expect(!!(x), 0) #else /* __GNUC__ > 2 ... */ #define likely(x) (x) #define unlikely(x) (x) #endif /* __GNUC__ > 2 ... */ #else /* __GNUC__ */ #define likely(x) (x) #define unlikely(x) (x) #endif /* __GNUC__ */ static PyObject *__pyx_m; static PyObject *__pyx_b; static PyObject *__pyx_empty_tuple; static PyObject *__pyx_empty_bytes; static int __pyx_lineno; static int __pyx_clineno = 0; static const char * __pyx_cfilenm= __FILE__; static const char *__pyx_filename; static const char **__pyx_f; /* Type declarations */ /* "/home/tachyon/h5py/h5py/h5t.pxd":72 * * cdef TypeID typewrap(hid_t id_) * cpdef TypeID py_create(object dtype, bint logical=*) # <<<<<<<<<<<<<< * * */ struct __pyx_opt_args_4h5py_3h5t_py_create { int __pyx_n; int logical; }; /* "/home/tachyon/h5py/h5py/utils.pxd":20 * cdef void efree(void* ptr) * * cpdef int check_numpy_read(ndarray arr, hid_t space_id=*) except -1 # <<<<<<<<<<<<<< * cpdef int check_numpy_write(ndarray arr, hid_t space_id=*) except -1 * */ struct __pyx_opt_args_4h5py_5utils_check_numpy_read { int __pyx_n; hid_t space_id; }; /* "/home/tachyon/h5py/h5py/utils.pxd":21 * * cpdef int check_numpy_read(ndarray arr, hid_t space_id=*) except -1 * cpdef int check_numpy_write(ndarray arr, hid_t space_id=*) except -1 # <<<<<<<<<<<<<< * * cdef int convert_tuple(object tuple, hsize_t *dims, hsize_t rank) except -1 */ struct __pyx_opt_args_4h5py_5utils_check_numpy_write { int __pyx_n; hid_t space_id; }; /* "/home/tachyon/h5py/h5py/h5a.pyx":282 * # === Iteration routines ====================================================== * * cdef class _AttrVisitor: # <<<<<<<<<<<<<< * cdef object func * cdef object retval */ struct __pyx_obj_4h5py_3h5a__AttrVisitor { PyObject_HEAD PyObject *func; PyObject *retval; }; /* "/home/tachyon/h5py/h5py/h5.pxd":34 * cdef readonly int locked * * cdef class ObjectID: # <<<<<<<<<<<<<< * * cdef object __weakref__ */ struct __pyx_obj_4h5py_2h5_ObjectID { PyObject_HEAD PyObject *__weakref__; struct __pyx_obj_4h5py_2h5_IDProxy *_proxy; PyObject *_hash; }; /* "/home/tachyon/h5py/h5py/h5p.pxd":23 * # --- Base classes --- * * cdef class PropID(ObjectID): # <<<<<<<<<<<<<< * """ Base class for all property lists """ * pass */ struct __pyx_obj_4h5py_3h5p_PropID { struct __pyx_obj_4h5py_2h5_ObjectID __pyx_base; }; /* "/home/tachyon/h5py/h5py/h5p.pxd":33 * pass * * cdef class PropInstanceID(PropID): # <<<<<<<<<<<<<< * """ Represents an instance of a property list class (i.e. an actual list * which can be passed on to other API functions). */ struct __pyx_obj_4h5py_3h5p_PropInstanceID { struct __pyx_obj_4h5py_3h5p_PropID __pyx_base; }; /* "/home/tachyon/h5py/h5py/h5p.pxd":62 * # --- Object access --- * * cdef class PropFAID(PropInstanceID): # <<<<<<<<<<<<<< * """ File access property list """ * pass */ struct __pyx_obj_4h5py_3h5p_PropFAID { struct __pyx_obj_4h5py_3h5p_PropInstanceID __pyx_base; }; /* "/home/tachyon/h5py/h5py/h5t.pxd":17 * from h5 cimport class ObjectID * * cdef class TypeID(ObjectID): # <<<<<<<<<<<<<< * * cdef object py_dtype(self) */ struct __pyx_obj_4h5py_3h5t_TypeID { struct __pyx_obj_4h5py_2h5_ObjectID __pyx_base; struct __pyx_vtabstruct_4h5py_3h5t_TypeID *__pyx_vtab; }; /* "/home/tachyon/h5py/h5py/h5t.pxd":40 * pass * * cdef class TypeBitfieldID(TypeID): # <<<<<<<<<<<<<< * pass * */ struct __pyx_obj_4h5py_3h5t_TypeBitfieldID { struct __pyx_obj_4h5py_3h5t_TypeID __pyx_base; }; /* "/home/tachyon/h5py/h5py/h5p.pxd":39 * pass * * cdef class PropCreateID(PropInstanceID): # <<<<<<<<<<<<<< * """ Base class for all object creation lists. * */ struct __pyx_obj_4h5py_3h5p_PropCreateID { struct __pyx_obj_4h5py_3h5p_PropInstanceID __pyx_base; }; /* "/home/tachyon/h5py/h5py/h5p.pxd":55 * pass * * cdef class PropFCID(PropCreateID): # <<<<<<<<<<<<<< * """ File creation property list """ * pass */ struct __pyx_obj_4h5py_3h5p_PropFCID { struct __pyx_obj_4h5py_3h5p_PropCreateID __pyx_base; }; /* "/home/tachyon/h5py/h5py/h5p.pxd":27 * pass * * cdef class PropClassID(PropID): # <<<<<<<<<<<<<< * """ Represents an HDF5 property list class. These can be either (locked) * library-defined classes or user-created classes. */ struct __pyx_obj_4h5py_3h5p_PropClassID { struct __pyx_obj_4h5py_3h5p_PropID __pyx_base; }; /* "/home/tachyon/h5py/h5py/h5t.pxd":59 * # --- Enums & compound types --- * * cdef class TypeCompositeID(TypeID): # <<<<<<<<<<<<<< * pass * */ struct __pyx_obj_4h5py_3h5t_TypeCompositeID { struct __pyx_obj_4h5py_3h5t_TypeID __pyx_base; }; /* "/home/tachyon/h5py/h5py/h5t.pxd":66 * cdef int enum_convert(self, long long *buf, int reverse) except -1 * * cdef class TypeCompoundID(TypeCompositeID): # <<<<<<<<<<<<<< * pass * */ struct __pyx_obj_4h5py_3h5t_TypeCompoundID { struct __pyx_obj_4h5py_3h5t_TypeCompositeID __pyx_base; }; /* "/home/tachyon/h5py/h5py/h5t.pxd":33 * pass * * cdef class TypeVlenID(TypeID): # <<<<<<<<<<<<<< * # Non-string vlens * pass */ struct __pyx_obj_4h5py_3h5t_TypeVlenID { struct __pyx_obj_4h5py_3h5t_TypeID __pyx_base; }; /* "/home/tachyon/h5py/h5py/h5p.pxd":51 * # --- Object creation --- * * cdef class PropDCID(PropCreateID): # <<<<<<<<<<<<<< * """ Dataset creation property list """ * pass */ struct __pyx_obj_4h5py_3h5p_PropDCID { struct __pyx_obj_4h5py_3h5p_PropCreateID __pyx_base; }; /* "/home/tachyon/h5py/h5py/h5t.pxd":37 * pass * * cdef class TypeTimeID(TypeID): # <<<<<<<<<<<<<< * pass * */ struct __pyx_obj_4h5py_3h5t_TypeTimeID { struct __pyx_obj_4h5py_3h5t_TypeID __pyx_base; }; /* "/home/tachyon/h5py/h5py/h5t.pxd":23 * # --- Top-level classes --- * * cdef class TypeArrayID(TypeID): # <<<<<<<<<<<<<< * pass * */ struct __pyx_obj_4h5py_3h5t_TypeArrayID { struct __pyx_obj_4h5py_3h5t_TypeID __pyx_base; }; /* "/home/tachyon/h5py/h5py/h5t.pxd":48 * # --- Numeric atomic types --- * * cdef class TypeAtomicID(TypeID): # <<<<<<<<<<<<<< * pass * */ struct __pyx_obj_4h5py_3h5t_TypeAtomicID { struct __pyx_obj_4h5py_3h5t_TypeID __pyx_base; }; /* "/home/tachyon/h5py/h5py/h5t.pxd":54 * pass * * cdef class TypeFloatID(TypeAtomicID): # <<<<<<<<<<<<<< * pass * */ struct __pyx_obj_4h5py_3h5t_TypeFloatID { struct __pyx_obj_4h5py_3h5t_TypeAtomicID __pyx_base; }; /* "/home/tachyon/h5py/h5py/h5t.pxd":29 * pass * * cdef class TypeStringID(TypeID): # <<<<<<<<<<<<<< * # Both vlen and fixed-len strings * pass */ struct __pyx_obj_4h5py_3h5t_TypeStringID { struct __pyx_obj_4h5py_3h5t_TypeID __pyx_base; }; /* "/home/tachyon/h5py/h5py/h5t.pxd":26 * pass * * cdef class TypeOpaqueID(TypeID): # <<<<<<<<<<<<<< * pass * */ struct __pyx_obj_4h5py_3h5t_TypeOpaqueID { struct __pyx_obj_4h5py_3h5t_TypeID __pyx_base; }; /* "/home/tachyon/h5py/h5py/h5t.pxd":62 * pass * * cdef class TypeEnumID(TypeCompositeID): # <<<<<<<<<<<<<< * * cdef int enum_convert(self, long long *buf, int reverse) except -1 */ struct __pyx_obj_4h5py_3h5t_TypeEnumID { struct __pyx_obj_4h5py_3h5t_TypeCompositeID __pyx_base; }; /* "/home/tachyon/h5py/h5py/h5.pxd":15 * include "defs.pxd" * * cdef class H5PYConfig: # <<<<<<<<<<<<<< * * cdef object _r_name */ struct __pyx_obj_4h5py_2h5_H5PYConfig { PyObject_HEAD PyObject *_r_name; PyObject *_i_name; PyObject *_f_name; PyObject *_t_name; PyObject *API_16; PyObject *API_18; PyObject *DEBUG; PyObject *THREADS; }; /* "/home/tachyon/h5py/h5py/h5p.pxd":46 * pass * * cdef class PropCopyID(PropInstanceID): # <<<<<<<<<<<<<< * """ Property list for copying objects (as in h5o.copy) """ * */ struct __pyx_obj_4h5py_3h5p_PropCopyID { struct __pyx_obj_4h5py_3h5p_PropInstanceID __pyx_base; }; /* "/home/tachyon/h5py/h5py/h5.pxd":28 * cpdef H5PYConfig get_config() * * cdef class IDProxy: # <<<<<<<<<<<<<< * * cdef object __weakref__ */ struct __pyx_obj_4h5py_2h5_IDProxy { PyObject_HEAD PyObject *__weakref__; hid_t id; int locked; }; /* "/home/tachyon/h5py/h5py/h5t.pxd":51 * pass * * cdef class TypeIntegerID(TypeAtomicID): # <<<<<<<<<<<<<< * pass * */ struct __pyx_obj_4h5py_3h5t_TypeIntegerID { struct __pyx_obj_4h5py_3h5t_TypeAtomicID __pyx_base; }; /* "/home/tachyon/h5py/h5py/h5t.pxd":43 * pass * * cdef class TypeReferenceID(TypeID): # <<<<<<<<<<<<<< * pass * */ struct __pyx_obj_4h5py_3h5t_TypeReferenceID { struct __pyx_obj_4h5py_3h5t_TypeID __pyx_base; }; /* "/home/tachyon/h5py/h5py/h5p.pxd":66 * pass * * cdef class PropDXID(PropInstanceID): # <<<<<<<<<<<<<< * """ Dataset transfer property list """ * pass */ struct __pyx_obj_4h5py_3h5p_PropDXID { struct __pyx_obj_4h5py_3h5p_PropInstanceID __pyx_base; }; /* "/home/tachyon/h5py/h5py/h5.pxd":40 * cdef object _hash * * cdef class SmartStruct: # <<<<<<<<<<<<<< * cdef object __weakref__ * cdef object _title */ struct __pyx_obj_4h5py_2h5_SmartStruct { PyObject_HEAD PyObject *__weakref__; PyObject *_title; }; /* "/home/tachyon/h5py/h5py/h5s.pxd":17 * from h5 cimport class ObjectID * * cdef class SpaceID(ObjectID): # <<<<<<<<<<<<<< * pass * */ struct __pyx_obj_4h5py_3h5s_SpaceID { struct __pyx_obj_4h5py_2h5_ObjectID __pyx_base; }; struct __pyx_obj_4h5py_3h5a_AttrID { struct __pyx_obj_4h5py_2h5_ObjectID __pyx_base; }; struct __pyx_vtabstruct_4h5py_3h5t_TypeID { PyObject *(*py_dtype)(struct __pyx_obj_4h5py_3h5t_TypeID *); }; static struct __pyx_vtabstruct_4h5py_3h5t_TypeID *__pyx_vtabptr_4h5py_3h5t_TypeID; /* "/home/tachyon/h5py/h5py/h5t.pxd":59 * # --- Enums & compound types --- * * cdef class TypeCompositeID(TypeID): # <<<<<<<<<<<<<< * pass * */ struct __pyx_vtabstruct_4h5py_3h5t_TypeCompositeID { struct __pyx_vtabstruct_4h5py_3h5t_TypeID __pyx_base; }; static struct __pyx_vtabstruct_4h5py_3h5t_TypeCompositeID *__pyx_vtabptr_4h5py_3h5t_TypeCompositeID; /* "/home/tachyon/h5py/h5py/h5t.pxd":66 * cdef int enum_convert(self, long long *buf, int reverse) except -1 * * cdef class TypeCompoundID(TypeCompositeID): # <<<<<<<<<<<<<< * pass * */ struct __pyx_vtabstruct_4h5py_3h5t_TypeCompoundID { struct __pyx_vtabstruct_4h5py_3h5t_TypeCompositeID __pyx_base; }; static struct __pyx_vtabstruct_4h5py_3h5t_TypeCompoundID *__pyx_vtabptr_4h5py_3h5t_TypeCompoundID; /* "/home/tachyon/h5py/h5py/h5t.pxd":26 * pass * * cdef class TypeOpaqueID(TypeID): # <<<<<<<<<<<<<< * pass * */ struct __pyx_vtabstruct_4h5py_3h5t_TypeOpaqueID { struct __pyx_vtabstruct_4h5py_3h5t_TypeID __pyx_base; }; static struct __pyx_vtabstruct_4h5py_3h5t_TypeOpaqueID *__pyx_vtabptr_4h5py_3h5t_TypeOpaqueID; /* "/home/tachyon/h5py/h5py/h5t.pxd":23 * # --- Top-level classes --- * * cdef class TypeArrayID(TypeID): # <<<<<<<<<<<<<< * pass * */ struct __pyx_vtabstruct_4h5py_3h5t_TypeArrayID { struct __pyx_vtabstruct_4h5py_3h5t_TypeID __pyx_base; }; static struct __pyx_vtabstruct_4h5py_3h5t_TypeArrayID *__pyx_vtabptr_4h5py_3h5t_TypeArrayID; /* "/home/tachyon/h5py/h5py/h5t.pxd":48 * # --- Numeric atomic types --- * * cdef class TypeAtomicID(TypeID): # <<<<<<<<<<<<<< * pass * */ struct __pyx_vtabstruct_4h5py_3h5t_TypeAtomicID { struct __pyx_vtabstruct_4h5py_3h5t_TypeID __pyx_base; }; static struct __pyx_vtabstruct_4h5py_3h5t_TypeAtomicID *__pyx_vtabptr_4h5py_3h5t_TypeAtomicID; /* "/home/tachyon/h5py/h5py/h5t.pxd":51 * pass * * cdef class TypeIntegerID(TypeAtomicID): # <<<<<<<<<<<<<< * pass * */ struct __pyx_vtabstruct_4h5py_3h5t_TypeIntegerID { struct __pyx_vtabstruct_4h5py_3h5t_TypeAtomicID __pyx_base; }; static struct __pyx_vtabstruct_4h5py_3h5t_TypeIntegerID *__pyx_vtabptr_4h5py_3h5t_TypeIntegerID; /* "/home/tachyon/h5py/h5py/h5t.pxd":43 * pass * * cdef class TypeReferenceID(TypeID): # <<<<<<<<<<<<<< * pass * */ struct __pyx_vtabstruct_4h5py_3h5t_TypeReferenceID { struct __pyx_vtabstruct_4h5py_3h5t_TypeID __pyx_base; }; static struct __pyx_vtabstruct_4h5py_3h5t_TypeReferenceID *__pyx_vtabptr_4h5py_3h5t_TypeReferenceID; /* "/home/tachyon/h5py/h5py/h5t.pxd":29 * pass * * cdef class TypeStringID(TypeID): # <<<<<<<<<<<<<< * # Both vlen and fixed-len strings * pass */ struct __pyx_vtabstruct_4h5py_3h5t_TypeStringID { struct __pyx_vtabstruct_4h5py_3h5t_TypeID __pyx_base; }; static struct __pyx_vtabstruct_4h5py_3h5t_TypeStringID *__pyx_vtabptr_4h5py_3h5t_TypeStringID; /* "/home/tachyon/h5py/h5py/h5t.pxd":54 * pass * * cdef class TypeFloatID(TypeAtomicID): # <<<<<<<<<<<<<< * pass * */ struct __pyx_vtabstruct_4h5py_3h5t_TypeFloatID { struct __pyx_vtabstruct_4h5py_3h5t_TypeAtomicID __pyx_base; }; static struct __pyx_vtabstruct_4h5py_3h5t_TypeFloatID *__pyx_vtabptr_4h5py_3h5t_TypeFloatID; /* "/home/tachyon/h5py/h5py/h5t.pxd":37 * pass * * cdef class TypeTimeID(TypeID): # <<<<<<<<<<<<<< * pass * */ struct __pyx_vtabstruct_4h5py_3h5t_TypeTimeID { struct __pyx_vtabstruct_4h5py_3h5t_TypeID __pyx_base; }; static struct __pyx_vtabstruct_4h5py_3h5t_TypeTimeID *__pyx_vtabptr_4h5py_3h5t_TypeTimeID; /* "/home/tachyon/h5py/h5py/h5t.pxd":40 * pass * * cdef class TypeBitfieldID(TypeID): # <<<<<<<<<<<<<< * pass * */ struct __pyx_vtabstruct_4h5py_3h5t_TypeBitfieldID { struct __pyx_vtabstruct_4h5py_3h5t_TypeID __pyx_base; }; static struct __pyx_vtabstruct_4h5py_3h5t_TypeBitfieldID *__pyx_vtabptr_4h5py_3h5t_TypeBitfieldID; /* "/home/tachyon/h5py/h5py/h5t.pxd":33 * pass * * cdef class TypeVlenID(TypeID): # <<<<<<<<<<<<<< * # Non-string vlens * pass */ struct __pyx_vtabstruct_4h5py_3h5t_TypeVlenID { struct __pyx_vtabstruct_4h5py_3h5t_TypeID __pyx_base; }; static struct __pyx_vtabstruct_4h5py_3h5t_TypeVlenID *__pyx_vtabptr_4h5py_3h5t_TypeVlenID; /* "/home/tachyon/h5py/h5py/h5t.pxd":62 * pass * * cdef class TypeEnumID(TypeCompositeID): # <<<<<<<<<<<<<< * * cdef int enum_convert(self, long long *buf, int reverse) except -1 */ struct __pyx_vtabstruct_4h5py_3h5t_TypeEnumID { struct __pyx_vtabstruct_4h5py_3h5t_TypeCompositeID __pyx_base; int (*enum_convert)(struct __pyx_obj_4h5py_3h5t_TypeEnumID *, PY_LONG_LONG *, int); }; static struct __pyx_vtabstruct_4h5py_3h5t_TypeEnumID *__pyx_vtabptr_4h5py_3h5t_TypeEnumID; #ifndef CYTHON_REFNANNY #define CYTHON_REFNANNY 0 #endif #if CYTHON_REFNANNY typedef struct { void (*INCREF)(void*, PyObject*, int); void (*DECREF)(void*, PyObject*, int); void (*GOTREF)(void*, PyObject*, int); void (*GIVEREF)(void*, PyObject*, int); void* (*SetupContext)(const char*, int, const char*); void (*FinishContext)(void**); } __Pyx_RefNannyAPIStruct; static __Pyx_RefNannyAPIStruct *__Pyx_RefNanny = NULL; static __Pyx_RefNannyAPIStruct * __Pyx_RefNannyImportAPI(const char *modname) { PyObject *m = NULL, *p = NULL; void *r = NULL; m = PyImport_ImportModule((char *)modname); if (!m) goto end; p = PyObject_GetAttrString(m, (char *)"RefNannyAPI"); if (!p) goto end; r = PyLong_AsVoidPtr(p); end: Py_XDECREF(p); Py_XDECREF(m); return (__Pyx_RefNannyAPIStruct *)r; } #define __Pyx_RefNannySetupContext(name) void *__pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__) #define __Pyx_RefNannyFinishContext() __Pyx_RefNanny->FinishContext(&__pyx_refnanny) #define __Pyx_INCREF(r) __Pyx_RefNanny->INCREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_DECREF(r) __Pyx_RefNanny->DECREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_GOTREF(r) __Pyx_RefNanny->GOTREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_GIVEREF(r) __Pyx_RefNanny->GIVEREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_XDECREF(r) do { if((r) != NULL) {__Pyx_DECREF(r);} } while(0) #else #define __Pyx_RefNannySetupContext(name) #define __Pyx_RefNannyFinishContext() #define __Pyx_INCREF(r) Py_INCREF(r) #define __Pyx_DECREF(r) Py_DECREF(r) #define __Pyx_GOTREF(r) #define __Pyx_GIVEREF(r) #define __Pyx_XDECREF(r) Py_XDECREF(r) #endif /* CYTHON_REFNANNY */ #define __Pyx_XGIVEREF(r) do { if((r) != NULL) {__Pyx_GIVEREF(r);} } while(0) #define __Pyx_XGOTREF(r) do { if((r) != NULL) {__Pyx_GOTREF(r);} } while(0) static void __Pyx_RaiseDoubleKeywordsError( const char* func_name, PyObject* kw_name); /*proto*/ static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact, Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); /*proto*/ static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[], PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args, const char* function_name); /*proto*/ static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); /*proto*/ static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb); /*proto*/ static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb); /*proto*/ static int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, const char *name, int exact); /*proto*/ static CYTHON_INLINE hid_t __Pyx_PyInt_from_py_hid_t(PyObject *); static CYTHON_INLINE PyObject *__Pyx_PyInt_to_py_hid_t(hid_t); static PyObject *__Pyx_GetName(PyObject *dict, PyObject *name); /*proto*/ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb); /*proto*/ static CYTHON_INLINE unsigned char __Pyx_PyInt_AsUnsignedChar(PyObject *); static CYTHON_INLINE unsigned short __Pyx_PyInt_AsUnsignedShort(PyObject *); static CYTHON_INLINE unsigned int __Pyx_PyInt_AsUnsignedInt(PyObject *); static CYTHON_INLINE char __Pyx_PyInt_AsChar(PyObject *); static CYTHON_INLINE short __Pyx_PyInt_AsShort(PyObject *); static CYTHON_INLINE int __Pyx_PyInt_AsInt(PyObject *); static CYTHON_INLINE signed char __Pyx_PyInt_AsSignedChar(PyObject *); static CYTHON_INLINE signed short __Pyx_PyInt_AsSignedShort(PyObject *); static CYTHON_INLINE signed int __Pyx_PyInt_AsSignedInt(PyObject *); static CYTHON_INLINE unsigned long __Pyx_PyInt_AsUnsignedLong(PyObject *); static CYTHON_INLINE unsigned PY_LONG_LONG __Pyx_PyInt_AsUnsignedLongLong(PyObject *); static CYTHON_INLINE long __Pyx_PyInt_AsLong(PyObject *); static CYTHON_INLINE PY_LONG_LONG __Pyx_PyInt_AsLongLong(PyObject *); static CYTHON_INLINE signed long __Pyx_PyInt_AsSignedLong(PyObject *); static CYTHON_INLINE signed PY_LONG_LONG __Pyx_PyInt_AsSignedLongLong(PyObject *); static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, long size, int strict); /*proto*/ static PyObject *__Pyx_ImportModule(const char *name); /*proto*/ static int __Pyx_GetVtable(PyObject *dict, void *vtabptr); /*proto*/ static int __Pyx_ImportFunction(PyObject *module, const char *funcname, void (**f)(void), const char *sig); /*proto*/ static void __Pyx_AddTraceback(const char *funcname); /*proto*/ static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); /*proto*/ /* Module declarations from h5py.h5 */ static PyTypeObject *__pyx_ptype_4h5py_2h5_H5PYConfig = 0; static PyTypeObject *__pyx_ptype_4h5py_2h5_IDProxy = 0; static PyTypeObject *__pyx_ptype_4h5py_2h5_ObjectID = 0; static PyTypeObject *__pyx_ptype_4h5py_2h5_SmartStruct = 0; static struct __pyx_obj_4h5py_2h5_H5PYConfig *(*__pyx_f_4h5py_2h5_get_config)(int __pyx_skip_dispatch); /*proto*/ static int (*__pyx_f_4h5py_2h5_init_hdf5)(void); /*proto*/ /* Module declarations from h5py.h5t */ static PyTypeObject *__pyx_ptype_4h5py_3h5t_TypeID = 0; static PyTypeObject *__pyx_ptype_4h5py_3h5t_TypeArrayID = 0; static PyTypeObject *__pyx_ptype_4h5py_3h5t_TypeOpaqueID = 0; static PyTypeObject *__pyx_ptype_4h5py_3h5t_TypeStringID = 0; static PyTypeObject *__pyx_ptype_4h5py_3h5t_TypeVlenID = 0; static PyTypeObject *__pyx_ptype_4h5py_3h5t_TypeTimeID = 0; static PyTypeObject *__pyx_ptype_4h5py_3h5t_TypeBitfieldID = 0; static PyTypeObject *__pyx_ptype_4h5py_3h5t_TypeReferenceID = 0; static PyTypeObject *__pyx_ptype_4h5py_3h5t_TypeAtomicID = 0; static PyTypeObject *__pyx_ptype_4h5py_3h5t_TypeIntegerID = 0; static PyTypeObject *__pyx_ptype_4h5py_3h5t_TypeFloatID = 0; static PyTypeObject *__pyx_ptype_4h5py_3h5t_TypeCompositeID = 0; static PyTypeObject *__pyx_ptype_4h5py_3h5t_TypeEnumID = 0; static PyTypeObject *__pyx_ptype_4h5py_3h5t_TypeCompoundID = 0; static struct __pyx_obj_4h5py_3h5t_TypeID *(*__pyx_f_4h5py_3h5t_typewrap)(hid_t); /*proto*/ static struct __pyx_obj_4h5py_3h5t_TypeID *(*__pyx_f_4h5py_3h5t_py_create)(PyObject *, int __pyx_skip_dispatch, struct __pyx_opt_args_4h5py_3h5t_py_create *__pyx_optional_args); /*proto*/ /* Module declarations from h5py.h5s */ static PyTypeObject *__pyx_ptype_4h5py_3h5s_SpaceID = 0; /* Module declarations from h5py.h5p */ static PyTypeObject *__pyx_ptype_4h5py_3h5p_PropID = 0; static PyTypeObject *__pyx_ptype_4h5py_3h5p_PropClassID = 0; static PyTypeObject *__pyx_ptype_4h5py_3h5p_PropInstanceID = 0; static PyTypeObject *__pyx_ptype_4h5py_3h5p_PropCreateID = 0; static PyTypeObject *__pyx_ptype_4h5py_3h5p_PropCopyID = 0; static PyTypeObject *__pyx_ptype_4h5py_3h5p_PropDCID = 0; static PyTypeObject *__pyx_ptype_4h5py_3h5p_PropFCID = 0; static PyTypeObject *__pyx_ptype_4h5py_3h5p_PropFAID = 0; static PyTypeObject *__pyx_ptype_4h5py_3h5p_PropDXID = 0; static hid_t (*__pyx_f_4h5py_3h5p_pdefault)(struct __pyx_obj_4h5py_3h5p_PropID *); /*proto*/ static PyObject *(*__pyx_f_4h5py_3h5p_propwrap)(hid_t); /*proto*/ /* Module declarations from numpy */ /* Module declarations from h5py.numpy */ static PyTypeObject *__pyx_ptype_4h5py_5numpy_dtype = 0; static PyTypeObject *__pyx_ptype_4h5py_5numpy_ndarray = 0; /* Module declarations from h5py.utils */ static void *(*__pyx_f_4h5py_5utils_emalloc)(size_t); /*proto*/ static void (*__pyx_f_4h5py_5utils_efree)(void *); /*proto*/ static int (*__pyx_f_4h5py_5utils_check_numpy_read)(PyArrayObject *, int __pyx_skip_dispatch, struct __pyx_opt_args_4h5py_5utils_check_numpy_read *__pyx_optional_args); /*proto*/ static int (*__pyx_f_4h5py_5utils_check_numpy_write)(PyArrayObject *, int __pyx_skip_dispatch, struct __pyx_opt_args_4h5py_5utils_check_numpy_write *__pyx_optional_args); /*proto*/ static int (*__pyx_f_4h5py_5utils_convert_tuple)(PyObject *, hsize_t *, hsize_t); /*proto*/ static PyObject *(*__pyx_f_4h5py_5utils_convert_dims)(hsize_t *, hsize_t); /*proto*/ static int (*__pyx_f_4h5py_5utils_require_tuple)(PyObject *, int, int, char *); /*proto*/ static PyObject *(*__pyx_f_4h5py_5utils_create_numpy_hsize)(int, hsize_t *); /*proto*/ static PyObject *(*__pyx_f_4h5py_5utils_create_hsize_array)(PyObject *); /*proto*/ /* Module declarations from h5py._proxy */ static herr_t (*__pyx_f_4h5py_6_proxy_attr_rw)(hid_t, hid_t, void *, int); /*proto*/ static herr_t (*__pyx_f_4h5py_6_proxy_dset_rw)(hid_t, hid_t, hid_t, hid_t, hid_t, void *, int); /*proto*/ /* Module declarations from h5py.h5a */ static PyTypeObject *__pyx_ptype_4h5py_3h5a_AttrID = 0; static PyTypeObject *__pyx_ptype_4h5py_3h5a__AttrVisitor = 0; static herr_t __pyx_f_4h5py_3h5a_cb_exist(hid_t, char *, void *); /*proto*/ static herr_t __pyx_f_4h5py_3h5a_cb_attr_iter(hid_t, char *, void *); /*proto*/ #define __Pyx_MODULE_NAME "h5py.h5a" int __pyx_module_is_main_h5py__h5a = 0; /* Implementation of h5py.h5a */ static PyObject *__pyx_builtin_TypeError; static PyObject *__pyx_builtin_ValueError; static char __pyx_k_1[] = "Exactly one of name or idx must be specified"; static char __pyx_k_2[] = "Starting index must be a non-negative integer."; static char __pyx_k_3[] = "get_simple_extent_dims"; static char __pyx_k_4[] = "The attribute's name"; static char __pyx_k_5[] = "A Numpy-style shape tuple representing the attribute's dataspace"; static char __pyx_k_6[] = "A Numpy-stype dtype object representing the attribute's datatype"; static char __pyx_k_7[] = "\n Provides access to the low-level HDF5 \"H5A\" attribute interface.\n"; static char __pyx_k__id[] = "id"; static char __pyx_k__loc[] = "loc"; static char __pyx_k__tid[] = "tid"; static char __pyx_k__func[] = "func"; static char __pyx_k__name[] = "name"; static char __pyx_k__dtype[] = "dtype"; static char __pyx_k__index[] = "index"; static char __pyx_k__space[] = "space"; static char __pyx_k__retval[] = "retval"; static char __pyx_k____main__[] = "__main__"; static char __pyx_k__get_name[] = "get_name"; static char __pyx_k__get_type[] = "get_type"; static char __pyx_k__py_dtype[] = "py_dtype"; static char __pyx_k__TypeError[] = "TypeError"; static char __pyx_k__get_space[] = "get_space"; static char __pyx_k__ValueError[] = "ValueError"; static PyObject *__pyx_kp_s_1; static PyObject *__pyx_kp_s_2; static PyObject *__pyx_n_s_3; static PyObject *__pyx_n_s__TypeError; static PyObject *__pyx_n_s__ValueError; static PyObject *__pyx_n_s____main__; static PyObject *__pyx_n_s__dtype; static PyObject *__pyx_n_s__func; static PyObject *__pyx_n_s__get_name; static PyObject *__pyx_n_s__get_space; static PyObject *__pyx_n_s__get_type; static PyObject *__pyx_n_s__id; static PyObject *__pyx_n_s__index; static PyObject *__pyx_n_s__loc; static PyObject *__pyx_n_s__name; static PyObject *__pyx_n_s__py_dtype; static PyObject *__pyx_n_s__retval; static PyObject *__pyx_n_s__space; static PyObject *__pyx_n_s__tid; /* "/home/tachyon/h5py/h5py/h5a.pyx":56 * ELSE: * * def create(ObjectID loc not None, char* name, TypeID tid not None, # <<<<<<<<<<<<<< * SpaceID space not None): * """(ObjectID loc, STRING name, TypeID tid, SpaceID space) => AttrID */ static PyObject *__pyx_pf_4h5py_3h5a_create(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static char __pyx_doc_4h5py_3h5a_create[] = "(ObjectID loc, STRING name, TypeID tid, SpaceID space) => AttrID\n\n Create a new attribute attached to a parent object, specifiying an \n HDF5 datatype and dataspace.\n "; static PyObject *__pyx_pf_4h5py_3h5a_create(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { struct __pyx_obj_4h5py_2h5_ObjectID *__pyx_v_loc = 0; char *__pyx_v_name; struct __pyx_obj_4h5py_3h5t_TypeID *__pyx_v_tid = 0; struct __pyx_obj_4h5py_3h5s_SpaceID *__pyx_v_space = 0; PyObject *__pyx_r = NULL; PyObject *__pyx_t_1 = NULL; hid_t __pyx_t_2; hid_t __pyx_t_3; hid_t __pyx_t_4; hid_t __pyx_t_5; PyObject *__pyx_t_6 = NULL; static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__loc,&__pyx_n_s__name,&__pyx_n_s__tid,&__pyx_n_s__space,0}; __Pyx_RefNannySetupContext("create"); __pyx_self = __pyx_self; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args = PyDict_Size(__pyx_kwds); PyObject* values[4] = {0,0,0,0}; switch (PyTuple_GET_SIZE(__pyx_args)) { case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); case 0: break; default: goto __pyx_L5_argtuple_error; } switch (PyTuple_GET_SIZE(__pyx_args)) { case 0: values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__loc); if (likely(values[0])) kw_args--; else goto __pyx_L5_argtuple_error; case 1: values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__name); if (likely(values[1])) kw_args--; else { __Pyx_RaiseArgtupleInvalid("create", 1, 4, 4, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 56; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 2: values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__tid); if (likely(values[2])) kw_args--; else { __Pyx_RaiseArgtupleInvalid("create", 1, 4, 4, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 56; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 3: values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__space); if (likely(values[3])) kw_args--; else { __Pyx_RaiseArgtupleInvalid("create", 1, 4, 4, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 56; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } if (unlikely(kw_args > 0)) { if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, PyTuple_GET_SIZE(__pyx_args), "create") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 56; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } __pyx_v_loc = ((struct __pyx_obj_4h5py_2h5_ObjectID *)values[0]); __pyx_v_name = __Pyx_PyBytes_AsString(values[1]); if (unlikely((!__pyx_v_name) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 56; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_tid = ((struct __pyx_obj_4h5py_3h5t_TypeID *)values[2]); __pyx_v_space = ((struct __pyx_obj_4h5py_3h5s_SpaceID *)values[3]); } else if (PyTuple_GET_SIZE(__pyx_args) != 4) { goto __pyx_L5_argtuple_error; } else { __pyx_v_loc = ((struct __pyx_obj_4h5py_2h5_ObjectID *)PyTuple_GET_ITEM(__pyx_args, 0)); __pyx_v_name = __Pyx_PyBytes_AsString(PyTuple_GET_ITEM(__pyx_args, 1)); if (unlikely((!__pyx_v_name) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 56; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_tid = ((struct __pyx_obj_4h5py_3h5t_TypeID *)PyTuple_GET_ITEM(__pyx_args, 2)); __pyx_v_space = ((struct __pyx_obj_4h5py_3h5s_SpaceID *)PyTuple_GET_ITEM(__pyx_args, 3)); } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("create", 1, 4, 4, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 56; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; __Pyx_AddTraceback("h5py.h5a.create"); return NULL; __pyx_L4_argument_unpacking_done:; if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_loc), __pyx_ptype_4h5py_2h5_ObjectID, 0, "loc", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 56; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_tid), __pyx_ptype_4h5py_3h5t_TypeID, 0, "tid", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 56; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_space), __pyx_ptype_4h5py_3h5s_SpaceID, 0, "space", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 57; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /* "/home/tachyon/h5py/h5py/h5a.pyx":63 * HDF5 datatype and dataspace. * """ * return AttrID(H5Acreate(loc.id, name, tid.id, space.id, H5P_DEFAULT)) # <<<<<<<<<<<<<< * * */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = PyObject_GetAttr(((PyObject *)__pyx_v_loc), __pyx_n_s__id); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 63; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = __Pyx_PyInt_from_py_hid_t(__pyx_t_1); if (unlikely((__pyx_t_2 == (hid_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 63; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_1 = PyObject_GetAttr(((PyObject *)__pyx_v_tid), __pyx_n_s__id); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 63; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_t_3 = __Pyx_PyInt_from_py_hid_t(__pyx_t_1); if (unlikely((__pyx_t_3 == (hid_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 63; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_1 = PyObject_GetAttr(((PyObject *)__pyx_v_space), __pyx_n_s__id); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 63; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_t_4 = __Pyx_PyInt_from_py_hid_t(__pyx_t_1); if (unlikely((__pyx_t_4 == (hid_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 63; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_5 = H5Acreate(__pyx_t_2, __pyx_v_name, __pyx_t_3, __pyx_t_4, H5P_DEFAULT); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 63; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_1 = __Pyx_PyInt_to_py_hid_t(__pyx_t_5); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 63; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_t_6 = PyTuple_New(1); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 63; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_6); PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_1); __Pyx_GIVEREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_1 = PyObject_Call(((PyObject *)((PyObject*)__pyx_ptype_4h5py_3h5a_AttrID)), __pyx_t_6, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 63; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_6); __Pyx_AddTraceback("h5py.h5a.create"); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "/home/tachyon/h5py/h5py/h5a.pyx":102 * ELSE: * * def open(ObjectID loc not None, char* name=NULL, int index=-1): # <<<<<<<<<<<<<< * """(ObjectID loc, STRING name=, INT index=) => AttrID * */ static PyObject *__pyx_pf_4h5py_3h5a_open(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static char __pyx_doc_4h5py_3h5a_open[] = "(ObjectID loc, STRING name=, INT index=) => AttrID\n\n Open an attribute attached to an existing object. You must specify\n exactly one of either name or idx.\n "; static PyObject *__pyx_pf_4h5py_3h5a_open(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { struct __pyx_obj_4h5py_2h5_ObjectID *__pyx_v_loc = 0; char *__pyx_v_name; int __pyx_v_index; PyObject *__pyx_r = NULL; int __pyx_t_1; int __pyx_t_2; int __pyx_t_3; int __pyx_t_4; PyObject *__pyx_t_5 = NULL; PyObject *__pyx_t_6 = NULL; hid_t __pyx_t_7; hid_t __pyx_t_8; static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__loc,&__pyx_n_s__name,&__pyx_n_s__index,0}; __Pyx_RefNannySetupContext("open"); __pyx_self = __pyx_self; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args = PyDict_Size(__pyx_kwds); PyObject* values[3] = {0,0,0}; switch (PyTuple_GET_SIZE(__pyx_args)) { case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); case 0: break; default: goto __pyx_L5_argtuple_error; } switch (PyTuple_GET_SIZE(__pyx_args)) { case 0: values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__loc); if (likely(values[0])) kw_args--; else goto __pyx_L5_argtuple_error; case 1: if (kw_args > 0) { PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__name); if (unlikely(value)) { values[1] = value; kw_args--; } } case 2: if (kw_args > 0) { PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__index); if (unlikely(value)) { values[2] = value; kw_args--; } } } if (unlikely(kw_args > 0)) { if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, PyTuple_GET_SIZE(__pyx_args), "open") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 102; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } __pyx_v_loc = ((struct __pyx_obj_4h5py_2h5_ObjectID *)values[0]); if (values[1]) { __pyx_v_name = __Pyx_PyBytes_AsString(values[1]); if (unlikely((!__pyx_v_name) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 102; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } else { __pyx_v_name = ((char *)NULL); } if (values[2]) { __pyx_v_index = __Pyx_PyInt_AsInt(values[2]); if (unlikely((__pyx_v_index == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 102; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } else { __pyx_v_index = ((int)-1); } } else { __pyx_v_name = ((char *)NULL); __pyx_v_index = ((int)-1); switch (PyTuple_GET_SIZE(__pyx_args)) { case 3: __pyx_v_index = __Pyx_PyInt_AsInt(PyTuple_GET_ITEM(__pyx_args, 2)); if (unlikely((__pyx_v_index == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 102; __pyx_clineno = __LINE__; goto __pyx_L3_error;} case 2: __pyx_v_name = __Pyx_PyBytes_AsString(PyTuple_GET_ITEM(__pyx_args, 1)); if (unlikely((!__pyx_v_name) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 102; __pyx_clineno = __LINE__; goto __pyx_L3_error;} case 1: __pyx_v_loc = ((struct __pyx_obj_4h5py_2h5_ObjectID *)PyTuple_GET_ITEM(__pyx_args, 0)); break; default: goto __pyx_L5_argtuple_error; } } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("open", 0, 1, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 102; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; __Pyx_AddTraceback("h5py.h5a.open"); return NULL; __pyx_L4_argument_unpacking_done:; __Pyx_INCREF((PyObject *)__pyx_v_loc); if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_loc), __pyx_ptype_4h5py_2h5_ObjectID, 0, "loc", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 102; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /* "/home/tachyon/h5py/h5py/h5a.pyx":108 * exactly one of either name or idx. * """ * if (name == NULL and index < 0) or (name != NULL and index >= 0): # <<<<<<<<<<<<<< * raise TypeError("Exactly one of name or idx must be specified") * */ __pyx_t_1 = (__pyx_v_name == NULL); if (__pyx_t_1) { __pyx_t_2 = (__pyx_v_index < 0); __pyx_t_3 = __pyx_t_2; } else { __pyx_t_3 = __pyx_t_1; } if (!__pyx_t_3) { __pyx_t_1 = (__pyx_v_name != NULL); if (__pyx_t_1) { __pyx_t_2 = (__pyx_v_index >= 0); __pyx_t_4 = __pyx_t_2; } else { __pyx_t_4 = __pyx_t_1; } __pyx_t_1 = __pyx_t_4; } else { __pyx_t_1 = __pyx_t_3; } if (__pyx_t_1) { /* "/home/tachyon/h5py/h5py/h5a.pyx":109 * """ * if (name == NULL and index < 0) or (name != NULL and index >= 0): * raise TypeError("Exactly one of name or idx must be specified") # <<<<<<<<<<<<<< * * if name != NULL: */ __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 109; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_INCREF(((PyObject *)__pyx_kp_s_1)); PyTuple_SET_ITEM(__pyx_t_5, 0, ((PyObject *)__pyx_kp_s_1)); __Pyx_GIVEREF(((PyObject *)__pyx_kp_s_1)); __pyx_t_6 = PyObject_Call(__pyx_builtin_TypeError, __pyx_t_5, NULL); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 109; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __Pyx_Raise(__pyx_t_6, 0, 0); __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; {__pyx_filename = __pyx_f[0]; __pyx_lineno = 109; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L6; } __pyx_L6:; /* "/home/tachyon/h5py/h5py/h5a.pyx":111 * raise TypeError("Exactly one of name or idx must be specified") * * if name != NULL: # <<<<<<<<<<<<<< * return AttrID(H5Aopen_name(loc.id, name)) * else: */ __pyx_t_1 = (__pyx_v_name != NULL); if (__pyx_t_1) { /* "/home/tachyon/h5py/h5py/h5a.pyx":112 * * if name != NULL: * return AttrID(H5Aopen_name(loc.id, name)) # <<<<<<<<<<<<<< * else: * return AttrID(H5Aopen_idx(loc.id, index)) */ __Pyx_XDECREF(__pyx_r); __pyx_t_6 = PyObject_GetAttr(((PyObject *)__pyx_v_loc), __pyx_n_s__id); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 112; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_6); __pyx_t_7 = __Pyx_PyInt_from_py_hid_t(__pyx_t_6); if (unlikely((__pyx_t_7 == (hid_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 112; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; __pyx_t_8 = H5Aopen_name(__pyx_t_7, __pyx_v_name); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 112; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_6 = __Pyx_PyInt_to_py_hid_t(__pyx_t_8); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 112; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_6); __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 112; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_6); __Pyx_GIVEREF(__pyx_t_6); __pyx_t_6 = 0; __pyx_t_6 = PyObject_Call(((PyObject *)((PyObject*)__pyx_ptype_4h5py_3h5a_AttrID)), __pyx_t_5, NULL); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 112; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_r = __pyx_t_6; __pyx_t_6 = 0; goto __pyx_L0; goto __pyx_L7; } /*else*/ { /* "/home/tachyon/h5py/h5py/h5a.pyx":114 * return AttrID(H5Aopen_name(loc.id, name)) * else: * return AttrID(H5Aopen_idx(loc.id, index)) # <<<<<<<<<<<<<< * * */ __Pyx_XDECREF(__pyx_r); __pyx_t_6 = PyObject_GetAttr(((PyObject *)__pyx_v_loc), __pyx_n_s__id); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 114; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_6); __pyx_t_8 = __Pyx_PyInt_from_py_hid_t(__pyx_t_6); if (unlikely((__pyx_t_8 == (hid_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 114; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; __pyx_t_7 = H5Aopen_idx(__pyx_t_8, __pyx_v_index); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 114; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_6 = __Pyx_PyInt_to_py_hid_t(__pyx_t_7); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 114; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_6); __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 114; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_6); __Pyx_GIVEREF(__pyx_t_6); __pyx_t_6 = 0; __pyx_t_6 = PyObject_Call(((PyObject *)((PyObject*)__pyx_ptype_4h5py_3h5a_AttrID)), __pyx_t_5, NULL); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 114; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_r = __pyx_t_6; __pyx_t_6 = 0; goto __pyx_L0; } __pyx_L7:; __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_5); __Pyx_XDECREF(__pyx_t_6); __Pyx_AddTraceback("h5py.h5a.open"); __pyx_r = NULL; __pyx_L0:; __Pyx_DECREF((PyObject *)__pyx_v_loc); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "/home/tachyon/h5py/h5py/h5a.pyx":136 * * ELSE: * cdef herr_t cb_exist(hid_t loc_id, char* attr_name, void* ref_name) except 2: # <<<<<<<<<<<<<< * * if strcmp(attr_name, <char*>ref_name) == 0: */ static herr_t __pyx_f_4h5py_3h5a_cb_exist(hid_t __pyx_v_loc_id, char *__pyx_v_attr_name, void *__pyx_v_ref_name) { herr_t __pyx_r; int __pyx_t_1; __Pyx_RefNannySetupContext("cb_exist"); /* "/home/tachyon/h5py/h5py/h5a.pyx":138 * cdef herr_t cb_exist(hid_t loc_id, char* attr_name, void* ref_name) except 2: * * if strcmp(attr_name, <char*>ref_name) == 0: # <<<<<<<<<<<<<< * return 1 * return 0 */ __pyx_t_1 = (strcmp(__pyx_v_attr_name, ((char *)__pyx_v_ref_name)) == 0); if (__pyx_t_1) { /* "/home/tachyon/h5py/h5py/h5a.pyx":139 * * if strcmp(attr_name, <char*>ref_name) == 0: * return 1 # <<<<<<<<<<<<<< * return 0 * */ __pyx_r = 1; goto __pyx_L0; goto __pyx_L3; } __pyx_L3:; /* "/home/tachyon/h5py/h5py/h5a.pyx":140 * if strcmp(attr_name, <char*>ref_name) == 0: * return 1 * return 0 # <<<<<<<<<<<<<< * * */ __pyx_r = 0; goto __pyx_L0; __pyx_r = 0; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "/home/tachyon/h5py/h5py/h5a.pyx":143 * * * def exists(ObjectID loc not None, char* name): # <<<<<<<<<<<<<< * """(ObjectID loc, STRING name) => BOOL * */ static PyObject *__pyx_pf_4h5py_3h5a_exists(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static char __pyx_doc_4h5py_3h5a_exists[] = "(ObjectID loc, STRING name) => BOOL\n\n Determine if an attribute named \"name\" is attached to this object.\n "; static PyObject *__pyx_pf_4h5py_3h5a_exists(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { struct __pyx_obj_4h5py_2h5_ObjectID *__pyx_v_loc = 0; char *__pyx_v_name; unsigned int __pyx_v_i; PyObject *__pyx_r = NULL; PyObject *__pyx_t_1 = NULL; hid_t __pyx_t_2; herr_t __pyx_t_3; static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__loc,&__pyx_n_s__name,0}; __Pyx_RefNannySetupContext("exists"); __pyx_self = __pyx_self; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args = PyDict_Size(__pyx_kwds); PyObject* values[2] = {0,0}; switch (PyTuple_GET_SIZE(__pyx_args)) { case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); case 0: break; default: goto __pyx_L5_argtuple_error; } switch (PyTuple_GET_SIZE(__pyx_args)) { case 0: values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__loc); if (likely(values[0])) kw_args--; else goto __pyx_L5_argtuple_error; case 1: values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__name); if (likely(values[1])) kw_args--; else { __Pyx_RaiseArgtupleInvalid("exists", 1, 2, 2, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 143; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } if (unlikely(kw_args > 0)) { if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, PyTuple_GET_SIZE(__pyx_args), "exists") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 143; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } __pyx_v_loc = ((struct __pyx_obj_4h5py_2h5_ObjectID *)values[0]); __pyx_v_name = __Pyx_PyBytes_AsString(values[1]); if (unlikely((!__pyx_v_name) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 143; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } else if (PyTuple_GET_SIZE(__pyx_args) != 2) { goto __pyx_L5_argtuple_error; } else { __pyx_v_loc = ((struct __pyx_obj_4h5py_2h5_ObjectID *)PyTuple_GET_ITEM(__pyx_args, 0)); __pyx_v_name = __Pyx_PyBytes_AsString(PyTuple_GET_ITEM(__pyx_args, 1)); if (unlikely((!__pyx_v_name) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 143; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("exists", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 143; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; __Pyx_AddTraceback("h5py.h5a.exists"); return NULL; __pyx_L4_argument_unpacking_done:; if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_loc), __pyx_ptype_4h5py_2h5_ObjectID, 0, "loc", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 143; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /* "/home/tachyon/h5py/h5py/h5a.pyx":148 * Determine if an attribute named "name" is attached to this object. * """ * cdef unsigned int i=0 # <<<<<<<<<<<<<< * * return <bint>H5Aiterate(loc.id, &i, <H5A_operator_t>cb_exist, <void*>name) */ __pyx_v_i = 0; /* "/home/tachyon/h5py/h5py/h5a.pyx":150 * cdef unsigned int i=0 * * return <bint>H5Aiterate(loc.id, &i, <H5A_operator_t>cb_exist, <void*>name) # <<<<<<<<<<<<<< * * */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = PyObject_GetAttr(((PyObject *)__pyx_v_loc), __pyx_n_s__id); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 150; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = __Pyx_PyInt_from_py_hid_t(__pyx_t_1); if (unlikely((__pyx_t_2 == (hid_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 150; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_3 = H5Aiterate(__pyx_t_2, (&__pyx_v_i), ((herr_t (*)(hid_t, char *, void *))__pyx_f_4h5py_3h5a_cb_exist), ((void *)__pyx_v_name)); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 150; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_1 = __Pyx_PyBool_FromLong(((int)__pyx_t_3)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 150; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("h5py.h5a.exists"); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "/home/tachyon/h5py/h5py/h5a.pyx":201 * ELSE: * * def delete(ObjectID loc not None, char* name): # <<<<<<<<<<<<<< * """(ObjectID loc, STRING name) * */ static PyObject *__pyx_pf_4h5py_3h5a_delete(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static char __pyx_doc_4h5py_3h5a_delete[] = "(ObjectID loc, STRING name)\n\n Remove an attribute from an object.\n "; static PyObject *__pyx_pf_4h5py_3h5a_delete(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { struct __pyx_obj_4h5py_2h5_ObjectID *__pyx_v_loc = 0; char *__pyx_v_name; PyObject *__pyx_r = NULL; PyObject *__pyx_t_1 = NULL; hid_t __pyx_t_2; herr_t __pyx_t_3; static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__loc,&__pyx_n_s__name,0}; __Pyx_RefNannySetupContext("delete"); __pyx_self = __pyx_self; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args = PyDict_Size(__pyx_kwds); PyObject* values[2] = {0,0}; switch (PyTuple_GET_SIZE(__pyx_args)) { case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); case 0: break; default: goto __pyx_L5_argtuple_error; } switch (PyTuple_GET_SIZE(__pyx_args)) { case 0: values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__loc); if (likely(values[0])) kw_args--; else goto __pyx_L5_argtuple_error; case 1: values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__name); if (likely(values[1])) kw_args--; else { __Pyx_RaiseArgtupleInvalid("delete", 1, 2, 2, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 201; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } if (unlikely(kw_args > 0)) { if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, PyTuple_GET_SIZE(__pyx_args), "delete") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 201; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } __pyx_v_loc = ((struct __pyx_obj_4h5py_2h5_ObjectID *)values[0]); __pyx_v_name = __Pyx_PyBytes_AsString(values[1]); if (unlikely((!__pyx_v_name) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 201; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } else if (PyTuple_GET_SIZE(__pyx_args) != 2) { goto __pyx_L5_argtuple_error; } else { __pyx_v_loc = ((struct __pyx_obj_4h5py_2h5_ObjectID *)PyTuple_GET_ITEM(__pyx_args, 0)); __pyx_v_name = __Pyx_PyBytes_AsString(PyTuple_GET_ITEM(__pyx_args, 1)); if (unlikely((!__pyx_v_name) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 201; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("delete", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 201; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; __Pyx_AddTraceback("h5py.h5a.delete"); return NULL; __pyx_L4_argument_unpacking_done:; if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_loc), __pyx_ptype_4h5py_2h5_ObjectID, 0, "loc", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 201; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /* "/home/tachyon/h5py/h5py/h5a.pyx":206 * Remove an attribute from an object. * """ * H5Adelete(loc.id, name) # <<<<<<<<<<<<<< * * */ __pyx_t_1 = PyObject_GetAttr(((PyObject *)__pyx_v_loc), __pyx_n_s__id); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 206; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = __Pyx_PyInt_from_py_hid_t(__pyx_t_1); if (unlikely((__pyx_t_2 == (hid_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 206; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_3 = H5Adelete(__pyx_t_2, __pyx_v_name); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 206; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("h5py.h5a.delete"); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "/home/tachyon/h5py/h5py/h5a.pyx":209 * * * def get_num_attrs(ObjectID loc not None): # <<<<<<<<<<<<<< * """(ObjectID loc) => INT * */ static PyObject *__pyx_pf_4h5py_3h5a_get_num_attrs(PyObject *__pyx_self, PyObject *__pyx_v_loc); /*proto*/ static char __pyx_doc_4h5py_3h5a_get_num_attrs[] = "(ObjectID loc) => INT\n\n Determine the number of attributes attached to an HDF5 object.\n "; static PyObject *__pyx_pf_4h5py_3h5a_get_num_attrs(PyObject *__pyx_self, PyObject *__pyx_v_loc) { PyObject *__pyx_r = NULL; PyObject *__pyx_t_1 = NULL; hid_t __pyx_t_2; int __pyx_t_3; __Pyx_RefNannySetupContext("get_num_attrs"); __pyx_self = __pyx_self; if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_loc), __pyx_ptype_4h5py_2h5_ObjectID, 0, "loc", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 209; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /* "/home/tachyon/h5py/h5py/h5a.pyx":214 * Determine the number of attributes attached to an HDF5 object. * """ * return H5Aget_num_attrs(loc.id) # <<<<<<<<<<<<<< * * */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = PyObject_GetAttr(__pyx_v_loc, __pyx_n_s__id); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 214; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = __Pyx_PyInt_from_py_hid_t(__pyx_t_1); if (unlikely((__pyx_t_2 == (hid_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 214; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_3 = H5Aget_num_attrs(__pyx_t_2); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 214; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_1 = PyInt_FromLong(__pyx_t_3); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 214; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("h5py.h5a.get_num_attrs"); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "/home/tachyon/h5py/h5py/h5a.pyx":285 * cdef object func * cdef object retval * def __init__(self, func): # <<<<<<<<<<<<<< * self.func = func * self.retval = None */ static int __pyx_pf_4h5py_3h5a_12_AttrVisitor___init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static int __pyx_pf_4h5py_3h5a_12_AttrVisitor___init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyObject *__pyx_v_func = 0; int __pyx_r; static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__func,0}; __Pyx_RefNannySetupContext("__init__"); if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args = PyDict_Size(__pyx_kwds); PyObject* values[1] = {0}; switch (PyTuple_GET_SIZE(__pyx_args)) { case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); case 0: break; default: goto __pyx_L5_argtuple_error; } switch (PyTuple_GET_SIZE(__pyx_args)) { case 0: values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__func); if (likely(values[0])) kw_args--; else goto __pyx_L5_argtuple_error; } if (unlikely(kw_args > 0)) { if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, PyTuple_GET_SIZE(__pyx_args), "__init__") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 285; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } __pyx_v_func = values[0]; } else if (PyTuple_GET_SIZE(__pyx_args) != 1) { goto __pyx_L5_argtuple_error; } else { __pyx_v_func = PyTuple_GET_ITEM(__pyx_args, 0); } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("__init__", 1, 1, 1, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 285; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; __Pyx_AddTraceback("h5py.h5a._AttrVisitor.__init__"); return -1; __pyx_L4_argument_unpacking_done:; /* "/home/tachyon/h5py/h5py/h5a.pyx":286 * cdef object retval * def __init__(self, func): * self.func = func # <<<<<<<<<<<<<< * self.retval = None * */ __Pyx_INCREF(__pyx_v_func); __Pyx_GIVEREF(__pyx_v_func); __Pyx_GOTREF(((struct __pyx_obj_4h5py_3h5a__AttrVisitor *)__pyx_v_self)->func); __Pyx_DECREF(((struct __pyx_obj_4h5py_3h5a__AttrVisitor *)__pyx_v_self)->func); ((struct __pyx_obj_4h5py_3h5a__AttrVisitor *)__pyx_v_self)->func = __pyx_v_func; /* "/home/tachyon/h5py/h5py/h5a.pyx":287 * def __init__(self, func): * self.func = func * self.retval = None # <<<<<<<<<<<<<< * * IF H5PY_18API: */ __Pyx_INCREF(Py_None); __Pyx_GIVEREF(Py_None); __Pyx_GOTREF(((struct __pyx_obj_4h5py_3h5a__AttrVisitor *)__pyx_v_self)->retval); __Pyx_DECREF(((struct __pyx_obj_4h5py_3h5a__AttrVisitor *)__pyx_v_self)->retval); ((struct __pyx_obj_4h5py_3h5a__AttrVisitor *)__pyx_v_self)->retval = Py_None; __pyx_r = 0; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "/home/tachyon/h5py/h5py/h5a.pyx":353 * ELSE: * * cdef herr_t cb_attr_iter(hid_t loc_id, char* attr_name, void* vis_in) except 2: # <<<<<<<<<<<<<< * cdef _AttrVisitor vis = <_AttrVisitor>vis_in * vis.retval = vis.func(attr_name) */ static herr_t __pyx_f_4h5py_3h5a_cb_attr_iter(hid_t __pyx_v_loc_id, char *__pyx_v_attr_name, void *__pyx_v_vis_in) { struct __pyx_obj_4h5py_3h5a__AttrVisitor *__pyx_v_vis = 0; herr_t __pyx_r; PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; int __pyx_t_3; __Pyx_RefNannySetupContext("cb_attr_iter"); /* "/home/tachyon/h5py/h5py/h5a.pyx":354 * * cdef herr_t cb_attr_iter(hid_t loc_id, char* attr_name, void* vis_in) except 2: * cdef _AttrVisitor vis = <_AttrVisitor>vis_in # <<<<<<<<<<<<<< * vis.retval = vis.func(attr_name) * if vis.retval is not None: */ __Pyx_INCREF(((PyObject *)((struct __pyx_obj_4h5py_3h5a__AttrVisitor *)__pyx_v_vis_in))); __pyx_v_vis = ((struct __pyx_obj_4h5py_3h5a__AttrVisitor *)__pyx_v_vis_in); /* "/home/tachyon/h5py/h5py/h5a.pyx":355 * cdef herr_t cb_attr_iter(hid_t loc_id, char* attr_name, void* vis_in) except 2: * cdef _AttrVisitor vis = <_AttrVisitor>vis_in * vis.retval = vis.func(attr_name) # <<<<<<<<<<<<<< * if vis.retval is not None: * return 1 */ __pyx_t_1 = __Pyx_PyBytes_FromString(__pyx_v_attr_name); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 355; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(((PyObject *)__pyx_t_1)); __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 355; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)__pyx_t_1)); __Pyx_GIVEREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; __pyx_t_1 = PyObject_Call(__pyx_v_vis->func, __pyx_t_2, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 355; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_GIVEREF(__pyx_t_1); __Pyx_GOTREF(__pyx_v_vis->retval); __Pyx_DECREF(__pyx_v_vis->retval); __pyx_v_vis->retval = __pyx_t_1; __pyx_t_1 = 0; /* "/home/tachyon/h5py/h5py/h5a.pyx":356 * cdef _AttrVisitor vis = <_AttrVisitor>vis_in * vis.retval = vis.func(attr_name) * if vis.retval is not None: # <<<<<<<<<<<<<< * return 1 * return 0 */ __pyx_t_3 = (__pyx_v_vis->retval != Py_None); if (__pyx_t_3) { /* "/home/tachyon/h5py/h5py/h5a.pyx":357 * vis.retval = vis.func(attr_name) * if vis.retval is not None: * return 1 # <<<<<<<<<<<<<< * return 0 * */ __pyx_r = 1; goto __pyx_L0; goto __pyx_L3; } __pyx_L3:; /* "/home/tachyon/h5py/h5py/h5a.pyx":358 * if vis.retval is not None: * return 1 * return 0 # <<<<<<<<<<<<<< * * */ __pyx_r = 0; goto __pyx_L0; __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_AddTraceback("h5py.h5a.cb_attr_iter"); __pyx_r = 2; __pyx_L0:; __Pyx_XDECREF((PyObject *)__pyx_v_vis); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "/home/tachyon/h5py/h5py/h5a.pyx":361 * * * def iterate(ObjectID loc not None, object func, int index=0): # <<<<<<<<<<<<<< * """(ObjectID loc, CALLABLE func, INT index=0) => <Return value from func> * */ static PyObject *__pyx_pf_4h5py_3h5a_iterate(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static char __pyx_doc_4h5py_3h5a_iterate[] = "(ObjectID loc, CALLABLE func, INT index=0) => <Return value from func>\n\n Iterate a callable (function, method or callable object) over the\n attributes attached to this object. You callable should have the\n signature::\n\n func(STRING name) => Result\n\n Returning None continues iteration; returning anything else aborts\n iteration and returns that value.\n "; static PyObject *__pyx_pf_4h5py_3h5a_iterate(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { struct __pyx_obj_4h5py_2h5_ObjectID *__pyx_v_loc = 0; PyObject *__pyx_v_func = 0; int __pyx_v_index; unsigned int __pyx_v_i; struct __pyx_obj_4h5py_3h5a__AttrVisitor *__pyx_v_vis = 0; PyObject *__pyx_r = NULL; int __pyx_t_1; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; hid_t __pyx_t_4; herr_t __pyx_t_5; static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__loc,&__pyx_n_s__func,&__pyx_n_s__index,0}; __Pyx_RefNannySetupContext("iterate"); __pyx_self = __pyx_self; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args = PyDict_Size(__pyx_kwds); PyObject* values[3] = {0,0,0}; switch (PyTuple_GET_SIZE(__pyx_args)) { case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); case 0: break; default: goto __pyx_L5_argtuple_error; } switch (PyTuple_GET_SIZE(__pyx_args)) { case 0: values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__loc); if (likely(values[0])) kw_args--; else goto __pyx_L5_argtuple_error; case 1: values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__func); if (likely(values[1])) kw_args--; else { __Pyx_RaiseArgtupleInvalid("iterate", 0, 2, 3, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 361; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 2: if (kw_args > 0) { PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__index); if (unlikely(value)) { values[2] = value; kw_args--; } } } if (unlikely(kw_args > 0)) { if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, PyTuple_GET_SIZE(__pyx_args), "iterate") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 361; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } __pyx_v_loc = ((struct __pyx_obj_4h5py_2h5_ObjectID *)values[0]); __pyx_v_func = values[1]; if (values[2]) { __pyx_v_index = __Pyx_PyInt_AsInt(values[2]); if (unlikely((__pyx_v_index == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 361; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } else { __pyx_v_index = ((int)0); } } else { __pyx_v_index = ((int)0); switch (PyTuple_GET_SIZE(__pyx_args)) { case 3: __pyx_v_index = __Pyx_PyInt_AsInt(PyTuple_GET_ITEM(__pyx_args, 2)); if (unlikely((__pyx_v_index == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 361; __pyx_clineno = __LINE__; goto __pyx_L3_error;} case 2: __pyx_v_func = PyTuple_GET_ITEM(__pyx_args, 1); __pyx_v_loc = ((struct __pyx_obj_4h5py_2h5_ObjectID *)PyTuple_GET_ITEM(__pyx_args, 0)); break; default: goto __pyx_L5_argtuple_error; } } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("iterate", 0, 2, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 361; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; __Pyx_AddTraceback("h5py.h5a.iterate"); return NULL; __pyx_L4_argument_unpacking_done:; __Pyx_INCREF((PyObject *)__pyx_v_loc); __Pyx_INCREF(__pyx_v_func); if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_loc), __pyx_ptype_4h5py_2h5_ObjectID, 0, "loc", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 361; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /* "/home/tachyon/h5py/h5py/h5a.pyx":373 * iteration and returns that value. * """ * if index < 0: # <<<<<<<<<<<<<< * raise ValueError("Starting index must be a non-negative integer.") * */ __pyx_t_1 = (__pyx_v_index < 0); if (__pyx_t_1) { /* "/home/tachyon/h5py/h5py/h5a.pyx":374 * """ * if index < 0: * raise ValueError("Starting index must be a non-negative integer.") # <<<<<<<<<<<<<< * * cdef unsigned int i = index */ __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 374; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_INCREF(((PyObject *)__pyx_kp_s_2)); PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)__pyx_kp_s_2)); __Pyx_GIVEREF(((PyObject *)__pyx_kp_s_2)); __pyx_t_3 = PyObject_Call(__pyx_builtin_ValueError, __pyx_t_2, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 374; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_Raise(__pyx_t_3, 0, 0); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; {__pyx_filename = __pyx_f[0]; __pyx_lineno = 374; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L6; } __pyx_L6:; /* "/home/tachyon/h5py/h5py/h5a.pyx":376 * raise ValueError("Starting index must be a non-negative integer.") * * cdef unsigned int i = index # <<<<<<<<<<<<<< * cdef _AttrVisitor vis = _AttrVisitor(func) * */ __pyx_v_i = __pyx_v_index; /* "/home/tachyon/h5py/h5py/h5a.pyx":377 * * cdef unsigned int i = index * cdef _AttrVisitor vis = _AttrVisitor(func) # <<<<<<<<<<<<<< * * H5Aiterate(loc.id, &i, <H5A_operator_t>cb_attr_iter, <void*>vis) */ __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 377; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_INCREF(__pyx_v_func); PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_func); __Pyx_GIVEREF(__pyx_v_func); __pyx_t_2 = PyObject_Call(((PyObject *)((PyObject*)__pyx_ptype_4h5py_3h5a__AttrVisitor)), __pyx_t_3, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 377; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_v_vis = ((struct __pyx_obj_4h5py_3h5a__AttrVisitor *)__pyx_t_2); __pyx_t_2 = 0; /* "/home/tachyon/h5py/h5py/h5a.pyx":379 * cdef _AttrVisitor vis = _AttrVisitor(func) * * H5Aiterate(loc.id, &i, <H5A_operator_t>cb_attr_iter, <void*>vis) # <<<<<<<<<<<<<< * * return vis.retval */ __pyx_t_2 = PyObject_GetAttr(((PyObject *)__pyx_v_loc), __pyx_n_s__id); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 379; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = __Pyx_PyInt_from_py_hid_t(__pyx_t_2); if (unlikely((__pyx_t_4 == (hid_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 379; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_5 = H5Aiterate(__pyx_t_4, (&__pyx_v_i), ((herr_t (*)(hid_t, char *, void *))__pyx_f_4h5py_3h5a_cb_attr_iter), ((void *)__pyx_v_vis)); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 379; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /* "/home/tachyon/h5py/h5py/h5a.pyx":381 * H5Aiterate(loc.id, &i, <H5A_operator_t>cb_attr_iter, <void*>vis) * * return vis.retval # <<<<<<<<<<<<<< * * */ __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(__pyx_v_vis->retval); __pyx_r = __pyx_v_vis->retval; goto __pyx_L0; __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_AddTraceback("h5py.h5a.iterate"); __pyx_r = NULL; __pyx_L0:; __Pyx_XDECREF((PyObject *)__pyx_v_vis); __Pyx_DECREF((PyObject *)__pyx_v_loc); __Pyx_DECREF(__pyx_v_func); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "/home/tachyon/h5py/h5py/h5a.pyx":402 * property name: * """The attribute's name""" * def __get__(self): # <<<<<<<<<<<<<< * return self.get_name() * */ static PyObject *__pyx_pf_4h5py_3h5a_6AttrID_4name___get__(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_pf_4h5py_3h5a_6AttrID_4name___get__(PyObject *__pyx_v_self) { PyObject *__pyx_r = NULL; PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; __Pyx_RefNannySetupContext("__get__"); /* "/home/tachyon/h5py/h5py/h5a.pyx":403 * """The attribute's name""" * def __get__(self): * return self.get_name() # <<<<<<<<<<<<<< * * property shape: */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = PyObject_GetAttr(__pyx_v_self, __pyx_n_s__get_name); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 403; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 403; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_r = __pyx_t_2; __pyx_t_2 = 0; goto __pyx_L0; __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_AddTraceback("h5py.h5a.AttrID.name.__get__"); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "/home/tachyon/h5py/h5py/h5a.pyx":407 * property shape: * """A Numpy-style shape tuple representing the attribute's dataspace""" * def __get__(self): # <<<<<<<<<<<<<< * * cdef SpaceID space */ static PyObject *__pyx_pf_4h5py_3h5a_6AttrID_5shape___get__(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_pf_4h5py_3h5a_6AttrID_5shape___get__(PyObject *__pyx_v_self) { struct __pyx_obj_4h5py_3h5s_SpaceID *__pyx_v_space; PyObject *__pyx_r = NULL; PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; __Pyx_RefNannySetupContext("__get__"); __pyx_v_space = ((struct __pyx_obj_4h5py_3h5s_SpaceID *)Py_None); __Pyx_INCREF(Py_None); /* "/home/tachyon/h5py/h5py/h5a.pyx":410 * * cdef SpaceID space * space = self.get_space() # <<<<<<<<<<<<<< * return space.get_simple_extent_dims() * */ __pyx_t_1 = PyObject_GetAttr(__pyx_v_self, __pyx_n_s__get_space); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 410; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 410; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_4h5py_3h5s_SpaceID))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 410; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(((PyObject *)__pyx_v_space)); __pyx_v_space = ((struct __pyx_obj_4h5py_3h5s_SpaceID *)__pyx_t_2); __pyx_t_2 = 0; /* "/home/tachyon/h5py/h5py/h5a.pyx":411 * cdef SpaceID space * space = self.get_space() * return space.get_simple_extent_dims() # <<<<<<<<<<<<<< * * property dtype: */ __Pyx_XDECREF(__pyx_r); __pyx_t_2 = PyObject_GetAttr(((PyObject *)__pyx_v_space), __pyx_n_s_3); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 411; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_1 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 411; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_AddTraceback("h5py.h5a.AttrID.shape.__get__"); __pyx_r = NULL; __pyx_L0:; __Pyx_DECREF((PyObject *)__pyx_v_space); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "/home/tachyon/h5py/h5py/h5a.pyx":415 * property dtype: * """A Numpy-stype dtype object representing the attribute's datatype""" * def __get__(self): # <<<<<<<<<<<<<< * * cdef TypeID tid */ static PyObject *__pyx_pf_4h5py_3h5a_6AttrID_5dtype___get__(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_pf_4h5py_3h5a_6AttrID_5dtype___get__(PyObject *__pyx_v_self) { struct __pyx_obj_4h5py_3h5t_TypeID *__pyx_v_tid; PyObject *__pyx_r = NULL; PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; __Pyx_RefNannySetupContext("__get__"); __pyx_v_tid = ((struct __pyx_obj_4h5py_3h5t_TypeID *)Py_None); __Pyx_INCREF(Py_None); /* "/home/tachyon/h5py/h5py/h5a.pyx":418 * * cdef TypeID tid * tid = self.get_type() # <<<<<<<<<<<<<< * return tid.py_dtype() * */ __pyx_t_1 = PyObject_GetAttr(__pyx_v_self, __pyx_n_s__get_type); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 418; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 418; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_4h5py_3h5t_TypeID))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 418; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(((PyObject *)__pyx_v_tid)); __pyx_v_tid = ((struct __pyx_obj_4h5py_3h5t_TypeID *)__pyx_t_2); __pyx_t_2 = 0; /* "/home/tachyon/h5py/h5py/h5a.pyx":419 * cdef TypeID tid * tid = self.get_type() * return tid.py_dtype() # <<<<<<<<<<<<<< * * */ __Pyx_XDECREF(__pyx_r); __pyx_t_2 = ((struct __pyx_vtabstruct_4h5py_3h5t_TypeID *)__pyx_v_tid->__pyx_vtab)->py_dtype(__pyx_v_tid); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 419; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_r = __pyx_t_2; __pyx_t_2 = 0; goto __pyx_L0; __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_AddTraceback("h5py.h5a.AttrID.dtype.__get__"); __pyx_r = NULL; __pyx_L0:; __Pyx_DECREF((PyObject *)__pyx_v_tid); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "/home/tachyon/h5py/h5py/h5a.pyx":422 * * * def _close(self): # <<<<<<<<<<<<<< * """() * */ static PyObject *__pyx_pf_4h5py_3h5a_6AttrID__close(PyObject *__pyx_v_self, PyObject *unused); /*proto*/ static char __pyx_doc_4h5py_3h5a_6AttrID__close[] = "()\n\n Close this attribute and release resources. You don't need to\n call this manually; attributes are automatically destroyed when\n their Python wrappers are freed.\n "; static PyObject *__pyx_pf_4h5py_3h5a_6AttrID__close(PyObject *__pyx_v_self, PyObject *unused) { PyObject *__pyx_r = NULL; PyObject *__pyx_t_1 = NULL; hid_t __pyx_t_2; herr_t __pyx_t_3; __Pyx_RefNannySetupContext("_close"); /* "/home/tachyon/h5py/h5py/h5a.pyx":429 * their Python wrappers are freed. * """ * H5Aclose(self.id) # <<<<<<<<<<<<<< * * */ __pyx_t_1 = PyObject_GetAttr(__pyx_v_self, __pyx_n_s__id); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 429; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = __Pyx_PyInt_from_py_hid_t(__pyx_t_1); if (unlikely((__pyx_t_2 == (hid_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 429; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_3 = H5Aclose(__pyx_t_2); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 429; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("h5py.h5a.AttrID._close"); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "/home/tachyon/h5py/h5py/h5a.pyx":432 * * * def read(self, ndarray arr not None): # <<<<<<<<<<<<<< * """(NDARRAY arr) * */ static PyObject *__pyx_pf_4h5py_3h5a_6AttrID_read(PyObject *__pyx_v_self, PyObject *__pyx_v_arr); /*proto*/ static char __pyx_doc_4h5py_3h5a_6AttrID_read[] = "(NDARRAY arr)\n\n Read the attribute data into the given Numpy array. Note that the \n Numpy array must have the same shape as the HDF5 attribute, and a \n conversion-compatible datatype.\n\n The Numpy array must be writable and C-contiguous. If this is not\n the case, the read will fail with an exception.\n "; static PyObject *__pyx_pf_4h5py_3h5a_6AttrID_read(PyObject *__pyx_v_self, PyObject *__pyx_v_arr) { struct __pyx_obj_4h5py_3h5t_TypeID *__pyx_v_mtype; hid_t __pyx_v_space_id; PyObject *__pyx_r = NULL; PyObject *__pyx_t_1 = NULL; hid_t __pyx_t_2; hid_t __pyx_t_3; int __pyx_t_4; struct __pyx_opt_args_4h5py_5utils_check_numpy_write __pyx_t_5; PyObject *__pyx_t_6 = NULL; hid_t __pyx_t_7; hid_t __pyx_t_8; herr_t __pyx_t_9; herr_t __pyx_t_10; __Pyx_RefNannySetupContext("read"); __Pyx_INCREF((PyObject *)__pyx_v_self); __Pyx_INCREF((PyObject *)__pyx_v_arr); __pyx_v_mtype = ((struct __pyx_obj_4h5py_3h5t_TypeID *)Py_None); __Pyx_INCREF(Py_None); if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_arr), __pyx_ptype_4h5py_5numpy_ndarray, 0, "arr", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 432; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /* "/home/tachyon/h5py/h5py/h5a.pyx":444 * cdef TypeID mtype * cdef hid_t space_id * space_id = 0 # <<<<<<<<<<<<<< * * try: */ __pyx_v_space_id = 0; /* "/home/tachyon/h5py/h5py/h5a.pyx":446 * space_id = 0 * * try: # <<<<<<<<<<<<<< * space_id = H5Aget_space(self.id) * check_numpy_write(arr, space_id) */ /*try:*/ { /* "/home/tachyon/h5py/h5py/h5a.pyx":447 * * try: * space_id = H5Aget_space(self.id) # <<<<<<<<<<<<<< * check_numpy_write(arr, space_id) * */ __pyx_t_1 = PyObject_GetAttr(__pyx_v_self, __pyx_n_s__id); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 447; __pyx_clineno = __LINE__; goto __pyx_L6;} __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = __Pyx_PyInt_from_py_hid_t(__pyx_t_1); if (unlikely((__pyx_t_2 == (hid_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 447; __pyx_clineno = __LINE__; goto __pyx_L6;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_3 = H5Aget_space(__pyx_t_2); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 447; __pyx_clineno = __LINE__; goto __pyx_L6;} __pyx_v_space_id = __pyx_t_3; /* "/home/tachyon/h5py/h5py/h5a.pyx":448 * try: * space_id = H5Aget_space(self.id) * check_numpy_write(arr, space_id) # <<<<<<<<<<<<<< * * mtype = py_create(arr.dtype) */ __pyx_t_5.__pyx_n = 1; __pyx_t_5.space_id = __pyx_v_space_id; __pyx_t_4 = __pyx_f_4h5py_5utils_check_numpy_write(((PyArrayObject *)__pyx_v_arr), 0, &__pyx_t_5); if (unlikely(__pyx_t_4 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 448; __pyx_clineno = __LINE__; goto __pyx_L6;} /* "/home/tachyon/h5py/h5py/h5a.pyx":450 * check_numpy_write(arr, space_id) * * mtype = py_create(arr.dtype) # <<<<<<<<<<<<<< * * attr_rw(self.id, mtype.id, PyArray_DATA(arr), 1) */ __pyx_t_1 = PyObject_GetAttr(__pyx_v_arr, __pyx_n_s__dtype); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 450; __pyx_clineno = __LINE__; goto __pyx_L6;} __Pyx_GOTREF(__pyx_t_1); __pyx_t_6 = ((PyObject *)__pyx_f_4h5py_3h5t_py_create(__pyx_t_1, 0, NULL)); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 450; __pyx_clineno = __LINE__; goto __pyx_L6;} __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_DECREF(((PyObject *)__pyx_v_mtype)); __pyx_v_mtype = ((struct __pyx_obj_4h5py_3h5t_TypeID *)__pyx_t_6); __pyx_t_6 = 0; /* "/home/tachyon/h5py/h5py/h5a.pyx":452 * mtype = py_create(arr.dtype) * * attr_rw(self.id, mtype.id, PyArray_DATA(arr), 1) # <<<<<<<<<<<<<< * * finally: */ __pyx_t_6 = PyObject_GetAttr(__pyx_v_self, __pyx_n_s__id); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 452; __pyx_clineno = __LINE__; goto __pyx_L6;} __Pyx_GOTREF(__pyx_t_6); __pyx_t_7 = __Pyx_PyInt_from_py_hid_t(__pyx_t_6); if (unlikely((__pyx_t_7 == (hid_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 452; __pyx_clineno = __LINE__; goto __pyx_L6;} __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; __pyx_t_6 = PyObject_GetAttr(((PyObject *)__pyx_v_mtype), __pyx_n_s__id); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 452; __pyx_clineno = __LINE__; goto __pyx_L6;} __Pyx_GOTREF(__pyx_t_6); __pyx_t_8 = __Pyx_PyInt_from_py_hid_t(__pyx_t_6); if (unlikely((__pyx_t_8 == (hid_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 452; __pyx_clineno = __LINE__; goto __pyx_L6;} __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; __pyx_t_9 = __pyx_f_4h5py_6_proxy_attr_rw(__pyx_t_7, __pyx_t_8, PyArray_DATA(((PyArrayObject *)__pyx_v_arr)), 1); if (unlikely(__pyx_t_9 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 452; __pyx_clineno = __LINE__; goto __pyx_L6;} } /*finally:*/ { int __pyx_why; PyObject *__pyx_exc_type, *__pyx_exc_value, *__pyx_exc_tb; int __pyx_exc_lineno; __pyx_exc_type = 0; __pyx_exc_value = 0; __pyx_exc_tb = 0; __pyx_exc_lineno = 0; __pyx_why = 0; goto __pyx_L7; __pyx_L6: { __pyx_why = 4; __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; __Pyx_ErrFetch(&__pyx_exc_type, &__pyx_exc_value, &__pyx_exc_tb); __pyx_exc_lineno = __pyx_lineno; goto __pyx_L7; } __pyx_L7:; /* "/home/tachyon/h5py/h5py/h5a.pyx":455 * * finally: * if space_id: # <<<<<<<<<<<<<< * H5Sclose(space_id) * */ __pyx_t_3 = __pyx_v_space_id; if (__pyx_t_3) { /* "/home/tachyon/h5py/h5py/h5a.pyx":456 * finally: * if space_id: * H5Sclose(space_id) # <<<<<<<<<<<<<< * * */ __pyx_t_10 = H5Sclose(__pyx_v_space_id); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 456; __pyx_clineno = __LINE__; goto __pyx_L8_error;} goto __pyx_L9; } __pyx_L9:; goto __pyx_L10; __pyx_L8_error:; if (__pyx_why == 4) { Py_XDECREF(__pyx_exc_type); Py_XDECREF(__pyx_exc_value); Py_XDECREF(__pyx_exc_tb); } goto __pyx_L1_error; __pyx_L10:; switch (__pyx_why) { case 4: { __Pyx_ErrRestore(__pyx_exc_type, __pyx_exc_value, __pyx_exc_tb); __pyx_lineno = __pyx_exc_lineno; __pyx_exc_type = 0; __pyx_exc_value = 0; __pyx_exc_tb = 0; goto __pyx_L1_error; } } } __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_6); __Pyx_AddTraceback("h5py.h5a.AttrID.read"); __pyx_r = NULL; __pyx_L0:; __Pyx_DECREF((PyObject *)__pyx_v_mtype); __Pyx_DECREF((PyObject *)__pyx_v_self); __Pyx_DECREF((PyObject *)__pyx_v_arr); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "/home/tachyon/h5py/h5py/h5a.pyx":459 * * * def write(self, ndarray arr not None): # <<<<<<<<<<<<<< * """(NDARRAY arr) * */ static PyObject *__pyx_pf_4h5py_3h5a_6AttrID_write(PyObject *__pyx_v_self, PyObject *__pyx_v_arr); /*proto*/ static char __pyx_doc_4h5py_3h5a_6AttrID_write[] = "(NDARRAY arr)\n\n Write the contents of a Numpy array too the attribute. Note that\n the Numpy array must have the same shape as the HDF5 attribute, and\n a conversion-compatible datatype. \n\n The Numpy array must be C-contiguous. If this is not the case, \n the write will fail with an exception.\n "; static PyObject *__pyx_pf_4h5py_3h5a_6AttrID_write(PyObject *__pyx_v_self, PyObject *__pyx_v_arr) { struct __pyx_obj_4h5py_3h5t_TypeID *__pyx_v_mtype; hid_t __pyx_v_space_id; PyObject *__pyx_r = NULL; PyObject *__pyx_t_1 = NULL; hid_t __pyx_t_2; hid_t __pyx_t_3; int __pyx_t_4; struct __pyx_opt_args_4h5py_5utils_check_numpy_read __pyx_t_5; PyObject *__pyx_t_6 = NULL; hid_t __pyx_t_7; hid_t __pyx_t_8; herr_t __pyx_t_9; herr_t __pyx_t_10; __Pyx_RefNannySetupContext("write"); __Pyx_INCREF((PyObject *)__pyx_v_self); __Pyx_INCREF((PyObject *)__pyx_v_arr); __pyx_v_mtype = ((struct __pyx_obj_4h5py_3h5t_TypeID *)Py_None); __Pyx_INCREF(Py_None); if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_arr), __pyx_ptype_4h5py_5numpy_ndarray, 0, "arr", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 459; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /* "/home/tachyon/h5py/h5py/h5a.pyx":471 * cdef TypeID mtype * cdef hid_t space_id * space_id = 0 # <<<<<<<<<<<<<< * * try: */ __pyx_v_space_id = 0; /* "/home/tachyon/h5py/h5py/h5a.pyx":473 * space_id = 0 * * try: # <<<<<<<<<<<<<< * space_id = H5Aget_space(self.id) * check_numpy_read(arr, space_id) */ /*try:*/ { /* "/home/tachyon/h5py/h5py/h5a.pyx":474 * * try: * space_id = H5Aget_space(self.id) # <<<<<<<<<<<<<< * check_numpy_read(arr, space_id) * mtype = py_create(arr.dtype) */ __pyx_t_1 = PyObject_GetAttr(__pyx_v_self, __pyx_n_s__id); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 474; __pyx_clineno = __LINE__; goto __pyx_L6;} __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = __Pyx_PyInt_from_py_hid_t(__pyx_t_1); if (unlikely((__pyx_t_2 == (hid_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 474; __pyx_clineno = __LINE__; goto __pyx_L6;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_3 = H5Aget_space(__pyx_t_2); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 474; __pyx_clineno = __LINE__; goto __pyx_L6;} __pyx_v_space_id = __pyx_t_3; /* "/home/tachyon/h5py/h5py/h5a.pyx":475 * try: * space_id = H5Aget_space(self.id) * check_numpy_read(arr, space_id) # <<<<<<<<<<<<<< * mtype = py_create(arr.dtype) * */ __pyx_t_5.__pyx_n = 1; __pyx_t_5.space_id = __pyx_v_space_id; __pyx_t_4 = __pyx_f_4h5py_5utils_check_numpy_read(((PyArrayObject *)__pyx_v_arr), 0, &__pyx_t_5); if (unlikely(__pyx_t_4 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 475; __pyx_clineno = __LINE__; goto __pyx_L6;} /* "/home/tachyon/h5py/h5py/h5a.pyx":476 * space_id = H5Aget_space(self.id) * check_numpy_read(arr, space_id) * mtype = py_create(arr.dtype) # <<<<<<<<<<<<<< * * attr_rw(self.id, mtype.id, PyArray_DATA(arr), 0) */ __pyx_t_1 = PyObject_GetAttr(__pyx_v_arr, __pyx_n_s__dtype); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 476; __pyx_clineno = __LINE__; goto __pyx_L6;} __Pyx_GOTREF(__pyx_t_1); __pyx_t_6 = ((PyObject *)__pyx_f_4h5py_3h5t_py_create(__pyx_t_1, 0, NULL)); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 476; __pyx_clineno = __LINE__; goto __pyx_L6;} __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_DECREF(((PyObject *)__pyx_v_mtype)); __pyx_v_mtype = ((struct __pyx_obj_4h5py_3h5t_TypeID *)__pyx_t_6); __pyx_t_6 = 0; /* "/home/tachyon/h5py/h5py/h5a.pyx":478 * mtype = py_create(arr.dtype) * * attr_rw(self.id, mtype.id, PyArray_DATA(arr), 0) # <<<<<<<<<<<<<< * * finally: */ __pyx_t_6 = PyObject_GetAttr(__pyx_v_self, __pyx_n_s__id); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 478; __pyx_clineno = __LINE__; goto __pyx_L6;} __Pyx_GOTREF(__pyx_t_6); __pyx_t_7 = __Pyx_PyInt_from_py_hid_t(__pyx_t_6); if (unlikely((__pyx_t_7 == (hid_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 478; __pyx_clineno = __LINE__; goto __pyx_L6;} __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; __pyx_t_6 = PyObject_GetAttr(((PyObject *)__pyx_v_mtype), __pyx_n_s__id); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 478; __pyx_clineno = __LINE__; goto __pyx_L6;} __Pyx_GOTREF(__pyx_t_6); __pyx_t_8 = __Pyx_PyInt_from_py_hid_t(__pyx_t_6); if (unlikely((__pyx_t_8 == (hid_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 478; __pyx_clineno = __LINE__; goto __pyx_L6;} __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; __pyx_t_9 = __pyx_f_4h5py_6_proxy_attr_rw(__pyx_t_7, __pyx_t_8, PyArray_DATA(((PyArrayObject *)__pyx_v_arr)), 0); if (unlikely(__pyx_t_9 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 478; __pyx_clineno = __LINE__; goto __pyx_L6;} } /*finally:*/ { int __pyx_why; PyObject *__pyx_exc_type, *__pyx_exc_value, *__pyx_exc_tb; int __pyx_exc_lineno; __pyx_exc_type = 0; __pyx_exc_value = 0; __pyx_exc_tb = 0; __pyx_exc_lineno = 0; __pyx_why = 0; goto __pyx_L7; __pyx_L6: { __pyx_why = 4; __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; __Pyx_ErrFetch(&__pyx_exc_type, &__pyx_exc_value, &__pyx_exc_tb); __pyx_exc_lineno = __pyx_lineno; goto __pyx_L7; } __pyx_L7:; /* "/home/tachyon/h5py/h5py/h5a.pyx":481 * * finally: * if space_id: # <<<<<<<<<<<<<< * H5Sclose(space_id) * */ __pyx_t_3 = __pyx_v_space_id; if (__pyx_t_3) { /* "/home/tachyon/h5py/h5py/h5a.pyx":482 * finally: * if space_id: * H5Sclose(space_id) # <<<<<<<<<<<<<< * * */ __pyx_t_10 = H5Sclose(__pyx_v_space_id); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 482; __pyx_clineno = __LINE__; goto __pyx_L8_error;} goto __pyx_L9; } __pyx_L9:; goto __pyx_L10; __pyx_L8_error:; if (__pyx_why == 4) { Py_XDECREF(__pyx_exc_type); Py_XDECREF(__pyx_exc_value); Py_XDECREF(__pyx_exc_tb); } goto __pyx_L1_error; __pyx_L10:; switch (__pyx_why) { case 4: { __Pyx_ErrRestore(__pyx_exc_type, __pyx_exc_value, __pyx_exc_tb); __pyx_lineno = __pyx_exc_lineno; __pyx_exc_type = 0; __pyx_exc_value = 0; __pyx_exc_tb = 0; goto __pyx_L1_error; } } } __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_6); __Pyx_AddTraceback("h5py.h5a.AttrID.write"); __pyx_r = NULL; __pyx_L0:; __Pyx_DECREF((PyObject *)__pyx_v_mtype); __Pyx_DECREF((PyObject *)__pyx_v_self); __Pyx_DECREF((PyObject *)__pyx_v_arr); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "/home/tachyon/h5py/h5py/h5a.pyx":485 * * * def get_name(self): # <<<<<<<<<<<<<< * """() => STRING name * */ static PyObject *__pyx_pf_4h5py_3h5a_6AttrID_get_name(PyObject *__pyx_v_self, PyObject *unused); /*proto*/ static char __pyx_doc_4h5py_3h5a_6AttrID_get_name[] = "() => STRING name\n\n Determine the name of this attribute.\n "; static PyObject *__pyx_pf_4h5py_3h5a_6AttrID_get_name(PyObject *__pyx_v_self, PyObject *unused) { int __pyx_v_blen; char *__pyx_v_buf; PyObject *__pyx_v_strout; PyObject *__pyx_r = NULL; PyObject *__pyx_t_1 = NULL; hid_t __pyx_t_2; ssize_t __pyx_t_3; void *__pyx_t_4; __Pyx_RefNannySetupContext("get_name"); __Pyx_INCREF((PyObject *)__pyx_v_self); __pyx_v_strout = Py_None; __Pyx_INCREF(Py_None); /* "/home/tachyon/h5py/h5py/h5a.pyx":492 * cdef int blen * cdef char* buf * buf = NULL # <<<<<<<<<<<<<< * * try: */ __pyx_v_buf = NULL; /* "/home/tachyon/h5py/h5py/h5a.pyx":494 * buf = NULL * * try: # <<<<<<<<<<<<<< * blen = H5Aget_name(self.id, 0, NULL) * assert blen >= 0 */ /*try:*/ { /* "/home/tachyon/h5py/h5py/h5a.pyx":495 * * try: * blen = H5Aget_name(self.id, 0, NULL) # <<<<<<<<<<<<<< * assert blen >= 0 * buf = <char*>emalloc(sizeof(char)*blen+1) */ __pyx_t_1 = PyObject_GetAttr(__pyx_v_self, __pyx_n_s__id); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 495; __pyx_clineno = __LINE__; goto __pyx_L6;} __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = __Pyx_PyInt_from_py_hid_t(__pyx_t_1); if (unlikely((__pyx_t_2 == (hid_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 495; __pyx_clineno = __LINE__; goto __pyx_L6;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_3 = H5Aget_name(__pyx_t_2, 0, NULL); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 495; __pyx_clineno = __LINE__; goto __pyx_L6;} __pyx_v_blen = __pyx_t_3; /* "/home/tachyon/h5py/h5py/h5a.pyx":496 * try: * blen = H5Aget_name(self.id, 0, NULL) * assert blen >= 0 # <<<<<<<<<<<<<< * buf = <char*>emalloc(sizeof(char)*blen+1) * blen = H5Aget_name(self.id, blen+1, buf) */ #ifndef PYREX_WITHOUT_ASSERTIONS if (unlikely(!(__pyx_v_blen >= 0))) { PyErr_SetNone(PyExc_AssertionError); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 496; __pyx_clineno = __LINE__; goto __pyx_L6;} } #endif /* "/home/tachyon/h5py/h5py/h5a.pyx":497 * blen = H5Aget_name(self.id, 0, NULL) * assert blen >= 0 * buf = <char*>emalloc(sizeof(char)*blen+1) # <<<<<<<<<<<<<< * blen = H5Aget_name(self.id, blen+1, buf) * strout = <bytes>buf */ __pyx_t_4 = __pyx_f_4h5py_5utils_emalloc((((sizeof(char)) * __pyx_v_blen) + 1)); if (unlikely(__pyx_t_4 == NULL && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 497; __pyx_clineno = __LINE__; goto __pyx_L6;} __pyx_v_buf = ((char *)__pyx_t_4); /* "/home/tachyon/h5py/h5py/h5a.pyx":498 * assert blen >= 0 * buf = <char*>emalloc(sizeof(char)*blen+1) * blen = H5Aget_name(self.id, blen+1, buf) # <<<<<<<<<<<<<< * strout = <bytes>buf * finally: */ __pyx_t_1 = PyObject_GetAttr(__pyx_v_self, __pyx_n_s__id); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 498; __pyx_clineno = __LINE__; goto __pyx_L6;} __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = __Pyx_PyInt_from_py_hid_t(__pyx_t_1); if (unlikely((__pyx_t_2 == (hid_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 498; __pyx_clineno = __LINE__; goto __pyx_L6;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_3 = H5Aget_name(__pyx_t_2, (__pyx_v_blen + 1), __pyx_v_buf); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 498; __pyx_clineno = __LINE__; goto __pyx_L6;} __pyx_v_blen = __pyx_t_3; /* "/home/tachyon/h5py/h5py/h5a.pyx":499 * buf = <char*>emalloc(sizeof(char)*blen+1) * blen = H5Aget_name(self.id, blen+1, buf) * strout = <bytes>buf # <<<<<<<<<<<<<< * finally: * efree(buf) */ __pyx_t_1 = __Pyx_PyBytes_FromString(__pyx_v_buf); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 499; __pyx_clineno = __LINE__; goto __pyx_L6;} __Pyx_GOTREF(((PyObject *)__pyx_t_1)); __Pyx_INCREF(((PyObject *)__pyx_t_1)); __Pyx_DECREF(__pyx_v_strout); __pyx_v_strout = ((PyObject *)__pyx_t_1); __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; } /*finally:*/ { int __pyx_why; PyObject *__pyx_exc_type, *__pyx_exc_value, *__pyx_exc_tb; int __pyx_exc_lineno; __pyx_exc_type = 0; __pyx_exc_value = 0; __pyx_exc_tb = 0; __pyx_exc_lineno = 0; __pyx_why = 0; goto __pyx_L7; __pyx_L6: { __pyx_why = 4; __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_ErrFetch(&__pyx_exc_type, &__pyx_exc_value, &__pyx_exc_tb); __pyx_exc_lineno = __pyx_lineno; goto __pyx_L7; } __pyx_L7:; /* "/home/tachyon/h5py/h5py/h5a.pyx":501 * strout = <bytes>buf * finally: * efree(buf) # <<<<<<<<<<<<<< * * return strout */ __pyx_f_4h5py_5utils_efree(__pyx_v_buf); switch (__pyx_why) { case 4: { __Pyx_ErrRestore(__pyx_exc_type, __pyx_exc_value, __pyx_exc_tb); __pyx_lineno = __pyx_exc_lineno; __pyx_exc_type = 0; __pyx_exc_value = 0; __pyx_exc_tb = 0; goto __pyx_L1_error; } } } /* "/home/tachyon/h5py/h5py/h5a.pyx":503 * efree(buf) * * return strout # <<<<<<<<<<<<<< * * */ __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(__pyx_v_strout); __pyx_r = __pyx_v_strout; goto __pyx_L0; __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("h5py.h5a.AttrID.get_name"); __pyx_r = NULL; __pyx_L0:; __Pyx_DECREF(__pyx_v_strout); __Pyx_DECREF((PyObject *)__pyx_v_self); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "/home/tachyon/h5py/h5py/h5a.pyx":506 * * * def get_space(self): # <<<<<<<<<<<<<< * """() => SpaceID * */ static PyObject *__pyx_pf_4h5py_3h5a_6AttrID_get_space(PyObject *__pyx_v_self, PyObject *unused); /*proto*/ static char __pyx_doc_4h5py_3h5a_6AttrID_get_space[] = "() => SpaceID\n\n Create and return a copy of the attribute's dataspace.\n "; static PyObject *__pyx_pf_4h5py_3h5a_6AttrID_get_space(PyObject *__pyx_v_self, PyObject *unused) { PyObject *__pyx_r = NULL; PyObject *__pyx_t_1 = NULL; hid_t __pyx_t_2; hid_t __pyx_t_3; PyObject *__pyx_t_4 = NULL; __Pyx_RefNannySetupContext("get_space"); /* "/home/tachyon/h5py/h5py/h5a.pyx":511 * Create and return a copy of the attribute's dataspace. * """ * return SpaceID(H5Aget_space(self.id)) # <<<<<<<<<<<<<< * * */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = PyObject_GetAttr(__pyx_v_self, __pyx_n_s__id); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 511; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = __Pyx_PyInt_from_py_hid_t(__pyx_t_1); if (unlikely((__pyx_t_2 == (hid_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 511; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_3 = H5Aget_space(__pyx_t_2); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 511; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_1 = __Pyx_PyInt_to_py_hid_t(__pyx_t_3); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 511; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 511; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_1); __Pyx_GIVEREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_1 = PyObject_Call(((PyObject *)((PyObject*)__pyx_ptype_4h5py_3h5s_SpaceID)), __pyx_t_4, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 511; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_4); __Pyx_AddTraceback("h5py.h5a.AttrID.get_space"); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "/home/tachyon/h5py/h5py/h5a.pyx":514 * * * def get_type(self): # <<<<<<<<<<<<<< * """() => TypeID * */ static PyObject *__pyx_pf_4h5py_3h5a_6AttrID_get_type(PyObject *__pyx_v_self, PyObject *unused); /*proto*/ static char __pyx_doc_4h5py_3h5a_6AttrID_get_type[] = "() => TypeID\n\n Create and return a copy of the attribute's datatype.\n "; static PyObject *__pyx_pf_4h5py_3h5a_6AttrID_get_type(PyObject *__pyx_v_self, PyObject *unused) { PyObject *__pyx_r = NULL; PyObject *__pyx_t_1 = NULL; hid_t __pyx_t_2; hid_t __pyx_t_3; __Pyx_RefNannySetupContext("get_type"); /* "/home/tachyon/h5py/h5py/h5a.pyx":519 * Create and return a copy of the attribute's datatype. * """ * return typewrap(H5Aget_type(self.id)) # <<<<<<<<<<<<<< * * IF H5PY_18API: */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = PyObject_GetAttr(__pyx_v_self, __pyx_n_s__id); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 519; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = __Pyx_PyInt_from_py_hid_t(__pyx_t_1); if (unlikely((__pyx_t_2 == (hid_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 519; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_3 = H5Aget_type(__pyx_t_2); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 519; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_1 = ((PyObject *)__pyx_f_4h5py_3h5t_typewrap(__pyx_t_3)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 519; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("h5py.h5a.AttrID.get_type"); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_tp_new_4h5py_3h5a_AttrID(PyTypeObject *t, PyObject *a, PyObject *k) { PyObject *o = __pyx_ptype_4h5py_2h5_ObjectID->tp_new(t, a, k); if (!o) return 0; return o; } static void __pyx_tp_dealloc_4h5py_3h5a_AttrID(PyObject *o) { __pyx_ptype_4h5py_2h5_ObjectID->tp_dealloc(o); } static int __pyx_tp_traverse_4h5py_3h5a_AttrID(PyObject *o, visitproc v, void *a) { int e; if (__pyx_ptype_4h5py_2h5_ObjectID->tp_traverse) { e = __pyx_ptype_4h5py_2h5_ObjectID->tp_traverse(o, v, a); if (e) return e; } return 0; } static int __pyx_tp_clear_4h5py_3h5a_AttrID(PyObject *o) { if (__pyx_ptype_4h5py_2h5_ObjectID->tp_clear) { __pyx_ptype_4h5py_2h5_ObjectID->tp_clear(o); } return 0; } static PyObject *__pyx_getprop_4h5py_3h5a_6AttrID_name(PyObject *o, void *x) { return __pyx_pf_4h5py_3h5a_6AttrID_4name___get__(o); } static PyObject *__pyx_getprop_4h5py_3h5a_6AttrID_shape(PyObject *o, void *x) { return __pyx_pf_4h5py_3h5a_6AttrID_5shape___get__(o); } static PyObject *__pyx_getprop_4h5py_3h5a_6AttrID_dtype(PyObject *o, void *x) { return __pyx_pf_4h5py_3h5a_6AttrID_5dtype___get__(o); } static struct PyMethodDef __pyx_methods_4h5py_3h5a_AttrID[] = { {__Pyx_NAMESTR("_close"), (PyCFunction)__pyx_pf_4h5py_3h5a_6AttrID__close, METH_NOARGS, __Pyx_DOCSTR(__pyx_doc_4h5py_3h5a_6AttrID__close)}, {__Pyx_NAMESTR("read"), (PyCFunction)__pyx_pf_4h5py_3h5a_6AttrID_read, METH_O, __Pyx_DOCSTR(__pyx_doc_4h5py_3h5a_6AttrID_read)}, {__Pyx_NAMESTR("write"), (PyCFunction)__pyx_pf_4h5py_3h5a_6AttrID_write, METH_O, __Pyx_DOCSTR(__pyx_doc_4h5py_3h5a_6AttrID_write)}, {__Pyx_NAMESTR("get_name"), (PyCFunction)__pyx_pf_4h5py_3h5a_6AttrID_get_name, METH_NOARGS, __Pyx_DOCSTR(__pyx_doc_4h5py_3h5a_6AttrID_get_name)}, {__Pyx_NAMESTR("get_space"), (PyCFunction)__pyx_pf_4h5py_3h5a_6AttrID_get_space, METH_NOARGS, __Pyx_DOCSTR(__pyx_doc_4h5py_3h5a_6AttrID_get_space)}, {__Pyx_NAMESTR("get_type"), (PyCFunction)__pyx_pf_4h5py_3h5a_6AttrID_get_type, METH_NOARGS, __Pyx_DOCSTR(__pyx_doc_4h5py_3h5a_6AttrID_get_type)}, {0, 0, 0, 0} }; static struct PyGetSetDef __pyx_getsets_4h5py_3h5a_AttrID[] = { {(char *)"name", __pyx_getprop_4h5py_3h5a_6AttrID_name, 0, __Pyx_DOCSTR(__pyx_k_4), 0}, {(char *)"shape", __pyx_getprop_4h5py_3h5a_6AttrID_shape, 0, __Pyx_DOCSTR(__pyx_k_5), 0}, {(char *)"dtype", __pyx_getprop_4h5py_3h5a_6AttrID_dtype, 0, __Pyx_DOCSTR(__pyx_k_6), 0}, {0, 0, 0, 0, 0} }; static PyNumberMethods __pyx_tp_as_number_AttrID = { 0, /*nb_add*/ 0, /*nb_subtract*/ 0, /*nb_multiply*/ #if PY_MAJOR_VERSION < 3 0, /*nb_divide*/ #endif 0, /*nb_remainder*/ 0, /*nb_divmod*/ 0, /*nb_power*/ 0, /*nb_negative*/ 0, /*nb_positive*/ 0, /*nb_absolute*/ 0, /*nb_nonzero*/ 0, /*nb_invert*/ 0, /*nb_lshift*/ 0, /*nb_rshift*/ 0, /*nb_and*/ 0, /*nb_xor*/ 0, /*nb_or*/ #if PY_MAJOR_VERSION < 3 0, /*nb_coerce*/ #endif 0, /*nb_int*/ #if PY_MAJOR_VERSION >= 3 0, /*reserved*/ #else 0, /*nb_long*/ #endif 0, /*nb_float*/ #if PY_MAJOR_VERSION < 3 0, /*nb_oct*/ #endif #if PY_MAJOR_VERSION < 3 0, /*nb_hex*/ #endif 0, /*nb_inplace_add*/ 0, /*nb_inplace_subtract*/ 0, /*nb_inplace_multiply*/ #if PY_MAJOR_VERSION < 3 0, /*nb_inplace_divide*/ #endif 0, /*nb_inplace_remainder*/ 0, /*nb_inplace_power*/ 0, /*nb_inplace_lshift*/ 0, /*nb_inplace_rshift*/ 0, /*nb_inplace_and*/ 0, /*nb_inplace_xor*/ 0, /*nb_inplace_or*/ 0, /*nb_floor_divide*/ 0, /*nb_true_divide*/ 0, /*nb_inplace_floor_divide*/ 0, /*nb_inplace_true_divide*/ #if (PY_MAJOR_VERSION >= 3) || (Py_TPFLAGS_DEFAULT & Py_TPFLAGS_HAVE_INDEX) 0, /*nb_index*/ #endif }; static PySequenceMethods __pyx_tp_as_sequence_AttrID = { 0, /*sq_length*/ 0, /*sq_concat*/ 0, /*sq_repeat*/ 0, /*sq_item*/ 0, /*sq_slice*/ 0, /*sq_ass_item*/ 0, /*sq_ass_slice*/ 0, /*sq_contains*/ 0, /*sq_inplace_concat*/ 0, /*sq_inplace_repeat*/ }; static PyMappingMethods __pyx_tp_as_mapping_AttrID = { 0, /*mp_length*/ 0, /*mp_subscript*/ 0, /*mp_ass_subscript*/ }; static PyBufferProcs __pyx_tp_as_buffer_AttrID = { #if PY_MAJOR_VERSION < 3 0, /*bf_getreadbuffer*/ #endif #if PY_MAJOR_VERSION < 3 0, /*bf_getwritebuffer*/ #endif #if PY_MAJOR_VERSION < 3 0, /*bf_getsegcount*/ #endif #if PY_MAJOR_VERSION < 3 0, /*bf_getcharbuffer*/ #endif #if PY_VERSION_HEX >= 0x02060000 0, /*bf_getbuffer*/ #endif #if PY_VERSION_HEX >= 0x02060000 0, /*bf_releasebuffer*/ #endif }; PyTypeObject __pyx_type_4h5py_3h5a_AttrID = { PyVarObject_HEAD_INIT(0, 0) __Pyx_NAMESTR("h5py.h5a.AttrID"), /*tp_name*/ sizeof(struct __pyx_obj_4h5py_3h5a_AttrID), /*tp_basicsize*/ 0, /*tp_itemsize*/ __pyx_tp_dealloc_4h5py_3h5a_AttrID, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare*/ 0, /*tp_repr*/ &__pyx_tp_as_number_AttrID, /*tp_as_number*/ &__pyx_tp_as_sequence_AttrID, /*tp_as_sequence*/ &__pyx_tp_as_mapping_AttrID, /*tp_as_mapping*/ 0, /*tp_hash*/ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ &__pyx_tp_as_buffer_AttrID, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ __Pyx_DOCSTR("\n Logical representation of an HDF5 attribute identifier.\n\n Objects of this class can be used in any HDF5 function call\n which expects an attribute identifier. Additionally, all ``H5A*``\n functions which always take an attribute instance as the first\n argument are presented as methods of this class. \n\n * Hashable: No\n * Equality: Identifier comparison\n "), /*tp_doc*/ __pyx_tp_traverse_4h5py_3h5a_AttrID, /*tp_traverse*/ __pyx_tp_clear_4h5py_3h5a_AttrID, /*tp_clear*/ 0, /*tp_richcompare*/ 0, /*tp_weaklistoffset*/ 0, /*tp_iter*/ 0, /*tp_iternext*/ __pyx_methods_4h5py_3h5a_AttrID, /*tp_methods*/ 0, /*tp_members*/ __pyx_getsets_4h5py_3h5a_AttrID, /*tp_getset*/ 0, /*tp_base*/ 0, /*tp_dict*/ 0, /*tp_descr_get*/ 0, /*tp_descr_set*/ 0, /*tp_dictoffset*/ 0, /*tp_init*/ 0, /*tp_alloc*/ __pyx_tp_new_4h5py_3h5a_AttrID, /*tp_new*/ 0, /*tp_free*/ 0, /*tp_is_gc*/ 0, /*tp_bases*/ 0, /*tp_mro*/ 0, /*tp_cache*/ 0, /*tp_subclasses*/ 0, /*tp_weaklist*/ 0, /*tp_del*/ #if PY_VERSION_HEX >= 0x02060000 0, /*tp_version_tag*/ #endif }; static PyObject *__pyx_tp_new_4h5py_3h5a__AttrVisitor(PyTypeObject *t, PyObject *a, PyObject *k) { struct __pyx_obj_4h5py_3h5a__AttrVisitor *p; PyObject *o = (*t->tp_alloc)(t, 0); if (!o) return 0; p = ((struct __pyx_obj_4h5py_3h5a__AttrVisitor *)o); p->func = Py_None; Py_INCREF(Py_None); p->retval = Py_None; Py_INCREF(Py_None); return o; } static void __pyx_tp_dealloc_4h5py_3h5a__AttrVisitor(PyObject *o) { struct __pyx_obj_4h5py_3h5a__AttrVisitor *p = (struct __pyx_obj_4h5py_3h5a__AttrVisitor *)o; Py_XDECREF(p->func); Py_XDECREF(p->retval); (*Py_TYPE(o)->tp_free)(o); } static int __pyx_tp_traverse_4h5py_3h5a__AttrVisitor(PyObject *o, visitproc v, void *a) { int e; struct __pyx_obj_4h5py_3h5a__AttrVisitor *p = (struct __pyx_obj_4h5py_3h5a__AttrVisitor *)o; if (p->func) { e = (*v)(p->func, a); if (e) return e; } if (p->retval) { e = (*v)(p->retval, a); if (e) return e; } return 0; } static int __pyx_tp_clear_4h5py_3h5a__AttrVisitor(PyObject *o) { struct __pyx_obj_4h5py_3h5a__AttrVisitor *p = (struct __pyx_obj_4h5py_3h5a__AttrVisitor *)o; PyObject* tmp; tmp = ((PyObject*)p->func); p->func = Py_None; Py_INCREF(Py_None); Py_XDECREF(tmp); tmp = ((PyObject*)p->retval); p->retval = Py_None; Py_INCREF(Py_None); Py_XDECREF(tmp); return 0; } static struct PyMethodDef __pyx_methods_4h5py_3h5a__AttrVisitor[] = { {0, 0, 0, 0} }; static PyNumberMethods __pyx_tp_as_number__AttrVisitor = { 0, /*nb_add*/ 0, /*nb_subtract*/ 0, /*nb_multiply*/ #if PY_MAJOR_VERSION < 3 0, /*nb_divide*/ #endif 0, /*nb_remainder*/ 0, /*nb_divmod*/ 0, /*nb_power*/ 0, /*nb_negative*/ 0, /*nb_positive*/ 0, /*nb_absolute*/ 0, /*nb_nonzero*/ 0, /*nb_invert*/ 0, /*nb_lshift*/ 0, /*nb_rshift*/ 0, /*nb_and*/ 0, /*nb_xor*/ 0, /*nb_or*/ #if PY_MAJOR_VERSION < 3 0, /*nb_coerce*/ #endif 0, /*nb_int*/ #if PY_MAJOR_VERSION >= 3 0, /*reserved*/ #else 0, /*nb_long*/ #endif 0, /*nb_float*/ #if PY_MAJOR_VERSION < 3 0, /*nb_oct*/ #endif #if PY_MAJOR_VERSION < 3 0, /*nb_hex*/ #endif 0, /*nb_inplace_add*/ 0, /*nb_inplace_subtract*/ 0, /*nb_inplace_multiply*/ #if PY_MAJOR_VERSION < 3 0, /*nb_inplace_divide*/ #endif 0, /*nb_inplace_remainder*/ 0, /*nb_inplace_power*/ 0, /*nb_inplace_lshift*/ 0, /*nb_inplace_rshift*/ 0, /*nb_inplace_and*/ 0, /*nb_inplace_xor*/ 0, /*nb_inplace_or*/ 0, /*nb_floor_divide*/ 0, /*nb_true_divide*/ 0, /*nb_inplace_floor_divide*/ 0, /*nb_inplace_true_divide*/ #if (PY_MAJOR_VERSION >= 3) || (Py_TPFLAGS_DEFAULT & Py_TPFLAGS_HAVE_INDEX) 0, /*nb_index*/ #endif }; static PySequenceMethods __pyx_tp_as_sequence__AttrVisitor = { 0, /*sq_length*/ 0, /*sq_concat*/ 0, /*sq_repeat*/ 0, /*sq_item*/ 0, /*sq_slice*/ 0, /*sq_ass_item*/ 0, /*sq_ass_slice*/ 0, /*sq_contains*/ 0, /*sq_inplace_concat*/ 0, /*sq_inplace_repeat*/ }; static PyMappingMethods __pyx_tp_as_mapping__AttrVisitor = { 0, /*mp_length*/ 0, /*mp_subscript*/ 0, /*mp_ass_subscript*/ }; static PyBufferProcs __pyx_tp_as_buffer__AttrVisitor = { #if PY_MAJOR_VERSION < 3 0, /*bf_getreadbuffer*/ #endif #if PY_MAJOR_VERSION < 3 0, /*bf_getwritebuffer*/ #endif #if PY_MAJOR_VERSION < 3 0, /*bf_getsegcount*/ #endif #if PY_MAJOR_VERSION < 3 0, /*bf_getcharbuffer*/ #endif #if PY_VERSION_HEX >= 0x02060000 0, /*bf_getbuffer*/ #endif #if PY_VERSION_HEX >= 0x02060000 0, /*bf_releasebuffer*/ #endif }; PyTypeObject __pyx_type_4h5py_3h5a__AttrVisitor = { PyVarObject_HEAD_INIT(0, 0) __Pyx_NAMESTR("h5py.h5a._AttrVisitor"), /*tp_name*/ sizeof(struct __pyx_obj_4h5py_3h5a__AttrVisitor), /*tp_basicsize*/ 0, /*tp_itemsize*/ __pyx_tp_dealloc_4h5py_3h5a__AttrVisitor, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare*/ 0, /*tp_repr*/ &__pyx_tp_as_number__AttrVisitor, /*tp_as_number*/ &__pyx_tp_as_sequence__AttrVisitor, /*tp_as_sequence*/ &__pyx_tp_as_mapping__AttrVisitor, /*tp_as_mapping*/ 0, /*tp_hash*/ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ &__pyx_tp_as_buffer__AttrVisitor, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ 0, /*tp_doc*/ __pyx_tp_traverse_4h5py_3h5a__AttrVisitor, /*tp_traverse*/ __pyx_tp_clear_4h5py_3h5a__AttrVisitor, /*tp_clear*/ 0, /*tp_richcompare*/ 0, /*tp_weaklistoffset*/ 0, /*tp_iter*/ 0, /*tp_iternext*/ __pyx_methods_4h5py_3h5a__AttrVisitor, /*tp_methods*/ 0, /*tp_members*/ 0, /*tp_getset*/ 0, /*tp_base*/ 0, /*tp_dict*/ 0, /*tp_descr_get*/ 0, /*tp_descr_set*/ 0, /*tp_dictoffset*/ __pyx_pf_4h5py_3h5a_12_AttrVisitor___init__, /*tp_init*/ 0, /*tp_alloc*/ __pyx_tp_new_4h5py_3h5a__AttrVisitor, /*tp_new*/ 0, /*tp_free*/ 0, /*tp_is_gc*/ 0, /*tp_bases*/ 0, /*tp_mro*/ 0, /*tp_cache*/ 0, /*tp_subclasses*/ 0, /*tp_weaklist*/ 0, /*tp_del*/ #if PY_VERSION_HEX >= 0x02060000 0, /*tp_version_tag*/ #endif }; static struct PyMethodDef __pyx_methods[] = { {__Pyx_NAMESTR("create"), (PyCFunction)__pyx_pf_4h5py_3h5a_create, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_4h5py_3h5a_create)}, {__Pyx_NAMESTR("open"), (PyCFunction)__pyx_pf_4h5py_3h5a_open, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_4h5py_3h5a_open)}, {__Pyx_NAMESTR("exists"), (PyCFunction)__pyx_pf_4h5py_3h5a_exists, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_4h5py_3h5a_exists)}, {__Pyx_NAMESTR("delete"), (PyCFunction)__pyx_pf_4h5py_3h5a_delete, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_4h5py_3h5a_delete)}, {__Pyx_NAMESTR("get_num_attrs"), (PyCFunction)__pyx_pf_4h5py_3h5a_get_num_attrs, METH_O, __Pyx_DOCSTR(__pyx_doc_4h5py_3h5a_get_num_attrs)}, {__Pyx_NAMESTR("iterate"), (PyCFunction)__pyx_pf_4h5py_3h5a_iterate, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_4h5py_3h5a_iterate)}, {0, 0, 0, 0} }; static void __pyx_init_filenames(void); /*proto*/ #if PY_MAJOR_VERSION >= 3 static struct PyModuleDef __pyx_moduledef = { PyModuleDef_HEAD_INIT, __Pyx_NAMESTR("h5a"), __Pyx_DOCSTR(__pyx_k_7), /* m_doc */ -1, /* m_size */ __pyx_methods /* m_methods */, NULL, /* m_reload */ NULL, /* m_traverse */ NULL, /* m_clear */ NULL /* m_free */ }; #endif static __Pyx_StringTabEntry __pyx_string_tab[] = { {&__pyx_kp_s_1, __pyx_k_1, sizeof(__pyx_k_1), 0, 0, 1, 0}, {&__pyx_kp_s_2, __pyx_k_2, sizeof(__pyx_k_2), 0, 0, 1, 0}, {&__pyx_n_s_3, __pyx_k_3, sizeof(__pyx_k_3), 0, 0, 1, 1}, {&__pyx_n_s__TypeError, __pyx_k__TypeError, sizeof(__pyx_k__TypeError), 0, 0, 1, 1}, {&__pyx_n_s__ValueError, __pyx_k__ValueError, sizeof(__pyx_k__ValueError), 0, 0, 1, 1}, {&__pyx_n_s____main__, __pyx_k____main__, sizeof(__pyx_k____main__), 0, 0, 1, 1}, {&__pyx_n_s__dtype, __pyx_k__dtype, sizeof(__pyx_k__dtype), 0, 0, 1, 1}, {&__pyx_n_s__func, __pyx_k__func, sizeof(__pyx_k__func), 0, 0, 1, 1}, {&__pyx_n_s__get_name, __pyx_k__get_name, sizeof(__pyx_k__get_name), 0, 0, 1, 1}, {&__pyx_n_s__get_space, __pyx_k__get_space, sizeof(__pyx_k__get_space), 0, 0, 1, 1}, {&__pyx_n_s__get_type, __pyx_k__get_type, sizeof(__pyx_k__get_type), 0, 0, 1, 1}, {&__pyx_n_s__id, __pyx_k__id, sizeof(__pyx_k__id), 0, 0, 1, 1}, {&__pyx_n_s__index, __pyx_k__index, sizeof(__pyx_k__index), 0, 0, 1, 1}, {&__pyx_n_s__loc, __pyx_k__loc, sizeof(__pyx_k__loc), 0, 0, 1, 1}, {&__pyx_n_s__name, __pyx_k__name, sizeof(__pyx_k__name), 0, 0, 1, 1}, {&__pyx_n_s__py_dtype, __pyx_k__py_dtype, sizeof(__pyx_k__py_dtype), 0, 0, 1, 1}, {&__pyx_n_s__retval, __pyx_k__retval, sizeof(__pyx_k__retval), 0, 0, 1, 1}, {&__pyx_n_s__space, __pyx_k__space, sizeof(__pyx_k__space), 0, 0, 1, 1}, {&__pyx_n_s__tid, __pyx_k__tid, sizeof(__pyx_k__tid), 0, 0, 1, 1}, {0, 0, 0, 0, 0, 0, 0} }; static int __Pyx_InitCachedBuiltins(void) { __pyx_builtin_TypeError = __Pyx_GetName(__pyx_b, __pyx_n_s__TypeError); if (!__pyx_builtin_TypeError) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 109; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_builtin_ValueError = __Pyx_GetName(__pyx_b, __pyx_n_s__ValueError); if (!__pyx_builtin_ValueError) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 374; __pyx_clineno = __LINE__; goto __pyx_L1_error;} return 0; __pyx_L1_error:; return -1; } static int __Pyx_InitGlobals(void) { if (__Pyx_InitStrings(__pyx_string_tab) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; return 0; __pyx_L1_error:; return -1; } #if PY_MAJOR_VERSION < 3 PyMODINIT_FUNC inith5a(void); /*proto*/ PyMODINIT_FUNC inith5a(void) #else PyMODINIT_FUNC PyInit_h5a(void); /*proto*/ PyMODINIT_FUNC PyInit_h5a(void) #endif { PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; PyObject *__pyx_t_5 = NULL; int __pyx_t_6; #if CYTHON_REFNANNY void* __pyx_refnanny = NULL; __Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny"); if (!__Pyx_RefNanny) { PyErr_Clear(); __Pyx_RefNanny = __Pyx_RefNannyImportAPI("Cython.Runtime.refnanny"); if (!__Pyx_RefNanny) Py_FatalError("failed to import 'refnanny' module"); } __pyx_refnanny = __Pyx_RefNanny->SetupContext("PyMODINIT_FUNC PyInit_h5a(void)", __LINE__, __FILE__); #endif __pyx_init_filenames(); __pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #if PY_MAJOR_VERSION < 3 __pyx_empty_bytes = PyString_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #else __pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #endif /*--- Library function declarations ---*/ /*--- Threads initialization code ---*/ #if defined(__PYX_FORCE_INIT_THREADS) && __PYX_FORCE_INIT_THREADS #ifdef WITH_THREAD /* Python build with threading support? */ PyEval_InitThreads(); #endif #endif /*--- Module creation code ---*/ #if PY_MAJOR_VERSION < 3 __pyx_m = Py_InitModule4(__Pyx_NAMESTR("h5a"), __pyx_methods, __Pyx_DOCSTR(__pyx_k_7), 0, PYTHON_API_VERSION); #else __pyx_m = PyModule_Create(&__pyx_moduledef); #endif if (!__pyx_m) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; #if PY_MAJOR_VERSION < 3 Py_INCREF(__pyx_m); #endif __pyx_b = PyImport_AddModule(__Pyx_NAMESTR(__Pyx_BUILTIN_MODULE_NAME)); if (!__pyx_b) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; if (__Pyx_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; /*--- Initialize various global constants etc. ---*/ if (unlikely(__Pyx_InitGlobals() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (__pyx_module_is_main_h5py__h5a) { if (__Pyx_SetAttrString(__pyx_m, "__name__", __pyx_n_s____main__) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; } /*--- Builtin init code ---*/ if (unlikely(__Pyx_InitCachedBuiltins() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /*--- Global init code ---*/ /*--- Function export code ---*/ /*--- Type init code ---*/ __pyx_ptype_4h5py_2h5_ObjectID = __Pyx_ImportType("h5py.h5", "ObjectID", sizeof(struct __pyx_obj_4h5py_2h5_ObjectID), 1); if (unlikely(!__pyx_ptype_4h5py_2h5_ObjectID)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_type_4h5py_3h5a_AttrID.tp_base = __pyx_ptype_4h5py_2h5_ObjectID; if (PyType_Ready(&__pyx_type_4h5py_3h5a_AttrID) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 386; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (__Pyx_SetAttrString(__pyx_m, "AttrID", (PyObject *)&__pyx_type_4h5py_3h5a_AttrID) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 386; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (__pyx_type_4h5py_3h5a_AttrID.tp_weaklistoffset == 0) __pyx_type_4h5py_3h5a_AttrID.tp_weaklistoffset = offsetof(struct __pyx_obj_4h5py_3h5a_AttrID, __pyx_base.__weakref__); __pyx_ptype_4h5py_3h5a_AttrID = &__pyx_type_4h5py_3h5a_AttrID; if (PyType_Ready(&__pyx_type_4h5py_3h5a__AttrVisitor) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 282; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (__Pyx_SetAttrString(__pyx_m, "_AttrVisitor", (PyObject *)&__pyx_type_4h5py_3h5a__AttrVisitor) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 282; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_ptype_4h5py_3h5a__AttrVisitor = &__pyx_type_4h5py_3h5a__AttrVisitor; /*--- Type import code ---*/ __pyx_ptype_4h5py_2h5_H5PYConfig = __Pyx_ImportType("h5py.h5", "H5PYConfig", sizeof(struct __pyx_obj_4h5py_2h5_H5PYConfig), 1); if (unlikely(!__pyx_ptype_4h5py_2h5_H5PYConfig)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 15; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_ptype_4h5py_2h5_IDProxy = __Pyx_ImportType("h5py.h5", "IDProxy", sizeof(struct __pyx_obj_4h5py_2h5_IDProxy), 1); if (unlikely(!__pyx_ptype_4h5py_2h5_IDProxy)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 28; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_ptype_4h5py_2h5_SmartStruct = __Pyx_ImportType("h5py.h5", "SmartStruct", sizeof(struct __pyx_obj_4h5py_2h5_SmartStruct), 1); if (unlikely(!__pyx_ptype_4h5py_2h5_SmartStruct)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 40; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_ptype_4h5py_3h5t_TypeID = __Pyx_ImportType("h5py.h5t", "TypeID", sizeof(struct __pyx_obj_4h5py_3h5t_TypeID), 1); if (unlikely(!__pyx_ptype_4h5py_3h5t_TypeID)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 17; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (__Pyx_GetVtable(__pyx_ptype_4h5py_3h5t_TypeID->tp_dict, &__pyx_vtabptr_4h5py_3h5t_TypeID) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 17; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_ptype_4h5py_3h5t_TypeArrayID = __Pyx_ImportType("h5py.h5t", "TypeArrayID", sizeof(struct __pyx_obj_4h5py_3h5t_TypeArrayID), 1); if (unlikely(!__pyx_ptype_4h5py_3h5t_TypeArrayID)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 23; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (__Pyx_GetVtable(__pyx_ptype_4h5py_3h5t_TypeArrayID->tp_dict, &__pyx_vtabptr_4h5py_3h5t_TypeArrayID) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 23; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_ptype_4h5py_3h5t_TypeOpaqueID = __Pyx_ImportType("h5py.h5t", "TypeOpaqueID", sizeof(struct __pyx_obj_4h5py_3h5t_TypeOpaqueID), 1); if (unlikely(!__pyx_ptype_4h5py_3h5t_TypeOpaqueID)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 26; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (__Pyx_GetVtable(__pyx_ptype_4h5py_3h5t_TypeOpaqueID->tp_dict, &__pyx_vtabptr_4h5py_3h5t_TypeOpaqueID) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 26; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_ptype_4h5py_3h5t_TypeStringID = __Pyx_ImportType("h5py.h5t", "TypeStringID", sizeof(struct __pyx_obj_4h5py_3h5t_TypeStringID), 1); if (unlikely(!__pyx_ptype_4h5py_3h5t_TypeStringID)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 29; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (__Pyx_GetVtable(__pyx_ptype_4h5py_3h5t_TypeStringID->tp_dict, &__pyx_vtabptr_4h5py_3h5t_TypeStringID) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 29; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_ptype_4h5py_3h5t_TypeVlenID = __Pyx_ImportType("h5py.h5t", "TypeVlenID", sizeof(struct __pyx_obj_4h5py_3h5t_TypeVlenID), 1); if (unlikely(!__pyx_ptype_4h5py_3h5t_TypeVlenID)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 33; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (__Pyx_GetVtable(__pyx_ptype_4h5py_3h5t_TypeVlenID->tp_dict, &__pyx_vtabptr_4h5py_3h5t_TypeVlenID) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 33; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_ptype_4h5py_3h5t_TypeTimeID = __Pyx_ImportType("h5py.h5t", "TypeTimeID", sizeof(struct __pyx_obj_4h5py_3h5t_TypeTimeID), 1); if (unlikely(!__pyx_ptype_4h5py_3h5t_TypeTimeID)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 37; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (__Pyx_GetVtable(__pyx_ptype_4h5py_3h5t_TypeTimeID->tp_dict, &__pyx_vtabptr_4h5py_3h5t_TypeTimeID) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 37; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_ptype_4h5py_3h5t_TypeBitfieldID = __Pyx_ImportType("h5py.h5t", "TypeBitfieldID", sizeof(struct __pyx_obj_4h5py_3h5t_TypeBitfieldID), 1); if (unlikely(!__pyx_ptype_4h5py_3h5t_TypeBitfieldID)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 40; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (__Pyx_GetVtable(__pyx_ptype_4h5py_3h5t_TypeBitfieldID->tp_dict, &__pyx_vtabptr_4h5py_3h5t_TypeBitfieldID) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 40; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_ptype_4h5py_3h5t_TypeReferenceID = __Pyx_ImportType("h5py.h5t", "TypeReferenceID", sizeof(struct __pyx_obj_4h5py_3h5t_TypeReferenceID), 1); if (unlikely(!__pyx_ptype_4h5py_3h5t_TypeReferenceID)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 43; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (__Pyx_GetVtable(__pyx_ptype_4h5py_3h5t_TypeReferenceID->tp_dict, &__pyx_vtabptr_4h5py_3h5t_TypeReferenceID) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 43; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_ptype_4h5py_3h5t_TypeAtomicID = __Pyx_ImportType("h5py.h5t", "TypeAtomicID", sizeof(struct __pyx_obj_4h5py_3h5t_TypeAtomicID), 1); if (unlikely(!__pyx_ptype_4h5py_3h5t_TypeAtomicID)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 48; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (__Pyx_GetVtable(__pyx_ptype_4h5py_3h5t_TypeAtomicID->tp_dict, &__pyx_vtabptr_4h5py_3h5t_TypeAtomicID) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 48; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_ptype_4h5py_3h5t_TypeIntegerID = __Pyx_ImportType("h5py.h5t", "TypeIntegerID", sizeof(struct __pyx_obj_4h5py_3h5t_TypeIntegerID), 1); if (unlikely(!__pyx_ptype_4h5py_3h5t_TypeIntegerID)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 51; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (__Pyx_GetVtable(__pyx_ptype_4h5py_3h5t_TypeIntegerID->tp_dict, &__pyx_vtabptr_4h5py_3h5t_TypeIntegerID) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 51; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_ptype_4h5py_3h5t_TypeFloatID = __Pyx_ImportType("h5py.h5t", "TypeFloatID", sizeof(struct __pyx_obj_4h5py_3h5t_TypeFloatID), 1); if (unlikely(!__pyx_ptype_4h5py_3h5t_TypeFloatID)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 54; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (__Pyx_GetVtable(__pyx_ptype_4h5py_3h5t_TypeFloatID->tp_dict, &__pyx_vtabptr_4h5py_3h5t_TypeFloatID) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 54; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_ptype_4h5py_3h5t_TypeCompositeID = __Pyx_ImportType("h5py.h5t", "TypeCompositeID", sizeof(struct __pyx_obj_4h5py_3h5t_TypeCompositeID), 1); if (unlikely(!__pyx_ptype_4h5py_3h5t_TypeCompositeID)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 59; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (__Pyx_GetVtable(__pyx_ptype_4h5py_3h5t_TypeCompositeID->tp_dict, &__pyx_vtabptr_4h5py_3h5t_TypeCompositeID) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 59; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_ptype_4h5py_3h5t_TypeEnumID = __Pyx_ImportType("h5py.h5t", "TypeEnumID", sizeof(struct __pyx_obj_4h5py_3h5t_TypeEnumID), 1); if (unlikely(!__pyx_ptype_4h5py_3h5t_TypeEnumID)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 62; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (__Pyx_GetVtable(__pyx_ptype_4h5py_3h5t_TypeEnumID->tp_dict, &__pyx_vtabptr_4h5py_3h5t_TypeEnumID) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 62; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_ptype_4h5py_3h5t_TypeCompoundID = __Pyx_ImportType("h5py.h5t", "TypeCompoundID", sizeof(struct __pyx_obj_4h5py_3h5t_TypeCompoundID), 1); if (unlikely(!__pyx_ptype_4h5py_3h5t_TypeCompoundID)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 66; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (__Pyx_GetVtable(__pyx_ptype_4h5py_3h5t_TypeCompoundID->tp_dict, &__pyx_vtabptr_4h5py_3h5t_TypeCompoundID) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 66; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_ptype_4h5py_3h5s_SpaceID = __Pyx_ImportType("h5py.h5s", "SpaceID", sizeof(struct __pyx_obj_4h5py_3h5s_SpaceID), 1); if (unlikely(!__pyx_ptype_4h5py_3h5s_SpaceID)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 17; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_ptype_4h5py_3h5p_PropID = __Pyx_ImportType("h5py.h5p", "PropID", sizeof(struct __pyx_obj_4h5py_3h5p_PropID), 1); if (unlikely(!__pyx_ptype_4h5py_3h5p_PropID)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 23; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_ptype_4h5py_3h5p_PropClassID = __Pyx_ImportType("h5py.h5p", "PropClassID", sizeof(struct __pyx_obj_4h5py_3h5p_PropClassID), 1); if (unlikely(!__pyx_ptype_4h5py_3h5p_PropClassID)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 27; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_ptype_4h5py_3h5p_PropInstanceID = __Pyx_ImportType("h5py.h5p", "PropInstanceID", sizeof(struct __pyx_obj_4h5py_3h5p_PropInstanceID), 1); if (unlikely(!__pyx_ptype_4h5py_3h5p_PropInstanceID)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 33; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_ptype_4h5py_3h5p_PropCreateID = __Pyx_ImportType("h5py.h5p", "PropCreateID", sizeof(struct __pyx_obj_4h5py_3h5p_PropCreateID), 1); if (unlikely(!__pyx_ptype_4h5py_3h5p_PropCreateID)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 39; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_ptype_4h5py_3h5p_PropCopyID = __Pyx_ImportType("h5py.h5p", "PropCopyID", sizeof(struct __pyx_obj_4h5py_3h5p_PropCopyID), 1); if (unlikely(!__pyx_ptype_4h5py_3h5p_PropCopyID)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 46; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_ptype_4h5py_3h5p_PropDCID = __Pyx_ImportType("h5py.h5p", "PropDCID", sizeof(struct __pyx_obj_4h5py_3h5p_PropDCID), 1); if (unlikely(!__pyx_ptype_4h5py_3h5p_PropDCID)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 51; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_ptype_4h5py_3h5p_PropFCID = __Pyx_ImportType("h5py.h5p", "PropFCID", sizeof(struct __pyx_obj_4h5py_3h5p_PropFCID), 1); if (unlikely(!__pyx_ptype_4h5py_3h5p_PropFCID)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_ptype_4h5py_3h5p_PropFAID = __Pyx_ImportType("h5py.h5p", "PropFAID", sizeof(struct __pyx_obj_4h5py_3h5p_PropFAID), 1); if (unlikely(!__pyx_ptype_4h5py_3h5p_PropFAID)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 62; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_ptype_4h5py_3h5p_PropDXID = __Pyx_ImportType("h5py.h5p", "PropDXID", sizeof(struct __pyx_obj_4h5py_3h5p_PropDXID), 1); if (unlikely(!__pyx_ptype_4h5py_3h5p_PropDXID)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 66; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_ptype_4h5py_5numpy_dtype = __Pyx_ImportType("numpy", "dtype", sizeof(PyArray_Descr), 0); if (unlikely(!__pyx_ptype_4h5py_5numpy_dtype)) {__pyx_filename = __pyx_f[5]; __pyx_lineno = 69; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_ptype_4h5py_5numpy_ndarray = __Pyx_ImportType("numpy", "ndarray", sizeof(PyArrayObject), 0); if (unlikely(!__pyx_ptype_4h5py_5numpy_ndarray)) {__pyx_filename = __pyx_f[5]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /*--- Function import code ---*/ __pyx_t_1 = __Pyx_ImportModule("h5py.h5"); if (!__pyx_t_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (__Pyx_ImportFunction(__pyx_t_1, "get_config", (void (**)(void))&__pyx_f_4h5py_2h5_get_config, "struct __pyx_obj_4h5py_2h5_H5PYConfig *(int __pyx_skip_dispatch)") < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (__Pyx_ImportFunction(__pyx_t_1, "init_hdf5", (void (**)(void))&__pyx_f_4h5py_2h5_init_hdf5, "int (void)") < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_2 = __Pyx_ImportModule("h5py.h5t"); if (!__pyx_t_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (__Pyx_ImportFunction(__pyx_t_2, "typewrap", (void (**)(void))&__pyx_f_4h5py_3h5t_typewrap, "struct __pyx_obj_4h5py_3h5t_TypeID *(hid_t)") < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (__Pyx_ImportFunction(__pyx_t_2, "py_create", (void (**)(void))&__pyx_f_4h5py_3h5t_py_create, "struct __pyx_obj_4h5py_3h5t_TypeID *(PyObject *, int __pyx_skip_dispatch, struct __pyx_opt_args_4h5py_3h5t_py_create *__pyx_optional_args)") < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_3 = __Pyx_ImportModule("h5py.h5p"); if (!__pyx_t_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (__Pyx_ImportFunction(__pyx_t_3, "pdefault", (void (**)(void))&__pyx_f_4h5py_3h5p_pdefault, "hid_t (struct __pyx_obj_4h5py_3h5p_PropID *)") < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (__Pyx_ImportFunction(__pyx_t_3, "propwrap", (void (**)(void))&__pyx_f_4h5py_3h5p_propwrap, "PyObject *(hid_t)") < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_4 = __Pyx_ImportModule("h5py.utils"); if (!__pyx_t_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (__Pyx_ImportFunction(__pyx_t_4, "emalloc", (void (**)(void))&__pyx_f_4h5py_5utils_emalloc, "void *(size_t)") < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (__Pyx_ImportFunction(__pyx_t_4, "efree", (void (**)(void))&__pyx_f_4h5py_5utils_efree, "void (void *)") < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (__Pyx_ImportFunction(__pyx_t_4, "check_numpy_read", (void (**)(void))&__pyx_f_4h5py_5utils_check_numpy_read, "int (PyArrayObject *, int __pyx_skip_dispatch, struct __pyx_opt_args_4h5py_5utils_check_numpy_read *__pyx_optional_args)") < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (__Pyx_ImportFunction(__pyx_t_4, "check_numpy_write", (void (**)(void))&__pyx_f_4h5py_5utils_check_numpy_write, "int (PyArrayObject *, int __pyx_skip_dispatch, struct __pyx_opt_args_4h5py_5utils_check_numpy_write *__pyx_optional_args)") < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (__Pyx_ImportFunction(__pyx_t_4, "convert_tuple", (void (**)(void))&__pyx_f_4h5py_5utils_convert_tuple, "int (PyObject *, hsize_t *, hsize_t)") < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (__Pyx_ImportFunction(__pyx_t_4, "convert_dims", (void (**)(void))&__pyx_f_4h5py_5utils_convert_dims, "PyObject *(hsize_t *, hsize_t)") < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (__Pyx_ImportFunction(__pyx_t_4, "require_tuple", (void (**)(void))&__pyx_f_4h5py_5utils_require_tuple, "int (PyObject *, int, int, char *)") < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (__Pyx_ImportFunction(__pyx_t_4, "create_numpy_hsize", (void (**)(void))&__pyx_f_4h5py_5utils_create_numpy_hsize, "PyObject *(int, hsize_t *)") < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (__Pyx_ImportFunction(__pyx_t_4, "create_hsize_array", (void (**)(void))&__pyx_f_4h5py_5utils_create_hsize_array, "PyObject *(PyObject *)") < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_5 = __Pyx_ImportModule("h5py._proxy"); if (!__pyx_t_5) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (__Pyx_ImportFunction(__pyx_t_5, "attr_rw", (void (**)(void))&__pyx_f_4h5py_6_proxy_attr_rw, "herr_t (hid_t, hid_t, void *, int)") < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (__Pyx_ImportFunction(__pyx_t_5, "dset_rw", (void (**)(void))&__pyx_f_4h5py_6_proxy_dset_rw, "herr_t (hid_t, hid_t, hid_t, hid_t, hid_t, void *, int)") < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(__pyx_t_5); __pyx_t_5 = 0; /*--- Execution code ---*/ /* "/home/tachyon/h5py/h5py/h5a.pyx":29 * * # Initialization * import_array() # <<<<<<<<<<<<<< * init_hdf5() * */ import_array(); /* "/home/tachyon/h5py/h5py/h5a.pyx":30 * # Initialization * import_array() * init_hdf5() # <<<<<<<<<<<<<< * * # === General attribute operations ============================================ */ __pyx_t_6 = __pyx_f_4h5py_2h5_init_hdf5(); if (unlikely(__pyx_t_6 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 30; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /* "/home/tachyon/h5py/h5py/h5a.pxd":1 * #+ # <<<<<<<<<<<<<< * # * # This file is part of h5py, a low-level Python interface to the HDF5 library. */ goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_XDECREF(__pyx_t_5); if (__pyx_m) { __Pyx_AddTraceback("init h5py.h5a"); Py_DECREF(__pyx_m); __pyx_m = 0; } else if (!PyErr_Occurred()) { PyErr_SetString(PyExc_ImportError, "init h5py.h5a"); } __pyx_L0:; __Pyx_RefNannyFinishContext(); #if PY_MAJOR_VERSION < 3 return; #else return __pyx_m; #endif } static const char *__pyx_filenames[] = { "h5a.pyx", "h5.pxd", "h5t.pxd", "h5s.pxd", "h5p.pxd", "numpy.pxd", }; /* Runtime support code */ static void __pyx_init_filenames(void) { __pyx_f = __pyx_filenames; } static void __Pyx_RaiseDoubleKeywordsError( const char* func_name, PyObject* kw_name) { PyErr_Format(PyExc_TypeError, #if PY_MAJOR_VERSION >= 3 "%s() got multiple values for keyword argument '%U'", func_name, kw_name); #else "%s() got multiple values for keyword argument '%s'", func_name, PyString_AS_STRING(kw_name)); #endif } static void __Pyx_RaiseArgtupleInvalid( const char* func_name, int exact, Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found) { Py_ssize_t num_expected; const char *number, *more_or_less; if (num_found < num_min) { num_expected = num_min; more_or_less = "at least"; } else { num_expected = num_max; more_or_less = "at most"; } if (exact) { more_or_less = "exactly"; } number = (num_expected == 1) ? "" : "s"; PyErr_Format(PyExc_TypeError, #if PY_VERSION_HEX < 0x02050000 "%s() takes %s %d positional argument%s (%d given)", #else "%s() takes %s %zd positional argument%s (%zd given)", #endif func_name, more_or_less, num_expected, number, num_found); } static int __Pyx_ParseOptionalKeywords( PyObject *kwds, PyObject **argnames[], PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args, const char* function_name) { PyObject *key = 0, *value = 0; Py_ssize_t pos = 0; PyObject*** name; PyObject*** first_kw_arg = argnames + num_pos_args; while (PyDict_Next(kwds, &pos, &key, &value)) { name = first_kw_arg; while (*name && (**name != key)) name++; if (*name) { values[name-argnames] = value; } else { #if PY_MAJOR_VERSION < 3 if (unlikely(!PyString_CheckExact(key)) && unlikely(!PyString_Check(key))) { #else if (unlikely(!PyUnicode_CheckExact(key)) && unlikely(!PyUnicode_Check(key))) { #endif goto invalid_keyword_type; } else { for (name = first_kw_arg; *name; name++) { #if PY_MAJOR_VERSION >= 3 if (PyUnicode_GET_SIZE(**name) == PyUnicode_GET_SIZE(key) && PyUnicode_Compare(**name, key) == 0) break; #else if (PyString_GET_SIZE(**name) == PyString_GET_SIZE(key) && _PyString_Eq(**name, key)) break; #endif } if (*name) { values[name-argnames] = value; } else { /* unexpected keyword found */ for (name=argnames; name != first_kw_arg; name++) { if (**name == key) goto arg_passed_twice; #if PY_MAJOR_VERSION >= 3 if (PyUnicode_GET_SIZE(**name) == PyUnicode_GET_SIZE(key) && PyUnicode_Compare(**name, key) == 0) goto arg_passed_twice; #else if (PyString_GET_SIZE(**name) == PyString_GET_SIZE(key) && _PyString_Eq(**name, key)) goto arg_passed_twice; #endif } if (kwds2) { if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; } else { goto invalid_keyword; } } } } } return 0; arg_passed_twice: __Pyx_RaiseDoubleKeywordsError(function_name, **name); goto bad; invalid_keyword_type: PyErr_Format(PyExc_TypeError, "%s() keywords must be strings", function_name); goto bad; invalid_keyword: PyErr_Format(PyExc_TypeError, #if PY_MAJOR_VERSION < 3 "%s() got an unexpected keyword argument '%s'", function_name, PyString_AsString(key)); #else "%s() got an unexpected keyword argument '%U'", function_name, key); #endif bad: return -1; } static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) { if (unlikely(!type)) { PyErr_Format(PyExc_SystemError, "Missing type object"); return 0; } if (likely(PyObject_TypeCheck(obj, type))) return 1; PyErr_Format(PyExc_TypeError, "Cannot convert %.200s to %.200s", Py_TYPE(obj)->tp_name, type->tp_name); return 0; } static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb) { PyObject *tmp_type, *tmp_value, *tmp_tb; PyThreadState *tstate = PyThreadState_GET(); tmp_type = tstate->curexc_type; tmp_value = tstate->curexc_value; tmp_tb = tstate->curexc_traceback; tstate->curexc_type = type; tstate->curexc_value = value; tstate->curexc_traceback = tb; Py_XDECREF(tmp_type); Py_XDECREF(tmp_value); Py_XDECREF(tmp_tb); } static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb) { PyThreadState *tstate = PyThreadState_GET(); *type = tstate->curexc_type; *value = tstate->curexc_value; *tb = tstate->curexc_traceback; tstate->curexc_type = 0; tstate->curexc_value = 0; tstate->curexc_traceback = 0; } static int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, const char *name, int exact) { if (!type) { PyErr_Format(PyExc_SystemError, "Missing type object"); return 0; } if (none_allowed && obj == Py_None) return 1; else if (exact) { if (Py_TYPE(obj) == type) return 1; } else { if (PyObject_TypeCheck(obj, type)) return 1; } PyErr_Format(PyExc_TypeError, "Argument '%s' has incorrect type (expected %s, got %s)", name, type->tp_name, Py_TYPE(obj)->tp_name); return 0; } static CYTHON_INLINE hid_t __Pyx_PyInt_from_py_hid_t(PyObject* x) { const hid_t neg_one = (hid_t)-1, const_zero = 0; const int is_unsigned = neg_one > const_zero; if (sizeof(hid_t) == sizeof(char)) { if (is_unsigned) return (hid_t)__Pyx_PyInt_AsUnsignedChar(x); else return (hid_t)__Pyx_PyInt_AsSignedChar(x); } else if (sizeof(hid_t) == sizeof(short)) { if (is_unsigned) return (hid_t)__Pyx_PyInt_AsUnsignedShort(x); else return (hid_t)__Pyx_PyInt_AsSignedShort(x); } else if (sizeof(hid_t) == sizeof(int)) { if (is_unsigned) return (hid_t)__Pyx_PyInt_AsUnsignedInt(x); else return (hid_t)__Pyx_PyInt_AsSignedInt(x); } else if (sizeof(hid_t) == sizeof(long)) { if (is_unsigned) return (hid_t)__Pyx_PyInt_AsUnsignedLong(x); else return (hid_t)__Pyx_PyInt_AsSignedLong(x); } else if (sizeof(hid_t) == sizeof(PY_LONG_LONG)) { if (is_unsigned) return (hid_t)__Pyx_PyInt_AsUnsignedLongLong(x); else return (hid_t)__Pyx_PyInt_AsSignedLongLong(x); #if 0 } else if (sizeof(hid_t) > sizeof(short) && sizeof(hid_t) < sizeof(int)) { /* __int32 ILP64 ? */ if (is_unsigned) return (hid_t)__Pyx_PyInt_AsUnsignedInt(x); else return (hid_t)__Pyx_PyInt_AsSignedInt(x); #endif } PyErr_SetString(PyExc_TypeError, "hid_t"); return (hid_t)-1; } static CYTHON_INLINE PyObject *__Pyx_PyInt_to_py_hid_t(hid_t val) { const hid_t neg_one = (hid_t)-1, const_zero = 0; const int is_unsigned = neg_one > const_zero; if (sizeof(hid_t) < sizeof(long)) { return PyInt_FromLong((long)val); } else if (sizeof(hid_t) == sizeof(long)) { if (is_unsigned) return PyLong_FromUnsignedLong((unsigned long)val); else return PyInt_FromLong((long)val); } else { /* (sizeof(hid_t) > sizeof(long)) */ if (is_unsigned) return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)val); else return PyLong_FromLongLong((PY_LONG_LONG)val); } } static PyObject *__Pyx_GetName(PyObject *dict, PyObject *name) { PyObject *result; result = PyObject_GetAttr(dict, name); if (!result) PyErr_SetObject(PyExc_NameError, name); return result; } #if PY_MAJOR_VERSION < 3 static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb) { Py_XINCREF(type); Py_XINCREF(value); Py_XINCREF(tb); /* First, check the traceback argument, replacing None with NULL. */ if (tb == Py_None) { Py_DECREF(tb); tb = 0; } else if (tb != NULL && !PyTraceBack_Check(tb)) { PyErr_SetString(PyExc_TypeError, "raise: arg 3 must be a traceback or None"); goto raise_error; } /* Next, replace a missing value with None */ if (value == NULL) { value = Py_None; Py_INCREF(value); } #if PY_VERSION_HEX < 0x02050000 if (!PyClass_Check(type)) #else if (!PyType_Check(type)) #endif { /* Raising an instance. The value should be a dummy. */ if (value != Py_None) { PyErr_SetString(PyExc_TypeError, "instance exception may not have a separate value"); goto raise_error; } /* Normalize to raise <class>, <instance> */ Py_DECREF(value); value = type; #if PY_VERSION_HEX < 0x02050000 if (PyInstance_Check(type)) { type = (PyObject*) ((PyInstanceObject*)type)->in_class; Py_INCREF(type); } else { type = 0; PyErr_SetString(PyExc_TypeError, "raise: exception must be an old-style class or instance"); goto raise_error; } #else type = (PyObject*) Py_TYPE(type); Py_INCREF(type); if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) { PyErr_SetString(PyExc_TypeError, "raise: exception class must be a subclass of BaseException"); goto raise_error; } #endif } __Pyx_ErrRestore(type, value, tb); return; raise_error: Py_XDECREF(value); Py_XDECREF(type); Py_XDECREF(tb); return; } #else /* Python 3+ */ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb) { if (tb == Py_None) { tb = 0; } else if (tb && !PyTraceBack_Check(tb)) { PyErr_SetString(PyExc_TypeError, "raise: arg 3 must be a traceback or None"); goto bad; } if (value == Py_None) value = 0; if (PyExceptionInstance_Check(type)) { if (value) { PyErr_SetString(PyExc_TypeError, "instance exception may not have a separate value"); goto bad; } value = type; type = (PyObject*) Py_TYPE(value); } else if (!PyExceptionClass_Check(type)) { PyErr_SetString(PyExc_TypeError, "raise: exception class must be a subclass of BaseException"); goto bad; } PyErr_SetObject(type, value); if (tb) { PyThreadState *tstate = PyThreadState_GET(); PyObject* tmp_tb = tstate->curexc_traceback; if (tb != tmp_tb) { Py_INCREF(tb); tstate->curexc_traceback = tb; Py_XDECREF(tmp_tb); } } bad: return; } #endif static CYTHON_INLINE unsigned char __Pyx_PyInt_AsUnsignedChar(PyObject* x) { const unsigned char neg_one = (unsigned char)-1, const_zero = 0; const int is_unsigned = neg_one > const_zero; if (sizeof(unsigned char) < sizeof(long)) { long val = __Pyx_PyInt_AsLong(x); if (unlikely(val != (long)(unsigned char)val)) { if (!unlikely(val == -1 && PyErr_Occurred())) { PyErr_SetString(PyExc_OverflowError, (is_unsigned && unlikely(val < 0)) ? "can't convert negative value to unsigned char" : "value too large to convert to unsigned char"); } return (unsigned char)-1; } return (unsigned char)val; } return (unsigned char)__Pyx_PyInt_AsUnsignedLong(x); } static CYTHON_INLINE unsigned short __Pyx_PyInt_AsUnsignedShort(PyObject* x) { const unsigned short neg_one = (unsigned short)-1, const_zero = 0; const int is_unsigned = neg_one > const_zero; if (sizeof(unsigned short) < sizeof(long)) { long val = __Pyx_PyInt_AsLong(x); if (unlikely(val != (long)(unsigned short)val)) { if (!unlikely(val == -1 && PyErr_Occurred())) { PyErr_SetString(PyExc_OverflowError, (is_unsigned && unlikely(val < 0)) ? "can't convert negative value to unsigned short" : "value too large to convert to unsigned short"); } return (unsigned short)-1; } return (unsigned short)val; } return (unsigned short)__Pyx_PyInt_AsUnsignedLong(x); } static CYTHON_INLINE unsigned int __Pyx_PyInt_AsUnsignedInt(PyObject* x) { const unsigned int neg_one = (unsigned int)-1, const_zero = 0; const int is_unsigned = neg_one > const_zero; if (sizeof(unsigned int) < sizeof(long)) { long val = __Pyx_PyInt_AsLong(x); if (unlikely(val != (long)(unsigned int)val)) { if (!unlikely(val == -1 && PyErr_Occurred())) { PyErr_SetString(PyExc_OverflowError, (is_unsigned && unlikely(val < 0)) ? "can't convert negative value to unsigned int" : "value too large to convert to unsigned int"); } return (unsigned int)-1; } return (unsigned int)val; } return (unsigned int)__Pyx_PyInt_AsUnsignedLong(x); } static CYTHON_INLINE char __Pyx_PyInt_AsChar(PyObject* x) { const char neg_one = (char)-1, const_zero = 0; const int is_unsigned = neg_one > const_zero; if (sizeof(char) < sizeof(long)) { long val = __Pyx_PyInt_AsLong(x); if (unlikely(val != (long)(char)val)) { if (!unlikely(val == -1 && PyErr_Occurred())) { PyErr_SetString(PyExc_OverflowError, (is_unsigned && unlikely(val < 0)) ? "can't convert negative value to char" : "value too large to convert to char"); } return (char)-1; } return (char)val; } return (char)__Pyx_PyInt_AsLong(x); } static CYTHON_INLINE short __Pyx_PyInt_AsShort(PyObject* x) { const short neg_one = (short)-1, const_zero = 0; const int is_unsigned = neg_one > const_zero; if (sizeof(short) < sizeof(long)) { long val = __Pyx_PyInt_AsLong(x); if (unlikely(val != (long)(short)val)) { if (!unlikely(val == -1 && PyErr_Occurred())) { PyErr_SetString(PyExc_OverflowError, (is_unsigned && unlikely(val < 0)) ? "can't convert negative value to short" : "value too large to convert to short"); } return (short)-1; } return (short)val; } return (short)__Pyx_PyInt_AsLong(x); } static CYTHON_INLINE int __Pyx_PyInt_AsInt(PyObject* x) { const int neg_one = (int)-1, const_zero = 0; const int is_unsigned = neg_one > const_zero; if (sizeof(int) < sizeof(long)) { long val = __Pyx_PyInt_AsLong(x); if (unlikely(val != (long)(int)val)) { if (!unlikely(val == -1 && PyErr_Occurred())) { PyErr_SetString(PyExc_OverflowError, (is_unsigned && unlikely(val < 0)) ? "can't convert negative value to int" : "value too large to convert to int"); } return (int)-1; } return (int)val; } return (int)__Pyx_PyInt_AsLong(x); } static CYTHON_INLINE signed char __Pyx_PyInt_AsSignedChar(PyObject* x) { const signed char neg_one = (signed char)-1, const_zero = 0; const int is_unsigned = neg_one > const_zero; if (sizeof(signed char) < sizeof(long)) { long val = __Pyx_PyInt_AsLong(x); if (unlikely(val != (long)(signed char)val)) { if (!unlikely(val == -1 && PyErr_Occurred())) { PyErr_SetString(PyExc_OverflowError, (is_unsigned && unlikely(val < 0)) ? "can't convert negative value to signed char" : "value too large to convert to signed char"); } return (signed char)-1; } return (signed char)val; } return (signed char)__Pyx_PyInt_AsSignedLong(x); } static CYTHON_INLINE signed short __Pyx_PyInt_AsSignedShort(PyObject* x) { const signed short neg_one = (signed short)-1, const_zero = 0; const int is_unsigned = neg_one > const_zero; if (sizeof(signed short) < sizeof(long)) { long val = __Pyx_PyInt_AsLong(x); if (unlikely(val != (long)(signed short)val)) { if (!unlikely(val == -1 && PyErr_Occurred())) { PyErr_SetString(PyExc_OverflowError, (is_unsigned && unlikely(val < 0)) ? "can't convert negative value to signed short" : "value too large to convert to signed short"); } return (signed short)-1; } return (signed short)val; } return (signed short)__Pyx_PyInt_AsSignedLong(x); } static CYTHON_INLINE signed int __Pyx_PyInt_AsSignedInt(PyObject* x) { const signed int neg_one = (signed int)-1, const_zero = 0; const int is_unsigned = neg_one > const_zero; if (sizeof(signed int) < sizeof(long)) { long val = __Pyx_PyInt_AsLong(x); if (unlikely(val != (long)(signed int)val)) { if (!unlikely(val == -1 && PyErr_Occurred())) { PyErr_SetString(PyExc_OverflowError, (is_unsigned && unlikely(val < 0)) ? "can't convert negative value to signed int" : "value too large to convert to signed int"); } return (signed int)-1; } return (signed int)val; } return (signed int)__Pyx_PyInt_AsSignedLong(x); } static CYTHON_INLINE unsigned long __Pyx_PyInt_AsUnsignedLong(PyObject* x) { const unsigned long neg_one = (unsigned long)-1, const_zero = 0; const int is_unsigned = neg_one > const_zero; #if PY_VERSION_HEX < 0x03000000 if (likely(PyInt_Check(x))) { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to unsigned long"); return (unsigned long)-1; } return (unsigned long)val; } else #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { if (unlikely(Py_SIZE(x) < 0)) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to unsigned long"); return (unsigned long)-1; } return PyLong_AsUnsignedLong(x); } else { return PyLong_AsLong(x); } } else { unsigned long val; PyObject *tmp = __Pyx_PyNumber_Int(x); if (!tmp) return (unsigned long)-1; val = __Pyx_PyInt_AsUnsignedLong(tmp); Py_DECREF(tmp); return val; } } static CYTHON_INLINE unsigned PY_LONG_LONG __Pyx_PyInt_AsUnsignedLongLong(PyObject* x) { const unsigned PY_LONG_LONG neg_one = (unsigned PY_LONG_LONG)-1, const_zero = 0; const int is_unsigned = neg_one > const_zero; #if PY_VERSION_HEX < 0x03000000 if (likely(PyInt_Check(x))) { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to unsigned PY_LONG_LONG"); return (unsigned PY_LONG_LONG)-1; } return (unsigned PY_LONG_LONG)val; } else #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { if (unlikely(Py_SIZE(x) < 0)) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to unsigned PY_LONG_LONG"); return (unsigned PY_LONG_LONG)-1; } return PyLong_AsUnsignedLongLong(x); } else { return PyLong_AsLongLong(x); } } else { unsigned PY_LONG_LONG val; PyObject *tmp = __Pyx_PyNumber_Int(x); if (!tmp) return (unsigned PY_LONG_LONG)-1; val = __Pyx_PyInt_AsUnsignedLongLong(tmp); Py_DECREF(tmp); return val; } } static CYTHON_INLINE long __Pyx_PyInt_AsLong(PyObject* x) { const long neg_one = (long)-1, const_zero = 0; const int is_unsigned = neg_one > const_zero; #if PY_VERSION_HEX < 0x03000000 if (likely(PyInt_Check(x))) { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to long"); return (long)-1; } return (long)val; } else #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { if (unlikely(Py_SIZE(x) < 0)) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to long"); return (long)-1; } return PyLong_AsUnsignedLong(x); } else { return PyLong_AsLong(x); } } else { long val; PyObject *tmp = __Pyx_PyNumber_Int(x); if (!tmp) return (long)-1; val = __Pyx_PyInt_AsLong(tmp); Py_DECREF(tmp); return val; } } static CYTHON_INLINE PY_LONG_LONG __Pyx_PyInt_AsLongLong(PyObject* x) { const PY_LONG_LONG neg_one = (PY_LONG_LONG)-1, const_zero = 0; const int is_unsigned = neg_one > const_zero; #if PY_VERSION_HEX < 0x03000000 if (likely(PyInt_Check(x))) { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to PY_LONG_LONG"); return (PY_LONG_LONG)-1; } return (PY_LONG_LONG)val; } else #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { if (unlikely(Py_SIZE(x) < 0)) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to PY_LONG_LONG"); return (PY_LONG_LONG)-1; } return PyLong_AsUnsignedLongLong(x); } else { return PyLong_AsLongLong(x); } } else { PY_LONG_LONG val; PyObject *tmp = __Pyx_PyNumber_Int(x); if (!tmp) return (PY_LONG_LONG)-1; val = __Pyx_PyInt_AsLongLong(tmp); Py_DECREF(tmp); return val; } } static CYTHON_INLINE signed long __Pyx_PyInt_AsSignedLong(PyObject* x) { const signed long neg_one = (signed long)-1, const_zero = 0; const int is_unsigned = neg_one > const_zero; #if PY_VERSION_HEX < 0x03000000 if (likely(PyInt_Check(x))) { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to signed long"); return (signed long)-1; } return (signed long)val; } else #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { if (unlikely(Py_SIZE(x) < 0)) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to signed long"); return (signed long)-1; } return PyLong_AsUnsignedLong(x); } else { return PyLong_AsLong(x); } } else { signed long val; PyObject *tmp = __Pyx_PyNumber_Int(x); if (!tmp) return (signed long)-1; val = __Pyx_PyInt_AsSignedLong(tmp); Py_DECREF(tmp); return val; } } static CYTHON_INLINE signed PY_LONG_LONG __Pyx_PyInt_AsSignedLongLong(PyObject* x) { const signed PY_LONG_LONG neg_one = (signed PY_LONG_LONG)-1, const_zero = 0; const int is_unsigned = neg_one > const_zero; #if PY_VERSION_HEX < 0x03000000 if (likely(PyInt_Check(x))) { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to signed PY_LONG_LONG"); return (signed PY_LONG_LONG)-1; } return (signed PY_LONG_LONG)val; } else #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { if (unlikely(Py_SIZE(x) < 0)) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to signed PY_LONG_LONG"); return (signed PY_LONG_LONG)-1; } return PyLong_AsUnsignedLongLong(x); } else { return PyLong_AsLongLong(x); } } else { signed PY_LONG_LONG val; PyObject *tmp = __Pyx_PyNumber_Int(x); if (!tmp) return (signed PY_LONG_LONG)-1; val = __Pyx_PyInt_AsSignedLongLong(tmp); Py_DECREF(tmp); return val; } } #ifndef __PYX_HAVE_RT_ImportType #define __PYX_HAVE_RT_ImportType static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, long size, int strict) { PyObject *py_module = 0; PyObject *result = 0; PyObject *py_name = 0; char warning[200]; py_module = __Pyx_ImportModule(module_name); if (!py_module) goto bad; #if PY_MAJOR_VERSION < 3 py_name = PyString_FromString(class_name); #else py_name = PyUnicode_FromString(class_name); #endif if (!py_name) goto bad; result = PyObject_GetAttr(py_module, py_name); Py_DECREF(py_name); py_name = 0; Py_DECREF(py_module); py_module = 0; if (!result) goto bad; if (!PyType_Check(result)) { PyErr_Format(PyExc_TypeError, "%s.%s is not a type object", module_name, class_name); goto bad; } if (!strict && ((PyTypeObject *)result)->tp_basicsize > size) { PyOS_snprintf(warning, sizeof(warning), "%s.%s size changed, may indicate binary incompatibility", module_name, class_name); PyErr_WarnEx(NULL, warning, 0); } else if (((PyTypeObject *)result)->tp_basicsize != size) { PyErr_Format(PyExc_ValueError, "%s.%s has the wrong size, try recompiling", module_name, class_name); goto bad; } return (PyTypeObject *)result; bad: Py_XDECREF(py_module); Py_XDECREF(result); return 0; } #endif #ifndef __PYX_HAVE_RT_ImportModule #define __PYX_HAVE_RT_ImportModule static PyObject *__Pyx_ImportModule(const char *name) { PyObject *py_name = 0; PyObject *py_module = 0; #if PY_MAJOR_VERSION < 3 py_name = PyString_FromString(name); #else py_name = PyUnicode_FromString(name); #endif if (!py_name) goto bad; py_module = PyImport_Import(py_name); Py_DECREF(py_name); return py_module; bad: Py_XDECREF(py_name); return 0; } #endif static int __Pyx_GetVtable(PyObject *dict, void *vtabptr) { PyObject *ob = PyMapping_GetItemString(dict, (char *)"__pyx_vtable__"); if (!ob) goto bad; #if PY_VERSION_HEX < 0x03010000 *(void **)vtabptr = PyCObject_AsVoidPtr(ob); #else *(void **)vtabptr = PyCapsule_GetPointer(ob, 0); #endif if (!*(void **)vtabptr) goto bad; Py_DECREF(ob); return 0; bad: Py_XDECREF(ob); return -1; } #ifndef __PYX_HAVE_RT_ImportFunction #define __PYX_HAVE_RT_ImportFunction static int __Pyx_ImportFunction(PyObject *module, const char *funcname, void (**f)(void), const char *sig) { PyObject *d = 0; PyObject *cobj = 0; union { void (*fp)(void); void *p; } tmp; #if PY_VERSION_HEX < 0x03010000 const char *desc, *s1, *s2; #endif d = PyObject_GetAttrString(module, (char *)"__pyx_capi__"); if (!d) goto bad; cobj = PyDict_GetItemString(d, funcname); if (!cobj) { PyErr_Format(PyExc_ImportError, "%s does not export expected C function %s", PyModule_GetName(module), funcname); goto bad; } #if PY_VERSION_HEX < 0x03010000 desc = (const char *)PyCObject_GetDesc(cobj); if (!desc) goto bad; s1 = desc; s2 = sig; while (*s1 != '\0' && *s1 == *s2) { s1++; s2++; } if (*s1 != *s2) { PyErr_Format(PyExc_TypeError, "C function %s.%s has wrong signature (expected %s, got %s)", PyModule_GetName(module), funcname, sig, desc); goto bad; } tmp.p = PyCObject_AsVoidPtr(cobj); #else if (!PyCapsule_IsValid(cobj, sig)) { PyErr_Format(PyExc_TypeError, "C function %s.%s has wrong signature (expected %s, got %s)", PyModule_GetName(module), funcname, sig, PyCapsule_GetName(cobj)); goto bad; } tmp.p = PyCapsule_GetPointer(cobj, sig); #endif *f = tmp.fp; if (!(*f)) goto bad; Py_DECREF(d); return 0; bad: Py_XDECREF(d); return -1; } #endif #include "compile.h" #include "frameobject.h" #include "traceback.h" static void __Pyx_AddTraceback(const char *funcname) { PyObject *py_srcfile = 0; PyObject *py_funcname = 0; PyObject *py_globals = 0; PyCodeObject *py_code = 0; PyFrameObject *py_frame = 0; #if PY_MAJOR_VERSION < 3 py_srcfile = PyString_FromString(__pyx_filename); #else py_srcfile = PyUnicode_FromString(__pyx_filename); #endif if (!py_srcfile) goto bad; if (__pyx_clineno) { #if PY_MAJOR_VERSION < 3 py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, __pyx_clineno); #else py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, __pyx_clineno); #endif } else { #if PY_MAJOR_VERSION < 3 py_funcname = PyString_FromString(funcname); #else py_funcname = PyUnicode_FromString(funcname); #endif } if (!py_funcname) goto bad; py_globals = PyModule_GetDict(__pyx_m); if (!py_globals) goto bad; py_code = PyCode_New( 0, /*int argcount,*/ #if PY_MAJOR_VERSION >= 3 0, /*int kwonlyargcount,*/ #endif 0, /*int nlocals,*/ 0, /*int stacksize,*/ 0, /*int flags,*/ __pyx_empty_bytes, /*PyObject *code,*/ __pyx_empty_tuple, /*PyObject *consts,*/ __pyx_empty_tuple, /*PyObject *names,*/ __pyx_empty_tuple, /*PyObject *varnames,*/ __pyx_empty_tuple, /*PyObject *freevars,*/ __pyx_empty_tuple, /*PyObject *cellvars,*/ py_srcfile, /*PyObject *filename,*/ py_funcname, /*PyObject *name,*/ __pyx_lineno, /*int firstlineno,*/ __pyx_empty_bytes /*PyObject *lnotab*/ ); if (!py_code) goto bad; py_frame = PyFrame_New( PyThreadState_GET(), /*PyThreadState *tstate,*/ py_code, /*PyCodeObject *code,*/ py_globals, /*PyObject *globals,*/ 0 /*PyObject *locals*/ ); if (!py_frame) goto bad; py_frame->f_lineno = __pyx_lineno; PyTraceBack_Here(py_frame); bad: Py_XDECREF(py_srcfile); Py_XDECREF(py_funcname); Py_XDECREF(py_code); Py_XDECREF(py_frame); } static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { while (t->p) { #if PY_MAJOR_VERSION < 3 if (t->is_unicode) { *t->p = PyUnicode_DecodeUTF8(t->s, t->n - 1, NULL); } else if (t->intern) { *t->p = PyString_InternFromString(t->s); } else { *t->p = PyString_FromStringAndSize(t->s, t->n - 1); } #else /* Python 3+ has unicode identifiers */ if (t->is_unicode | t->is_str) { if (t->intern) { *t->p = PyUnicode_InternFromString(t->s); } else if (t->encoding) { *t->p = PyUnicode_Decode(t->s, t->n - 1, t->encoding, NULL); } else { *t->p = PyUnicode_FromStringAndSize(t->s, t->n - 1); } } else { *t->p = PyBytes_FromStringAndSize(t->s, t->n - 1); } #endif if (!*t->p) return -1; ++t; } return 0; } /* Type Conversion Functions */ static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) { if (x == Py_True) return 1; else if ((x == Py_False) | (x == Py_None)) return 0; else return PyObject_IsTrue(x); } static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) { PyNumberMethods *m; const char *name = NULL; PyObject *res = NULL; #if PY_VERSION_HEX < 0x03000000 if (PyInt_Check(x) || PyLong_Check(x)) #else if (PyLong_Check(x)) #endif return Py_INCREF(x), x; m = Py_TYPE(x)->tp_as_number; #if PY_VERSION_HEX < 0x03000000 if (m && m->nb_int) { name = "int"; res = PyNumber_Int(x); } else if (m && m->nb_long) { name = "long"; res = PyNumber_Long(x); } #else if (m && m->nb_int) { name = "int"; res = PyNumber_Long(x); } #endif if (res) { #if PY_VERSION_HEX < 0x03000000 if (!PyInt_Check(res) && !PyLong_Check(res)) { #else if (!PyLong_Check(res)) { #endif PyErr_Format(PyExc_TypeError, "__%s__ returned non-%s (type %.200s)", name, name, Py_TYPE(res)->tp_name); Py_DECREF(res); return NULL; } } else if (!PyErr_Occurred()) { PyErr_SetString(PyExc_TypeError, "an integer is required"); } return res; } static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) { Py_ssize_t ival; PyObject* x = PyNumber_Index(b); if (!x) return -1; ival = PyInt_AsSsize_t(x); Py_DECREF(x); return ival; } static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) { #if PY_VERSION_HEX < 0x02050000 if (ival <= LONG_MAX) return PyInt_FromLong((long)ival); else { unsigned char *bytes = (unsigned char *) &ival; int one = 1; int little = (int)*(unsigned char*)&one; return _PyLong_FromByteArray(bytes, sizeof(size_t), little, 0); } #else return PyInt_FromSize_t(ival); #endif } static CYTHON_INLINE size_t __Pyx_PyInt_AsSize_t(PyObject* x) { unsigned PY_LONG_LONG val = __Pyx_PyInt_AsUnsignedLongLong(x); if (unlikely(val == (unsigned PY_LONG_LONG)-1 && PyErr_Occurred())) { return (size_t)-1; } else if (unlikely(val != (unsigned PY_LONG_LONG)(size_t)val)) { PyErr_SetString(PyExc_OverflowError, "value too large to convert to size_t"); return (size_t)-1; } return (size_t)val; } #endif /* Py_PYTHON_H */
40.420059
465
0.678986
[ "object", "shape" ]
fce8ea93d0469b84ff66c31618f0e25e67cd8408
5,162
h
C
Plugins/org.mitk.gui.qt.igt.app.hummelprotocolmeasurements/src/internal/QmitkIGTTrackingDataEvaluationView.h
zhaomengxiao/MITK
a09fd849a4328276806008bfa92487f83a9e2437
[ "BSD-3-Clause" ]
1
2022-03-03T12:03:32.000Z
2022-03-03T12:03:32.000Z
Plugins/org.mitk.gui.qt.igt.app.hummelprotocolmeasurements/src/internal/QmitkIGTTrackingDataEvaluationView.h
zhaomengxiao/MITK
a09fd849a4328276806008bfa92487f83a9e2437
[ "BSD-3-Clause" ]
1
2021-12-22T10:19:02.000Z
2021-12-22T10:19:02.000Z
Plugins/org.mitk.gui.qt.igt.app.hummelprotocolmeasurements/src/internal/QmitkIGTTrackingDataEvaluationView.h
zhaomengxiao/MITK_lancet
a09fd849a4328276806008bfa92487f83a9e2437
[ "BSD-3-Clause" ]
1
2020-11-27T09:41:18.000Z
2020-11-27T09:41:18.000Z
/*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef QmitkIGTTrackingDataEvaluationView_h #define QmitkIGTTrackingDataEvaluationView_h #include <berryISelectionListener.h> #include <QmitkFunctionality.h> #include <QmitkStdMultiWidget.h> #include "ui_QmitkIGTTrackingDataEvaluationViewControls.h" #include "mitkHummelProtocolEvaluation.h" #include <mitkNavigationDataEvaluationFilter.h> #include "mitkNavigationDataCSVSequentialPlayer.h" /*! \brief QmitkIGTTrackingDataEvaluationView \warning This application module is not yet documented. Use "svn blame/praise/annotate" and ask the author to provide basic documentation. \sa QmitkFunctionality \ingroup Functionalities */ class QmitkIGTTrackingDataEvaluationView : public QmitkFunctionality { // this is needed for all Qt objects that should have a Qt meta-object // (everything that derives from QObject and wants to have signal/slots) Q_OBJECT public: static const std::string VIEW_ID; QmitkIGTTrackingDataEvaluationView(); ~QmitkIGTTrackingDataEvaluationView() override; void CreateQtPartControl(QWidget *parent) override; virtual void MultiWidgetAvailable(QmitkAbstractMultiWidget &multiWidget) override; virtual void MultiWidgetNotAvailable() override; protected slots: void OnLoadFileList(); void OnAddToCurrentList(); void OnEvaluateData(); void OnEvaluateDataAll(); void OnGeneratePointSet(); void OnGeneratePointSetsOfSinglePositions(); void OnGenerateRotationLines(); void OnGenerateGroundTruthPointSet(); void OnConvertCSVtoXMLFile(); void OnCSVtoXMLLoadInputList(); void OnCSVtoXMLLoadOutputList(); void OnPerfomGridMatching(); void OnComputeRotation(); /** Reads in exactly three position files als reference. */ void OnOrientationCalculation_CalcRef(); /** Uses always three positions (1,2,3: first orientation; 4,5,6: second orientation; and so on) in every file to calcualte a orientation. */ void OnOrientationCalculation_CalcOrientandWriteToFile(); protected: Ui::QmitkIGTTrackingDataEvaluationViewControls* m_Controls; QmitkStdMultiWidget* m_MultiWidget; std::vector<std::string> m_FilenameVector; void MessageBox(std::string s); std::fstream m_CurrentWriteFile; void WriteHeader(); void WriteDataSet(mitk::NavigationDataEvaluationFilter::Pointer evaluationFilter, std::string dataSetName); //members for orientation calculation mitk::Point3D m_RefPoint1; mitk::Point3D m_RefPoint2; mitk::Point3D m_RefPoint3; double m_scalingfactor; //scaling factor for visualization, 1 by default //angle diffrences: seperated file std::fstream m_CurrentAngleDifferencesWriteFile; void CalculateDifferenceAngles(); void WriteDifferenceAnglesHeader(); void WriteDifferenceAnglesDataSet(std::string pos1, std::string pos2, int idx1, int idx2, double angle); void writeToFile(std::string filename, std::vector<mitk::HummelProtocolEvaluation::HummelProtocolDistanceError> values); //different help methods to read a csv logging file std::vector<mitk::NavigationData::Pointer> GetNavigationDatasFromFile(std::string filename); std::vector<std::string> GetFileContentLineByLine(std::string filename); mitk::NavigationData::Pointer GetNavigationDataOutOfOneLine(std::string line); //help method to sonstruct the NavigationDataCSVSequentialPlayer filled with all the options from the UI mitk::NavigationDataCSVSequentialPlayer::Pointer ConstructNewNavigationDataPlayer(); //CSV to XML members std::vector<std::string> m_CSVtoXMLInputFilenameVector; std::vector<std::string> m_CSVtoXMLOutputFilenameVector; //returns the number of converted lines int ConvertOneFile(std::string inputFilename, std::string outputFilename); /** @brief calculates the angle in the plane perpendicular to the rotation axis of the two quaterions. */ double GetAngleBetweenTwoQuaterions(mitk::Quaternion a, mitk::Quaternion b); /** @brief calculates the slerp average of a set of quaternions which is stored in the navigation data evaluation filter */ mitk::Quaternion GetSLERPAverage(mitk::NavigationDataEvaluationFilter::Pointer); /** @brief Stores the mean positions of all evaluated data */ mitk::PointSet::Pointer m_PointSetMeanPositions; /** @return returns the mean orientation of all given data */ std::vector<mitk::Quaternion> GetMeanOrientationsOfAllData(std::vector<mitk::NavigationDataEvaluationFilter::Pointer> allData, bool useSLERP = false); /** @return returns all data read from the data list as NavigationDataEvaluationFilters */ std::vector<mitk::NavigationDataEvaluationFilter::Pointer> GetAllDataFromUIList(); }; #endif // _QMITKIGTTRACKINGDATAEVALUATIONVIEW_H_INCLUDED
36.871429
154
0.751647
[ "object", "vector" ]
fceea362afa1cbbf00411592c546d5f249f721a0
3,382
h
C
libraries/statx/statx/distributions/gamma.h
LEON-MING/TheiaSfM_Leon
8ac187b80100ad7f52fe9af49fa4a0db6db226b9
[ "BSD-3-Clause" ]
3
2019-01-17T17:37:37.000Z
2021-03-26T09:21:38.000Z
libraries/statx/statx/distributions/gamma.h
LEON-MING/TheiaSfM_Leon
8ac187b80100ad7f52fe9af49fa4a0db6db226b9
[ "BSD-3-Clause" ]
null
null
null
libraries/statx/statx/distributions/gamma.h
LEON-MING/TheiaSfM_Leon
8ac187b80100ad7f52fe9af49fa4a0db6db226b9
[ "BSD-3-Clause" ]
3
2019-07-16T08:45:55.000Z
2020-02-11T05:32:16.000Z
// Copyright (C) 2014 Victor Fragoso <vfragoso@cs.ucsb.edu> // 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 the University of California, Santa Barbara 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 VICTOR FRAGOSO 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. // #ifndef STATX_DISTRIBUTIONS_GAMMA_H_ #define STATX_DISTRIBUTIONS_GAMMA_H_ #include <cmath> #include <vector> #include <limits> namespace statx { namespace distributions { /// Evaluates the lower incomplete gamma /// Parameters a & x >= 0 inline double lower_inc_gamma(const double a, const double x) { if (a <= 0.0 || x <= 0.0) return std::numeric_limits<double>::infinity(); double acc = 0.0; double term = 1.0 / a; int n = 1; while (term != 0) { acc += term; term *= x / (a + n++); } return pow(x, a)*exp(-x)*acc; } // Evaluates the gamma density at x with k and theta parameters. // Parameter constraints: // x > 0 // k > 0 // theta > 0 inline double gammapdf(const double x, const double k, const double theta) { if ( x <= 0 || k <= 0 || theta <= 0) return 0.0; double term1 = 1.0 / (tgamma(k) * pow(theta, k)); double term2 = exp(-x / theta); return term1 * pow(x, k - 1) * term2; } // Evaluates the gamma distribution function (CDF) at x with k and theta // parameters. // Parameter constraints: // x > 0 // k > 0 // theta > 0 inline double gammacdf(const double x, const double k, const double theta) { if (x <= 0.0 || k <= 0.0 || theta <= 0.0) return 0.0; double term1 = 1.0 / tgamma(k); double term2 = lower_inc_gamma(k, x / theta); return term1*term2; } // Computes the Maximum Likelihood estimate of the Gamma distribution // k: shape parameter // theta: scale parameter bool gammafit(const std::vector<double>& data, double* k, // shape double* theta /* scale*/); } // distributions } // statx #endif // STATX_DISTRIBUTIONS_GAMMA_H_
35.978723
80
0.670609
[ "shape", "vector" ]
fcf1aec84c5ae6c368c268027e661172408f782e
5,237
h
C
src/ledger/bin/cloud_sync/impl/page_download.h
yanyushr/fuchsia
98e70672a81a206d235503e398f37b7b65581f79
[ "BSD-3-Clause" ]
1
2019-10-09T10:50:57.000Z
2019-10-09T10:50:57.000Z
src/ledger/bin/cloud_sync/impl/page_download.h
bootingman/fuchsia2
04012f0aa1edd1d4108a2ac647a65e59730fc4c2
[ "BSD-3-Clause" ]
null
null
null
src/ledger/bin/cloud_sync/impl/page_download.h
bootingman/fuchsia2
04012f0aa1edd1d4108a2ac647a65e59730fc4c2
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2017 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef SRC_LEDGER_BIN_CLOUD_SYNC_IMPL_PAGE_DOWNLOAD_H_ #define SRC_LEDGER_BIN_CLOUD_SYNC_IMPL_PAGE_DOWNLOAD_H_ #include <fuchsia/ledger/cloud/cpp/fidl.h> #include <lib/backoff/backoff.h> #include <lib/callback/managed_container.h> #include <lib/callback/scoped_task_runner.h> #include <lib/fidl/cpp/binding.h> #include <lib/fit/function.h> #include "peridot/lib/commit_pack/commit_pack.h" #include "src/ledger/bin/cloud_sync/impl/batch_download.h" #include "src/ledger/bin/cloud_sync/public/sync_state_watcher.h" #include "src/ledger/bin/encryption/public/encryption_service.h" #include "src/ledger/bin/storage/public/page_sync_delegate.h" #include "src/lib/fxl/macros.h" #include "src/lib/fxl/memory/ref_ptr.h" namespace cloud_sync { // PageDownload handles all the download operations (commits and objects) for a // page. class PageDownload : public cloud_provider::PageCloudWatcher, public storage::PageSyncDelegate { public: // Delegate ensuring coordination between PageDownload and the class that owns // it. class Delegate { public: // Report that the download state changed. virtual void SetDownloadState(DownloadSyncState sync_state) = 0; }; PageDownload(callback::ScopedTaskRunner* task_runner, storage::PageStorage* storage, storage::PageSyncClient* sync_client, encryption::EncryptionService* encryption_service, cloud_provider::PageCloudPtr* page_cloud, Delegate* delegate, std::unique_ptr<backoff::Backoff> backoff); ~PageDownload() override; // Downloads the initial backlog of remote commits, and sets up the remote // watcher upon success. void StartDownload(); // Returns if PageDownload is idle. bool IsIdle(); private: // cloud_provider::PageCloudWatcher: void OnNewCommits(cloud_provider::CommitPack commits, cloud_provider::Token position_token, OnNewCommitsCallback callback) override; void OnNewObject(std::vector<uint8_t> id, fuchsia::mem::Buffer data, OnNewObjectCallback callback) override; void OnError(cloud_provider::Status status) override; // Called when the initial commit backlog is downloaded. void BacklogDownloaded(); // Starts watching for Cloud commit notifications. void SetRemoteWatcher(bool is_retry); // Downloads the given batch of commits. void DownloadBatch(std::vector<cloud_provider::CommitPackEntry> entries, std::unique_ptr<cloud_provider::Token> position_token, fit::closure on_done); // storage::PageSyncDelegate: void GetObject( storage::ObjectIdentifier object_identifier, fit::function<void(storage::Status, storage::ChangeSource, storage::IsObjectSynced, std::unique_ptr<storage::DataSource::DataChunk>)> callback) override; void DecryptObject( storage::ObjectIdentifier object_identifier, std::unique_ptr<storage::DataSource> content, fit::function<void(storage::Status, storage::ChangeSource, storage::IsObjectSynced, std::unique_ptr<storage::DataSource::DataChunk>)> callback); void HandleGetObjectError( storage::ObjectIdentifier object_identifier, bool is_permanent, const char error_name[], fit::function<void(storage::Status, storage::ChangeSource, storage::IsObjectSynced, std::unique_ptr<storage::DataSource::DataChunk>)> callback); void HandleDownloadCommitError(const char error_description[]); // Sets the state for commit download. void SetCommitState(DownloadSyncState new_state); void UpdateDownloadState(); void RetryWithBackoff(fit::closure callable); // Owned by whoever owns this class. callback::ScopedTaskRunner* const task_runner_; storage::PageStorage* const storage_; storage::PageSyncClient* sync_client_; encryption::EncryptionService* const encryption_service_; cloud_provider::PageCloudPtr* const page_cloud_; Delegate* const delegate_; std::unique_ptr<backoff::Backoff> backoff_; const std::string log_prefix_; // Work queue: // The current batch of remote commits being downloaded. std::unique_ptr<BatchDownload> batch_download_; // Pending remote commits to download. std::vector<cloud_provider::CommitPackEntry> commits_to_download_; std::unique_ptr<cloud_provider::Token> position_token_; // Container for in-progress datasource. callback::ManagedContainer managed_container_; // State: // Commit download state. DownloadSyncState commit_state_ = DOWNLOAD_NOT_STARTED; int current_get_object_calls_ = 0; // Merged state of commit and object download. DownloadSyncState merged_state_ = DOWNLOAD_NOT_STARTED; fidl::Binding<cloud_provider::PageCloudWatcher> watcher_binding_; FXL_DISALLOW_COPY_AND_ASSIGN(PageDownload); }; } // namespace cloud_sync #endif // SRC_LEDGER_BIN_CLOUD_SYNC_IMPL_PAGE_DOWNLOAD_H_
36.622378
80
0.72637
[ "object", "vector" ]
fcf6db24e987c8790d2d5761843ee890f3b3f737
4,481
h
C
Chapter 07/7d_ClearingBackground/include/VulkanRenderer.h
luopan007/Learning-Vulkan
bd0bbb92657456411c06485ed85fa1936efe76c5
[ "MIT" ]
143
2017-01-03T15:26:44.000Z
2022-03-28T01:00:52.000Z
Chapter 07/7d_ClearingBackground/include/VulkanRenderer.h
luopan007/Learning-Vulkan
bd0bbb92657456411c06485ed85fa1936efe76c5
[ "MIT" ]
4
2017-01-09T23:02:46.000Z
2020-10-14T07:20:51.000Z
Chapter 07/7d_ClearingBackground/include/VulkanRenderer.h
luopan007/Learning-Vulkan
bd0bbb92657456411c06485ed85fa1936efe76c5
[ "MIT" ]
47
2017-01-30T11:56:35.000Z
2022-02-20T23:35:12.000Z
/* * Learning Vulkan - ISBN: 9781786469809 * * Author: Parminder Singh, parminder.vulkan@gmail.com * Linkedin: https://www.linkedin.com/in/parmindersingh18 * * 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. */ #pragma once #include "Headers.h" #include "VulkanSwapChain.h" #include "VulkanDrawable.h" // Number of samples needs to be the same at image creation // Used at renderpass creation (in attachment) and pipeline creation #define NUM_SAMPLES VK_SAMPLE_COUNT_1_BIT // The Vulkan Renderer is custom class, it is not a Vulkan specific class. // It works as a presentation manager. // It manages the presentation windows and drawing surfaces. class VulkanRenderer { public: VulkanRenderer(VulkanApplication* app, VulkanDevice* deviceObject); ~VulkanRenderer(); public: //Simple life cycle void initialize(); void prepare(); bool render(); // Create an empty window void createPresentationWindow(const int& windowWidth = 500, const int& windowHeight = 500); void setImageLayout(VkImage image, VkImageAspectFlags aspectMask, VkImageLayout oldImageLayout, VkImageLayout newImageLayout, VkAccessFlagBits srcAccessMask, const VkCommandBuffer& cmdBuf); //! Windows procedure method for handling events. static LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam); // Destroy the presentation window void destroyPresentationWindow(); // Getter functions for member variable specific to classes. inline VulkanApplication* getApplication() { return application; } inline VulkanDevice* getDevice() { return deviceObj; } inline VulkanSwapChain* getSwapChain() { return swapChainObj; } inline std::vector<VulkanDrawable*>* getDrawingItems() { return &drawableList; } inline VkCommandPool* getCommandPool() { return &cmdPool; } void createCommandPool(); // Create command pool void buildSwapChainAndDepthImage(); // Create swapchain color image and depth image void createDepthImage(); // Create depth image void createVertexBuffer(); void createRenderPass(bool includeDepth, bool clear = true); // Render Pass creation void createFrameBuffer(bool includeDepth); void destroyCommandBuffer(); void destroyCommandPool(); void destroyDepthBuffer(); void destroyDrawableVertexBuffer(); void destroyRenderpass(); // Destroy the render pass object when no more required void destroyFramebuffers(); public: #ifdef _WIN32 #define APP_NAME_STR_LEN 80 HINSTANCE connection; // hInstance - Windows Instance char name[APP_NAME_STR_LEN]; // name - App name appearing on the window HWND window; // hWnd - the window handle #else xcb_connection_t* connection; xcb_screen_t* screen; xcb_window_t window; xcb_intern_atom_reply_t* reply; #endif struct{ VkFormat format; VkImage image; VkDeviceMemory mem; VkImageView view; }Depth; VkCommandBuffer cmdDepthImage; // Command buffer for depth image layout VkCommandPool cmdPool; // Command pool VkCommandBuffer cmdVertexBuffer; // Command buffer for vertex buffer - Triangle geometry VkRenderPass renderPass; // Render pass created object std::vector<VkFramebuffer> framebuffers; // Number of frame buffer corresponding to each swap chain int width, height; private: VulkanApplication* application; // The device object associated with this Presentation layer. VulkanDevice* deviceObj; VulkanSwapChain* swapChainObj; std::vector<VulkanDrawable*> drawableList; };
37.974576
190
0.766347
[ "geometry", "render", "object", "vector" ]
fcfadaa7b0a49027a271225c9efbe9cd08093cb4
1,323
h
C
ceppengine/src/ceppengine/assets/assetloader.h
Winded/ceppengine
52a9c1723dc45aba4d85d50e4c919ec8016c8d94
[ "MIT" ]
2
2017-11-13T11:29:03.000Z
2017-11-13T12:09:12.000Z
ceppengine/src/ceppengine/assets/assetloader.h
Winded/ceppengine
52a9c1723dc45aba4d85d50e4c919ec8016c8d94
[ "MIT" ]
null
null
null
ceppengine/src/ceppengine/assets/assetloader.h
Winded/ceppengine
52a9c1723dc45aba4d85d50e4c919ec8016c8d94
[ "MIT" ]
null
null
null
#pragma once #include <string> #include "importers/assetimporter.h" #include "../util/ref.h" #include "asset.h" namespace cepp { class AssetLoader { public: struct LoadedAsset { LoadedAsset(Asset *lAsset, const std::string &lPath) : asset(lAsset), path(lPath) {} Ref<Asset> asset; std::string path; }; AssetLoader(); /** * Get asset path relative to executable path */ std::string loadPath() const; /** * Set asset path relative to executable path */ void setLoadPath(const std::string &path); /** * Load engine default asset importers */ void loadDefaultImporters(); Asset *loadAsset(const std::string &path, const std::string &type); /** * Remove assets from asset list, which unloads them if no other references are attached to them. */ void unloadAssets(); private: std::string filePathToAssetPath(const std::string &filePath) const; std::string assetPathToFilePath(const std::string &assetPath) const; std::string mLoadPath; std::vector<Ref<AssetImporter>> mImporters; std::vector<LoadedAsset> mLoadedAssets; }; } // namespace cepp
23.625
105
0.584278
[ "vector" ]
1e00003d31242a14bef74286c66a08ae355b1053
3,728
h
C
mafDLL/mafDllMacros.h
FusionBox2/MAF2
b576955f4f6b954467021f12baedfebcaf79a382
[ "Apache-2.0" ]
1
2018-01-23T09:13:40.000Z
2018-01-23T09:13:40.000Z
mafDLL/mafDllMacros.h
gradicosmo/MAF2
86ddf1f52a2de4479c09fd3f43dc321ff412af42
[ "Apache-2.0" ]
null
null
null
mafDLL/mafDllMacros.h
gradicosmo/MAF2
86ddf1f52a2de4479c09fd3f43dc321ff412af42
[ "Apache-2.0" ]
3
2020-09-24T16:04:53.000Z
2020-09-24T16:50:30.000Z
#ifndef DllExportH #define DllExportH #if defined(_MSC_VER) #ifdef _DEBUG # define class_it_base class #else # define class_it_base struct #endif #define EXPORT_STL_VECTOR(declspec_, T_) \ template class declspec_ std::allocator<T_ >; \ template class declspec_ std::vector<T_ >; #define EXPORT_STL_VECTOR_CONST_ITERATOR(declspec_, T_) \ class_it_base declspec_ std::_Iterator_base; \ template class declspec_ std::_Vector_const_iterator<T_,\ std::allocator<T_ > >; #define EXPORT_STL_DEQUE(declspec_, T_) \ template class declspec_ std::allocator<T_ >; \ template class declspec_ std::allocator<T_* >; \ template class declspec_ std::deque<T_ >; #define EXPORT_STL_LIST(declspec_, T_) \ template class declspec_ std::allocator<T_ >; \ template class declspec_ std::allocator<std::_List_nod<T_,\ std::allocator<T_ > >::_Node>; \ template class declspec_ std::allocator<std::_List_nod<T_,\ std::allocator<T_ > >::_Node*>; \ template class declspec_ std::list<T_ >; // #define EXPORT_STL_SET(declspec_, T_) \ // template class declspec_ std::allocator<T_ >; \ // template struct declspec_ std::less<T_ >; \ // template class declspec_ std::allocator<std::_Tree_nod< \ // std::_Tset_traits<T_, std::less<T_ >, std::allocator<T_ >, false> \ // >::_Node>; \ // template class declspec_ std::allocator<std::_Tree_ptr< \ // std::_Tset_traits<T_, std::less<T_ >, std::allocator<T_ >, false> \ // >::_Node*>; \ // template class declspec_ std::set<T_ >; #define EXPORT_STL_MULTISET(declspec_, T_) \ template class declspec_ std::allocator<T_ >; \ template struct declspec_ std::less<T_ >; \ template class declspec_ std::allocator<std::_Tree_nod< \ std::_Tset_traits<T_, std::less<T_ >, std::allocator<T_ >, true> \ >::_Node>; \ template class declspec_ std::allocator<std::_Tree_ptr< \ std::_Tset_traits<T_, std::less<T_ >, std::allocator<T_ >, true> \ >::_Node*>; \ template class declspec_ std::multiset<T_ >; #define EXPORT_STL_MAP(declspec_, K_, V_) \ template struct declspec_ std::less<K_ >; \ template class declspec_ std::allocator<std::_Tree_nod< \ std::_Tmap_traits<K_, V_, std::less<K_ >, \ std::allocator<std::pair<const K_, V_ > >, false> >::_Node>; \ template class declspec_ std::allocator<std::_Tree_nod< \ std::_Tmap_traits<K_, V_, std::less<K_ >, \ std::allocator<std::pair<const K_, V_ > >, false> >::_Node*>; \ template class declspec_ std::allocator<std::pair<const K_, V_ > >; \ template class declspec_ std::map<K_, V_ >; #define EXPORT_STL_MAP_CONST_ITERATOR(declspec_, K_, V_) \ class_it_base declspec_ std::_Iterator_base; \ template class declspec_ std::_Tree<std::_Tmap_traits<K_, V_, \ std::less<K_>, std::allocator<std::pair<const K_, V_ > >, false> \ >::const_iterator; #define EXPORT_STL_MULTIMAP(declspec_, K_, V_) \ template struct declspec_ std::less<K_ >; \ template class declspec_ std::allocator<std::_Tree_nod< \ std::_Tmap_traits<K_, V_, std::less<K_ >, \ std::allocator<std::pair<const K_, V_ > >, true> >::_Node>; \ template class declspec_ std::allocator<std::_Tree_nod< \ std::_Tmap_traits<K_, V_, std::less<K_ >, \ std::allocator<std::pair<const K_, V_ > >, true> >::_Node*>; \ template class declspec_ std::allocator<std::pair<const K_, V_ > >; \ template class declspec_ std::multimap<K_, V_ >; #else #define EXPORT_STL_VECTOR(declspec_, T_) #define EXPORT_STL_VECTOR_CONST_ITERATOR(declspec_, T_) #define EXPORT_STL_DEQUE(declspec_, T_) #define EXPORT_STL_LIST(declspec_, T_) #define EXPORT_STL_SET(declspec_, T_) #define EXPORT_STL_MULTISET(declspec_, T_) #define EXPORT_STL_MAP(declspec_, K_, V_) #define EXPORT_STL_MAP_CONST_ITERATOR(declspec_, K_, V_) #define EXPORT_STL_MULTIMAP(declspec_, K_, V_) #endif #endif
37.656566
71
0.719421
[ "vector" ]
1e052b4c969b59453b8eb0f53a674b1138353615
3,284
c
C
chapter_6/array_structs.c
nickaigi/c-programming-language
a88d09befb63beeb7212e0c804ce495103f60867
[ "Unlicense" ]
null
null
null
chapter_6/array_structs.c
nickaigi/c-programming-language
a88d09befb63beeb7212e0c804ce495103f60867
[ "Unlicense" ]
null
null
null
chapter_6/array_structs.c
nickaigi/c-programming-language
a88d09befb63beeb7212e0c804ce495103f60867
[ "Unlicense" ]
null
null
null
/* consider writing a program to count the occurrences of each C keyword */ #include<stdio.h> #include<ctype.h> #include<string.h> #define MAXWORD 100 struct key { char *word; int count; } keytab[] = { "auto", 0, "break", 0, "case", 0, "char", 0, "const", 0, "continue", 0, "unsigned", 0, "void", 0, "volatile", 0, "while", 0, }; //#define NKEYS (sizeof keytab / sizeof(struct key)) #define NKEYS (sizeof keytab / sizeof(keytab[0])) /* the 2nd version has an advantage that it does not need to be changed if the * type changes */ int getword(char *, int); int binsearch(char *, struct key *, int); /* count C keywords */ int main(){ int n; char word[MAXWORD]; while (getword(word, MAXWORD) != EOF) if (isalpha(word[0])) if ((n = binsearch(word, keytab, NKEYS)) >= 0) keytab[n].count++; for (n = 0; n < NKEYS; n++) if (keytab[n].count > 0) printf("%4d %s\n", keytab[n].count, keytab[n].word); return 0; } /* NKEYS is the number of keywords in 'keytab' * we could count this by hand, but its easier and safer to do it by machine (lol) * - The size of the array is the size of one entry times the number of entries * so the size of entries is just * * size of keytab / size of struct key * * - C provides a compile-time unary operator called 'sizeof' that can be used * to compute the size of any object. * The expressions * * sizeof object * * and * * sizeof (type name) * * yield an integer equal to the size of the specified object or type in bytes */ /* binsearch: find word in tab[0]...tab[n-1] */ int binsearch(char *word, struct key tab[], int n){ int cond; int low, high, mid; low = 0; high = n - 1; while (low <= high){ mid = (low + high)/2; if ((cond = strcmp(word, tab[mid].word)) < 0) high = mid - 1; else if (cond > 0) low = mid + 1; else return mid; } return -1; } /* - since the structure keytab contains set of names, it is easiest to make it * an external variable and initialize it once and for all when it is defined. * - The initializers are listed in pairs corresponding to the structure * members. It would be more precise to enclose the initializers for each * "row" or structure in braces like * * {"auto", 0 }, * {"break", 0 }, * {"case", 0 }, * * but inner braces are not necessary when the initializers are simple * variables or character strings and when all are present */ /* getword: get next word or character from input */ int getword(char *word, int lim) { int c, getch(void); void ungetch(int); char *w = word; while (isspace(c = getch())) ; if (c != EOF) *w++ = c; if (isalpha(c)) { *w = '\0'; return c; } for (; --lim > 0; w++) if (!isalnum(*w = getch())){ ungetch(*w); break; } *w = '\0'; return word[0]; } /* isspace: used to skip whitespaces * isalpha: to identify letters * isalnum: to identify letters and digits * * all are from the standard header <ctype.h> */
24.507463
82
0.5676
[ "object" ]
1e0cafe0f636f0bcef146021f4d6d19d482078bd
41,304
h
C
Code/Core/Data/IO/vnsLookUpTableFileReader.h
spacebel/MAJA
3e5d20bc9c744c610e608cfcf1f4c5c738d4de9e
[ "Apache-2.0" ]
57
2020-09-30T08:51:22.000Z
2021-12-19T20:28:30.000Z
Code/Core/Data/IO/vnsLookUpTableFileReader.h
spacebel/MAJA
3e5d20bc9c744c610e608cfcf1f4c5c738d4de9e
[ "Apache-2.0" ]
34
2020-09-29T21:27:22.000Z
2022-02-03T09:56:45.000Z
Code/Core/Data/IO/vnsLookUpTableFileReader.h
spacebel/MAJA
3e5d20bc9c744c610e608cfcf1f4c5c738d4de9e
[ "Apache-2.0" ]
14
2020-10-11T13:17:59.000Z
2022-03-09T15:58:19.000Z
/* * Copyright (C) 2020 Centre National d'Etudes Spatiales (CNES) * * 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. * */ /************************************************************************************************************ * * * ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo * * o * * o * * o * * o * * o ooooooo ooooooo o o oo * * o o o o o o o o o o * * o o o o o o o o o o * * o o o o o o o o o o * * o o o oooo o o o o o o * * o o o o o o o o o * * o o o o o o o o o o * * oo oooooooo o o o oooooo o oooo * * o * * o * * o o * * o o oooo o o oooo * * o o o o o o * * o o ooo o o ooo * * o o o o o * * ooooo oooo o ooooo oooo * * o * * * ************************************************************************************************************ * * * Author: CS Systemes d'Information (France) * * * ************************************************************************************************************ * HISTORIQUE * * * * VERSION : 5-1-0 : FA : LAIG-FA-MAC-145739-CS : 27 juin 2016 : Audit code - Supp de la macro ITK_EXPORT * * VERSION : 5-1-0 : FA : LAIG-FA-MAC-144674-CS : 2 mai 2016 : Correction warning, qualite, etc * * VERSION : 4-0-0 : FA : LAIG-FA-MAC-372-CNES : 18 avril 2014 : Decoupage des methodes trop complexes. * * VERSION : 4-0-0 : FA : LAIG-FA-MAC-117040-CS : 31 mars 2014 : Modifications mineures * * VERSION : 1-0-0 : <TypeFT> : <NumFT> : 12 mai 2010 : Creation * * * FIN-HISTORIQUE * * * * $Id$ * * ************************************************************************************************************/ #ifndef __vnsLookUpTableFileReader_h #define __vnsLookUpTableFileReader_h #include "vnsLookUpTable.h" #include "vnsVectorLookUpTable.h" #include "itkProcessObject.h" #include "vnsUtilities.h" #include "vnsSystem.h" namespace vns { /** \class LookUpTableFileReader * \brief * * LookUpTableFileReader is used to load a LookUpTable file. * The output is an otbImage or a n otbVectorImage with precision and dimension * is given as class template. * * \ingroup L2 * * \sa LookUpTable * \sa VectorLookUpTable */ template<class TLookUpTableType = LookUpTable<double> > class LookUpTableFileReader : public itk::ProcessObject { public: /** Standard class typedefs. */ typedef LookUpTableFileReader<TLookUpTableType> Self; typedef itk::ProcessObject Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; typedef TLookUpTableType LookUpTableType; typedef typename LookUpTableType::PixelType LookUpTablePixelType; typedef typename LookUpTableType::InternalPixelType LookUpTableInternalPixelType; typedef typename LookUpTableType::ParameterValuesType ParameterValuesType; typedef typename LookUpTableType::ParametersValuesType ParametersValuesType; typedef typename LookUpTableType::IndexType IndexType; typedef typename LookUpTableType::IndexValueType IndexValueType; typedef Utilities::ListOfListOfFloats ListOfListOfFloats; typedef itk::VariableLengthVector<LookUpTableInternalPixelType> VectorPixelType; /** Method for creation through the object factory. */ itkNewMacro(Self) /** Run-time type information (and related methods). */ itkTypeMacro(LookUpTableFileReader,itk::ProcessObject) /** * Get the output LookUpTable * \return The extracted LookUpTablea. */ virtual LookUpTableType * GetLUT(void) { return static_cast<LookUpTableType *>(m_LUT); } /** Check FileName : is the nth filename is available */ bool IsLookUpTableFile(int num); /** Add parameters values to the LUT */ void AddParameterValues(const ParameterValuesType &NewParamValues) { // Add parameters to the LUT (readind hdr) m_LUT->AddParameterValues(NewParamValues); } /** LUT bands filename Add/Get */ void AddBandFilename(std::string path) { m_BandFileName.push_back(path); // Increase the number of bands m_LUT->SetNumberOfComponentsPerPixel(m_BandFileName.size()); } std::string GetBandFileName() { return m_BandFileName.at(0); } std::string GetBandFileName(unsigned int num) { return m_BandFileName.at(num); } /* Read and fill the LUT */ void GenerateLUT(void); protected: LookUpTableFileReader(); virtual ~LookUpTableFileReader() { } void PrintSelf(std::ostream& os, itk::Indent indent) const; /** Generate Requested Data */ virtual void GenerateData(void) { } void SetPixelSize(VectorPixelType & pPix, unsigned int pSize) { pPix.SetSize(pSize); } void SetPixelSize(LookUpTableInternalPixelType &, unsigned int) { } void SetPixelValue(VectorPixelType & pPix, float var, unsigned int lNumBand) { pPix[lNumBand] = static_cast<LookUpTableInternalPixelType>( var); } void SetPixelValue(LookUpTableInternalPixelType & pPix, float var, unsigned int) { pPix = static_cast<LookUpTableInternalPixelType>(var); } private: LookUpTableFileReader(const LookUpTableFileReader&); //purposely not implemented void operator=(const LookUpTableFileReader&); //purposely not implemented // ---------------------------------------------------------- // Generates LUT with 2D template<class TValue> void GenerateXDLUT(VectorLookUpTable<TValue, 2> * pLUT, const ListOfListOfFloats & pBuffersBands, const unsigned int pNbBands) { typedef VectorLookUpTable<TValue, 2> LocalLookUpTableType; vnsLogDebugMacro("Generate LUT "<<LocalLookUpTableType::ImageDimension <<"D ...") // ---------------------------------------------------------- // Used only for VectorLUTs // The pixel size is equal to the number of spectral band typename LocalLookUpTableType::PixelType lPix = static_cast<typename LocalLookUpTableType::PixelType>(0); this->SetPixelSize(lPix, pNbBands); // ---------------------------------------------------------- // Index of the pixel typename LocalLookUpTableType::IndexType index; // ---------------------------------------------------------- // Fill to 0 index.Fill((typename LocalLookUpTableType::IndexValueType) 0); // ---------------------------------------------------------- // Initialization std::streamoff cpt(0); const ParametersValuesType & LUT_Indexes(pLUT->GetParametersValues()); const unsigned int LUT_Indexes0ParameterValuesSize(LUT_Indexes.at(0).ParameterValues.size()); const unsigned int LUT_Indexes1ParameterValuesSize(LUT_Indexes.at(1).ParameterValues.size()); const std::size_t l_NbValues = pBuffersBands.front().size(); const std::size_t l_IndexSize = LUT_Indexes0ParameterValuesSize * LUT_Indexes1ParameterValuesSize; if (l_NbValues != l_IndexSize) { vnsExceptionDataMacro( "The size of the buffered value is "<<l_NbValues << " and is incoherent with the size of the indexes parameters values "<< l_IndexSize) } // loop over the first parameter (for example TOA reflectance) for (unsigned int a = 0; a < LUT_Indexes0ParameterValuesSize; a++) { index[0] = a; // loop over the second parameter (for example altitude reflectance) for (unsigned int b = 0; b < LUT_Indexes1ParameterValuesSize; b++) { index[1] = b; // Number of components per pixel for (unsigned int lNumBand = 0; lNumBand < pNbBands; lNumBand++) { this->SetPixelValue(lPix, pBuffersBands[lNumBand][cpt], lNumBand); } cpt++; pLUT->SetValue(index, lPix); } } } // ---------------------------------------------------------- // Generates LUT with 2D template<class TValue> void GenerateXDLUT(LookUpTable<TValue, 2> * pLUT, const ListOfListOfFloats & pBuffersBands, const unsigned int pNbBands) { typedef LookUpTable<TValue, 2> LocalLookUpTableType; vnsLogDebugMacro("Generate LUT "<<LocalLookUpTableType::ImageDimension <<"D ...") // ---------------------------------------------------------- // Used only for VectorLUTs // The pixel size is equal to the number of spectral band typename LocalLookUpTableType::PixelType lPix = static_cast<typename LocalLookUpTableType::PixelType>(0); this->SetPixelSize(lPix, pNbBands); // ---------------------------------------------------------- // Index of the pixel typename LocalLookUpTableType::IndexType index; // ---------------------------------------------------------- // Fill to 0 index.Fill((typename LocalLookUpTableType::IndexValueType) 0); // ---------------------------------------------------------- // Initialization std::streamoff cpt(0); const ParametersValuesType & LUT_Indexes(pLUT->GetParametersValues()); const unsigned int LUT_Indexes0ParameterValuesSize(LUT_Indexes.at(0).ParameterValues.size()); const unsigned int LUT_Indexes1ParameterValuesSize(LUT_Indexes.at(1).ParameterValues.size()); const std::size_t l_NbValues = pBuffersBands.front().size(); const std::size_t l_IndexSize = LUT_Indexes0ParameterValuesSize * LUT_Indexes1ParameterValuesSize; if (l_NbValues != l_IndexSize) { vnsExceptionDataMacro( "The size of the buffered value is "<<l_NbValues << " and is incoherent with the size of the indexes parameters values "<< l_IndexSize) } // loop over the first parameter (for example TOA reflectance) for (unsigned int a = 0; a < LUT_Indexes0ParameterValuesSize; a++) { index[0] = a; // loop over the second parameter (for example altitude reflectance) for (unsigned int b = 0; b < LUT_Indexes1ParameterValuesSize; b++) { index[1] = b; // Number of components per pixel for (unsigned int lNumBand = 0; lNumBand < pNbBands; lNumBand++) { this->SetPixelValue(lPix, pBuffersBands[lNumBand][cpt], lNumBand); } cpt++; pLUT->SetValue(index, lPix); } } } // ---------------------------------------------------------- // Generates LUT with 3D template<class TValue> void GenerateXDLUT(VectorLookUpTable<TValue, 3> * pLUT, const ListOfListOfFloats & pBuffersBands, const unsigned int pNbBands) { typedef VectorLookUpTable<TValue, 3> LocalLookUpTableType; vnsLogDebugMacro("Generate LUT "<<LocalLookUpTableType::ImageDimension <<"D ...") // ---------------------------------------------------------- // Used only for VectorLUTs // The pixel size is equal to the number of spectral band typename LocalLookUpTableType::PixelType lPix = static_cast<typename LocalLookUpTableType::PixelType>(0); this->SetPixelSize(lPix, pNbBands); // ---------------------------------------------------------- // Index of the pixel typename LocalLookUpTableType::IndexType index; // ---------------------------------------------------------- // Fill to 0 index.Fill((typename LocalLookUpTableType::IndexValueType) 0); // ---------------------------------------------------------- // Initialization std::streamoff cpt(0); const ParametersValuesType & LUT_Indexes(pLUT->GetParametersValues()); const unsigned int LUT_Indexes0ParameterValuesSize(LUT_Indexes.at(0).ParameterValues.size()); const unsigned int LUT_Indexes1ParameterValuesSize(LUT_Indexes.at(1).ParameterValues.size()); const unsigned int LUT_Indexes2ParameterValuesSize(LUT_Indexes.at(2).ParameterValues.size()); const std::size_t l_NbValues = pBuffersBands.front().size(); const std::size_t l_IndexSize = LUT_Indexes0ParameterValuesSize * LUT_Indexes1ParameterValuesSize * LUT_Indexes2ParameterValuesSize; if (l_NbValues != l_IndexSize) { vnsExceptionDataMacro( "The size of the buffered value is "<<l_NbValues << " and is incoherent with the size of the indexes parameters values "<< l_IndexSize) } // loop over the first parameter (for example TOA reflectance) for (unsigned int a = 0; a < LUT_Indexes0ParameterValuesSize; a++) { index[0] = a; // loop over the second parameter (for example AOT) for (unsigned int b = 0; b < LUT_Indexes1ParameterValuesSize; b++) { index[1] = b; // loop over the third parameter (for example altitude) for (unsigned int c = 0; c < LUT_Indexes2ParameterValuesSize; c++) { index[2] = c; // Number of components per pixel for (unsigned int lNumBand = 0; lNumBand < pNbBands; lNumBand++) { this->SetPixelValue(lPix, pBuffersBands[lNumBand][cpt], lNumBand); } pLUT->SetValue(index, lPix); cpt++; } } } } // ---------------------------------------------------------- // Generates LUT with 3D template<class TValue> void GenerateXDLUT(LookUpTable<TValue, 3> * pLUT, const ListOfListOfFloats & pBuffersBands, const unsigned int pNbBands) { typedef LookUpTable<TValue, 3> LocalLookUpTableType; vnsLogDebugMacro("Generate LUT "<<LocalLookUpTableType::ImageDimension <<"D ...") // ---------------------------------------------------------- // Used only for VectorLUTs // The pixel size is equal to the number of spectral band typename LocalLookUpTableType::PixelType lPix = static_cast<typename LocalLookUpTableType::PixelType>(0); this->SetPixelSize(lPix, pNbBands); // ---------------------------------------------------------- // Index of the pixel typename LocalLookUpTableType::IndexType index; // ---------------------------------------------------------- // Fill to 0 index.Fill((typename LocalLookUpTableType::IndexValueType) 0); // ---------------------------------------------------------- // Initialization std::streamoff cpt(0); const ParametersValuesType & LUT_Indexes(pLUT->GetParametersValues()); const unsigned int LUT_Indexes0ParameterValuesSize(LUT_Indexes.at(0).ParameterValues.size()); const unsigned int LUT_Indexes1ParameterValuesSize(LUT_Indexes.at(1).ParameterValues.size()); const unsigned int LUT_Indexes2ParameterValuesSize(LUT_Indexes.at(2).ParameterValues.size()); const std::size_t l_NbValues = pBuffersBands.front().size(); const std::size_t l_IndexSize = LUT_Indexes0ParameterValuesSize * LUT_Indexes1ParameterValuesSize * LUT_Indexes2ParameterValuesSize; if (l_NbValues != l_IndexSize) { vnsExceptionDataMacro( "The size of the buffered value is "<<l_NbValues << " and is incoherent with the size of the indexes parameters values "<< l_IndexSize) } // loop over the first parameter (for example TOA reflectance) for (unsigned int a = 0; a < LUT_Indexes0ParameterValuesSize; a++) { index[0] = a; // loop over the second parameter (for example AOT) for (unsigned int b = 0; b < LUT_Indexes1ParameterValuesSize; b++) { index[1] = b; // loop over the third parameter (for example altitude) for (unsigned int c = 0; c < LUT_Indexes2ParameterValuesSize; c++) { index[2] = c; // Number of components per pixel for (unsigned int lNumBand = 0; lNumBand < pNbBands; lNumBand++) { this->SetPixelValue(lPix, pBuffersBands[lNumBand][cpt], lNumBand); } pLUT->SetValue(index, lPix); cpt++; } } } } // ---------------------------------------------------------- // Generates LUT with 4D template<class TValue> void GenerateXDLUT(VectorLookUpTable<TValue, 4> * pLUT, const ListOfListOfFloats & pBuffersBands, const unsigned int pNbBands) { typedef VectorLookUpTable<TValue, 4> LocalLookUpTableType; vnsLogDebugMacro("Generate LUT "<<LocalLookUpTableType::ImageDimension <<"D ...") // ---------------------------------------------------------- // Used only for VectorLUTs // The pixel size is equal to the number of spectral band typename LocalLookUpTableType::PixelType lPix = static_cast<typename LocalLookUpTableType::PixelType>(0); this->SetPixelSize(lPix, pNbBands); // ---------------------------------------------------------- // Index of the pixel typename LocalLookUpTableType::IndexType index; // ---------------------------------------------------------- // Fill to 0 index.Fill((typename LocalLookUpTableType::IndexValueType) 0); // ---------------------------------------------------------- // Initialization std::streamoff cpt(0); const ParametersValuesType & LUT_Indexes(pLUT->GetParametersValues()); const unsigned int LUT_Indexes0ParameterValuesSize(LUT_Indexes.at(0).ParameterValues.size()); const unsigned int LUT_Indexes1ParameterValuesSize(LUT_Indexes.at(1).ParameterValues.size()); const unsigned int LUT_Indexes2ParameterValuesSize(LUT_Indexes.at(2).ParameterValues.size()); const unsigned int LUT_Indexes3ParameterValuesSize(LUT_Indexes.at(3).ParameterValues.size()); const std::size_t l_NbValues = pBuffersBands.front().size(); const std::size_t l_IndexSize = LUT_Indexes0ParameterValuesSize * LUT_Indexes1ParameterValuesSize * LUT_Indexes2ParameterValuesSize * LUT_Indexes3ParameterValuesSize; if (l_NbValues != l_IndexSize) { vnsExceptionDataMacro( "The size of the buffered value is "<<l_NbValues << " and is incoherent with the size of the indexes parameters values "<< l_IndexSize) } for (unsigned int a = 0; a < LUT_Indexes0ParameterValuesSize; a++) { index[0] = a; for (unsigned int b = 0; b < LUT_Indexes1ParameterValuesSize; b++) { index[1] = b; for (unsigned int c = 0; c < LUT_Indexes2ParameterValuesSize; c++) { index[2] = c; for (unsigned int d = 0; d < LUT_Indexes3ParameterValuesSize; d++) { index[3] = d; // Number of components per pixel for (unsigned int lNumBand = 0; lNumBand < pNbBands; lNumBand++) { this->SetPixelValue(lPix, pBuffersBands[lNumBand][cpt], lNumBand); } pLUT->SetValue(index, lPix); cpt++; } } } } } // ---------------------------------------------------------- // Generates LUT with 4D template<class TValue> void GenerateXDLUT(LookUpTable<TValue, 4> * pLUT, const ListOfListOfFloats & pBuffersBands, const unsigned int pNbBands) { typedef LookUpTable<TValue, 4> LocalLookUpTableType; vnsLogDebugMacro("Generate LUT "<<LocalLookUpTableType::ImageDimension <<"D ...") // ---------------------------------------------------------- // Used only for VectorLUTs // The pixel size is equal to the number of spectral band typename LocalLookUpTableType::PixelType lPix = static_cast<typename LocalLookUpTableType::PixelType>(0); this->SetPixelSize(lPix, pNbBands); // ---------------------------------------------------------- // Index of the pixel typename LocalLookUpTableType::IndexType index; // ---------------------------------------------------------- // Fill to 0 index.Fill((typename LocalLookUpTableType::IndexValueType) 0); // ---------------------------------------------------------- // Initialization std::streamoff cpt(0); const ParametersValuesType & LUT_Indexes(pLUT->GetParametersValues()); const unsigned int LUT_Indexes0ParameterValuesSize(LUT_Indexes.at(0).ParameterValues.size()); const unsigned int LUT_Indexes1ParameterValuesSize(LUT_Indexes.at(1).ParameterValues.size()); const unsigned int LUT_Indexes2ParameterValuesSize(LUT_Indexes.at(2).ParameterValues.size()); const unsigned int LUT_Indexes3ParameterValuesSize(LUT_Indexes.at(3).ParameterValues.size()); const std::size_t l_NbValues = pBuffersBands.front().size(); const std::size_t l_IndexSize = LUT_Indexes0ParameterValuesSize * LUT_Indexes1ParameterValuesSize * LUT_Indexes2ParameterValuesSize * LUT_Indexes3ParameterValuesSize; if (l_NbValues != l_IndexSize) { vnsExceptionDataMacro( "The size of the buffered value is "<<l_NbValues << " and is incoherent with the size of the indexes parameters values "<< l_IndexSize) } for (unsigned int a = 0; a < LUT_Indexes0ParameterValuesSize; a++) { index[0] = a; for (unsigned int b = 0; b < LUT_Indexes1ParameterValuesSize; b++) { index[1] = b; for (unsigned int c = 0; c < LUT_Indexes2ParameterValuesSize; c++) { index[2] = c; for (unsigned int d = 0; d < LUT_Indexes3ParameterValuesSize; d++) { index[3] = d; // Number of components per pixel for (unsigned int lNumBand = 0; lNumBand < pNbBands; lNumBand++) { this->SetPixelValue(lPix, pBuffersBands[lNumBand][cpt], lNumBand); } pLUT->SetValue(index, lPix); cpt++; } } } } } // ---------------------------------------------------------- // Generates LUT with 6D template<class TValue> void GenerateXDLUT(VectorLookUpTable<TValue, 6> * pLUT, const ListOfListOfFloats & pBuffersBands, const unsigned int pNbBands) { typedef VectorLookUpTable<TValue, 6> LocalLookUpTableType; vnsLogDebugMacro("Generate LUT "<<LocalLookUpTableType::ImageDimension <<"D ...") // ---------------------------------------------------------- // Used only for VectorLUTs // The pixel size is equal to the number of spectral band typename LocalLookUpTableType::PixelType lPix = static_cast<typename LocalLookUpTableType::PixelType>(0); this->SetPixelSize(lPix, pNbBands); // ---------------------------------------------------------- // Index of the pixel typename LocalLookUpTableType::IndexType index; // ---------------------------------------------------------- // Fill to 0 index.Fill((typename LocalLookUpTableType::IndexValueType) 0); // ---------------------------------------------------------- // Initialization std::streamoff cpt(0); // ---------------------------------------------------------- //Init parameters const ParametersValuesType & LUT_Indexes(pLUT->GetParametersValues()); const unsigned int LUT_Indexes0ParameterValuesSize(LUT_Indexes.at(0).ParameterValues.size()); const unsigned int LUT_Indexes1ParameterValuesSize(LUT_Indexes.at(1).ParameterValues.size()); const unsigned int LUT_Indexes2ParameterValuesSize(LUT_Indexes.at(2).ParameterValues.size()); const unsigned int LUT_Indexes3ParameterValuesSize(LUT_Indexes.at(3).ParameterValues.size()); const unsigned int LUT_Indexes4ParameterValuesSize(LUT_Indexes.at(4).ParameterValues.size()); const unsigned int LUT_Indexes5ParameterValuesSize(LUT_Indexes.at(5).ParameterValues.size()); const std::size_t l_NbValues = pBuffersBands.front().size(); const std::size_t l_IndexSize = LUT_Indexes0ParameterValuesSize * LUT_Indexes1ParameterValuesSize * LUT_Indexes2ParameterValuesSize * LUT_Indexes3ParameterValuesSize * LUT_Indexes4ParameterValuesSize * LUT_Indexes5ParameterValuesSize; if (l_NbValues != l_IndexSize) { vnsExceptionDataMacro( "The size of the buffered value is "<<l_NbValues << " and is incoherent with the size of the indexes parameters values "<< l_IndexSize) } for (unsigned int a = 0; a < LUT_Indexes0ParameterValuesSize; a++) { index[0] = a; for (unsigned int b = 0; b < LUT_Indexes1ParameterValuesSize; b++) { index[1] = b; for (unsigned int c = 0; c < LUT_Indexes2ParameterValuesSize; c++) { index[2] = c; for (unsigned int d = 0; d < LUT_Indexes3ParameterValuesSize; d++) { index[3] = d; for (unsigned int e = 0; e < LUT_Indexes4ParameterValuesSize; e++) { index[4] = e; for (unsigned int f = 0; f < LUT_Indexes5ParameterValuesSize; f++) { index[5] = f; // Number of components per pixel for (unsigned int lNumBand = 0; lNumBand < pNbBands; lNumBand++) { this->SetPixelValue(lPix, pBuffersBands[lNumBand][cpt], lNumBand); } pLUT->SetValue(index, lPix); cpt++; } } } } } } } // ---------------------------------------------------------- // Generates LUT with 6D template<class TValue> void GenerateXDLUT(LookUpTable<TValue, 6> * pLUT, const ListOfListOfFloats & pBuffersBands, const unsigned int pNbBands) { typedef LookUpTable<TValue, 6> LocalLookUpTableType; vnsLogDebugMacro("Generate LUT "<<LocalLookUpTableType::ImageDimension <<"D ...") // ---------------------------------------------------------- // Used only for VectorLUTs // The pixel size is equal to the number of spectral band typename LocalLookUpTableType::PixelType lPix = static_cast<typename LocalLookUpTableType::PixelType>(0); this->SetPixelSize(lPix, pNbBands); // ---------------------------------------------------------- // Index of the pixel typename LocalLookUpTableType::IndexType index; // ---------------------------------------------------------- // Fill to 0 index.Fill((typename LocalLookUpTableType::IndexValueType) 0); // ---------------------------------------------------------- // Initialization std::streamoff cpt(0); // ---------------------------------------------------------- //Init parameters const ParametersValuesType & LUT_Indexes(pLUT->GetParametersValues()); const unsigned int LUT_Indexes0ParameterValuesSize(LUT_Indexes.at(0).ParameterValues.size()); const unsigned int LUT_Indexes1ParameterValuesSize(LUT_Indexes.at(1).ParameterValues.size()); const unsigned int LUT_Indexes2ParameterValuesSize(LUT_Indexes.at(2).ParameterValues.size()); const unsigned int LUT_Indexes3ParameterValuesSize(LUT_Indexes.at(3).ParameterValues.size()); const unsigned int LUT_Indexes4ParameterValuesSize(LUT_Indexes.at(4).ParameterValues.size()); const unsigned int LUT_Indexes5ParameterValuesSize(LUT_Indexes.at(5).ParameterValues.size()); const std::size_t l_NbValues = pBuffersBands.front().size(); const std::size_t l_IndexSize = LUT_Indexes0ParameterValuesSize * LUT_Indexes1ParameterValuesSize * LUT_Indexes2ParameterValuesSize * LUT_Indexes3ParameterValuesSize * LUT_Indexes4ParameterValuesSize * LUT_Indexes5ParameterValuesSize; if (l_NbValues != l_IndexSize) { vnsExceptionDataMacro( "The size of the buffered value is "<<l_NbValues << " and is incoherent with the size of the indexes parameters values "<< l_IndexSize) } for (unsigned int a = 0; a < LUT_Indexes0ParameterValuesSize; a++) { index[0] = a; for (unsigned int b = 0; b < LUT_Indexes1ParameterValuesSize; b++) { index[1] = b; for (unsigned int c = 0; c < LUT_Indexes2ParameterValuesSize; c++) { index[2] = c; for (unsigned int d = 0; d < LUT_Indexes3ParameterValuesSize; d++) { index[3] = d; for (unsigned int e = 0; e < LUT_Indexes4ParameterValuesSize; e++) { index[4] = e; for (unsigned int f = 0; f < LUT_Indexes5ParameterValuesSize; f++) { index[5] = f; // Number of components per pixel for (unsigned int lNumBand = 0; lNumBand < pNbBands; lNumBand++) { this->SetPixelValue(lPix, pBuffersBands[lNumBand][cpt], lNumBand); } pLUT->SetValue(index, lPix); cpt++; } } } } } } } /** LUT Bands filename */ Utilities::ListOfStrings m_BandFileName; /** LUT Object */ typename LookUpTableType::Pointer m_LUT; }; } // end namespace vns #ifndef VNS_MANUAL_INSTANTIATION #include "vnsLookUpTableFileReader.txx" #endif #endif
55.740891
167
0.422066
[ "object", "3d" ]
1e111899b1d78bcfdb2546ce356c5366fbd4336e
5,130
h
C
MatlabCode/savefile_ert_rtw/savefile.h
pection/Lanedetection_matlab_Amas2016-2017
598c9f97e2abe5cfc775f195e10fb9a0c36eb059
[ "MIT" ]
null
null
null
MatlabCode/savefile_ert_rtw/savefile.h
pection/Lanedetection_matlab_Amas2016-2017
598c9f97e2abe5cfc775f195e10fb9a0c36eb059
[ "MIT" ]
null
null
null
MatlabCode/savefile_ert_rtw/savefile.h
pection/Lanedetection_matlab_Amas2016-2017
598c9f97e2abe5cfc775f195e10fb9a0c36eb059
[ "MIT" ]
1
2020-11-24T18:19:51.000Z
2020-11-24T18:19:51.000Z
/* * savefile.h * * Trial License - for use to evaluate programs for possible purchase as * an end-user only. * * Code generation for model "savefile". * * Model version : 1.3 * Simulink Coder version : 8.12 (R2017a) 16-Feb-2017 * C source code generated on : Sat Mar 31 14:27:06 2018 * * Target selection: ert.tlc * Note: GRT includes extra infrastructure and instrumentation for prototyping * Embedded hardware selection: ARM Compatible->ARM Cortex * Code generation objectives: Unspecified * Validation result: Not run */ #ifndef RTW_HEADER_savefile_h_ #define RTW_HEADER_savefile_h_ #include <string.h> #include <float.h> #include <stddef.h> #ifndef savefile_COMMON_INCLUDES_ # define savefile_COMMON_INCLUDES_ #include "rtwtypes.h" #include "rtw_extmode.h" #include "sysran_types.h" #include "rtw_continuous.h" #include "rtw_solver.h" #include "dt_info.h" #include "ext_work.h" #include "MW_SDL_video_display.h" #include "v4l2_capture.h" #endif /* savefile_COMMON_INCLUDES_ */ #include "savefile_types.h" /* Shared type includes */ #include "multiword_types.h" /* Macros for accessing real-time model data structure */ #ifndef rtmGetFinalTime # define rtmGetFinalTime(rtm) ((rtm)->Timing.tFinal) #endif #ifndef rtmGetRTWExtModeInfo # define rtmGetRTWExtModeInfo(rtm) ((rtm)->extModeInfo) #endif #ifndef rtmGetErrorStatus # define rtmGetErrorStatus(rtm) ((rtm)->errorStatus) #endif #ifndef rtmSetErrorStatus # define rtmSetErrorStatus(rtm, val) ((rtm)->errorStatus = (val)) #endif #ifndef rtmGetStopRequested # define rtmGetStopRequested(rtm) ((rtm)->Timing.stopRequestedFlag) #endif #ifndef rtmSetStopRequested # define rtmSetStopRequested(rtm, val) ((rtm)->Timing.stopRequestedFlag = (val)) #endif #ifndef rtmGetStopRequestedPtr # define rtmGetStopRequestedPtr(rtm) (&((rtm)->Timing.stopRequestedFlag)) #endif #ifndef rtmGetT # define rtmGetT(rtm) ((rtm)->Timing.taskTime0) #endif #ifndef rtmGetTFinal # define rtmGetTFinal(rtm) ((rtm)->Timing.tFinal) #endif /* Block signals (auto storage) */ typedef struct { uint8_T V4L2VideoCapture_o1[307200]; /* '<Root>/V4L2 Video Capture' */ uint8_T V4L2VideoCapture_o2[307200]; /* '<Root>/V4L2 Video Capture' */ uint8_T V4L2VideoCapture_o3[307200]; /* '<Root>/V4L2 Video Capture' */ uint8_T u0[307200]; uint8_T u1[307200]; uint8_T u2[307200]; } B_savefile_T; /* Block states (auto storage) for system '<Root>' */ typedef struct { codertarget_linux_blocks_SDLV_T obj; /* '<S1>/MATLAB System' */ void *MATLABSystem_PWORK; /* '<S1>/MATLAB System' */ boolean_T objisempty; /* '<S1>/MATLAB System' */ } DW_savefile_T; /* Constant parameters (auto storage) */ typedef struct { /* Expression: devName * Referenced by: '<Root>/V4L2 Video Capture' */ uint8_T V4L2VideoCapture_p1[12]; } ConstP_savefile_T; /* Real-time Model Data Structure */ struct tag_RTM_savefile_T { const char_T *errorStatus; RTWExtModeInfo *extModeInfo; /* * Sizes: * The following substructure contains sizes information * for many of the model attributes such as inputs, outputs, * dwork, sample times, etc. */ struct { uint32_T checksums[4]; } Sizes; /* * SpecialInfo: * The following substructure contains special information * related to other components that are dependent on RTW. */ struct { const void *mappingInfo; } SpecialInfo; /* * Timing: * The following substructure contains information regarding * the timing information for the model. */ struct { time_T taskTime0; uint32_T clockTick0; uint32_T clockTickH0; time_T stepSize0; time_T tFinal; boolean_T stopRequestedFlag; } Timing; }; /* Block signals (auto storage) */ extern B_savefile_T savefile_B; /* Block states (auto storage) */ extern DW_savefile_T savefile_DW; /* Constant parameters (auto storage) */ extern const ConstP_savefile_T savefile_ConstP; /* Model entry point functions */ extern void savefile_initialize(void); extern void savefile_step(void); extern void savefile_terminate(void); /* Real-time Model object */ extern RT_MODEL_savefile_T *const savefile_M; /*- * The generated code includes comments that allow you to trace directly * back to the appropriate location in the model. The basic format * is <system>/block_name, where system is the system number (uniquely * assigned by Simulink) and block_name is the name of the block. * * Use the MATLAB hilite_system command to trace the generated code back * to the model. For example, * * hilite_system('<S3>') - opens system 3 * hilite_system('<S3>/Kp') - opens and selects block Kp which resides in S3 * * Here is the system hierarchy for this model * * '<Root>' : 'savefile' * '<S1>' : 'savefile/SDL Video Display' */ #endif /* RTW_HEADER_savefile_h_ */
28.659218
81
0.682261
[ "object", "model" ]
1e126297f89a830c90d052929f36fd5b40754a72
4,076
h
C
chrome_frame/dll_redirector.h
Gitman1989/chromium
2b1cceae1075ef012fb225deec8b4c8bbe4bc897
[ "BSD-3-Clause" ]
2
2017-09-02T19:08:28.000Z
2021-11-15T15:15:14.000Z
chrome_frame/dll_redirector.h
Gitman1989/chromium
2b1cceae1075ef012fb225deec8b4c8bbe4bc897
[ "BSD-3-Clause" ]
null
null
null
chrome_frame/dll_redirector.h
Gitman1989/chromium
2b1cceae1075ef012fb225deec8b4c8bbe4bc897
[ "BSD-3-Clause" ]
1
2020-04-13T05:45:10.000Z
2020-04-13T05:45:10.000Z
// Copyright (c) 2010 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. #ifndef CHROME_FRAME_MODULE_UTILS_H_ #define CHROME_FRAME_MODULE_UTILS_H_ #include <ObjBase.h> #include <windows.h> #include "base/basictypes.h" #include "base/scoped_ptr.h" #include "base/shared_memory.h" #include "base/singleton.h" // Forward namespace ATL { class CSecurityAttributes; } class Version; // A singleton class that provides a facility to register the version of the // current module as the only version that should be loaded system-wide. If // this module is not the first instance loaded in the system, then the version // that loaded first will be delegated to. This makes a few assumptions: // 1) That different versions of the module this code is in reside in // neighbouring versioned directories, e.g. // C:\foo\bar\1.2.3.4\my_module.dll // C:\foo\bar\1.2.3.5\my_module.dll // 2) That the instance of this class will outlive the module that may be // delegated to. That is to say, that this class only guarantees that the // module is loaded as long as this instance is active. // 3) The module this is compiled into is built with version info. class DllRedirector { public: // Returns the singleton instance. static DllRedirector* GetInstance(); virtual ~DllRedirector(); // Attempts to register this Chrome Frame version as the first loaded version // on the system. If this succeeds, return true. If it fails, it returns // false meaning that there is another version already loaded somewhere and // the caller should delegate to that version instead. bool DllRedirector::RegisterAsFirstCFModule(); // Unregisters the well known window class if we registered it earlier. // This is intended to be called from DllMain under PROCESS_DETACH. void DllRedirector::UnregisterAsFirstCFModule(); // Helper function to return the DllGetClassObject function pointer from // the given module. On success, the return value is non-null and module // will have had its reference count incremented. LPFNGETCLASSOBJECT GetDllGetClassObjectPtr(); protected: DllRedirector(); friend struct DefaultSingletonTraits<DllRedirector>; // Constructor used for tests. explicit DllRedirector(const char* shared_memory_name); // Returns an HMODULE to the version of the module that should be loaded. virtual HMODULE GetFirstModule(); // Returns the version of the current module or NULL if none can be found. // The caller must free the Version. virtual Version* GetCurrentModuleVersion(); // Attempt to load the specified version dll. Finds it by walking up one // directory from our current module's location, then appending the newly // found version number. The Version class in base will have ensured that we // actually have a valid version and not e.g. ..\..\..\..\MyEvilFolder\. virtual HMODULE LoadVersionedModule(Version* version); // Builds the necessary SECURITY_ATTRIBUTES to allow low integrity access // to an object. Returns true on success, false otherwise. virtual bool BuildSecurityAttributesForLock( ATL::CSecurityAttributes* sec_attr); // Attempts to change the permissions on the given file mapping to read only. // Returns true on success, false otherwise. virtual bool SetFileMappingToReadOnly(base::SharedMemoryHandle mapping); // Shared memory segment that contains the version beacon. scoped_ptr<base::SharedMemory> shared_memory_; // The current version of the DLL to be loaded. scoped_ptr<Version> dll_version_; // The handle to the first version of this module that was loaded. This // may refer to the current module, or another version of the same module // that we go and load. HMODULE first_module_handle_; // Used for tests to override the name of the shared memory segment. std::string shared_memory_name_; friend class ModuleUtilsTest; DISALLOW_COPY_AND_ASSIGN(DllRedirector); }; #endif // CHROME_FRAME_MODULE_UTILS_H_
38.819048
79
0.757115
[ "object" ]
1e162214d6400769669ae2688da620ae780bcbc6
2,284
h
C
chromium/components/data_reduction_proxy/content/browser/content_data_reduction_proxy_debug_ui_service.h
wedataintelligence/vivaldi-source
22a46f2c969f6a0b7ca239a05575d1ea2738768c
[ "BSD-3-Clause" ]
null
null
null
chromium/components/data_reduction_proxy/content/browser/content_data_reduction_proxy_debug_ui_service.h
wedataintelligence/vivaldi-source
22a46f2c969f6a0b7ca239a05575d1ea2738768c
[ "BSD-3-Clause" ]
null
null
null
chromium/components/data_reduction_proxy/content/browser/content_data_reduction_proxy_debug_ui_service.h
wedataintelligence/vivaldi-source
22a46f2c969f6a0b7ca239a05575d1ea2738768c
[ "BSD-3-Clause" ]
2
2020-04-04T13:34:56.000Z
2020-11-04T07:17:52.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. #ifndef COMPONENTS_DATA_REDUCTION_PROXY_CONTENT_DATA_REDUCTION_PROXY_DEBUG_UI_SERVICE_H_ #define COMPONENTS_DATA_REDUCTION_PROXY_CONTENT_DATA_REDUCTION_PROXY_DEBUG_UI_SERVICE_H_ #include "base/macros.h" #include "base/memory/ref_counted.h" #include "components/data_reduction_proxy/core/browser/data_reduction_proxy_debug_ui_service.h" #include "components/data_reduction_proxy/core/browser/data_reduction_proxy_network_delegate.h" namespace base { class SingleThreadTaskRunner; } namespace net { class ProxyConfig; } namespace data_reduction_proxy { class DataReductionProxyDebugUIManager; // Creates a DataReductionProxyDebugUIManager which handles showing // interstitials. Also holds a ProxyConfigGetter which the // DataReductionProxyDebugResourceThrottle uses to decide when to display the // interstitials. class ContentDataReductionProxyDebugUIService : public DataReductionProxyDebugUIService { public: // Constructs a ContentDataReductionProxyDebugUIService object. |getter| is // used to get the Data Reduction Proxy config. |ui_task_runner| and // |io_task_runner| are used to create a DataReductionDebugProxyUIService. ContentDataReductionProxyDebugUIService( const DataReductionProxyNetworkDelegate::ProxyConfigGetter& getter, const scoped_refptr<base::SingleThreadTaskRunner>& ui_task_runner, const scoped_refptr<base::SingleThreadTaskRunner>& io_task_runner, const std::string& app_locale); ~ContentDataReductionProxyDebugUIService() override; const net::ProxyConfig& data_reduction_proxy_config() const override; const scoped_refptr<DataReductionProxyDebugUIManager>& ui_manager() const override; private: // The UI manager handles showing interstitials. Accessed on both UI and IO // thread. scoped_refptr<DataReductionProxyDebugUIManager> ui_manager_; DataReductionProxyNetworkDelegate::ProxyConfigGetter proxy_config_getter_; DISALLOW_COPY_AND_ASSIGN(ContentDataReductionProxyDebugUIService); }; } // namespace data_reduction_proxy #endif // COMPONENTS_DATA_REDUCTION_PROXY_CONTENT_DATA_REDUCTION_PROXY_DEBUG_UI_SERVICE_H_
38.066667
95
0.831436
[ "object" ]
1e1a51510e83b43b73d822b6fb644eca34eb37cc
23,704
c
C
lib/linux-5.18-rc3-smdk/drivers/firmware/arm_sdei.c
OpenMPDK/SMDK
8f19d32d999731242cb1ab116a4cb445d9993b15
[ "BSD-3-Clause" ]
44
2022-03-16T08:32:31.000Z
2022-03-31T16:02:35.000Z
releases/hanggai/src/linux-5.18/drivers/firmware/arm_sdei.c
marmolak/gray486linux
6403fc9d12cf6e8c6f42213ae287bc1e19b83e60
[ "BSD-2-Clause" ]
1
2022-03-29T02:30:28.000Z
2022-03-30T03:40:46.000Z
releases/hanggai/src/linux-5.18/drivers/firmware/arm_sdei.c
marmolak/gray486linux
6403fc9d12cf6e8c6f42213ae287bc1e19b83e60
[ "BSD-2-Clause" ]
18
2022-03-19T04:41:04.000Z
2022-03-31T03:32:12.000Z
// SPDX-License-Identifier: GPL-2.0 // Copyright (C) 2017 Arm Ltd. #define pr_fmt(fmt) "sdei: " fmt #include <acpi/ghes.h> #include <linux/acpi.h> #include <linux/arm_sdei.h> #include <linux/arm-smccc.h> #include <linux/atomic.h> #include <linux/bitops.h> #include <linux/compiler.h> #include <linux/cpuhotplug.h> #include <linux/cpu.h> #include <linux/cpu_pm.h> #include <linux/errno.h> #include <linux/hardirq.h> #include <linux/kernel.h> #include <linux/kprobes.h> #include <linux/kvm_host.h> #include <linux/list.h> #include <linux/mutex.h> #include <linux/notifier.h> #include <linux/of.h> #include <linux/of_platform.h> #include <linux/percpu.h> #include <linux/platform_device.h> #include <linux/pm.h> #include <linux/ptrace.h> #include <linux/preempt.h> #include <linux/reboot.h> #include <linux/slab.h> #include <linux/smp.h> #include <linux/spinlock.h> /* * The call to use to reach the firmware. */ static asmlinkage void (*sdei_firmware_call)(unsigned long function_id, unsigned long arg0, unsigned long arg1, unsigned long arg2, unsigned long arg3, unsigned long arg4, struct arm_smccc_res *res); /* entry point from firmware to arch asm code */ static unsigned long sdei_entry_point; struct sdei_event { /* These three are protected by the sdei_list_lock */ struct list_head list; bool reregister; bool reenable; u32 event_num; u8 type; u8 priority; /* This pointer is handed to firmware as the event argument. */ union { /* Shared events */ struct sdei_registered_event *registered; /* CPU private events */ struct sdei_registered_event __percpu *private_registered; }; }; /* Take the mutex for any API call or modification. Take the mutex first. */ static DEFINE_MUTEX(sdei_events_lock); /* and then hold this when modifying the list */ static DEFINE_SPINLOCK(sdei_list_lock); static LIST_HEAD(sdei_list); /* Private events are registered/enabled via IPI passing one of these */ struct sdei_crosscall_args { struct sdei_event *event; atomic_t errors; int first_error; }; #define CROSSCALL_INIT(arg, event) \ do { \ arg.event = event; \ arg.first_error = 0; \ atomic_set(&arg.errors, 0); \ } while (0) static inline int sdei_do_local_call(smp_call_func_t fn, struct sdei_event *event) { struct sdei_crosscall_args arg; CROSSCALL_INIT(arg, event); fn(&arg); return arg.first_error; } static inline int sdei_do_cross_call(smp_call_func_t fn, struct sdei_event *event) { struct sdei_crosscall_args arg; CROSSCALL_INIT(arg, event); on_each_cpu(fn, &arg, true); return arg.first_error; } static inline void sdei_cross_call_return(struct sdei_crosscall_args *arg, int err) { if (err && (atomic_inc_return(&arg->errors) == 1)) arg->first_error = err; } static int sdei_to_linux_errno(unsigned long sdei_err) { switch (sdei_err) { case SDEI_NOT_SUPPORTED: return -EOPNOTSUPP; case SDEI_INVALID_PARAMETERS: return -EINVAL; case SDEI_DENIED: return -EPERM; case SDEI_PENDING: return -EINPROGRESS; case SDEI_OUT_OF_RESOURCE: return -ENOMEM; } return 0; } static int invoke_sdei_fn(unsigned long function_id, unsigned long arg0, unsigned long arg1, unsigned long arg2, unsigned long arg3, unsigned long arg4, u64 *result) { int err; struct arm_smccc_res res; if (sdei_firmware_call) { sdei_firmware_call(function_id, arg0, arg1, arg2, arg3, arg4, &res); err = sdei_to_linux_errno(res.a0); } else { /* * !sdei_firmware_call means we failed to probe or called * sdei_mark_interface_broken(). -EIO is not an error returned * by sdei_to_linux_errno() and is used to suppress messages * from this driver. */ err = -EIO; res.a0 = SDEI_NOT_SUPPORTED; } if (result) *result = res.a0; return err; } NOKPROBE_SYMBOL(invoke_sdei_fn); static struct sdei_event *sdei_event_find(u32 event_num) { struct sdei_event *e, *found = NULL; lockdep_assert_held(&sdei_events_lock); spin_lock(&sdei_list_lock); list_for_each_entry(e, &sdei_list, list) { if (e->event_num == event_num) { found = e; break; } } spin_unlock(&sdei_list_lock); return found; } int sdei_api_event_context(u32 query, u64 *result) { return invoke_sdei_fn(SDEI_1_0_FN_SDEI_EVENT_CONTEXT, query, 0, 0, 0, 0, result); } NOKPROBE_SYMBOL(sdei_api_event_context); static int sdei_api_event_get_info(u32 event, u32 info, u64 *result) { return invoke_sdei_fn(SDEI_1_0_FN_SDEI_EVENT_GET_INFO, event, info, 0, 0, 0, result); } static struct sdei_event *sdei_event_create(u32 event_num, sdei_event_callback *cb, void *cb_arg) { int err; u64 result; struct sdei_event *event; struct sdei_registered_event *reg; lockdep_assert_held(&sdei_events_lock); event = kzalloc(sizeof(*event), GFP_KERNEL); if (!event) { err = -ENOMEM; goto fail; } INIT_LIST_HEAD(&event->list); event->event_num = event_num; err = sdei_api_event_get_info(event_num, SDEI_EVENT_INFO_EV_PRIORITY, &result); if (err) goto fail; event->priority = result; err = sdei_api_event_get_info(event_num, SDEI_EVENT_INFO_EV_TYPE, &result); if (err) goto fail; event->type = result; if (event->type == SDEI_EVENT_TYPE_SHARED) { reg = kzalloc(sizeof(*reg), GFP_KERNEL); if (!reg) { err = -ENOMEM; goto fail; } reg->event_num = event->event_num; reg->priority = event->priority; reg->callback = cb; reg->callback_arg = cb_arg; event->registered = reg; } else { int cpu; struct sdei_registered_event __percpu *regs; regs = alloc_percpu(struct sdei_registered_event); if (!regs) { err = -ENOMEM; goto fail; } for_each_possible_cpu(cpu) { reg = per_cpu_ptr(regs, cpu); reg->event_num = event->event_num; reg->priority = event->priority; reg->callback = cb; reg->callback_arg = cb_arg; } event->private_registered = regs; } spin_lock(&sdei_list_lock); list_add(&event->list, &sdei_list); spin_unlock(&sdei_list_lock); return event; fail: kfree(event); return ERR_PTR(err); } static void sdei_event_destroy_llocked(struct sdei_event *event) { lockdep_assert_held(&sdei_events_lock); lockdep_assert_held(&sdei_list_lock); list_del(&event->list); if (event->type == SDEI_EVENT_TYPE_SHARED) kfree(event->registered); else free_percpu(event->private_registered); kfree(event); } static void sdei_event_destroy(struct sdei_event *event) { spin_lock(&sdei_list_lock); sdei_event_destroy_llocked(event); spin_unlock(&sdei_list_lock); } static int sdei_api_get_version(u64 *version) { return invoke_sdei_fn(SDEI_1_0_FN_SDEI_VERSION, 0, 0, 0, 0, 0, version); } int sdei_mask_local_cpu(void) { int err; WARN_ON_ONCE(preemptible()); err = invoke_sdei_fn(SDEI_1_0_FN_SDEI_PE_MASK, 0, 0, 0, 0, 0, NULL); if (err && err != -EIO) { pr_warn_once("failed to mask CPU[%u]: %d\n", smp_processor_id(), err); return err; } return 0; } static void _ipi_mask_cpu(void *ignored) { sdei_mask_local_cpu(); } int sdei_unmask_local_cpu(void) { int err; WARN_ON_ONCE(preemptible()); err = invoke_sdei_fn(SDEI_1_0_FN_SDEI_PE_UNMASK, 0, 0, 0, 0, 0, NULL); if (err && err != -EIO) { pr_warn_once("failed to unmask CPU[%u]: %d\n", smp_processor_id(), err); return err; } return 0; } static void _ipi_unmask_cpu(void *ignored) { sdei_unmask_local_cpu(); } static void _ipi_private_reset(void *ignored) { int err; err = invoke_sdei_fn(SDEI_1_0_FN_SDEI_PRIVATE_RESET, 0, 0, 0, 0, 0, NULL); if (err && err != -EIO) pr_warn_once("failed to reset CPU[%u]: %d\n", smp_processor_id(), err); } static int sdei_api_shared_reset(void) { return invoke_sdei_fn(SDEI_1_0_FN_SDEI_SHARED_RESET, 0, 0, 0, 0, 0, NULL); } static void sdei_mark_interface_broken(void) { pr_err("disabling SDEI firmware interface\n"); on_each_cpu(&_ipi_mask_cpu, NULL, true); sdei_firmware_call = NULL; } static int sdei_platform_reset(void) { int err; on_each_cpu(&_ipi_private_reset, NULL, true); err = sdei_api_shared_reset(); if (err) { pr_err("Failed to reset platform: %d\n", err); sdei_mark_interface_broken(); } return err; } static int sdei_api_event_enable(u32 event_num) { return invoke_sdei_fn(SDEI_1_0_FN_SDEI_EVENT_ENABLE, event_num, 0, 0, 0, 0, NULL); } /* Called directly by the hotplug callbacks */ static void _local_event_enable(void *data) { int err; struct sdei_crosscall_args *arg = data; WARN_ON_ONCE(preemptible()); err = sdei_api_event_enable(arg->event->event_num); sdei_cross_call_return(arg, err); } int sdei_event_enable(u32 event_num) { int err = -EINVAL; struct sdei_event *event; mutex_lock(&sdei_events_lock); event = sdei_event_find(event_num); if (!event) { mutex_unlock(&sdei_events_lock); return -ENOENT; } cpus_read_lock(); if (event->type == SDEI_EVENT_TYPE_SHARED) err = sdei_api_event_enable(event->event_num); else err = sdei_do_cross_call(_local_event_enable, event); if (!err) { spin_lock(&sdei_list_lock); event->reenable = true; spin_unlock(&sdei_list_lock); } cpus_read_unlock(); mutex_unlock(&sdei_events_lock); return err; } static int sdei_api_event_disable(u32 event_num) { return invoke_sdei_fn(SDEI_1_0_FN_SDEI_EVENT_DISABLE, event_num, 0, 0, 0, 0, NULL); } static void _ipi_event_disable(void *data) { int err; struct sdei_crosscall_args *arg = data; err = sdei_api_event_disable(arg->event->event_num); sdei_cross_call_return(arg, err); } int sdei_event_disable(u32 event_num) { int err = -EINVAL; struct sdei_event *event; mutex_lock(&sdei_events_lock); event = sdei_event_find(event_num); if (!event) { mutex_unlock(&sdei_events_lock); return -ENOENT; } spin_lock(&sdei_list_lock); event->reenable = false; spin_unlock(&sdei_list_lock); if (event->type == SDEI_EVENT_TYPE_SHARED) err = sdei_api_event_disable(event->event_num); else err = sdei_do_cross_call(_ipi_event_disable, event); mutex_unlock(&sdei_events_lock); return err; } static int sdei_api_event_unregister(u32 event_num) { return invoke_sdei_fn(SDEI_1_0_FN_SDEI_EVENT_UNREGISTER, event_num, 0, 0, 0, 0, NULL); } /* Called directly by the hotplug callbacks */ static void _local_event_unregister(void *data) { int err; struct sdei_crosscall_args *arg = data; WARN_ON_ONCE(preemptible()); err = sdei_api_event_unregister(arg->event->event_num); sdei_cross_call_return(arg, err); } int sdei_event_unregister(u32 event_num) { int err; struct sdei_event *event; WARN_ON(in_nmi()); mutex_lock(&sdei_events_lock); event = sdei_event_find(event_num); if (!event) { pr_warn("Event %u not registered\n", event_num); err = -ENOENT; goto unlock; } spin_lock(&sdei_list_lock); event->reregister = false; event->reenable = false; spin_unlock(&sdei_list_lock); if (event->type == SDEI_EVENT_TYPE_SHARED) err = sdei_api_event_unregister(event->event_num); else err = sdei_do_cross_call(_local_event_unregister, event); if (err) goto unlock; sdei_event_destroy(event); unlock: mutex_unlock(&sdei_events_lock); return err; } /* * unregister events, but don't destroy them as they are re-registered by * sdei_reregister_shared(). */ static int sdei_unregister_shared(void) { int err = 0; struct sdei_event *event; mutex_lock(&sdei_events_lock); spin_lock(&sdei_list_lock); list_for_each_entry(event, &sdei_list, list) { if (event->type != SDEI_EVENT_TYPE_SHARED) continue; err = sdei_api_event_unregister(event->event_num); if (err) break; } spin_unlock(&sdei_list_lock); mutex_unlock(&sdei_events_lock); return err; } static int sdei_api_event_register(u32 event_num, unsigned long entry_point, void *arg, u64 flags, u64 affinity) { return invoke_sdei_fn(SDEI_1_0_FN_SDEI_EVENT_REGISTER, event_num, (unsigned long)entry_point, (unsigned long)arg, flags, affinity, NULL); } /* Called directly by the hotplug callbacks */ static void _local_event_register(void *data) { int err; struct sdei_registered_event *reg; struct sdei_crosscall_args *arg = data; WARN_ON(preemptible()); reg = per_cpu_ptr(arg->event->private_registered, smp_processor_id()); err = sdei_api_event_register(arg->event->event_num, sdei_entry_point, reg, 0, 0); sdei_cross_call_return(arg, err); } int sdei_event_register(u32 event_num, sdei_event_callback *cb, void *arg) { int err; struct sdei_event *event; WARN_ON(in_nmi()); mutex_lock(&sdei_events_lock); if (sdei_event_find(event_num)) { pr_warn("Event %u already registered\n", event_num); err = -EBUSY; goto unlock; } event = sdei_event_create(event_num, cb, arg); if (IS_ERR(event)) { err = PTR_ERR(event); pr_warn("Failed to create event %u: %d\n", event_num, err); goto unlock; } cpus_read_lock(); if (event->type == SDEI_EVENT_TYPE_SHARED) { err = sdei_api_event_register(event->event_num, sdei_entry_point, event->registered, SDEI_EVENT_REGISTER_RM_ANY, 0); } else { err = sdei_do_cross_call(_local_event_register, event); if (err) sdei_do_cross_call(_local_event_unregister, event); } if (err) { sdei_event_destroy(event); pr_warn("Failed to register event %u: %d\n", event_num, err); goto cpu_unlock; } spin_lock(&sdei_list_lock); event->reregister = true; spin_unlock(&sdei_list_lock); cpu_unlock: cpus_read_unlock(); unlock: mutex_unlock(&sdei_events_lock); return err; } static int sdei_reregister_shared(void) { int err = 0; struct sdei_event *event; mutex_lock(&sdei_events_lock); spin_lock(&sdei_list_lock); list_for_each_entry(event, &sdei_list, list) { if (event->type != SDEI_EVENT_TYPE_SHARED) continue; if (event->reregister) { err = sdei_api_event_register(event->event_num, sdei_entry_point, event->registered, SDEI_EVENT_REGISTER_RM_ANY, 0); if (err) { pr_err("Failed to re-register event %u\n", event->event_num); sdei_event_destroy_llocked(event); break; } } if (event->reenable) { err = sdei_api_event_enable(event->event_num); if (err) { pr_err("Failed to re-enable event %u\n", event->event_num); break; } } } spin_unlock(&sdei_list_lock); mutex_unlock(&sdei_events_lock); return err; } static int sdei_cpuhp_down(unsigned int cpu) { struct sdei_event *event; int err; /* un-register private events */ spin_lock(&sdei_list_lock); list_for_each_entry(event, &sdei_list, list) { if (event->type == SDEI_EVENT_TYPE_SHARED) continue; err = sdei_do_local_call(_local_event_unregister, event); if (err) { pr_err("Failed to unregister event %u: %d\n", event->event_num, err); } } spin_unlock(&sdei_list_lock); return sdei_mask_local_cpu(); } static int sdei_cpuhp_up(unsigned int cpu) { struct sdei_event *event; int err; /* re-register/enable private events */ spin_lock(&sdei_list_lock); list_for_each_entry(event, &sdei_list, list) { if (event->type == SDEI_EVENT_TYPE_SHARED) continue; if (event->reregister) { err = sdei_do_local_call(_local_event_register, event); if (err) { pr_err("Failed to re-register event %u: %d\n", event->event_num, err); } } if (event->reenable) { err = sdei_do_local_call(_local_event_enable, event); if (err) { pr_err("Failed to re-enable event %u: %d\n", event->event_num, err); } } } spin_unlock(&sdei_list_lock); return sdei_unmask_local_cpu(); } /* When entering idle, mask/unmask events for this cpu */ static int sdei_pm_notifier(struct notifier_block *nb, unsigned long action, void *data) { int rv; switch (action) { case CPU_PM_ENTER: rv = sdei_mask_local_cpu(); break; case CPU_PM_EXIT: case CPU_PM_ENTER_FAILED: rv = sdei_unmask_local_cpu(); break; default: return NOTIFY_DONE; } if (rv) return notifier_from_errno(rv); return NOTIFY_OK; } static struct notifier_block sdei_pm_nb = { .notifier_call = sdei_pm_notifier, }; static int sdei_device_suspend(struct device *dev) { on_each_cpu(_ipi_mask_cpu, NULL, true); return 0; } static int sdei_device_resume(struct device *dev) { on_each_cpu(_ipi_unmask_cpu, NULL, true); return 0; } /* * We need all events to be reregistered when we resume from hibernate. * * The sequence is freeze->thaw. Reboot. freeze->restore. We unregister * events during freeze, then re-register and re-enable them during thaw * and restore. */ static int sdei_device_freeze(struct device *dev) { int err; /* unregister private events */ cpuhp_remove_state(CPUHP_AP_ARM_SDEI_STARTING); err = sdei_unregister_shared(); if (err) return err; return 0; } static int sdei_device_thaw(struct device *dev) { int err; /* re-register shared events */ err = sdei_reregister_shared(); if (err) { pr_warn("Failed to re-register shared events...\n"); sdei_mark_interface_broken(); return err; } err = cpuhp_setup_state(CPUHP_AP_ARM_SDEI_STARTING, "SDEI", &sdei_cpuhp_up, &sdei_cpuhp_down); if (err) pr_warn("Failed to re-register CPU hotplug notifier...\n"); return err; } static int sdei_device_restore(struct device *dev) { int err; err = sdei_platform_reset(); if (err) return err; return sdei_device_thaw(dev); } static const struct dev_pm_ops sdei_pm_ops = { .suspend = sdei_device_suspend, .resume = sdei_device_resume, .freeze = sdei_device_freeze, .thaw = sdei_device_thaw, .restore = sdei_device_restore, }; /* * Mask all CPUs and unregister all events on panic, reboot or kexec. */ static int sdei_reboot_notifier(struct notifier_block *nb, unsigned long action, void *data) { /* * We are going to reset the interface, after this there is no point * doing work when we take CPUs offline. */ cpuhp_remove_state(CPUHP_AP_ARM_SDEI_STARTING); sdei_platform_reset(); return NOTIFY_OK; } static struct notifier_block sdei_reboot_nb = { .notifier_call = sdei_reboot_notifier, }; static void sdei_smccc_smc(unsigned long function_id, unsigned long arg0, unsigned long arg1, unsigned long arg2, unsigned long arg3, unsigned long arg4, struct arm_smccc_res *res) { arm_smccc_smc(function_id, arg0, arg1, arg2, arg3, arg4, 0, 0, res); } NOKPROBE_SYMBOL(sdei_smccc_smc); static void sdei_smccc_hvc(unsigned long function_id, unsigned long arg0, unsigned long arg1, unsigned long arg2, unsigned long arg3, unsigned long arg4, struct arm_smccc_res *res) { arm_smccc_hvc(function_id, arg0, arg1, arg2, arg3, arg4, 0, 0, res); } NOKPROBE_SYMBOL(sdei_smccc_hvc); int sdei_register_ghes(struct ghes *ghes, sdei_event_callback *normal_cb, sdei_event_callback *critical_cb) { int err; u64 result; u32 event_num; sdei_event_callback *cb; if (!IS_ENABLED(CONFIG_ACPI_APEI_GHES)) return -EOPNOTSUPP; event_num = ghes->generic->notify.vector; if (event_num == 0) { /* * Event 0 is reserved by the specification for * SDEI_EVENT_SIGNAL. */ return -EINVAL; } err = sdei_api_event_get_info(event_num, SDEI_EVENT_INFO_EV_PRIORITY, &result); if (err) return err; if (result == SDEI_EVENT_PRIORITY_CRITICAL) cb = critical_cb; else cb = normal_cb; err = sdei_event_register(event_num, cb, ghes); if (!err) err = sdei_event_enable(event_num); return err; } int sdei_unregister_ghes(struct ghes *ghes) { int i; int err; u32 event_num = ghes->generic->notify.vector; might_sleep(); if (!IS_ENABLED(CONFIG_ACPI_APEI_GHES)) return -EOPNOTSUPP; /* * The event may be running on another CPU. Disable it * to stop new events, then try to unregister a few times. */ err = sdei_event_disable(event_num); if (err) return err; for (i = 0; i < 3; i++) { err = sdei_event_unregister(event_num); if (err != -EINPROGRESS) break; schedule(); } return err; } static int sdei_get_conduit(struct platform_device *pdev) { const char *method; struct device_node *np = pdev->dev.of_node; sdei_firmware_call = NULL; if (np) { if (of_property_read_string(np, "method", &method)) { pr_warn("missing \"method\" property\n"); return SMCCC_CONDUIT_NONE; } if (!strcmp("hvc", method)) { sdei_firmware_call = &sdei_smccc_hvc; return SMCCC_CONDUIT_HVC; } else if (!strcmp("smc", method)) { sdei_firmware_call = &sdei_smccc_smc; return SMCCC_CONDUIT_SMC; } pr_warn("invalid \"method\" property: %s\n", method); } else if (!acpi_disabled) { if (acpi_psci_use_hvc()) { sdei_firmware_call = &sdei_smccc_hvc; return SMCCC_CONDUIT_HVC; } else { sdei_firmware_call = &sdei_smccc_smc; return SMCCC_CONDUIT_SMC; } } return SMCCC_CONDUIT_NONE; } static int sdei_probe(struct platform_device *pdev) { int err; u64 ver = 0; int conduit; conduit = sdei_get_conduit(pdev); if (!sdei_firmware_call) return 0; err = sdei_api_get_version(&ver); if (err) { pr_err("Failed to get SDEI version: %d\n", err); sdei_mark_interface_broken(); return err; } pr_info("SDEIv%d.%d (0x%x) detected in firmware.\n", (int)SDEI_VERSION_MAJOR(ver), (int)SDEI_VERSION_MINOR(ver), (int)SDEI_VERSION_VENDOR(ver)); if (SDEI_VERSION_MAJOR(ver) != 1) { pr_warn("Conflicting SDEI version detected.\n"); sdei_mark_interface_broken(); return -EINVAL; } err = sdei_platform_reset(); if (err) return err; sdei_entry_point = sdei_arch_get_entry_point(conduit); if (!sdei_entry_point) { /* Not supported due to hardware or boot configuration */ sdei_mark_interface_broken(); return 0; } err = cpu_pm_register_notifier(&sdei_pm_nb); if (err) { pr_warn("Failed to register CPU PM notifier...\n"); goto error; } err = register_reboot_notifier(&sdei_reboot_nb); if (err) { pr_warn("Failed to register reboot notifier...\n"); goto remove_cpupm; } err = cpuhp_setup_state(CPUHP_AP_ARM_SDEI_STARTING, "SDEI", &sdei_cpuhp_up, &sdei_cpuhp_down); if (err) { pr_warn("Failed to register CPU hotplug notifier...\n"); goto remove_reboot; } return 0; remove_reboot: unregister_reboot_notifier(&sdei_reboot_nb); remove_cpupm: cpu_pm_unregister_notifier(&sdei_pm_nb); error: sdei_mark_interface_broken(); return err; } static const struct of_device_id sdei_of_match[] = { { .compatible = "arm,sdei-1.0" }, {} }; static struct platform_driver sdei_driver = { .driver = { .name = "sdei", .pm = &sdei_pm_ops, .of_match_table = sdei_of_match, }, .probe = sdei_probe, }; static bool __init sdei_present_acpi(void) { acpi_status status; struct acpi_table_header *sdei_table_header; if (acpi_disabled) return false; status = acpi_get_table(ACPI_SIG_SDEI, 0, &sdei_table_header); if (ACPI_FAILURE(status) && status != AE_NOT_FOUND) { const char *msg = acpi_format_exception(status); pr_info("Failed to get ACPI:SDEI table, %s\n", msg); } if (ACPI_FAILURE(status)) return false; acpi_put_table(sdei_table_header); return true; } void __init sdei_init(void) { struct platform_device *pdev; int ret; ret = platform_driver_register(&sdei_driver); if (ret || !sdei_present_acpi()) return; pdev = platform_device_register_simple(sdei_driver.driver.name, 0, NULL, 0); if (IS_ERR(pdev)) { ret = PTR_ERR(pdev); platform_driver_unregister(&sdei_driver); pr_info("Failed to register ACPI:SDEI platform device %d\n", ret); } } int sdei_event_handler(struct pt_regs *regs, struct sdei_registered_event *arg) { int err; u32 event_num = arg->event_num; err = arg->callback(event_num, regs, arg->callback_arg); if (err) pr_err_ratelimited("event %u on CPU %u failed with error: %d\n", event_num, smp_processor_id(), err); return err; } NOKPROBE_SYMBOL(sdei_event_handler);
21.647489
80
0.715871
[ "vector" ]
1e217c27242e04622a1ccc2e1e7b4973930840cf
2,194
h
C
chrome/browser/task_manager/providers/child_process_task.h
zipated/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
chrome/browser/task_manager/providers/child_process_task.h
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
chrome/browser/task_manager/providers/child_process_task.h
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.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. #ifndef CHROME_BROWSER_TASK_MANAGER_PROVIDERS_CHILD_PROCESS_TASK_H_ #define CHROME_BROWSER_TASK_MANAGER_PROVIDERS_CHILD_PROCESS_TASK_H_ #include <stdint.h> #include <memory> #include "base/macros.h" #include "chrome/browser/task_manager/providers/task.h" class ProcessResourceUsage; namespace content { struct ChildProcessData; } // namespace content namespace task_manager { // Represents several types of the browser's child processes such as // a plugin or a GPU process, ... etc. class ChildProcessTask : public Task { public: // Creates a child process task given its |data| which is // received from observing |content::BrowserChildProcessObserver|. explicit ChildProcessTask(const content::ChildProcessData& data); ~ChildProcessTask() override; // task_manager::Task: void Refresh(const base::TimeDelta& update_interval, int64_t refresh_flags) override; Type GetType() const override; int GetChildProcessUniqueID() const override; bool ReportsV8Memory() const; int64_t GetV8MemoryAllocated() const override; int64_t GetV8MemoryUsed() const override; private: static gfx::ImageSkia* s_icon_; // The Mojo service wrapper that will provide us with the V8 memory usage of // the browser child process represented by this object. std::unique_ptr<ProcessResourceUsage> process_resources_sampler_; // The allocated and used V8 memory (in bytes). int64_t v8_memory_allocated_; int64_t v8_memory_used_; // The unique ID of the child process. It is not the PID of the process. // See |content::ChildProcessData::id|. const int unique_child_process_id_; // The type of the child process. See |content::ProcessType| and // |NaClTrustedProcessType|. const int process_type_; // Depending on the |process_type_|, determines whether this task uses V8 // memory or not. const bool uses_v8_memory_; DISALLOW_COPY_AND_ASSIGN(ChildProcessTask); }; } // namespace task_manager #endif // CHROME_BROWSER_TASK_MANAGER_PROVIDERS_CHILD_PROCESS_TASK_H_
30.901408
78
0.770283
[ "object" ]
1e2591da056729d55593293e7f86fb9b54a81984
1,513
h
C
Qt-Tim-Like/Ubuntu_qt/TimLike/SoftKeyBoard.h
yujiecong/Qt-TimLike
54172a907bd9b8a96c0bc6a827f15abbdb152de8
[ "MIT" ]
null
null
null
Qt-Tim-Like/Ubuntu_qt/TimLike/SoftKeyBoard.h
yujiecong/Qt-TimLike
54172a907bd9b8a96c0bc6a827f15abbdb152de8
[ "MIT" ]
null
null
null
Qt-Tim-Like/Ubuntu_qt/TimLike/SoftKeyBoard.h
yujiecong/Qt-TimLike
54172a907bd9b8a96c0bc6a827f15abbdb152de8
[ "MIT" ]
null
null
null
#ifndef SOFTKEYBOARD_H #define SOFTKEYBOARD_H #include <QtGui> #include <QtCore> #include <QPoint> #include <QPushButton> #include <map> #include <vector> #include "ui_SoftKeyBoard.h" class SoftKeyBoard : public QWidget { Q_OBJECT public: SoftKeyBoard(QWidget * parent = 0); signals: void characterGenerated(int character); protected: bool event(QEvent *e); void mousePressEvent(QMouseEvent *event); void mouseMoveEvent(QMouseEvent *event); void mouseReleaseEvent(QMouseEvent *event); void paintEvent(QPaintEvent *); private slots: void saveFocusWidget(QWidget *oldFocus, QWidget *newFocus); void buttonClicked(QWidget *w); void on_btn_language__clicked(); void on_btn_caplock__clicked(); void on_btn_next__clicked(); void on_btn_last__clicked(); void on_btn_shift__clicked(); private: //初始化字库 bool InitChinese(); bool GetBtnText(QWidget * widget,QString & text,int start,int count); void ShowChinese(QString str,int page,int pos); private: Ui::SoftKeyBoard ui; QWidget * m_lastFocusedWidget_; QSignalMapper m_signalMapper_; QPushButton * m_btns_[65]; //用于拖动窗口 QPoint m_ptPress_; bool m_bLeftBtnPress_; //语言,false:英文,true:中文 bool m_bIsChinese_; bool m_bIsUppercase_; bool m_bShiftPressed_; //汉字库 key:拼音 value:字 std::map<QString,std::vector<QString> >m_map_; //拼音 QString m_strPingying_; //选中的文字位置 int m_currentPos_; //当前页 int m_currentPage_; }; #endif
22.58209
73
0.709187
[ "vector" ]
1e34a62c35cf8736f7be890addbd985eacdd4ea3
20,330
c
C
src/redis-check-rdb.c
yupferris/radis
d25d67ccd82da93b6207feb8d80d5811fba08e46
[ "BSD-3-Clause" ]
1
2019-06-30T06:30:42.000Z
2019-06-30T06:30:42.000Z
src/redis-check-rdb.c
yupferris/radis
d25d67ccd82da93b6207feb8d80d5811fba08e46
[ "BSD-3-Clause" ]
null
null
null
src/redis-check-rdb.c
yupferris/radis
d25d67ccd82da93b6207feb8d80d5811fba08e46
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2009-2012, Pieter Noordhuis <pcnoordhuis at gmail dot com> * Copyright (c) 2009-2012, Salvatore Sanfilippo <antirez at gmail dot com> * 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 Redis 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 "server.h" #include "rdb.h" #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/mman.h> #include "lzf.h" #include "crc64.h" #define ERROR(...) { \ serverLog(LL_WARNING, __VA_ARGS__); \ exit(1); \ } /* data type to hold offset in file and size */ typedef struct { void *data; size_t size; size_t offset; } pos; static unsigned char level = 0; static pos positions[16]; #define CURR_OFFSET (positions[level].offset) /* Hold a stack of errors */ typedef struct { char error[16][1024]; size_t offset[16]; size_t level; } errors_t; static errors_t errors; #define SHIFT_ERROR(provided_offset, ...) { \ sprintf(errors.error[errors.level], __VA_ARGS__); \ errors.offset[errors.level] = provided_offset; \ errors.level++; \ } /* Data type to hold opcode with optional key name an success status */ typedef struct { char* key; int type; char success; } entry; #define MAX_TYPES_NUM 256 #define MAX_TYPE_NAME_LEN 16 /* store string types for output */ static char types[MAX_TYPES_NUM][MAX_TYPE_NAME_LEN]; /* Return true if 't' is a valid object type. */ static int rdbCheckType(unsigned char t) { /* In case a new object type is added, update the following * condition as necessary. */ return (t >= RDB_TYPE_HASH_ZIPMAP && t <= RDB_TYPE_HASH_ZIPLIST) || t <= RDB_TYPE_HASH || t >= RDB_OPCODE_EXPIRETIME_MS; } /* when number of bytes to read is negative, do a peek */ static int readBytes(void *target, long num) { char peek = (num < 0) ? 1 : 0; num = (num < 0) ? -num : num; pos p = positions[level]; if (p.offset + num > p.size) { return 0; } else { memcpy(target, (void*)((size_t)p.data + p.offset), num); if (!peek) positions[level].offset += num; } return 1; } int processHeader(void) { char buf[10] = "_________"; int dump_version; if (!readBytes(buf, 9)) { ERROR("Cannot read header"); } /* expect the first 5 bytes to equal REDIS */ if (memcmp(buf,"REDIS",5) != 0) { ERROR("Wrong signature in header"); } dump_version = (int)strtol(buf + 5, NULL, 10); if (dump_version < 1 || dump_version > 6) { ERROR("Unknown RDB format version: %d", dump_version); } return dump_version; } static int loadType(entry *e) { uint32_t offset = CURR_OFFSET; /* this byte needs to qualify as type */ unsigned char t; if (readBytes(&t, 1)) { if (rdbCheckType(t)) { e->type = t; return 1; } else { SHIFT_ERROR(offset, "Unknown type (0x%02x)", t); } } else { SHIFT_ERROR(offset, "Could not read type"); } /* failure */ return 0; } static int peekType() { unsigned char t; if (readBytes(&t, -1) && (rdbCheckType(t))) return t; return -1; } /* discard time, just consume the bytes */ static int processTime(int type) { uint32_t offset = CURR_OFFSET; unsigned char t[8]; int timelen = (type == RDB_OPCODE_EXPIRETIME_MS) ? 8 : 4; if (readBytes(t,timelen)) { return 1; } else { SHIFT_ERROR(offset, "Could not read time"); } /* failure */ return 0; } static uint64_t loadLength(int *isencoded) { unsigned char buf[2]; uint32_t len; int type; if (isencoded) *isencoded = 0; if (!readBytes(buf, 1)) return RDB_LENERR; type = (buf[0] & 0xC0) >> 6; if (type == RDB_6BITLEN) { /* Read a 6 bit len */ return buf[0] & 0x3F; } else if (type == RDB_ENCVAL) { /* Read a 6 bit len encoding type */ if (isencoded) *isencoded = 1; return buf[0] & 0x3F; } else if (type == RDB_14BITLEN) { /* Read a 14 bit len */ if (!readBytes(buf+1,1)) return RDB_LENERR; return ((buf[0] & 0x3F) << 8) | buf[1]; } else if (buf[0] == RDB_32BITLEN) { /* Read a 32 bit len */ if (!readBytes(&len, 4)) return RDB_LENERR; return ntohl(len); } else if (buf[0] == RDB_64BITLEN) { /* Read a 64 bit len */ if (!readBytes(&len, 8)) return RDB_LENERR; return ntohu64(len); } else { return RDB_LENERR; } } static char *loadIntegerObject(int enctype) { uint32_t offset = CURR_OFFSET; unsigned char enc[4]; long long val; if (enctype == RDB_ENC_INT8) { uint8_t v; if (!readBytes(enc, 1)) return NULL; v = enc[0]; val = (int8_t)v; } else if (enctype == RDB_ENC_INT16) { uint16_t v; if (!readBytes(enc, 2)) return NULL; v = enc[0]|(enc[1]<<8); val = (int16_t)v; } else if (enctype == RDB_ENC_INT32) { uint32_t v; if (!readBytes(enc, 4)) return NULL; v = enc[0]|(enc[1]<<8)|(enc[2]<<16)|(enc[3]<<24); val = (int32_t)v; } else { SHIFT_ERROR(offset, "Unknown integer encoding (0x%02x)", enctype); return NULL; } /* convert val into string */ char *buf; buf = zmalloc(sizeof(char) * 128); sprintf(buf, "%lld", val); return buf; } static char* loadLzfStringObject() { uint64_t slen, clen; char *c, *s; if ((clen = loadLength(NULL)) == RDB_LENERR) return NULL; if ((slen = loadLength(NULL)) == RDB_LENERR) return NULL; c = zmalloc(clen); if (!readBytes(c, clen)) { zfree(c); return NULL; } s = zmalloc(slen+1); if (lzf_decompress(c,clen,s,slen) == 0) { zfree(c); zfree(s); return NULL; } zfree(c); return s; } /* returns NULL when not processable, char* when valid */ static char* loadStringObject() { uint64_t offset = CURR_OFFSET; uint64_t len; int isencoded; len = loadLength(&isencoded); if (isencoded) { switch(len) { case RDB_ENC_INT8: case RDB_ENC_INT16: case RDB_ENC_INT32: return loadIntegerObject(len); case RDB_ENC_LZF: return loadLzfStringObject(); default: /* unknown encoding */ SHIFT_ERROR(offset, "Unknown string encoding (0x%02llx)", len); return NULL; } } if (len == RDB_LENERR) return NULL; char *buf = zmalloc(sizeof(char) * (len+1)); if (buf == NULL) return NULL; buf[len] = '\0'; if (!readBytes(buf, len)) { zfree(buf); return NULL; } return buf; } static int processStringObject(char** store) { unsigned long offset = CURR_OFFSET; char *key = loadStringObject(); if (key == NULL) { SHIFT_ERROR(offset, "Error reading string object"); zfree(key); return 0; } if (store != NULL) { *store = key; } else { zfree(key); } return 1; } static double* loadDoubleValue() { char buf[256]; unsigned char len; double* val; if (!readBytes(&len,1)) return NULL; val = zmalloc(sizeof(double)); switch(len) { case 255: *val = R_NegInf; return val; case 254: *val = R_PosInf; return val; case 253: *val = R_Nan; return val; default: if (!readBytes(buf, len)) { zfree(val); return NULL; } buf[len] = '\0'; sscanf(buf, "%lg", val); return val; } } static int processDoubleValue(double** store) { unsigned long offset = CURR_OFFSET; double *val = loadDoubleValue(); if (val == NULL) { SHIFT_ERROR(offset, "Error reading double value"); zfree(val); return 0; } if (store != NULL) { *store = val; } else { zfree(val); } return 1; } static int loadPair(entry *e) { uint64_t offset = CURR_OFFSET; uint64_t i; /* read key first */ char *key; if (processStringObject(&key)) { e->key = key; } else { SHIFT_ERROR(offset, "Error reading entry key"); return 0; } uint64_t length = 0; if (e->type == RDB_TYPE_LIST || e->type == RDB_TYPE_SET || e->type == RDB_TYPE_ZSET || e->type == RDB_TYPE_HASH) { if ((length = loadLength(NULL)) == RDB_LENERR) { SHIFT_ERROR(offset, "Error reading %s length", types[e->type]); return 0; } } switch(e->type) { case RDB_TYPE_STRING: case RDB_TYPE_HASH_ZIPMAP: case RDB_TYPE_LIST_ZIPLIST: case RDB_TYPE_SET_INTSET: case RDB_TYPE_ZSET_ZIPLIST: case RDB_TYPE_HASH_ZIPLIST: if (!processStringObject(NULL)) { SHIFT_ERROR(offset, "Error reading entry value"); return 0; } break; case RDB_TYPE_LIST: case RDB_TYPE_SET: for (i = 0; i < length; i++) { offset = CURR_OFFSET; if (!processStringObject(NULL)) { SHIFT_ERROR(offset, "Error reading element at index %llu (length: %llu)", i, length); return 0; } } break; case RDB_TYPE_ZSET: for (i = 0; i < length; i++) { offset = CURR_OFFSET; if (!processStringObject(NULL)) { SHIFT_ERROR(offset, "Error reading element key at index %llu (length: %llu)", i, length); return 0; } offset = CURR_OFFSET; if (!processDoubleValue(NULL)) { SHIFT_ERROR(offset, "Error reading element value at index %llu (length: %llu)", i, length); return 0; } } break; case RDB_TYPE_HASH: for (i = 0; i < length; i++) { offset = CURR_OFFSET; if (!processStringObject(NULL)) { SHIFT_ERROR(offset, "Error reading element key at index %llu (length: %llu)", i, length); return 0; } offset = CURR_OFFSET; if (!processStringObject(NULL)) { SHIFT_ERROR(offset, "Error reading element value at index %llu (length: %llu)", i, length); return 0; } } break; default: SHIFT_ERROR(offset, "Type not implemented"); return 0; } /* because we're done, we assume success */ e->success = 1; return 1; } static entry loadEntry() { entry e = { NULL, -1, 0 }; uint64_t length, offset[4]; /* reset error container */ errors.level = 0; offset[0] = CURR_OFFSET; if (!loadType(&e)) { return e; } offset[1] = CURR_OFFSET; if (e.type == RDB_OPCODE_SELECTDB) { if ((length = loadLength(NULL)) == RDB_LENERR) { SHIFT_ERROR(offset[1], "Error reading database number"); return e; } if (length > 63) { SHIFT_ERROR(offset[1], "Database number out of range (%llu)", length); return e; } } else if (e.type == RDB_OPCODE_EOF) { if (positions[level].offset < positions[level].size) { SHIFT_ERROR(offset[0], "Unexpected EOF"); } else { e.success = 1; } return e; } else { /* optionally consume expire */ if (e.type == RDB_OPCODE_EXPIRETIME || e.type == RDB_OPCODE_EXPIRETIME_MS) { if (!processTime(e.type)) return e; if (!loadType(&e)) return e; } offset[1] = CURR_OFFSET; if (!loadPair(&e)) { SHIFT_ERROR(offset[1], "Error for type %s", types[e.type]); return e; } } /* all entries are followed by a valid type: * e.g. a new entry, SELECTDB, EXPIRE, EOF */ offset[2] = CURR_OFFSET; if (peekType() == -1) { SHIFT_ERROR(offset[2], "Followed by invalid type"); SHIFT_ERROR(offset[0], "Error for type %s", types[e.type]); e.success = 0; } else { e.success = 1; } return e; } static void printCentered(int indent, int width, char* body) { char head[256], tail[256]; memset(head, '\0', 256); memset(tail, '\0', 256); memset(head, '=', indent); memset(tail, '=', width - 2 - indent - strlen(body)); serverLog(LL_WARNING, "%s %s %s", head, body, tail); } static void printValid(uint64_t ops, uint64_t bytes) { char body[80]; sprintf(body, "Processed %llu valid opcodes (in %llu bytes)", (unsigned long long) ops, (unsigned long long) bytes); printCentered(4, 80, body); } static void printSkipped(uint64_t bytes, uint64_t offset) { char body[80]; sprintf(body, "Skipped %llu bytes (resuming at 0x%08llx)", (unsigned long long) bytes, (unsigned long long) offset); printCentered(4, 80, body); } static void printErrorStack(entry *e) { unsigned int i; char body[64]; if (e->type == -1) { sprintf(body, "Error trace"); } else if (e->type >= 253) { sprintf(body, "Error trace (%s)", types[e->type]); } else if (!e->key) { sprintf(body, "Error trace (%s: (unknown))", types[e->type]); } else { char tmp[41]; strncpy(tmp, e->key, 40); /* display truncation at the last 3 chars */ if (strlen(e->key) > 40) { memset(&tmp[37], '.', 3); } /* display unprintable characters as ? */ for (i = 0; i < strlen(tmp); i++) { if (tmp[i] <= 32) tmp[i] = '?'; } sprintf(body, "Error trace (%s: %s)", types[e->type], tmp); } printCentered(4, 80, body); /* display error stack */ for (i = 0; i < errors.level; i++) { serverLog(LL_WARNING, "0x%08lx - %s", (unsigned long) errors.offset[i], errors.error[i]); } } void process(void) { uint64_t num_errors = 0, num_valid_ops = 0, num_valid_bytes = 0; entry entry = { NULL, -1, 0 }; int dump_version = processHeader(); /* Exclude the final checksum for RDB >= 5. Will be checked at the end. */ if (dump_version >= 5) { if (positions[0].size < 8) { serverLog(LL_WARNING, "RDB version >= 5 but no room for checksum."); exit(1); } positions[0].size -= 8; } level = 1; while(positions[0].offset < positions[0].size) { positions[1] = positions[0]; entry = loadEntry(); if (!entry.success) { printValid(num_valid_ops, num_valid_bytes); printErrorStack(&entry); num_errors++; num_valid_ops = 0; num_valid_bytes = 0; /* search for next valid entry */ uint64_t offset = positions[0].offset + 1; int i = 0; while (!entry.success && offset < positions[0].size) { positions[1].offset = offset; /* find 3 consecutive valid entries */ for (i = 0; i < 3; i++) { entry = loadEntry(); if (!entry.success) break; } /* check if we found 3 consecutive valid entries */ if (i < 3) { offset++; } } /* print how many bytes we have skipped to find a new valid opcode */ if (offset < positions[0].size) { printSkipped(offset - positions[0].offset, offset); } positions[0].offset = offset; } else { num_valid_ops++; num_valid_bytes += positions[1].offset - positions[0].offset; /* advance position */ positions[0] = positions[1]; } zfree(entry.key); } /* because there is another potential error, * print how many valid ops we have processed */ printValid(num_valid_ops, num_valid_bytes); /* expect an eof */ if (entry.type != RDB_OPCODE_EOF) { /* last byte should be EOF, add error */ errors.level = 0; SHIFT_ERROR(positions[0].offset, "Expected EOF, got %s", types[entry.type]); /* this is an EOF error so reset type */ entry.type = -1; printErrorStack(&entry); num_errors++; } /* Verify checksum */ if (dump_version >= 5) { uint64_t crc = crc64(0,positions[0].data,positions[0].size); uint64_t crc2; unsigned char *p = (unsigned char*)positions[0].data+positions[0].size; crc2 = ((uint64_t)p[0] << 0) | ((uint64_t)p[1] << 8) | ((uint64_t)p[2] << 16) | ((uint64_t)p[3] << 24) | ((uint64_t)p[4] << 32) | ((uint64_t)p[5] << 40) | ((uint64_t)p[6] << 48) | ((uint64_t)p[7] << 56); if (crc != crc2) { SHIFT_ERROR(positions[0].offset, "RDB CRC64 does not match."); } else { serverLog(LL_WARNING, "CRC64 checksum is OK"); } } /* print summary on errors */ if (num_errors) { serverLog(LL_WARNING, "Total unprocessable opcodes: %llu", (unsigned long long) num_errors); } } int redis_check_rdb(char *rdbfilename) { int fd; off_t size; struct stat stat; void *data; fd = open(rdbfilename, O_RDONLY); if (fd < 1) { ERROR("Cannot open file: %s", rdbfilename); } if (fstat(fd, &stat) == -1) { ERROR("Cannot stat: %s", rdbfilename); } else { size = stat.st_size; } if (sizeof(size_t) == sizeof(int32_t) && size >= INT_MAX) { ERROR("Cannot check dump files >2GB on a 32-bit platform"); } data = mmap(NULL, size, PROT_READ, MAP_SHARED, fd, 0); if (data == MAP_FAILED) { ERROR("Cannot mmap: %s", rdbfilename); } /* Initialize static vars */ positions[0].data = data; positions[0].size = size; positions[0].offset = 0; errors.level = 0; /* Object types */ sprintf(types[RDB_TYPE_STRING], "STRING"); sprintf(types[RDB_TYPE_LIST], "LIST"); sprintf(types[RDB_TYPE_SET], "SET"); sprintf(types[RDB_TYPE_ZSET], "ZSET"); sprintf(types[RDB_TYPE_HASH], "HASH"); /* Object types only used for dumping to disk */ sprintf(types[RDB_OPCODE_EXPIRETIME], "EXPIRETIME"); sprintf(types[RDB_OPCODE_SELECTDB], "SELECTDB"); sprintf(types[RDB_OPCODE_EOF], "EOF"); process(); munmap(data, size); close(fd); return 0; } /* RDB check main: called form redis.c when Redis is executed with the * redis-check-rdb alias. */ int redis_check_rdb_main(char **argv, int argc) { if (argc != 2) { fprintf(stderr, "Usage: %s <rdb-file-name>\n", argv[0]); exit(1); } serverLog(LL_WARNING, "Checking RDB file %s", argv[1]); exit(redis_check_rdb(argv[1])); return 0; }
28.354254
107
0.565175
[ "object" ]
1e38378a5e6f6a207d2df995f2dcddc23639dbaf
7,017
h
C
src/XE.Math/include/XE/Math/Quaternion.h
fapablazacl/XE
9a047af9ba1892711ee637a975bfdb4a0ed68e0e
[ "MIT" ]
null
null
null
src/XE.Math/include/XE/Math/Quaternion.h
fapablazacl/XE
9a047af9ba1892711ee637a975bfdb4a0ed68e0e
[ "MIT" ]
3
2019-02-20T02:27:21.000Z
2019-02-20T03:00:56.000Z
src/XE.Math/include/XE/Math/Quaternion.h
fapablazacl/XE
9a047af9ba1892711ee637a975bfdb4a0ed68e0e
[ "MIT" ]
null
null
null
#ifndef __XE_MATH_QUATERNION_HPP__ #define __XE_MATH_QUATERNION_HPP__ #include <cmath> #include <cstdint> #include <cassert> #include <XE/Math/Vector.h> #include <XE/Math/Rotation.h> namespace XE { template<typename T> struct Quaternion { union { struct { Vector<T, 3> V; T W; }; T data[4]; }; Quaternion() {} Quaternion(const T value) { V.X = value; V.Y = value; V.Z = value; W = value; } explicit Quaternion(const T *values) { assert(values); for (int i=0; i<4; i++) { data[i] = values[i]; } } Quaternion(const T x, const T y, const T z, const T w) { V.X = x; V.Y = y; V.Z = z; W = w; } explicit Quaternion(const Vector<T, 3> &v) { V = v; W = T(0); } explicit Quaternion(const T x, const T y, const T z) { V.X = x; V.Y = y; V.Z = z; W = T(0); } Quaternion(const Vector<T, 3> &v, T w) { V = v; W = w; } explicit Quaternion(const Vector<T, 4> &v) { V.X = v.X; V.Y = v.Y; V.Z = v.Z; W = v.W; } Quaternion(const Quaternion<T> &other) { V = other.V; W = other.W; } explicit operator Rotation<T>() const { const T angle = T(2) * std::acos(W); if (angle == T(0)) { return {angle, {T(1), T(0), T(0)}}; } else { return {angle, normalize(V)}; } } explicit operator Vector<T, 4>() const { return {V.X, V.Y, V.Z, V.W}; } Quaternion<T> operator+ (const Quaternion<T> &rhs) const { Quaternion<T> result; for (int i=0; i<4; i++) { result.data[i] = this->data[i] + rhs.data[i]; } return result; } Quaternion<T> operator- (const Quaternion<T> &rhs) const { Quaternion<T> result; for (int i=0; i<4; i++) { result.data[i] = this->data[i] - rhs.data[i]; } return result; } Quaternion<T> operator- () const { Quaternion<T> result; for (int i=0; i<4; i++) { result.data[i] = -this->data[i]; } return result; } Quaternion<T> operator+ () const { return *this; } Quaternion<T> operator* (const Quaternion<T> &rhs) const { return { cross(V, rhs.V) + rhs.V*W + V*rhs.W, W*rhs.W - dot(V, rhs.V) }; } Quaternion<T> operator/ (const Quaternion<T> &rhs) const { return (*this) * inverse(rhs); } Quaternion<T> operator* (const T s) const { Quaternion<T> result; for (int i=0; i<4; i++) { result.data[i] = this->data[i] * s; } return result; } Quaternion<T> operator/ (const T s) const { Quaternion<T> result; for (int i=0; i<4; i++) { result.data[i] = this->data[i] / s; } return result; } friend Quaternion<T> operator* (const T s, const Quaternion<T> &q) { return q * s; } Quaternion<T>& operator+= (const Quaternion<T> &rhs) { for (int i=0; i<4; i++) { this->data[i] += rhs.data[i]; } return *this; } Quaternion<T>& operator-= (const Quaternion<T> &rhs) { for (int i=0; i<4; i++) { this->data[i] -= rhs.data[i]; } return *this; } Quaternion<T>& operator*= (const Quaternion<T> &rhs) { *this = *this * rhs; return *this; } Quaternion<T>& operator/= (const Quaternion<T> &rhs) { *this = *this / rhs; return *this; } Quaternion<T>& operator*= (const T s) { for (int i=0; i<4; i++) { this->data[i] *= s; } return *this; } Quaternion<T>& operator/= (const T s) { for (int i=0; i<4; i++) { this->data[i] /= s; } return *this; } bool operator== (const Quaternion<T> &rhs) const { for (int i=0; i<4; i++) { if (this->data[i] != rhs.data[i]) { return false; } } return true; } bool operator!= (const Quaternion<T> &rhs) const { return !(*this == rhs); } static Quaternion<T> createZero() { return Quaternion<T>({T(0), T(0), T(0)}, T(0)); } static Quaternion<T> createIdentity() { return Quaternion<T>({T(0), T(0), T(0)}, T(1)); } static Quaternion<T> createRotation(const T radians, const Vector<T, 3> &axis) { auto q = Quaternion<T>(axis, std::cos(radians / T(2))); return normalize(q); } static Quaternion<T> createRotation(const Vector<T, 3> &v1, const Vector<T, 3> &v2) { auto v = cross(v1, v2); auto w = std::sqrt(dot(v1, v1) * dot(v2, v2)) + dot(v1, v2); return normalize(Quaternion<T>(v, w)); } }; template<typename T> Quaternion<T> conjugate(const Quaternion<T> &q) { return {-q.V, q.W}; } template<typename T> Quaternion<T> inverse(const Quaternion<T> &q) { return conjugate(q) / norm2(q); } template<typename T> T dot(const Quaternion<T> &q1, const Quaternion<T> &q2) { T sum = T(0); for (int i=0; i<4; i++) { sum += q1.data[i]*q2.data[i]; } return sum; } template<typename T> T norm2(const Quaternion<T> &q) { return dot(q, q); } /** * @brief Compute the magnitude, module or length (AKA Absolute Value) for a given Quaternion. */ template<typename T> T norm(const Quaternion<T> &q) { return static_cast<T>(std::sqrt(norm2(q))); } /** * @brief Compute a Quaternion with a unit magnitude (1) */ template<typename T> Quaternion<T> normalize(const Quaternion<T> &q) { return q / norm(q); } template<typename T> Vector<T, 3> transform(const Quaternion<T> &q, const Vector<T, 3> &v) { return (q * Quaternion<T>(v) * Inverse(q)).V; } } #endif
24.280277
98
0.425395
[ "vector", "transform" ]
1e384489dcfe07cf2c73d1f73b04f7c20fd05597
21,221
h
C
applications/metis_application/custom_processes/metis_partitioning_process.h
jiaqiwang969/Kratos-test
ed082abc163e7b627f110a1ae1da465f52f48348
[ "BSD-4-Clause" ]
null
null
null
applications/metis_application/custom_processes/metis_partitioning_process.h
jiaqiwang969/Kratos-test
ed082abc163e7b627f110a1ae1da465f52f48348
[ "BSD-4-Clause" ]
null
null
null
applications/metis_application/custom_processes/metis_partitioning_process.h
jiaqiwang969/Kratos-test
ed082abc163e7b627f110a1ae1da465f52f48348
[ "BSD-4-Clause" ]
null
null
null
/* ============================================================================== KratosPFEMApplication A library based on: Kratos A General Purpose Software for Multi-Physics Finite Element Analysis Version 1.0 (Released on march 05, 2007). Copyright 2007 Pooyan Dadvand, Riccardo Rossi pooyan@cimne.upc.edu rrossi@cimne.upc.edu - CIMNE (International Center for Numerical Methods in Engineering), Gran Capita' s/n, 08034 Barcelona, Spain 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 condition: Distribution of this code for any commercial purpose is permissible ONLY BY DIRECT ARRANGEMENT WITH THE COPYRIGHT OWNERS. 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. ============================================================================== */ // // Project Name: Kratos // Last Modified by: $Author: rrossi $ // Date: $Date: 2009-01-15 11:11:35 $ // Revision: $Revision: 1.6 $ // // #if !defined(KRATOS_METIS_PARTITIONING_PROCESS_INCLUDED ) #define KRATOS_METIS_PARTITIONING_PROCESS_INCLUDED // System includes #include <string> #include <iostream> #include <algorithm> #include <fstream> // External includes #include <parmetis.h> // Project includes #include "includes/define.h" #include "processes/process.h" #include "includes/node.h" #include "includes/element.h" #include "includes/model_part.h" extern "C" { //extern void METIS_PartMeshDual(int*, int*, idxtype*, int*, int*, int*, int*, idxtype*, idxtype*); extern int METIS_PartMeshDual(int*, int*, int*, int*, int*, int*, int*, int*, int*); }; namespace Kratos { ///@name Kratos Globals ///@{ ///@} ///@name Type Definitions ///@{ ///@} ///@name Enum's ///@{ ///@} ///@name Functions ///@{ ///@} ///@name Kratos Classes ///@{ /// Short class definition. /** Detail class definition. */ class MetisPartitioningProcess : public Process { public: ///@name Type Definitions ///@{ /// Pointer definition of MetisPartitioningProcess KRATOS_CLASS_POINTER_DEFINITION(MetisPartitioningProcess); typedef std::size_t SizeType; typedef std::size_t IndexType; typedef matrix<int> GraphType; ///@} ///@name Life Cycle ///@{ /// Default constructor. MetisPartitioningProcess(ModelPart& model_part, IO& rIO, SizeType NumberOfPartitions, int Dimension = 3) : mrModelPart(model_part), mrIO(rIO), mNumberOfPartitions(NumberOfPartitions), mDimension(Dimension) { KRATOS_TRY int rank = GetRank(); std::stringstream log_filename; log_filename << "kratos_metis_" << rank << ".log"; mLogFile.open(log_filename.str().c_str()); KRATOS_CATCH("") } /// Copy constructor. MetisPartitioningProcess(MetisPartitioningProcess const& rOther) : mrModelPart(rOther.mrModelPart), mrIO(rOther.mrIO), mNumberOfPartitions(rOther.mNumberOfPartitions), mDimension(rOther.mDimension) { KRATOS_TRY int rank = GetRank(); std::stringstream log_filename; log_filename << "kratos_metis_" << rank << ".log"; mLogFile.open(log_filename.str().c_str()); KRATOS_CATCH("") } /// Destructor. virtual ~MetisPartitioningProcess() { } ///@} ///@name Operators ///@{ void operator()() { Execute(); } ///@} ///@name Operations ///@{ virtual void Execute() { KRATOS_TRY; int number_of_processes; MPI_Comm_size (MPI_COMM_WORLD,&number_of_processes); // if mNumberOfPartitions is not defined we set it to the number_of_processes if (mNumberOfPartitions == 0) mNumberOfPartitions = static_cast<SizeType>(number_of_processes); KRATOS_WATCH(mNumberOfPartitions); int rank = GetRank(); // Reading connectivities IO::ConnectivitiesContainerType elements_connectivities; int number_of_elements = mrIO.ReadElementsConnectivities(elements_connectivities); mLogFile << rank << " :Reading nodes" << std::endl; ModelPart::NodesContainerType temp_nodes; mrIO.ReadNodes(temp_nodes); int number_of_nodes = temp_nodes.size(); // considering sequencial numbering!! idxtype* epart = new idxtype[number_of_elements]; idxtype* npart = new idxtype[number_of_nodes]; GraphType domains_graph = ZeroMatrix(mNumberOfPartitions, mNumberOfPartitions); GraphType domains_colored_graph; int* coloring_send_buffer; // Adding interface meshes mrModelPart.GetMeshes().push_back(ModelPart::MeshType()); int colors_number; if(rank == 0) { CallingMetis(number_of_nodes, number_of_elements, elements_connectivities, npart, epart); CalculateDomainsGraph(domains_graph, number_of_elements, elements_connectivities, npart, epart); colors_number = GraphColoring(domains_graph, domains_colored_graph); KRATOS_WATCH(colors_number); KRATOS_WATCH(domains_colored_graph); // Filling the sending buffer int buffer_index = 0; coloring_send_buffer = new int[mNumberOfPartitions*colors_number]; for(unsigned int i = 0 ; i < mNumberOfPartitions ; i++) for(int j = 0 ; j < colors_number ; j++) coloring_send_buffer[buffer_index++] = domains_colored_graph(i,j); mLogFile << rank << " : colors_number = " << colors_number << std::endl; mLogFile << rank << " : coloring_send_buffer = ["; for(int j = 0 ; j < mNumberOfPartitions*colors_number ; j++) mLogFile << coloring_send_buffer[j] << " ,"; mLogFile << "]" << std::endl; } // Broadcasting partioning information MPI_Bcast(&colors_number, 1, MPI_INT, 0, MPI_COMM_WORLD); MPI_Bcast(npart, number_of_nodes, MPI_INT, 0, MPI_COMM_WORLD); MPI_Bcast(epart, number_of_elements, MPI_INT, 0, MPI_COMM_WORLD); /* vector<int> neighbours_indices(colors_number); */ vector<int>& neighbours_indices = mrModelPart[NEIGHBOURS_INDICES]; if(neighbours_indices.size() != static_cast<unsigned int>(colors_number)) neighbours_indices.resize(colors_number,false); for(int i = 0 ; i < colors_number ; i++) neighbours_indices[i] = 0; mLogFile << rank << " : neighbours_indices = ["; for(unsigned int j = 0 ; j < neighbours_indices.size() ; j++) mLogFile << neighbours_indices[j] << " ,"; mLogFile << "]" << std::endl; mLogFile << rank << " : colors_number = " << colors_number << std::endl; MPI_Scatter(coloring_send_buffer,colors_number,MPI_INT,&(neighbours_indices[0]),colors_number,MPI_INT,0,MPI_COMM_WORLD); mLogFile << rank << " : "; for(int j = 0 ; j < colors_number ; j++) mLogFile << mrModelPart[NEIGHBOURS_INDICES][j] << " ,"; mLogFile << "]" << std::endl; // Adding local, ghost and interface meshes to ModelPart if is necessary int number_of_meshes = ModelPart::Kratos_Ownership_Size + colors_number; // (all + local + ghost) + (colors_number for interfaces) if(mrModelPart.GetMeshes().size() < static_cast<unsigned int>(number_of_meshes)) for(int i = mrModelPart.GetMeshes().size() ; i < number_of_meshes ; i++) mrModelPart.GetMeshes().push_back(ModelPart::MeshType()); for(ModelPart::NodeIterator i_node = temp_nodes.begin() ; i_node != temp_nodes.end() ; i_node++) i_node->SetSolutionStepVariablesList(&(mrModelPart.GetNodalSolutionStepVariablesList())); // Adding nodes to modelpart AddingNodes(temp_nodes, number_of_elements, elements_connectivities, npart, epart); mLogFile << rank << " : Start reading Properties " << std::endl; // Adding properties to modelpart mrIO.ReadProperties(mrModelPart.rProperties()); mLogFile << rank << " : End adding Properties " << std::endl; // Adding elements to each partition mesh AddingElements(temp_nodes, npart, epart); // Adding conditions to each partition mesh ModelPart::ConditionsContainerType temp_conditions; AddingConditions(temp_nodes, npart, epart, temp_conditions); mrIO.ReadInitialValues(temp_nodes, mrModelPart.Elements(), temp_conditions); mLogFile << rank << " : start cleaning memory " << std::endl; delete[] epart; delete[] npart; if(rank == 0) { mLogFile << rank << " : deleting coloring_send_buffer " << std::endl; delete[] coloring_send_buffer; } mLogFile << rank << " : cleaning memory Finished" << std::endl; KRATOS_CATCH("") } void CalculateDomainsGraph(GraphType& rDomainsGraph, SizeType NumberOfElements, IO::ConnectivitiesContainerType& ElementsConnectivities, idxtype* NPart, idxtype* EPart ) { for(SizeType i_element = 0 ; i_element < NumberOfElements ; i_element++) for(std::vector<std::size_t>::iterator i_node = ElementsConnectivities[i_element].begin() ; i_node != ElementsConnectivities[i_element].end() ; i_node++) { SizeType node_rank = NPart[*i_node-1]; SizeType element_rank = EPart[i_element]; if(node_rank != element_rank) rDomainsGraph(node_rank, element_rank) = 1; } } int GraphColoring(GraphType& rDomainsGraph, GraphType& rDomainsColoredGraph) { int max_color = 0; // Initializing the coloered graph. -1 means no connection rDomainsColoredGraph = ScalarMatrix(mNumberOfPartitions, mNumberOfPartitions, -1.00); // Start coloring... for(SizeType i = 0 ; i < rDomainsGraph.size1() ; i++) // for each domain for(SizeType j = i + 1 ; j < rDomainsGraph.size2() ; j++) // finding neighbor domains if(rDomainsGraph(i,j) != 0.00) // domain i has interface with domain j for(SizeType color = 0 ; color < rDomainsColoredGraph.size2() ; color++) // finding color if((rDomainsColoredGraph(i,color) == -1.00) && (rDomainsColoredGraph(j,color) == -1.00)) // the first unused color { rDomainsColoredGraph(i,color) = j; rDomainsColoredGraph(j,color) = i; if(max_color < static_cast<int>(color + 1)) max_color = color + 1; break; } return max_color; } ///@} ///@name Access ///@{ ///@} ///@name Inquiry ///@{ ///@} ///@name Input and output ///@{ /// Turn back information as a string. virtual std::string Info() const { return "MetisPartitioningProcess"; } /// Print information about this object. virtual void PrintInfo(std::ostream& rOStream) const { rOStream << "MetisPartitioningProcess"; } /// Print object's data. virtual void PrintData(std::ostream& rOStream) const { } ///@} ///@name Friends ///@{ ///@} protected: ///@name Protected static Member Variables ///@{ ///@} ///@name Protected member Variables ///@{ ///@} ///@name Protected Operators ///@{ ///@} ///@name Protected Operations ///@{ ///@} ///@name Protected Access ///@{ ///@} ///@name Protected Inquiry ///@{ ///@} ///@name Protected LifeCycle ///@{ ///@} private: ///@name Static Member Variables ///@{ ///@} ///@name Member Variables ///@{ ModelPart& mrModelPart; IO& mrIO; SizeType mNumberOfPartitions; std::ofstream mLogFile; SizeType mDimension; ///@} ///@name Private Operators ///@{ int GetRank() { int rank; MPI_Comm_rank(MPI_COMM_WORLD,&rank); return rank; } void CallingMetis(SizeType NumberOfNodes, SizeType NumberOfElements, IO::ConnectivitiesContainerType& ElementsConnectivities, idxtype* NPart, idxtype* EPart) { int rank = GetRank(); // calculating total size of connectivity vector int connectivity_size = 0; for(IO::ConnectivitiesContainerType::iterator i_connectivities = ElementsConnectivities.begin() ; i_connectivities != ElementsConnectivities.end() ; i_connectivities++) connectivity_size += i_connectivities->size(); int number_of_element_nodes = ElementsConnectivities.begin()->size(); // here assuming that all elements are the same!! int ne = NumberOfElements; int nn = NumberOfNodes; int etype; if(number_of_element_nodes == 3) // triangles etype = 1; else if(number_of_element_nodes == 4) // tetrahedra or quadilateral { if(mDimension == 2) // quadilateral etype = 4; else // tetrahedra etype = 2; } else if(number_of_element_nodes == 8) // hexahedra etype = 3; else KRATOS_ERROR(std::invalid_argument, "invalid element type with number of nodes : ", number_of_element_nodes); int numflag = 0; int number_of_partitions = static_cast<int>(mNumberOfPartitions); int edgecut; idxtype* elmnts = new idxtype[connectivity_size]; mLogFile << rank << " : Preparing Data for metis..." << std::endl; int i = 0; // Creating the elmnts array for Metis for(IO::ConnectivitiesContainerType::iterator i_connectivities = ElementsConnectivities.begin() ; i_connectivities != ElementsConnectivities.end() ; i_connectivities++) for(unsigned int j = 0 ; j < i_connectivities->size() ; j++) elmnts[i++] = (*i_connectivities)[j] - 1; // transforming to zero base indexing mLogFile << rank << " : Calling metis..." << std::endl; // Calling Metis to partition METIS_PartMeshDual(&ne, &nn, elmnts, &etype, &numflag, &number_of_partitions, &edgecut, EPart, NPart); mLogFile << rank << " : Metis Finished!!!" << std::endl; mLogFile << rank << " : edgecut = " << edgecut << std::endl; delete[] elmnts; } void AddingNodes(ModelPart::NodesContainerType& AllNodes, SizeType NumberOfElements, IO::ConnectivitiesContainerType& ElementsConnectivities, idxtype* NPart, idxtype* EPart) { int rank = GetRank(); mLogFile << rank << " : Adding nodes to modelpart" << std::endl; // first adding the partition's nodes for(ModelPart::NodeIterator i_node = AllNodes.begin() ; i_node != AllNodes.end() ; i_node++) if(NPart[i_node->Id()-1] == rank) { mrModelPart.AssignNode(*(i_node.base())); mrModelPart.AssignNode(*(i_node.base()), ModelPart::Kratos_Local); i_node->GetSolutionStepValue(PARTITION_INDEX) = rank; } std::vector<int> interface_indices(mNumberOfPartitions, -1); // std::vector<int> interface_indices(mNumberOfPartitions, 10000); vector<int>& neighbours_indices = mrModelPart[NEIGHBOURS_INDICES]; std::vector<int> aux; for(SizeType i = 0 ; i < neighbours_indices.size() ; i++) aux.push_back(neighbours_indices[i]); for(SizeType i = 0 ; i < neighbours_indices.size() ; i++) if(SizeType(neighbours_indices[i]) < interface_indices.size()) interface_indices[neighbours_indices[i]] = i; // what does it happen if otherwise? indeed it will not break the memory like this ... but ... does it do the correct? mLogFile << rank << " : Adding interface nodes to modelpart" << std::endl; // now adding interface nodes which belongs to other partitions for(SizeType i_element = 0 ; i_element < NumberOfElements ; i_element++) if(EPart[i_element] == rank) { for(std::vector<std::size_t>::iterator i_node = ElementsConnectivities[i_element].begin() ; i_node != ElementsConnectivities[i_element].end() ; i_node++) if(NPart[*i_node-1] != rank) { mrModelPart.AssignNode(AllNodes((*i_node))); mrModelPart.AssignNode(AllNodes((*i_node)), ModelPart::Kratos_Ghost); AllNodes((*i_node))->GetSolutionStepValue(PARTITION_INDEX) = NPart[*i_node-1]; mLogFile << rank << " : Adding ghost node # " << AllNodes[(*i_node)] << "with partition index " << AllNodes[(*i_node)].GetSolutionStepValue(PARTITION_INDEX) << " in " << AllNodes((*i_node)) << std::endl; } } else // adding the owened interface nodes { for(std::vector<std::size_t>::iterator i_node = ElementsConnectivities[i_element].begin() ; i_node != ElementsConnectivities[i_element].end() ; i_node++) if(NPart[*i_node-1] == rank) { SizeType mesh_index = interface_indices[EPart[i_element]] + ModelPart::Kratos_Ownership_Size; if(mesh_index > mNumberOfPartitions + ModelPart::Kratos_Ownership_Size) // Means the neighbour domain is not registered!! KRATOS_ERROR(std::logic_error, "Cannot find the neighbour domain : ", EPart[i_element]); mrModelPart.AssignNode(AllNodes((*i_node)), mesh_index); // mLogFile << rank << " : Adding interface node # " << *i_node << std::endl; mLogFile << rank << " : Adding interface node # " << *i_node << " to mesh: " << mesh_index << std::endl; AllNodes((*i_node))->GetSolutionStepValue(PARTITION_INDEX) = rank; // mLogFile << rank << " : Adding interface node # " << AllNodes[(*i_node)] << "with partition index " << AllNodes[(*i_node)].GetSolutionStepValue(PARTITION_INDEX) << " in " << AllNodes((*i_node)) << std::endl; } } mLogFile << rank << " : Nodes added to modelpart" << std::endl; } void AddingElements(ModelPart::NodesContainerType& AllNodes, idxtype* NPart, idxtype* EPart) { int rank = GetRank(); mLogFile << rank << " : Reading elements" << std::endl; ModelPart::ElementsContainerType temp_elements; mrIO.ReadElements(AllNodes, mrModelPart.rProperties(), temp_elements); mLogFile << rank << " : Adding elements to modelpart" << std::endl; idxtype* epart_position = EPart; for(Kratos::ModelPart::ElementIterator i_element = temp_elements.begin() ; i_element != temp_elements.end() ; i_element++) { if(*epart_position == rank) { mrModelPart.AddElement(*(i_element.base())); mrModelPart.AddElement(*(i_element.base()), ModelPart::Kratos_Local); } epart_position++; } mLogFile << rank << " : Elements added" << std::endl; } void AddingConditions(ModelPart::NodesContainerType& AllNodes, idxtype* NPart, idxtype* EPart, ModelPart::ConditionsContainerType& AllConditions) { int rank = GetRank(); mLogFile << rank << " : Reading conditions" << std::endl; mrIO.ReadConditions(AllNodes, mrModelPart.rProperties(), AllConditions); mLogFile << rank << " : Adding conditions to modelpart" << std::endl; for(Kratos::ModelPart::ConditionIterator i_condition = AllConditions.begin() ; i_condition != AllConditions.end() ; i_condition++) { bool is_local = 1; // See if all of the condition nodes are in this partition as a local or even as a ghost // TODO: THIS IS DANGEROUSE AND MAY FAILE DUE TO THE MESH!!! MUST BE CHANGED!! for(ModelPart::ConditionType::GeometryType::iterator i_node = i_condition->GetGeometry().begin() ; i_node != i_condition->GetGeometry().end() ; i_node++) if(mrModelPart.Nodes().find(i_node->Id()) == mrModelPart.Nodes().end()) is_local = 0; if(is_local) { mrModelPart.AddCondition(*(i_condition.base())); mrModelPart.AddCondition(*(i_condition.base()), ModelPart::Kratos_Local); } } mLogFile << rank << " : Conditions added" << std::endl; } ///@} ///@name Private Operations ///@{ ///@} ///@name Private Access ///@{ ///@} ///@name Private Inquiry ///@{ ///@} ///@name Un accessible methods ///@{ /// Assignment operator. MetisPartitioningProcess& operator=(MetisPartitioningProcess const& rOther); /// Copy constructor. //MetisPartitioningProcess(MetisPartitioningProcess const& rOther); ///@} }; // Class MetisPartitioningProcess ///@} ///@name Type Definitions ///@{ ///@} ///@name Input and output ///@{ /// input stream function inline std::istream& operator >> (std::istream& rIStream, MetisPartitioningProcess& rThis); /// output stream function inline std::ostream& operator << (std::ostream& rOStream, const MetisPartitioningProcess& rThis) { rThis.PrintInfo(rOStream); rOStream << std::endl; rThis.PrintData(rOStream); return rOStream; } ///@} } // namespace Kratos. #endif // KRATOS_METIS_PARTITIONING_PROCESS_INCLUDED defined
30.359084
215
0.651666
[ "mesh", "object", "vector" ]
1e3c291f51547300cede1926a0f9fd7323523987
2,373
h
C
src/include/optimizer/statistics/child_stats_deriver.h
weijietong/noisepage
f3da5498b4c47f4a1b468655f1e2432cd33f177e
[ "MIT" ]
1
2020-11-16T12:23:00.000Z
2020-11-16T12:23:00.000Z
src/include/optimizer/statistics/child_stats_deriver.h
weijietong/noisepage
f3da5498b4c47f4a1b468655f1e2432cd33f177e
[ "MIT" ]
null
null
null
src/include/optimizer/statistics/child_stats_deriver.h
weijietong/noisepage
f3da5498b4c47f4a1b468655f1e2432cd33f177e
[ "MIT" ]
null
null
null
#pragma once #include <vector> #include "optimizer/group_expression.h" #include "optimizer/operator_visitor.h" namespace noisepage::parser { class AbstractExpression; } // namespace noisepage::parser namespace noisepage::optimizer { class Memo; /** * Derive child stats that have not yet been calculated for * a logical group expression. */ class ChildStatsDeriver : public OperatorVisitor { public: /** * Derives child statistics for an input logical group expression * @param gexpr Logical Group Expression to derive for * @param required_cols Expressions that derived stats must include * @param memo Memo table * @returns Set indicating what columns require stats */ std::vector<ExprSet> DeriveInputStats(GroupExpression *gexpr, ExprSet required_cols, Memo *memo); /** * Visit for a LogicalQueryDerivedGet * @param op Visiting LogicalQueryDerivedGet */ void Visit(const LogicalQueryDerivedGet *op) override; /** * Visit for a LogicalInnerJoin * @param op Visiting LogicalInnerJoin */ void Visit(const LogicalInnerJoin *op) override; /** * Visit for a LogicalLeftJoin * @param op Visiting LogicalLeftJoin */ void Visit(const LogicalLeftJoin *op) override; /** * Visit for a LogicalRightJoin * @param op Visiting LogicalRightJoin */ void Visit(const LogicalRightJoin *op) override; /** * Visit for a LogicalOuterJoin * @param op Visiting LogicalOuterJoin */ void Visit(const LogicalOuterJoin *op) override; /** * Visit for a LogicalSemiJoin * @param op Visiting LogicalSemiJoin */ void Visit(const LogicalSemiJoin *op) override; /** * Visit for a LogicalAggregateAndGroupBy * @param op Visiting LogicalAggregateAndGroupBy */ void Visit(const LogicalAggregateAndGroupBy *op) override; private: /** * Function to pass down all required_cols_ to output list */ void PassDownRequiredCols(); /** * Function for passing down a single column * @param col Column to passdown */ void PassDownColumn(common::ManagedPointer<parser::AbstractExpression> col); /** * Set of required child stats columns */ ExprSet required_cols_; /** * GroupExpression to derive for */ GroupExpression *gexpr_; /** * Memo */ Memo *memo_; std::vector<ExprSet> output_; }; } // namespace noisepage::optimizer
22.817308
99
0.710493
[ "vector" ]
1e403204acd96a1e7f4f9e33d3a31664eaca4565
3,225
h
C
ace/tao/orbsvcs/IFR_Service/PrimaryKeyDef_i.h
tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective
1b0172cdb78757fd17898503aaf6ce03d940ef28
[ "Apache-1.1" ]
46
2015-12-04T17:12:58.000Z
2022-03-11T04:30:49.000Z
ace/tao/orbsvcs/IFR_Service/PrimaryKeyDef_i.h
tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective
1b0172cdb78757fd17898503aaf6ce03d940ef28
[ "Apache-1.1" ]
null
null
null
ace/tao/orbsvcs/IFR_Service/PrimaryKeyDef_i.h
tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective
1b0172cdb78757fd17898503aaf6ce03d940ef28
[ "Apache-1.1" ]
23
2016-10-24T09:18:14.000Z
2022-02-25T02:11:35.000Z
/* -*- C++ -*- */ // PrimaryKeyDef_i.h,v 1.4 2001/03/30 16:43:23 parsons Exp // ============================================================================ // // = LIBRARY // TAO/orbsvcs/IFR_Service // // = FILENAME // PrimaryKeyDef_i.h // // = DESCRIPTION // PrimaryKeyDef servant class. // // = AUTHOR // Jeff Parsons <parsons@cs.wustl.edu> // // ============================================================================ #ifndef TAO_PRIMARYKEYDEF_I_H #define TAO_PRIMARYKEYDEF_I_H #include "Contained_i.h" #if !defined (ACE_LACKS_PRAGMA_ONCE) # pragma once #endif /* ACE_LACKS_PRAGMA_ONCE */ #if defined(_MSC_VER) #if (_MSC_VER >= 1200) #pragma warning(push) #endif /* _MSC_VER >= 1200 */ #pragma warning(disable:4250) #endif /* _MSC_VER */ class TAO_PrimaryKeyDef_i : public virtual TAO_Contained_i { // = TITLE // TAO_PrimaryKeyDef_i // // = DESCRIPTION // Represents a primary key definition. It refers to a ValueDef // object which contains the actual information about the // primary key. // public: TAO_PrimaryKeyDef_i (TAO_Repository_i *repo, ACE_Configuration_Section_Key section_key); // Constructor virtual ~TAO_PrimaryKeyDef_i (void); // Destructor virtual CORBA::DefinitionKind def_kind ( CORBA::Environment &ACE_TRY_ENV = TAO_default_environment () ) ACE_THROW_SPEC ((CORBA::SystemException)); // Return our definition kind. virtual void destroy ( CORBA::Environment &ACE_TRY_ENV = TAO_default_environment () ) ACE_THROW_SPEC ((CORBA::SystemException)); // Remove the repository entry. virtual void destroy_i ( CORBA::Environment &ACE_TRY_ENV = TAO_default_environment () ) ACE_THROW_SPEC ((CORBA::SystemException)); virtual CORBA_Contained::Description *describe ( CORBA::Environment &ACE_TRY_ENV = TAO_default_environment () ) ACE_THROW_SPEC ((CORBA::SystemException)); // From Contained_i's pure virtual function. virtual CORBA_Contained::Description *describe_i ( CORBA::Environment &ACE_TRY_ENV = TAO_default_environment () ) ACE_THROW_SPEC ((CORBA::SystemException)); // From Contained_i's pure virtual function. virtual CORBA::Boolean is_a ( const char *primary_key_id, CORBA::Environment &ACE_TRY_ENV = TAO_default_environment () ) ACE_THROW_SPEC ((CORBA::SystemException)); CORBA::Boolean is_a_i ( const char *primary_key_id, CORBA::Environment &ACE_TRY_ENV = TAO_default_environment () ) ACE_THROW_SPEC ((CORBA::SystemException)); virtual CORBA_ValueDef_ptr primary_key ( CORBA::Environment &ACE_TRY_ENV = TAO_default_environment () ) ACE_THROW_SPEC ((CORBA::SystemException)); CORBA_ValueDef_ptr primary_key_i ( CORBA::Environment &ACE_TRY_ENV = TAO_default_environment () ) ACE_THROW_SPEC ((CORBA::SystemException)); }; #if defined(_MSC_VER) && (_MSC_VER >= 1200) #pragma warning(pop) #endif /* _MSC_VER */ #endif /* TAO_PRIMARYKEYDEF_I_H */
26.652893
80
0.621395
[ "object" ]
1e43eae8724dda646faeeadf7fd77f090a5d198d
8,771
h
C
kernel/msm-4.14/drivers/gpu/drm/msm/sde_rsc_priv.h
clovadevice/clockplus2
c347c3e1bf20dbb93ab533c58c2ce11367aa80cd
[ "Apache-2.0" ]
null
null
null
kernel/msm-4.14/drivers/gpu/drm/msm/sde_rsc_priv.h
clovadevice/clockplus2
c347c3e1bf20dbb93ab533c58c2ce11367aa80cd
[ "Apache-2.0" ]
null
null
null
kernel/msm-4.14/drivers/gpu/drm/msm/sde_rsc_priv.h
clovadevice/clockplus2
c347c3e1bf20dbb93ab533c58c2ce11367aa80cd
[ "Apache-2.0" ]
null
null
null
/* Copyright (c) 2016-2020, The Linux Foundation. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 and * only version 2 as published by the Free Software Foundation. * * 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 * GNU General Public License for more details. * */ #ifndef _SDE_RSC_PRIV_H_ #define _SDE_RSC_PRIV_H_ #include <linux/kernel.h> #include <linux/sde_io_util.h> #include <linux/sde_rsc.h> #include <soc/qcom/tcs.h> #include "sde_power_handle.h" #define SDE_RSC_COMPATIBLE "disp_rscc" #define MAX_RSC_COUNT 5 #define ALL_MODES_DISABLED 0x0 #define ONLY_MODE_0_ENABLED 0x1 #define ONLY_MODE_0_1_ENABLED 0x3 #define ALL_MODES_ENABLED 0x7 #define MAX_COUNT_SIZE_SUPPORTED 128 struct sde_rsc_priv; /** * rsc_mode_req: sde rsc mode request information * MODE_READ: read vsync status * MODE_UPDATE: mode timeslot update * 0x0: all modes are disabled. * 0x1: Mode-0 is enabled and other two modes are disabled. * 0x3: Mode-0 & Mode-1 are enabled and mode-2 is disabled. * 0x7: all modes are enabled. */ enum rsc_mode_req { MODE_READ, MODE_UPDATE = 0x1, }; /** * rsc_vsync_req: sde rsc vsync request information * VSYNC_READ: read vsync status * VSYNC_READ_VSYNC0: read value vsync0 timestamp (cast to int from u32) * VSYNC_ENABLE: enable rsc wrapper vsync status * VSYNC_DISABLE: disable rsc wrapper vsync status */ enum rsc_vsync_req { VSYNC_READ, VSYNC_READ_VSYNC0, VSYNC_ENABLE, VSYNC_DISABLE, }; /** * struct sde_rsc_hw_ops - sde resource state coordinator hardware ops * @init: Initialize the sequencer, solver, qtimer, etc. hardware blocks on RSC. * @timer_update: update the static wrapper time and pdc/rsc backoff time. * @tcs_wait: Waits for TCS block OK to allow sending a * TCS command. * @hw_vsync: Enables the vsync on RSC block. * @tcs_use_ok: set TCS set to high to allow RSC to use it. * @bwi_status: It updates the BW increase/decrease status. * @is_amc_mode: Check current amc mode status * @debug_dump: dump debug bus registers or enable debug bus * @state_update: Enable/override the solver based on rsc state * status (command/video) * @mode_show: shows current mode status, mode0/1/2 * @debug_show: Show current debug status. */ struct sde_rsc_hw_ops { int (*init)(struct sde_rsc_priv *rsc); int (*timer_update)(struct sde_rsc_priv *rsc); int (*tcs_wait)(struct sde_rsc_priv *rsc); int (*hw_vsync)(struct sde_rsc_priv *rsc, enum rsc_vsync_req request, char *buffer, int buffer_size, u32 mode); int (*tcs_use_ok)(struct sde_rsc_priv *rsc); int (*bwi_status)(struct sde_rsc_priv *rsc, bool bw_indication); bool (*is_amc_mode)(struct sde_rsc_priv *rsc); void (*debug_dump)(struct sde_rsc_priv *rsc, u32 mux_sel); int (*state_update)(struct sde_rsc_priv *rsc, enum sde_rsc_state state); int (*debug_show)(struct seq_file *s, struct sde_rsc_priv *rsc); int (*mode_ctrl)(struct sde_rsc_priv *rsc, enum rsc_mode_req request, char *buffer, int buffer_size, u32 mode); }; /** * struct sde_rsc_timer_config: this is internal configuration between * rsc and rsc_hw API. * * @static_wakeup_time_ns: wrapper backoff time in nano seconds * @rsc_backoff_time_ns: rsc backoff time in nano seconds * @pdc_backoff_time_ns: pdc backoff time in nano seconds * @rsc_mode_threshold_time_ns: rsc mode threshold time in nano seconds * @rsc_time_slot_0_ns: mode-0 time slot threshold in nano seconds * @rsc_time_slot_1_ns: mode-1 time slot threshold in nano seconds * @rsc_time_slot_2_ns: mode-2 time slot threshold in nano seconds * * @min_threshold_time_ns: minimum time required to enter & exit mode0 * @bwi_threshold_time_ns: worst case time to increase the BW vote */ struct sde_rsc_timer_config { u32 static_wakeup_time_ns; u32 rsc_backoff_time_ns; u32 pdc_backoff_time_ns; u32 rsc_mode_threshold_time_ns; u32 rsc_time_slot_0_ns; u32 rsc_time_slot_1_ns; u32 rsc_time_slot_2_ns; u32 min_threshold_time_ns; u32 bwi_threshold_time_ns; }; struct sde_rsc_state_switch_ops { int (*switch_to_idle)(struct sde_rsc_priv *rsc, struct sde_rsc_cmd_config *config, struct sde_rsc_client *caller_client, int *wait_vblank_crtc_id); int (*switch_to_vid)(struct sde_rsc_priv *rsc, struct sde_rsc_cmd_config *config, struct sde_rsc_client *caller_client, int *wait_vblank_crtc_id); int (*switch_to_cmd)(struct sde_rsc_priv *rsc, struct sde_rsc_cmd_config *config, struct sde_rsc_client *caller_client, int *wait_vblank_crtc_id); int (*switch_to_clk)(struct sde_rsc_priv *rsc, int *wait_vblank_crtc_id); }; /** * struct sde_rsc_bw_config: bandwidth configuration * * @ab_vote: Stored ab_vote for SDE_POWER_HANDLE_DBUS_ID_MAX * @ib_vote: Stored ib_vote for SDE_POWER_HANDLE_DBUS_ID_MAX * @new_ab_vote: ab_vote for incoming frame. * @new_ib_vote: ib_vote for incoming frame. */ struct sde_rsc_bw_config { u64 ab_vote[SDE_POWER_HANDLE_DBUS_ID_MAX]; u64 ib_vote[SDE_POWER_HANDLE_DBUS_ID_MAX]; u64 new_ab_vote[SDE_POWER_HANDLE_DBUS_ID_MAX]; u64 new_ib_vote[SDE_POWER_HANDLE_DBUS_ID_MAX]; }; /** * struct sde_rsc_priv: sde resource state coordinator(rsc) private handle * @version: rsc sequence version * @phandle: module power handle for clocks * @pclient: module power client of phandle * @fs: "MDSS GDSC" handle * @sw_fs_enabled: track "MDSS GDSC" sw vote during probe * @need_hwinit: rsc hw init is required for the next update * * @disp_rsc: display rsc handle * @drv_io: sde drv io data mapping * @wrapper_io: wrapper io data mapping * * @client_list: current rsc client list handle * @event_list: current rsc event list handle * @client_lock: current rsc client synchronization lock * * timer_config: current rsc timer configuration * cmd_config: current panel config * current_state: current rsc state (video/command), solver * override/enabled. * vsync_source: Interface index to provide the vsync ticks * debug_mode: enables the logging for each register read/write * debugfs_root: debugfs file system root node * * hw_ops: sde rsc hardware operations * power_collapse: if all clients are in IDLE state then it enters in * mode2 state and enable the power collapse state * power_collapse_block:By default, rsc move to mode-2 if all clients are in * invalid state. It can be blocked by this boolean entry. * primary_client: A client which is allowed to make command state request * and ab/ib vote on display rsc * single_tcs_execution_time: worst case time to execute one tcs vote * (sleep/wake) * backoff_time_ns: time to only wake tcs in any mode * mode_threshold_time_ns: time to wake TCS in mode-0, must be greater than * backoff time * time_slot_0_ns: time for sleep & wake TCS in mode-1 * master_drm: Primary client waits for vsync on this drm object based * on crtc id * rsc_vsync_wait: Refcount to indicate if we have to wait for the vsync. * rsc_vsync_waitq: Queue to wait for the vsync. * bw_config: check sde_rsc_bw_config structure description. */ struct sde_rsc_priv { u32 version; struct sde_power_handle phandle; struct sde_power_client *pclient; struct regulator *fs; bool sw_fs_enabled; bool need_hwinit; struct rpmh_client *disp_rsc; struct dss_io_data drv_io; struct dss_io_data wrapper_io; struct list_head client_list; struct list_head event_list; struct mutex client_lock; struct sde_rsc_timer_config timer_config; struct sde_rsc_cmd_config cmd_config; u32 current_state; u32 vsync_source; struct sde_rsc_state_switch_ops state_ops; u32 debug_mode; struct dentry *debugfs_root; struct sde_rsc_hw_ops hw_ops; bool power_collapse; bool power_collapse_block; struct sde_rsc_client *primary_client; u32 single_tcs_execution_time; u32 backoff_time_ns; u32 mode_threshold_time_ns; u32 time_slot_0_ns; struct drm_device *master_drm; atomic_t rsc_vsync_wait; wait_queue_head_t rsc_vsync_waitq; struct sde_rsc_bw_config bw_config; }; /** * sde_rsc_hw_register() - register hardware API. It manages V1 and V2 support. * * @client: Client pointer provided by sde_rsc_client_create(). * * Return: error code. */ int sde_rsc_hw_register(struct sde_rsc_priv *rsc); /** * sde_rsc_hw_register_v3() - register hardware API. It manages V3 support. * * @client: Client pointer provided by sde_rsc_client_create(). * * Return: error code. */ int sde_rsc_hw_register_v3(struct sde_rsc_priv *rsc); #endif /* _SDE_RSC_PRIV_H_ */
32.973684
79
0.757838
[ "object" ]
1e4800cbad9aabec505741932cc084bfedd9058c
5,741
h
C
src/camera.h
crazyBaboon/MathWorlds
dd35e88e207a26be8632999ad09eeef81820343d
[ "CC-BY-4.0" ]
1
2018-03-01T13:03:01.000Z
2018-03-01T13:03:01.000Z
src/camera.h
crazyBaboon/MathWorlds
dd35e88e207a26be8632999ad09eeef81820343d
[ "CC-BY-4.0" ]
null
null
null
src/camera.h
crazyBaboon/MathWorlds
dd35e88e207a26be8632999ad09eeef81820343d
[ "CC-BY-4.0" ]
null
null
null
/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. 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 GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef CAMERA_HEADER #define CAMERA_HEADER #include "irrlichttypes_extrabloated.h" #include "inventory.h" #include "mesh.h" #include "client/tile.h" #include "util/numeric.h" #include <ICameraSceneNode.h> #include <ISceneNode.h> #include <list> #include "client.h" class LocalPlayer; struct MapDrawControl; class Client; class WieldMeshSceneNode; struct Nametag { Nametag(scene::ISceneNode *a_parent_node, const std::string &a_nametag_text, const video::SColor &a_nametag_color): parent_node(a_parent_node), nametag_text(a_nametag_text), nametag_color(a_nametag_color) { } scene::ISceneNode *parent_node; std::string nametag_text; video::SColor nametag_color; }; enum CameraMode {CAMERA_MODE_FIRST, CAMERA_MODE_THIRD, CAMERA_MODE_THIRD_FRONT}; /* Client camera class, manages the player and camera scene nodes, the viewing distance and performs view bobbing etc. It also displays the wielded tool in front of the first-person camera. */ class Camera { public: Camera(scene::ISceneManager* smgr, MapDrawControl& draw_control, Client *client); ~Camera(); // Get camera scene node. // It has the eye transformation, pitch and view bobbing applied. inline scene::ICameraSceneNode* getCameraNode() const { return m_cameranode; } // Get the camera position (in absolute scene coordinates). // This has view bobbing applied. inline v3f getPosition() const { return m_camera_position; } // Get the camera direction (in absolute camera coordinates). // This has view bobbing applied. inline v3f getDirection() const { return m_camera_direction; } // Get the camera offset inline v3s16 getOffset() const { return m_camera_offset; } // Horizontal field of view inline f32 getFovX() const { return m_fov_x; } // Vertical field of view inline f32 getFovY() const { return m_fov_y; } // Get maximum of getFovX() and getFovY() inline f32 getFovMax() const { return MYMAX(m_fov_x, m_fov_y); } // Checks if the constructor was able to create the scene nodes bool successfullyCreated(std::string &error_message); // Step the camera: updates the viewing range and view bobbing. void step(f32 dtime); // Update the camera from the local player's position. // busytime is used to adjust the viewing range. void update(LocalPlayer* player, f32 frametime, f32 busytime, f32 tool_reload_ratio, ClientEnvironment &c_env); // Update render distance void updateViewingRange(); // Start digging animation // Pass 0 for left click, 1 for right click void setDigging(s32 button); // Replace the wielded item mesh void wield(const ItemStack &item); // Draw the wielded tool. // This has to happen *after* the main scene is drawn. // Warning: This clears the Z buffer. void drawWieldedTool(irr::core::matrix4* translation=NULL); // Toggle the current camera mode void toggleCameraMode() { if (m_camera_mode == CAMERA_MODE_FIRST) m_camera_mode = CAMERA_MODE_THIRD; else if (m_camera_mode == CAMERA_MODE_THIRD) m_camera_mode = CAMERA_MODE_THIRD_FRONT; else m_camera_mode = CAMERA_MODE_FIRST; } // Set the current camera mode inline void setCameraMode(CameraMode mode) { m_camera_mode = mode; } //read the current camera mode inline CameraMode getCameraMode() { return m_camera_mode; } Nametag *addNametag(scene::ISceneNode *parent_node, std::string nametag_text, video::SColor nametag_color); void removeNametag(Nametag *nametag); const std::list<Nametag *> &getNametags() { return m_nametags; } void drawNametags(); private: // Nodes scene::ISceneNode* m_playernode; scene::ISceneNode* m_headnode; scene::ICameraSceneNode* m_cameranode; scene::ISceneManager* m_wieldmgr; WieldMeshSceneNode* m_wieldnode; // draw control MapDrawControl& m_draw_control; Client *m_client; video::IVideoDriver *m_driver; // Absolute camera position v3f m_camera_position; // Absolute camera direction v3f m_camera_direction; // Camera offset v3s16 m_camera_offset; // Field of view and aspect ratio stuff f32 m_aspect; f32 m_fov_x; f32 m_fov_y; // View bobbing animation frame (0 <= m_view_bobbing_anim < 1) f32 m_view_bobbing_anim; // If 0, view bobbing is off (e.g. player is standing). // If 1, view bobbing is on (player is walking). // If 2, view bobbing is getting switched off. s32 m_view_bobbing_state; // Speed of view bobbing animation f32 m_view_bobbing_speed; // Fall view bobbing f32 m_view_bobbing_fall; // Digging animation frame (0 <= m_digging_anim < 1) f32 m_digging_anim; // If -1, no digging animation // If 0, left-click digging animation // If 1, right-click digging animation s32 m_digging_button; // Animation when changing wielded item f32 m_wield_change_timer; ItemStack m_wield_item_next; CameraMode m_camera_mode; f32 m_cache_fall_bobbing_amount; f32 m_cache_view_bobbing_amount; f32 m_cache_fov; f32 m_cache_zoom_fov; std::list<Nametag *> m_nametags; }; #endif
25.069869
85
0.755443
[ "mesh", "render" ]
1e58235718283ce264911f8d4efcf9149a442112
3,260
h
C
lib/veins/src/veins/modules/utility/BBoxLookup.h
dbuse/reception-study
f60cfec0312c0de81721c627b2ebfd97faf9cfa7
[ "MIT" ]
null
null
null
lib/veins/src/veins/modules/utility/BBoxLookup.h
dbuse/reception-study
f60cfec0312c0de81721c627b2ebfd97faf9cfa7
[ "MIT" ]
null
null
null
lib/veins/src/veins/modules/utility/BBoxLookup.h
dbuse/reception-study
f60cfec0312c0de81721c627b2ebfd97faf9cfa7
[ "MIT" ]
null
null
null
// // Copyright (C) 2019 Dominik S. Buse <buse@ccs-labs.org> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program 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 2 of the License, or // (at your option) any later version. // // 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 // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #pragma once #include <algorithm> #include <functional> #include <vector> #include "veins/veins.h" namespace veins { class Obstacle; /** * Fast grid-based spatial datastructure to find obstacles (geometric shapes) in a bounding box. * * Stores bounding boxes for a set of obstacles and allows searching for them via another bounding box. * * Only considers a 2-dimensional plane (x and y coordinates). * * In principle, any kind (or implementation) of a obstacle/shape/polygon is possible. * There only has to be a function to derive a bounding box for a given obstacle. * Obstacle instances are stored as pointers, so the lifetime of the obstacle instances is not managed by this class. */ class VEINS_API BBoxLookup { public: struct Point { double x; double y; }; // array of stucts approach // cache line size: 64byte = 8 x 8-byte double = 2 bboxes per line // bbox coordinates are inherently local, if i check x1, i likely also check the other struct Box { Point p1; Point p2; }; struct BBoxCell { size_t index; /**< index of the first element of this cell in bboxes */ size_t count; /**< number of elements in this cell; index + number = index of last element */ }; BBoxLookup() = default; BBoxLookup(const std::vector<Obstacle*>& obstacles, std::function<BBoxLookup::Box(Obstacle*)> makeBBox, double scenarioX, double scenarioY, int cellSize = 250); /** * Return all obstacles which have their bounding box touched by the transmission from sender to receiver. * * The obstacles itself may not actually overlap with transmission (false positives are possible). */ std::vector<Obstacle*> findOverlapping(Point sender, Point receiver) const; private: // NOTE: obstacles may occur multiple times in bboxes/obstacleLookup (if they are in multiple cells) std::vector<Box> bboxes; /**< ALL bboxes in one chunck of contiguos memory, ordered by cells */ std::vector<Obstacle*> obstacleLookup; /**< bboxes[i] belongs to instance in obstacleLookup[i] */ std::vector<BBoxCell> bboxCells; /**< flattened matrix of X * Y BBoxCell instances */ int cellSize = 0; size_t numCols = 0; /**< X BBoxCell instances in a row */ size_t numRows = 0; /**< Y BBoxCell instances in a column */ }; } // namespace veins
38.352941
164
0.705215
[ "shape", "vector" ]
1e58c5317fbd1716dcc7edbafc1bb8d1e7b92231
13,746
c
C
std/spell_vend.c
Dbevan/SunderingShadows
6c15ec56cef43c36361899bae6dc08d0ee907304
[ "MIT" ]
9
2021-07-05T15:24:54.000Z
2022-02-25T19:44:15.000Z
std/spell_vend.c
Dbevan/SunderingShadows
6c15ec56cef43c36361899bae6dc08d0ee907304
[ "MIT" ]
4
2021-03-15T18:56:39.000Z
2021-08-17T17:08:22.000Z
std/spell_vend.c
Dbevan/SunderingShadows
6c15ec56cef43c36361899bae6dc08d0ee907304
[ "MIT" ]
10
2021-03-13T00:18:03.000Z
2022-03-29T15:02:42.000Z
//Added a check for move ok to stop items being lost in the void. Circe 12/14/03 //Last change was August 24, 2003 // /std/spell_vend.c // a standard object that sells spells in shops // created by Vashkar@ShadowGate by modifying /std/comp_vend.c // which was created by Melnmarn@ShadowGate // Note from Tristan@shadowgate Made to work // Gratuitous shit code doesn't describe this crap // The comp_vend was okay but this spell_vend is pure shit #include <std.h> #include <money.h> #include <daemons.h> #include <move.h> #define SCROLL_PATH "/d/magic/scroll" #define LINE "%^BOLD%^%^BLUE%^-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-%^RESET%^\n" #define BACKUP_DIR "/d/save/spellbook/backup_books" #define SAVE_DIR "/d/save/spellbook/save" inherit MONSTER; string *Available, tmpstr; int number; mapping spellnames, backing; mixed sort_items(object one, object two); int set_spells_sold(mapping map); int has_comp_bag(object targ); void create() { ::create(); } void set_name(string str) { ::set_name(str); if(file_exists(SAVE_DIR+"/"+query_name()+".spell_seller.o") ) restore_object(SAVE_DIR+"/"+query_name()+".spell_seller"); if(!backing) backing = ([]); } void init() { ::init(); add_action("__Buy", "buy"); add_action("__List", "list"); add_action("__Help", "help"); add_action("__Pickup", "pickup"); add_action("__Sell","sell"); add_action("__Check","check"); } int __Pickup(string str){ int i,j,k,l; string *bdspell = ({}); object tmpbook; string *spells; mapping newlist = ([]); if(member_array(str,({ "book","spell book","spellbook"})) != -1){ if(member_array(TPQN,keys(backing)) == -1) return notify_fail("You didn't leave a spell book here!\n"); if(time() - backing[TPQN] > 1){ if(time() - backing[TPQN] < 200){ write("%^ORANGE%^I just started copying the book, it takes me about twenty minutes to copy a spell book."); return 1; } if(time() - backing[TPQN] < 600){ write("%^ORANGE%^I'm not even halfway done with copying the book, come back later."); return 1; } if(time() - backing[TPQN] < 1000){ write("%^ORANGE%^I have most of the book copied, give me a bit more time..."); return 1; } if(time() - backing[TPQN] < 1200){ write("%^ORANGE%^Almost done...almost done..."); return 1; } write("%^ORANGE%^"+query_cap_name()+" hands you your spellbook!"); } map_delete(backing, TPQN); save_object(SAVE_DIR+"/"+query_name()+".spell_seller"); tmpbook=new("/d/magic/spellbook"); tmpbook->restore_me(BACKUP_DIR+"/"+TPQN+"_"+query_name()+".backup"); if((int)(tmpbook->move(TP))!=MOVE_OK){ write("%^MAGENTA%^"+TO->query_name()+" says%^RESET%^: You can't carry your book, I will drop it on the floor."); tmpbook->move(ETP); } write("%^MAGENTA%^"+TO->query_name()+" says%^RESET%^: Here is your spell book back, come back any time to pick up the backup of it.\n"); return 1; } if(member_array(str,({ "backup","back up"})) != -1){ if(backing[TPQN]) return notify_fail("You must pick up your original spellbook first!\n"); if(!file_exists(BACKUP_DIR+"/"+TPQN+"_"+query_name()+".backup.o")) return notify_fail("You never made a backup of your spell book!\n"); tmpbook=new("/d/magic/spellbook"); tmpbook->restore_me(BACKUP_DIR+"/"+TPQN+"_"+query_name()+".backup"); spells = tmpbook->query_spells(); i = sizeof(spells); j = random(i); for(l= 0;l<j;l++){ k = random(i); bdspell += ({spells[k]}); } spells -= ({bdspell}); j = sizeof(spells); for(i=0;i<j;i++){ k = tmpbook->query_spellbook(spells[i]); newlist[spells[i]]=k; } tmpbook->set_spells(newlist); write("You notice that the book looks much thinner!"); if((int)(tmpbook->move(TP))!=MOVE_OK){ write("%^MAGENTA%^"+TO->query_name()+" says%^RESET%^: You can't carry your book, I will drop it on the floor."); tmpbook->move(ETP); } tmpbook->resetdesc(); rm(BACKUP_DIR+"/"+TPQN+"_"+query_name()+".backup.o"); write("Here is your backup copy of the spell book, enjoy!"); return 1; } return notify_fail("Pickup what?\n"); } int __Buy(mixed str){ object ob, newbook, newbag; string magetype; int pgold,cost, success; if(!str) return notify_fail("%^BOLD%^Syntax: buy <itemname> or <itemnumber>\n"); if(!TP->is_class("mage") && !TP->is_class("bard") && !TP->is_class("sorcerer")) return notify_fail("Sorry, I sell nothing to non-magi such as yourself."); if(member_array(str,({"book","spellbook","spell book"})) != -1){ if(!TP->query_funds("gold",100)){ write("%^RED%^You don't have enough money to buy a new spellbook!"); return 1; } TP->use_funds("gold",100); magetype=MAGIC_D->query_title(TP); write("%^CYAN%^Here is a spellbook fit for a "+magetype+" like yourself."); newbook = new("/d/magic/spellbook"); //added move code Circe 12/14/03 if (newbook->move(TP) != MOVE_OK){ newbook->move(ETP); write("%^MAGENTA%^"+TO->query_name()+" says%^RESET%^: You can't carry your book, I will drop it on the floor."); } return 1; } if(str == "backup"){ write("%^RED%^Buy a backup of what?"); return 1; } tmpstr = 0; if(!sscanf(str,"backup of %s",tmpstr)) sscanf(str,"back up of %s",tmpstr); if(tmpstr && tmpstr != ""){ if(!TP->query_funds("gold",2000)){ write("%^RED%^You don't have enough gold to buy a backup copy of your spell book!"); return 1; } if(!ob=present(tmpstr,TP)){ write("%^RED%^You don't have a "+tmpstr+" to make a copy of!"); return 1; } if(!ob->is_spellbook()){ write("%^RED%^That's not a spell book!"); return 1; } TP->use_funds("gold",2000); write("%^GREEN%^You relinquish your book to "+query_cap_name()+".\n%^MAGENTA%^"+query_cap_name()+"%^RESET%^: I will have your spell book copied in twenty minutes. Come back then to <pickup spell book>"); ob->save_me(BACKUP_DIR+"/"+TPQN+"_"+query_name()+".backup"); ob->save_me("/d/save/spellbook/save_books/"+TPQN+"_"+query_name()+".backup"); ob->remove(); backing += ([ TPQN : time() ]); save_object(SAVE_DIR+"/"+query_name()+".spell_seller"); return 1; } if(member_array(str,({"bag","component bag", "components bag","spell components bag", "spell component bag"})) != -1){ if(!TP->query_funds("gold",10)){ write("%^RED%^You don't have enough gold to buy a new components bag!"); return 1; } /* if(has_comp_bag(TP)) { write("%^RED%^You already have one of those, you don't need two."); return 1; } */ TP->use_funds("gold",10); write("%^CYAN%^Here is your components bag."); newbag = new("/d/magic/comp_bag"); //added move code Circe 12/14/03 if (newbag->move(TP) != MOVE_OK){ newbag->move(ETP); write("You can't carry your bag, I will drop it on the floor."); } return 1; } if(!sscanf(str,"%d",number)){ if(member_array(str,Available) == -1) return notify_fail("Sorry, I'm not selling any spells of "+str+".\n"); else{ number = member_array(str,Available); } } if (number > ( sizeof(Available) - 1)) return notify_fail("There is no spell number %^BOLD%^"+number+".\n"); cost = spellnames[Available[number]]; pgold = (int)TP->query_exp(); if(pgold < cost) { write("%^RED%^You don't have enough experience points to buy the spell of "+Available[number]+"'s!"); return 1; } if((int)TP->set_XP_tax(cost, 0, "improvement") == -1) { TP->add_exp(-1 * cost); } TP->resetLevelForExp(0); tell_object(TP,"%^RED%^Subtracting "+cost+" experience points.%^RESET%^"); write("%^CYAN%^Here is a scroll with the magical text of %^YELLOW%^"+Available[number]+"%^CYAN%^ written upon it."); ob = new(SCROLL_PATH); ob->set_spell_name(Available[number]); if((int)(ob->move(TP))!=MOVE_OK){ write("%^MAGENTA%^"+TO->query_name()+" says%^RESET%^: You can't carry the scroll, I will drop it on the floor."); ob->move(ETP); return 1; } return 1; } int __List(string str){ string bigstring; int inc,lines; lines = to_int(TP->getenv("LINES")); lines -= 2; if(!str) return notify_fail("List what?\n"); if(strsrch(str,"spells") == -1) return notify_fail("I don't sell that!\n"); Available = sort_array(Available,"sort_strings",TO); bigstring = LINE; for(inc = 0; inc < sizeof(Available);inc++){ bigstring += sprintf("%3d: ",inc); bigstring += sprintf("%%^GREEN%%^%-30s %%^YELLOW%%^%9d %%^RESET%%^%%^CYAN%%^experience points\n",capitalize(Available[inc]),spellnames[Available[inc]]); if(((inc+1)%lines == 0) &&(inc > 1)) bigstring += (LINE + LINE); } bigstring += sprintf("%%^GREEN%%^%-30s %%^YELLOW%%^%9d %%^RESET%%^%%^CYAN%%^gold\n","Spell book", 100); bigstring += sprintf("%%^GREEN%%^%-30s %%^YELLOW%%^%9d %%^RESET%%^%%^CYAN%%^gold\n","Components bag", 10); bigstring += sprintf("%%^GREEN%%^%-30s %%^YELLOW%%^%9d %%^RESET%%^%%^CYAN%%^gold\n","Backup", 2000); bigstring += LINE; TP->more(explode(bigstring,"\n")); return 1; } string sort_strings(string one, string two) { return strcmp(one, two); } int set_spells_sold(mapping map) { int inc, temp; string *str; spellnames = map; Available = keys(map); return 1; } string *query_spells() { return Available; } mixed sort_items(object one, object two) { return strcmp(one->query_short(), two->query_short()); } int __Help(string nothing) { if (nothing != "store" && nothing != "shop") return 0; write("%^CYAN%^%^ULINE%^Spell store%^RESET%^ %^ORANGE%^<list spells>%^RESET%^ The list command will list all spells available in this shop. %^ORANGE%^<buy %^ORANGE%^%^ULINE%^SPELL_NAME%^RESET%^%^ORANGE%^|book|backup of book>%^RESET%^ This will let you buy a spell, spell book, or a backup of your spell book that the shopkeeper will hold for you. If you want to buy a spell, you may either enter the number of the spell you want to buy, or its name. e.g. %^ORANGE%^<buy 5>%^RESET%^ will buy spell #5 on the list e.g. %^ORANGE%^<buy magic missile>%^RESET%^ will buy the spell of magic missile %^ORANGE%^<pickup spell book>%^RESET%^ or %^ORANGE%^<pickup backup>%^RESET%^ Get a spell book that you left here to be backed up, or get the backup copy of a book you had backed up in this store. %^ORANGE%^<check backup>%^RESET%^ or %^ORANGE%^<check back up>%^RESET%^ This will check if you have a backup in the shop. %^ORANGE%^<help store>%^RESET%^ Displays this text. "); return 1; } int __Sell(string str){ object ob; int level; if(!str) return 0; if(!ob = present(str,TP)) return notify_fail("You don't have that item.\n"); if(!ob->is_scroll()) return notify_fail("I only buy scrolls.\n"); // was this, changing to use query_value to fix problems with safe scrolls *Styx* 8/24/03 // level = ob->query_spell_level(); // TP->add_money("gold",(level*level)*100); TP->add_money("gold",ob->query_value()); write(query_cap_name()+" takes the scroll and hands you "+ob->query_value()+" gold."); tell_room(ETO,query_cap_name()+" takes a scroll from "+TPQCN+" and hands "+TP->query_objective()+" some money.",TP); ob->remove(); return 1; } int __Check(string str){ if((str != "backup") && (str != "back up")) return 0; if(backing[TPQN]) return notify_fail("Your original spellbook is still in the shop! Pick it up first.\n"); if(!file_exists(BACKUP_DIR+"/"+TPQN+"_"+query_name()+".backup.o")) { tell_object(TP,"%^RED%^You don't have a backup spellbook here!"); return 1; } if(file_exists(BACKUP_DIR+"/"+TPQN+"_"+query_name()+".backup.o")) { tell_object(TP,"%^GREEN%^There is a copy of your spellbook here!"); return 1; } return 0; } int has_comp_bag(object targ){ object *inv; int x; inv = deep_inventory(targ); for(x = 0;x<sizeof(inv);x++) if(inv[x]->id("components bag")) return 1; return 0; } int is_vendor() { return 1; } /** * Generates random spell list from list of all mage spells */ mapping gen_spells_sold(int maxrand) { mapping all_spells, tmp; string *all_spell_names, spellfile; int lvl, i, j, k; object spell; all_spells = MAGIC_D->query_index("mage"); all_spell_names = keys(all_spells); all_spell_names = map_array(all_spell_names, (: MAGIC_D->get_spell_file_name($1):)); // all_spell_names=filter_array(all_spell_names,(:file_exists($1):)); all_spells = ([]); foreach(spellfile in all_spell_names) { if (catch(spell = new(spellfile))) continue; if (lvl = spell->query_spell_level("mage")) if (spell->query_feat_required("mage") == "me" && lvl < 10) all_spells[spell->query_spell_name()] = (2132 * lvl * lvl - 3522 * lvl + 3870 + roll_dice(lvl, 100)); spell->remove(); } tmp = ([]); all_spell_names = keys(all_spells); k = sizeof(all_spell_names); for (i = 1; i < maxrand; i++) { j = random(k); tmp[all_spell_names[j]] = all_spells[all_spell_names[j]]; } return tmp; }
35.427835
219
0.596755
[ "object", "3d" ]
d81ccc2cf52032d25df485a8a29dceb688e967ab
11,145
h
C
3rd/xulrunner-sdk/include/nsIDragSession.h
ShoufuLuo/csaw
0d030d5ab93e61b62dff10b27a15c83fcfce3ff3
[ "Apache-2.0" ]
null
null
null
3rd/xulrunner-sdk/include/nsIDragSession.h
ShoufuLuo/csaw
0d030d5ab93e61b62dff10b27a15c83fcfce3ff3
[ "Apache-2.0" ]
null
null
null
3rd/xulrunner-sdk/include/nsIDragSession.h
ShoufuLuo/csaw
0d030d5ab93e61b62dff10b27a15c83fcfce3ff3
[ "Apache-2.0" ]
null
null
null
/* * DO NOT EDIT. THIS FILE IS GENERATED FROM /builds/slave/rel-m-rel-xr-osx64-bld/build/widget/public/nsIDragSession.idl */ #ifndef __gen_nsIDragSession_h__ #define __gen_nsIDragSession_h__ #ifndef __gen_nsISupports_h__ #include "nsISupports.h" #endif #ifndef __gen_nsISupportsArray_h__ #include "nsISupportsArray.h" #endif #ifndef __gen_nsITransferable_h__ #include "nsITransferable.h" #endif /* For IDL files that don't want to include root IDL files. */ #ifndef NS_NO_VTABLE #define NS_NO_VTABLE #endif #include "nsSize.h" class nsIDOMDocument; /* forward declaration */ class nsIDOMNode; /* forward declaration */ class nsIDOMDataTransfer; /* forward declaration */ /* starting interface: nsIDragSession */ #define NS_IDRAGSESSION_IID_STR "fde41f6a-c710-46f8-a0a8-1ff76ca4ff57" #define NS_IDRAGSESSION_IID \ {0xfde41f6a, 0xc710, 0x46f8, \ { 0xa0, 0xa8, 0x1f, 0xf7, 0x6c, 0xa4, 0xff, 0x57 }} class NS_NO_VTABLE NS_SCRIPTABLE nsIDragSession : public nsISupports { public: NS_DECLARE_STATIC_IID_ACCESSOR(NS_IDRAGSESSION_IID) /* attribute boolean canDrop; */ NS_SCRIPTABLE NS_IMETHOD GetCanDrop(PRBool *aCanDrop) = 0; NS_SCRIPTABLE NS_IMETHOD SetCanDrop(PRBool aCanDrop) = 0; /* attribute boolean onlyChromeDrop; */ NS_SCRIPTABLE NS_IMETHOD GetOnlyChromeDrop(PRBool *aOnlyChromeDrop) = 0; NS_SCRIPTABLE NS_IMETHOD SetOnlyChromeDrop(PRBool aOnlyChromeDrop) = 0; /* attribute unsigned long dragAction; */ NS_SCRIPTABLE NS_IMETHOD GetDragAction(PRUint32 *aDragAction) = 0; NS_SCRIPTABLE NS_IMETHOD SetDragAction(PRUint32 aDragAction) = 0; /* [noscript] attribute nsSize targetSize; */ NS_IMETHOD GetTargetSize(nsSize *aTargetSize) = 0; NS_IMETHOD SetTargetSize(nsSize aTargetSize) = 0; /* readonly attribute unsigned long numDropItems; */ NS_SCRIPTABLE NS_IMETHOD GetNumDropItems(PRUint32 *aNumDropItems) = 0; /* readonly attribute nsIDOMDocument sourceDocument; */ NS_SCRIPTABLE NS_IMETHOD GetSourceDocument(nsIDOMDocument * *aSourceDocument) = 0; /* readonly attribute nsIDOMNode sourceNode; */ NS_SCRIPTABLE NS_IMETHOD GetSourceNode(nsIDOMNode * *aSourceNode) = 0; /* attribute nsIDOMDataTransfer dataTransfer; */ NS_SCRIPTABLE NS_IMETHOD GetDataTransfer(nsIDOMDataTransfer * *aDataTransfer) = 0; NS_SCRIPTABLE NS_IMETHOD SetDataTransfer(nsIDOMDataTransfer *aDataTransfer) = 0; /* void getData (in nsITransferable aTransferable, in unsigned long aItemIndex); */ NS_SCRIPTABLE NS_IMETHOD GetData(nsITransferable *aTransferable, PRUint32 aItemIndex) = 0; /* boolean isDataFlavorSupported (in string aDataFlavor); */ NS_SCRIPTABLE NS_IMETHOD IsDataFlavorSupported(const char * aDataFlavor, PRBool *_retval NS_OUTPARAM) = 0; }; NS_DEFINE_STATIC_IID_ACCESSOR(nsIDragSession, NS_IDRAGSESSION_IID) /* Use this macro when declaring classes that implement this interface. */ #define NS_DECL_NSIDRAGSESSION \ NS_SCRIPTABLE NS_IMETHOD GetCanDrop(PRBool *aCanDrop); \ NS_SCRIPTABLE NS_IMETHOD SetCanDrop(PRBool aCanDrop); \ NS_SCRIPTABLE NS_IMETHOD GetOnlyChromeDrop(PRBool *aOnlyChromeDrop); \ NS_SCRIPTABLE NS_IMETHOD SetOnlyChromeDrop(PRBool aOnlyChromeDrop); \ NS_SCRIPTABLE NS_IMETHOD GetDragAction(PRUint32 *aDragAction); \ NS_SCRIPTABLE NS_IMETHOD SetDragAction(PRUint32 aDragAction); \ NS_IMETHOD GetTargetSize(nsSize *aTargetSize); \ NS_IMETHOD SetTargetSize(nsSize aTargetSize); \ NS_SCRIPTABLE NS_IMETHOD GetNumDropItems(PRUint32 *aNumDropItems); \ NS_SCRIPTABLE NS_IMETHOD GetSourceDocument(nsIDOMDocument * *aSourceDocument); \ NS_SCRIPTABLE NS_IMETHOD GetSourceNode(nsIDOMNode * *aSourceNode); \ NS_SCRIPTABLE NS_IMETHOD GetDataTransfer(nsIDOMDataTransfer * *aDataTransfer); \ NS_SCRIPTABLE NS_IMETHOD SetDataTransfer(nsIDOMDataTransfer *aDataTransfer); \ NS_SCRIPTABLE NS_IMETHOD GetData(nsITransferable *aTransferable, PRUint32 aItemIndex); \ NS_SCRIPTABLE NS_IMETHOD IsDataFlavorSupported(const char * aDataFlavor, PRBool *_retval NS_OUTPARAM); /* Use this macro to declare functions that forward the behavior of this interface to another object. */ #define NS_FORWARD_NSIDRAGSESSION(_to) \ NS_SCRIPTABLE NS_IMETHOD GetCanDrop(PRBool *aCanDrop) { return _to GetCanDrop(aCanDrop); } \ NS_SCRIPTABLE NS_IMETHOD SetCanDrop(PRBool aCanDrop) { return _to SetCanDrop(aCanDrop); } \ NS_SCRIPTABLE NS_IMETHOD GetOnlyChromeDrop(PRBool *aOnlyChromeDrop) { return _to GetOnlyChromeDrop(aOnlyChromeDrop); } \ NS_SCRIPTABLE NS_IMETHOD SetOnlyChromeDrop(PRBool aOnlyChromeDrop) { return _to SetOnlyChromeDrop(aOnlyChromeDrop); } \ NS_SCRIPTABLE NS_IMETHOD GetDragAction(PRUint32 *aDragAction) { return _to GetDragAction(aDragAction); } \ NS_SCRIPTABLE NS_IMETHOD SetDragAction(PRUint32 aDragAction) { return _to SetDragAction(aDragAction); } \ NS_IMETHOD GetTargetSize(nsSize *aTargetSize) { return _to GetTargetSize(aTargetSize); } \ NS_IMETHOD SetTargetSize(nsSize aTargetSize) { return _to SetTargetSize(aTargetSize); } \ NS_SCRIPTABLE NS_IMETHOD GetNumDropItems(PRUint32 *aNumDropItems) { return _to GetNumDropItems(aNumDropItems); } \ NS_SCRIPTABLE NS_IMETHOD GetSourceDocument(nsIDOMDocument * *aSourceDocument) { return _to GetSourceDocument(aSourceDocument); } \ NS_SCRIPTABLE NS_IMETHOD GetSourceNode(nsIDOMNode * *aSourceNode) { return _to GetSourceNode(aSourceNode); } \ NS_SCRIPTABLE NS_IMETHOD GetDataTransfer(nsIDOMDataTransfer * *aDataTransfer) { return _to GetDataTransfer(aDataTransfer); } \ NS_SCRIPTABLE NS_IMETHOD SetDataTransfer(nsIDOMDataTransfer *aDataTransfer) { return _to SetDataTransfer(aDataTransfer); } \ NS_SCRIPTABLE NS_IMETHOD GetData(nsITransferable *aTransferable, PRUint32 aItemIndex) { return _to GetData(aTransferable, aItemIndex); } \ NS_SCRIPTABLE NS_IMETHOD IsDataFlavorSupported(const char * aDataFlavor, PRBool *_retval NS_OUTPARAM) { return _to IsDataFlavorSupported(aDataFlavor, _retval); } /* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */ #define NS_FORWARD_SAFE_NSIDRAGSESSION(_to) \ NS_SCRIPTABLE NS_IMETHOD GetCanDrop(PRBool *aCanDrop) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetCanDrop(aCanDrop); } \ NS_SCRIPTABLE NS_IMETHOD SetCanDrop(PRBool aCanDrop) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetCanDrop(aCanDrop); } \ NS_SCRIPTABLE NS_IMETHOD GetOnlyChromeDrop(PRBool *aOnlyChromeDrop) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetOnlyChromeDrop(aOnlyChromeDrop); } \ NS_SCRIPTABLE NS_IMETHOD SetOnlyChromeDrop(PRBool aOnlyChromeDrop) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetOnlyChromeDrop(aOnlyChromeDrop); } \ NS_SCRIPTABLE NS_IMETHOD GetDragAction(PRUint32 *aDragAction) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetDragAction(aDragAction); } \ NS_SCRIPTABLE NS_IMETHOD SetDragAction(PRUint32 aDragAction) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetDragAction(aDragAction); } \ NS_IMETHOD GetTargetSize(nsSize *aTargetSize) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetTargetSize(aTargetSize); } \ NS_IMETHOD SetTargetSize(nsSize aTargetSize) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetTargetSize(aTargetSize); } \ NS_SCRIPTABLE NS_IMETHOD GetNumDropItems(PRUint32 *aNumDropItems) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetNumDropItems(aNumDropItems); } \ NS_SCRIPTABLE NS_IMETHOD GetSourceDocument(nsIDOMDocument * *aSourceDocument) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetSourceDocument(aSourceDocument); } \ NS_SCRIPTABLE NS_IMETHOD GetSourceNode(nsIDOMNode * *aSourceNode) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetSourceNode(aSourceNode); } \ NS_SCRIPTABLE NS_IMETHOD GetDataTransfer(nsIDOMDataTransfer * *aDataTransfer) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetDataTransfer(aDataTransfer); } \ NS_SCRIPTABLE NS_IMETHOD SetDataTransfer(nsIDOMDataTransfer *aDataTransfer) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetDataTransfer(aDataTransfer); } \ NS_SCRIPTABLE NS_IMETHOD GetData(nsITransferable *aTransferable, PRUint32 aItemIndex) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetData(aTransferable, aItemIndex); } \ NS_SCRIPTABLE NS_IMETHOD IsDataFlavorSupported(const char * aDataFlavor, PRBool *_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->IsDataFlavorSupported(aDataFlavor, _retval); } #if 0 /* Use the code below as a template for the implementation class for this interface. */ /* Header file */ class nsDragSession : public nsIDragSession { public: NS_DECL_ISUPPORTS NS_DECL_NSIDRAGSESSION nsDragSession(); private: ~nsDragSession(); protected: /* additional members */ }; /* Implementation file */ NS_IMPL_ISUPPORTS1(nsDragSession, nsIDragSession) nsDragSession::nsDragSession() { /* member initializers and constructor code */ } nsDragSession::~nsDragSession() { /* destructor code */ } /* attribute boolean canDrop; */ NS_IMETHODIMP nsDragSession::GetCanDrop(PRBool *aCanDrop) { return NS_ERROR_NOT_IMPLEMENTED; } NS_IMETHODIMP nsDragSession::SetCanDrop(PRBool aCanDrop) { return NS_ERROR_NOT_IMPLEMENTED; } /* attribute boolean onlyChromeDrop; */ NS_IMETHODIMP nsDragSession::GetOnlyChromeDrop(PRBool *aOnlyChromeDrop) { return NS_ERROR_NOT_IMPLEMENTED; } NS_IMETHODIMP nsDragSession::SetOnlyChromeDrop(PRBool aOnlyChromeDrop) { return NS_ERROR_NOT_IMPLEMENTED; } /* attribute unsigned long dragAction; */ NS_IMETHODIMP nsDragSession::GetDragAction(PRUint32 *aDragAction) { return NS_ERROR_NOT_IMPLEMENTED; } NS_IMETHODIMP nsDragSession::SetDragAction(PRUint32 aDragAction) { return NS_ERROR_NOT_IMPLEMENTED; } /* [noscript] attribute nsSize targetSize; */ NS_IMETHODIMP nsDragSession::GetTargetSize(nsSize *aTargetSize) { return NS_ERROR_NOT_IMPLEMENTED; } NS_IMETHODIMP nsDragSession::SetTargetSize(nsSize aTargetSize) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute unsigned long numDropItems; */ NS_IMETHODIMP nsDragSession::GetNumDropItems(PRUint32 *aNumDropItems) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute nsIDOMDocument sourceDocument; */ NS_IMETHODIMP nsDragSession::GetSourceDocument(nsIDOMDocument * *aSourceDocument) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute nsIDOMNode sourceNode; */ NS_IMETHODIMP nsDragSession::GetSourceNode(nsIDOMNode * *aSourceNode) { return NS_ERROR_NOT_IMPLEMENTED; } /* attribute nsIDOMDataTransfer dataTransfer; */ NS_IMETHODIMP nsDragSession::GetDataTransfer(nsIDOMDataTransfer * *aDataTransfer) { return NS_ERROR_NOT_IMPLEMENTED; } NS_IMETHODIMP nsDragSession::SetDataTransfer(nsIDOMDataTransfer *aDataTransfer) { return NS_ERROR_NOT_IMPLEMENTED; } /* void getData (in nsITransferable aTransferable, in unsigned long aItemIndex); */ NS_IMETHODIMP nsDragSession::GetData(nsITransferable *aTransferable, PRUint32 aItemIndex) { return NS_ERROR_NOT_IMPLEMENTED; } /* boolean isDataFlavorSupported (in string aDataFlavor); */ NS_IMETHODIMP nsDragSession::IsDataFlavorSupported(const char * aDataFlavor, PRBool *_retval NS_OUTPARAM) { return NS_ERROR_NOT_IMPLEMENTED; } /* End of implementation class template. */ #endif #endif /* __gen_nsIDragSession_h__ */
43.535156
196
0.797936
[ "object" ]
d820ad48bf49eb839aea0809cab6d1c8b708c7b2
1,931
h
C
Character.h
Marbax/second_exam_cpp
2c812e1a33a717adb3b8393ea9412c5b6d31f519
[ "MIT" ]
null
null
null
Character.h
Marbax/second_exam_cpp
2c812e1a33a717adb3b8393ea9412c5b6d31f519
[ "MIT" ]
null
null
null
Character.h
Marbax/second_exam_cpp
2c812e1a33a717adb3b8393ea9412c5b6d31f519
[ "MIT" ]
null
null
null
#ifndef CHARACTER_H #define CHARACTER_H #include "Entity.h" #include "Pistol.h" class Character : public Entity { private: int health; void initVariables(); protected: float CurrentFrame, anim_speed, jump_speed, jumpH, cur_jumpH, sit_slawer; Pistol *weapon = nullptr; enum state { stay_left, moving_left, stay_right, moving_right, down_left, down_right, jump_top, jump_left, jump_right } state; public: Character() = delete; Character(const float &posX, const float &posY, sf::Image &image, const sf::String &name); virtual ~Character() = 0; virtual void setMaxHealth(const unsigned short &max_hp); virtual void damage(const unsigned short &dmg); virtual Pistol &getWeapon(); virtual void setOnGround(const bool &b); virtual const bool &isOnGround() const; // передвижение спрайта(текстуры) virtual void setPosition(); // задает координаты спрайта(x , y) virtual void setSpriteCoords(const int &sprite_posX, const int &sprite_posY); // задает размер спрайтов(низ_ширина,низ_высота) virtual void setSpriteSize(const int &sprite_width, const int &sprite_height); // движение обьекта(координаты) и смена состояний virtual void move(const float &boostX, const float &boostY, const float &dt); // кое-какие прыжки virtual void updateJumps(const float &dt); // включение атаки virtual void atack(const float &dt); // void control(const float &dt); virtual void movingAnimation(const bool &right, const unsigned short &frame_limit); virtual void frameChange(const bool &right); // обновление анимации virtual void updateAnimation(const float &dt) = 0; // обновление компонентов void update(const float &dt) override; // отрисовка спрайтов void render(sf::RenderTarget *target) override; }; #endif
23.54878
94
0.680476
[ "render" ]
d824989c1aa8d2aa6aaffb4eb5c9cc924166b572
38,872
h
C
inc/margin.h
mhaukness-ucsc/MarginPolish
eee90f0e1f29cf15ca995f96fe31c7ff05f1345c
[ "MIT" ]
null
null
null
inc/margin.h
mhaukness-ucsc/MarginPolish
eee90f0e1f29cf15ca995f96fe31c7ff05f1345c
[ "MIT" ]
null
null
null
inc/margin.h
mhaukness-ucsc/MarginPolish
eee90f0e1f29cf15ca995f96fe31c7ff05f1345c
[ "MIT" ]
null
null
null
/* * Copyright (C) 2017 by Benedict Paten (benedictpaten@gmail.com) * * Released under the MIT license, see LICENSE.txt */ #ifndef ST_RP_HMM_H_ #define ST_RP_HMM_H_ #include <stdint.h> #include <stdlib.h> #include <stddef.h> #include <math.h> #include <float.h> #include <inttypes.h> #include <ctype.h> #include <time.h> #include <ctype.h> #include <unistd.h> //#include <util.h> #include <stdio.h> #include <string.h> #include "sonLib.h" #include "hashTableC.h" #include "pairwiseAligner.h" #include "randomSequences.h" #include "multipleAligner.h" /* * More function documentation is in the .c files */ /* * Phasing structs */ typedef struct _stProfileSeq stProfileSeq; typedef struct _stRPHmm stRPHmm; typedef struct _stRPHmmParameters stRPHmmParameters; typedef struct _stRPColumn stRPColumn; typedef struct _stRPCell stRPCell; typedef struct _stRPMergeColumn stRPMergeColumn; typedef struct _stRPMergeCell stRPMergeCell; typedef struct _stGenomeFragment stGenomeFragment; typedef struct _stReferencePriorProbs stReferencePriorProbs; typedef struct _stBaseMapper stBaseMapper; typedef struct _stReferencePositionFilter stReferencePositionFilter; /* * Polisher structs */ typedef struct _stReadHaplotypeSequence stReadHaplotypeSequence; typedef struct hashtable stReadHaplotypePartitionTable; typedef struct _repeatSubMatrix RepeatSubMatrix; typedef struct _polishParams PolishParams; typedef struct _Poa Poa; typedef struct _poaNode PoaNode; typedef struct _poaInsert PoaInsert; typedef struct _poaDelete PoaDelete; typedef struct _poaBaseObservation PoaBaseObservation; typedef struct _rleString RleString; typedef struct _refMsaView MsaView; /* * Combined params object */ typedef struct _params Params; /* * Combined parameter object for phase, polish, view, etc. */ struct _params { PolishParams *polishParams; stRPHmmParameters *phaseParams; stBaseMapper *baseMapper; }; Params *params_readParams(char *paramsFile); Params *params_readParams2(char *paramsFile, bool requirePolish, bool requirePhase); void params_destruct(Params *params); void params_printParameters(Params *params, FILE *fh); /* * Overall coordination functions */ stList *filterReadsByCoverageDepth(stList *profileSeqs, stRPHmmParameters *params, stList *filteredProfileSeqs, stList *discardedProfileSeqs, stHash *referenceNamesToReferencePriors); stList *getRPHmms(stList *profileSeqs, stHash *referenceNamesToReferencePriors, stRPHmmParameters *params); stList *getTilingPaths(stSortedSet *hmms); stSet *getOverlappingComponents(stList *tilingPath1, stList *tilingPath2); /* * Math */ #define ST_MATH_LOG_ZERO -INFINITY #define ST_MATH_LOG_ONE 0.0 double logAddP(double a, double b, bool maxNotSum); /* * Alphabet */ #define ALPHABET_SIZE 5 #define ALPHABET_MAX_PROB 255 #define ALPHABET_MIN_PROB 0 #define ALPHABET_CHARACTER_BITS 8 #define ALPHABET_MIN_SUBSTITUTION_PROB 65535 // 2^16 -1 /* * Strandedness */ #define POS_STRAND_IDX 1 #define NEG_STRAND_IDX 0 /* * Repeat Count */ #define MAXIMUM_REPEAT_LENGTH 51 // Each value is expressed as an unsigned integer scaled linearly from 0 to 2^16-1, // with 0 = log(1) and 2^16-1 = -7 = log(0.0000001) uint16_t scaleToLogIntegerSubMatrix(double logProb); double invertScaleToLogIntegerSubMatrix(int64_t i); void setSubstitutionProb(uint16_t *logSubMatrix, double *logSubMatrixSlow, int64_t sourceCharacterIndex, int64_t derivedCharacterIndex, double prob); uint16_t *getSubstitutionProb(uint16_t *matrix, int64_t from, int64_t to); double *getSubstitutionProbSlow(double *matrix, int64_t from, int64_t to); /* * Binary partition stuff */ // The maximum read depth the model can support #define MAX_READ_PARTITIONING_DEPTH 64 char * intToBinaryString(uint64_t i); uint64_t makeAcceptMask(uint64_t depth); uint64_t mergePartitionsOrMasks(uint64_t partition1, uint64_t partition2, uint64_t depthOfPartition1, uint64_t depthOfPartition2); uint64_t maskPartition(uint64_t partition, uint64_t mask); bool seqInHap1(uint64_t partition, int64_t seqIndex); uint64_t invertPartition(uint64_t partition, uint64_t depth); uint64_t flipAReadsPartition(uint64_t partition, uint64_t readIndex); /* * _stProfileSeq * Struct for profile sequence */ #define FIRST_ALPHABET_CHAR 48 // Ascii symbol '0' struct _stProfileSeq { char *referenceName; char *readId; int64_t refStart; int64_t length; // The probability of alphabet characters, as specified by uint8_t // Each is expressed as an 8 bit unsigned int, with 0x00 representing 0 prob and // 0xFF representing 1.0 and each step between representing a linear step in probability of // 1.0/255 uint8_t *profileProbs; }; stProfileSeq *stProfileSeq_constructEmptyProfile(char *referenceName, char *readId, int64_t referenceStart, int64_t length); stProfileSeq *stProfileSeq_constructFromPosteriorProbs(char *refName, char *refSeq, int64_t refLength, char *readId, char *readSeq, stList *anchorAlignment, Params *params); void stProfileSeq_destruct(stProfileSeq *seq); void stProfileSeq_print(stProfileSeq *seq, FILE *fileHandle, bool includeProbs); float getProb(uint8_t *p, int64_t characterIndex); void printSeqs(FILE *fileHandle, stSet *profileSeqs); void printPartition(FILE *fileHandle, stSet *profileSeqs1, stSet *profileSeqs2); int stRPProfileSeq_cmpFn(const void *a, const void *b); /* * _stReferencePriorProbs * Struct for prior over reference positions */ struct _stReferencePriorProbs { char *referenceName; int64_t refStart; int64_t length; // The log probability of alphabet characters, as specified by uint16_t // see scaleToLogIntegerSubMatrix() // and invertScaleToLogIntegerSubMatrix() to see how probabilities are stored uint16_t *profileProbs; uint8_t *referenceSequence; // The reference sequence // Read counts for the bases seen in reads double *baseCounts; // Filter array of positions in the reference, used to ignore some columns in the alignment bool *referencePositionsIncluded; }; stReferencePriorProbs *stReferencePriorProbs_constructEmptyProfile(char *referenceName, int64_t referenceStart, int64_t length); void stReferencePriorProbs_destruct(stReferencePriorProbs *seq); stHash *createEmptyReferencePriorProbabilities(stList *profileSequences); int64_t filterHomozygousReferencePositions(stHash *referenceNamesToReferencePriors, stRPHmmParameters *params, int64_t *totalPositions); double *stReferencePriorProbs_estimateReadErrorProbs(stHash *referenceNamesToReferencePriors, stRPHmmParameters *params); /* * Emission probabilities methods */ double emissionLogProbability(stRPColumn *column, stRPCell *cell, uint64_t *bitCountVectors, stReferencePriorProbs *referencePriorProbs, stRPHmmParameters *params); double emissionLogProbabilitySlow(stRPColumn *column, stRPCell *cell, uint64_t *bitCountVectors, stReferencePriorProbs *referencePriorProbs, stRPHmmParameters *params, bool maxNotSum); void fillInPredictedGenome(stGenomeFragment *gF, uint64_t partition, stRPColumn *column, stReferencePriorProbs *referencePriorProbs, stRPHmmParameters *params); /* * Constituent functions tested and used to do bit twiddling */ int popcount64(uint64_t x); uint64_t getExpectedInstanceNumber(uint64_t *bitCountVectors, uint64_t depth, uint64_t partition, int64_t position, int64_t characterIndex); uint64_t *calculateCountBitVectors(uint8_t **seqs, int64_t depth, int64_t *activePositions, int64_t totalActivePositions); /* * _stRPHmmParameters * Struct for hmm parameters */ struct _stRPHmmParameters { /* * Parameters used for the HMM computation */ uint16_t *hetSubModel; uint16_t *readErrorSubModel; double *hetSubModelSlow; double *readErrorSubModelSlow; bool maxNotSumTransitions; // Filters on the number of states in a column // Used to prune the hmm int64_t minPartitionsInAColumn; int64_t maxPartitionsInAColumn; double minPosteriorProbabilityForPartition; // MaxCoverageDepth is the maximum depth of profileSeqs to allow at any base. // If the coverage depth is higher than this then some profile seqs are randomly discarded. int64_t maxCoverageDepth; int64_t minReadCoverageToSupportPhasingBetweenHeterozygousSites; // Training // Number of iterations of training int64_t trainingIterations; // Pseudo counts used to make training of substitution matrices a bit more robust double offDiagonalReadErrorPseudoCount; double onDiagonalReadErrorPseudoCount; // Before doing any training estimate the read error substitution parameters empirically bool estimateReadErrorProbsEmpirically; // Whether or not to filter out poorly matching reads after one round and try again bool filterBadReads; double filterMatchThreshold; // Use a prior for the reference sequence bool useReferencePrior; // Verbosity options for printing bool verboseTruePositives; bool verboseFalsePositives; bool verboseFalseNegatives; // Ensure symmetry in the HMM such that the inverted partition of each partition is included in the HMM bool includeInvertedPartitions; // Options to filter which positions in the reference sequence are included in the computation bool filterLikelyHomozygousSites; double minSecondMostFrequentBaseFilter; // See stReferencePriorProbs_setReferencePositionFilter double minSecondMostFrequentBaseLogProbFilter; // See stReferencePriorProbs_setReferencePositionFilter // Whether or not to make deletions gap characters (otherwise, profile probs will be flat) bool gapCharactersForDeletions; // Any read that has one of the following sam flags is ignored when parsing the reads from the SAM/BAM file. // This allows the ability to optionally ignore, for example, secondary alignments. uint16_t filterAReadWithAnyOneOfTheseSamFlagsSet; // Filter out any reads with a MAPQ score less than or equal to this. int64_t mapqFilter; // Number of rounds of iterative refinement to attempt to improve the partition. int64_t roundsOfIterativeRefinement; // Whether or not to write a gvcf as output bool writeGVCF; // What types of file formats of split reads to output bool writeSplitSams; bool writeUnifiedSam; // bool writeSplitBams; }; void stRPHmmParameters_destruct(stRPHmmParameters *params); void stRPHmmParameters_learnParameters(stRPHmmParameters *params, stList *profileSequences, stHash *referenceNamesToReferencePriors); void stRPHmmParameters_printParameters(stRPHmmParameters *params, FILE *fH); void stRPHmmParameters_setReadErrorSubstitutionParameters(stRPHmmParameters *params, double *readErrorSubModel); void normaliseSubstitutionMatrix(double *subMatrix); double *getEmptyReadErrorSubstitutionMatrix(stRPHmmParameters *params); /* * _stRPHmm * Struct for read partitioning hmm */ struct _stRPHmm { char *referenceName; int64_t refStart; int64_t refLength; stList *profileSeqs; // List of stProfileSeq int64_t columnNumber; // Number of columns, excluding merge columns int64_t maxDepth; stRPColumn *firstColumn; stRPColumn *lastColumn; const stRPHmmParameters *parameters; //Forward/backward probability calculation things double forwardLogProb; double backwardLogProb; // Prior over reference bases stReferencePriorProbs *referencePriorProbs; // Filter used to mask column positions from consideration stReferencePositionFilter *referencePositionFilter; }; stRPHmm *stRPHmm_construct(stProfileSeq *profileSeq, stReferencePriorProbs *referencePriorProbs, stRPHmmParameters *params); void stRPHmm_destruct(stRPHmm *hmm, bool destructColumns); void stRPHmm_destruct2(stRPHmm *hmm); bool stRPHmm_overlapOnReference(stRPHmm *hmm1, stRPHmm *hmm2); stRPHmm *stRPHmm_createCrossProductOfTwoAlignedHmm(stRPHmm *hmm1, stRPHmm *hmm2); void stRPHmm_alignColumns(stRPHmm *hmm1, stRPHmm *hmm2); stRPHmm *stRPHmm_fuse(stRPHmm *leftHmm, stRPHmm *rightHmm); void stRPHmm_forwardBackward(stRPHmm *hmm); void stRPHmm_prune(stRPHmm *hmm); void stRPHmm_print(stRPHmm *hmm, FILE *fileHandle, bool includeColumns, bool includeCells); stList *stRPHmm_forwardTraceBack(stRPHmm *hmm); stSet *stRPHmm_partitionSequencesByStatePath(stRPHmm *hmm, stList *path, bool partition1); int stRPHmm_cmpFn(const void *a, const void *b); stRPHmm *stRPHmm_split(stRPHmm *hmm, int64_t splitPoint); void stRPHmm_resetColumnNumberAndDepth(stRPHmm *hmm); stList *stRPHMM_splitWherePhasingIsUncertain(stRPHmm *hmm); void printBaseComposition2(double *baseCounts); double *getColumnBaseComposition(stRPColumn *column, int64_t pos); void printColumnAtPosition(stRPHmm *hmm, int64_t pos); double *getProfileSequenceBaseCompositionAtPosition(stSet *profileSeqs, int64_t pos); void logHmm(stRPHmm *hmm, stSet *reads1, stSet *reads2, stGenomeFragment *gF); /* * _stRPColumn * Column of read partitioning hmm */ struct _stRPColumn { int64_t refStart; int64_t length; int64_t depth; stProfileSeq **seqHeaders; uint8_t **seqs; stRPCell *head; stRPMergeColumn *nColumn, *pColumn; double totalLogProb; // Record of which positions in the column are not filtered out int64_t *activePositions; // List of positions that are not filtered out, relative to the start of the column in reference coordinates int64_t totalActivePositions; // The length of activePositions }; stRPColumn *stRPColumn_construct(int64_t refStart, int64_t length, int64_t depth, stProfileSeq **seqHeaders, uint8_t **seqs, stReferencePriorProbs *rProbs); void stRPColumn_destruct(stRPColumn *column); void stRPColumn_print(stRPColumn *column, FILE *fileHandle, bool includeCells); void stRPColumn_split(stRPColumn *column, int64_t firstHalfLength, stRPHmm *hmm); stSet *stRPColumn_getSequencesInCommon(stRPColumn *column1, stRPColumn *column2); stSet *stRPColumn_getColumnSequencesAsSet(stRPColumn *column); /* * _stRPCell * State of read partitioning hmm */ struct _stRPCell { uint64_t partition; double forwardLogProb, backwardLogProb; stRPCell *nCell; }; stRPCell *stRPCell_construct(int64_t partition); void stRPCell_destruct(stRPCell *cell); void stRPCell_print(stRPCell *cell, FILE *fileHandle); double stRPCell_posteriorProb(stRPCell *cell, stRPColumn *column); /* * _stRPMergeColumn * Merge column of read partitioning hmm */ struct _stRPMergeColumn { uint64_t maskFrom; uint64_t maskTo; stHash *mergeCellsFrom; stHash *mergeCellsTo; stRPColumn *nColumn, *pColumn; }; stRPMergeColumn *stRPMergeColumn_construct(uint64_t maskFrom, uint64_t maskTo); void stRPMergeColumn_destruct(stRPMergeColumn *mColumn); void stRPMergeColumn_print(stRPMergeColumn *mColumn, FILE *fileHandle, bool includeCells); stRPMergeCell *stRPMergeColumn_getNextMergeCell(stRPCell *cell, stRPMergeColumn *mergeColumn); stRPMergeCell *stRPMergeColumn_getPreviousMergeCell(stRPCell *cell, stRPMergeColumn *mergeColumn); int64_t stRPMergeColumn_numberOfPartitions(stRPMergeColumn *mColumn); /* * _stRPMergeCell * Merge cell of read partitioning hmm */ struct _stRPMergeCell { uint64_t fromPartition; uint64_t toPartition; double forwardLogProb, backwardLogProb; }; stRPMergeCell *stRPMergeCell_construct(uint64_t fromPartition, uint64_t toPartition, stRPMergeColumn *mColumn); void stRPMergeCell_destruct(stRPMergeCell *mCell); void stRPMergeCell_print(stRPMergeCell *mCell, FILE *fileHandle); double stRPMergeCell_posteriorProb(stRPMergeCell *mCell, stRPMergeColumn *mColumn); /* * _stGenomeFragment * String to represent genotype and haplotype inference from an HMM */ struct _stGenomeFragment { // A string where each element represents the predicted genotype at the corresponding // position. // A genotype is represented by an integer in the range [0, ALPHABET_SIZE**2) // A genotype expresses two characters. For two characters x, y represented by two integers // in [0, ALPHABET_SIZE) then the genotype is expressed as x * ALPHABET_SIZE + y if x <= y // else y * ALPHABET_SIZE + x uint64_t *genotypeString; // An array of genotype posterior probabilities, // each between 0 and 1, for the corresponding genotypes // in the genotype string float *genotypeProbs; float **genotypeLikelihoods; // Strings representing the predicted haplotypes, where each element is an alphabet character // index in [0, ALPHABET_SIZE) uint64_t *haplotypeString1; uint64_t *haplotypeString2; // An array of haplotype posterior probabilities, // each between 0 and 1, for the corresponding haplotypes // in the haplotype strings float *haplotypeProbs1; float *haplotypeProbs2; // The reference coordinates of the genotypes & other read info char *referenceName; int64_t refStart; int64_t length; uint8_t *referenceSequence; // Depth and allele counts uint8_t *hap1Depth; uint8_t *hap2Depth; uint8_t *alleleCountsHap1; uint8_t *alleleCountsHap2; uint8_t *allele2CountsHap1; uint8_t *allele2CountsHap2; }; stGenomeFragment *stGenomeFragment_construct(stRPHmm *hmm, stList *path); void stGenomeFragment_destruct(stGenomeFragment *genomeFragment); void stGenomeFragment_refineGenomeFragment(stGenomeFragment *gF, stSet *reads1, stSet *reads2, stRPHmm *hmm, stList *path, int64_t maxIterations); double getLogProbOfReadGivenHaplotype(uint64_t *haplotypeString, int64_t start, int64_t length, stProfileSeq *profileSeq, stRPHmmParameters *params); /* * _stBaseMapper * Struct for alphabet and mapping bases to numbers */ struct _stBaseMapper { uint8_t *charToNum; char *numToChar; char *wildcard; uint8_t size; }; stBaseMapper* stBaseMapper_construct(); void stBaseMapper_destruct(stBaseMapper *bm); void stBaseMapper_addBases(stBaseMapper *bm, char *bases); void stBaseMapper_setWildcard(stBaseMapper* bm, char *wildcard); char stBaseMapper_getCharForValue(stBaseMapper *bm, uint64_t value); uint8_t stBaseMapper_getValueForChar(stBaseMapper *bm, char base); // Verbosity for what's printed. To add more verbose options, you need to update: // usage, setVerbosity, struct _stRPHmmParameters, stRPHmmParameters_printParameters, writeParamFile #define LOG_TRUE_POSITIVES 1 #define LOG_FALSE_POSITIVES 2 #define LOG_FALSE_NEGATIVES 4 void setVerbosity(stRPHmmParameters *params, int64_t bitstring); /* * File writing methods */ void writeParamFile(char *outputFilename, stRPHmmParameters *params); // Tag definitions (for haplotype output) #define HAPLOTYPE_TAG "ht" #define MARGIN_PHASE_TAG "mp" /* * _stReadHaplotypeSequence * Struct for tracking haplotypes for read */ struct _stReadHaplotypeSequence { int64_t readStart; int64_t phaseBlock; int64_t length; int8_t haplotype; void *next; }; stReadHaplotypeSequence *stReadHaplotypeSequence_construct(int64_t readStart, int64_t phaseBlock, int64_t length, int8_t haplotype); char *stReadHaplotypeSequence_toString(stReadHaplotypeSequence *rhs); char *stReadHaplotypeSequence_toStringEmpty(); void stReadHaplotypeSequence_destruct(stReadHaplotypeSequence * rhs); /* * stReadHaplotypePartitionTable * Tracking haplotypes for all reads */ stReadHaplotypePartitionTable *stReadHaplotypePartitionTable_construct(int64_t initialSize); void stReadHaplotypePartitionTable_add(stReadHaplotypePartitionTable *hpt, char *readName, int64_t readStart, int64_t phaseBlock, int64_t length, int8_t haplotype); void stReadHaplotypePartitionTable_destruct(stReadHaplotypePartitionTable *hpt); void populateReadHaplotypePartitionTable(stReadHaplotypePartitionTable *hpt, stGenomeFragment *gF, stRPHmm *hmm, stList *path); void addProfileSeqIdsToSet(stSet *pSeqs, stSet *readIds); /* * Polish functions */ /* * Parameter object for polish algorithm */ struct _polishParams { bool useRunLengthEncoding; double referenceBasePenalty; // used by poa_getConsensus to weight against picking the reference base double *minPosteriorProbForAlignmentAnchors; // used by by poa_getAnchorAlignments to determine which alignment pairs // to use for alignment anchors during poa_realignIterative, of the form of even-length array of form // [ min_posterio_anchor_prob_1, diagonal_expansion_1, min_posterio_anchor_prob_2, diagonal_expansion_2, ... ] int64_t minPosteriorProbForAlignmentAnchorsLength; // Length of array minPosteriorProbForAlignmentAnchors Hmm *hmm; // Pair hmm used for aligning reads to the reference. StateMachine *sM; // Statemachine derived from the hmm PairwiseAlignmentParameters *p; // Parameters object used for aligning RepeatSubMatrix *repeatSubMatrix; // Repeat submatrix // chunking configuration bool includeSoftClipping; uint64_t chunkSize; uint64_t chunkBoundary; uint64_t maxDepth; double candidateVariantWeight; // The fraction (from 0 to 1) of the average position coverage needed to define a candidate variant uint64_t columnAnchorTrim; // The min distance between a column anchor and a candidate variant uint64_t maxConsensusStrings; // The maximum number of different consensus strings to consider for a substring. uint64_t maxPoaConsensusIterations; // Maximum number of poa_consensus / realignment iterations uint64_t minPoaConsensusIterations; // Minimum number of poa_consensus / realignment iterations uint64_t maxRealignmentPolishIterations; // Maximum number of poa_polish iterations uint64_t minRealignmentPolishIterations; // Minimum number of poa_polish iterations uint64_t minReadsToCallConsensus; // Min reads to choose between consensus sequences for a region uint64_t filterReadsWhileHaveAtLeastThisCoverage; // Only filter read substrings if we have at least this coverage // at a locus double minAvgBaseQuality; // Minimum average base quality to include a substring for consensus finding }; PolishParams *polishParams_readParams(FILE *fileHandle); void polishParams_printParameters(PolishParams *polishParams, FILE *fh); void polishParams_destruct(PolishParams *polishParams); /* * Basic data structures for representing a POA alignment. */ struct _Poa { char *refString; // The reference string stList *nodes; }; struct _poaNode { stList *inserts; // Inserts that happen immediately after this position stList *deletes; // Deletes that happen immediately after this position char base; // Char representing base, e.g. 'A', 'C', etc. double *baseWeights; // Array of length SYMBOL_NUMBER, encoding the weight given go each base, using the Symbol enum stList *observations; // Individual events representing event, a list of PoaObservations }; struct _poaInsert { char *insert; // String representing characters of insert e.g. "GAT", etc. double weightForwardStrand; double weightReverseStrand; stList *observations; // Individual events representing event, a list of PoaObservations }; struct _poaDelete { int64_t length; // Length of delete double weightForwardStrand; double weightReverseStrand; stList *observations; // Individual events representing event, a list of PoaObservations }; struct _poaBaseObservation { int64_t readNo; int64_t offset; double weight; }; /* * Poa functions. */ double poaInsert_getWeight(PoaInsert *toInsert); double poaDelete_getWeight(PoaDelete *toDelete); /* * Creates a POA representing the given reference sequence, with one node for each reference base and a * prefix 'N' base to represent place to add inserts/deletes that precede the first position of the reference. */ Poa *poa_getReferenceGraph(char *reference); /* * Adds to given POA the matches, inserts and deletes from the alignment of the given read to the reference. * Adds the inserts and deletes so that they are left aligned. */ void poa_augment(Poa *poa, char *read, bool readStrand, int64_t readNo, stList *matches, stList *inserts, stList *deletes); /* * Creates a POA representing the reference and the expected inserts / deletes and substitutions from the * alignment of the given set of reads aligned to the reference. Anchor alignments is a set of pairwise * alignments between the reads and the reference sequence. There is one alignment for each read. See * poa_getAnchorAlignments. The anchorAlignments can be null, in which case no anchors are used. */ Poa *poa_realign(stList *bamChunkReads, stList *alignments, char *reference, PolishParams *polishParams); /* * Generates a set of anchor alignments for the reads aligned to a consensus sequence derived from the poa. * These anchors can be used to restrict subsequent alignments to the consensus to generate a new poa. * PoaToConsensusMap is a map from the positions in the poa reference sequence to the derived consensus * sequence. See poa_getConsensus for description of poaToConsensusMap. If poaToConsensusMap is NULL then * the alignment is just the reference sequence of the poa. */ stList *poa_getAnchorAlignments(Poa *poa, int64_t *poaToConsensusMap, int64_t noOfReads, PolishParams *polishParams); /* * Generates a set of maximal expected alignments for the reads aligned to the the POA reference sequence. * Unlike the draft anchor alignments, these are designed to be complete, high quality alignments. */ stList *poa_getReadAlignmentsToConsensus(Poa *poa, stList *bamChunkReads, PolishParams *polishParams); /* * Prints representation of the POA. */ void poa_print(Poa *poa, FILE *fH, stList *bamChunkReads, float indelSignificanceThreshold, float strandBalanceRatio); /* * Prints a tab separated version of the POA graph. */ void poa_printTSV(Poa *poa, FILE *fH, stList *bamChunkReads, float indelSignificanceThreshold, float strandBalanceRatio); /* * Print repeat count observations. */ void poa_printRepeatCounts(Poa *poa, FILE *fH, stList *rleReads, stList *bamChunkReads); /* * Prints some summary stats on the POA. */ void poa_printSummaryStats(Poa *poa, FILE *fH); /* * Creates a consensus reference sequence from the POA. poaToConsensusMap is a pointer to an * array of integers of length str(poa->refString), giving the index of the reference positions * alignment to the consensus sequence, or -1 if not aligned. It is initialised as a * return value of the function. */ char *poa_getConsensus(Poa *poa, int64_t **poaToConsensusMap, PolishParams *polishParams); Poa *poa_polish(Poa *poa, stList *bamChunkReads, PolishParams *params); char *poa_polish2(Poa *poa, stList *bamChunkReads, PolishParams *params, int64_t **poaToConsensusMap); /* * Iteratively used poa_realign and poa_getConsensus to refine the median reference sequence * for the given reads and the starting reference. */ Poa *poa_realignIterative(stList *bamChunkReads, stList *alignments, char *reference, PolishParams *polishParams); /* * Ad poa_realignIterative, but allows the specification of the min and max number of realignment cycles, * also, can switch between the "poa_polish" and the "poa_consensus" algorithm using hmmNotRealign (poa_consensus * if non-zero). */ Poa *poa_realignIterative2(stList *bamChunkReads, stList *anchorAlignments, char *reference, PolishParams *polishParams, bool hmmNotRealign, int64_t minIterations, int64_t maxIterations); /* * As poa_realignIterative, but takes a starting poa. Input poa is destroyed by function. */ Poa *poa_realignIterative3(Poa *poa, stList *bamChunkReads, PolishParams *polishParams, bool hmmMNotRealign, int64_t minIterations, int64_t maxIterations); /* * Convenience function that iteratively polishes sequence using poa_consensus and then poa_polish for * a specified number of iterations. */ Poa *poa_realignAll(stList *bamChunkReads, stList *anchorAlignments, char *reference, PolishParams *polishParams); /* * Greedily evaluate the top scoring indels. */ Poa *poa_checkMajorIndelEditsGreedily(Poa *poa, stList *bamChunkReads, PolishParams *polishParams); void poa_destruct(Poa *poa); double *poaNode_getStrandSpecificBaseWeights(PoaNode *node, stList *bamChunkReads, double *totalWeight, double *totalPositiveWeight, double *totalNegativeWeight); /* * Finds shift, expressed as a reference coordinate, that the given substring str can * be shifted left in the refString, starting from a match at refStart. */ int64_t getShift(char *refString, int64_t refStart, char *str, int64_t length); /* * Get sum of weights for reference bases in poa - proxy to agreement of reads * with reference. */ double poa_getReferenceNodeTotalMatchWeight(Poa *poa); /* * Get sum of weights for delete in poa - proxy to delete disagreement of reads * with reference. */ double poa_getDeleteTotalWeight(Poa *poa); /* * Get sum of weights for inserts in poa - proxy to insert disagreement of reads * with reference. */ double poa_getInsertTotalWeight(Poa *poa); /* * Get sum of weights for non-reference bases in poa - proxy to disagreement of read positions * aligned with reference. */ double poa_getReferenceNodeTotalDisagreementWeight(Poa *poa); /* * Functions for run-length encoding/decoding with POAs */ // Data structure for representing RLE strings struct _rleString { char *rleString; //Run-length-encoded (RLE) string int64_t *repeatCounts; // Count of repeat for each position in rleString int64_t *rleToNonRleCoordinateMap; // For each position in the RLE string the corresponding, left-most position // in the expanded non-RLE string int64_t *nonRleToRleCoordinateMap; // For each position in the expanded non-RLE string the corresponding position // in the RLE string int64_t length; // Length of the rleString int64_t nonRleLength; // Length of the expanded non-rle string }; RleString *rleString_construct(char *string); RleString *rleString_constructNoRLE(char *str); RleString *rleString_constructPreComputed(char *rleChars, uint8_t *rleCounts); void rleString_destruct(RleString *rlString); /* * Generates the expanded non-rle string. */ char *rleString_expand(RleString *rleString); // Data structure for storing log-probabilities of observing // one repeat count given another struct _repeatSubMatrix { double *logProbabilities; int64_t maximumRepeatLength; int64_t maxEntry; }; /* * Reads the repeat count matrix from a given input file. */ RepeatSubMatrix *repeatSubMatrix_constructEmpty(); void repeatSubMatrix_destruct(RepeatSubMatrix *repeatSubMatrix); /* * Gets the log probability of observing a given repeat conditioned on an underlying repeat count and base. */ double repeatSubMatrix_getLogProb(RepeatSubMatrix *repeatSubMatrix, Symbol base, bool strand, int64_t observedRepeatCount, int64_t underlyingRepeatCount); /* * As gets, but returns the address. */ double *repeatSubMatrix_setLogProb(RepeatSubMatrix *repeatSubMatrix, Symbol base, bool strand, int64_t observedRepeatCount, int64_t underlyingRepeatCount); /* * Gets the log probability of observing a given set of repeat observations conditioned on an underlying repeat count and base. */ double repeatSubMatrix_getLogProbForGivenRepeatCount(RepeatSubMatrix *repeatSubMatrix, Symbol base, stList *observations, stList *rleReads, stList *bamChunkReads, int64_t underlyingRepeatCount); /* * Gets the maximum likelihood underlying repeat count for a given set of observed read repeat counts. * Puts the ml log probility in *logProbabilty. */ int64_t repeatSubMatrix_getMLRepeatCount(RepeatSubMatrix *repeatSubMatrix, Symbol base, stList *observations, stList *rleReads, stList *bamChunkReads, double *logProbability); /* * Takes a POA done in run-length space and returns the expanded consensus string in * non-run-length space as an RleString. */ RleString *expandRLEConsensus(Poa *poa, stList *rlReads, stList *bamChunkReads, RepeatSubMatrix *repeatSubMatrix); /* * Translate a sequence of aligned pairs (as stIntTuples) whose coordinates are monotonically increasing * in both underlying sequences (seqX and seqY) into an equivalent run-length encoded space alignment. */ stList *runLengthEncodeAlignment(stList *alignment, RleString *seqX, RleString *seqY); stList *runLengthEncodeAlignment2(stList *alignment, RleString *seqX, RleString *seqY, int64_t xIdx, int64_t yIdx, int64_t weightIdx); /* * Make edited string with given insert. Edit start is the index of the position to insert the string. */ char *addInsert(char *string, char *insertString, int64_t editStart); /* * Make edited string with given insert. Edit start is the index of the first position to delete from the string. */ char *removeDelete(char *string, int64_t deleteLength, int64_t editStart); /* * Generates aligned pairs and indel probs, but first crops reference to only include sequence from first * to last anchor position. */ void getAlignedPairsWithIndelsCroppingReference(char *reference, int64_t refLength, char *read, stList *anchorPairs, stList **matches, stList **inserts, stList **deletes, PolishParams *polishParams); /* * Functions for processing BAMs */ // TODO: MOVE BAMCHUNKER TO PARSER .c typedef struct _bamChunker { // file locations char *bamFile; // configuration uint64_t chunkSize; uint64_t chunkBoundary; bool includeSoftClip; PolishParams *params; // internal data stList *chunks; uint64_t chunkCount; } BamChunker; typedef struct _bamChunk { char *refSeqName; // name of contig int64_t chunkBoundaryStart; // the first 'position' where we have an aligned read int64_t chunkStart; // the actual boundary of the chunk, calculations from chunkMarginStart to chunkStart // should be used to initialize the probabilities at chunkStart int64_t chunkEnd; // same for chunk end int64_t chunkBoundaryEnd; // no reads should start after this position BamChunker *parent; // reference to parent (may not be needed) } BamChunk; typedef struct _bamChunkRead { char *readName; // read name char *nucleotides; // nucleotide string int64_t readLength; uint8_t *qualities; // quality scores. will be NULL if not given, else will be of length readLength bool forwardStrand; // whether the alignment is matched to the forward strand BamChunk *parent; // reference to parent chunk } BamChunkRead; BamChunkRead *bamChunkRead_construct(); BamChunkRead *bamChunkRead_construct2(char *readName, char *nucleotides, uint8_t *qualities, bool forwardStrand, BamChunk *parent); BamChunkRead *bamChunkRead_constructRLECopy(BamChunkRead *read, RleString *rle); void bamChunkRead_destruct(BamChunkRead *bamChunkRead); /* * Remove overlap between two overlapping strings. Returns max weight of split point. */ int64_t removeOverlap(char *prefixString, char *suffixString, int64_t approxOverlap, PolishParams *polishParams, int64_t *prefixStringCropEnd, int64_t *suffixStringCropStart); /* * View functions */ struct _refMsaView { int64_t refLength; // The length of the reference sequence char *refSeq; // The reference sequence - this is not copied by the constructor char *refSeqName; // The reference sequence name - this is not copied by the constructor, and can be NULL int64_t seqNo; // The number of non-ref sequences aligned to the reference stList *seqs; // The non-ref sequences - - this is not copied by the constructor stList *seqNames; // The non-ref sequence names - this is not copied by the constructor, and can be NULL int64_t *seqCoordinates; // A matrix giving the coordinates of the non-reference sequence // as aligned to the reference sequence int64_t *maxPrecedingInsertLengths; // The maximum length of an insert in // any of the sequences preceding the reference positions int64_t **precedingInsertCoverages; // The number of sequences with each given indel position }; /* * Get the coordinate in the given sequence aligned to the given reference position. Returns -1 if * no sequence position is aligned to the reference position. */ int64_t msaView_getSeqCoordinate(MsaView *view, int64_t refCoordinate, int64_t seqIndex); /* * Gets the length of any insert in the given sequence preceding the given reference position. If * the sequence is not aligned at the given reference position returns 0. */ int64_t msaView_getPrecedingInsertLength(MsaView *view, int64_t rightRefCoordinate, int64_t seqIndex); /* * Gets the first position in the sequence of an insert preceding the given reference position. If there * is no such insert returns -1. */ int64_t msaView_getPrecedingInsertStart(MsaView *view, int64_t rightRefCoordinate, int64_t seqIndex); /* * Gets the maximum length of an indel preceding the given reference position */ int64_t msaView_getMaxPrecedingInsertLength(MsaView *view, int64_t rightRefCoordinate); /* * Get the number of sequences with an insertion at a given position. IndelOffset if the position, from 0, of the indel from left-to-right. */ int64_t msaView_getPrecedingCoverageDepth(MsaView *view, int64_t rightRefCoordinate, int64_t indelOffset); /* * Get the maximum length of an insertion at a given position with a minimum of reads supporting it. */ int64_t msaView_getMaxPrecedingInsertLengthWithGivenCoverage(MsaView *view, int64_t rightRefCoordinate, int64_t minCoverage); /* * Builds an MSA view for the given reference and aligned sequences. * Does not copy the strings or string names, just holds references. */ MsaView *msaView_construct(char *refSeq, char *refName, stList *refToSeqAlignments, stList *seqs, stList *seqNames); void msaView_destruct(MsaView * view); /* * Prints a quick view of the MSA for debugging/browsing. */ void msaView_print(MsaView *view, int64_t minInsertCoverage, FILE *fh); /* * Prints the repeat counts of the MSA. */ void msaView_printRepeatCounts(MsaView *view, int64_t minInsertCoverage, RleString *refString, stList *rleStrings, FILE *fh); /* * Phase to polish functions */ void phaseReads(char *reference, int64_t referenceLength, stList *reads, stList *anchorAlignments, stList **readsPartition1, stList **readsPartition2, Params *params); /* * For logging while multithreading */ char *getLogIdentifier(); /* * HELEN Features */ typedef enum { HFEAT_NONE=0, HFEAT_SIMPLE_WEIGHT=1, HFEAT_SPLIT_RLE_WEIGHT=2, } HelenFeatureType; #define POAFEATURE_SPLIT_MAX_RUN_LENGTH_DEFAULT 10 #endif /* ST_RP_HMM_H_ */
34.676182
155
0.773282
[ "object", "model" ]
d8261225456052e7c9550748914e5292e6e39a14
667
h
C
saiplayer/CommandLineOptions.h
arlakshm/sonic-sairedis
caa7ab297d8b535b3ee2e16252c8c9170930032e
[ "Apache-2.0" ]
null
null
null
saiplayer/CommandLineOptions.h
arlakshm/sonic-sairedis
caa7ab297d8b535b3ee2e16252c8c9170930032e
[ "Apache-2.0" ]
null
null
null
saiplayer/CommandLineOptions.h
arlakshm/sonic-sairedis
caa7ab297d8b535b3ee2e16252c8c9170930032e
[ "Apache-2.0" ]
1
2019-07-23T23:15:45.000Z
2019-07-23T23:15:45.000Z
#pragma once #include "swss/sal.h" #include <string> #include <vector> namespace saiplayer { class CommandLineOptions { public: CommandLineOptions(); virtual ~CommandLineOptions() = default; public: virtual std::string getCommandLineString() const; public: bool m_useTempView; bool m_inspectAsic; bool m_skipNotifySyncd; bool m_enableDebug; bool m_sleep; bool m_syncMode; std::string m_profileMapFile; std::string m_contextConfig; std::vector<std::string> m_files; }; }
15.511628
61
0.557721
[ "vector" ]
d82654b0d867e02f5731f600ad4c4e34470a8170
3,078
h
C
cocos2d/plugin/protocols/include/ProtocolShare.h
davidyuan/WagonWar
a52211c0e5490dffaacfa1c722d321d969ae612c
[ "MIT" ]
553
2015-01-10T08:16:23.000Z
2022-03-07T19:15:17.000Z
samples/SwiftTetris/cocos2d/plugin/protocols/include/ProtocolShare.h
OhGameKillers/cocos2d-x-samples
9f1472d9083a18853bb1fe97a337292f42abe44a
[ "MIT" ]
14
2015-01-24T23:38:22.000Z
2021-03-04T08:38:05.000Z
samples/SwiftTetris/cocos2d/plugin/protocols/include/ProtocolShare.h
OhGameKillers/cocos2d-x-samples
9f1472d9083a18853bb1fe97a337292f42abe44a
[ "MIT" ]
240
2015-01-09T12:53:16.000Z
2022-03-29T02:32:06.000Z
/**************************************************************************** Copyright (c) 2012-2013 cocos2d-x.org http://www.cocos2d-x.org 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. ****************************************************************************/ #ifndef __CCX_PROTOCOL_SHARE_H__ #define __CCX_PROTOCOL_SHARE_H__ #include "PluginProtocol.h" #include <map> #include <string> namespace cocos2d { namespace plugin { typedef std::map<std::string, std::string> TShareDeveloperInfo; typedef std::map<std::string, std::string> TShareInfo; typedef enum { kShareSuccess = 0, kShareFail, kShareCancel, kShareTimeOut, } ShareResultCode; class ShareResultListener { public: virtual void onShareResult(ShareResultCode ret, const char* msg) = 0; }; class ProtocolShare : public PluginProtocol { public: ProtocolShare(); virtual ~ProtocolShare(); /** @brief config the share developer info @param devInfo This parameter is the info of developer, different plugin have different format @warning Must invoke this interface before other interfaces. And invoked only once. */ void configDeveloperInfo(TShareDeveloperInfo devInfo); /** @brief share information @param info The info of share, contains key: SharedText The text need to share SharedImagePath The full path of image file need to share (optinal) @warning For different plugin, the parameter should have other keys to share. Look at the manual of plugins. */ void share(TShareInfo info); /** @breif set the result listener @param pListener The callback object for share result @wraning Must invoke this interface before share */ void setResultListener(ShareResultListener* pListener); /** @brief share result callback */ void onShareResult(ShareResultCode ret, const char* msg); protected: ShareResultListener* _listener; }; }} // namespace cocos2d { namespace plugin { #endif /* ----- #ifndef __CCX_PROTOCOL_SHARE_H__ ----- */
32.744681
82
0.697856
[ "object" ]
d82a8ed0a33cb48992ba7dd39b25a335cc3a9e4c
1,129
c
C
test.c
kellencataldo/aes_lib
f548b43d2d90f6f86834bebcfea18947f0706e04
[ "MIT" ]
5
2018-08-18T12:10:25.000Z
2021-02-10T16:57:32.000Z
test.c
kellencataldo/aes_lib
f548b43d2d90f6f86834bebcfea18947f0706e04
[ "MIT" ]
null
null
null
test.c
kellencataldo/aes_lib
f548b43d2d90f6f86834bebcfea18947f0706e04
[ "MIT" ]
6
2018-08-20T08:05:17.000Z
2021-12-16T05:58:54.000Z
#include <stdio.h> #include <string.h> #include "aes_lib/aes_lib.h" int main() { //Electronic Code Book (ECB) mode unsigned char message[(AES_SIZE * 2) + 1] = { "I LOVE 2 ENCRYPT WORDS WITH AES!" }; unsigned char key[AES_SIZE+1] = { "YELLOW SUBMARINE" }; printf("This message will be encrypted using ECB mode: %s\n", message); printf("With this key: %s\n", key); aes_ecb_encrypt(message, key, 32); printf("Here is the encrypted result: %s\n", message); aes_ecb_decrypt(message, key, 32); printf("Here is the decrypted message: %s\n\n", message); //Cipher Block Chaining (CBC) mode, Initilization Vector (IV) required memcpy(message, "I LOVE 2 ENCRYPT WORDS WITH CBC!", 32); memcpy(key, "HERE IS MY KEY!!", 16); unsigned char iv[AES_SIZE+1] = { "HERE IS MY IV!!!" }; printf("This message will be encrypted using CBC mode: %s\n", message); printf("With this key: %s and this IV: %s\n", key, iv); aes_cbc_encrypt(message, key, 32, iv); printf("Here is the encrypted result: %s\n", message); aes_cbc_decrypt(message, key, 32, iv); printf("Here is the decrypted message: %s\n\n", message); return 0; }
30.513514
84
0.677591
[ "vector" ]
d82e43f94adbd48f08e45c6b51179cb5d3d25079
14,891
c
C
bin/varnishd/cache/cache_panic.c
otto-de/Varnish-Cache
2825c0ea6f7e902a653d7db4ce1a367979779799
[ "BSD-2-Clause" ]
null
null
null
bin/varnishd/cache/cache_panic.c
otto-de/Varnish-Cache
2825c0ea6f7e902a653d7db4ce1a367979779799
[ "BSD-2-Clause" ]
null
null
null
bin/varnishd/cache/cache_panic.c
otto-de/Varnish-Cache
2825c0ea6f7e902a653d7db4ce1a367979779799
[ "BSD-2-Clause" ]
null
null
null
/*- * Copyright (c) 2006 Verdens Gang AS * Copyright (c) 2006-2014 Varnish Software AS * All rights reserved. * * Author: Dag-Erling Smørgrav <des@des.no> * * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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" #ifndef HAVE_EXECINFO_H #include "compat/execinfo.h" #else #include <execinfo.h> #endif #include <stdio.h> #include <stdlib.h> #include <signal.h> #include "cache.h" #include "cache_filter.h" #include "vend.h" #include "common/heritage.h" #include "cache_backend.h" #include "storage/storage.h" #include "vcl.h" /* * The panic string is constructed in memory, then copied to the * shared memory. * * It can be extracted post-mortem from a core dump using gdb: * * (gdb) printf "%s", panicstr */ static struct vsb pan_vsp_storage, *pan_vsp; static pthread_mutex_t panicstr_mtx = PTHREAD_MUTEX_INITIALIZER; static void pan_sess(const struct sess *sp); /*--------------------------------------------------------------------*/ const char * body_status_2str(enum body_status e) { switch(e) { #define BODYSTATUS(U,l) case BS_##U: return (#l); #include "tbl/body_status.h" #undef BODYSTATUS default: return ("?"); } } /*--------------------------------------------------------------------*/ static const char * reqbody_status_2str(enum req_body_state_e e) { switch (e) { #define REQ_BODY(U) case REQ_BODY_##U: return("R_BODY_" #U); #include "tbl/req_body.h" #undef REQ_BODY default: return("?"); } } /*--------------------------------------------------------------------*/ const char * sess_close_2str(enum sess_close sc, int want_desc) { switch (sc) { case SC_NULL: return(want_desc ? "(null)": "NULL"); #define SESS_CLOSE(nm, desc) case SC_##nm: return(want_desc ? desc : #nm); #include "tbl/sess_close.h" #undef SESS_CLOSE default: return(want_desc ? "(invalid)" : "INVALID"); } } /*--------------------------------------------------------------------*/ static void pan_ws(const struct ws *ws, int indent) { VSB_printf(pan_vsp, "%*sws = %p {", indent, "", ws); if (!VALID_OBJ(ws, WS_MAGIC)) { if (ws != NULL) VSB_printf(pan_vsp, " BAD_MAGIC(0x%08x) ", ws->magic); } else { if (WS_Overflowed(ws)) VSB_printf(pan_vsp, " OVERFLOW"); VSB_printf(pan_vsp, "\n%*sid = \"%s\",\n", indent + 2, "", ws->id); VSB_printf(pan_vsp, "%*s{s,f,r,e} = {%p", indent + 2, "", ws->s); if (ws->f > ws->s) VSB_printf(pan_vsp, ",+%ld", (long) (ws->f - ws->s)); else VSB_printf(pan_vsp, ",%p", ws->f); if (ws->r > ws->s) VSB_printf(pan_vsp, ",+%ld", (long) (ws->r - ws->s)); else VSB_printf(pan_vsp, ",%p", ws->r); if (ws->e > ws->s) VSB_printf(pan_vsp, ",+%ld", (long) (ws->e - ws->s)); else VSB_printf(pan_vsp, ",%p", ws->e); } VSB_printf(pan_vsp, "},\n"); VSB_printf(pan_vsp, "%*s},\n", indent, "" ); } /*--------------------------------------------------------------------*/ static void pan_vbc(const struct vbc *vbc) { struct backend *be; be = vbc->backend; VSB_printf(pan_vsp, " backend = %p fd = %d {\n", be, vbc->fd); VSB_printf(pan_vsp, " display_name = \"%s\",\n", be->display_name); VSB_printf(pan_vsp, " },\n"); } /*--------------------------------------------------------------------*/ #if 0 static void pan_storage(const struct storage *st) { int i, j; #define MAX_BYTES (4*16) #define show(ch) (((ch) > 31 && (ch) < 127) ? (ch) : '.') VSB_printf(pan_vsp, " %u {\n", st->len); for (i = 0; i < MAX_BYTES && i < st->len; i += 16) { VSB_printf(pan_vsp, " "); for (j = 0; j < 16; ++j) { if (i + j < st->len) VSB_printf(pan_vsp, "%02x ", st->ptr[i + j]); else VSB_printf(pan_vsp, " "); } VSB_printf(pan_vsp, "|"); for (j = 0; j < 16; ++j) if (i + j < st->len) VSB_printf(pan_vsp, "%c", show(st->ptr[i + j])); VSB_printf(pan_vsp, "|\n"); } if (st->len > MAX_BYTES) VSB_printf(pan_vsp, " [%u more]\n", st->len - MAX_BYTES); VSB_printf(pan_vsp, " },\n"); #undef show #undef MAX_BYTES } #endif /*--------------------------------------------------------------------*/ static void pan_http(const char *id, const struct http *h, int indent) { int i; VSB_printf(pan_vsp, "%*shttp[%s] = {\n", indent, "", id); VSB_printf(pan_vsp, "%*sws = %p[%s]\n", indent + 2, "", h->ws, h->ws ? h->ws->id : ""); for (i = 0; i < h->nhd; ++i) { if (h->hd[i].b == NULL && h->hd[i].e == NULL) continue; VSB_printf(pan_vsp, "%*s\"%.*s\",\n", indent + 4, "", (int)(h->hd[i].e - h->hd[i].b), h->hd[i].b); } VSB_printf(pan_vsp, "%*s},\n", indent, ""); } /*--------------------------------------------------------------------*/ #if 0 static void pan_object(const char *typ, const struct object *o) { const struct storage *st; VSB_printf(pan_vsp, " obj (%s) = %p {\n", typ, o); VSB_printf(pan_vsp, " vxid = %u,\n", VXID(vbe32dec(o->oa_vxid))); pan_http("obj", o->http, 4); VSB_printf(pan_vsp, " len = %jd,\n", (intmax_t)o->body->len); VSB_printf(pan_vsp, " store = {\n"); VTAILQ_FOREACH(st, &o->body->list, list) pan_storage(st); VSB_printf(pan_vsp, " },\n"); VSB_printf(pan_vsp, " },\n"); } #endif /*--------------------------------------------------------------------*/ static void pan_objcore(const char *typ, const struct objcore *oc) { VSB_printf(pan_vsp, " objcore (%s) = %p {\n", typ, oc); VSB_printf(pan_vsp, " refcnt = %d\n", oc->refcnt); VSB_printf(pan_vsp, " flags = 0x%x\n", oc->flags); VSB_printf(pan_vsp, " objhead = %p\n", oc->objhead); VSB_printf(pan_vsp, " stevedore = %p", oc->stobj->stevedore); if (oc->stobj->stevedore != NULL) { VSB_printf(pan_vsp, " (%s", oc->stobj->stevedore->name); if (strlen(oc->stobj->stevedore->ident)) VSB_printf(pan_vsp, " %s", oc->stobj->stevedore->ident); VSB_printf(pan_vsp, ")"); } VSB_printf(pan_vsp, "\n"); VSB_printf(pan_vsp, " }\n"); } /*--------------------------------------------------------------------*/ static void pan_vcl(const struct VCL_conf *vcl) { int i; VSB_printf(pan_vsp, " vcl = {\n"); VSB_printf(pan_vsp, " srcname = {\n"); for (i = 0; i < vcl->nsrc; ++i) VSB_printf(pan_vsp, " \"%s\",\n", vcl->srcname[i]); VSB_printf(pan_vsp, " },\n"); VSB_printf(pan_vsp, " },\n"); } /*--------------------------------------------------------------------*/ static void pan_wrk(const struct worker *wrk) { const char *hand; unsigned m, u; const char *p; VSB_printf(pan_vsp, " worker = %p {\n", wrk); VSB_printf(pan_vsp, " stack = {0x%jx -> 0x%jx}\n", (uintmax_t)wrk->stack_start, (uintmax_t)wrk->stack_end); pan_ws(wrk->aws, 4); m = wrk->cur_method; VSB_printf(pan_vsp, " VCL::method = "); if (m == 0) { VSB_printf(pan_vsp, "none,\n"); return; } if (!(m & 1)) VSB_printf(pan_vsp, "*"); m &= ~1; hand = VCL_Method_Name(m); if (hand != NULL) VSB_printf(pan_vsp, "%s,\n", hand); else VSB_printf(pan_vsp, "0x%x,\n", m); hand = VCL_Return_Name(wrk->handling); if (hand != NULL) VSB_printf(pan_vsp, " VCL::return = %s,\n", hand); else VSB_printf(pan_vsp, " VCL::return = 0x%x,\n", wrk->handling); VSB_printf(pan_vsp, " VCL::methods = {"); m = wrk->seen_methods; p = ""; for (u = 1; m ; u <<= 1) { if (m & u) { VSB_printf(pan_vsp, "%s%s", p, VCL_Method_Name(u)); m &= ~u; p = ", "; } } VSB_printf(pan_vsp, "},\n },\n"); } static void pan_busyobj(const struct busyobj *bo) { struct vfp_entry *vfe; VSB_printf(pan_vsp, " busyobj = %p {\n", bo); pan_ws(bo->ws, 4); VSB_printf(pan_vsp, " refcnt = %u\n", bo->refcount); VSB_printf(pan_vsp, " retries = %d\n", bo->retries); VSB_printf(pan_vsp, " failed = %d\n", bo->vfc->failed); VSB_printf(pan_vsp, " state = %d\n", (int)bo->state); #define BO_FLAG(l, r, w, d) if(bo->l) VSB_printf(pan_vsp, " is_" #l "\n"); #include "tbl/bo_flags.h" #undef BO_FLAG if (bo->htc != NULL) { VSB_printf(pan_vsp, " bodystatus = %d (%s),\n", bo->htc->body_status, body_status_2str(bo->htc->body_status)); } if (!VTAILQ_EMPTY(&bo->vfc->vfp)) { VSB_printf(pan_vsp, " filters ="); VTAILQ_FOREACH(vfe, &bo->vfc->vfp, list) VSB_printf(pan_vsp, " %s=%d", vfe->vfp->name, (int)vfe->closed); VSB_printf(pan_vsp, "\n"); } VSB_printf(pan_vsp, " },\n"); if (bo->htc != NULL && bo->htc->vbc != NULL && VALID_OBJ(bo->htc->vbc, BACKEND_MAGIC)) pan_vbc(bo->htc->vbc); if (bo->bereq != NULL && bo->bereq->ws != NULL) pan_http("bereq", bo->bereq, 4); if (bo->beresp != NULL && bo->beresp->ws != NULL) pan_http("beresp", bo->beresp, 4); if (bo->fetch_objcore) pan_objcore("FETCH", bo->fetch_objcore); if (bo->ims_oc) pan_objcore("IMS", bo->ims_oc); VSB_printf(pan_vsp, " }\n"); } /*--------------------------------------------------------------------*/ static void pan_req(const struct req *req) { const char *stp; VSB_printf(pan_vsp, "req = %p {\n", req); VSB_printf(pan_vsp, " sp = %p, vxid = %u,", req->sp, VXID(req->vsl->wid)); switch (req->req_step) { #define REQ_STEP(l, u, arg) case R_STP_##u: stp = "R_STP_" #u; break; #include "tbl/steps.h" #undef REQ_STEP default: stp = NULL; } if (stp != NULL) VSB_printf(pan_vsp, " step = %s,\n", stp); else VSB_printf(pan_vsp, " step = 0x%x,\n", req->req_step); VSB_printf(pan_vsp, " req_body = %s,\n", reqbody_status_2str(req->req_body_status)); if (req->err_code) VSB_printf(pan_vsp, " err_code = %d, err_reason = %s,\n", req->err_code, req->err_reason ? req->err_reason : "(null)"); VSB_printf(pan_vsp, " restarts = %d, esi_level = %d\n", req->restarts, req->esi_level); if (req->sp != NULL) pan_sess(req->sp); if (req->wrk != NULL) pan_wrk(req->wrk); pan_ws(req->ws, 2); pan_http("req", req->http, 2); if (req->resp->ws != NULL) pan_http("resp", req->resp, 2); if (VALID_OBJ(req->vcl, VCL_CONF_MAGIC)) pan_vcl(req->vcl); if (req->objcore != NULL) { pan_objcore("REQ", req->objcore); if (req->objcore->busyobj != NULL) pan_busyobj(req->objcore->busyobj); } VSB_printf(pan_vsp, "},\n"); } /*--------------------------------------------------------------------*/ static void pan_sess(const struct sess *sp) { const char *stp; VSB_printf(pan_vsp, " sp = %p {\n", sp); VSB_printf(pan_vsp, " fd = %d, vxid = %u,\n", sp->fd, VXID(sp->vxid)); VSB_printf(pan_vsp, " client = %s %s,\n", sp->client_addr_str, sp->client_port_str); switch (sp->sess_step) { #define SESS_STEP(l, u) case S_STP_##u: stp = "S_STP_" #u; break; #include "tbl/steps.h" #undef SESS_STEP default: stp = NULL; } if (stp != NULL) VSB_printf(pan_vsp, " step = %s,\n", stp); else VSB_printf(pan_vsp, " step = 0x%x,\n", sp->sess_step); VSB_printf(pan_vsp, " },\n"); } /*--------------------------------------------------------------------*/ static void pan_backtrace(void) { void *array[10]; size_t size; size_t i; size = backtrace (array, 10); if (size == 0) return; VSB_printf(pan_vsp, "Backtrace:\n"); for (i = 0; i < size; i++) { VSB_printf (pan_vsp, " "); if (Symbol_Lookup(pan_vsp, array[i]) < 0) { char **strings; strings = backtrace_symbols(&array[i], 1); if (strings != NULL && strings[0] != NULL) VSB_printf(pan_vsp, "%p: %s", array[i], strings[0]); else VSB_printf(pan_vsp, "%p: (?)", array[i]); } VSB_printf (pan_vsp, "\n"); } } /*--------------------------------------------------------------------*/ static void __attribute__((__noreturn__)) pan_ic(const char *func, const char *file, int line, const char *cond, int err, enum vas_e kind) { const char *q; struct req *req; struct busyobj *bo; struct sigaction sa; AZ(pthread_mutex_lock(&panicstr_mtx)); /* Won't be released, we're going to die anyway */ /* * should we trigger a SIGSEGV while handling a panic, our sigsegv * handler would hide the panic, so we need to reset the handler to * default */ memset(&sa, 0, sizeof sa); sa.sa_handler = SIG_DFL; (void)sigaction(SIGSEGV, &sa, NULL); switch(kind) { case VAS_WRONG: VSB_printf(pan_vsp, "Wrong turn at %s:%d:\n%s\n", file, line, cond); break; case VAS_VCL: VSB_printf(pan_vsp, "Panic from VCL:\n %s\n", cond); break; case VAS_MISSING: VSB_printf(pan_vsp, "Missing errorhandling code in %s(), %s line %d:\n" " Condition(%s) not true.", func, file, line, cond); break; case VAS_INCOMPLETE: VSB_printf(pan_vsp, "Incomplete code in %s(), %s line %d:\n", func, file, line); break; default: case VAS_ASSERT: VSB_printf(pan_vsp, "Assert error in %s(), %s line %d:\n" " Condition(%s) not true.\n", func, file, line, cond); break; } if (err) VSB_printf(pan_vsp, "errno = %d (%s)\n", err, strerror(err)); q = THR_GetName(); if (q != NULL) VSB_printf(pan_vsp, "thread = (%s)\n", q); VSB_printf(pan_vsp, "version = %s\n", VCS_version); VSB_printf(pan_vsp, "ident = %s,%s\n", VSB_data(vident) + 1, WAIT_GetName()); pan_backtrace(); if (!FEATURE(FEATURE_SHORT_PANIC)) { req = THR_GetRequest(); if (req != NULL) { pan_req(req); VSL_Flush(req->vsl, 0); } bo = THR_GetBusyobj(); if (bo != NULL) { pan_busyobj(bo); VSL_Flush(bo->vsl, 0); } } VSB_printf(pan_vsp, "\n"); VSB_bcat(pan_vsp, "", 1); /* NUL termination */ if (FEATURE(FEATURE_NO_COREDUMP)) exit(4); else abort(); } /*--------------------------------------------------------------------*/ void PAN_Init(void) { VAS_Fail = pan_ic; pan_vsp = &pan_vsp_storage; AN(heritage.panic_str); AN(heritage.panic_str_len); AN(VSB_new(pan_vsp, heritage.panic_str, heritage.panic_str_len, VSB_FIXEDLEN)); }
26.078809
77
0.571486
[ "object" ]
d82f41ca37f3cfd0a4d42b82351d923319a10831
3,050
c
C
kernel/mm/vmobject.c
jfsulliv/os
7690e137a7c790f18f88d502595ef6e395ec95b7
[ "BSD-3-Clause" ]
2
2016-05-22T16:55:08.000Z
2016-11-27T22:01:35.000Z
kernel/mm/vmobject.c
jfsulliv/os
7690e137a7c790f18f88d502595ef6e395ec95b7
[ "BSD-3-Clause" ]
1
2016-05-27T03:23:55.000Z
2016-07-17T01:48:30.000Z
kernel/mm/vmobject.c
jfsulliv/os
7690e137a7c790f18f88d502595ef6e395ec95b7
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2016, James Sullivan <sullivan.james.f@gmail.com> 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 the <organization> 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 <COPYRIGHT HOLDER> 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 <mm/vma.h> #include <mm/vmobject.h> #include <mm/paging.h> #include <sys/panic.h> #include <sys/sysinit.h> static mem_cache_t *vmobject_cache; static void vmobject_ctor(void *p, __attribute__((unused))size_t sz) { vmobject_t *obj = (vmobject_t *)p; obj->refct = 0; obj->size = 0; obj->page = NULL; } vmobject_t * vmobject_create_anon(size_t sz, pflags_t flags) { if (sz == 0 || BAD_PFLAGS(flags)) return NULL; vmobject_t *obj = mem_cache_alloc(vmobject_cache, M_KERNEL); if (!obj) return NULL; obj->size = PAGE_ROUNDUP(sz); obj->pflags = flags; return obj; } void vmobject_destroy(vmobject_t *object) { bug_on(!object, "Destoying NULL object"); bug_on(object->refct > 0, "Destroying referenced object"); // TODO } void vmobject_add_page(vmobject_t *object, page_t *pg) { bug_on(!object, "NULL object"); bug_on(!pg, "NULL page"); bug_on(pg->next, "page is already owned"); pg->next = object->page; object->page = pg; } static int vmobject_init(void) { vmobject_cache = mem_cache_create("vmobject_cache", sizeof(vmobject_t), sizeof(vmobject_t), 0, vmobject_ctor, NULL); bug_on(!vmobject_cache, "Failed to allocate vmobject cache"); return 0; } SYSINIT_STEP("vmobject", vmobject_init, SYSINIT_VMOBJ, 0);
32.795699
72
0.688852
[ "object" ]
d8378e937cc9012115a4653de87e49e7d5b4f607
955
h
C
FastCAE_Linux/Code/GeometryCommand/GeoCommandCreateFillet.h
alleindrach/calculix-desktop
2cb2c434b536eb668ff88bdf82538d22f4f0f711
[ "MIT" ]
23
2020-03-16T03:01:43.000Z
2022-03-21T16:36:22.000Z
FastCAE_Linux/Code/GeometryCommand/GeoCommandCreateFillet.h
alleindrach/calculix-desktop
2cb2c434b536eb668ff88bdf82538d22f4f0f711
[ "MIT" ]
1
2020-03-17T05:50:07.000Z
2020-03-17T05:50:07.000Z
FastCAE_Linux/Code/GeometryCommand/GeoCommandCreateFillet.h
alleindrach/calculix-desktop
2cb2c434b536eb668ff88bdf82538d22f4f0f711
[ "MIT" ]
17
2020-03-16T01:46:36.000Z
2022-03-21T16:36:37.000Z
#ifndef GEOCOMMANDCREATEFILLET_H_ #define GEOCOMMANDCREATEFILLET_H_ #include "geometryCommandAPI.h" #include "GeoCommandBase.h" #include <QString> #include <QMultiHash> namespace Geometry { class GeometrySet; } class TopoDS_Shape; namespace Command { class GEOMETRYCOMMANDAPI CommandCreateFillet : public GeoCommandBase { Q_OBJECT public: CommandCreateFillet(GUI::MainWindow* m, MainWidget::PreWindow* p); ~CommandCreateFillet() = default; void setShapeList(QMultiHash<Geometry::GeometrySet*, int> s); void setRadius(double d); bool execute() override; void undo() override; void redo() override; void releaseResult() override; private: QString _name{"Fillet_%1"}; // Geometry::GeometrySet* _result{}; QMultiHash<Geometry::GeometrySet*, int> _shapeHash{}; double _radius{ 0.0 }; QHash<Geometry::GeometrySet*, Geometry::GeometrySet*> _inputOutputHash{}; }; } #endif
20.76087
76
0.713089
[ "geometry" ]
d838eb41673378ec350aba67526dad96cd8cbe1e
1,129
h
C
esphome/components/pzemdc/pzemdc.h
huhuhugo1/esphome
eb895d2095861a4d51f1a5fcd582a97389c27b4f
[ "MIT" ]
249
2018-04-07T12:04:11.000Z
2019-01-25T01:11:34.000Z
esphome/components/pzemdc/pzemdc.h
huhuhugo1/esphome
eb895d2095861a4d51f1a5fcd582a97389c27b4f
[ "MIT" ]
243
2018-04-11T16:37:11.000Z
2019-01-25T16:50:37.000Z
esphome/components/pzemdc/pzemdc.h
huhuhugo1/esphome
eb895d2095861a4d51f1a5fcd582a97389c27b4f
[ "MIT" ]
40
2018-04-10T05:50:14.000Z
2019-01-25T15:20:36.000Z
#pragma once #include "esphome/core/component.h" #include "esphome/components/sensor/sensor.h" #include "esphome/components/modbus/modbus.h" namespace esphome { namespace pzemdc { class PZEMDC : public PollingComponent, public modbus::ModbusDevice { public: void set_voltage_sensor(sensor::Sensor *voltage_sensor) { voltage_sensor_ = voltage_sensor; } void set_current_sensor(sensor::Sensor *current_sensor) { current_sensor_ = current_sensor; } void set_power_sensor(sensor::Sensor *power_sensor) { power_sensor_ = power_sensor; } void set_frequency_sensor(sensor::Sensor *frequency_sensor) { frequency_sensor_ = frequency_sensor; } void set_powerfactor_sensor(sensor::Sensor *powerfactor_sensor) { power_factor_sensor_ = powerfactor_sensor; } void update() override; void on_modbus_data(const std::vector<uint8_t> &data) override; void dump_config() override; protected: sensor::Sensor *voltage_sensor_; sensor::Sensor *current_sensor_; sensor::Sensor *power_sensor_; sensor::Sensor *frequency_sensor_; sensor::Sensor *power_factor_sensor_; }; } // namespace pzemdc } // namespace esphome
33.205882
112
0.779451
[ "vector" ]
d83ed39e88cf78ac52484c2cdcbc6aa39438ae24
14,102
h
C
opal/mca/pmix/pmix_server.h
spsweeney/Work-open-mpi
ae6884804e7f06c79fc65aed501bc8cbecb682e6
[ "BSD-3-Clause-Open-MPI" ]
null
null
null
opal/mca/pmix/pmix_server.h
spsweeney/Work-open-mpi
ae6884804e7f06c79fc65aed501bc8cbecb682e6
[ "BSD-3-Clause-Open-MPI" ]
null
null
null
opal/mca/pmix/pmix_server.h
spsweeney/Work-open-mpi
ae6884804e7f06c79fc65aed501bc8cbecb682e6
[ "BSD-3-Clause-Open-MPI" ]
null
null
null
/* * Copyright (c) 2014-2016 Intel, Inc. All rights reserved. * $COPYRIGHT$ * * Additional copyrights may follow * * $HEADER$ */ #ifndef OPAL_PMIX_SERVER_H #define OPAL_PMIX_SERVER_H #include "opal_config.h" #include "opal/types.h" #include "opal/mca/pmix/pmix_types.h" BEGIN_C_DECLS /**** SERVER FUNCTION-SHIPPED APIs ****/ /* NOTE: for performance purposes, the host server is required to * return as quickly as possible from all functions. Execution of * the function is thus to be done asynchronously so as to allow * the server support library to handle multiple client requests * as quickly and scalably as possible. * * ALL data passed to the host server functions is "owned" by the * server support library and MUST NOT be free'd. Data returned * by the host server via callback function is owned by the host * server, which is free to release it upon return from the callback */ /* Notify the host server that a client connected to us */ typedef int (*opal_pmix_server_client_connected_fn_t)(opal_process_name_t *proc, void* server_object, opal_pmix_op_cbfunc_t cbfunc, void *cbdata); /* Notify the host server that a client called pmix.finalize - note * that the client will be in a blocked state until the host server * executes the callback function, thus allowing the server support * library to release the client */ typedef int (*opal_pmix_server_client_finalized_fn_t)(opal_process_name_t *proc, void* server_object, opal_pmix_op_cbfunc_t cbfunc, void *cbdata); /* A local client called pmix.abort - note that the client will be in a blocked * state until the host server executes the callback function, thus * allowing the server support library to release the client. The * list of procs_to_abort indicates which processes are to be terminated. A NULL * indicates that all procs in the client's nspace are to be terminated */ typedef int (*opal_pmix_server_abort_fn_t)(opal_process_name_t *proc, void *server_object, int status, const char msg[], opal_list_t *procs_to_abort, opal_pmix_op_cbfunc_t cbfunc, void *cbdata); /* At least one client called either pmix.fence or pmix.fence_nb. In either case, * the host server will be called via a non-blocking function to execute * the specified operation once all participating local procs have * contributed. All processes in the specified list are required to participate * in the fence[_nb] operation. The callback is to be executed once each daemon * hosting at least one participant has called the host server's fencenb function. * * The list of opal_value_t includes any directives from the user regarding * how the fence is to be executed (e.g., timeout limits). * * The provided data is to be collectively shared with all host * servers involved in the fence operation, and returned in the modex * cbfunc. A _NULL_ data value indicates that the local procs had * no data to contribute */ typedef int (*opal_pmix_server_fencenb_fn_t)(opal_list_t *procs, opal_list_t *info, char *data, size_t ndata, opal_pmix_modex_cbfunc_t cbfunc, void *cbdata); /* Used by the PMIx server to request its local host contact the * PMIx server on the remote node that hosts the specified proc to * obtain and return a direct modex blob for that proc * * The list of opal_value_t includes any directives from the user regarding * how the operation is to be executed (e.g., timeout limits). */ typedef int (*opal_pmix_server_dmodex_req_fn_t)(opal_process_name_t *proc, opal_list_t *info, opal_pmix_modex_cbfunc_t cbfunc, void *cbdata); /* Publish data per the PMIx API specification. The callback is to be executed * upon completion of the operation. The host server is not required to guarantee * support for the requested scope - i.e., the server does not need to return an * error if the data store doesn't support scope-based isolation. However, the * server must return an error (a) if the key is duplicative within the storage * scope, and (b) if the server does not allow overwriting of published info by * the original publisher - it is left to the discretion of the host server to * allow info-key-based flags to modify this behavior. The persist flag indicates * how long the server should retain the data. The nspace/rank of the publishing * process is also provided and is expected to be returned on any subsequent * lookup request */ typedef int (*opal_pmix_server_publish_fn_t)(opal_process_name_t *proc, opal_list_t *info, opal_pmix_op_cbfunc_t cbfunc, void *cbdata); /* Lookup published data. The host server will be passed a NULL-terminated array * of string keys along with the scope within which the data is expected to have * been published. The host server is not required to guarantee support for all * PMIx-defined scopes, but should only search data stores within the specified * scope within the context of the corresponding "publish" API. The wait flag * indicates whether the server should wait for all data to become available * before executing the callback function, or should callback with whatever * data is immediately available. * * The list of opal_value_t includes any directives from the user regarding * how the operation is to be executed (e.g., timeout limits, whether the * lookup should wait until data appears). */ typedef int (*opal_pmix_server_lookup_fn_t)(opal_process_name_t *proc, char **keys, opal_list_t *info, opal_pmix_lookup_cbfunc_t cbfunc, void *cbdata); /* Delete data from the data store. The host server will be passed a NULL-terminated array * of string keys along with the scope within which the data is expected to have * been published. The callback is to be executed upon completion of the delete * procedure */ typedef int (*opal_pmix_server_unpublish_fn_t)(opal_process_name_t *proc, char **keys, opal_list_t *info, opal_pmix_op_cbfunc_t cbfunc, void *cbdata); /* Spawn a set of applications/processes as per the PMIx API. Note that * applications are not required to be MPI or any other programming model. * Thus, the host server cannot make any assumptions as to their required * support. The callback function is to be executed once all processes have * been started. An error in starting any application or process in this * request shall cause all applications and processes in the request to * be terminated, and an error returned to the originating caller */ typedef int (*opal_pmix_server_spawn_fn_t)(opal_process_name_t *requestor, opal_list_t *job_info, opal_list_t *apps, opal_pmix_spawn_cbfunc_t cbfunc, void *cbdata); /* Record the specified processes as "connected". This means that the resource * manager should treat the failure of any process in the specified group as * a reportable event, and take appropriate action. The callback function is * to be called once all participating processes have called connect. Note that * a process can only engage in *one* connect operation involving the identical * set of procs at a time. However, a process *can* be simultaneously engaged * in multiple connect operations, each involving a different set of procs * * The list of opal_value_t includes any directives from the user regarding * how the operation is to be executed (e.g., timeout limits). */ typedef int (*opal_pmix_server_connect_fn_t)(opal_list_t *procs, opal_list_t *info, opal_pmix_op_cbfunc_t cbfunc, void *cbdata); /* Disconnect a previously connected set of processes. An error should be returned * if the specified set of procs was not previously "connected". As above, a process * may be involved in multiple simultaneous disconnect operations. However, a process * is not allowed to reconnect to a set of ranges that has not fully completed * disconnect - i.e., you have to fully disconnect before you can reconnect to the * same group of processes. * * The list of opal_value_t includes any directives from the user regarding * how the operation is to be executed (e.g., timeout limits). */ typedef int (*opal_pmix_server_disconnect_fn_t)(opal_list_t *procs, opal_list_t *info, opal_pmix_op_cbfunc_t cbfunc, void *cbdata); /* Register to receive notifications for the specified events. The resource * manager may have access to events beyond process failure. In cases where * the client application requests to be notified of such events, the request * will be passed to the PMIx server, which in turn shall pass the request to * the resource manager. The list of opal_value_t will provide the OPAL * error codes corresponding to the desired events */ typedef int (*opal_pmix_server_register_events_fn_t)(opal_list_t *info, opal_pmix_op_cbfunc_t cbfunc, void *cbdata); /* Deregister from the specified events. The list of opal_value_t will provide the OPAL * error codes corresponding to the desired events */ typedef int (*opal_pmix_server_deregister_events_fn_t)(opal_list_t *info, opal_pmix_op_cbfunc_t cbfunc, void *cbdata); /* Notify the specified processes of an event generated either by * the PMIx server itself, or by one of its local clients. The RTE * is requested to pass the notification to each PMIx server that * hosts one or more of the specified processes */ typedef int (*opal_pmix_server_notify_fn_t)(int code, opal_process_name_t *source, opal_list_t *info, opal_pmix_op_cbfunc_t cbfunc, void *cbdata); /* Query the RTE for information - the list is composed of opal_pmix_query_t items */ typedef int (*opal_pmix_server_query_fn_t)(opal_process_name_t *requestor, opal_list_t *queries, opal_pmix_info_cbfunc_t cbfunc, void *cbdata); /* Register that a tool has connected to the server, and request * that the tool be assigned a jobid for further interactions. * The optional opal_value_t list can be used to pass qualifiers for * the connection request: * * (a) OPAL_PMIX_USERID - effective userid of the tool * (b) OPAL_PMIX_GRPID - effective groupid of the tool * (c) OPAL_PMIX_FWD_STDOUT - forward any stdout to this tool * (d) OPAL_PMIX_FWD_STDERR - forward any stderr to this tool * (e) OPAL_PMIX_FWD_STDIN - forward stdin from this tool to any * processes spawned on its behalf */ typedef void (*opal_pmix_server_tool_connection_fn_t)(opal_list_t *info, opal_pmix_tool_connection_cbfunc_t cbfunc, void *cbdata); /* Log data on behalf of the client */ typedef void (*opal_pmix_server_log_fn_t)(opal_process_name_t *requestor, opal_list_t *info, opal_list_t *directives, opal_pmix_op_cbfunc_t cbfunc, void *cbdata); /* Callback function for incoming connection requests from * local clients */ typedef void (*opal_pmix_connection_cbfunc_t)(int incoming_sd); /* Register a socket the host server can monitor for connection * requests, harvest them, and then call our internal callback * function for further processing. A listener thread is essential * to efficiently harvesting connection requests from large * numbers of local clients such as occur when running on large * SMPs. The host server listener is required to call accept * on the incoming connection request, and then passing the * resulting socket to the provided cbfunc. A NULL for this function * will cause the internal PMIx server to spawn its own listener * thread */ typedef int (*opal_pmix_server_listener_fn_t)(int listening_sd, opal_pmix_connection_cbfunc_t cbfunc); typedef struct opal_pmix_server_module_1_0_0_t { opal_pmix_server_client_connected_fn_t client_connected; opal_pmix_server_client_finalized_fn_t client_finalized; opal_pmix_server_abort_fn_t abort; opal_pmix_server_fencenb_fn_t fence_nb; opal_pmix_server_dmodex_req_fn_t direct_modex; opal_pmix_server_publish_fn_t publish; opal_pmix_server_lookup_fn_t lookup; opal_pmix_server_unpublish_fn_t unpublish; opal_pmix_server_spawn_fn_t spawn; opal_pmix_server_connect_fn_t connect; opal_pmix_server_disconnect_fn_t disconnect; opal_pmix_server_register_events_fn_t register_events; opal_pmix_server_deregister_events_fn_t deregister_events; opal_pmix_server_notify_fn_t notify_event; opal_pmix_server_query_fn_t query; opal_pmix_server_tool_connection_fn_t tool_connected; opal_pmix_server_log_fn_t log; opal_pmix_server_listener_fn_t listener; } opal_pmix_server_module_t; END_C_DECLS #endif
54.658915
101
0.683236
[ "model" ]
d84285e2031407be91c24ba9daf00adf0c18b10f
1,383
h
C
iOSOpenDev/frameworks/OfficeImport.framework/Headers/CHPCategoryAndSeriesReordering.h
bzxy/cydia
f8c838cdbd86e49dddf15792e7aa56e2af80548d
[ "MIT" ]
678
2017-11-17T08:33:19.000Z
2022-03-26T10:40:20.000Z
iOSOpenDev/frameworks/OfficeImport.framework/Headers/CHPCategoryAndSeriesReordering.h
chenfanfang/Cydia
5efce785bfd5f1064b9c0f0e29a9cc05aa24cad0
[ "MIT" ]
22
2019-04-16T05:51:53.000Z
2021-11-08T06:18:45.000Z
iOSOpenDev/frameworks/OfficeImport.framework/Headers/CHPCategoryAndSeriesReordering.h
chenfanfang/Cydia
5efce785bfd5f1064b9c0f0e29a9cc05aa24cad0
[ "MIT" ]
170
2018-06-10T07:59:20.000Z
2022-03-22T16:19:33.000Z
/** * This header is generated by class-dump-z 0.2b. * * Source: /System/Library/PrivateFrameworks/OfficeImport.framework/OfficeImport */ #import <OfficeImport/EDProcessor.h> #import <OfficeImport/CHPCategoryAndSeriesReordering.h> __attribute__((visibility("hidden"))) @interface CHPCategoryAndSeriesReordering : EDProcessor { } - (bool)isObjectSupported:(id)supported; // 0x16fb31 - (void)applyProcessorToObject:(id)object sheet:(id)sheet; // 0x173591 - (void)reorderCategoryAndSeries:(id)series sheet:(id)sheet clearAxisReversedFlag:(bool)flag; // 0x1735b5 @end @interface CHPCategoryAndSeriesReordering (CHDInternal) - (bool)isObjectSupportedForSeriesReorderingPreprocessor:(id)seriesReorderingPreprocessor isCategoryOrderReversed:(bool)reversed; // 0x1737ad - (void)applySeriesReorderingPreprocessor:(id)preprocessor; // 0x2669a9 - (void)applyCategoryReorderingPreprocessor:(id)preprocessor; // 0x1fe73d - (void)reorderSeriesCategory:(id)category dataPointCount:(unsigned)count byRow:(bool)row; // 0x1fe831 - (void)reorderValueProperties:(id)properties dataPointCount:(unsigned)count; // 0x1febc9 - (void)reorderData:(id)data dataPointCount:(unsigned)count byRow:(bool)row; // 0x1fe8b9 - (void)reorderDataValues:(id)values dataPointCount:(unsigned)count; // 0x1fe931 - (void)reorderDataFormula:(id)formula dataPointCount:(unsigned)count byRow:(bool)row; // 0x1fe99d @end
47.689655
141
0.801157
[ "object" ]
d8492f658601052d4a10e796e7dac0b65dc5d727
8,335
c
C
libs/qmlglsink/gst-plugins-good/gst/equalizer/gstiirequalizer10bands.c
ant-nihil/routen-qgroundcontrol
0868aa1d6aba3f066dbaa55c53c943fc77eb8ff7
[ "Apache-2.0" ]
2
2021-05-24T14:18:37.000Z
2022-03-04T06:59:42.000Z
libs/qmlglsink/gst-plugins-good/gst/equalizer/gstiirequalizer10bands.c
ant-nihil/routen-qgroundcontrol
0868aa1d6aba3f066dbaa55c53c943fc77eb8ff7
[ "Apache-2.0" ]
null
null
null
libs/qmlglsink/gst-plugins-good/gst/equalizer/gstiirequalizer10bands.c
ant-nihil/routen-qgroundcontrol
0868aa1d6aba3f066dbaa55c53c943fc77eb8ff7
[ "Apache-2.0" ]
null
null
null
/* GStreamer * Copyright (C) <2007> Stefan Kost <ensonic@users.sf.net> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, * Boston, MA 02110-1301, USA. */ /** * SECTION:element-equalizer-10bands * @title: equalizer-10bands * * The 10 band equalizer element allows to change the gain of 10 equally distributed * frequency bands between 30 Hz and 15 kHz. * * ## Example launch line * |[ * gst-launch-1.0 filesrc location=song.ogg ! oggdemux ! vorbisdec ! audioconvert ! equalizer-10bands band2=3.0 ! alsasink * ]| This raises the volume of the 3rd band which is at 119 Hz by 3 db. * */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "gstiirequalizer.h" #include "gstiirequalizer10bands.h" enum { PROP_BAND0 = 1, PROP_BAND1, PROP_BAND2, PROP_BAND3, PROP_BAND4, PROP_BAND5, PROP_BAND6, PROP_BAND7, PROP_BAND8, PROP_BAND9, }; static void gst_iir_equalizer_10bands_set_property (GObject * object, guint prop_id, const GValue * value, GParamSpec * pspec); static void gst_iir_equalizer_10bands_get_property (GObject * object, guint prop_id, GValue * value, GParamSpec * pspec); GST_DEBUG_CATEGORY_EXTERN (equalizer_debug); #define GST_CAT_DEFAULT equalizer_debug #define gst_iir_equalizer_10bands_parent_class parent_class G_DEFINE_TYPE (GstIirEqualizer10Bands, gst_iir_equalizer_10bands, GST_TYPE_IIR_EQUALIZER); /* equalizer implementation */ static void gst_iir_equalizer_10bands_class_init (GstIirEqualizer10BandsClass * klass) { GObjectClass *gobject_class = (GObjectClass *) klass; GstElementClass *gstelement_class = (GstElementClass *) klass; gobject_class->set_property = gst_iir_equalizer_10bands_set_property; gobject_class->get_property = gst_iir_equalizer_10bands_get_property; g_object_class_install_property (gobject_class, PROP_BAND0, g_param_spec_double ("band0", "29 Hz", "gain for the frequency band 29 Hz, ranging from -24 dB to +12 dB", -24.0, 12.0, 0.0, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS | GST_PARAM_CONTROLLABLE)); g_object_class_install_property (gobject_class, PROP_BAND1, g_param_spec_double ("band1", "59 Hz", "gain for the frequency band 59 Hz, ranging from -24 dB to +12 dB", -24.0, 12.0, 0.0, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS | GST_PARAM_CONTROLLABLE)); g_object_class_install_property (gobject_class, PROP_BAND2, g_param_spec_double ("band2", "119 Hz", "gain for the frequency band 119 Hz, ranging from -24 dB to +12 dB", -24.0, 12.0, 0.0, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS | GST_PARAM_CONTROLLABLE)); g_object_class_install_property (gobject_class, PROP_BAND3, g_param_spec_double ("band3", "237 Hz", "gain for the frequency band 237 Hz, ranging from -24 dB to +12 dB", -24.0, 12.0, 0.0, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS | GST_PARAM_CONTROLLABLE)); g_object_class_install_property (gobject_class, PROP_BAND4, g_param_spec_double ("band4", "474 Hz", "gain for the frequency band 474 Hz, ranging from -24 dB to +12 dB", -24.0, 12.0, 0.0, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS | GST_PARAM_CONTROLLABLE)); g_object_class_install_property (gobject_class, PROP_BAND5, g_param_spec_double ("band5", "947 Hz", "gain for the frequency band 947 Hz, ranging from -24 dB to +12 dB", -24.0, 12.0, 0.0, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS | GST_PARAM_CONTROLLABLE)); g_object_class_install_property (gobject_class, PROP_BAND6, g_param_spec_double ("band6", "1889 Hz", "gain for the frequency band 1889 Hz, ranging from -24 dB to +12 dB", -24.0, 12.0, 0.0, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS | GST_PARAM_CONTROLLABLE)); g_object_class_install_property (gobject_class, PROP_BAND7, g_param_spec_double ("band7", "3770 Hz", "gain for the frequency band 3770 Hz, ranging from -24 dB to +12 dB", -24.0, 12.0, 0.0, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS | GST_PARAM_CONTROLLABLE)); g_object_class_install_property (gobject_class, PROP_BAND8, g_param_spec_double ("band8", "7523 Hz", "gain for the frequency band 7523 Hz, ranging from -24 dB to +12 dB", -24.0, 12.0, 0.0, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS | GST_PARAM_CONTROLLABLE)); g_object_class_install_property (gobject_class, PROP_BAND9, g_param_spec_double ("band9", "15011 Hz", "gain for the frequency band 15011 Hz, ranging from -24 dB to +12 dB", -24.0, 12.0, 0.0, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS | GST_PARAM_CONTROLLABLE)); gst_element_class_set_static_metadata (gstelement_class, "10 Band Equalizer", "Filter/Effect/Audio", "Direct Form 10 band IIR equalizer", "Stefan Kost <ensonic@users.sf.net>"); } static void gst_iir_equalizer_10bands_init (GstIirEqualizer10Bands * equ_n) { GstIirEqualizer *equ = GST_IIR_EQUALIZER (equ_n); gst_iir_equalizer_compute_frequencies (equ, 10); } static void gst_iir_equalizer_10bands_set_property (GObject * object, guint prop_id, const GValue * value, GParamSpec * pspec) { GstChildProxy *equ = GST_CHILD_PROXY (object); switch (prop_id) { case PROP_BAND0: gst_child_proxy_set_property (equ, "band0::gain", value); break; case PROP_BAND1: gst_child_proxy_set_property (equ, "band1::gain", value); break; case PROP_BAND2: gst_child_proxy_set_property (equ, "band2::gain", value); break; case PROP_BAND3: gst_child_proxy_set_property (equ, "band3::gain", value); break; case PROP_BAND4: gst_child_proxy_set_property (equ, "band4::gain", value); break; case PROP_BAND5: gst_child_proxy_set_property (equ, "band5::gain", value); break; case PROP_BAND6: gst_child_proxy_set_property (equ, "band6::gain", value); break; case PROP_BAND7: gst_child_proxy_set_property (equ, "band7::gain", value); break; case PROP_BAND8: gst_child_proxy_set_property (equ, "band8::gain", value); break; case PROP_BAND9: gst_child_proxy_set_property (equ, "band9::gain", value); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); break; } } static void gst_iir_equalizer_10bands_get_property (GObject * object, guint prop_id, GValue * value, GParamSpec * pspec) { GstChildProxy *equ = GST_CHILD_PROXY (object); switch (prop_id) { case PROP_BAND0: gst_child_proxy_get_property (equ, "band0::gain", value); break; case PROP_BAND1: gst_child_proxy_get_property (equ, "band1::gain", value); break; case PROP_BAND2: gst_child_proxy_get_property (equ, "band2::gain", value); break; case PROP_BAND3: gst_child_proxy_get_property (equ, "band3::gain", value); break; case PROP_BAND4: gst_child_proxy_get_property (equ, "band4::gain", value); break; case PROP_BAND5: gst_child_proxy_get_property (equ, "band5::gain", value); break; case PROP_BAND6: gst_child_proxy_get_property (equ, "band6::gain", value); break; case PROP_BAND7: gst_child_proxy_get_property (equ, "band7::gain", value); break; case PROP_BAND8: gst_child_proxy_get_property (equ, "band8::gain", value); break; case PROP_BAND9: gst_child_proxy_get_property (equ, "band9::gain", value); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); break; } }
36.23913
122
0.704019
[ "object" ]
d84d34bb51cf8ff6856998a4445a424f38ddae33
4,011
h
C
core/embed/extmod/modtrezorcrypto/modtrezorcrypto-sha512.h
Kayuii/trezor-crypto
6556616681a4e2d7e18817e8692d4f6e041dee01
[ "MIT" ]
null
null
null
core/embed/extmod/modtrezorcrypto/modtrezorcrypto-sha512.h
Kayuii/trezor-crypto
6556616681a4e2d7e18817e8692d4f6e041dee01
[ "MIT" ]
1
2019-02-08T00:22:42.000Z
2019-02-13T09:41:54.000Z
core/embed/extmod/modtrezorcrypto/modtrezorcrypto-sha512.h
Kayuii/trezor-crypto
6556616681a4e2d7e18817e8692d4f6e041dee01
[ "MIT" ]
2
2019-02-07T23:57:09.000Z
2020-10-21T07:07:27.000Z
/* * This file is part of the TREZOR project, https://trezor.io/ * * Copyright (c) SatoshiLabs * * This program 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 of the License, or * (at your option) any later version. * * 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "py/objstr.h" #include "memzero.h" #include "sha2.h" /// package: trezorcrypto.__init__ /// class Sha512: /// ''' /// SHA512 context. /// ''' typedef struct _mp_obj_Sha512_t { mp_obj_base_t base; SHA512_CTX ctx; } mp_obj_Sha512_t; STATIC mp_obj_t mod_trezorcrypto_Sha512_update(mp_obj_t self, mp_obj_t data); /// def __init__(self, data: bytes = None) -> None: /// ''' /// Creates a hash context object. /// ''' STATIC mp_obj_t mod_trezorcrypto_Sha512_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { mp_arg_check_num(n_args, n_kw, 0, 1, false); mp_obj_Sha512_t *o = m_new_obj(mp_obj_Sha512_t); o->base.type = type; sha512_Init(&(o->ctx)); if (n_args == 1) { mod_trezorcrypto_Sha512_update(MP_OBJ_FROM_PTR(o), args[0]); } return MP_OBJ_FROM_PTR(o); } /// def hash(self, data: bytes) -> None: /// ''' /// Update the hash context with hashed data. /// ''' STATIC mp_obj_t mod_trezorcrypto_Sha512_update(mp_obj_t self, mp_obj_t data) { mp_obj_Sha512_t *o = MP_OBJ_TO_PTR(self); mp_buffer_info_t msg; mp_get_buffer_raise(data, &msg, MP_BUFFER_READ); if (msg.len > 0) { sha512_Update(&(o->ctx), msg.buf, msg.len); } return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_2(mod_trezorcrypto_Sha512_update_obj, mod_trezorcrypto_Sha512_update); /// def digest(self) -> bytes: /// ''' /// Returns the digest of hashed data. /// ''' STATIC mp_obj_t mod_trezorcrypto_Sha512_digest(mp_obj_t self) { mp_obj_Sha512_t *o = MP_OBJ_TO_PTR(self); uint8_t out[SHA512_DIGEST_LENGTH]; SHA512_CTX ctx; memcpy(&ctx, &(o->ctx), sizeof(SHA512_CTX)); sha512_Final(&ctx, out); memzero(&ctx, sizeof(SHA512_CTX)); return mp_obj_new_bytes(out, sizeof(out)); } STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_trezorcrypto_Sha512_digest_obj, mod_trezorcrypto_Sha512_digest); STATIC mp_obj_t mod_trezorcrypto_Sha512___del__(mp_obj_t self) { mp_obj_Sha512_t *o = MP_OBJ_TO_PTR(self); memzero(&(o->ctx), sizeof(SHA512_CTX)); return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_trezorcrypto_Sha512___del___obj, mod_trezorcrypto_Sha512___del__); STATIC const mp_rom_map_elem_t mod_trezorcrypto_Sha512_locals_dict_table[] = { {MP_ROM_QSTR(MP_QSTR_update), MP_ROM_PTR(&mod_trezorcrypto_Sha512_update_obj)}, {MP_ROM_QSTR(MP_QSTR_digest), MP_ROM_PTR(&mod_trezorcrypto_Sha512_digest_obj)}, {MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&mod_trezorcrypto_Sha512___del___obj)}, {MP_ROM_QSTR(MP_QSTR_block_size), MP_OBJ_NEW_SMALL_INT(SHA512_BLOCK_LENGTH)}, {MP_ROM_QSTR(MP_QSTR_digest_size), MP_OBJ_NEW_SMALL_INT(SHA512_DIGEST_LENGTH)}, }; STATIC MP_DEFINE_CONST_DICT(mod_trezorcrypto_Sha512_locals_dict, mod_trezorcrypto_Sha512_locals_dict_table); STATIC const mp_obj_type_t mod_trezorcrypto_Sha512_type = { {&mp_type_type}, .name = MP_QSTR_Sha512, .make_new = mod_trezorcrypto_Sha512_make_new, .locals_dict = (void *)&mod_trezorcrypto_Sha512_locals_dict, };
34.577586
78
0.700075
[ "object" ]
d84d57e32355d5ec6702f2d4d8c80b01464eae19
380,334
c
C
qd/cae/dyna_cpp/dyna/binout/lsda/l2a.c
martinventer/musical-dollop
debb36b87551a68fddee16a3d1194f9961d13756
[ "MIT" ]
104
2017-08-29T19:33:53.000Z
2022-03-19T11:36:05.000Z
qd/cae/dyna_cpp/dyna/binout/lsda/l2a.c
martinventer/musical-dollop
debb36b87551a68fddee16a3d1194f9961d13756
[ "MIT" ]
72
2017-08-10T10:59:43.000Z
2021-10-06T19:06:50.000Z
qd/cae/dyna_cpp/dyna/binout/lsda/l2a.c
martinventer/musical-dollop
debb36b87551a68fddee16a3d1194f9961d13756
[ "MIT" ]
37
2017-11-20T14:00:56.000Z
2022-03-09T17:19:06.000Z
/* Copyright (C) 2002 by Livermore Software Technology Corp. (LSTC) All rights reserved */ #include <stdlib.h> #include <stdio.h> #ifdef MACX #include <sys/malloc.h> #else #include <malloc.h> #endif #include <ctype.h> #include <string.h> #include <math.h> /* Requested by ARUP for portability */ #ifndef LOCALIZED #include "lsda.h" #endif /* ** structure definitions */ typedef struct { char states[20][32]; int idsize; int *ids,*mat,*state,*locats,*locatn,*nip,*nqt; float *sxx,*syy,*szz,*sxy,*syz,*szx,*yield,*effsg; } MDSOLID; typedef struct { char states[20][32]; int idsize,nhv; int *ids,*mat,*ndata,*nhist; float *data,*hist,*strain; } MDHIST; /* for solid_hist, shell_hist, etc */ typedef struct { char states[20][32]; char system[8]; int *state,*ids,*mat,*nip,*npl,*locats,*locatn,*damage; float *sxx,*syy,*szz,*sxy,*syz,*szx; float *exx,*eyy,*ezz,*exy,*eyz,*ezx; float *lxx,*lyy,*lzz,*lxy,*lyz,*lzx; float *uxx,*uyy,*uzz,*uxy,*uyz,*uzx; float *yield,*effsg; } MDTSHELL; typedef struct { int idsize, dsize; int *ids, *mat, *nip, *mtype; float *axial, *shears, *sheart, *moments, *momentt, *torsion; float *clength, *vforce; float *s11,*s12,*s31,*plastic; } MDBEAM; typedef struct { char states[20][32]; char system[8]; int idsize, dsize; int *ids, *mat, *nip, *state, *iop, *npl, *nqt, *locats, *locatn; int *damage; float *sxx, *syy, *szz; float *sxy, *syz, *szx; float *ps; float *exx, *eyy, *ezz; float *exy, *eyz, *ezx; float *lxx, *lyy, *lzz; float *lxy, *lyz, *lzx; float *uxx, *uyy, *uzz; float *uxy, *uyz, *uzx; } MDSHELL; typedef struct { char states[20][32]; char system[8]; int *ids; float *factor, *lyield, *uyield; float *lxx, *lyy, *lzz,*lxy, *lyz, *lzx; float *uxx, *uyy, *uzz,*uxy, *uyz, *uzx; } MDNODAVG; typedef struct { int num; int *ids,*setid,*locats,*locatn; float *xf,*yf,*zf,*e,*xm,*ym,*zm; } BND_DATA; /* ** Function prototypes */ int translate_secforc(int handle); int translate_rwforc(int handle); int translate_nodout(int handle); int translate_curvout(int handle); int translate_nodouthf(int handle); int translate_elout(int handle); int translate_eloutdet(int handle); int translate_glstat(int handle); int translate_ssstat(int handle); int translate_deforc(int handle); int translate_matsum(int handle); int translate_ncforc(int handle); int translate_rcforc(int handle); int translate_spcforc(int handle); int translate_swforc(int handle); int translate_abstat(int handle); int translate_abstat_cpm(int handle); int translate_abstat_pbm(int handle); int translate_cpm_sensor(int handle); int translate_cpm_sensor_new(int handle); int translate_pgstat(int handle); int translate_pg_sensor(int handle); int translate_pg_sensor_new(int handle); int translate_nodfor(int handle); int translate_bndout(int handle); int translate_rbdout(int handle); int translate_gceout(int handle); int translate_sleout(int handle); int translate_sbtout(int handle); int translate_jntforc(int handle); int translate_sphout(int handle); int translate_defgeo(int handle); int translate_dcfail(int handle); int translate_tprint(int handle); int translate_trhist(int handle); int translate_dbsensor(int handle); int translate_dbfsi(int handle); int translate_elout_ssd(int handle); int translate_elout_spcm(int handle); int translate_elout_psd(int handle); int translate_nodout_ssd(int handle); int translate_nodout_spcm(int handle); int translate_nodout_psd(int handle); int translate_pllyout(int handle); int translate_dem_rcforc(int handle); int translate_disbout(int handle); int translate_dem_trhist(int handle); void output_title(int , char *, FILE *); void output_legend(int, FILE *, int, int); int elout_solid(FILE *, int, int, MDSOLID *); int elout_tshell(FILE *, int, int, MDTSHELL *); int elout_beam(FILE *, int, int, MDBEAM *); int elout_shell(FILE *, int, int, MDSHELL *); int eloutdet_solid(FILE *, int, int, int, int, int, int, MDSOLID *); int eloutdet_tshell(FILE *, int, int, int, int, int, int,MDTSHELL *); int eloutdet_shell(FILE *, int, int, int, int, int, int,MDSHELL *); int eloutdet_nodavg(FILE *, int, int, MDNODAVG *); int comp_ncn(const void *, const void *); int bndout_dn(FILE *, int, int, BND_DATA *, float *, float *, float *, float *, int *); int bndout_dr(FILE *, int, int, BND_DATA *, float *, float *, float *, float *, int *); int bndout_p(FILE *, int, int, BND_DATA *, int *); int bndout_vn(FILE *, int, int, BND_DATA *, float *, float *, float *, float *, int *); int bndout_vr(FILE *, int, int, BND_DATA *, float *, float *, float *, float *, int *); int bndout_or(FILE *, int, int, BND_DATA *, float *, float *, float *, float *, int *); /* ** New static functions */ static char *tochar2(float,int); static void db_floating_format(float, int, char *, int, int); static char output_path[256]; static char output_file[256]; /* * Requested by ARUP for portability: */ #ifdef LOCALIZED #include "lsda_localizations.inc" #else static void write_message(FILE *fp, char *string) { if (!fp) printf("Unable to open : %s\n",string); else printf("Writing : %s\n",string); } #endif void l2a_set_output_path(char *pwd) { strcpy(output_path, pwd); } void output_legend(int handle, FILE *fp,int NO_LONGER_USED, int last) { int i,bpt,typid,filenum,*ids,num; char *legend; LSDA_Length length; char format[64]; static int need_begin = 1; lsda_queryvar(handle,"legend_ids",&typid,&length,&filenum); num = length; if(num > 0) { /* The length of each title is either 70 or 80 (or maybe changed in future?) So figure out what it is, and create the proper output format string bpt = bytes per title */ lsda_queryvar(handle,"legend",&typid,&length,&filenum); bpt = length / num; sprintf(format,"%%9d %%.%ds\n",bpt); ids = (int *) malloc(num*sizeof(int)); legend = (char *) malloc(bpt*num); lsda_read(handle,LSDA_INT,"legend_ids",0,num,ids); lsda_read(handle,LSDA_I1,"legend",0,bpt*num,legend); if(need_begin) { fprintf(fp,"\n{BEGIN LEGEND}\n"); fprintf(fp," Entity # Title\n"); need_begin=0; } for(i=0; i<num; i++) { fprintf(fp,format,ids[i],legend+bpt*i); } free(legend); free(ids); } if(last) { /* have to finish off legend.... */ if(need_begin) fprintf(fp,"\n\n"); /* legend never started -- leave empty */ else fprintf(fp,"\n{END LEGEND}\n"); /* finish legend */ need_begin = 1; } return; } void output_legend_nosort(int handle, FILE *fp,int NO_LONGER_USED, int last, int *no_sort) { int i,bpt,typid,filenum,*ids,num,k; char *legend; LSDA_Length length; char format[64]; static int need_begin = 1; lsda_queryvar(handle,"legend_ids",&typid,&length,&filenum); num = length; if(num > 0) { /* The length of each title is either 70 or 80 (or maybe changed in future?) So figure out what it is, and create the proper output format string bpt = bytes per title */ lsda_queryvar(handle,"legend",&typid,&length,&filenum); bpt = length / num; sprintf(format,"%%9d %%.%ds\n",bpt); ids = (int *) malloc(num*sizeof(int)); legend = (char *) malloc(bpt*num); lsda_read(handle,LSDA_INT,"legend_ids",0,num,ids); lsda_read(handle,LSDA_I1,"legend",0,bpt*num,legend); if(need_begin) { fprintf(fp,"\n{BEGIN LEGEND}\n"); fprintf(fp," Entity # Title\n"); need_begin=0; } for(k=0; k<num; k++) { i=no_sort[k]-1; fprintf(fp,format,ids[i],legend+bpt*i); } if(last) fprintf(fp,"{END LEGEND}\n\n"); free(legend); free(ids); } if(last) { /* have to finish off legend.... */ if(need_begin) fprintf(fp,"\n\n"); /* legend never started -- leave empty */ else fprintf(fp,"\n{END LEGEND}\n"); /* finish legend */ need_begin = 0; } return; } void output_title(int handle, char *path, FILE *fp) { int typid,filenum; char pwd[512]; char title[81],version[13],revision[11],date[11]; char s1[32],s2[32],sout[64]; int i1,i2,major,minor; LSDA_Length length; /* save current location in file so we can restore it */ strcpy(pwd,lsda_getpwd(handle)); /* move to metadata directory where stuff should live */ lsda_cd(handle,path); lsda_read(handle,LSDA_I1,"title",0,80,title); title[72]=0; lsda_read(handle,LSDA_I1,"date",0,10,date); date[10]=0; /* write header */ fprintf(fp," %s\n",title); /* Older version of this file had "version" as 10 bytes, and did not have "revision" at all. When "revision" was added, "version" became 12 bytes, and the output format changed a bit... */ lsda_queryvar(handle,"revision",&typid,&length,&filenum); if(typid > 0) { /* revision exists -- new format */ lsda_read(handle,LSDA_I1,"version",0,12,version); version[12]=0; lsda_read(handle,LSDA_I1,"revision",0,10,revision); revision[10]=0; /* version is something like "ls971 beta" and revision is something like " 5434.012 ". Either might have leading and/or trailing spaces. I want to put together a string like: "ls971.5434.012 beta" (the "beta" is optional) */ i1=sscanf(version,"%s %s",s1,s2); if(i1 < 2) s2[0]=0; i2=sscanf(revision,"%d.%d",&major,&minor); if(i2 < 2) { sprintf(sout,"%s.%d %s",s1,major,s2); } else { sprintf(sout,"%s.%d.%3.3d %s",s1,major,minor,s2); } fprintf(fp," ls-dyna %-22s date %s\n",sout,date); } else { /* no revision -- old format */ lsda_read(handle,LSDA_I1,"version",0,10,version); version[10]=0; fprintf(fp," ls-dyna (version %s) date %s\n",version,date); } lsda_cd(handle,pwd); } LSDADir *next_dir(int handle, char *pwd, LSDADir *dp, char *name) /* Look for data directories. The first time this is called (dp==NULL), we open the directory and start reading the listing. We return each time we find a subdirectory in the form "dXXXXXXX" where X are all digits. readdir returns things in alphabetic order, so we should be getting them in the correct order, no problem. When we can't find any more, return NULL. We fill in the directory name in "name", and CD in to the new directory. And we return the new value of dp -- this is just easier than passing &dp and having all those extra * floating around... */ { char path[64]; int typid; LSDA_Length length; int i,filenum; if(!dp) dp = lsda_opendir(handle,pwd); if(!dp) return NULL; while (1) { lsda_readdir(dp,name,&typid,&length,&filenum); if(name[0]==0) { /* end of directory listing */ lsda_closedir(dp); return NULL; } if(typid==0 && name[0] == 'd') { for(i=1; name[i] && isdigit(name[i]); i++) ; if(!name[i]) { sprintf(path,"%s/%s",pwd,name); lsda_cd(handle,path); return dp; } } } } int next_dir_6or8digitd(int handle, char *pwd, int state) { char dirname[128]; int typid; LSDA_Length length; int i,filenum; if(state<=999999) sprintf(dirname,"%s/d%6.6d",pwd,state); else sprintf(dirname,"%s/d%8.8d",pwd,state); lsda_queryvar(handle,dirname,&typid,&length,&filenum); if(typid != 0) return 0; lsda_cd(handle,dirname); return 1; } /* SECFORC file */ int translate_secforc(int handle) { int i,typid,num,filenum,state,need_renumber; LSDA_Length length; char dirname[32]; int *ids, *idfix; int *rigidbody; int *accelerometer; int *coordinate_system; float time; float *x_force; float *y_force; float *z_force; float *total_force; float *x_moment; float *y_moment; float *z_moment; float *total_moment; float *x_centroid; float *y_centroid; float *z_centroid; float *area; FILE *fp; LSDADir *dp = NULL; if (lsda_cd(handle,"/secforc/metadata") == -1) return 0; printf("Extracting SECFORC data\n"); lsda_queryvar(handle,"ids",&typid,&length,&filenum); num=length; /* allocate memory to read in 1 state */ ids = (int *) malloc(num*sizeof(int)); rigidbody = (int *) malloc(num*sizeof(int)); accelerometer = (int *) malloc(num*sizeof(int)); coordinate_system = (int *) malloc(num*sizeof(int)); x_force = (float *) malloc(num*sizeof(float)); y_force = (float *) malloc(num*sizeof(float)); z_force = (float *) malloc(num*sizeof(float)); total_force = (float *) malloc(num*sizeof(float)); x_moment = (float *) malloc(num*sizeof(float)); y_moment = (float *) malloc(num*sizeof(float)); z_moment = (float *) malloc(num*sizeof(float)); total_moment = (float *) malloc(num*sizeof(float)); x_centroid = (float *) malloc(num*sizeof(float)); y_centroid = (float *) malloc(num*sizeof(float)); z_centroid = (float *) malloc(num*sizeof(float)); area = (float *) malloc(num*sizeof(float)); /* Read metadata */ lsda_read(handle,LSDA_INT,"ids",0,num,ids); /* * There is a bug in some of the earlier releases of DYNA, whereby the * MPP code assigns the wrong ids to the cross sections: each processor * numbers their own from 1-n locally. The result is that the id numbers * actually written can be wrong. The actual data is correct, and in the * correct order. So, if we can detect this condition, we will just * renumber them here from 1 to num. In the broken code, each section * gets, as its id, the max of its ids on all the processors it lives on. * The only thing we can reliably look for is collisions. If there are * no collisions, there is no why to be SURE the data is not correct. * But watch for ids > num, in case the user assigned IDs (which are * honored, even in the broken code). */ idfix = rigidbody; /* use this as scratch space. */ memset(idfix,0,num*sizeof(int)); need_renumber = 0; for(i=0; i<num; i++) { if(ids[i] > 0 && ids[i] <= num) { if(++idfix[ids[i]-1] > 1) need_renumber=1; } } if(need_renumber) { for(i=0; i<num; i++) { if(ids[i] > 0 && ids[i] <= num) /* leave user given IDS alone... */ ids[i]=i+1; } } lsda_read(handle,LSDA_INT,"rigidbody",0,num,rigidbody); lsda_read(handle,LSDA_INT,"accelerometer",0,num,accelerometer); lsda_queryvar(handle,"coordinate_system",&typid,&length,&filenum); if(typid > 0) { lsda_read(handle,LSDA_INT,"coordinate_system",0,num,coordinate_system); } else { memset(coordinate_system,0,num*sizeof(int)); } /* open file and write header */ sprintf(output_file,"%ssecforc",output_path); fp=fopen(output_file,"w"); write_message(fp,output_file); if (!fp) return 0; output_title(handle,"/secforc/metadata",fp); output_legend(handle,fp,1,1); fprintf(fp,"\n\n"); fprintf(fp," line#1 section# time x-force y-force z-force magnitude\n"); fprintf(fp," line#2 resultant moments x-moment y-moment z-moment magnitude\n"); fprintf(fp," line#3 centroids x y z area \n"); /* Loop through time states and write each one */ for(state=1; (dp = next_dir(handle,"/secforc",dp,dirname)) != NULL; state++) { if(lsda_read(handle,LSDA_FLOAT,"time",0,1,&time) != 1) break; if(lsda_read(handle,LSDA_FLOAT,"x_force",0,num,x_force) != num) break; if(lsda_read(handle,LSDA_FLOAT,"y_force",0,num,y_force) != num) break; if(lsda_read(handle,LSDA_FLOAT,"z_force",0,num,z_force) != num) break; if(lsda_read(handle,LSDA_FLOAT,"total_force",0,num,total_force) != num) break; if(lsda_read(handle,LSDA_FLOAT,"x_moment",0,num,x_moment) != num) break; if(lsda_read(handle,LSDA_FLOAT,"y_moment",0,num,y_moment) != num) break; if(lsda_read(handle,LSDA_FLOAT,"z_moment",0,num,z_moment) != num) break; if(lsda_read(handle,LSDA_FLOAT,"total_moment",0,num,total_moment) != num) break; if(lsda_read(handle,LSDA_FLOAT,"x_centroid",0,num,x_centroid) != num) break; if(lsda_read(handle,LSDA_FLOAT,"y_centroid",0,num,y_centroid) != num) break; if(lsda_read(handle,LSDA_FLOAT,"z_centroid",0,num,z_centroid) != num) break; if(lsda_read(handle,LSDA_FLOAT,"area",0,num,area) != num) break; for(i=0; i<num; i++) { fprintf(fp,"%12d%15.5E",ids[i],time); fprintf(fp,"%15.4E%12.4E%12.4E%12.4E\n",x_force[i],y_force[i],z_force[i],total_force[i]); if(rigidbody[i] != 0) { fprintf(fp,"rb ID =%8d ",rigidbody[i]); } else if(accelerometer[i] != 0) { fprintf(fp,"ac ID =%8d ",accelerometer[i]); } else if(coordinate_system[i] != 0) { fprintf(fp,"cs ID =%8d ",coordinate_system[i]); } else { fprintf(fp,"global system "); } fprintf(fp,"%15.4E%12.4E%12.4E%12.4E\n",x_moment[i],y_moment[i],z_moment[i],total_moment[i]); fprintf(fp," "); fprintf(fp,"%15.4E%12.4E%12.4E%12.4E\n\n",x_centroid[i],y_centroid[i],z_centroid[i],area[i]); } } fclose(fp); free(area); free(z_centroid); free(y_centroid); free(x_centroid); free(total_moment); free(z_moment); free(y_moment); free(x_moment); free(total_force); free(z_force); free(y_force); free(x_force); free(coordinate_system); free(accelerometer); free(rigidbody); free(ids); printf(" %d states extracted\n",state-1); return 0; } /* RWFORC file */ typedef struct _ipair { int id; int pos; } IPAIR; int ipsort(const void *v1, const void *v2) { IPAIR *ip1 = (IPAIR *) v1; IPAIR *ip2 = (IPAIR *) v2; return (ip1->id - ip2->id); } int translate_rwforc(int handle) { int i,j,k,typid,num,filenum,state; LSDA_Length length; char dirname[128],dname[32]; int *ids,*setid; int *nwalls,maxwall; float time; float *fx,*fy,*fz,*fn; float *sfx,*sfy,*sfz,tx,ty,tz; int *ftid,*ftns,*ftwall,ncycle,nft; IPAIR *ftsort; float *ftx,*fty,*ftz; FILE *fp; LSDADir *dp = NULL; if (lsda_cd(handle,"/rwforc/forces/metadata") == -1) return 0; printf("Extracting RWFORC data\n"); /* Read metadata */ lsda_queryvar(handle,"ids",&typid,&length,&filenum); num=length; ids = (int *) malloc(num*sizeof(int)); nwalls = (int *) malloc(num*sizeof(int)); setid = (int *) malloc(num*sizeof(int)); lsda_read(handle,LSDA_INT,"ids",0,num,ids); lsda_read(handle,LSDA_INT,"setid",0,num,setid); /* Check for force transducers */ if (lsda_cd(handle,"/rwforc/transducer/metadata") == -1) { nft=0; } else { lsda_queryvar(handle,"ids",&typid,&length,&filenum); nft=length; ftid = (int *) malloc(nft*sizeof(int)); ftns = (int *) malloc(nft*sizeof(int)); ftwall = (int *) malloc(nft*sizeof(int)); ftx = (float *) malloc(nft*sizeof(int)); fty = (float *) malloc(nft*sizeof(int)); ftz = (float *) malloc(nft*sizeof(int)); /* and read in metadata for them while we are here */ lsda_read(handle,LSDA_INTEGER,"ids",0,nft,ftid); lsda_read(handle,LSDA_INTEGER,"nodeset",0,nft,ftns); lsda_read(handle,LSDA_INTEGER,"rigidwall",0,nft,ftwall); /* resort pointer: to make sure the data is output in increasing order of transducer ID. MPP already does this, but SMP may not, and it is easy enough to do here rather than in dyna */ ftsort = (IPAIR *) malloc(nft*sizeof(IPAIR)); for (i=0; i<nft; i++) { ftsort[i].id = ftid[i]; ftsort[i].pos = i; } qsort(ftsort,nft,sizeof(IPAIR),ipsort); } /* allocate memory to read in 1 state */ fx = (float *) malloc(num*sizeof(float)); fy = (float *) malloc(num*sizeof(float)); fz = (float *) malloc(num*sizeof(float)); fn = (float *) malloc(num*sizeof(float)); /* see which if any walls have segments defined for them... */ for(i=maxwall=0; i<num; i++) { sprintf(dirname,"/rwforc/wall%3.3d/metadata/ids",i+1); lsda_queryvar(handle,dirname,&typid,&length,&filenum); if(typid > 0) nwalls[i] = length; else nwalls[i] = 0; if(maxwall < nwalls[i]) maxwall=nwalls[i]; } if(maxwall > 0) { sfx = (float *) malloc(maxwall*sizeof(float)); sfy = (float *) malloc(maxwall*sizeof(float)); sfz = (float *) malloc(maxwall*sizeof(float)); } /* open file and write header */ sprintf(output_file,"%srwforc",output_path); fp=fopen(output_file,"w"); write_message(fp,output_file); if (!fp) return 0; output_title(handle,"/rwforc/forces/metadata",fp); output_legend(handle,fp,1,1); /* Loop through time states and write each one */ for(state=1; (dp = next_dir(handle,"/rwforc/forces",dp,dname)) != NULL; state++) { if(state==1 || nft > 0) { fprintf(fp,"\n\n"); fprintf(fp," time wall# normal-force x-force y-force z-force\n"); } if(lsda_read(handle,LSDA_FLOAT,"time",0,1,&time) != 1) break; if(lsda_read(handle,LSDA_FLOAT,"x_force",0,num,fx) != num) break; if(lsda_read(handle,LSDA_FLOAT,"y_force",0,num,fy) != num) break; if(lsda_read(handle,LSDA_FLOAT,"z_force",0,num,fz) != num) break; if(lsda_read(handle,LSDA_FLOAT,"normal_force",0,num,fn) != num) break; for(i=0; i<num; i++) { fprintf(fp,"%12.5E%8d%15.6E%15.6E%15.6E%15.6E\n", time,setid[i],fn[i],fx[i],fy[i],fz[i]); if(nwalls[i] > 0) { sprintf(dirname,"/rwforc/wall%3.3d/%s",i+1,dname); lsda_cd(handle,dirname); if(lsda_read(handle,LSDA_FLOAT,"x_force",0,nwalls[i],sfx) != nwalls[i]) break; if(lsda_read(handle,LSDA_FLOAT,"y_force",0,nwalls[i],sfy) != nwalls[i]) break; if(lsda_read(handle,LSDA_FLOAT,"z_force",0,nwalls[i],sfz) != nwalls[i]) break; if(lsda_read(handle,LSDA_FLOAT,"total_x",0,1,&tx) != 1) break; if(lsda_read(handle,LSDA_FLOAT,"total_y",0,1,&ty) != 1) break; if(lsda_read(handle,LSDA_FLOAT,"total_z",0,1,&tz) != 1) break; fprintf(fp," seg# \n"); for(j=0; j<nwalls[i]; j++) { fprintf(fp," %8d %15.6E%15.6E%15.6E\n", j+1,sfx[j],sfy[j],sfz[j]); } fprintf(fp," total force %15.6E%15.6E%15.6E\n", tx,ty,tz); } } if(nft > 0) { sprintf(dirname,"/rwforc/transducer/%s",dname); lsda_cd(handle,dirname); if(lsda_read(handle,LSDA_INTEGER,"cycle",0,1,&ncycle) != 1) break; if(lsda_read(handle,LSDA_FLOAT,"x_force",0,nft,ftx) != nft) break; if(lsda_read(handle,LSDA_FLOAT,"y_force",0,nft,fty) != nft) break; if(lsda_read(handle,LSDA_FLOAT,"z_force",0,nft,ftz) != nft) break; fprintf(fp,"\n\n\n"); fprintf(fp,"r i g i d w a l l n o d e s e t f o r c e s u m m a t i o n s\n"); fprintf(fp,"f o r t i m e s t e p %9d ( at time %12.5E )\n\n",ncycle,time); fprintf(fp," time wall # transducer node set # x-force y-force z-force\n"); for(j=0; j<nft; j++) { k=ftsort[j].pos; fprintf(fp,"%12.5E %10d %10d %10d %12.5E %12.5E %12.5E\n", time,ftwall[k],ftid[k],ftns[k],ftx[k],fty[k],ftz[k]); } fprintf(fp,"\n\n"); } } fclose(fp); if(nft > 0) { free(ftsort); free(ftz); free(fty); free(ftx); free(ftwall); free(ftns); free(ftid); } if(maxwall > 0) { free(sfz); free(sfy); free(sfx); } free(setid); free(fn); free(fz); free(fy); free(fx); free(nwalls); free(ids); printf(" %d states extracted\n",state-1); } /* NODOUT file */ int translate_nodout2(char *base, int handle) { int i,typid,num,filenum,state; LSDA_Length length; char dirname[128]; long *ids; int cycle,have_rot; double time; float *x,*y,*z; float *x_d,*y_d,*z_d; float *x_v,*y_v,*z_v; float *x_a,*y_a,*z_a; FILE *fp; LSDADir *dp = NULL; sprintf(dirname,"%s/metadata",base); if (lsda_cd(handle,dirname) == -1) return 0; printf("Extracting NODOUT data\n"); lsda_queryvar(handle,"ids",&typid,&length,&filenum); num=length; /* allocate memory to read in 1 state */ ids = (long *) malloc(num*sizeof(long)); x = (float *) malloc(num*sizeof(float)); y = (float *) malloc(num*sizeof(float)); z = (float *) malloc(num*sizeof(float)); x_d = (float *) malloc(num*sizeof(float)); y_d = (float *) malloc(num*sizeof(float)); z_d = (float *) malloc(num*sizeof(float)); x_v = (float *) malloc(num*sizeof(float)); y_v = (float *) malloc(num*sizeof(float)); z_v = (float *) malloc(num*sizeof(float)); x_a = (float *) malloc(num*sizeof(float)); y_a = (float *) malloc(num*sizeof(float)); z_a = (float *) malloc(num*sizeof(float)); lsda_queryvar(handle,"../d000001/rx_displacement",&typid,&length,&filenum); if(typid > 0) { have_rot = 1; } else { have_rot = 0; } /* Read metadata */ lsda_read(handle,LSDA_LONG,"ids",0,num,ids); /* open file and write header */ sprintf(output_file,"%s%s",output_path,base+1); fp=fopen(output_file,"w"); write_message(fp,output_file); if (!fp) return 0; output_title(handle,dirname,fp); output_legend(handle,fp,1,1); /* Loop through time states and write each one */ for(state=1; next_dir_6or8digitd(handle,base,state) != 0; state++) { if(lsda_read(handle,LSDA_DOUBLE,"time",0,1,&time) != 1) break; if(lsda_read(handle,LSDA_INT,"cycle",0,1,&cycle) != 1) break; if(lsda_read(handle,LSDA_FLOAT,"x_displacement",0,num,x_d) != num) break; if(lsda_read(handle,LSDA_FLOAT,"y_displacement",0,num,y_d) != num) break; if(lsda_read(handle,LSDA_FLOAT,"z_displacement",0,num,z_d) != num) break; if(lsda_read(handle,LSDA_FLOAT,"x_velocity",0,num,x_v) != num) break; if(lsda_read(handle,LSDA_FLOAT,"y_velocity",0,num,y_v) != num) break; if(lsda_read(handle,LSDA_FLOAT,"z_velocity",0,num,z_v) != num) break; if(lsda_read(handle,LSDA_FLOAT,"x_acceleration",0,num,x_a) != num) break; if(lsda_read(handle,LSDA_FLOAT,"y_acceleration",0,num,y_a) != num) break; if(lsda_read(handle,LSDA_FLOAT,"z_acceleration",0,num,z_a) != num) break; if(lsda_read(handle,LSDA_FLOAT,"x_coordinate",0,num,x) != num) break; if(lsda_read(handle,LSDA_FLOAT,"y_coordinate",0,num,y) != num) break; if(lsda_read(handle,LSDA_FLOAT,"z_coordinate",0,num,z) != num) break; fprintf(fp,"\n\n\n n o d a l p r i n t o u t f o r t i m e "); fprintf(fp,"s t e p%8d ( at time%14.7E )\n",cycle,time); fprintf(fp,"\n nodal point x-disp y-disp z-disp "); fprintf(fp,"x-vel y-vel z-vel x-accl y-accl "); fprintf(fp,"z-accl x-coor y-coor z-coor\n"); for(i=0; i<num; i++) { fprintf(fp,"%9ld%13.4E%12.4E%12.4E",ids[i],x_d[i],y_d[i],z_d[i]); fprintf(fp,"%12.4E%12.4E%12.4E",x_v[i],y_v[i],z_v[i]); fprintf(fp,"%12.4E%12.4E%12.4E",x_a[i],y_a[i],z_a[i]); fprintf(fp,"%12.4E%12.4E%12.4E\n",x[i],y[i],z[i]); } if(have_rot) { if(lsda_read(handle,LSDA_FLOAT,"rx_displacement",0,num,x_d) != num) break; if(lsda_read(handle,LSDA_FLOAT,"ry_displacement",0,num,y_d) != num) break; if(lsda_read(handle,LSDA_FLOAT,"rz_displacement",0,num,z_d) != num) break; if(lsda_read(handle,LSDA_FLOAT,"rx_velocity",0,num,x_v) != num) break; if(lsda_read(handle,LSDA_FLOAT,"ry_velocity",0,num,y_v) != num) break; if(lsda_read(handle,LSDA_FLOAT,"rz_velocity",0,num,z_v) != num) break; if(lsda_read(handle,LSDA_FLOAT,"rx_acceleration",0,num,x_a) != num) break; if(lsda_read(handle,LSDA_FLOAT,"ry_acceleration",0,num,y_a) != num) break; if(lsda_read(handle,LSDA_FLOAT,"rz_acceleration",0,num,z_a) != num) break; fprintf(fp,"\n\n\n n o d a l p r i n t o u t f o r t i m e "); fprintf(fp,"s t e p%8d ( at time%14.7E )\n",cycle,time); fprintf(fp,"\n nodal point x-rot y-rot z-rot "); fprintf(fp,"x-rot vel y-rot vel z-rot vel x-rot acc y-rot acc "); fprintf(fp,"z-rot acc\n"); for(i=0; i<num; i++) { fprintf(fp,"%9ld%13.4E%12.4E%12.4E",ids[i],x_d[i],y_d[i],z_d[i]); fprintf(fp,"%12.4E%12.4E%12.4E",x_v[i],y_v[i],z_v[i]); fprintf(fp,"%12.4E%12.4E%12.4E\n",x_a[i],y_a[i],z_a[i]); } } } fclose(fp); free(z_a); free(y_a); free(x_a); free(z_v); free(y_v); free(x_v); free(z_d); free(y_d); free(x_d); free(z); free(y); free(x); free(ids); printf(" %d states extracted\n",state-1); return 0; } int translate_nodout(int handle) { return translate_nodout2("/nodout",handle); } int translate_nodouthf(int handle) { return translate_nodout2("/nodouthf",handle); } /* ELOUTDET file */ int translate_eloutdet(int handle) { int i,j,k,typid,filenum,state,intsts,intstn,nodsts,nodstn; LSDA_Length length; char dirname[256]; int have_solid, have_tshell, have_nodavg, have_shell; FILE *fp; MDSOLID solid; MDTSHELL tshell; MDNODAVG nodavg; MDSHELL shell; char title_location[128]; if (lsda_cd(handle,"/eloutdet") == -1) return 0; lsda_queryvar(handle,"/eloutdet/solid",&typid,&length,&filenum); have_solid= (typid >= 0); lsda_queryvar(handle,"/eloutdet/thickshell",&typid,&length,&filenum); have_tshell= (typid >= 0); lsda_queryvar(handle,"/eloutdet/nodavg",&typid,&length,&filenum); have_nodavg= (typid >= 0); lsda_queryvar(handle,"/eloutdet/shell",&typid,&length,&filenum); have_shell= (typid >= 0); title_location[0]=0; /* Read metadata Solids */ if(have_solid) { lsda_cd(handle,"/eloutdet/solid/metadata"); strcpy(title_location,"/eloutdet/solid/metadata"); lsda_queryvar(handle,"states",&typid,&length,&filenum); lsda_read(handle,LSDA_I1,"states",0,length,dirname); for(i=j=k=0; i<length; i++) { if(dirname[i] == ',') { solid.states[j][k]=0; j++; k=0; } else { solid.states[j][k++]=dirname[i]; } } solid.states[j][k]=0; solid.idsize = -1; solid.ids = NULL; solid.locats=NULL; solid.locatn=NULL; lsda_read(handle,LSDA_INT,"intsts",0,1,&intsts); lsda_read(handle,LSDA_INT,"nodsts",0,1,&nodsts); lsda_read(handle,LSDA_INT,"intstn",0,1,&intstn); lsda_read(handle,LSDA_INT,"nodstn",0,1,&nodstn); } /* thick shells */ if(have_tshell) { lsda_cd(handle,"/eloutdet/thickshell/metadata"); strcpy(title_location,"/eloutdet/thickshell/metadata"); lsda_queryvar(handle,"states",&typid,&length,&filenum); lsda_read(handle,LSDA_I1,"states",0,length,dirname); for(i=j=k=0; i<length; i++) { if(dirname[i] == ',') { tshell.states[j][k]=0; j++; k=0; } else { tshell.states[j][k++]=dirname[i]; } } tshell.states[j][k]=0; lsda_read(handle,LSDA_I1,"system",0,6,tshell.system); tshell.system[6]=0; lsda_read(handle,LSDA_INT,"intsts",0,1,&intsts); lsda_read(handle,LSDA_INT,"nodsts",0,1,&nodsts); lsda_read(handle,LSDA_INT,"intstn",0,1,&intstn); lsda_read(handle,LSDA_INT,"nodstn",0,1,&nodstn); } /* shells */ if(have_shell) { lsda_cd(handle,"/eloutdet/shell/metadata"); strcpy(title_location,"/eloutdet/shell/metadata"); lsda_queryvar(handle,"states",&typid,&length,&filenum); lsda_read(handle,LSDA_I1,"states",0,length,dirname); for(i=j=k=0; i<length; i++) { if(dirname[i] == ',') { shell.states[j][k]=0; j++; k=0; } else { shell.states[j][k++]=dirname[i]; } } shell.states[j][k]=0; lsda_read(handle,LSDA_I1,"system",0,6,shell.system); shell.system[6]=0; for(i=5; i>0 && shell.system[i] == ' '; i--) shell.system[i]=0; shell.idsize = -1; shell.dsize = -1; shell.ids = NULL; shell.npl = NULL; shell.lxx = NULL; shell.exx = NULL; shell.uxx = NULL; shell.sxx = NULL; shell.npl = NULL; lsda_read(handle,LSDA_INT,"intsts",0,1,&intsts); lsda_read(handle,LSDA_INT,"nodsts",0,1,&nodsts); lsda_read(handle,LSDA_INT,"intstn",0,1,&intstn); lsda_read(handle,LSDA_INT,"nodstn",0,1,&nodstn); } /* nodavg */ if(have_nodavg) { lsda_cd(handle,"/eloutdet/nodavg/metadata"); strcpy(title_location,"/eloutdet/nodavg/metadata"); lsda_read(handle,LSDA_I1,"system",0,6,tshell.system); } if(strlen(title_location) == 0) return 0; /* huh? */ /* open file and write header */ printf("Extracting ELOUTDET data\n"); sprintf(output_file,"%seloutdet",output_path); fp=fopen(output_file,"w"); write_message(fp,output_file); if (!fp) return 0; output_title(handle,title_location,fp); k = 0; if(have_solid) { lsda_cd(handle,"/eloutdet/solid/metadata"); i = (have_tshell | have_shell | have_nodavg) ? 0 : 1; output_legend(handle,fp,1,i); k = 1; } if(have_tshell) { lsda_cd(handle,"/eloutdet/thickshell/metadata"); i = !k; j = (have_shell | have_nodavg) ? 0 : 1; output_legend(handle,fp,i,j); k = 1; } if(have_shell) { lsda_cd(handle,"/eloutdet/shell/metadata"); i = !k; j = (have_nodavg) ? 0 : 1; output_legend(handle,fp,i,j); k = 1; } if(have_nodavg) { lsda_cd(handle,"/eloutdet/nodavg/metadata"); i = !k; output_legend(handle,fp,i,1); } /* Loop through time states and write each one */ for(state=1;have_solid || have_tshell || have_shell || have_nodavg ; state++) { if(have_solid) { if(! eloutdet_solid(fp,handle,state,intsts,intstn,nodsts,nodstn,&solid)){ if(solid.ids) { free(solid.ids); free(solid.mat); free(solid.nip); free(solid.nqt); if (solid.locats) { free(solid.state); free(solid.sxx); free(solid.syy); free(solid.szz); free(solid.sxy); free(solid.syz); free(solid.szx); free(solid.yield); free(solid.effsg); free(solid.locats); } if (solid.locatn) { free(solid.locatn); } } have_solid = 0; } } if(have_tshell) { if(! eloutdet_tshell(fp,handle,state,intsts,intstn,nodsts,nodstn,&tshell)) { have_tshell = 0; } } if(have_shell) { if(! eloutdet_shell(fp,handle,state,intsts,intstn,nodsts,nodstn,&shell)) { if(shell.ids) { free(shell.ids); free(shell.mat); free(shell.nip); free(shell.npl); free(shell.nqt); free(shell.iop); if(shell.lxx) { free(shell.lxx); free(shell.lyy); free(shell.lzz); free(shell.lxy); free(shell.lyz); free(shell.lzx); } if(shell.uxx) { free(shell.uxx); free(shell.uyy); free(shell.uzz); free(shell.uxy); free(shell.uyz); free(shell.uzx); free(shell.locatn); } if(shell.sxx) { free(shell.sxx); free(shell.syy); free(shell.szz); free(shell.sxy); free(shell.syz); free(shell.szx); free(shell.ps); free(shell.state); free(shell.locats); } if(shell.exx) { free(shell.exx); free(shell.eyy); free(shell.ezz); free(shell.exy); free(shell.eyz); free(shell.ezx); free(shell.locatn); } } have_shell=0; } } if(have_nodavg) { if(! eloutdet_nodavg(fp,handle,state,&nodavg)) { if(nodavg.ids) { free(nodavg.ids); free(nodavg.factor); free(nodavg.lxx); free(nodavg.lyy); free(nodavg.lzz); free(nodavg.lxy); free(nodavg.lyz); free(nodavg.lzx); free(nodavg.lyield); free(nodavg.uxx); free(nodavg.uyy); free(nodavg.uzz); free(nodavg.uxy); free(nodavg.uyz); free(nodavg.uzx); free(nodavg.uyield); } have_nodavg = 0; } } } fclose(fp); /* free everything here.... */ if(have_solid && solid.ids) { free(solid.ids); free(solid.mat); free(solid.nip); free(solid.nqt); free(solid.state); free(solid.sxx); free(solid.syy); free(solid.szz); free(solid.sxy); free(solid.syz); free(solid.szx); free(solid.yield); free(solid.effsg); free(solid.locatn); free(solid.locats); } if(have_nodavg && nodavg.ids) { free(nodavg.ids); free(nodavg.factor); free(nodavg.lxx); free(nodavg.lyy); free(nodavg.lzz); free(nodavg.lxy); free(nodavg.lyz); free(nodavg.lzx); free(nodavg.lyield); free(nodavg.uxx); free(nodavg.uyy); free(nodavg.uzz); free(nodavg.uxy); free(nodavg.uyz); free(nodavg.uzx); free(nodavg.uyield); } if(have_shell && shell.ids) { free(shell.ids); free(shell.mat); free(shell.nip); free(shell.state); free(shell.iop); if(shell.npl) free(shell.npl); if(shell.lxx) { free(shell.lxx); free(shell.lyy); free(shell.lzz); free(shell.lxy); free(shell.lyz); free(shell.lzx); } if(shell.uxx) { free(shell.uxx); free(shell.uyy); free(shell.uzz); free(shell.uxy); free(shell.uyz); free(shell.uzx); } free(shell.sxx); free(shell.syy); free(shell.szz); free(shell.sxy); free(shell.syz); free(shell.szx); free(shell.ps); } printf(" %d states extracted\n",state-1); return 0; } int eloutdet_solid(FILE *fp,int handle, int state, int intsts,int intstn, int nodsts,int nodstn,MDSOLID *solid) { char dirname[128]; float time; int cycle; int typid, filenum; LSDA_Length length; int num, nums, numn; int have_strain,have_stress,i,j,k; if(state<=999999) sprintf(dirname,"/eloutdet/solid/d%6.6d",state); else sprintf(dirname,"/eloutdet/solid/d%8.8d",state); lsda_queryvar(handle,dirname,&typid,&length,&filenum); if(typid != 0) return 0; lsda_cd(handle,dirname); lsda_queryvar(handle,"sig_xx",&typid,&length,&filenum); have_stress = (typid > 0); lsda_queryvar(handle,"eps_xx",&typid,&length,&filenum); have_strain = (typid > 0); lsda_queryvar(handle,"ids",&typid,&length,&filenum); if(typid < 0) return 0; /* all elements deleted */ num=length; /* element information */ solid->ids = (int *) malloc(num*sizeof(int)); solid->mat = (int *) malloc(num*sizeof(int)); solid->nip = (int *) malloc(num*sizeof(int)); solid->nqt = (int *) malloc(num*sizeof(int)); if(lsda_read(handle,LSDA_FLOAT,"time",0,1,&time) != 1) return 0; if(lsda_read(handle,LSDA_INT,"cycle",0,1,&cycle) != 1) return 0; if(lsda_read(handle,LSDA_INT,"ids",0,length,solid->ids) != num) return 0; if(lsda_read(handle,LSDA_INT,"mat",0,length,solid->mat) != num) return 0; if(lsda_read(handle,LSDA_INT,"nip",0,length,solid->nip) != num) return 0; if(lsda_read(handle,LSDA_INT,"nqt",0,length,solid->nqt) != num) return 0; fprintf(fp,"\n\n\n e l e m e n t s t r e s s c a l c u l a t i o n s"); fprintf(fp," f o r t i m e s t e p%9d ( at time %12.5E )\n\n",cycle,time); fprintf(fp," element materl\n"); /* stress */ nums=0; if (have_stress) { lsda_queryvar(handle,"locats",&typid,&length,&filenum); nums=length; solid->state = (int *) malloc(nums*sizeof(int)); solid->sxx = (float *) malloc(nums*sizeof(float)); solid->syy = (float *) malloc(nums*sizeof(float)); solid->szz = (float *) malloc(nums*sizeof(float)); solid->sxy = (float *) malloc(nums*sizeof(float)); solid->syz = (float *) malloc(nums*sizeof(float)); solid->szx = (float *) malloc(nums*sizeof(float)); solid->yield = (float *) malloc(nums*sizeof(float)); solid->effsg = (float *) malloc(nums*sizeof(float)); solid->locats = (int *) malloc(nums*sizeof(int)); if(lsda_read(handle,LSDA_INT,"state",0,nums,solid->state) != nums) return 0; if(lsda_read(handle,LSDA_FLOAT,"sig_xx",0,nums,solid->sxx) != nums) return 0; if(lsda_read(handle,LSDA_FLOAT,"sig_yy",0,nums,solid->syy) != nums) return 0; if(lsda_read(handle,LSDA_FLOAT,"sig_zz",0,nums,solid->szz) != nums) return 0; if(lsda_read(handle,LSDA_FLOAT,"sig_xy",0,nums,solid->sxy) != nums) return 0; if(lsda_read(handle,LSDA_FLOAT,"sig_yz",0,nums,solid->syz) != nums) return 0; if(lsda_read(handle,LSDA_FLOAT,"sig_zx",0,nums,solid->szx) != nums) return 0; if(lsda_read(handle,LSDA_FLOAT,"yield",0,nums,solid->yield) != nums) return 0; if(lsda_read(handle,LSDA_FLOAT,"effsg",0,nums,solid->effsg) != nums) return 0; if(lsda_read(handle,LSDA_INT,"locats",0,nums,solid->locats) != nums) return 0; fprintf(fp," ipt stress sig-xx sig-yy sig"); fprintf(fp,"-zz sig-xy sig-yz sig-zx "); fprintf(fp," yield location\n state "); fprintf(fp," "); fprintf(fp,"effsg function\n"); for(i=k=0; i<num; i++) { fprintf(fp,"%8d-%7d\n",solid->ids[i],solid->mat[i]); if (intsts==1) { for(j=0; j<solid->nip[i]; j++,k++) { fprintf(fp," %-7s ",solid->states[solid->state[k]-1]); fprintf(fp,"%12.4E%12.4E%12.4E",solid->sxx[k],solid->syy[k],solid->szz[k]); fprintf(fp,"%12.4E%12.4E%12.4E%14.4E%14.4E int. point%3d\n", solid->sxy[k],solid->syz[k],solid->szx[k],solid->effsg[k], solid->yield[k],solid->locats[k]); } } if (nodsts==1) { for(j=0; j<solid->nqt[i]; j++,k++) { fprintf(fp," %-7s ",solid->states[solid->state[k]-1]); fprintf(fp,"%12.4E%12.4E%12.4E",solid->sxx[k],solid->syy[k],solid->szz[k]); fprintf(fp,"%12.4E%12.4E%12.4E%14.4E%14.4E node%9d\n", solid->sxy[k],solid->syz[k],solid->szx[k],solid->effsg[k], solid->yield[k],solid->locats[k]); } } } } numn=0; if (have_strain) { lsda_queryvar(handle,"locatn",&typid,&length,&filenum); numn=length; solid->locatn = (int *) malloc(numn*sizeof(int)); if (numn>nums) { solid->sxx = (float *) malloc(numn*sizeof(float)); solid->syy = (float *) malloc(numn*sizeof(float)); solid->szz = (float *) malloc(numn*sizeof(float)); solid->sxy = (float *) malloc(numn*sizeof(float)); solid->syz = (float *) malloc(numn*sizeof(float)); solid->szx = (float *) malloc(numn*sizeof(float)); } if(lsda_read(handle,LSDA_FLOAT,"eps_xx",0,numn,solid->sxx) != numn) return 0; if(lsda_read(handle,LSDA_FLOAT,"eps_yy",0,numn,solid->syy) != numn) return 0; if(lsda_read(handle,LSDA_FLOAT,"eps_zz",0,numn,solid->szz) != numn) return 0; if(lsda_read(handle,LSDA_FLOAT,"eps_xy",0,numn,solid->sxy) != numn) return 0; if(lsda_read(handle,LSDA_FLOAT,"eps_yz",0,numn,solid->syz) != numn) return 0; if(lsda_read(handle,LSDA_FLOAT,"eps_zx",0,numn,solid->szx) != numn) return 0; if(lsda_read(handle,LSDA_INT,"locatn",0,numn,solid->locatn) != numn) return 0; fprintf(fp,"\n\n\n e l e m e n t s t r a i n c a l c u l a t i o n s"); fprintf(fp," f o r t i m e s t e p%9d ( at time %12.5E )\n\n",cycle,time); fprintf(fp," element strain eps-xx eps-yy eps"); fprintf(fp,"-zz eps-xy eps-yz eps-zx location\n"); fprintf(fp," num/ipt state\n"); for(i=k=0; i<num; i++) { fprintf(fp,"%8d-%7d\n",solid->ids[i],solid->mat[i]); if (intstn==1) { for(j=0; j<solid->nip[i]; j++,k++) { fprintf(fp," "); fprintf(fp,"%12.4E%12.4E%12.4E",solid->sxx[k],solid->syy[k],solid->szz[k]); fprintf(fp,"%12.4E%12.4E%12.4E int. point%3d\n",solid->sxy[k], solid->syz[k],solid->szx[k],solid->locatn[k]); } } if (nodstn==1) { for(j=0; j<solid->nqt[i]; j++,k++) { fprintf(fp," "); fprintf(fp,"%12.4E%12.4E%12.4E",solid->sxx[k],solid->syy[k],solid->szz[k]); fprintf(fp,"%12.4E%12.4E%12.4E node%9d\n",solid->sxy[k], solid->syz[k],solid->szx[k],solid->locatn[k]); } } } } return 1; } int eloutdet_tshell(FILE *fp,int handle, int state, int intsts,int intstn, int nodsts,int nodstn,MDTSHELL *tshell) { char dirname[128]; float time; int cycle; int typid, filenum; LSDA_Length length; int num,numn,nums; int have_strain,have_stress,i,j,k,i1; if(state<=999999) sprintf(dirname,"/eloutdet/thickshell/d%6.6d",state); else sprintf(dirname,"/eloutdet/thickshell/d%8.8d",state); lsda_queryvar(handle,dirname,&typid,&length,&filenum); if(typid != 0) return 0; lsda_cd(handle,dirname); lsda_queryvar(handle,"sig_xx",&typid,&length,&filenum); have_stress = (typid > 0); lsda_queryvar(handle,"eps_xx",&typid,&length,&filenum); have_strain = (typid > 0); lsda_queryvar(handle,"ids",&typid,&length,&filenum); if(typid < 0) return 0; /* all elements deleted */ /* read in element information */ num=length; tshell->ids = (int *) malloc(num*sizeof(int)); tshell->mat = (int *) malloc(num*sizeof(int)); tshell->nip = (int *) malloc(num*sizeof(int)); tshell->npl = (int *) malloc(num*sizeof(int)); if(lsda_read(handle,LSDA_FLOAT,"time",0,1,&time) != 1) return 0; if(lsda_read(handle,LSDA_INT,"cycle",0,1,&cycle) != 1) return 0; if(lsda_read(handle,LSDA_INT,"ids",0,num,tshell->ids) != num) return 0; if(lsda_read(handle,LSDA_INT,"mat",0,num,tshell->mat) != num) return 0; if(lsda_read(handle,LSDA_INT,"nip",0,num,tshell->nip) != num) return 0; if(lsda_read(handle,LSDA_INT,"npl",0,num,tshell->npl) != num) return 0; fprintf(fp,"\n\n\n e l e m e n t s t r e s s c a l c u l a t i o n s"); fprintf(fp," f o r t i m e s t e p%9d ( at time %12.5E )\n\n",cycle,time); fprintf(fp," element materl\n"); /* read in stress */ if (have_stress) { lsda_queryvar(handle,"locats",&typid,&length,&filenum); if(typid < 0) return 0; /* all elements deleted */ nums=length; tshell->state = (int *) malloc(nums*sizeof(int)); tshell->sxx = (float *) malloc(nums*sizeof(float)); tshell->syy = (float *) malloc(nums*sizeof(float)); tshell->szz = (float *) malloc(nums*sizeof(float)); tshell->sxy = (float *) malloc(nums*sizeof(float)); tshell->syz = (float *) malloc(nums*sizeof(float)); tshell->szx = (float *) malloc(nums*sizeof(float)); tshell->yield = (float *) malloc(nums*sizeof(float)); tshell->effsg = (float *) malloc(nums*sizeof(float)); tshell->locats = (int *) malloc(nums*sizeof(int)); if(lsda_read(handle,LSDA_INT,"state",0,nums,tshell->state) != nums) return 0; if(lsda_read(handle,LSDA_FLOAT,"sig_xx",0,nums,tshell->sxx) != nums) return 0; if(lsda_read(handle,LSDA_FLOAT,"sig_yy",0,nums,tshell->syy) != nums) return 0; if(lsda_read(handle,LSDA_FLOAT,"sig_zz",0,nums,tshell->szz) != nums) return 0; if(lsda_read(handle,LSDA_FLOAT,"sig_xy",0,nums,tshell->sxy) != nums) return 0; if(lsda_read(handle,LSDA_FLOAT,"sig_yz",0,nums,tshell->syz) != nums) return 0; if(lsda_read(handle,LSDA_FLOAT,"sig_zx",0,nums,tshell->szx) != nums) return 0; if(lsda_read(handle,LSDA_FLOAT,"yield",0,nums,tshell->yield) != nums) return 0; if(lsda_read(handle,LSDA_INT,"locats",0,nums,tshell->locats) != nums) return 0; /* Output stress */ fprintf(fp," num/ipt stress sig-xx sig-yy sig"); fprintf(fp,"-zz sig-xy sig-yz sig-zx "); fprintf(fp,"yield location\n state "); fprintf(fp," "); fprintf(fp," function\n"); for(j=k=0;j<num;j++){ fprintf(fp,"%8d-%5d\n",tshell->ids[j],tshell->mat[j]); if (intsts==1) { for(i=0; i<tshell->nip[j]; i++) { for(i1=0; i1<tshell->npl[j]; i1++,k++) { fprintf(fp," %d %-7s ",i+1,tshell->states[tshell->state[k]-1]); fprintf(fp,"%12.4E%12.4E%12.4E",tshell->sxx[k],tshell->syy[k], tshell->szz[k]); fprintf(fp,"%12.4E%12.4E%12.4E%14.4E int. point%3d\n",tshell->sxy[k], tshell->syz[k],tshell->szx[k],tshell->yield[k],i1+1); } } } if (nodsts==1) { for(i=0; i<8; i++,k++) { fprintf(fp," %-7s ",tshell->states[tshell->state[k]-1]); fprintf(fp,"%12.4E%12.4E%12.4E",tshell->sxx[k],tshell->syy[k], tshell->szz[k]); fprintf(fp,"%12.4E%12.4E%12.4E%14.4E node %8d\n",tshell->sxy[k], tshell->syz[k],tshell->szx[k],tshell->yield[k],tshell->locats[k]); } } } } if (have_strain) { lsda_queryvar(handle,"locatn",&typid,&length,&filenum); if(typid < 0) return 0; /* all elements deleted */ numn=length; tshell->exx = (float *) malloc(numn*sizeof(float)); tshell->eyy = (float *) malloc(numn*sizeof(float)); tshell->ezz = (float *) malloc(numn*sizeof(float)); tshell->exy = (float *) malloc(numn*sizeof(float)); tshell->eyz = (float *) malloc(numn*sizeof(float)); tshell->ezx = (float *) malloc(numn*sizeof(float)); tshell->locatn = (int *) malloc(numn*sizeof(int)); if(lsda_read(handle,LSDA_FLOAT,"eps_xx",0,numn,tshell->exx) != numn) return 0; if(lsda_read(handle,LSDA_FLOAT,"eps_yy",0,numn,tshell->eyy) != numn) return 0; if(lsda_read(handle,LSDA_FLOAT,"eps_zz",0,numn,tshell->ezz) != numn) return 0; if(lsda_read(handle,LSDA_FLOAT,"eps_xy",0,numn,tshell->exy) != numn) return 0; if(lsda_read(handle,LSDA_FLOAT,"eps_yz",0,numn,tshell->eyz) != numn) return 0; if(lsda_read(handle,LSDA_FLOAT,"eps_zx",0,numn,tshell->ezx) != numn) return 0; if(lsda_read(handle,LSDA_INT,"locatn",0,numn,tshell->locatn) != numn) return 0; fprintf(fp,"\n num/ipt strain"); fprintf(fp," eps-xx eps-yy eps"); fprintf(fp,"-zz eps-xy eps-yz eps-zx location \n\n "); for(j=k=0;j<num;j++){ fprintf(fp,"%8d-%5d\n",tshell->ids[j],tshell->mat[j]); if (intstn==1) { for(i=0; i<tshell->nip[j]; i++) { for(i1=0; i1<tshell->npl[j]; i1++,k++) { fprintf(fp,"%4d- %12.4E%12.4E%12.4E",i+1, tshell->exx[k],tshell->eyy[k],tshell->ezz[k]); fprintf(fp,"%12.4E%12.4E%12.4E int. point%3d\n",tshell->exy[k], tshell->eyz[k],tshell->ezx[k],i1+1); } } } if (nodstn==1) { for(i=0; i<8; i++,k++) { fprintf(fp," %12.4E%12.4E%12.4E", tshell->exx[k],tshell->eyy[k],tshell->ezz[k]); fprintf(fp,"%12.4E%12.4E%12.4E node %8d\n",tshell->exy[k], tshell->eyz[k],tshell->ezx[k],tshell->locatn[k]); } } } } free(tshell->ids); free(tshell->mat); free(tshell->nip); free(tshell->npl); if (have_stress) { free(tshell->state); free(tshell->sxx); free(tshell->syy); free(tshell->szz); free(tshell->sxy); free(tshell->syz); free(tshell->szx); free(tshell->yield); free(tshell->effsg); free(tshell->locats); } if (have_strain) { free(tshell->exx); free(tshell->eyy); free(tshell->ezz); free(tshell->exy); free(tshell->eyz); free(tshell->ezx); free(tshell->locatn); } return 1; } int eloutdet_shell(FILE *fp,int handle, int state, int intsts, int intstn, int nodsts,int nodstn,MDSHELL *shell) { char dirname[128]; float time; int cycle; int typid, filenum; LSDA_Length length,length2; int num,numn,nums; int have_strain,have_stress,i,j,k,j1; if(state<=999999) sprintf(dirname,"/eloutdet/shell/d%6.6d",state); else sprintf(dirname,"/eloutdet/shell/d%8.8d",state); lsda_queryvar(handle,dirname,&typid,&length,&filenum); if(typid != 0) return 0; lsda_cd(handle,dirname); lsda_queryvar(handle,"sig_xx",&typid,&length2,&filenum); have_stress = (typid > 0); lsda_queryvar(handle,"eps_xx",&typid,&length2,&filenum); have_strain = (typid > 0); lsda_queryvar(handle,"ids",&typid,&length,&filenum); if(typid < 0) return 0; num=length; if (have_stress) { lsda_queryvar(handle,"locats",&typid,&length,&filenum); nums=length; } else { nums=0; } if (have_strain) { lsda_queryvar(handle,"locatn",&typid,&length,&filenum); numn=length; } else { numn=0; } if(lsda_read(handle,LSDA_FLOAT,"time",0,1,&time) != 1) return 0; if(lsda_read(handle,LSDA_INT,"cycle",0,1,&cycle) != 1) return 0; shell->ids = (int *) malloc(num*sizeof(int)); shell->mat = (int *) malloc(num*sizeof(int)); shell->nip = (int *) malloc(num*sizeof(int)); shell->iop = (int *) malloc(num*sizeof(int)); shell->npl = (int *) malloc(num*sizeof(int)); shell->nqt = (int *) malloc(num*sizeof(int)); if(lsda_read(handle,LSDA_INT,"ids",0,num,shell->ids) != num) return 0; if(lsda_read(handle,LSDA_INT,"mat",0,num,shell->mat) != num) return 0; if(lsda_read(handle,LSDA_INT,"nip",0,num,shell->nip) != num) return 0; if(lsda_read(handle,LSDA_INT,"iop",0,num,shell->iop) != num) return 0; if(lsda_read(handle,LSDA_INT,"npl",0,num,shell->npl) != num) return 0; if(lsda_read(handle,LSDA_INT,"nqt",0,num,shell->nqt) != num) return 0; fprintf(fp,"\n\n\n e l e m e n t s t r e s s c a l c u l a t i o n s"); fprintf(fp," f o r t i m e s t e p%9d ( at time %12.5E )\n\n",cycle,time); sprintf(dirname,"(%s)",shell->system); fprintf(fp," element materl%-8s\n",dirname); if(have_stress) { shell->state = (int *) malloc(nums*sizeof(int)); shell->sxx = (float *) malloc(nums*sizeof(float)); shell->syy = (float *) malloc(nums*sizeof(float)); shell->szz = (float *) malloc(nums*sizeof(float)); shell->sxy = (float *) malloc(nums*sizeof(float)); shell->syz = (float *) malloc(nums*sizeof(float)); shell->szx = (float *) malloc(nums*sizeof(float)); shell->ps = (float *) malloc(nums*sizeof(float)); shell->locats = (int *) malloc(nums*sizeof(int)); if(lsda_read(handle,LSDA_INT,"state",0,nums,shell->state) != nums) return 0; if(lsda_read(handle,LSDA_FLOAT,"sig_xx",0,nums,shell->sxx) != nums) return 0; if(lsda_read(handle,LSDA_FLOAT,"sig_yy",0,nums,shell->syy) != nums) return 0; if(lsda_read(handle,LSDA_FLOAT,"sig_zz",0,nums,shell->szz) != nums) return 0; if(lsda_read(handle,LSDA_FLOAT,"sig_xy",0,nums,shell->sxy) != nums) return 0; if(lsda_read(handle,LSDA_FLOAT,"sig_yz",0,nums,shell->syz) != nums) return 0; if(lsda_read(handle,LSDA_FLOAT,"sig_zx",0,nums,shell->szx) != nums) return 0; if(lsda_read(handle,LSDA_FLOAT,"plastic_strain",0,nums,shell->ps) != nums) return 0; if(lsda_read(handle,LSDA_INT,"locats",0,nums,shell->locats) != nums) return 0; /* Output this data */ fprintf(fp," ipt-shl stress sig-xx sig-yy sig"); fprintf(fp,"-zz sig-xy sig-yz sig-zx plastic location\n"); fprintf(fp," state "); fprintf(fp," strain \n"); for(i=k=0; i<num; i++) { fprintf(fp,"%8d-%7d\n",shell->ids[i],shell->mat[i]); for(j=0; j<shell->nip[i]; j++) { if (intsts==1) { for (j1=0; j1<shell->npl[i]; j1++,k++) { fprintf(fp,"%4d-%3d %-7s ",j+1,shell->iop[i],shell->states[shell->state[k]-1]); fprintf(fp,"%12.4E%12.4E%12.4E",shell->sxx[k],shell->syy[k],shell->szz[k]); fprintf(fp,"%12.4E%12.4E%12.4E%14.4E int. point%3d\n",shell->sxy[k], shell->syz[k],shell->szx[k],shell->ps[k],j1+1); } } if (nodsts==1) { for (j1=0; j1<shell->nqt[i]; j1++,k++) { fprintf(fp,"%4d-%3d %-7s ",j+1,shell->iop[i],shell->states[shell->state[k]-1]); fprintf(fp,"%12.4E%12.4E%12.4E",shell->sxx[k],shell->syy[k],shell->szz[k]); fprintf(fp,"%12.4E%12.4E%12.4E%14.4E node %8d\n",shell->sxy[k], shell->syz[k],shell->szx[k],shell->ps[k],shell->locats[k]); } } } } } if(have_strain) { shell->exx = (float *) malloc(numn*sizeof(float)); shell->eyy = (float *) malloc(numn*sizeof(float)); shell->ezz = (float *) malloc(numn*sizeof(float)); shell->exy = (float *) malloc(numn*sizeof(float)); shell->eyz = (float *) malloc(numn*sizeof(float)); shell->ezx = (float *) malloc(numn*sizeof(float)); shell->locatn = (int *) malloc(numn*sizeof(int)); if(lsda_read(handle,LSDA_FLOAT,"eps_xx",0,numn,shell->exx) != numn) return 0; if(lsda_read(handle,LSDA_FLOAT,"eps_yy",0,numn,shell->eyy) != numn) return 0; if(lsda_read(handle,LSDA_FLOAT,"eps_zz",0,numn,shell->ezz) != numn) return 0; if(lsda_read(handle,LSDA_FLOAT,"eps_xy",0,numn,shell->exy) != numn) return 0; if(lsda_read(handle,LSDA_FLOAT,"eps_yz",0,numn,shell->eyz) != numn) return 0; if(lsda_read(handle,LSDA_FLOAT,"eps_zx",0,numn,shell->ezx) != numn) return 0; if(lsda_read(handle,LSDA_INT,"locatn",0,numn,shell->locatn) != numn) return 0; /* all the blanks here are silly, but are output by DYNA so..... */ /* sprintf(dirname,"(%s)",shell->system); */ fprintf(fp,"\n ipt-shl strain eps-xx eps-yy eps"); fprintf(fp,"-zz eps-xy eps-yz eps-zx location \n"); fprintf(fp," "); fprintf(fp," \n"); for(i=k=0; i<num; i++) { fprintf(fp,"%8d-%7d\n",shell->ids[i],shell->mat[i]); for(j=0; j<shell->nip[i]; j++) { if (intstn==1) { for (j1=0; j1<shell->npl[i]; j1++,k++) { fprintf(fp,"%4d- %12.4E%12.4E%12.4E",j+1, shell->exx[k],shell->eyy[k],shell->ezz[k]); fprintf(fp,"%12.4E%12.4E%12.4E int. point%3d\n",shell->exy[k], shell->eyz[k],shell->ezx[k],j1+1); } } if (nodstn==1) { for (j1=0; j1<shell->nqt[i]; j1++,k++) { fprintf(fp,"%4d- %12.4E%12.4E%12.4E",j+1, shell->exx[k],shell->eyy[k],shell->ezz[k]); fprintf(fp,"%12.4E%12.4E%12.4E node %8d\n",shell->exy[k], shell->eyz[k],shell->ezx[k],shell->locatn[k]); } } } } } return 1; } int eloutdet_nodavg(FILE *fp,int handle, int state, MDNODAVG *nodavg) { char dirname[128]; float time; int cycle; int typid, filenum; LSDA_Length length,length2; int num; int have_strain,have_stress,i; if(state<=999999) sprintf(dirname,"/eloutdet/nodavg/d%6.6d",state); else sprintf(dirname,"/eloutdet/nodavg/d%8.8d",state); lsda_queryvar(handle,dirname,&typid,&length,&filenum); if(typid != 0) return 0; lsda_cd(handle,dirname); lsda_queryvar(handle,"lower_sig_xx",&typid,&length2,&filenum); have_stress = (typid > 0); lsda_queryvar(handle,"lower_eps_xx",&typid,&length2,&filenum); have_strain = (typid > 0); lsda_queryvar(handle,"ids",&typid,&length,&filenum); if(typid < 0) return 0; num=length; if(lsda_read(handle,LSDA_FLOAT,"time",0,1,&time) != 1) return 0; if(lsda_read(handle,LSDA_INT,"cycle",0,1,&cycle) != 1) return 0; nodavg->ids = (int *) malloc(num*sizeof(int)); nodavg->factor = (float *) malloc(num*sizeof(float)); nodavg->lxx = (float *) malloc(num*sizeof(float)); nodavg->lyy = (float *) malloc(num*sizeof(float)); nodavg->lzz = (float *) malloc(num*sizeof(float)); nodavg->lxy = (float *) malloc(num*sizeof(float)); nodavg->lyz = (float *) malloc(num*sizeof(float)); nodavg->lzx = (float *) malloc(num*sizeof(float)); nodavg->lyield = (float *) malloc(num*sizeof(float)); nodavg->uxx = (float *) malloc(num*sizeof(float)); nodavg->uyy = (float *) malloc(num*sizeof(float)); nodavg->uzz = (float *) malloc(num*sizeof(float)); nodavg->uxy = (float *) malloc(num*sizeof(float)); nodavg->uyz = (float *) malloc(num*sizeof(float)); nodavg->uzx = (float *) malloc(num*sizeof(float)); nodavg->uyield = (float *) malloc(num*sizeof(float)); if(lsda_read(handle,LSDA_INT,"ids",0,num,nodavg->ids) != num) return 0; if(lsda_read(handle,LSDA_FLOAT,"factor",0,num,nodavg->factor) != num) return 0; if(have_stress) { fprintf(fp,"\n\n\n n o d a l s t r e s s c a l c u l a t i o n s"); fprintf(fp," f o r t i m e s t e p%9d ( at time%12.5E )\n\n",cycle,time); fprintf(fp," node (global)\n"); sprintf(dirname,"(%s)",nodavg->system); if(lsda_read(handle,LSDA_FLOAT,"lower_sig_xx",0,num,nodavg->lxx) != num) return 0; if(lsda_read(handle,LSDA_FLOAT,"lower_sig_yy",0,num,nodavg->lyy) != num) return 0; if(lsda_read(handle,LSDA_FLOAT,"lower_sig_zz",0,num,nodavg->lzz) != num) return 0; if(lsda_read(handle,LSDA_FLOAT,"lower_sig_xy",0,num,nodavg->lxy) != num) return 0; if(lsda_read(handle,LSDA_FLOAT,"lower_sig_yz",0,num,nodavg->lyz) != num) return 0; if(lsda_read(handle,LSDA_FLOAT,"lower_sig_zx",0,num,nodavg->lzx) != num) return 0; if(lsda_read(handle,LSDA_FLOAT,"lower_yield",0,num,nodavg->lyield) != num) return 0; if(lsda_read(handle,LSDA_FLOAT,"upper_sig_xx",0,num,nodavg->uxx) != num) return 0; if(lsda_read(handle,LSDA_FLOAT,"upper_sig_yy",0,num,nodavg->uyy) != num) return 0; if(lsda_read(handle,LSDA_FLOAT,"upper_sig_zz",0,num,nodavg->uzz) != num) return 0; if(lsda_read(handle,LSDA_FLOAT,"upper_sig_xy",0,num,nodavg->uxy) != num) return 0; if(lsda_read(handle,LSDA_FLOAT,"upper_sig_yz",0,num,nodavg->uyz) != num) return 0; if(lsda_read(handle,LSDA_FLOAT,"upper_sig_zx",0,num,nodavg->uzx) != num) return 0; if(lsda_read(handle,LSDA_FLOAT,"upper_sig_zx",0,num,nodavg->uzx) != num) return 0; if(lsda_read(handle,LSDA_FLOAT,"upper_yield",0,num,nodavg->uyield) != num) return 0; /* Output this data */ fprintf(fp," stress sig-xx sig-yy sig"); fprintf(fp,"-zz sig-xy sig-yz sig-zx plastic\n"); fprintf(fp," "); fprintf(fp," strain \n"); for(i=0; i<num; i++) { fprintf(fp,"%8d-\n",nodavg->ids[i]); if (nodavg->factor[i]>0) { fprintf(fp," lower surface %12.4E%12.4E",nodavg->lxx[i],nodavg->lyy[i]); fprintf(fp,"%12.4E%12.4E%12.4E",nodavg->lzz[i],nodavg->lxy[i],nodavg->lyz[i]); fprintf(fp,"%12.4E%12.4E\n",nodavg->lzx[i],nodavg->lyield[i]); fprintf(fp," upper surface %12.4E%12.4E",nodavg->uxx[i],nodavg->uyy[i]); fprintf(fp,"%12.4E%12.4E%12.4E",nodavg->uzz[i],nodavg->uxy[i],nodavg->uyz[i]); fprintf(fp,"%12.4E%12.4E\n",nodavg->uzx[i],nodavg->uyield[i]);} else { fprintf(fp," mid. surface %12.4E%12.4E",nodavg->lxx[i],nodavg->lyy[i]); fprintf(fp,"%12.4E%12.4E%12.4E",nodavg->lzz[i],nodavg->lxy[i],nodavg->lyz[i]); fprintf(fp,"%12.4E%12.4E\n",nodavg->lzx[i],nodavg->lyield[i]); } } } if(have_strain) { fprintf(fp,"\n\n\n n o d a l s t r a i n c a l c u l a t i o n s"); fprintf(fp," f o r t i m e s t e p%9d ( at time%12.5E )\n\n",cycle,time); fprintf(fp," node (global)\n"); sprintf(dirname,"(%s)",nodavg->system); if(lsda_read(handle,LSDA_FLOAT,"lower_eps_xx",0,num,nodavg->lxx) != num) return 0; if(lsda_read(handle,LSDA_FLOAT,"lower_eps_yy",0,num,nodavg->lyy) != num) return 0; if(lsda_read(handle,LSDA_FLOAT,"lower_eps_zz",0,num,nodavg->lzz) != num) return 0; if(lsda_read(handle,LSDA_FLOAT,"lower_eps_xy",0,num,nodavg->lxy) != num) return 0; if(lsda_read(handle,LSDA_FLOAT,"lower_eps_yz",0,num,nodavg->lyz) != num) return 0; if(lsda_read(handle,LSDA_FLOAT,"lower_eps_zx",0,num,nodavg->lzx) != num) return 0; if(lsda_read(handle,LSDA_FLOAT,"upper_eps_xx",0,num,nodavg->uxx) != num) return 0; if(lsda_read(handle,LSDA_FLOAT,"upper_eps_yy",0,num,nodavg->uyy) != num) return 0; if(lsda_read(handle,LSDA_FLOAT,"upper_eps_zz",0,num,nodavg->uzz) != num) return 0; if(lsda_read(handle,LSDA_FLOAT,"upper_eps_xy",0,num,nodavg->uxy) != num) return 0; if(lsda_read(handle,LSDA_FLOAT,"upper_eps_yz",0,num,nodavg->uyz) != num) return 0; if(lsda_read(handle,LSDA_FLOAT,"upper_eps_zx",0,num,nodavg->uzx) != num) return 0; if(lsda_read(handle,LSDA_FLOAT,"upper_eps_zx",0,num,nodavg->uzx) != num) return 0; /* Output this data */ fprintf(fp," strain eps-xx eps-yy eps"); fprintf(fp,"-zz eps-xy eps-yz eps-zx \n"); for(i=0; i<num; i++) { fprintf(fp,"%8d-\n",nodavg->ids[i]); if (nodavg->factor[i]>0) { fprintf(fp," lower surface %12.4E%12.4E",nodavg->lxx[i],nodavg->lyy[i]); fprintf(fp,"%12.4E%12.4E%12.4E",nodavg->lzz[i],nodavg->lxy[i],nodavg->lyz[i]); fprintf(fp,"%12.4E\n",nodavg->lzx[i]); fprintf(fp," upper surface %12.4E%12.4E",nodavg->uxx[i],nodavg->uyy[i]); fprintf(fp,"%12.4E%12.4E%12.4E",nodavg->uzz[i],nodavg->uxy[i],nodavg->uyz[i]); fprintf(fp,"%12.4E\n",nodavg->uzx[i]);} else { fprintf(fp," mid. surface %12.4E%12.4E",nodavg->lxx[i],nodavg->lyy[i]); fprintf(fp,"%12.4E%12.4E%12.4E",nodavg->lzz[i],nodavg->lxy[i],nodavg->lyz[i]); fprintf(fp,"%12.4E\n",nodavg->lzx[i]); } } } return 1; } /* ELOUT file */ int translate_elout(int handle) { int i,j,k,typid,filenum,state; LSDA_Length length; char dirname[256]; int have_solid, have_tshell, have_beam, have_shell; int have_solid_hist, have_tshell_hist, have_beam_hist, have_shell_hist; FILE *fp; MDSOLID solid; MDTSHELL tshell; MDBEAM beam; MDSHELL shell; MDHIST solid_hist,tshell_hist,beam_hist,shell_hist; char title_location[128]; if (lsda_cd(handle,"/elout") == -1) return 0; lsda_queryvar(handle,"/elout/solid",&typid,&length,&filenum); have_solid= (typid >= 0); lsda_queryvar(handle,"/elout/solid_hist",&typid,&length,&filenum); have_solid_hist= (typid >= 0); lsda_queryvar(handle,"/elout/thickshell",&typid,&length,&filenum); have_tshell= (typid >= 0); lsda_queryvar(handle,"/elout/thickshell_hist",&typid,&length,&filenum); have_tshell_hist= (typid >= 0); lsda_queryvar(handle,"/elout/beam",&typid,&length,&filenum); have_beam= (typid >= 0); lsda_queryvar(handle,"/elout/beam_hist",&typid,&length,&filenum); have_beam_hist= (typid >= 0); lsda_queryvar(handle,"/elout/shell",&typid,&length,&filenum); have_shell= (typid >= 0); lsda_queryvar(handle,"/elout/shell_hist",&typid,&length,&filenum); have_shell_hist= (typid >= 0); title_location[0]=0; /* Read metadata Solids */ if(have_solid) { lsda_cd(handle,"/elout/solid/metadata"); strcpy(title_location,"/elout/solid/metadata"); lsda_queryvar(handle,"states",&typid,&length,&filenum); lsda_read(handle,LSDA_I1,"states",0,length,dirname); for(i=j=k=0; i<length; i++) { if(dirname[i] == ',') { solid.states[j][k]=0; j++; k=0; } else { solid.states[j][k++]=dirname[i]; } } solid.states[j][k]=0; solid.idsize = -1; solid.ids = NULL; } /* thick shells */ if(have_tshell) { lsda_cd(handle,"/elout/thickshell/metadata"); strcpy(title_location,"/elout/thickshell/metadata"); lsda_queryvar(handle,"states",&typid,&length,&filenum); lsda_read(handle,LSDA_I1,"states",0,length,dirname); for(i=j=k=0; i<length; i++) { if(dirname[i] == ',') { tshell.states[j][k]=0; j++; k=0; } else { tshell.states[j][k++]=dirname[i]; } } tshell.states[j][k]=0; lsda_read(handle,LSDA_I1,"system",0,6,tshell.system); tshell.system[6]=0; } /* beams */ if(have_beam) { lsda_cd(handle,"/elout/beam/metadata"); strcpy(title_location,"/elout/beam/metadata"); beam.idsize = -1; beam.dsize = -1; beam.ids = NULL; beam.s11 = NULL; } /* shells */ if(have_shell) { lsda_cd(handle,"/elout/shell/metadata"); strcpy(title_location,"/elout/shell/metadata"); lsda_queryvar(handle,"states",&typid,&length,&filenum); lsda_read(handle,LSDA_I1,"states",0,length,dirname); for(i=j=k=0; i<length; i++) { if(dirname[i] == ',') { shell.states[j][k]=0; j++; k=0; } else { shell.states[j][k++]=dirname[i]; } } shell.states[j][k]=0; lsda_read(handle,LSDA_I1,"system",0,6,shell.system); shell.system[6]=0; for(i=5; i>0 && shell.system[i] == ' '; i--) shell.system[i]=0; shell.idsize = -1; shell.dsize = -1; shell.ids = NULL; shell.npl = NULL; shell.lxx = NULL; shell.uxx = NULL; shell.sxx = NULL; } /* HIST types */ if(have_solid_hist) { lsda_cd(handle,"/elout/solid_hist/metadata"); strcpy(title_location,"/elout/solid_hist/metadata"); lsda_queryvar(handle,"states",&typid,&length,&filenum); lsda_read(handle,LSDA_I1,"states",0,length,dirname); for(i=j=k=0; i<length; i++) { if(dirname[i] == ',') { solid_hist.states[j][k]=0; j++; k=0; } else { solid_hist.states[j][k++]=dirname[i]; } } solid_hist.states[j][k]=0; solid_hist.idsize = -1; solid_hist.nhv = -1; solid_hist.ids = NULL; solid_hist.mat = NULL; solid_hist.ndata = NULL; solid_hist.nhist = NULL; solid_hist.data = NULL; solid_hist.hist = NULL; solid_hist.strain = NULL; } if(have_tshell_hist) { lsda_cd(handle,"/elout/thickshell_hist/metadata"); strcpy(title_location,"/elout/thickshell_hist/metadata"); lsda_queryvar(handle,"states",&typid,&length,&filenum); lsda_read(handle,LSDA_I1,"states",0,length,dirname); for(i=j=k=0; i<length; i++) { if(dirname[i] == ',') { tshell_hist.states[j][k]=0; j++; k=0; } else { tshell_hist.states[j][k++]=dirname[i]; } } tshell_hist.states[j][k]=0; tshell_hist.idsize = -1; tshell_hist.nhv = -1; tshell_hist.ids = NULL; tshell_hist.mat = NULL; tshell_hist.ndata = NULL; tshell_hist.nhist = NULL; tshell_hist.data = NULL; tshell_hist.hist = NULL; tshell_hist.strain = NULL; } if(have_beam_hist) { lsda_cd(handle,"/elout/beam_hist/metadata"); strcpy(title_location,"/elout/beam_hist/metadata"); lsda_queryvar(handle,"states",&typid,&length,&filenum); lsda_read(handle,LSDA_I1,"states",0,length,dirname); for(i=j=k=0; i<length; i++) { if(dirname[i] == ',') { beam_hist.states[j][k]=0; j++; k=0; } else { beam_hist.states[j][k++]=dirname[i]; } } beam_hist.states[j][k]=0; beam_hist.idsize = -1; beam_hist.nhv = -1; beam_hist.ids = NULL; beam_hist.mat = NULL; beam_hist.ndata = NULL; beam_hist.nhist = NULL; beam_hist.data = NULL; beam_hist.hist = NULL; beam_hist.strain = NULL; } if(have_shell_hist) { lsda_cd(handle,"/elout/shell_hist/metadata"); strcpy(title_location,"/elout/shell_hist/metadata"); lsda_queryvar(handle,"states",&typid,&length,&filenum); lsda_read(handle,LSDA_I1,"states",0,length,dirname); for(i=j=k=0; i<length; i++) { if(dirname[i] == ',') { shell_hist.states[j][k]=0; j++; k=0; } else { shell_hist.states[j][k++]=dirname[i]; } } shell_hist.states[j][k]=0; shell_hist.idsize = -1; shell_hist.nhv = -1; shell_hist.ids = NULL; shell_hist.mat = NULL; shell_hist.ndata = NULL; shell_hist.nhist = NULL; shell_hist.data = NULL; shell_hist.hist = NULL; shell_hist.strain = NULL; } if(strlen(title_location) == 0) return 0; /* huh? */ /* open file and write header */ printf("Extracting ELOUT data\n"); sprintf(output_file,"%selout",output_path); fp=fopen(output_file,"w"); write_message(fp,output_file); if (!fp) return 0; output_title(handle,title_location,fp); k = 0; if(have_solid) { lsda_cd(handle,"/elout/solid/metadata"); i = (have_tshell | have_beam | have_shell | have_tshell_hist | have_beam_hist | have_shell_hist) ? 0 : 1; output_legend(handle,fp,1,i); k = 1; } else if(have_solid_hist) { lsda_cd(handle,"/elout/solid_hist/metadata"); i = (have_tshell | have_beam | have_shell | have_tshell_hist | have_beam_hist | have_shell_hist) ? 0 : 1; output_legend(handle,fp,1,i); k = 1; } if(have_tshell) { lsda_cd(handle,"/elout/thickshell/metadata"); i = !k; j = (have_beam | have_shell | have_beam_hist | have_shell_hist) ? 0 : 1; output_legend(handle,fp,i,j); k = 1; } else if(have_tshell_hist) { lsda_cd(handle,"/elout/thickshell_hist/metadata"); i = !k; j = (have_beam | have_shell | have_beam_hist | have_shell_hist) ? 0 : 1; output_legend(handle,fp,i,j); k = 1; } if(have_beam) { lsda_cd(handle,"/elout/beam/metadata"); i = !k; j = (have_shell | have_shell_hist) ? 0 : 1; output_legend(handle,fp,i,j); k = 1; } else if(have_beam_hist) { lsda_cd(handle,"/elout/beam_hist/metadata"); i = !k; j = (have_shell | have_shell_hist) ? 0 : 1; output_legend(handle,fp,i,j); k = 1; } if(have_shell) { lsda_cd(handle,"/elout/shell/metadata"); i = !k; output_legend(handle,fp,i,1); } else if(have_shell_hist) { lsda_cd(handle,"/elout/shell_hist/metadata"); i = !k; output_legend(handle,fp,i,1); } /* Loop through time states and write each one */ for(state=1; have_solid || have_solid_hist || have_tshell || have_tshell_hist || have_beam || have_beam_hist || have_shell || have_shell_hist ; state++) { if(have_solid) { if(! elout_solid(fp,handle,state,&solid)) { if(solid.ids) { free(solid.ids); free(solid.mat); free(solid.state); free(solid.sxx); free(solid.syy); free(solid.szz); free(solid.sxy); free(solid.syz); free(solid.szx); free(solid.yield); free(solid.effsg); } have_solid = 0; } } else if(have_solid_hist) { if(! elout_solid_hist(fp,handle,state,&solid_hist)) { if(solid_hist.ids) { free(solid_hist.ids); free(solid_hist.mat); free(solid_hist.ndata); free(solid_hist.nhist); free(solid_hist.data); free(solid_hist.hist); free(solid_hist.strain); } have_solid_hist = 0; } } if(have_tshell) { if(! elout_tshell(fp,handle,state,&tshell)) { have_tshell = 0; } } else if(have_tshell_hist) { if(! elout_tshell_hist(fp,handle,state,&tshell_hist)) { if(tshell_hist.ids) { free(tshell_hist.ids); free(tshell_hist.mat); free(tshell_hist.ndata); free(tshell_hist.nhist); free(tshell_hist.data); free(tshell_hist.hist); free(tshell_hist.strain); } have_tshell_hist = 0; } } if(have_beam) { if(! elout_beam(fp,handle,state,&beam)) { if(beam.ids) { free(beam.ids); free(beam.mat); free(beam.nip); free(beam.mtype); free(beam.axial); free(beam.shears); free(beam.sheart); free(beam.moments); free(beam.momentt); free(beam.torsion); free(beam.clength); free(beam.vforce); if(beam.s11) { free(beam.s11); free(beam.s12); free(beam.s31); free(beam.plastic); } } have_beam = 0; } } else if(have_beam_hist) { if(! elout_beam_hist(fp,handle,state,&beam_hist)) { if(beam_hist.ids) { free(beam_hist.ids); free(beam_hist.mat); free(beam_hist.ndata); free(beam_hist.nhist); free(beam_hist.data); free(beam_hist.hist); free(beam_hist.strain); } have_beam_hist = 0; } } if(have_shell) { if(! elout_shell(fp,handle,state,&shell)) { if(shell.ids) { free(shell.ids); free(shell.mat); free(shell.nip); free(shell.state); free(shell.iop); if(shell.npl) free(shell.npl); free(shell.damage); if(shell.lxx) { free(shell.lxx); free(shell.lyy); free(shell.lzz); free(shell.lxy); free(shell.lyz); free(shell.lzx); } if(shell.uxx) { free(shell.uxx); free(shell.uyy); free(shell.uzz); free(shell.uxy); free(shell.uyz); free(shell.uzx); } free(shell.sxx); free(shell.syy); free(shell.szz); free(shell.sxy); free(shell.syz); free(shell.szx); free(shell.ps); } have_shell=0; } } else if(have_shell_hist) { if(! elout_shell_hist(fp,handle,state,&shell_hist)) { if(shell_hist.ids) { free(shell_hist.ids); free(shell_hist.mat); free(shell_hist.ndata); free(shell_hist.nhist); free(shell_hist.data); free(shell_hist.hist); free(shell_hist.strain); } have_shell_hist = 0; } } } fclose(fp); /* free everything here.... */ if(have_solid && solid.ids) { free(solid.ids); free(solid.mat); free(solid.state); free(solid.sxx); free(solid.syy); free(solid.szz); free(solid.sxy); free(solid.syz); free(solid.szx); free(solid.yield); free(solid.effsg); } if(have_beam && beam.ids) { free(beam.ids); free(beam.mat); free(beam.nip); free(beam.mtype); free(beam.axial); free(beam.shears); free(beam.sheart); free(beam.moments); free(beam.momentt); free(beam.torsion); free(beam.clength); free(beam.vforce); if(beam.s11) { free(beam.s11); free(beam.s12); free(beam.s31); free(beam.plastic); } } if(have_shell && shell.ids) { free(shell.ids); free(shell.mat); free(shell.nip); free(shell.state); free(shell.iop); free(shell.damage); if(shell.lxx) { free(shell.lxx); free(shell.lyy); free(shell.lzz); free(shell.lxy); free(shell.lyz); free(shell.lzx); free(shell.uxx); free(shell.uyy); free(shell.uzz); free(shell.uxy); free(shell.uyz); free(shell.uzx); } free(shell.sxx); free(shell.syy); free(shell.szz); free(shell.sxy); free(shell.syz); free(shell.szx); free(shell.ps); } if(have_solid_hist && solid_hist.ids) { free(solid_hist.ids); free(solid_hist.mat); free(solid_hist.ndata); free(solid_hist.nhist); free(solid_hist.data); free(solid_hist.hist); free(solid_hist.strain); } if(have_tshell_hist && tshell_hist.ids) { free(tshell_hist.ids); free(tshell_hist.mat); free(tshell_hist.ndata); free(tshell_hist.nhist); free(tshell_hist.data); free(tshell_hist.hist); free(tshell_hist.strain); } if(have_beam_hist && beam_hist.ids) { free(beam_hist.ids); free(beam_hist.mat); free(beam_hist.ndata); free(beam_hist.nhist); free(beam_hist.data); free(beam_hist.hist); free(beam_hist.strain); } if(have_shell_hist && shell_hist.ids) { free(shell_hist.ids); free(shell_hist.mat); free(shell_hist.ndata); free(shell_hist.nhist); free(shell_hist.data); free(shell_hist.hist); free(shell_hist.strain); } printf(" %d states extracted\n",state-1); return 0; } int elout_solid(FILE *fp,int handle, int state, MDSOLID *solid) { char dirname[128]; float time; int cycle; int typid, filenum; LSDA_Length length; int num; int have_strain,i; if(state<=999999) sprintf(dirname,"/elout/solid/d%6.6d",state); else sprintf(dirname,"/elout/solid/d%8.8d",state); lsda_queryvar(handle,dirname,&typid,&length,&filenum); if(typid != 0) return 0; lsda_cd(handle,dirname); lsda_queryvar(handle,"eps_xx",&typid,&length,&filenum); have_strain = (typid > 0); lsda_queryvar(handle,"ids",&typid,&length,&filenum); if(typid < 0) return 0; /* all elements deleted */ num=length; if(num > solid->idsize) { if(solid->ids) { free(solid->ids); free(solid->mat); free(solid->state); free(solid->sxx); free(solid->syy); free(solid->szz); free(solid->sxy); free(solid->syz); free(solid->szx); free(solid->yield); free(solid->effsg); } solid->ids = (int *) malloc(num*sizeof(int)); solid->mat = (int *) malloc(num*sizeof(int)); solid->state = (int *) malloc(num*sizeof(int)); solid->sxx = (float *) malloc(num*sizeof(float)); solid->syy = (float *) malloc(num*sizeof(float)); solid->szz = (float *) malloc(num*sizeof(float)); solid->sxy = (float *) malloc(num*sizeof(float)); solid->syz = (float *) malloc(num*sizeof(float)); solid->szx = (float *) malloc(num*sizeof(float)); solid->yield = (float *) malloc(num*sizeof(float)); solid->effsg = (float *) malloc(num*sizeof(float)); solid->idsize = num; } if(lsda_read(handle,LSDA_FLOAT,"time",0,1,&time) != 1) return 0; if(lsda_read(handle,LSDA_INT,"cycle",0,1,&cycle) != 1) return 0; if(lsda_read(handle,LSDA_INT,"ids",0,length,solid->ids) != length) return 0; if(lsda_read(handle,LSDA_INT,"mtype",0,length,solid->mat) != length) return 0; if(lsda_read(handle,LSDA_INT,"state",0,length,solid->state) != length) return 0; if(lsda_read(handle,LSDA_FLOAT,"sig_xx",0,length,solid->sxx) != length) return 0; if(lsda_read(handle,LSDA_FLOAT,"sig_yy",0,length,solid->syy) != length) return 0; if(lsda_read(handle,LSDA_FLOAT,"sig_zz",0,length,solid->szz) != length) return 0; if(lsda_read(handle,LSDA_FLOAT,"sig_xy",0,length,solid->sxy) != length) return 0; if(lsda_read(handle,LSDA_FLOAT,"sig_yz",0,length,solid->syz) != length) return 0; if(lsda_read(handle,LSDA_FLOAT,"sig_zx",0,length,solid->szx) != length) return 0; if(lsda_read(handle,LSDA_FLOAT,"yield",0,length,solid->yield) != length) return 0; if(lsda_read(handle,LSDA_FLOAT,"effsg",0,length,solid->effsg) != length) return 0; /* Output stress data */ fprintf(fp,"\n\n\n e l e m e n t s t r e s s c a l c u l a t i o n s"); fprintf(fp," f o r t i m e s t e p%9d ( at time %12.5E )\n\n",cycle,time); fprintf(fp," element materl\n"); fprintf(fp," ipt stress sig-xx sig-yy sig"); fprintf(fp,"-zz sig-xy sig-yz sig-zx "); fprintf(fp," yield\n state "); fprintf(fp," "); fprintf(fp,"effsg function\n"); for(i=0; i<length; i++) { fprintf(fp,"%8d-%7d\n",solid->ids[i],solid->mat[i]); fprintf(fp," 1 %-7s ",solid->states[solid->state[i]-1]); fprintf(fp,"%12.4E%12.4E%12.4E",solid->sxx[i],solid->syy[i],solid->szz[i]); fprintf(fp,"%12.4E%12.4E%12.4E%14.4E%14.4E\n",solid->sxy[i],solid->syz[i], solid->szx[i],solid->effsg[i],solid->yield[i]); } if(have_strain) { if(lsda_read(handle,LSDA_FLOAT,"eps_xx",0,length,solid->sxx) != length) return 0; if(lsda_read(handle,LSDA_FLOAT,"eps_yy",0,length,solid->syy) != length) return 0; if(lsda_read(handle,LSDA_FLOAT,"eps_zz",0,length,solid->szz) != length) return 0; if(lsda_read(handle,LSDA_FLOAT,"eps_xy",0,length,solid->sxy) != length) return 0; if(lsda_read(handle,LSDA_FLOAT,"eps_yz",0,length,solid->syz) != length) return 0; if(lsda_read(handle,LSDA_FLOAT,"eps_zx",0,length,solid->szx) != length) return 0; fprintf(fp,"\n\n\n e l e m e n t s t r a i n c a l c u l a t i o n s"); fprintf(fp," f o r t i m e s t e p%9d ( at time %12.5E )\n\n",cycle,time); fprintf(fp," element strain eps-xx eps-yy eps"); fprintf(fp,"-zz eps-xy eps-yz eps-zx "); fprintf(fp," yield\n num/ipt state\n"); /* yield? But nothing is printed out there....ack! */ for(i=0; i<length; i++) { fprintf(fp,"%8d-%7d\n",solid->ids[i],solid->mat[i]); fprintf(fp," 1 %-7s ",solid->states[solid->state[i]-1]); fprintf(fp,"%12.4E%12.4E%12.4E",solid->sxx[i],solid->syy[i],solid->szz[i]); fprintf(fp,"%12.4E%12.4E%12.4E\n",solid->sxy[i],solid->syz[i],solid->szx[i]); } } return 1; } int elout_tshell(FILE *fp,int handle, int state, MDTSHELL *tshell) { char dirname[128]; float time; int cycle; int typid, filenum; LSDA_Length length; int num,num1,num2; int have_strain,have_genoa,i,j,k; if(state<=999999) sprintf(dirname,"/elout/thickshell/d%6.6d",state); else sprintf(dirname,"/elout/thickshell/d%8.8d",state); lsda_queryvar(handle,dirname,&typid,&length,&filenum); if(typid != 0) return 0; lsda_cd(handle,dirname); lsda_queryvar(handle,"lower_eps_xx",&typid,&length,&filenum); num2=length; have_strain = (typid > 0); lsda_queryvar(handle,"ids",&typid,&length,&filenum); if(typid < 0) return 0; /* all elements deleted */ num=length; lsda_queryvar(handle,"genoa_damage",&typid,&length,&filenum); have_genoa= (typid > 0); lsda_queryvar(handle,"state",&typid,&length,&filenum); num1=length; tshell->ids = (int *) malloc(num*sizeof(int)); tshell->mat = (int *) malloc(num*sizeof(int)); tshell->state = (int *) malloc(num1*sizeof(int)); tshell->nip = (int *) malloc(num*sizeof(int)); tshell->damage = (int *) malloc(num1*sizeof(int)); tshell->sxx = (float *) malloc(num1*sizeof(float)); tshell->syy = (float *) malloc(num1*sizeof(float)); tshell->szz = (float *) malloc(num1*sizeof(float)); tshell->sxy = (float *) malloc(num1*sizeof(float)); tshell->syz = (float *) malloc(num1*sizeof(float)); tshell->szx = (float *) malloc(num1*sizeof(float)); tshell->uxx = (float *) malloc(num2*sizeof(float)); tshell->uyy = (float *) malloc(num2*sizeof(float)); tshell->uzz = (float *) malloc(num2*sizeof(float)); tshell->uxy = (float *) malloc(num2*sizeof(float)); tshell->uyz = (float *) malloc(num2*sizeof(float)); tshell->uzx = (float *) malloc(num2*sizeof(float)); tshell->yield = (float *) malloc(num1*sizeof(float)); tshell->effsg = (float *) malloc(num1*sizeof(float)); if(lsda_read(handle,LSDA_FLOAT,"time",0,1,&time) != 1) return 0; if(lsda_read(handle,LSDA_INT,"cycle",0,1,&cycle) != 1) return 0; if(lsda_read(handle,LSDA_INT,"ids",0,num,tshell->ids) != num) return 0; if(lsda_read(handle,LSDA_INT,"mat",0,num,tshell->mat) != num) return 0; if(lsda_read(handle,LSDA_INT,"nip",0,num,tshell->nip) != num) return 0; if(lsda_read(handle,LSDA_INT,"state",0,num1,tshell->state) != num1) return 0; if(lsda_read(handle,LSDA_FLOAT,"sig_xx",0,num1,tshell->sxx) != num1) return 0; if(lsda_read(handle,LSDA_FLOAT,"sig_yy",0,num1,tshell->syy) != num1) return 0; if(lsda_read(handle,LSDA_FLOAT,"sig_zz",0,num1,tshell->szz) != num1) return 0; if(lsda_read(handle,LSDA_FLOAT,"sig_xy",0,num1,tshell->sxy) != num1) return 0; if(lsda_read(handle,LSDA_FLOAT,"sig_yz",0,num1,tshell->syz) != num1) return 0; if(lsda_read(handle,LSDA_FLOAT,"sig_zx",0,num1,tshell->szx) != num1) return 0; if(lsda_read(handle,LSDA_FLOAT,"yield",0,num1,tshell->yield) != num1) return 0; if(have_genoa) if(lsda_read(handle,LSDA_INT,"genoa_damage",0,num1,tshell->damage) != num1) return 0; /* Output stress data */ fprintf(fp,"\n\n\n e l e m e n t s t r e s s c a l c u l a t i o n s"); fprintf(fp," f o r t i m e s t e p%9d ( at time%12.5E )\n\n",cycle,time); fprintf(fp," element materl\n"); fprintf(fp," num/ipt stress sig-xx sig-yy sig"); fprintf(fp,"-zz sig-xy sig-yz sig-zx "); fprintf(fp,"yield%s\n state ",(have_genoa?" genoa":"")); fprintf(fp," "); fprintf(fp," function%s\n",(have_genoa?" damage":"")); for(j=k=0;j<num;j++){ fprintf(fp,"%8d-%5d\n",tshell->ids[j],tshell->mat[j]); for(i=0; i<tshell->nip[j]; i++,k++) { fprintf(fp,"%7d %-7s ",i+1,tshell->states[tshell->state[k]-1]); fprintf(fp,"%12.4E%12.4E%12.4E",tshell->sxx[k],tshell->syy[k],tshell->szz[k]); fprintf(fp,"%12.4E%12.4E%12.4E%14.4E",tshell->sxy[k],tshell->syz[k], tshell->szx[k],tshell->yield[k]); if(have_genoa) if(tshell->damage[k]!=-1)fprintf(fp,"%10d",tshell->damage[k]); fprintf(fp,"\n"); } } if(have_strain) { fprintf(fp,"\n strains (global)"); fprintf(fp," eps-xx eps-yy eps"); fprintf(fp,"-zz eps-xy eps-yz eps-zx \n "); if(lsda_read(handle,LSDA_FLOAT,"lower_eps_xx",0,num2,tshell->sxx) != num2) return 0; if(lsda_read(handle,LSDA_FLOAT,"lower_eps_yy",0,num2,tshell->syy) != num2) return 0; if(lsda_read(handle,LSDA_FLOAT,"lower_eps_zz",0,num2,tshell->szz) != num2) return 0; if(lsda_read(handle,LSDA_FLOAT,"lower_eps_xy",0,num2,tshell->sxy) != num2) return 0; if(lsda_read(handle,LSDA_FLOAT,"lower_eps_yz",0,num2,tshell->syz) != num2) return 0; if(lsda_read(handle,LSDA_FLOAT,"lower_eps_zx",0,num2,tshell->szx) != num2) return 0; if(lsda_read(handle,LSDA_FLOAT,"upper_eps_xx",0,num2,tshell->uxx) != num2) return 0; if(lsda_read(handle,LSDA_FLOAT,"upper_eps_yy",0,num2,tshell->uyy) != num2) return 0; if(lsda_read(handle,LSDA_FLOAT,"upper_eps_zz",0,num2,tshell->uzz) != num2) return 0; if(lsda_read(handle,LSDA_FLOAT,"upper_eps_xy",0,num2,tshell->uxy) != num2) return 0; if(lsda_read(handle,LSDA_FLOAT,"upper_eps_yz",0,num2,tshell->uyz) != num2) return 0; if(lsda_read(handle,LSDA_FLOAT,"upper_eps_zx",0,num2,tshell->uzx) != num2) return 0; for(i=0;i<num;i++){ fprintf(fp,"\n%8d-%5d\n",tshell->ids[i],tshell->mat[i]); fprintf(fp," lower ipt %12.4E%12.4E%12.4E",tshell->sxx[i],tshell->syy[i],tshell->szz[i]); fprintf(fp,"%12.4E%12.4E%12.4E\n",tshell->sxy[i],tshell->syz[i],tshell->szx[i]); fprintf(fp," upper ipt %12.4E%12.4E%12.4E",tshell->uxx[i],tshell->uyy[i],tshell->uzz[i]); fprintf(fp,"%12.4E%12.4E%12.4E\n",tshell->uxy[i],tshell->uyz[i],tshell->uzx[i]); } } free(tshell->ids); free(tshell->mat); free(tshell->state); free(tshell->nip); free(tshell->damage); free(tshell->sxx); free(tshell->syy); free(tshell->szz); free(tshell->sxy); free(tshell->syz); free(tshell->szx); free(tshell->uxx); free(tshell->uyy); free(tshell->uzz); free(tshell->uxy); free(tshell->uyz); free(tshell->uzx); free(tshell->yield); free(tshell->effsg); return 1; } int elout_beam(FILE *fp,int handle, int state, MDBEAM *beam) { char dirname[128]; float time; int cycle; int typid, filenum; LSDA_Length length; int i,j,k,len2,have_mtype; if(state<=999999) sprintf(dirname,"/elout/beam/d%6.6d",state); else sprintf(dirname,"/elout/beam/d%8.8d",state); lsda_queryvar(handle,dirname,&typid,&length,&filenum); if(typid != 0) return 0; lsda_cd(handle,dirname); lsda_queryvar(handle,"ids",&typid,&length,&filenum); if(typid < 0) return 0; if((int) length > beam->idsize) { if(beam->ids) { free(beam->ids); free(beam->mat); free(beam->nip); free(beam->mtype); free(beam->axial); free(beam->shears); free(beam->sheart); free(beam->moments); free(beam->momentt); free(beam->torsion); free(beam->clength); free(beam->vforce); } beam->ids = (int *) malloc(length*sizeof(int)); beam->mat = (int *) malloc(length*sizeof(int)); beam->nip = (int *) malloc(length*sizeof(int)); beam->mtype = (int *) malloc(length*sizeof(int)); beam->axial = (float *) malloc(length*sizeof(float)); beam->shears = (float *) malloc(length*sizeof(float)); beam->sheart = (float *) malloc(length*sizeof(float)); beam->moments = (float *) malloc(length*sizeof(float)); beam->momentt = (float *) malloc(length*sizeof(float)); beam->torsion = (float *) malloc(length*sizeof(float)); beam->clength = (float *) malloc(length*sizeof(float)); beam->vforce = (float *) malloc(length*sizeof(float)); beam->idsize = length; } if(lsda_read(handle,LSDA_FLOAT,"time",0,1,&time) != 1) return 0; if(lsda_read(handle,LSDA_INT,"cycle",0,1,&cycle) != 1) return 0; if(lsda_read(handle,LSDA_INT,"ids",0,length,beam->ids) != length) return 0; if(lsda_read(handle,LSDA_INT,"mat",0,length,beam->mat) != length) return 0; if(lsda_read(handle,LSDA_INT,"nip",0,length,beam->nip) != length) return 0; have_mtype=1; if(lsda_read(handle,LSDA_INT,"mtype",0,length,beam->mtype) != length) have_mtype=0; for(i=len2=0; i < length; i++) len2 += beam->nip[i]; if(len2 && len2 > beam->dsize) { if(beam->s11) { free(beam->s11); free(beam->s12); free(beam->s31); free(beam->plastic); } beam->s11 = (float *) malloc(len2*sizeof(float)); beam->s12 = (float *) malloc(len2*sizeof(float)); beam->s31 = (float *) malloc(len2*sizeof(float)); beam->plastic = (float *) malloc(len2*sizeof(float)); beam->dsize = len2; } if(lsda_read(handle,LSDA_FLOAT,"axial",0,length,beam->axial) != length) return 0; if(lsda_read(handle,LSDA_FLOAT,"shear_s",0,length,beam->shears) != length) return 0; if(lsda_read(handle,LSDA_FLOAT,"shear_t",0,length,beam->sheart) != length) return 0; if(lsda_read(handle,LSDA_FLOAT,"moment_s",0,length,beam->moments) != length) return 0; if(lsda_read(handle,LSDA_FLOAT,"moment_t",0,length,beam->momentt) != length) return 0; if(lsda_read(handle,LSDA_FLOAT,"torsion",0,length,beam->torsion) != length) return 0; if(have_mtype) { if(lsda_read(handle,LSDA_FLOAT,"coef_length",0,length,beam->clength) != length) return 0; if(lsda_read(handle,LSDA_FLOAT,"visc_force",0,length,beam->vforce) != length) return 0; } if(len2) { if(lsda_read(handle,LSDA_FLOAT,"sigma_11",0,len2,beam->s11) != len2) return 0; if(lsda_read(handle,LSDA_FLOAT,"sigma_12",0,len2,beam->s12) != len2) return 0; if(lsda_read(handle,LSDA_FLOAT,"sigma_31",0,len2,beam->s31) != len2) return 0; if(lsda_read(handle,LSDA_FLOAT,"plastic_eps",0,len2,beam->plastic) != len2) return 0; } /* Output this data */ fprintf(fp," r e s u l t a n t s a n d s t r e s s e s "); fprintf(fp,"f o r t i m e s t e p%9d ( at time%12.5E )\n",cycle,time); for(i=k=0; i<length; i++) { if(have_mtype) { fprintf(fp,"\n\n beam/truss # =%8d part ID =%10d material type=%8d\n", beam->ids[i],beam->mat[i],beam->mtype[i]); if(beam->mtype[i] == 156) { fprintf(fp,"\n muscle data length actlevel lgth "); fprintf(fp,"coef epsrate pass frc visc frc activ frc total frc\n"); fprintf(fp," %11.3E%11.3E%11.3E",beam->momentt[i],beam->moments[i],beam->clength[i]); fprintf(fp,"%11.3E%11.3E%11.3E%11.3E%11.3E\n",beam->torsion[i],beam->shears[i],beam->vforce[i],beam->sheart[i],beam->axial[i]); } else { fprintf(fp,"\n resultants axial shear-s she"); fprintf(fp,"ar-t moment-s moment-t torsion\n"); fprintf(fp," %11.3E%11.3E%11.3E",beam->axial[i],beam->shears[i],beam->sheart[i]); fprintf(fp,"%11.3E%11.3E%11.3E\n",beam->moments[i],beam->momentt[i],beam->torsion[i]); } } else { fprintf(fp,"\n\n\n\n beam/truss # =%8d material # =%5d\n", beam->ids[i],beam->mat[i]); fprintf(fp,"\n\n resultants axial shear-s she"); fprintf(fp,"ar-t moment-s moment-t torsion\n"); fprintf(fp," %11.3E%11.3E%11.3E",beam->axial[i],beam->shears[i],beam->sheart[i]); fprintf(fp,"%11.3E%11.3E%11.3E\n",beam->moments[i],beam->momentt[i],beam->torsion[i]); } if(beam->nip[i]) { fprintf(fp,"\n\n integration point stresses\n"); fprintf(fp," "); fprintf(fp,"sigma 11 sigma 12 sigma 31 plastic eps\n"); for(j=0; j<beam->nip[i]; j++,k++) fprintf(fp,"%5d %15.6E%15.6E%15.6E%15.6E\n",j+1, beam->s11[k],beam->s12[k],beam->s31[k],beam->plastic[k]); } } return 1; } int elout_shell(FILE *fp,int handle, int state, MDSHELL *shell) { char dirname[128]; float time; int cycle; int typid, filenum; LSDA_Length length,length2; int have_strain,have_genoa,i,j,k,len2; int jj,k1,k2; int have_npl; if(state<=999999) sprintf(dirname,"/elout/shell/d%6.6d",state); else sprintf(dirname,"/elout/shell/d%8.8d",state); lsda_queryvar(handle,dirname,&typid,&length,&filenum); if(typid != 0) return 0; lsda_cd(handle,dirname); lsda_queryvar(handle,"npl",&typid,&length2,&filenum); have_npl = (typid > 0); if(have_npl) { lsda_queryvar(handle,"eps_xx",&typid,&length2,&filenum); have_strain = (typid > 0); } else { lsda_queryvar(handle,"lower_eps_xx",&typid,&length2,&filenum); have_strain = (typid > 0); } lsda_queryvar(handle,"genoa_damage",&typid,&length2,&filenum); have_genoa = (typid > 0); lsda_queryvar(handle,"ids",&typid,&length,&filenum); if(typid < 0) return 0; if((int) length > shell->idsize) { if(shell->ids) { free(shell->ids); free(shell->mat); free(shell->nip); free(shell->iop); if(shell->npl) free(shell->npl); if(shell->lxx) { free(shell->lxx); free(shell->lyy); free(shell->lzz); free(shell->lxy); free(shell->lyz); free(shell->lzx); } if(shell->uxx) { free(shell->uxx); free(shell->uyy); free(shell->uzz); free(shell->uxy); free(shell->uyz); free(shell->uzx); } } shell->ids = (int *) malloc(length*sizeof(int)); shell->mat = (int *) malloc(length*sizeof(int)); shell->nip = (int *) malloc(length*sizeof(int)); shell->iop = (int *) malloc(length*sizeof(int)); if(have_npl) { shell->npl = (int *) malloc(length*sizeof(int)); /* don't know how big lxx needs to be yet, so allocate it below */ shell->uxx = NULL; } else { shell->npl = NULL; if(have_strain) { shell->lxx = (float *) malloc(length*sizeof(float)); shell->lyy = (float *) malloc(length*sizeof(float)); shell->lzz = (float *) malloc(length*sizeof(float)); shell->lxy = (float *) malloc(length*sizeof(float)); shell->lyz = (float *) malloc(length*sizeof(float)); shell->lzx = (float *) malloc(length*sizeof(float)); shell->uxx = (float *) malloc(length*sizeof(float)); shell->uyy = (float *) malloc(length*sizeof(float)); shell->uzz = (float *) malloc(length*sizeof(float)); shell->uxy = (float *) malloc(length*sizeof(float)); shell->uyz = (float *) malloc(length*sizeof(float)); shell->uzx = (float *) malloc(length*sizeof(float)); } } shell->idsize = length; } if(lsda_read(handle,LSDA_FLOAT,"time",0,1,&time) != 1) return 0; if(lsda_read(handle,LSDA_INT,"cycle",0,1,&cycle) != 1) return 0; if(lsda_read(handle,LSDA_INT,"ids",0,length,shell->ids) != length) return 0; if(lsda_read(handle,LSDA_INT,"mat",0,length,shell->mat) != length) return 0; if(lsda_read(handle,LSDA_INT,"nip",0,length,shell->nip) != length) return 0; if(lsda_read(handle,LSDA_INT,"iop",0,length,shell->iop) != length) return 0; if(have_npl) { if(lsda_read(handle,LSDA_INT,"npl",0,length,shell->npl) != length) return 0; for(i=len2=0; i < length; i++) len2 += shell->nip[i]*shell->npl[i]; if(have_strain) { shell->lxx = (float *) malloc(len2*sizeof(float)); shell->lyy = (float *) malloc(len2*sizeof(float)); shell->lzz = (float *) malloc(len2*sizeof(float)); shell->lxy = (float *) malloc(len2*sizeof(float)); shell->lyz = (float *) malloc(len2*sizeof(float)); shell->lzx = (float *) malloc(len2*sizeof(float)); } } else { for(i=len2=0; i < length; i++) len2 += shell->nip[i]; } if(len2 > shell->dsize) { if(shell->sxx) { free(shell->state); free(shell->sxx); free(shell->syy); free(shell->szz); free(shell->sxy); free(shell->syz); free(shell->szx); free(shell->ps); free(shell->damage); } shell->state = (int *) malloc(len2*sizeof(int)); shell->sxx = (float *) malloc(len2*sizeof(float)); shell->syy = (float *) malloc(len2*sizeof(float)); shell->szz = (float *) malloc(len2*sizeof(float)); shell->sxy = (float *) malloc(len2*sizeof(float)); shell->syz = (float *) malloc(len2*sizeof(float)); shell->szx = (float *) malloc(len2*sizeof(float)); shell->ps = (float *) malloc(len2*sizeof(float)); shell->damage= (int *) malloc(len2*sizeof(int)); shell->dsize = len2; } if(lsda_read(handle,LSDA_INT,"state",0,len2,shell->state) != len2) return 0; if(lsda_read(handle,LSDA_FLOAT,"sig_xx",0,len2,shell->sxx) != len2) return 0; if(lsda_read(handle,LSDA_FLOAT,"sig_yy",0,len2,shell->syy) != len2) return 0; if(lsda_read(handle,LSDA_FLOAT,"sig_zz",0,len2,shell->szz) != len2) return 0; if(lsda_read(handle,LSDA_FLOAT,"sig_xy",0,len2,shell->sxy) != len2) return 0; if(lsda_read(handle,LSDA_FLOAT,"sig_yz",0,len2,shell->syz) != len2) return 0; if(lsda_read(handle,LSDA_FLOAT,"sig_zx",0,len2,shell->szx) != len2) return 0; if(lsda_read(handle,LSDA_FLOAT,"plastic_strain",0,len2,shell->ps) != len2) return 0; if(have_npl && have_strain) { if(lsda_read(handle,LSDA_FLOAT,"eps_xx",0,len2,shell->lxx) != len2) return 0; if(lsda_read(handle,LSDA_FLOAT,"eps_yy",0,len2,shell->lyy) != len2) return 0; if(lsda_read(handle,LSDA_FLOAT,"eps_zz",0,len2,shell->lzz) != len2) return 0; if(lsda_read(handle,LSDA_FLOAT,"eps_xy",0,len2,shell->lxy) != len2) return 0; if(lsda_read(handle,LSDA_FLOAT,"eps_yz",0,len2,shell->lyz) != len2) return 0; if(lsda_read(handle,LSDA_FLOAT,"eps_zx",0,len2,shell->lzx) != len2) return 0; } if(have_genoa) if(lsda_read(handle,LSDA_INT,"genoa_damage",0,len2,shell->damage) != len2) return 0; /* Output this data */ if(have_npl) { fprintf(fp,"\n\n\n e l e m e n t s t r e s s c a l c u l a t i o n s"); fprintf(fp," f o r t i m e s t e p%9d ( at time %12.5E )\n\n",cycle,time); sprintf(dirname,"(%s)",shell->system); fprintf(fp," element materl%-8s\n",dirname); fprintf(fp," ipt-shl component xx yy "); fprintf(fp," zz xy yz zx plastic%s\n",(have_genoa?" genoa":"")); fprintf(fp," "); fprintf(fp," strain %s\n",(have_genoa?" damage":"")); for(i=k1=k2=0; i<length; i++) { fprintf(fp,"%8d-%7d\n",shell->ids[i],shell->mat[i]); for(j=0; j<shell->nip[i]; j++) { for(jj=0; jj<shell->npl[i]; jj++,k1++) { fprintf(fp,"%4d p%1d %-7s ",j+1,jj+1,"stress"); fprintf(fp,"%12.4E%12.4E%12.4E",shell->sxx[k1],shell->syy[k1],shell->szz[k1]); fprintf(fp,"%12.4E%12.4E%12.4E%14.4E",shell->sxy[k1],shell->syz[k1], shell->szx[k1],shell->ps[k1]); if(have_genoa) if(shell->damage[k1]!=-1)fprintf(fp,"%10d",shell->damage[k1]); fprintf(fp,"\n"); } if(have_strain) { for(jj=0; jj<shell->npl[i]; jj++,k2++) { fprintf(fp,"%4d p%1d %-7s ",j+1,jj+1,"strain"); fprintf(fp,"%12.4E%12.4E%12.4E" ,shell->lxx[k2],shell->lyy[k2],shell->lzz[k2]); fprintf(fp,"%12.4E%12.4E%12.4E\n",shell->lxy[k2],shell->lyz[k2],shell->lzx[k2]); } } } } } else { fprintf(fp,"\n\n\n e l e m e n t s t r e s s c a l c u l a t i o n s"); fprintf(fp," f o r t i m e s t e p%9d ( at time %12.5E )\n\n",cycle,time); sprintf(dirname,"(%s)",shell->system); fprintf(fp," element materl%-8s\n",dirname); fprintf(fp," ipt-shl stress sig-xx sig-yy sig"); fprintf(fp,"-zz sig-xy sig-yz sig-zx plastic%s\n",(have_genoa?" genoa":"")); fprintf(fp," state "); fprintf(fp," strain %s\n",(have_genoa?" damage":"")); for(i=k=0; i<length; i++) { fprintf(fp,"%8d-%7d\n",shell->ids[i],shell->mat[i]); for(j=0; j<shell->nip[i]; j++,k++) { fprintf(fp,"%4d-%3d %-7s ",j+1,shell->iop[i],shell->states[shell->state[k]-1]); fprintf(fp,"%12.4E%12.4E%12.4E",shell->sxx[k],shell->syy[k],shell->szz[k]); fprintf(fp,"%12.4E%12.4E%12.4E%14.4E",shell->sxy[k],shell->syz[k], shell->szx[k],shell->ps[k]); if(have_genoa) if(shell->damage[k]!=-1)fprintf(fp,"%10d",shell->damage[k]); fprintf(fp,"\n"); } } } if(have_strain && !have_npl) { if(lsda_read(handle,LSDA_FLOAT,"lower_eps_xx",0,length,shell->lxx) != length) return 0; if(lsda_read(handle,LSDA_FLOAT,"lower_eps_yy",0,length,shell->lyy) != length) return 0; if(lsda_read(handle,LSDA_FLOAT,"lower_eps_zz",0,length,shell->lzz) != length) return 0; if(lsda_read(handle,LSDA_FLOAT,"lower_eps_xy",0,length,shell->lxy) != length) return 0; if(lsda_read(handle,LSDA_FLOAT,"lower_eps_yz",0,length,shell->lyz) != length) return 0; if(lsda_read(handle,LSDA_FLOAT,"lower_eps_zx",0,length,shell->lzx) != length) return 0; if(lsda_read(handle,LSDA_FLOAT,"upper_eps_xx",0,length,shell->uxx) != length) return 0; if(lsda_read(handle,LSDA_FLOAT,"upper_eps_yy",0,length,shell->uyy) != length) return 0; if(lsda_read(handle,LSDA_FLOAT,"upper_eps_zz",0,length,shell->uzz) != length) return 0; if(lsda_read(handle,LSDA_FLOAT,"upper_eps_xy",0,length,shell->uxy) != length) return 0; if(lsda_read(handle,LSDA_FLOAT,"upper_eps_yz",0,length,shell->uyz) != length) return 0; if(lsda_read(handle,LSDA_FLOAT,"upper_eps_zx",0,length,shell->uzx) != length) return 0; /* all the blanks here are silly, but are output by DYNA so..... */ sprintf(dirname,"(%s)",shell->system); fprintf(fp,"\n strains %-8s eps-xx eps-yy eps",dirname); fprintf(fp,"-zz eps-xy eps-yz eps-zx \n"); fprintf(fp," "); fprintf(fp," \n"); for(i=0; i<length; i++) { fprintf(fp,"%8d-%7d\n",shell->ids[i],shell->mat[i]); fprintf(fp," lower ipt %12.4E%12.4E%12.4E",shell->lxx[i],shell->lyy[i],shell->lzz[i]); fprintf(fp,"%12.4E%12.4E%12.4E\n",shell->lxy[i],shell->lyz[i],shell->lzx[i]); fprintf(fp," upper ipt %12.4E%12.4E%12.4E",shell->uxx[i],shell->uyy[i],shell->uzz[i]); fprintf(fp,"%12.4E%12.4E%12.4E\n",shell->uxy[i],shell->uyz[i],shell->uzx[i]); } } return 1; } int elout_solid_hist(FILE *fp,int handle, int state, MDHIST *dp) { char dirname[128]; float time; int cycle; int typid, filenum; LSDA_Length length,lhist,lstr,ldata; int num; int have_strain,have_hist,i,j,k,kk,l,n,nips,istate,perip,nlines; if(state<=999999) sprintf(dirname,"/elout/solid_hist/d%6.6d",state); else sprintf(dirname,"/elout/solid_hist/d%8.8d",state); lsda_queryvar(handle,dirname,&typid,&length,&filenum); if(typid != 0) return 0; lsda_cd(handle,dirname); lsda_queryvar(handle,"data",&typid,&ldata,&filenum); lsda_queryvar(handle,"hist",&typid,&lhist,&filenum); have_hist = (typid > 0); lsda_queryvar(handle,"strain",&typid,&lstr,&filenum); have_strain = (typid > 0); lsda_queryvar(handle,"ids",&typid,&length,&filenum); if(typid < 0) return 0; /* all elements deleted */ num=length; if(num > dp->idsize) { if(dp->ids) { free(dp->ids); free(dp->mat); free(dp->ndata); free(dp->data); free(dp->nhist); free(dp->hist); free(dp->strain); } dp->ids = (int *) malloc(num*sizeof(int)); dp->mat = (int *) malloc(num*sizeof(int)); dp->ndata = (int *) malloc(num*sizeof(int)); dp->data = (float *) malloc(ldata*sizeof(float)); if(have_hist) { dp->nhist = (int *) malloc(num*sizeof(int)); dp->hist = (float *) malloc(lhist*sizeof(float)); } else { dp->nhist = (int *) malloc(sizeof(int)); dp->hist = (float *) malloc(sizeof(float)); } if(have_strain) { dp->strain = (float *) malloc(lstr*sizeof(float)); } else { dp->strain = (float *) malloc(sizeof(float)); } } if(lsda_read(handle,LSDA_FLOAT,"time",0,1,&time) != 1) return 0; if(lsda_read(handle,LSDA_INT,"cycle",0,1,&cycle) != 1) return 0; if(lsda_read(handle,LSDA_INT,"nhv",0,1,&dp->nhv) != 1) return 0; if(lsda_read(handle,LSDA_INT,"ids",0,length,dp->ids) != length) return 0; if(lsda_read(handle,LSDA_INT,"mats",0,length,dp->mat) != length) return 0; if(lsda_read(handle,LSDA_INT,"ndata",0,length,dp->ndata) != length) return 0; if(lsda_read(handle,LSDA_FLOAT,"data",0,ldata,dp->data) != ldata) return 0; if(have_hist) { if(lsda_read(handle,LSDA_INT,"nhist",0,length,dp->nhist) != length) return 0; if(lsda_read(handle,LSDA_FLOAT,"hist",0,lhist,dp->hist) != lhist) return 0; } if(have_strain) { if(lsda_read(handle,LSDA_FLOAT,"strain",0,lstr,dp->strain) != lstr) return 0; } /* Output stress data */ fprintf(fp,"\n\n\n e l e m e n t s t r e s s c a l c u l a t i o n s"); fprintf(fp," f o r t i m e s t e p%9d ( at time %12.5E )\n",cycle,time); fprintf(fp," element part ID (solid)\n"); fprintf(fp," ipt stress stress-xx stress-yy stress"); fprintf(fp,"-zz stress-xy stress-yz stress-zx "); fprintf(fp," yield\n state "); fprintf(fp," "); fprintf(fp,"effsg function\n"); for(i=k=0; i<length; i++) { fprintf(fp,"%8d-%7d\n",dp->ids[i],dp->mat[i]); nips = dp->ndata[i]/9; for(j=0; j<nips; j++) { istate = dp->data[k]; fprintf(fp,"%8d %-7s ",j+1,dp->states[istate-1]); fprintf(fp,"%12.4E%12.4E%12.4E",dp->data[k+1],dp->data[k+2], dp->data[k+3]); fprintf(fp,"%12.4E%12.4E%12.4E%14.4E%14.4E\n",dp->data[k+4],dp->data[k+5], dp->data[k+6],dp->data[k+7],dp->data[k+8]); k=k+9; } } if(have_hist) { fprintf(fp,"\n\n\n e l e m e n t h i s t r y c a l c u l a t i o n s"); fprintf(fp," f o r t i m e s t e p%9d ( at time %12.5E )\n",cycle,time); fprintf(fp," element part ID (solid)\n"); fprintf(fp," ipt history 1 history 2 history 3 history 4"); fprintf(fp," history 5 history 6 history 7 history 8\n"); nlines = (dp->nhv-1)/8+1; for(i=k=0; i<length; i++) { fprintf(fp,"%8d-%7d\n",dp->ids[i],dp->mat[i]); nips = dp->ndata[i]/9; perip = dp->nhist[i]/nips; /* This part is a bit strange. The ascii routines print out nhv entries, 8 per line. But there may be fewer data values than that, in which case it just prints out blanks until nhv entries have been output */ for(j=0; j<nips; j++) { istate = dp->hist[k]; for(l=0,kk=1; l<nlines; l++,kk+=8) { fprintf(fp,"%8d %-7s ",j+1,dp->states[istate-1]); for(n=kk; n<kk+8 && n<perip; n++) fprintf(fp,"%12.4E",dp->hist[k+n]); fprintf(fp,"\n"); } k += perip; } } } if(have_strain) { /* strain is easy -- for solids there are 6 words per element */ fprintf(fp,"\n\n\n e l e m e n t s t r a i n c a l c u l a t i o n s"); fprintf(fp," f o r t i m e s t e p%9d ( at time %12.5E )\n",cycle,time); fprintf(fp," element part ID (solid)\n"); fprintf(fp," strain-xx strain-yy strain-zz strain-xy strain-yz strain-zx\n"); for(i=0; i<length; i++) { j=6*i; fprintf(fp,"%8d-%7d\n",dp->ids[i],dp->mat[i]); fprintf(fp," average "); fprintf(fp,"%12.4E%12.4E%12.4E" ,dp->strain[j ],dp->strain[j+1],dp->strain[j+2]); fprintf(fp,"%12.4E%12.4E%12.4E\n",dp->strain[j+3],dp->strain[j+4],dp->strain[j+5]); } } return 1; } int elout_tshell_hist(FILE *fp,int handle, int state, MDHIST *dp) { char dirname[128]; float time; int cycle; int typid, filenum; LSDA_Length length,lhist,lstr,ldata; int num; int have_strain,have_hist,i,j,k,kk,l,n,nips,istate,perip,nlines; if(state<=999999) sprintf(dirname,"/elout/thickshell_hist/d%6.6d",state); else sprintf(dirname,"/elout/thickshell_hist/d%8.8d",state); lsda_queryvar(handle,dirname,&typid,&length,&filenum); if(typid != 0) return 0; lsda_cd(handle,dirname); lsda_queryvar(handle,"data",&typid,&ldata,&filenum); lsda_queryvar(handle,"hist",&typid,&lhist,&filenum); have_hist = (typid > 0); lsda_queryvar(handle,"strain",&typid,&lstr,&filenum); have_strain = (typid > 0); lsda_queryvar(handle,"ids",&typid,&length,&filenum); if(typid < 0) return 0; /* all elements deleted */ num=length; if(num > dp->idsize) { if(dp->ids) { free(dp->ids); free(dp->mat); free(dp->ndata); free(dp->data); free(dp->nhist); free(dp->hist); free(dp->strain); } dp->ids = (int *) malloc(num*sizeof(int)); dp->mat = (int *) malloc(num*sizeof(int)); dp->ndata = (int *) malloc(num*sizeof(int)); dp->data = (float *) malloc(ldata*sizeof(float)); if(have_hist) { dp->nhist = (int *) malloc(num*sizeof(int)); dp->hist = (float *) malloc(lhist*sizeof(float)); } else { dp->nhist = (int *) malloc(sizeof(int)); dp->hist = (float *) malloc(sizeof(float)); } if(have_strain) { dp->strain = (float *) malloc(lstr*sizeof(float)); } else { dp->strain = (float *) malloc(sizeof(float)); } } if(lsda_read(handle,LSDA_FLOAT,"time",0,1,&time) != 1) return 0; if(lsda_read(handle,LSDA_INT,"cycle",0,1,&cycle) != 1) return 0; if(lsda_read(handle,LSDA_INT,"nhv",0,1,&dp->nhv) != 1) return 0; if(lsda_read(handle,LSDA_INT,"ids",0,length,dp->ids) != length) return 0; if(lsda_read(handle,LSDA_INT,"mats",0,length,dp->mat) != length) return 0; if(lsda_read(handle,LSDA_INT,"ndata",0,length,dp->ndata) != length) return 0; if(lsda_read(handle,LSDA_FLOAT,"data",0,ldata,dp->data) != ldata) return 0; if(have_hist) { if(lsda_read(handle,LSDA_INT,"nhist",0,length,dp->nhist) != length) return 0; if(lsda_read(handle,LSDA_FLOAT,"hist",0,lhist,dp->hist) != lhist) return 0; } if(have_strain) { if(lsda_read(handle,LSDA_FLOAT,"strain",0,lstr,dp->strain) != lstr) return 0; } /* Output stress data */ fprintf(fp,"\n\n\n e l e m e n t s t r e s s c a l c u l a t i o n s"); fprintf(fp," f o r t i m e s t e p%9d ( at time %12.5E )\n",cycle,time); fprintf(fp," element part ID (thick shell)\n"); fprintf(fp," ipt stress stress-xx stress-yy stress"); fprintf(fp,"-zz stress-xy stress-yz stress-zx "); fprintf(fp," yield\n state "); fprintf(fp," "); fprintf(fp,"effsg function\n"); for(i=k=0; i<length; i++) { fprintf(fp,"%8d-%7d\n",dp->ids[i],dp->mat[i]); nips = dp->ndata[i]/9; for(j=0; j<nips; j++) { istate = dp->data[k]; fprintf(fp,"%8d %-7s ",j+1,dp->states[istate-1]); fprintf(fp,"%12.4E%12.4E%12.4E",dp->data[k+1],dp->data[k+2], dp->data[k+3]); fprintf(fp,"%12.4E%12.4E%12.4E%14.4E%14.4E\n",dp->data[k+4],dp->data[k+5], dp->data[k+6],dp->data[k+7],dp->data[k+8]); k=k+9; } } if(have_hist) { fprintf(fp,"\n\n\n e l e m e n t h i s t r y c a l c u l a t i o n s"); fprintf(fp," f o r t i m e s t e p%9d ( at time %12.5E )\n",cycle,time); fprintf(fp," element part ID (thick shell)\n"); fprintf(fp," ipt history 1 history 2 history 3 history 4"); fprintf(fp," history 5 history 6 history 7 history 8\n"); nlines = (dp->nhv-1)/8+1; for(i=k=0; i<length; i++) { fprintf(fp,"%8d-%7d\n",dp->ids[i],dp->mat[i]); nips = dp->ndata[i]/9; perip = dp->nhist[i]/nips; /* This part is a bit strange. The ascii routines print out nhv entries, 8 per line. But there may be fewer data values than that, in which case it just prints out blanks until nhv entries have been output */ for(j=0; j<nips; j++) { istate = dp->hist[k]; for(l=0,kk=1; l<nlines; l++,kk+=8) { fprintf(fp,"%8d %-7s ",j+1,dp->states[istate-1]); for(n=kk; n<kk+8 && n<perip; n++) fprintf(fp,"%12.4E",dp->hist[k+n]); fprintf(fp,"\n"); } k += perip; } } } if(have_strain) { /* strain is easy -- for solids there are 6 words per element */ fprintf(fp,"\n\n\n e l e m e n t s t r a i n c a l c u l a t i o n s"); fprintf(fp," f o r t i m e s t e p%9d ( at time %12.5E )\n",cycle,time); fprintf(fp," element part ID (thick shell)\n"); fprintf(fp," strain-xx strain-yy strain-zz strain-xy strain-yz strain-zx\n"); for(i=0; i<length; i++) { j=12*i; fprintf(fp,"%8d-%7d\n",dp->ids[i],dp->mat[i]); fprintf(fp," lower ipt "); fprintf(fp,"%12.4E%12.4E%12.4E" ,dp->strain[j ],dp->strain[j+1],dp->strain[j+2]); fprintf(fp,"%12.4E%12.4E%12.4E\n",dp->strain[j+3],dp->strain[j+4],dp->strain[j+5]); j += 6; fprintf(fp," upper ipt "); fprintf(fp,"%12.4E%12.4E%12.4E" ,dp->strain[j ],dp->strain[j+1],dp->strain[j+2]); fprintf(fp,"%12.4E%12.4E%12.4E\n",dp->strain[j+3],dp->strain[j+4],dp->strain[j+5]); } } return 1; } int elout_beam_hist(FILE *fp,int handle, int state, MDHIST *dp) { char dirname[128]; float time; int cycle; int typid, filenum; LSDA_Length length,lhist,lstr,ldata; int num; int have_strain,have_hist,i,j,k,kk,l,n,nips,istate,perip,nlines; if(state<=999999) sprintf(dirname,"/elout/beam_hist/d%6.6d",state); else sprintf(dirname,"/elout/beam_hist/d%8.8d",state); lsda_queryvar(handle,dirname,&typid,&length,&filenum); if(typid != 0) return 0; lsda_cd(handle,dirname); lsda_queryvar(handle,"data",&typid,&ldata,&filenum); lsda_queryvar(handle,"hist",&typid,&lhist,&filenum); have_hist = (typid > 0); lsda_queryvar(handle,"strain",&typid,&lstr,&filenum); have_strain = (typid > 0); lsda_queryvar(handle,"ids",&typid,&length,&filenum); if(typid < 0) return 0; /* all elements deleted */ num=length; if(num > dp->idsize) { if(dp->ids) { free(dp->ids); free(dp->mat); free(dp->ndata); free(dp->data); free(dp->nhist); free(dp->hist); free(dp->strain); } dp->ids = (int *) malloc(num*sizeof(int)); dp->mat = (int *) malloc(num*sizeof(int)); dp->ndata = (int *) malloc(num*sizeof(int)); dp->data = (float *) malloc(ldata*sizeof(float)); if(have_hist) { dp->nhist = (int *) malloc(num*sizeof(int)); dp->hist = (float *) malloc(lhist*sizeof(float)); } else { dp->nhist = (int *) malloc(sizeof(int)); dp->hist = (float *) malloc(sizeof(float)); } if(have_strain) { dp->strain = (float *) malloc(lstr*sizeof(float)); } else { dp->strain = (float *) malloc(sizeof(float)); } } if(lsda_read(handle,LSDA_FLOAT,"time",0,1,&time) != 1) return 0; if(lsda_read(handle,LSDA_INT,"cycle",0,1,&cycle) != 1) return 0; if(lsda_read(handle,LSDA_INT,"nhv",0,1,&dp->nhv) != 1) return 0; if(lsda_read(handle,LSDA_INT,"ids",0,length,dp->ids) != length) return 0; if(lsda_read(handle,LSDA_INT,"mats",0,length,dp->mat) != length) return 0; if(lsda_read(handle,LSDA_INT,"ndata",0,length,dp->ndata) != length) return 0; if(lsda_read(handle,LSDA_FLOAT,"data",0,ldata,dp->data) != ldata) return 0; if(have_hist) { if(lsda_read(handle,LSDA_INT,"nhist",0,length,dp->nhist) != length) return 0; if(lsda_read(handle,LSDA_FLOAT,"hist",0,lhist,dp->hist) != lhist) return 0; } if(have_strain) { if(lsda_read(handle,LSDA_FLOAT,"strain",0,lstr,dp->strain) != lstr) return 0; } /* Output stress data */ fprintf(fp,"\n\n\n e l e m e n t s t r e s s c a l c u l a t i o n s"); fprintf(fp," f o r t i m e s t e p%9d ( at time %12.5E )\n",cycle,time); fprintf(fp," element part ID (beam)\n"); fprintf(fp," ipt stress stress-xx stress-yy stress"); fprintf(fp,"-zz stress-xy stress-yz stress-zx "); fprintf(fp," yield\n state "); fprintf(fp," "); fprintf(fp,"effsg function\n"); for(i=k=0; i<length; i++) { fprintf(fp,"%8d-%7d\n",dp->ids[i],dp->mat[i]); nips = dp->ndata[i]/9; for(j=0; j<nips; j++) { istate = dp->data[k]; fprintf(fp,"%8d %-7s ",j+1,dp->states[istate-1]); fprintf(fp,"%12.4E%12.4E%12.4E",dp->data[k+1],dp->data[k+2], dp->data[k+3]); fprintf(fp,"%12.4E%12.4E%12.4E%14.4E%14.4E\n",dp->data[k+4],dp->data[k+5], dp->data[k+6],dp->data[k+7],dp->data[k+8]); k=k+9; } } if(have_hist) { fprintf(fp,"\n\n\n e l e m e n t h i s t r y c a l c u l a t i o n s"); fprintf(fp," f o r t i m e s t e p%9d ( at time %12.5E )\n",cycle,time); fprintf(fp," element part ID (beam)\n"); fprintf(fp," ipt history 1 history 2 history 3 history 4"); fprintf(fp," history 5 history 6 history 7 history 8\n"); nlines = (dp->nhv-1)/8+1; for(i=k=0; i<length; i++) { fprintf(fp,"%8d-%7d\n",dp->ids[i],dp->mat[i]); nips = dp->ndata[i]/9; perip = dp->nhist[i]/nips; /* This part is a bit strange. The ascii routines print out nhv entries, 8 per line. But there may be fewer data values than that, in which case it just prints out blanks until nhv entries have been output */ for(j=0; j<nips; j++) { istate = dp->hist[k]; for(l=0,kk=1; l<nlines; l++,kk+=8) { fprintf(fp,"%8d %-7s ",j+1,dp->states[istate-1]); for(n=kk; n<kk+8 && n<perip; n++) fprintf(fp,"%12.4E",dp->hist[k+n]); fprintf(fp,"\n"); } k += perip; } } } if(have_strain) { /* strain is easy -- for solids there are 6 words per element */ fprintf(fp,"\n\n\n e l e m e n t s t r e s s r e s u l t a n t s "); fprintf(fp," f o r t i m e s t e p%9d ( at time %12.5E )\n",cycle,time); fprintf(fp," element part ID (beam)\n"); fprintf(fp," axial shear-s shear-t moment-s moment-t torsion\n"); for(i=0; i<length; i++) { j=6*i; fprintf(fp,"%8d-%7d\n",dp->ids[i],dp->mat[i]); fprintf(fp," resultants "); fprintf(fp,"%12.4E%12.4E%12.4E" ,dp->strain[j ],dp->strain[j+1],dp->strain[j+2]); fprintf(fp,"%12.4E%12.4E%12.4E\n",dp->strain[j+3],dp->strain[j+4],dp->strain[j+5]); } } return 1; } int elout_shell_hist(FILE *fp,int handle, int state, MDHIST *dp) { char dirname[128]; float time; int cycle; int typid, filenum; LSDA_Length length,lhist,lstr,ldata; int num; int have_strain,have_hist,i,j,k,kk,l,n,nips,istate,perip,nlines; if(state<=999999) sprintf(dirname,"/elout/shell_hist/d%6.6d",state); else sprintf(dirname,"/elout/shell_hist/d%8.8d",state); lsda_queryvar(handle,dirname,&typid,&length,&filenum); if(typid != 0) return 0; lsda_cd(handle,dirname); lsda_queryvar(handle,"data",&typid,&ldata,&filenum); lsda_queryvar(handle,"hist",&typid,&lhist,&filenum); have_hist = (typid > 0); lsda_queryvar(handle,"strain",&typid,&lstr,&filenum); have_strain = (typid > 0); lsda_queryvar(handle,"ids",&typid,&length,&filenum); if(typid < 0) return 0; /* all elements deleted */ num=length; if(num > dp->idsize) { if(dp->ids) { free(dp->ids); free(dp->mat); free(dp->ndata); free(dp->data); free(dp->nhist); free(dp->hist); free(dp->strain); } dp->ids = (int *) malloc(num*sizeof(int)); dp->mat = (int *) malloc(num*sizeof(int)); dp->ndata = (int *) malloc(num*sizeof(int)); dp->data = (float *) malloc(ldata*sizeof(float)); if(have_hist) { dp->nhist = (int *) malloc(num*sizeof(int)); dp->hist = (float *) malloc(lhist*sizeof(float)); } else { dp->nhist = (int *) malloc(sizeof(int)); dp->hist = (float *) malloc(sizeof(float)); } if(have_strain) { dp->strain = (float *) malloc(lstr*sizeof(float)); } else { dp->strain = (float *) malloc(sizeof(float)); } } if(lsda_read(handle,LSDA_FLOAT,"time",0,1,&time) != 1) return 0; if(lsda_read(handle,LSDA_INT,"cycle",0,1,&cycle) != 1) return 0; if(lsda_read(handle,LSDA_INT,"nhv",0,1,&dp->nhv) != 1) return 0; if(lsda_read(handle,LSDA_INT,"ids",0,length,dp->ids) != length) return 0; if(lsda_read(handle,LSDA_INT,"mats",0,length,dp->mat) != length) return 0; if(lsda_read(handle,LSDA_INT,"ndata",0,length,dp->ndata) != length) return 0; if(lsda_read(handle,LSDA_FLOAT,"data",0,ldata,dp->data) != ldata) return 0; if(have_hist) { if(lsda_read(handle,LSDA_INT,"nhist",0,length,dp->nhist) != length) return 0; if(lsda_read(handle,LSDA_FLOAT,"hist",0,lhist,dp->hist) != lhist) return 0; } if(have_strain) { if(lsda_read(handle,LSDA_FLOAT,"strain",0,lstr,dp->strain) != lstr) return 0; } /* Output stress data */ fprintf(fp,"\n\n\n e l e m e n t s t r e s s c a l c u l a t i o n s"); fprintf(fp," f o r t i m e s t e p%9d ( at time %12.5E )\n",cycle,time); fprintf(fp," element part ID (shell)\n"); fprintf(fp," ipt stress stress-xx stress-yy stress"); fprintf(fp,"-zz stress-xy stress-yz stress-zx "); fprintf(fp," yield\n state "); fprintf(fp," "); fprintf(fp,"effsg function\n"); for(i=k=0; i<length; i++) { fprintf(fp,"%8d-%7d\n",dp->ids[i],dp->mat[i]); nips = dp->ndata[i]/9; for(j=0; j<nips; j++) { istate = dp->data[k]; fprintf(fp,"%8d %-7s ",j+1,dp->states[istate-1]); fprintf(fp,"%12.4E%12.4E%12.4E",dp->data[k+1],dp->data[k+2], dp->data[k+3]); fprintf(fp,"%12.4E%12.4E%12.4E%14.4E%14.4E\n",dp->data[k+4],dp->data[k+5], dp->data[k+6],dp->data[k+7],dp->data[k+8]); k=k+9; } } if(have_hist) { fprintf(fp,"\n\n\n e l e m e n t h i s t r y c a l c u l a t i o n s"); fprintf(fp," f o r t i m e s t e p%9d ( at time %12.5E )\n",cycle,time); fprintf(fp," element part ID (shell)\n"); fprintf(fp," ipt history 1 history 2 history 3 history 4"); fprintf(fp," history 5 history 6 history 7 history 8\n"); nlines = (dp->nhv-1)/8+1; for(i=k=0; i<length; i++) { fprintf(fp,"%8d-%7d\n",dp->ids[i],dp->mat[i]); nips = dp->ndata[i]/9; perip = dp->nhist[i]/nips; /* This part is a bit strange. The ascii routines print out nhv entries, 8 per line. But there may be fewer data values than that, in which case it just prints out blanks until nhv entries have been output */ for(j=0; j<nips; j++) { istate = dp->hist[k]; for(l=0,kk=1; l<nlines; l++,kk+=8) { fprintf(fp,"%8d %-7s ",j+1,dp->states[istate-1]); for(n=kk; n<kk+8 && n<perip; n++) fprintf(fp,"%12.4E",dp->hist[k+n]); fprintf(fp,"\n"); } k += perip; } } } if(have_strain) { /* strain is easy -- for solids there are 6 words per element */ fprintf(fp,"\n\n\n e l e m e n t s t r a i n c a l c u l a t i o n s"); fprintf(fp," f o r t i m e s t e p%9d ( at time %12.5E )\n",cycle,time); fprintf(fp," element part ID (shell)\n"); fprintf(fp," strain-xx strain-yy strain-zz strain-xy strain-yz strain-zx\n"); for(i=0; i<length; i++) { j=12*i; fprintf(fp,"%8d-%7d\n",dp->ids[i],dp->mat[i]); fprintf(fp," lower ipt "); fprintf(fp,"%12.4E%12.4E%12.4E" ,dp->strain[j ],dp->strain[j+1],dp->strain[j+2]); fprintf(fp,"%12.4E%12.4E%12.4E\n",dp->strain[j+3],dp->strain[j+4],dp->strain[j+5]); j += 6; fprintf(fp," upper ipt "); fprintf(fp,"%12.4E%12.4E%12.4E" ,dp->strain[j ],dp->strain[j+1],dp->strain[j+2]); fprintf(fp,"%12.4E%12.4E%12.4E\n",dp->strain[j+3],dp->strain[j+4],dp->strain[j+5]); } } return 1; } /* GLSTAT file */ int translate_glstat(int handle) { int i,j,k,typid,filenum,state,part; LSDA_Length length; char dirname[640]; char types[40][16]; int cycle; float *swe; int nsw; float x; FILE *fp; LSDADir *dp = NULL; if (lsda_cd(handle,"/glstat/metadata") == -1) return 0; printf("Extracting GLSTAT data\n"); /* Read metadata */ lsda_queryvar(handle,"element_types",&typid,&length,&filenum); lsda_read(handle,LSDA_I1,"element_types",0,length,dirname); /* parse dirname to split out the element types zero all pointers first to prevent garbage output */ for(i=0; i<40; i++) types[i][0]=0; for(i=j=k=0; i<length; i++) { if(dirname[i] == ',') { types[j][k]=0; j++; k=0; } else { types[j][k++]=dirname[i]; } } types[j][k]=0; /* see if we have any stonewall energies, and if so allocate space for them */ lsda_queryvar(handle,"../d000001/stonewall_energy",&typid,&length,&filenum); if(typid > 0) { nsw = length; swe = (float *) malloc(nsw*sizeof(float)); } else { nsw = -1; } /* open file and write header */ sprintf(output_file,"%sglstat",output_path); fp=fopen(output_file,"w"); write_message(fp,output_file); if (!fp) return 0; output_title(handle,"/glstat/metadata",fp); /* Loop through time states and write each one */ for(state=1; (dp = next_dir(handle,"/glstat",dp,dirname)) != NULL; state++) { if(lsda_read(handle,LSDA_INT,"cycle",0,1,&cycle) != 1) break; if(lsda_read(handle,LSDA_INT,"ts_eltype",0,1,&i) != 1) { /* older codes didn't write ts_eltype if there was a loadcurve */ fprintf(fp,"\n\n dt of cycle%8d is controlled by load curve\n\n",cycle); } else { if(lsda_read(handle,LSDA_INT,"ts_element",0,1,&j) != 1) break; part=0; /* newer codes always write ts_part, some didn't but we'll just ignore the error and part will be 0 which is fine */ lsda_read(handle,LSDA_INT,"ts_part",0,1,&part); if(i == 14 || i == 19) { fprintf(fp,"\n\n dt of cycle%8d is controlled by %s\n",cycle,types[i-1]); } else if(part == 0) { fprintf(fp,"\n\n dt of cycle%8d is controlled by %s%10d\n", cycle,types[i-1],j); } else { fprintf(fp,"\n\n dt of cycle%8d is controlled by %s%10d of part%10d\n", cycle,types[i-1],j,part); } } if(lsda_read(handle,LSDA_FLOAT,"time",0,1,&x) != 1) break; fprintf(fp," time...........................%14.5E\n",x); if(lsda_read(handle,LSDA_FLOAT,"time_step",0,1,&x) != 1) break; fprintf(fp," time step......................%14.5E\n",x); if(lsda_read(handle,LSDA_FLOAT,"kinetic_energy",0,1,&x) != 1) break; fprintf(fp," kinetic energy.................%14.5E\n",x); if(lsda_read(handle,LSDA_FLOAT,"internal_energy",0,1,&x) != 1) break; fprintf(fp," internal energy................%14.5E\n",x); if(nsw > 0) { if(lsda_read(handle,LSDA_FLOAT,"stonewall_energy",0,nsw,swe) != nsw) break; for(i=0; i<nsw; i++) fprintf(fp," stonewall energy...............%14.5E wall#%2d\n",swe[i],i+1); } if(lsda_read(handle,LSDA_FLOAT,"rb_stopper_energy",0,1,&x) == 1) fprintf(fp," rigid body stopper energy......%14.5E\n",x); if(lsda_read(handle,LSDA_FLOAT,"spring_and_damper_energy",0,1,&x) == 1) fprintf(fp," spring and damper energy.......%14.5E\n",x); if(lsda_read(handle,LSDA_FLOAT,"joint_internal_energy",0,1,&x) == 1) fprintf(fp," joint internal energy..........%14.5E\n",x); if(lsda_read(handle,LSDA_FLOAT,"hourglass_energy",0,1,&x) == 1) fprintf(fp," hourglass energy ..............%14.5E\n",x); if(lsda_read(handle,LSDA_FLOAT,"system_damping_energy",0,1,&x) != 1) break; fprintf(fp," system damping energy..........%14.5E\n",x); if(lsda_read(handle,LSDA_FLOAT,"sliding_interface_energy",0,1,&x) != 1) break; fprintf(fp," sliding interface energy.......%14.5E\n",x); if(lsda_read(handle,LSDA_FLOAT,"external_work",0,1,&x) != 1) break; fprintf(fp," external work..................%14.5E\n",x); if(lsda_read(handle,LSDA_FLOAT,"eroded_kinetic_energy",0,1,&x) == 1) fprintf(fp," eroded kinetic energy..........%14.5E\n",x); if(lsda_read(handle,LSDA_FLOAT,"eroded_internal_energy",0,1,&x) == 1) fprintf(fp," eroded internal energy.........%14.5E\n",x); if(lsda_read(handle,LSDA_FLOAT,"eroded_hourglass_energy",0,1,&x) == 1) fprintf(fp," eroded hourglass energy........%14.5E\n",x); if(lsda_read(handle,LSDA_FLOAT,"total_energy",0,1,&x) != 1) break; fprintf(fp," total energy...................%14.5E\n",x); if(lsda_read(handle,LSDA_FLOAT,"energy_ratio",0,1,&x) != 1) break; fprintf(fp," total energy / initial energy..%14.5E\n",x); if(lsda_read(handle,LSDA_FLOAT,"energy_ratio_wo_eroded",0,1,&x) == 1) fprintf(fp," energy ratio w/o eroded energy.%14.5E\n",x); if(lsda_read(handle,LSDA_FLOAT,"global_x_velocity",0,1,&x) != 1) break; fprintf(fp," global x velocity..............%14.5E\n",x); if(lsda_read(handle,LSDA_FLOAT,"global_y_velocity",0,1,&x) != 1) break; fprintf(fp," global y velocity..............%14.5E\n",x); if(lsda_read(handle,LSDA_FLOAT,"global_z_velocity",0,1,&x) != 1) break; fprintf(fp," global z velocity..............%14.5E\n",x); if(lsda_read(handle,LSDA_INT,"number_of_nodes",0,1,&i) == 1) { fprintf(fp," number of nodes................%14d\n",i); } if(lsda_read(handle,LSDA_INT,"number_of_elements",0,1,&i) == 1) { fprintf(fp," number of elements.............%14d\n",i); } if(lsda_read(handle,LSDA_INT,"nzc",0,1,&i) != 1) break; fprintf(fp," time per zone cycle.(nanosec)..%14d\n",i); if(lsda_read(handle,LSDA_INT,"num_bad_shells",0,1,&i) == 1) { fprintf(fp,"\n\n number of shell elements that \n"); fprintf(fp," reached the minimum time step..%5d\n",i); } if(lsda_read(handle,LSDA_FLOAT,"added_mass",0,1,&x) == 1) fprintf(fp,"\n\n added mass.....................%14.5E\n",x); if(lsda_read(handle,LSDA_FLOAT,"percent_increase",0,1,&x) == 1) fprintf(fp," percentage increase............%14.5E\n",x); /* Check for optional output of system RB properties */ if(lsda_read(handle,LSDA_FLOAT,"total_mass",0,1,&x) == 1) { float t[9]; fprintf(fp,"\n m a s s p r o p e r t i e s o f b o d y\n"); fprintf(fp," total mass of body =%15.8E\n",x); if(lsda_read(handle,LSDA_FLOAT,"x_mass_center",0,1,&x) != 1) break; fprintf(fp," x-coordinate of mass center =%15.8E\n",x); if(lsda_read(handle,LSDA_FLOAT,"y_mass_center",0,1,&x) != 1) break; fprintf(fp," y-coordinate of mass center =%15.8E\n",x); if(lsda_read(handle,LSDA_FLOAT,"z_mass_center",0,1,&x) != 1) break; fprintf(fp," z-coordinate of mass center =%15.8E\n\n",x); if(lsda_read(handle,LSDA_FLOAT,"inertia_tensor",0,9,&t) != 9) break; fprintf(fp," inertia tensor of body\n"); fprintf(fp," row1=%15.4E%15.4E%15.4E\n",t[0],t[1],t[2]); fprintf(fp," row2=%15.4E%15.4E%15.4E\n",t[3],t[4],t[5]); fprintf(fp," row3=%15.4E%15.4E%15.4E\n\n\n",t[6],t[7],t[8]); if(lsda_read(handle,LSDA_FLOAT,"principal_inertias",0,3,&t) != 3) break; fprintf(fp,"\n principal inertias of body\n"); fprintf(fp," i11 =%15.4E\n",t[0]); fprintf(fp," i22 =%15.4E\n",t[1]); fprintf(fp," i33 =%15.4E\n\n",t[2]); if(lsda_read(handle,LSDA_FLOAT,"principal_directions",0,9,&t) != 9) break; fprintf(fp," principal directions\n"); fprintf(fp," row1=%15.4E%15.4E%15.4E\n",t[0],t[1],t[2]); fprintf(fp," row2=%15.4E%15.4E%15.4E\n",t[3],t[4],t[5]); fprintf(fp," row3=%15.4E%15.4E%15.4E\n",t[6],t[7],t[8]); fprintf(fp,"\n ************************************************************\n\n"); } } fclose(fp); if(nsw > 0) free(swe); printf(" %d states extracted\n",state-1); return 0; } /* SSSTAT file */ int translate_ssstat(int handle) { int i,j,k,typid,num,filenum,state; LSDA_Length length; char dirname[256],dname[32]; char types[20][32]; char elnam[10]; int nintcy,ityptc,ielprt,ipartc; int *systems; int *ids; int cycle,sub_system; float keg, ieg, heg, time, time_step; float *ke, *ie, *he, *xm, *ym, *zm, *ker, *ier; float *system_inertia; FILE *fp; LSDADir *dp = NULL; lsda_cd(handle,"/glstat/metadata"); printf("Extracting SSSTAT data\n"); /* Read metadata */ lsda_queryvar(handle,"element_types",&typid,&length,&filenum); lsda_read(handle,LSDA_I1,"element_types",0,length,dirname); /* parse dirname to split out the element types */ for(i=j=k=0; i<length; i++) { if(dirname[i] == ',') { types[j][k]=0; j++; k=0; } else { types[j][k++]=dirname[i]; } } types[j][k]=0; /* Now data from ssstat */ lsda_cd(handle,"/ssstat/metadata"); lsda_queryvar(handle,"systems",&typid,&length,&filenum); num = length; systems = (int *) malloc(num*sizeof(int)); ke = (float *) malloc(num*sizeof(float)); ie = (float *) malloc(num*sizeof(float)); he = (float *) malloc(num*sizeof(float)); xm = (float *) malloc(num*sizeof(float)); ym = (float *) malloc(num*sizeof(float)); zm = (float *) malloc(num*sizeof(float)); ker = (float *) malloc(num*sizeof(float)); ier = (float *) malloc(num*sizeof(float)); system_inertia = (float *) malloc(25*num*sizeof(float)); lsda_read(handle,LSDA_INT,"systems",0,num,systems); lsda_queryvar(handle,"ids",&typid,&length,&filenum); ids = (int *) malloc(length*sizeof(int)); lsda_read(handle,LSDA_INT,"ids",0,length,ids); /* open file and write header */ sprintf(output_file,"%sssstat",output_path); fp=fopen(output_file,"w"); write_message(fp,output_file); if (!fp) return 0; output_title(handle,"/ssstat/metadata",fp); /* susbsystem info */ for(i=j=0; i<num; i++) { fprintf(fp,"\n\n subsystem definition ID=%12d part ID list:\n",i+1); for(k=0; k<systems[i]; k++) { fprintf(fp,"%10d",ids[j++]); if((k+1)%8 == 0) fprintf(fp,"\n"); } if(k%8 != 0) fprintf(fp,"\n"); } free(ids); /* Loop through time states and write each one. */ for(state=1; (dp = next_dir(handle,"/ssstat",dp,dname)) != NULL; state++) { /* First get the subsystem data */ sub_system=num; if(lsda_read(handle,LSDA_INT,"ncycle",0,1,&nintcy) != 1) break; if(lsda_read(handle,LSDA_INT,"elmtyp",0,1,&ityptc) != 1) break; if(lsda_read(handle,LSDA_INT,"elemid",0,1,&ielprt) != 1) break; if(lsda_read(handle,LSDA_INT,"partid",0,1,&ipartc) != 1) break; if(lsda_read(handle,LSDA_FLOAT,"time",0,1,&time) != 1) break; if(lsda_read(handle,LSDA_FLOAT,"time_step",0,1,&time_step) != 1) break; if(lsda_read(handle,LSDA_FLOAT,"kin_energy_g",0,1,&keg) != 1) break; if(lsda_read(handle,LSDA_FLOAT,"int_energy_g",0,1,&ieg) != 1) break; if(lsda_read(handle,LSDA_FLOAT,"hgl_energy_g",0,1,&heg) != 1) heg = 0.; if(lsda_read(handle,LSDA_FLOAT,"kinetic_energy",0,num,ke) != num) break; if(lsda_read(handle,LSDA_FLOAT,"internal_energy",0,num,ie) != num) break; if(lsda_read(handle,LSDA_FLOAT,"hourglass_energy",0,num,he) != num) break; if(lsda_read(handle,LSDA_FLOAT,"x_momentum",0,num,xm) != num) break; if(lsda_read(handle,LSDA_FLOAT,"y_momentum",0,num,ym) != num) break; if(lsda_read(handle,LSDA_FLOAT,"z_momentum",0,num,zm) != num) break; if(lsda_read(handle,LSDA_FLOAT,"kinetic_energy_ratios",0,num,ker) != num) break; if(lsda_read(handle,LSDA_FLOAT,"internal_energy_ratios",0,num,ier) != num) break; if(lsda_read(handle,LSDA_FLOAT,"subsystem_inertia_info",0,25*num,system_inertia) != 25*num) sub_system=0; /* Now get the necessary global data from the glstat directory. */ strcpy(elnam," "); if(ityptc == 2) strcpy(elnam,"solid"); if(ityptc == 3) strcpy(elnam,"beam"); if(ityptc == 4) strcpy(elnam,"shell"); if(ityptc == 5) strcpy(elnam,"thk shell"); fprintf(fp,"\n\n dt of cycle %8d is controlled by %s %10d of part %10d\n",nintcy,&elnam,ielprt,ipartc); fprintf(fp,"\n time........................ %14.5E\n",time); fprintf(fp," time step................... %14.5E\n",time_step); fprintf(fp," kinetic energy global....... %14.5E\n",keg); fprintf(fp," kinetic energy subsystems .."); for(i=0; i<num; i++) { if(i>0 && i%3 == 0) fprintf(fp," "); fprintf(fp,"%3d.%13.5E",i+1,ke[i]); if((i+1)%3 == 0) fprintf(fp,"\n"); } if(num%3 != 0) fprintf(fp,"\n"); fprintf(fp," internal energy global...... %14.5E\n",ieg); fprintf(fp," internal energy subsystems ."); for(i=0; i<num; i++) { if(i>0 && i%3 == 0) fprintf(fp," "); fprintf(fp,"%3d.%13.5E",i+1,ie[i]); if((i+1)%3 == 0) fprintf(fp,"\n"); } if(num%3 != 0) fprintf(fp,"\n"); fprintf(fp," hourglass energy global .... %14.5E\n",heg); fprintf(fp," hourglass energy subsystems "); for(i=0; i<num; i++) { if(i>0 && i%3 == 0) fprintf(fp," "); fprintf(fp,"%3d.%13.5E",i+1,he[i]); if((i+1)%3 == 0) fprintf(fp,"\n"); } if(num%3 != 0) fprintf(fp,"\n"); fprintf(fp," kinetic energy ratios ......"); for(i=0; i<num; i++) { if(i>0 && i%3 == 0) fprintf(fp," "); fprintf(fp,"%3d.%13.5E",i+1,ker[i]); if((i+1)%3 == 0) fprintf(fp,"\n"); } if(num%3 != 0) fprintf(fp,"\n"); fprintf(fp," internal energy ratios ....."); for(i=0; i<num; i++) { if(i>0 && i%3 == 0) fprintf(fp," "); fprintf(fp,"%3d.%13.5E",i+1,ier[i]); if((i+1)%3 == 0) fprintf(fp,"\n"); } if(num%3 != 0) fprintf(fp,"\n"); fprintf(fp," x-momentum subsystems ......"); for(i=0; i<num; i++) { if(i>0 && i%3 == 0) fprintf(fp," "); fprintf(fp,"%3d.%13.5E",i+1,xm[i]); if((i+1)%3 == 0) fprintf(fp,"\n"); } if(num%3 != 0) fprintf(fp,"\n"); fprintf(fp," y-momentum subsystems ......"); for(i=0; i<num; i++) { if(i>0 && i%3 == 0) fprintf(fp," "); fprintf(fp,"%3d.%13.5E",i+1,ym[i]); if((i+1)%3 == 0) fprintf(fp,"\n"); } if(num%3 != 0) fprintf(fp,"\n"); fprintf(fp," z-momentum subsystems ......"); for(i=0; i<num; i++) { if(i>0 && i%3 == 0) fprintf(fp," "); fprintf(fp,"%3d.%13.5E",i+1,zm[i]); if((i+1)%3 == 0) fprintf(fp,"\n"); } if(num%3 != 0) fprintf(fp,"\n"); for(i=0; i<sub_system; i++) { k = 25*i; fprintf(fp,"\n\n subsystem:%5d\n\n",i+1); fprintf(fp," total mass of subsystem =%15.8E\n",system_inertia[k ]); fprintf(fp," x-coordinate of mass center =%15.8E\n",system_inertia[k+1]); fprintf(fp," y-coordinate of mass center =%15.8E\n",system_inertia[k+2]); fprintf(fp," z-coordinate of mass center =%15.8E\n",system_inertia[k+3]); fprintf(fp,"\n inertia tensor in global coordinates\n"); fprintf(fp," row1=%15.4E%15.4E%15.4E\n",system_inertia[k+ 4],system_inertia[k+ 5],system_inertia[k+ 6]); fprintf(fp," row2=%15.4E%15.4E%15.4E\n",system_inertia[k+ 7],system_inertia[k+ 8],system_inertia[k+ 9]); fprintf(fp," row3=%15.4E%15.4E%15.4E\n",system_inertia[k+10],system_inertia[k+11],system_inertia[k+12]); fprintf(fp,"\n principal inertias\n"); fprintf(fp," i11 =%14.4E\n",system_inertia[k+13]); fprintf(fp," i22 =%14.4E\n",system_inertia[k+14]); fprintf(fp," i33 =%14.4E\n",system_inertia[k+15]); fprintf(fp,"\n principal directions\n"); fprintf(fp," row1=%15.4E%15.4E%15.4E\n",system_inertia[k+16],system_inertia[k+17],system_inertia[k+18]); fprintf(fp," row2=%15.4E%15.4E%15.4E\n",system_inertia[k+19],system_inertia[k+20],system_inertia[k+21]); fprintf(fp," row3=%15.4E%15.4E%15.4E\n",system_inertia[k+22],system_inertia[k+23],system_inertia[k+24]); } } fclose(fp); free(system_inertia); free(ier); free(ker); free(zm); free(ym); free(xm); free(he); free(ie); free(ke); free(systems); printf(" %d states extracted\n",state-1); return 0; } /* DEFORC file */ int translate_deforc(int handle) { int i,typid,num,filenum,state; LSDA_Length length; char dirname[256]; int *ids, *irot; float *fx,*fy,*fz,*rf,*disp; float time; FILE *fp; LSDADir *dp = NULL; if (lsda_cd(handle,"/deforc/metadata") == -1) return 0; printf("Extracting DEFORC data\n"); /* Read metadata */ lsda_queryvar(handle,"ids",&typid,&length,&filenum); num = length; ids = (int *) malloc(num*sizeof(int)); irot = (int *) malloc(num*sizeof(int)); fx = (float *) malloc(num*sizeof(float)); fy = (float *) malloc(num*sizeof(float)); fz = (float *) malloc(num*sizeof(float)); rf = (float *) malloc(num*sizeof(float)); disp = (float *) malloc(num*sizeof(float)); lsda_read(handle,LSDA_INT,"ids",0,num,ids); lsda_read(handle,LSDA_INT,"irot",0,num,irot); /* open file and write header */ sprintf(output_file,"%sdeforc",output_path); fp=fopen(output_file,"w"); write_message(fp,output_file); if (!fp) return 0; output_title(handle,"/deforc/metadata",fp); output_legend(handle,fp,1,1); /* Loop through time states and write each one. */ for(state=1; (dp = next_dir(handle,"/deforc",dp,dirname)) != NULL; state++) { if(lsda_read(handle,LSDA_FLOAT,"time",0,1,&time) != 1) break; if(lsda_read(handle,LSDA_FLOAT,"x_force",0,num,fx) != num) break; if(lsda_read(handle,LSDA_FLOAT,"y_force",0,num,fy) != num) break; if(lsda_read(handle,LSDA_FLOAT,"z_force",0,num,fz) != num) break; if(lsda_read(handle,LSDA_FLOAT,"resultant_force",0,num,rf) != num) break; if(lsda_read(handle,LSDA_FLOAT,"displacement",0,num,disp) != num) break; fprintf(fp,"\n time.........................%14.5E\n",time); for(i=0; i<num; i++) { fprintf(fp," spring/damper number.........%10d\n",ids[i]); if(irot[i] == 0) { fprintf(fp," x-force......................%14.5E\n",fx[i]); fprintf(fp," y-force......................%14.5E\n",fy[i]); fprintf(fp," z-force......................%14.5E\n",fz[i]); fprintf(fp," resultant force..............%14.5E\n",rf[i]); fprintf(fp," change in length.............%14.5E\n",disp[i]); } else { fprintf(fp," x-moment.....................%14.5E\n",fx[i]); fprintf(fp," y-moment.....................%14.5E\n",fy[i]); fprintf(fp," z-moment.....................%14.5E\n",fz[i]); fprintf(fp," resultant moment.............%14.5E\n",rf[i]); fprintf(fp," relative rotation............%14.5E\n",disp[i]); } } } fclose(fp); free(disp); free(rf); free(fz); free(fy); free(fx); free(irot); free(ids); printf(" %d states extracted\n",state-1); return 0; } /* MATSUM file */ int translate_matsum(int handle) { int i,typid,num,filenum,state; int have_mass, have_he, have_eroded; LSDA_Length length; char dirname[256]; int *ids; float *ke, *ie, *he, *mass, *xm, *ym, *zm, *xrbv, *yrbv, *zrbv; float *eke, *eie; float mm,time,x; int mid; FILE *fp; LSDADir *dp = NULL; if (lsda_cd(handle,"/matsum/metadata") == -1) return 0; printf("Extracting MATSUM data\n"); /* Read metadata */ lsda_queryvar(handle,"ids",&typid,&length,&filenum); num = length; ids = (int *) malloc(num*sizeof(int)); ie = (float *) malloc(num*sizeof(float)); ke = (float *) malloc(num*sizeof(float)); eie = (float *) malloc(num*sizeof(float)); eke = (float *) malloc(num*sizeof(float)); mass = (float *) malloc(num*sizeof(float)); xm = (float *) malloc(num*sizeof(float)); ym = (float *) malloc(num*sizeof(float)); zm = (float *) malloc(num*sizeof(float)); xrbv = (float *) malloc(num*sizeof(float)); yrbv = (float *) malloc(num*sizeof(float)); zrbv = (float *) malloc(num*sizeof(float)); he = (float *) malloc(num*sizeof(float)); lsda_read(handle,LSDA_INT,"ids",0,num,ids); /* open file and write header */ sprintf(output_file,"%smatsum",output_path); fp=fopen(output_file,"w"); write_message(fp,output_file); if (!fp) return 0; output_title(handle,"/matsum/metadata",fp); output_legend(handle,fp,1,1); /* Loop through time states and write each one. */ for(state=1; (dp = next_dir(handle,"/matsum",dp,dirname)) != NULL; state++) { if(lsda_read(handle,LSDA_FLOAT,"time",0,1,&time) != 1) break; if(lsda_read(handle,LSDA_FLOAT,"internal_energy",0,num,ie) != num) break; if(lsda_read(handle,LSDA_FLOAT,"kinetic_energy",0,num,ke) != num) break; lsda_queryvar(handle,"eroded_internal_energy",&have_eroded,&length,&filenum); if(have_eroded > 0) { if(lsda_read(handle,LSDA_FLOAT,"eroded_internal_energy",0,num,eie) != num) break; if(lsda_read(handle,LSDA_FLOAT,"eroded_kinetic_energy",0,num,eke) != num) break; } lsda_queryvar(handle,"mass",&have_mass,&length,&filenum); if(have_mass > 0) if(lsda_read(handle,LSDA_FLOAT,"mass",0,num,mass) != num) break; lsda_queryvar(handle,"hourglass_energy",&have_he,&length,&filenum); if(have_he > 0) if(lsda_read(handle,LSDA_FLOAT,"hourglass_energy",0,num,he) != num) break; if(lsda_read(handle,LSDA_FLOAT,"x_momentum",0,num,xm) != num) break; if(lsda_read(handle,LSDA_FLOAT,"y_momentum",0,num,ym) != num) break; if(lsda_read(handle,LSDA_FLOAT,"z_momentum",0,num,zm) != num) break; if(lsda_read(handle,LSDA_FLOAT,"x_rbvelocity",0,num,xrbv) != num) break; if(lsda_read(handle,LSDA_FLOAT,"y_rbvelocity",0,num,yrbv) != num) break; if(lsda_read(handle,LSDA_FLOAT,"z_rbvelocity",0,num,zrbv) != num) break; fprintf(fp,"\n\n time =%13.4E\n",time); /* This is an...."interesting" bit of a hack. The kinetic energies of lumped masses can optionally be output, in which case they are supposed to show up in the ascii matsum file as material 0....ugh. */ if(lsda_read(handle,LSDA_FLOAT,"lumped_kinetic_energy",0,1,&x) == 1) { fprintf(fp," mat.#=%5d ",0); fprintf(fp," inten=%13.4E kinen=%13.4E",0.0,x); fprintf(fp," eroded_ie=%13.4E eroded_ke=%13.4E\n",0.0,0.0); } for(i=0; i<num; i++) { if(ids[i] < 100000 ) fprintf(fp," mat.#=%5d ",ids[i]); else fprintf(fp," mat.#=%8d",ids[i]); fprintf(fp," inten=%13.4E kinen=%13.4E",ie[i],ke[i]); if(have_eroded>0) fprintf(fp," eroded_ie=%13.4E eroded_ke=%13.4E",eie[i],eke[i]); fprintf(fp,"\n"); fprintf(fp," x-mom=%13.4E y-mom=%13.4E z-mom=%13.4E\n", xm[i],ym[i],zm[i]); fprintf(fp," x-rbv=%13.4E y-rbv=%13.4E z-rbv=%13.4E\n", xrbv[i],yrbv[i],zrbv[i]); if(have_he>0) { fprintf(fp," hgeng=%13.4E ",he[i]); if(have_mass>0) fprintf(fp,"+mass=%13.4E\n",mass[i]); else fprintf(fp,"\n"); fprintf(fp,"\n\n"); } else if(have_mass>0) { fprintf(fp," "); fprintf(fp,"+mass=%13.4E\n",mass[i]); } } lsda_queryvar(handle,"brick_id",&typid,&length,&filenum); if(typid > 0) { lsda_read(handle,LSDA_FLOAT,"max_brick_mass",0,1,&mm); lsda_read(handle,LSDA_INT,"brick_id",0,1,&mid); fprintf(fp,"\n\n Maximum mass increase in brick elements ="); fprintf(fp,"%13.4E ID=%8d\n",mm,mid); } lsda_queryvar(handle,"beam_id",&typid,&length,&filenum); if(typid > 0) { lsda_read(handle,LSDA_FLOAT,"max_beam_mass",0,1,&mm); lsda_read(handle,LSDA_INT,"beam_id",0,1,&mid); fprintf(fp,"\n\n Maximum mass increase in beam elements ="); fprintf(fp,"%13.4E ID=%8d\n",mm,mid); } lsda_queryvar(handle,"shell_id",&typid,&length,&filenum); if(typid > 0) { lsda_read(handle,LSDA_FLOAT,"max_shell_mass",0,1,&mm); lsda_read(handle,LSDA_INT,"shell_id",0,1,&mid); fprintf(fp,"\n\n Maximum mass increase in shell elements ="); fprintf(fp,"%13.4E ID=%8d\n",mm,mid); } lsda_queryvar(handle,"thick_shell_id",&typid,&length,&filenum); if(typid > 0) { lsda_read(handle,LSDA_FLOAT,"max_thick_shell_mass",0,1,&mm); lsda_read(handle,LSDA_INT,"thick_shell_id",0,1,&mid); fprintf(fp,"\n\n Maximum mass increase in thick shell elements="); fprintf(fp,"%13.4E ID=%8d\n",mm,mid); } } fclose(fp); free(he); free(zrbv); free(yrbv); free(xrbv); free(zm); free(ym); free(xm); free(mass); free(eke); free(eie); free(ke); free(ie); free(ids); printf(" %d states extracted\n",state-1); return 0; } /* NCFORC file */ typedef struct { int master; /* 0 for slave, 1 for master */ int inum; /* interface number for output */ int *ids; /* user ids for nodes */ int n; /* number of nodes */ char legend[80]; char dname[32]; /* so I don't have to keep rebuilding it...*/ } NCFDATA; int comp_ncn(const void *v1, const void *v2) { NCFDATA *p1 = (NCFDATA *) v1; NCFDATA *p2 = (NCFDATA *) v2; if(p1->inum != p2->inum) return (p1->inum - p2->inum); return (p1->master - p2->master); } int translate_ncforc(int handle) { /* This one is a bit strange in that there are separate dirs for each slave/master side of each interface. The only way to tell how many there are is to count the dirs. Fortunately, they appear in the same order we want to output them in..... NOT! readdir now returns things in alphabetic order, so we will have to resort them according to their number..... */ NCFDATA *dp; int ndirs; LSDADir *ldp; int i,j,k,bpt,typid,filenum,state,nmax; LSDA_Length length; char dirname[256]; float *xf,*yf,*zf,*p, *x, *y, *z; float time; FILE *fp; int have_legend=0, lterms=0; if(!(ldp = lsda_opendir(handle,"/ncforc"))) return 0; printf("Extracting NCFORC data\n"); for(ndirs=0; ;ndirs++) { lsda_readdir(ldp,dirname,&typid,&length,&filenum); if(dirname[0]==0) break ; /* end of listing */ } lsda_closedir(ldp); dp = (NCFDATA *) malloc(ndirs * sizeof(NCFDATA)); ldp = lsda_opendir(handle,"/ncforc"); for(i=0;i<ndirs ;i++) { lsda_readdir(ldp,dirname,&typid,&length,&filenum); if(strcmp(dirname,"metadata")==0) { /* skip this one */ i--; continue; } dp[i].master = (dirname[0] == 'm'); if(dp[i].master) sscanf(dirname+7,"%d",&dp[i].inum); else sscanf(dirname+6,"%d",&dp[i].inum); sprintf(dp[i].dname,"/ncforc/%s",dirname); } lsda_closedir(ldp); qsort(dp,ndirs,sizeof(NCFDATA),comp_ncn); /* Ok, now go through each directory and get the list of user ids. Also, build up legend info if we have any */ for(i=nmax=0; i<ndirs; i++) { sprintf(dirname,"%s/metadata",dp[i].dname); lsda_cd(handle,dirname); lsda_queryvar(handle,"ids",&typid,&length,&filenum); if(typid > 0) { dp[i].n = length; if(nmax < length) nmax = length; dp[i].ids = (int *) malloc(dp[i].n*sizeof(int)); lsda_read(handle,LSDA_INT,"ids",0,length,dp[i].ids); } else { dp[i].n = 0; dp[i].ids = NULL; } lsda_queryvar(handle,"legend",&typid,&length,&filenum); if(typid > 0) { k=length; bpt=sizeof(dp[i].legend); if(k > bpt) k=bpt; lsda_read(handle,LSDA_I1,"legend",0,k,dp[i].legend); for( ; k < bpt; k++) dp[i].legend[k]=' '; have_legend=1; } else dp[i].legend[0]=0; } if(nmax == 0) return 0; /* ???? */ xf = (float *) malloc(nmax*sizeof(float)); yf = (float *) malloc(nmax*sizeof(float)); zf = (float *) malloc(nmax*sizeof(float)); p = (float *) malloc(nmax*sizeof(float)); x = (float *) malloc(nmax*sizeof(float)); y = (float *) malloc(nmax*sizeof(float)); z = (float *) malloc(nmax*sizeof(float)); /* open file and write header */ sprintf(output_file,"%sncforc",output_path); fp=fopen(output_file,"w"); write_message(fp,output_file); if (!fp) return 0; output_title(handle,dirname,fp); if(have_legend) { fprintf(fp,"\n{BEGIN LEGEND\n"); fprintf(fp," Entity # Title\n"); for(i=j=0; i<ndirs; i++) { if(dp[i].legend[0] && dp[i].inum != j) { fprintf(fp,"%9d %.80s\n",dp[i].inum,dp[i].legend); j=dp[i].inum; } } fprintf(fp,"{END LEGEND}\n\n"); } /* Loop through time states and write each one. */ for(state=1; ; state++) { for(k=0; k<ndirs; k++) { if(state<=999999) sprintf(dirname,"%s/d%6.6d",dp[k].dname,state); else sprintf(dirname,"%s/d%8.8d",dp[k].dname,state); lsda_queryvar(handle,dirname,&typid,&length,&filenum); if(typid != 0) goto done; lsda_cd(handle,dirname); if(lsda_read(handle,LSDA_FLOAT,"time",0,1,&time) != 1) goto done; /* If this is an eroding interface, the number of nodes can change each time. We know if there is and "ids" array in this directory... */ lsda_queryvar(handle,"ids",&typid,&length,&filenum); lterms = (int) length; if(typid > 0 && lterms > 0) { dp[k].n = lterms; if(dp[k].ids) free(dp[k].ids); dp[k].ids = (int *) malloc(dp[k].n*sizeof(int)); lsda_read(handle,LSDA_INT,"ids",0,lterms,dp[k].ids); if(lterms > nmax) { nmax = lterms; free(xf); free(yf); free(zf); free(p); free(x); free(y); free(z); xf = (float *) malloc(nmax*sizeof(float)); yf = (float *) malloc(nmax*sizeof(float)); zf = (float *) malloc(nmax*sizeof(float)); p = (float *) malloc(nmax*sizeof(float)); x = (float *) malloc(nmax*sizeof(float)); y = (float *) malloc(nmax*sizeof(float)); z = (float *) malloc(nmax*sizeof(float)); } } if(dp[k].n > 0) { if(lsda_read(handle,LSDA_FLOAT,"x_force",0,dp[k].n,xf) != dp[k].n) goto done; if(lsda_read(handle,LSDA_FLOAT,"y_force",0,dp[k].n,yf) != dp[k].n) goto done; if(lsda_read(handle,LSDA_FLOAT,"z_force",0,dp[k].n,zf) != dp[k].n) goto done; if(lsda_read(handle,LSDA_FLOAT,"pressure",0,dp[k].n,p) != dp[k].n) goto done; if(lsda_read(handle,LSDA_FLOAT,"x",0,dp[k].n,x) != dp[k].n) goto done; if(lsda_read(handle,LSDA_FLOAT,"y",0,dp[k].n,y) != dp[k].n) goto done; if(lsda_read(handle,LSDA_FLOAT,"z",0,dp[k].n,z) != dp[k].n) goto done; } fprintf(fp,"\n\n\n forces (t=%11.5E) for interface%10d %s side\n\n", time,dp[k].inum,(dp[k].master ? "master" : "slave ")); fprintf(fp," node x-force/ y-force/ z-force/"); fprintf(fp," pressure/\n"); fprintf(fp," coordinate coordinate coordinate\n"); for(i=0; i<dp[k].n; i++) { fprintf(fp,"%10d %14.5E%14.5E%14.5E%14.5E\n",dp[k].ids[i], xf[i],yf[i],zf[i],p[i]); fprintf(fp," %14.5E%14.5E%14.5E\n",x[i],y[i],z[i]); } } } done: fclose(fp); free(z); free(y); free(x); free(p); free(zf); free(yf); free(xf); for(i=0; i<ndirs; i++) if(dp[i].ids) free(dp[i].ids); free(dp); printf(" %d states extracted\n",state-1); return 0; } /* RCFORC file */ int translate_rcforc(int handle) { int i,j,typid,num,filenum,state; LSDA_Length length; char dirname[32]; int *ids; int *sides, *single, nsingle, nsout; int *tcount; float *xf,*yf,*zf,*mass; float *xm,*ym,*zm; float *tarea; float time; FILE *fp; LSDADir *dp = NULL; if (lsda_cd(handle,"/rcforc/metadata") == -1) return 0; printf("Extracting RCFORC data\n"); /* Read metadata */ lsda_queryvar(handle,"ids",&typid,&length,&filenum); num = length; lsda_queryvar(handle,"singlesided",&typid,&length,&filenum); if(typid > 0) nsingle = length/2; else nsingle = 0; ids = (int *) malloc(num*sizeof(int)); sides = (int *) malloc(num*sizeof(int)); xf = (float *) malloc(num*sizeof(float)); yf = (float *) malloc(num*sizeof(float)); zf = (float *) malloc(num*sizeof(float)); mass = (float *) malloc(num*sizeof(float)); lsda_queryvar(handle,"/rcforc/d000001/x_moment",&typid,&length,&filenum); if(length > 0) { xm = (float *) malloc(num*sizeof(float)); ym = (float *) malloc(num*sizeof(float)); zm = (float *) malloc(num*sizeof(float)); } else { xm = ym = zm = NULL; } lsda_queryvar(handle,"/rcforc/d000001/tie_area",&typid,&length,&filenum); if(length > 0) { tcount = (int *) malloc(num*sizeof(int)); tarea = (float *) malloc(num*sizeof(float)); } else { tcount = NULL; tarea = NULL; } lsda_read(handle,LSDA_INT,"ids",0,num,ids); lsda_read(handle,LSDA_INT,"side",0,num,sides); /* in case of some illegal contact definition, ie no slave/master in the input deck which contact ID will be 0 */ lsda_queryvar(handle,"/rcforc/d000001/x_force",&typid,&length,&filenum); if(length < num) { j=0; for(i=0; i<num; i++) { if(ids[i] != 0 ) { ids[j] =ids[i]; sides[j]=sides[i]; j++; } else { printf (" *** Warning: Please check contact definition %d\n",i/2); } } num = j; } if(nsingle) { single = (int *) malloc(nsingle*2*sizeof(int)); lsda_read(handle,LSDA_INT,"singlesided",0,2*nsingle,single); } /* open file and write header */ sprintf(output_file,"%srcforc",output_path); fp=fopen(output_file,"w"); write_message(fp,output_file); if (!fp) return 0; output_title(handle,"/rcforc/metadata",fp); output_legend(handle,fp,1,1); /* Loop through time states and write each one. */ for(state=1; (dp = next_dir(handle,"/rcforc",dp,dirname)) != NULL; state++) { if(lsda_read(handle,LSDA_FLOAT,"time",0,1,&time) != 1) break; if(lsda_read(handle,LSDA_FLOAT,"x_force",0,num,xf) != num) break; if(lsda_read(handle,LSDA_FLOAT,"y_force",0,num,yf) != num) break; if(lsda_read(handle,LSDA_FLOAT,"z_force",0,num,zf) != num) break; if(lsda_read(handle,LSDA_FLOAT,"mass",0,num,mass) != num) break; if(xm) { if(lsda_read(handle,LSDA_FLOAT,"x_moment",0,num,xm) != num) break; if(lsda_read(handle,LSDA_FLOAT,"y_moment",0,num,ym) != num) break; if(lsda_read(handle,LSDA_FLOAT,"z_moment",0,num,zm) != num) break; } if(tcount) { if(lsda_read(handle,LSDA_FLOAT,"tie_area",0,num,tarea) != num) break; if(lsda_read(handle,LSDA_INT,"tie_count",0,num,tcount) != num) break; } nsout=0; for(i=0; i<num; i++) { while(nsout < nsingle && i == single[2*nsout]) { fprintf(fp," interface number, %9d,is single surface-resultants are undefined\n",single[2*nsout+1]); nsout++; } if(sides[i]) fprintf(fp," master%11d time",ids[i]); else fprintf(fp," slave %11d time",ids[i]); fprintf(fp,"%12.5E x %12.5E y %12.5E z %12.5E mass %12.5E", time,xf[i],yf[i],zf[i],mass[i]); if(xm) { fprintf(fp," mx %12.5E my %12.5E mz %12.5E",xm[i],ym[i],zm[i]); } if(tcount && tcount[i] >= 0) { if(!xm) fprintf(fp," "); fprintf(fp," tied %10d tied area %12.5E",tcount[i],tarea[i]); } fprintf(fp,"\n"); } while(nsout < nsingle && num == single[2*nsout]) { fprintf(fp," interface number, %11d,is single surface-resultants are undefined\n",single[2*nsout+1]); nsout++; } } fclose(fp); free(mass); free(zf); free(yf); free(xf); free(sides); if(nsingle) free(single); if(xm) { free(xm); free(ym); free(zm); } if(tcount) { free(tcount); free(tarea); } free(ids); printf(" %d states extracted\n",state-1); return 0; } /* SPCFORC file */ int translate_spcforc(int handle) { int i,j,typid,filenum,state; LSDA_Length length; char dirname[256]; int *tids,*rids,*id,*mid,numt,numr; float *xf,*yf,*zf,*xm,*ym,*zm,xtot,ytot,ztot; float time; FILE *fp; LSDADir *dp = NULL; if (lsda_cd(handle,"/spcforc/metadata") == -1) return 0; /* Read metadata */ lsda_queryvar(handle,"force_ids",&typid,&length,&filenum); if(typid > 0) { numt = length; tids = (int *) malloc(numt*sizeof(int)); id = (int *) malloc(numt*sizeof(int)); xf = (float *) malloc(numt*sizeof(float)); yf = (float *) malloc(numt*sizeof(float)); zf = (float *) malloc(numt*sizeof(float)); lsda_read(handle,LSDA_INT,"force_ids",0,length,tids); } else { numt = 0; } lsda_queryvar(handle,"moment_ids",&typid,&length,&filenum); if(typid > 0) { numr = length; rids = (int *) malloc(numr*sizeof(int)); mid = (int *) malloc(numr*sizeof(int)); xm = (float *) malloc(numr*sizeof(float)); ym = (float *) malloc(numr*sizeof(float)); zm = (float *) malloc(numr*sizeof(float)); lsda_read(handle,LSDA_INT,"moment_ids",0,length,rids); } else { numr = 0; } if(numt == 0 && numr == 0) return 0; lsda_queryvar(handle,"spc_ids",&typid,&length,&filenum); if(typid > 0) { lsda_read(handle,LSDA_INT,"spc_ids",0,length,id); } else { memset(id,0,numt*sizeof(int)); } lsda_queryvar(handle,"spc_mids",&typid,&length,&filenum); if(typid > 0) { lsda_read(handle,LSDA_INT,"spc_mids",0,length,mid); } else { if(numr) memset(mid,0,numr*sizeof(int)); } /* open file and write header */ printf("Extracting SPCFORC data\n"); sprintf(output_file,"%sspcforc",output_path); fp=fopen(output_file,"w"); write_message(fp,output_file); if (!fp) return 0; output_title(handle,"/spcforc/metadata",fp); /* This may have worked for the one test problem that some user submitted, but it is seg faulting when the id[] array isn't just "1, 2, 3,..." and it doesn't account at all for rotational SPCs, so it can't be completely correct. I don't know what "problem" it was trying to solve, so just remove it.... output_legend_nosort(handle,fp,1,1,id); */ output_legend(handle,fp,1,1); fprintf(fp," single point constraint forces\n\n"); /* Loop through time states and write each one. */ for(state=1; (dp = next_dir(handle,"/spcforc",dp,dirname)) != NULL; state++) { if(lsda_read(handle,LSDA_FLOAT,"time", 0, 1,&time) != 1) break; if(numt) { if(lsda_read(handle,LSDA_FLOAT,"x_force",0,numt,xf) != numt) break; if(lsda_read(handle,LSDA_FLOAT,"y_force",0,numt,yf) != numt) break; if(lsda_read(handle,LSDA_FLOAT,"z_force",0,numt,zf) != numt) break; } if(numr) { if(lsda_read(handle,LSDA_FLOAT,"x_moment",0,numr,xm) != numr) break; if(lsda_read(handle,LSDA_FLOAT,"y_moment",0,numr,ym) != numr) break; if(lsda_read(handle,LSDA_FLOAT,"z_moment",0,numr,zm) != numr) break; } if(lsda_read(handle,LSDA_FLOAT,"x_resultant",0,1,&xtot) != 1) break; if(lsda_read(handle,LSDA_FLOAT,"y_resultant",0,1,&ytot) != 1) break; if(lsda_read(handle,LSDA_FLOAT,"z_resultant",0,1,&ztot) != 1) break; /* Now, it appears that the serial code normally outputs them in increasing node order, with translations before moments if both appear. So we will put them out that way also for compatibility */ fprintf(fp," output at time =%14.5E\n",time); i=j=0; while(i<numt || j<numr) { if(i < numt) { if(j >= numr || tids[i] <= rids[j]) { fprintf(fp," node=%8d local x,y,z forces =%14.4E%14.4E%14.4E setid=%8d\n", tids[i],xf[i],yf[i],zf[i],id[i]); i++; } } if(j < numr) { if(i >= numt || tids[i] > rids[j]) { fprintf(fp," node=%8d local x,y,z moments=%14.4E%14.4E%14.4E setid=%8d\n", rids[j],xm[j],ym[j],zm[j],mid[j]); j++; } } } fprintf(fp," force resultants =%14.4E%14.4E%14.4E\n",xtot,ytot,ztot); } fclose(fp); if(numr) { free(zm); free(ym); free(xm); free(mid); free(rids); } if(numt) { free(zf); free(yf); free(xf); free(id); free(tids); } printf(" %d states extracted\n",state-1); return 0; } /* convert floating point value to a major hack of a string format * to match the strange format used by the ascii file */ char *tochar(float value,int len) { static char s[20]; int i,to,from; sprintf(s,"%12.5E",value); from = 9; to = len-2; for(i=0; i<4; i++) s[to+i]=s[from+i]; return s+1; } /* SWFORC file */ int translate_swforc(int handle) { int i,j,typid,num,filenum,state; LSDA_Length length,length2; char dirname[256]; int *ids,*type,nnnodal; float *axial,*shear,*ftime,*emom,*swlen,*fflag; float *rmom,*torsion,*fp1,*fn1,*fp2,*fn2; float *fmax,*tfmax; float time; FILE *fp; LSDADir *dp = NULL; if (lsda_cd(handle,"/swforc/metadata") == -1) return 0; /* Read metadata */ lsda_queryvar(handle,"ids",&typid,&length,&filenum); num = length; ids = (int *) malloc(num*sizeof(int)); type = (int *) malloc(num*sizeof(int)); fflag = (float *) malloc(num*sizeof(float)); axial = (float *) malloc(num*sizeof(float)); shear = (float *) malloc(num*sizeof(float)); i=sizeof(float) > sizeof(int) ? sizeof(float) : sizeof(int); ftime = (float *) malloc(num*i); swlen = (float *) malloc(num*sizeof(float)); lsda_read(handle,LSDA_INT,"ids",0,length,ids); lsda_read(handle,LSDA_INT,"types",0,length,type); lsda_cd(handle,"/swforc/d000001"); lsda_queryvar(handle,"emom",&typid,&length2,&filenum); if(typid > 0) { nnnodal = length2; emom = (float *) malloc(nnnodal*sizeof(float)); } else { nnnodal = 0; } lsda_queryvar(handle,"resultant_moment",&typid,&length2,&filenum); if(typid > 0) { rmom = (float *) malloc(num*sizeof(float)); } else { rmom = NULL; } lsda_queryvar(handle,"torsion",&typid,&length2,&filenum); if(typid > 0) { torsion = (float *) malloc(num*sizeof(float)); } else { torsion = NULL; } lsda_queryvar(handle,"fp1",&typid,&length2,&filenum); if(typid > 0) { fp1 = (float *) malloc(num*sizeof(float)); fn1 = (float *) malloc(num*sizeof(float)); fp2 = (float *) malloc(num*sizeof(float)); fn2 = (float *) malloc(num*sizeof(float)); } else { fp1 = NULL; fn1 = NULL; fp2 = NULL; fn2 = NULL; } lsda_queryvar(handle,"max_failure",&typid,&length2,&filenum); if(typid > 0) { fmax = (float *) malloc(num*sizeof(float)); tfmax = (float *) malloc(num*sizeof(float)); } else { fmax = NULL; tfmax = NULL; } /* open file and write header */ printf("Extracting SWFORC data\n"); sprintf(output_file,"%sswforc",output_path); fp=fopen(output_file,"w"); write_message(fp,output_file); if (!fp) return 0; output_title(handle,"/swforc/metadata",fp); /* Loop through time states and write each one. */ for(state=1; (dp = next_dir(handle,"/swforc",dp,dirname)) != NULL; state++) { if(lsda_read(handle,LSDA_FLOAT,"time", 0, 1,&time) != 1) break; if(lsda_read(handle,LSDA_FLOAT,"axial", 0,num,axial) != num) break; if(lsda_read(handle,LSDA_FLOAT,"shear", 0,num,shear) != num) break; if(lsda_read(handle,LSDA_FLOAT,"failure",0,num,fflag) != num) { /* check for older file, which had integer flags stored as "failure_flag" */ int *iflag = (int *) ftime; int i; if(lsda_read(handle,LSDA_INT,"failure_flag",0,num,iflag) != num) break; /* convert integers (0/1) to floats */ for(i=0; i<num; i++) fflag[i] = (float) iflag[i]; } if(lsda_read(handle,LSDA_FLOAT,"failure_time",0,num,ftime) != num) break; if(lsda_read(handle,LSDA_FLOAT,"length",0,num,swlen) != num) { memset(swlen,0,num*sizeof(float)); } if(nnnodal) if(lsda_read(handle,LSDA_FLOAT,"emom",0,nnnodal,emom) != nnnodal) break; if(rmom!=NULL) if(lsda_read(handle,LSDA_FLOAT,"resultant_moment",0,num,rmom) != num) { free(rmom); rmom = NULL; } if(torsion!=NULL) if(lsda_read(handle,LSDA_FLOAT,"torsion",0,num,torsion) != num) { free(torsion); torsion = NULL; } if(fp1!=NULL) { if(lsda_read(handle,LSDA_FLOAT,"fp1",0,num,fp1) != num) break; if(lsda_read(handle,LSDA_FLOAT,"fn1",0,num,fn1) != num) break; if(lsda_read(handle,LSDA_FLOAT,"fp2",0,num,fp2) != num) break; if(lsda_read(handle,LSDA_FLOAT,"fn2",0,num,fn2) != num) break; } if(fmax != NULL) { if(lsda_read(handle,LSDA_FLOAT,"max_failure",0,num,fmax) != num) break; if(lsda_read(handle,LSDA_FLOAT,"max_failure_time",0,num,tfmax) != num) break; } fprintf(fp,"\n constraint # axial shear time"); fprintf(fp," failure length"); fprintf(fp," rslt moment torsion"); if (fp1!=NULL) { fprintf(fp," fp1 fn1 fp2 fn2"); } fprintf(fp,"\n"); for(i=j=0; i<num; i++) { if(type[i] == 3 || type[i] == 6) fprintf(fp," %5d%13.5E%13.5E%13.5E %8.4f ", i+1,axial[i],shear[i],time,fflag[i]); else if(fflag[i] < 1.0) fprintf(fp," %5d%13.5E%13.5E%13.5E %-7s ", i+1,axial[i],shear[i],time,tochar2(fflag[i],7)); else fprintf(fp," %5d%13.5E%13.5E%13.5E failure ", i+1,axial[i],shear[i],time); if(type[i] == 0) { fprintf(fp,"constraint/weld ID %8d",ids[i]); if(swlen[i] > 0.0) fprintf(fp,"%13.5E",swlen[i]); if(rmom != NULL) fprintf(fp,"%13.5E",rmom[i]); fprintf(fp,"\n"); } else if(type[i] == 1) fprintf(fp,"generalized weld ID %8d\n",ids[i]); else if(type[i] == 2) { fprintf(fp,"spotweld beam ID %8d",ids[i]); if(fmax != NULL && fmax[i] > 0.) { fprintf(fp,"%13.5E",swlen[i]); if(rmom != NULL) fprintf(fp,"%13.5E",rmom[i]); fprintf(fp," fcmx=%s",tochar2(fmax[i],7)); fprintf(fp," t=%s\n",tochar2(tfmax[i],8)); } else if(ftime[i] > 0.0) { fprintf(fp," failure time=%12.4E\n",ftime[i]); } else { fprintf(fp,"%13.5E",swlen[i]); if(rmom != NULL) fprintf(fp,"%13.5E",rmom[i]); else fprintf(fp," "); if(fp1 != NULL) { fprintf(fp," %13.5E%13.5E%13.5E%13.5E",fp1[i],fn1[i],fp2[i],fn2[i]); } fprintf(fp,"\n"); } } else if(type[i] == 3) { fprintf(fp,"spotweld solid ID %8d",ids[i]); if(fmax != NULL && fmax[i] > 0.) { fprintf(fp,"%13.5E",swlen[i]); fprintf(fp," fcmx=%s",tochar2(fmax[i],7)); fprintf(fp," t=%s\n",tochar2(tfmax[i],8)); } else if(ftime[i] > 0.0) { fprintf(fp," failure time=%12.4E\n",ftime[i]); } else { fprintf(fp,"%13.5E",swlen[i]); if(rmom != NULL) fprintf(fp,"%13.5E",rmom[i]); else fprintf(fp," "); if(torsion) fprintf(fp,"%13.5E\n",torsion[i]); else fprintf(fp,"\n"); } } else if(type[i] == 4) { fprintf(fp,"nonnodal cnst ID %8d",ids[i]); if(fflag[i]) fprintf(fp," failure time=%12.4E %13.5E\n",ftime[i],emom[j]); else fprintf(fp," %13.5E\n",emom[j]); j++; } else if(type[i] == 6) { fprintf(fp,"spotweld assmy ID %8d",ids[i]); if(ftime[i] > 0.0) fprintf(fp," failure time=%12.4E\n",ftime[i]); else { fprintf(fp,"%13.5E",swlen[i]); if(rmom != NULL) fprintf(fp,"%13.5E",rmom[i]); else fprintf(fp," "); if(torsion) fprintf(fp,"%13.5E\n",torsion[i]); else fprintf(fp,"\n"); } } else { fprintf(fp,"\n"); } } } fclose(fp); if(rmom!=NULL) free(rmom); if(fmax!=NULL) free(fmax); if(tfmax!=NULL) free(tfmax); if(torsion!=NULL) free(torsion); if(nnnodal) free(emom); if(fp1!=NULL) free(fp1); if(fn1!=NULL) free(fn1); if(fp2!=NULL) free(fp2); if(fn2!=NULL) free(fn2); free(swlen); free(ftime); free(shear); free(axial); free(fflag); free(type); free(ids); printf(" %d states extracted\n",state-1); return 1; } /* ABSTAT file */ int translate_abstat(int handle) { int i,j,k,typid,num,filenum,state,nmatc; LSDA_Length length; char dirname[256]; int *ids, *nmat, *matids, nmatids; float *v,*p,*ie,*din,*den,*dout,*tm,*gt,*sa,*r, *b, *ub, *doutp, *doutv; float time; FILE *fp; LSDADir *dp = NULL; int idoutp=0; if (lsda_cd(handle,"/abstat/metadata") == -1) return 0; /* Read metadata */ lsda_queryvar(handle,"../d000001/volume",&typid,&length,&filenum); if(typid < 0) return 0; num = length; ids = (int *) malloc(num*sizeof(int)); if(lsda_read(handle,LSDA_INT,"ids",0,num,ids) != num) { for(i=0; i<num; i++) ids[i] = i+1; } v = (float *) malloc(num*sizeof(float)); p = (float *) malloc(num*sizeof(float)); ie = (float *) malloc(num*sizeof(float)); din = (float *) malloc(num*sizeof(float)); den = (float *) malloc(num*sizeof(float)); dout = (float *) malloc(num*sizeof(float)); tm = (float *) malloc(num*sizeof(float)); gt = (float *) malloc(num*sizeof(float)); sa = (float *) malloc(num*sizeof(float)); r = (float *) malloc(num*sizeof(float)); lsda_queryvar(handle,"/abstat/d000001/dm_dt_outp",&typid,&length,&filenum); if(length > 0) { doutp= (float *) malloc(num*sizeof(float)); doutv= (float *) malloc(num*sizeof(float)); idoutp=1; } /* Check for (optional?) blockage output */ lsda_queryvar(handle,"../metadata/mat_ids",&typid,&length,&filenum); if(typid < 0) { nmatids = 0; } else { nmatids = length; matids = (int *) malloc(nmatids*sizeof(int)); lsda_read(handle,LSDA_INT,"mat_ids",0,nmatids,matids); lsda_queryvar(handle,"../metadata/mat_counts",&typid,&length,&filenum); nmatc = length; nmat = (int *) malloc(nmatc*sizeof(int)); lsda_read(handle,LSDA_INT,"mat_counts",0,nmatc,nmat); b = (float *) malloc(nmatids*sizeof(float)); ub = (float *) malloc(nmatids*sizeof(float)); } /* open file and write header */ printf("Extracting ABSTAT data\n"); sprintf(output_file,"%sabstat",output_path); fp=fopen(output_file,"w"); write_message(fp,output_file); if (!fp) return 0; output_title(handle,"/abstat/metadata",fp); output_legend(handle,fp,1,1); /* Loop through time states and write each one. */ for(state=1; (dp = next_dir(handle,"/abstat",dp,dirname)) != NULL; state++) { if(lsda_read(handle,LSDA_FLOAT,"time", 0, 1,&time) != 1) break; if(lsda_read(handle,LSDA_FLOAT,"volume", 0,num, v) != num) break; if(lsda_read(handle,LSDA_FLOAT,"pressure", 0,num, p) != num) break; if(lsda_read(handle,LSDA_FLOAT,"internal_energy",0,num, ie) != num) break; if(lsda_read(handle,LSDA_FLOAT,"dm_dt_in", 0,num, din) != num) break; if(lsda_read(handle,LSDA_FLOAT,"density", 0,num, den) != num) break; if(lsda_read(handle,LSDA_FLOAT,"dm_dt_out", 0,num, dout) != num) break; if(lsda_read(handle,LSDA_FLOAT,"total_mass", 0,num, tm) != num) break; if(lsda_read(handle,LSDA_FLOAT,"gas_temp", 0,num, gt) != num) break; if(lsda_read(handle,LSDA_FLOAT,"surface_area", 0,num, sa) != num) break; if(lsda_read(handle,LSDA_FLOAT,"reaction", 0,num, r) != num) break; if(idoutp==1) { if(lsda_read(handle,LSDA_FLOAT,"dm_dt_outp", 0,num,doutp) != num) break; if(lsda_read(handle,LSDA_FLOAT,"dm_dt_outv", 0,num,doutv) != num) break; } if(nmatids > 0) { lsda_read(handle,LSDA_FLOAT,"blocked_area", 0,nmatids,b); lsda_read(handle,LSDA_FLOAT,"unblocked_area", 0,nmatids,ub); } fprintf(fp,"\n\n time airbag/cv # volume pressure internal energy"); fprintf(fp," dm/dt in density dm/dt out total mass gas temp. surface area"); fprintf(fp," reaction dm/dt outp dm/dt outv\n"); k=0; for(i=0; i<num; i++) { fprintf(fp,"%12.5E%8d%15.4E%15.4E%15.4E%15.4E%15.4E", time,ids[i],v[i],p[i],ie[i],din[i],den[i]); if(idoutp==1) { fprintf(fp,"%11.3E%11.3E%11.3E%11.3E%11.3E%11.3E%11.3E\n", dout[i],tm[i],gt[i],sa[i],r[i],doutp[i],doutv[i]); } else { fprintf(fp,"%11.3E%11.3E%11.3E%11.3E%11.3E\n", dout[i],tm[i],gt[i],sa[i],r[i]); } if(nmatids > 0) { for(j=0; j<nmat[i]; j++) { fprintf(fp," Material I.D.=%8d Unblocked Area =",matids[k]); fprintf(fp,"%12.4E Blocked Area=%12.4E\n",ub[k],b[k]); k=k+1; } } } } fclose(fp); free(r); free(sa); free(gt); free(tm); free(dout); if(idoutp==1) { free(doutp); free(doutv); } free(den); free(din); free(ie); free(p); free(v); free(ids); if(nmatids > 0) { free(ub); free(b); free(nmat); free(matids); } printf(" %d states extracted\n",state-1); return 1; } /* PABSTAT file - Particle Gas Dynamic */ int translate_abstat_cpm(int handle) { int i,j,jj,k,kk,typid,num,filenum,state; LSDA_Length length; char dirname[256],dname[256]; int *bag_id; int *nspec, *nparts, *part_id, *part_type, numtot, numspectot, numvent; float *v,*p,*ie,*din,*den,*dout,*tm,*gt,*sa,*r; float time; FILE *fp, *fp_tmp1, *fp_tmp2, *fp_tmp3; char output_file_tmp1[256], output_file_tmp2[256]; LSDADir *dp = NULL; /* more data for cpm chamber option */ int nchm,ntchm,*nbag_c,*chm_iid,*chm_uid; float *c_v,*c_p,*c_ie,*c_din,*c_den,*c_dout,*c_tm,*c_gt,*c_sa,*c_r,*c_te; char output_file_tmp3[256]; /* airbag parts data */ float *ppres, *ppor_leak, *pvent_leak, *parea_tot, *parea_unblocked, *ptemp; float *ppresp, *ppresm; float *pnt_spec; if (lsda_cd(handle,"/abstat_cpm/metadata") == -1) return 0; /* Read metadata */ lsda_queryvar(handle,"../d000001/volume",&typid,&length,&filenum); if(typid < 0) return 0; num = length; lsda_queryvar(handle,"nbag_chamber",&typid,&length,&filenum); if(typid < 0) nchm=0; else nchm=length; if(nchm>0) { nbag_c = (int *) malloc(nchm*sizeof(int)); lsda_read(handle,LSDA_INT,"nbag_chamber",0,nchm,nbag_c); lsda_queryvar(handle,"chamber_iid",&typid,&length,&filenum); ntchm=length; chm_iid = (int *) malloc(ntchm*sizeof(int)); chm_uid = (int *) malloc(ntchm*sizeof(int)); lsda_read(handle,LSDA_INT,"chamber_iid",0,ntchm,chm_iid); lsda_read(handle,LSDA_INT,"chamber_uid",0,ntchm,chm_uid); lsda_queryvar(handle,"../d000001/chamber_data/volume",&typid,&length,&filenum); ntchm=length; c_v = (float *) malloc(ntchm*sizeof(float)); c_p = (float *) malloc(ntchm*sizeof(float)); c_ie = (float *) malloc(ntchm*sizeof(float)); c_din = (float *) malloc(ntchm*sizeof(float)); c_den = (float *) malloc(ntchm*sizeof(float)); c_dout = (float *) malloc(ntchm*sizeof(float)); c_tm = (float *) malloc(ntchm*sizeof(float)); c_gt = (float *) malloc(ntchm*sizeof(float)); c_sa = (float *) malloc(ntchm*sizeof(float)); c_r = (float *) malloc(ntchm*sizeof(float)); c_te = (float *) malloc(ntchm*sizeof(float)); } bag_id = (int *) malloc(num*sizeof(int)); nspec = (int *) malloc(num*sizeof(int)); nparts = (int *) malloc(num*sizeof(int)); if(lsda_read(handle,LSDA_INT,"ids",0,num,bag_id) != num) { for(i=0; i<num; i++) bag_id[i] = i+1; } lsda_read(handle,LSDA_INT,"nspec", 0,num,nspec ); lsda_read(handle,LSDA_INT,"nparts",0,num,nparts); numtot=0; for(i=0; i<num; i++) numtot += nparts[i]; numspectot=0; for(i=0; i<num; i++) numspectot += nparts[i] * (nspec[i]+1); part_id = (int *) malloc(numtot*sizeof(int)); part_type = (int *) malloc(numtot*sizeof(int)); lsda_read(handle,LSDA_INT,"pid" ,0,numtot,part_id); lsda_read(handle,LSDA_INT,"ptype",0,numtot,part_type); v = (float *) malloc(num*sizeof(float)); p = (float *) malloc(num*sizeof(float)); ie = (float *) malloc(num*sizeof(float)); din = (float *) malloc(num*sizeof(float)); den = (float *) malloc(num*sizeof(float)); dout = (float *) malloc(num*sizeof(float)); tm = (float *) malloc(num*sizeof(float)); gt = (float *) malloc(num*sizeof(float)); sa = (float *) malloc(num*sizeof(float)); r = (float *) malloc(num*sizeof(float)); /* read in part and species data */ ppres = (float *) malloc(numtot*sizeof(float)); ppor_leak = (float *) malloc(numtot*sizeof(float)); pvent_leak = (float *) malloc(numtot*sizeof(float)); parea_tot = (float *) malloc(numtot*sizeof(float)); parea_unblocked = (float *) malloc(numtot*sizeof(float)); ptemp = (float *) malloc(numtot*sizeof(float)); ppresp = (float *) malloc(numtot*sizeof(float)); ppresm = (float *) malloc(numtot*sizeof(float)); pnt_spec = (float *) malloc(numspectot*sizeof(float)); /* open file and write header */ printf("Extracting PARTICLE ABSTAT_CPM data\n"); sprintf(output_file,"%sabstat_cpm",output_path); fp=fopen(output_file,"w"); write_message(fp,output_file); if (!fp) return 0; output_title(handle,"/abstat_cpm/metadata",fp); output_legend(handle,fp,1,1); if(nchm>0) { sprintf(output_file_tmp3,"%sabstat_chamber",output_path); fp_tmp3=fopen(output_file_tmp3,"w"); write_message(fp_tmp3,output_file_tmp3); output_title(handle,"/abstat_cpm/metadata",fp_tmp3); output_legend(handle,fp_tmp3,1,1); } sprintf(output_file_tmp1,"%spartgas_partdata_p.txt",output_path); fp_tmp1=fopen(output_file_tmp1,"w"); output_title(handle,"/abstat_cpm/metadata",fp_tmp1); output_legend(handle,fp_tmp1,1,1); fprintf(fp_tmp1," time\n PART ID pressure por_leak vent_leak part_area unblk_area temperature\n press s+ press s-\n\n"); numvent=jj=kk=0; for(i=0; i<num; i++) { if(nspec[i]>0) for(k=0;k<nparts[i];k++) if(part_type[kk+k] >= 3) numvent++; kk += nparts[i]; jj += nspec[i]+1; } if(numvent) { sprintf(output_file_tmp2,"%spartgas_partdata_sp.txt",output_path); fp_tmp2=fopen(output_file_tmp2,"w"); output_title(handle,"/abstat_cpm/metadata",fp_tmp2); output_legend(handle,fp_tmp2,1,1); fprintf(fp_tmp2," time\n PART ID dmout/dt\n\n"); } /* Loop through time states and write each one. */ for(state=1; (dp = next_dir(handle,"/abstat_cpm",dp,dname)) != NULL; state++) { if(lsda_read(handle,LSDA_FLOAT,"time", 0, 1,&time) != 1) break; if(lsda_read(handle,LSDA_FLOAT,"volume", 0,num, v) != num) break; if(lsda_read(handle,LSDA_FLOAT,"pressure", 0,num, p) != num) break; if(lsda_read(handle,LSDA_FLOAT,"internal_energy",0,num, ie) != num) break; if(lsda_read(handle,LSDA_FLOAT,"dm_dt_in", 0,num, din) != num) break; if(lsda_read(handle,LSDA_FLOAT,"density", 0,num, den) != num) break; if(lsda_read(handle,LSDA_FLOAT,"dm_dt_out", 0,num, dout) != num) break; if(lsda_read(handle,LSDA_FLOAT,"total_mass", 0,num, tm) != num) break; if(lsda_read(handle,LSDA_FLOAT,"gas_temp", 0,num, gt) != num) break; if(lsda_read(handle,LSDA_FLOAT,"surface_area", 0,num, sa) != num) break; if(lsda_read(handle,LSDA_FLOAT,"reaction", 0,num, r) != num) break; fprintf(fp,"\n\n time airbag/cv # volume pressure internal energy"); fprintf(fp," dm/dt in density dm/dt out total mass gas temp. surface area"); fprintf(fp," reaction\n"); k=0; for(i=0; i<num; i++) { fprintf(fp,"%12.5E%8d%15.4E%15.4E%15.4E%15.4E%15.4E", time,bag_id[i],v[i],p[i],ie[i],din[i],den[i]); fprintf(fp,"%11.3E%11.3E%11.3E%11.3E%11.3E\n", dout[i],tm[i],gt[i],sa[i],r[i]); } sprintf(dirname,"/abstat_cpm/%s/bag_data",dname); lsda_queryvar(handle,dirname,&typid,&length,&filenum); if(typid != 0) break; lsda_cd(handle,dirname); lsda_read(handle,LSDA_FLOAT,"pressure", 0,numtot,ppres); lsda_read(handle,LSDA_FLOAT,"por_leak", 0,numtot,ppor_leak); lsda_read(handle,LSDA_FLOAT,"vent_leak", 0,numtot,pvent_leak); lsda_read(handle,LSDA_FLOAT,"area_tot", 0,numtot,parea_tot); lsda_read(handle,LSDA_FLOAT,"area_unblocked",0,numtot,parea_unblocked); lsda_read(handle,LSDA_FLOAT,"temperature", 0,numtot,ptemp); lsda_read(handle,LSDA_FLOAT,"pres+", 0,numtot,ppresp); lsda_read(handle,LSDA_FLOAT,"pres-", 0,numtot,ppresm); fprintf(fp_tmp1,"%12.4E\n",time); for(i=0; i<numtot; i++) { fprintf(fp_tmp1,"%8d%12.4E%12.4E%12.4E%12.4E%12.4E%12.4E\n %12.4E%12.4E\n", part_id[i],ppres[i],ppor_leak[i],pvent_leak[i],parea_tot[i], parea_unblocked[i],ptemp[i],ppresp[i],ppresm[i]); } if(numvent) { lsda_read(handle,LSDA_FLOAT,"nt_species",0,numspectot,pnt_spec); fprintf(fp_tmp2,"%12.4E\n",time); jj=kk=0; for(i=0; i<num; i++) { if(nspec[i]>0) { for(k=0; k<nparts[i]; k++) { if(part_type[kk+k] >= 3) { fprintf(fp_tmp2,"%8d%12.4E",part_id[kk+k],ptemp[kk+k]); for(j=0;j<=nspec[i];j++) fprintf(fp_tmp2,"%12.4E",pnt_spec[jj+j]); fprintf(fp_tmp2,"\n"); } } } kk += nparts[i]; jj += nspec[i]+1; } } if(nchm>0) { sprintf(dirname,"/abstat_cpm/%s/chamber_data",dname); lsda_queryvar(handle,dirname,&typid,&length,&filenum); if(typid != 0) break; lsda_cd(handle,dirname); if(lsda_read(handle,LSDA_FLOAT,"volume", 0,ntchm, c_v) != ntchm) break; if(lsda_read(handle,LSDA_FLOAT,"pressure", 0,ntchm, c_p) != ntchm) break; if(lsda_read(handle,LSDA_FLOAT,"internal_energy",0,ntchm, c_ie) != ntchm) break; if(lsda_read(handle,LSDA_FLOAT,"dm_dt_in", 0,ntchm, c_din) != ntchm) break; if(lsda_read(handle,LSDA_FLOAT,"density", 0,ntchm, c_den) != ntchm) break; if(lsda_read(handle,LSDA_FLOAT,"dm_dt_out", 0,ntchm,c_dout) != ntchm) break; if(lsda_read(handle,LSDA_FLOAT,"total_mass", 0,ntchm, c_tm) != ntchm) break; if(lsda_read(handle,LSDA_FLOAT,"gas_temp", 0,ntchm, c_gt) != ntchm) break; if(lsda_read(handle,LSDA_FLOAT,"surface_area", 0,ntchm, c_sa) != ntchm) break; if(lsda_read(handle,LSDA_FLOAT,"reaction", 0,ntchm, c_r) != ntchm) break; if(lsda_read(handle,LSDA_FLOAT,"transE", 0,ntchm, c_te) != ntchm) break; fprintf(fp_tmp3,"\n\n time airbag/cv # volume pressure internal energy"); fprintf(fp_tmp3," dm/dt in density dm/dt out total mass gas temp. surface area"); fprintf(fp_tmp3," reaction Trans E\n"); for(i=0; i<ntchm; i++) { for(j=0; j<ntchm; j++) if(chm_iid[j]==i+1) { fprintf(fp_tmp3,"%12.5E%8d%15.4E%15.4E%15.4E%15.4E%15.4E", time,chm_uid[j],c_v[i],c_p[i],c_ie[i],c_din[i],c_den[i]); fprintf(fp_tmp3,"%11.3E%11.3E%11.3E%11.3E%11.3E%11.3E\n", c_dout[i],c_tm[i],c_gt[i],c_sa[i],c_r[i],c_te[i]); } } } } fclose(fp); fclose(fp_tmp1); if(numvent) fclose(fp_tmp2); free(r); free(sa); free(gt); free(tm); free(dout); free(den); free(din); free(ie); free(p); free(v); free(ppres); free(ppor_leak); free(pvent_leak); free(parea_tot); free(parea_unblocked); free(ptemp); free(pnt_spec); free(part_type); free(part_id); free(nparts); free(nspec); free(bag_id); if(nchm>0) { fclose(fp_tmp3); free(c_te); free(c_r); free(c_sa); free(c_gt); free(c_tm); free(c_dout); free(c_den); free(c_din); free(c_ie); free(c_p); free(c_v); free(chm_uid); free(chm_iid); free(nbag_c); } printf(" %d states extracted\n",state-1); return 1; } /* ABSTAT PBlast file - Particle Blast */ int translate_abstat_pbm(int handle) { int i,j,jj,k,kk,typid,num,filenum,state; LSDA_Length length; char dirname[256],dname[256]; int *bag_id; int *nparts, *part_id, *part_type, numtot; float *air_ie, *air_tr, *he_ie, *he_tr, *out_ie, *out_tr; float time; FILE *fp; char output_file_tmp1[256], output_file_tmp2[256]; LSDADir *dp = NULL; float *c_v,*c_p,*c_ie,*c_din,*c_den,*c_dout,*c_tm,*c_gt,*c_sa,*c_r,*c_te; char output_file_tmp3[256]; float *pp_air,*pp_he,*pp_result,*area,*fx_air,*fy_air,*fz_air,*fx_he,*fy_he,*fz_he,*fx_result,*fy_result,*fz_result; if (lsda_cd(handle,"/abstat_pbm/metadata") == -1) return 0; /* Read metadata */ lsda_read(handle,LSDA_INT,"nbag",0,1,&num); bag_id = (int *) malloc(num*sizeof(int)); nparts = (int *) malloc(num*sizeof(int)); if(lsda_read(handle,LSDA_INT,"ids",0,num,bag_id) != num) { for(i=0; i<num; i++) bag_id[i] = i+1; } lsda_read(handle,LSDA_INT,"nparts",0,num,nparts); numtot=0; for(i=0; i<num; i++) numtot += nparts[i]; part_id = (int *) malloc(numtot*sizeof(int)); lsda_read(handle,LSDA_INT,"pid" ,0,numtot,part_id); air_ie = (float *) malloc(num*sizeof(float)); air_tr = (float *) malloc(num*sizeof(float)); he_ie = (float *) malloc(num*sizeof(float)); he_tr = (float *) malloc(num*sizeof(float)); out_ie = (float *) malloc(num*sizeof(float)); out_tr = (float *) malloc(num*sizeof(float)); /* read in part and species data */ pp_air = (float *) malloc(numtot*sizeof(float)); pp_he = (float *) malloc(numtot*sizeof(float)); pp_result = (float *) malloc(numtot*sizeof(float)); area = (float *) malloc(numtot*sizeof(float)); fx_air = (float *) malloc(numtot*sizeof(float)); fy_air = (float *) malloc(numtot*sizeof(float)); fz_air = (float *) malloc(numtot*sizeof(float)); fx_he = (float *) malloc(numtot*sizeof(float)); fy_he = (float *) malloc(numtot*sizeof(float)); fz_he = (float *) malloc(numtot*sizeof(float)); fx_result = (float *) malloc(numtot*sizeof(float)); fy_result = (float *) malloc(numtot*sizeof(float)); fz_result = (float *) malloc(numtot*sizeof(float)); /* open file and write header */ printf("Extracting PARTICLE ABSTAT_PBM data\n"); sprintf(output_file,"%sabstat_pbm",output_path); fp=fopen(output_file,"w"); write_message(fp,output_file); if (!fp) return 0; output_title(handle,"/abstat_pbm/metadata",fp); output_legend(handle,fp,1,1); fprintf(fp,"\n Total number Particle Blast defined: %d\n Total number parts: %d\n\n",num,numtot); /* Loop through time states and write each one. */ for(state=1; (dp = next_dir(handle,"/abstat_pbm",dp,dname)) != NULL; state++) { if(lsda_read(handle,LSDA_FLOAT,"time", 0, 1, &time) != 1) break; if(lsda_read(handle,LSDA_FLOAT,"air_inter_e", 0,num, air_ie) != num) break; if(lsda_read(handle,LSDA_FLOAT,"air_trans_e", 0,num, air_tr) != num) break; if(lsda_read(handle,LSDA_FLOAT,"detonation_product_inter_e",0,num, he_ie) != num) break; if(lsda_read(handle,LSDA_FLOAT,"detonation_product_trans_e",0,num, he_tr) != num) break; if(lsda_read(handle,LSDA_FLOAT,"outside_domain_inter_e", 0,num, out_ie) != num) break; if(lsda_read(handle,LSDA_FLOAT,"outside_domain_trans_e", 0,num, out_tr) != num) break; fprintf(fp,"\n\n time : %15.4E\n",time); fprintf(fp,"\n\nPBlast # Air IE Air TE HE IE HE TE Out IE Out TE\n"); for(i=0; i<num; i++) { fprintf(fp,"%8d%15.4E%15.4E%15.4E%15.4E%15.4E%15.4E\n", bag_id[i],air_ie[i],air_tr[i],he_ie[i],he_tr[i],out_ie[i],out_tr[i]); } sprintf(dirname,"/abstat_pbm/%s/bag_data",dname); lsda_queryvar(handle,dirname,&typid,&length,&filenum); if(typid != 0) break; lsda_cd(handle,dirname); lsda_read(handle,LSDA_FLOAT,"pressure_air", 0,numtot,pp_air); lsda_read(handle,LSDA_FLOAT,"pressure_det_products",0,numtot,pp_he); lsda_read(handle,LSDA_FLOAT,"pressure_resultant", 0,numtot,pp_result); lsda_read(handle,LSDA_FLOAT,"surface_area", 0,numtot,area); lsda_read(handle,LSDA_FLOAT,"x_force_air", 0,numtot,fx_air); lsda_read(handle,LSDA_FLOAT,"y_force_air", 0,numtot,fy_air); lsda_read(handle,LSDA_FLOAT,"z_force_air", 0,numtot,fz_air); lsda_read(handle,LSDA_FLOAT,"x_force_det_products", 0,numtot,fx_he); lsda_read(handle,LSDA_FLOAT,"y_force_det_products", 0,numtot,fy_he); lsda_read(handle,LSDA_FLOAT,"z_force_det_products", 0,numtot,fz_he); lsda_read(handle,LSDA_FLOAT,"x_force_resultant", 0,numtot,fx_result); lsda_read(handle,LSDA_FLOAT,"y_force_resultant", 0,numtot,fy_result); lsda_read(handle,LSDA_FLOAT,"z_force_resultant", 0,numtot,fz_result); fprintf(fp,"\n\n Part # Air P HE P Resultant P Area Air Fx AIR Fy Air Fz\n"); fprintf(fp, " HE Fx HE Fy HE Fz R Fx R Fy R Fz\n"); for(i=0; i<numtot; i++) { fprintf(fp,"%8d%12.4E%12.4E%12.4E%12.4E%12.4E%12.4E%12.4E\n %12.4E%12.4E%12.4E%12.4E%12.4E%12.4E\n", part_id[i],pp_air[i],pp_he[i],pp_result[i],area[i],fx_air[i],fy_air[i],fz_air[i], fx_he[i],fy_he[i],fy_he[i],fx_result[i],fy_result[i],fz_result[i]); } } fclose(fp); free(pp_air); free(pp_he); free(pp_result); free(area); free(fx_air); free(fy_air); free(fz_air); free(fx_he); free(fy_he); free(fz_he); free(fx_result); free(fy_result); free(fz_result); free(air_ie); free(air_tr); free(he_ie); free(he_tr); free(out_ie); free(out_tr); free(bag_id); free(part_id); printf(" %d states extracted\n",state-1); return 1; } /* CPM_SENSOR file */ int translate_cpm_sensor(int handle) { int i,state,nsensor,revision,newformat; LSDA_Length length; FILE *fp; float time,*dens,*pres,*temp,*velx,*vely,*velz,*velr,*xpos,*ypos,*zpos,*part; char dirname[256]; char name[15],*rev; LSDADir *dp = NULL; if (lsda_cd(handle,"/cpm_sensor/metadata") == -1) return 0; /* Read metadata */ rev = (char *)malloc(10); lsda_read(handle,LSDA_I1,"../metadata/revision",0,10,rev); revision = atoi(rev); free(rev); lsda_read(handle,LSDA_INT,"../metadata/n_bags",0,1,&newformat); if (revision > 48400) { if (newformat != 0) { translate_cpm_sensor_new(handle); return 0; } } lsda_read(handle,LSDA_INT,"../metadata/nsensor",0,1,&nsensor); printf("Extracting CPM_SENSOR data\n"); velr = (float *) malloc(nsensor*sizeof(float)); velx = (float *) malloc(nsensor*sizeof(float)); vely = (float *) malloc(nsensor*sizeof(float)); velz = (float *) malloc(nsensor*sizeof(float)); temp = (float *) malloc(nsensor*sizeof(float)); pres = (float *) malloc(nsensor*sizeof(float)); dens = (float *) malloc(nsensor*sizeof(float)); xpos = (float *) malloc(nsensor*sizeof(float)); ypos = (float *) malloc(nsensor*sizeof(float)); zpos = (float *) malloc(nsensor*sizeof(float)); part = (float *) malloc(nsensor*sizeof(float)); /* open file and write header */ sprintf(output_file,"%scpm_sensor",output_path); fp=fopen(output_file,"w"); write_message(fp,output_file); if (!fp) return 0; fprintf(fp,"Airbag Particle sensor file\n"); fprintf(fp,"%5d%5d\n",nsensor,16); fprintf(fp," time\n"); fprintf(fp," x y z\n"); fprintf(fp," vx vy vz\n"); fprintf(fp," pres dens temp npart\n\n\n"); /* Loop through time states and write each one */ for(state=1; (dp = next_dir(handle,"/cpm_sensor",dp,dirname)) != NULL; state++) { if(lsda_read(handle,LSDA_FLOAT,"time",0,1,&time) != 1) break; if(lsda_read(handle,LSDA_FLOAT,"ave_velx",0,nsensor,velx) != nsensor) break; if(lsda_read(handle,LSDA_FLOAT,"ave_vely",0,nsensor,vely) != nsensor) break; if(lsda_read(handle,LSDA_FLOAT,"ave_velz",0,nsensor,velz) != nsensor) break; if(lsda_read(handle,LSDA_FLOAT,"ave_velr",0,nsensor,velr) != nsensor) break; if(lsda_read(handle,LSDA_FLOAT,"temp",0,nsensor,temp) != nsensor) break; if(lsda_read(handle,LSDA_FLOAT,"rho",0,nsensor,dens) != nsensor) break; if(lsda_read(handle,LSDA_FLOAT,"pressure",0,nsensor,pres) != nsensor) break; if(lsda_read(handle,LSDA_FLOAT,"sensor_x",0,nsensor,xpos) != nsensor) break; if(lsda_read(handle,LSDA_FLOAT,"sensor_y",0,nsensor,ypos) != nsensor) break; if(lsda_read(handle,LSDA_FLOAT,"sensor_z",0,nsensor,zpos) != nsensor) break; if(lsda_read(handle,LSDA_FLOAT,"npart",0,nsensor,part) != nsensor) break; fprintf(fp,"%13.5E\n",time); for (i=0; i<nsensor; i++) { fprintf(fp,"%13.5E%13.5E%13.5E\n",xpos[i],ypos[i],zpos[i]); fprintf(fp,"%13.5E%13.5E%13.5E%13.5E\n",velx[i],vely[i],velz[i],velr[i]); fprintf(fp,"%13.5E%13.5E%13.5E%13d\n",pres[i],dens[i],temp[i],(int) part[i]); } } fclose(fp); free(part); free(zpos); free(ypos); free(xpos); free(dens); free(pres); free(temp); free(velz); free(vely); free(velx); free(velr); printf(" %d states extracted\n",state-1); return 0; } /* CPM_SENSOR file with new format */ int translate_cpm_sensor_new(int handle) { int i,j,k,state; FILE *fp; char dirname[256]; int npartgas,nhcpmsor,icpmsor_nd,ntotsor,nin; int *ids,*n_seg; float *dens,*pres,*temp,*velr,*velx,*vely,*velz,*xpos,*ypos,*zpos; float time; int m,mi,isensor; LSDADir *dp = NULL; if (lsda_cd(handle,"/cpm_sensor/metadata") == -1) return 0; /* Read metadata */ lsda_read(handle,LSDA_INT,"n_bags",0,1,&npartgas); lsda_read(handle,LSDA_INT,"n_set_sensor",0,1,&nhcpmsor); lsda_read(handle,LSDA_INT,"n_struc",0,1,&icpmsor_nd); lsda_read(handle,LSDA_INT,"n_sensor",0,1,&ntotsor); nin = npartgas*nhcpmsor; ids = (int *) malloc(ntotsor*sizeof(int)); n_seg = (int *) malloc(nin*sizeof(int)); lsda_read(handle,LSDA_INT,"id_sensor",0,ntotsor,ids); lsda_read(handle,LSDA_INT,"n_seg_in_each_set",0,nin,n_seg); printf("Extracting CPM_SENSOR from new database\n"); /* open file and write header */ sprintf(output_file,"%strhist_cpm_sensor",output_path); fp=fopen(output_file,"w"); write_message(fp,output_file); if (!fp) return 0; fprintf(fp," CPM sensors output\n"); fprintf(fp," Number of sensors:%5d\n\n\n",ntotsor); fprintf(fp," id x y z velx vely\n"); fprintf(fp," velx velr temp dens pres\n"); /* Loop through time states and write each one */ velr = (float *) malloc(ntotsor*sizeof(float)); velx = (float *) malloc(ntotsor*sizeof(float)); vely = (float *) malloc(ntotsor*sizeof(float)); velz = (float *) malloc(ntotsor*sizeof(float)); temp = (float *) malloc(ntotsor*sizeof(float)); pres = (float *) malloc(ntotsor*sizeof(float)); dens = (float *) malloc(ntotsor*sizeof(float)); xpos = (float *) malloc(ntotsor*sizeof(float)); ypos = (float *) malloc(ntotsor*sizeof(float)); zpos = (float *) malloc(ntotsor*sizeof(float)); for(state=1; (dp = next_dir(handle,"/cpm_sensor",dp,dirname)) != NULL; state++) { if(lsda_read(handle,LSDA_FLOAT,"time",0,1,&time) != 1) break; fprintf(fp," time=%13.5E\n",time); lsda_read(handle,LSDA_FLOAT,"ave_velx",0,ntotsor,velx); lsda_read(handle,LSDA_FLOAT,"ave_vely",0,ntotsor,vely); lsda_read(handle,LSDA_FLOAT,"ave_velz",0,ntotsor,velz); lsda_read(handle,LSDA_FLOAT,"ave_velr",0,ntotsor,velr); lsda_read(handle,LSDA_FLOAT,"temp",0,ntotsor,temp); lsda_read(handle,LSDA_FLOAT,"rho",0,ntotsor,dens); lsda_read(handle,LSDA_FLOAT,"pressure",0,ntotsor,pres); lsda_read(handle,LSDA_FLOAT,"sensor_x",0,ntotsor,xpos); lsda_read(handle,LSDA_FLOAT,"sensor_y",0,ntotsor,ypos); lsda_read(handle,LSDA_FLOAT,"sensor_z",0,ntotsor,zpos); k=m=0; for(i=1;i<=npartgas;i++) { for(j=1;j<=nhcpmsor;j++) { if(n_seg[k] != 0) { fprintf(fp," Bag ID, Sensor set:%10d%10d\n",i,j); for(isensor=0; isensor<n_seg[k];isensor++){ mi=m+isensor; fprintf(fp,"%10d%14.4e%14.4e%14.4e%14.4e%14.4e\n", ids[mi],xpos[mi],ypos[mi],zpos[mi],velx[mi],vely[mi]); fprintf(fp," %14.4e%14.4e%14.4e%14.4e%14.4e\n", velz[mi],velr[mi],temp[mi],dens[mi],pres[mi]); } fprintf(fp,"\n"); m += n_seg[k]; } k++; } } } fclose(fp); printf(" %d states extracted\n",state-1); free(velr); free(velx); free(vely); free(velz); free(temp); free(pres); free(dens); free(xpos); free(ypos); free(zpos); return 0; } /* PG_STAT file - Particle general */ int translate_pgstat(int handle) { int i,j,jj,k,kk,typid,num,filenum,state; LSDA_Length length; char dirname[256],dname[256]; int *bag_id; int *nspec, *nparts, *part_id, *part_type, numtot, numspectot, numvent; float *v,*p,*ie,*din,*den,*dout,*tm,*gt,*sa,*r; float time; FILE *fp, *fp_tmp1, *fp_tmp2, *fp_tmp3; char output_file_tmp1[256], output_file_tmp2[256]; LSDADir *dp = NULL; /* more data for PG chamber option */ int nchm,ntchm,*nbag_c,*chm_iid,*chm_uid; float *c_v,*c_p,*c_ie,*c_din,*c_den,*c_dout,*c_tm,*c_gt,*c_sa,*c_r,*c_te; char output_file_tmp3[256]; /* airbag parts data */ float *ppres, *ppor_leak, *pvent_leak, *parea_tot, *parea_unblocked, *ptemp; float *ppresp, *ppresm; float *pnt_spec; if (lsda_cd(handle,"/pg_stat/metadata") == -1) return 0; /* Read metadata */ lsda_queryvar(handle,"../d000001/volume",&typid,&length,&filenum); if(typid < 0) return 0; num = length; lsda_queryvar(handle,"nbag_chamber",&typid,&length,&filenum); if(typid < 0) nchm=0; else nchm=length; if(nchm>0) { nbag_c = (int *) malloc(nchm*sizeof(int)); lsda_read(handle,LSDA_INT,"nbag_chamber",0,nchm,nbag_c); lsda_queryvar(handle,"chamber_iid",&typid,&length,&filenum); ntchm=length; chm_iid = (int *) malloc(ntchm*sizeof(int)); chm_uid = (int *) malloc(ntchm*sizeof(int)); lsda_read(handle,LSDA_INT,"chamber_iid",0,ntchm,chm_iid); lsda_read(handle,LSDA_INT,"chamber_uid",0,ntchm,chm_uid); lsda_queryvar(handle,"../d000001/chamber_data/volume",&typid,&length,&filenum); ntchm=length; c_v = (float *) malloc(ntchm*sizeof(float)); c_p = (float *) malloc(ntchm*sizeof(float)); c_ie = (float *) malloc(ntchm*sizeof(float)); c_din = (float *) malloc(ntchm*sizeof(float)); c_den = (float *) malloc(ntchm*sizeof(float)); c_dout = (float *) malloc(ntchm*sizeof(float)); c_tm = (float *) malloc(ntchm*sizeof(float)); c_gt = (float *) malloc(ntchm*sizeof(float)); c_sa = (float *) malloc(ntchm*sizeof(float)); c_r = (float *) malloc(ntchm*sizeof(float)); c_te = (float *) malloc(ntchm*sizeof(float)); } bag_id = (int *) malloc(num*sizeof(int)); nspec = (int *) malloc(num*sizeof(int)); nparts = (int *) malloc(num*sizeof(int)); if(lsda_read(handle,LSDA_INT,"ids",0,num,bag_id) != num) { for(i=0; i<num; i++) bag_id[i] = i+1; } lsda_read(handle,LSDA_INT,"nspec", 0,num,nspec ); lsda_read(handle,LSDA_INT,"nparts",0,num,nparts); numtot=0; for(i=0; i<num; i++) numtot += nparts[i]; numspectot=0; for(i=0; i<num; i++) numspectot += nparts[i] * (nspec[i]+1); part_id = (int *) malloc(numtot*sizeof(int)); part_type = (int *) malloc(numtot*sizeof(int)); lsda_read(handle,LSDA_INT,"pid" ,0,numtot,part_id); lsda_read(handle,LSDA_INT,"ptype",0,numtot,part_type); v = (float *) malloc(num*sizeof(float)); p = (float *) malloc(num*sizeof(float)); ie = (float *) malloc(num*sizeof(float)); din = (float *) malloc(num*sizeof(float)); den = (float *) malloc(num*sizeof(float)); dout = (float *) malloc(num*sizeof(float)); tm = (float *) malloc(num*sizeof(float)); gt = (float *) malloc(num*sizeof(float)); sa = (float *) malloc(num*sizeof(float)); r = (float *) malloc(num*sizeof(float)); /* read in part and species data */ ppres = (float *) malloc(numtot*sizeof(float)); ppor_leak = (float *) malloc(numtot*sizeof(float)); pvent_leak = (float *) malloc(numtot*sizeof(float)); parea_tot = (float *) malloc(numtot*sizeof(float)); parea_unblocked = (float *) malloc(numtot*sizeof(float)); ptemp = (float *) malloc(numtot*sizeof(float)); ppresp = (float *) malloc(numtot*sizeof(float)); ppresm = (float *) malloc(numtot*sizeof(float)); pnt_spec = (float *) malloc(numspectot*sizeof(float)); /* open file and write header */ printf("Extracting PARTICLE GENERAL PG_STAT data\n"); sprintf(output_file,"%spg_stat",output_path); fp=fopen(output_file,"w"); write_message(fp,output_file); if (!fp) return 0; output_title(handle,"/pg_stat/metadata",fp); output_legend(handle,fp,1,1); if(nchm>0) { sprintf(output_file_tmp3,"%spgstat_chamber",output_path); fp_tmp3=fopen(output_file_tmp3,"w"); write_message(fp_tmp3,output_file_tmp3); output_title(handle,"/pg_stat/metadata",fp_tmp3); output_legend(handle,fp_tmp3,1,1); } sprintf(output_file_tmp1,"%spg_partdata_p.txt",output_path); fp_tmp1=fopen(output_file_tmp1,"w"); output_title(handle,"/pg_stat/metadata",fp_tmp1); output_legend(handle,fp_tmp1,1,1); fprintf(fp_tmp1," time\n PART ID pressure por_leak vent_leak part_area unblk_area temperature\n press s+ press s-\n\n"); numvent=jj=kk=0; for(i=0; i<num; i++) { if(nspec[i]>0) for(k=0;k<nparts[i];k++) if(part_type[kk+k] >= 3) numvent++; kk += nparts[i]; jj += nspec[i]+1; } if(numvent) { sprintf(output_file_tmp2,"%spg_partdata_sp.txt",output_path); fp_tmp2=fopen(output_file_tmp2,"w"); output_title(handle,"/pg_stat/metadata",fp_tmp2); output_legend(handle,fp_tmp2,1,1); fprintf(fp_tmp2," time\n PART ID dmout/dt\n\n"); } /* Loop through time states and write each one. */ for(state=1; (dp = next_dir(handle,"/pg_stat",dp,dname)) != NULL; state++) { if(lsda_read(handle,LSDA_FLOAT,"time", 0, 1,&time) != 1) break; if(lsda_read(handle,LSDA_FLOAT,"volume", 0,num, v) != num) break; if(lsda_read(handle,LSDA_FLOAT,"pressure", 0,num, p) != num) break; if(lsda_read(handle,LSDA_FLOAT,"internal_energy",0,num, ie) != num) break; if(lsda_read(handle,LSDA_FLOAT,"dm_dt_in", 0,num, din) != num) break; if(lsda_read(handle,LSDA_FLOAT,"density", 0,num, den) != num) break; if(lsda_read(handle,LSDA_FLOAT,"dm_dt_out", 0,num, dout) != num) break; if(lsda_read(handle,LSDA_FLOAT,"total_mass", 0,num, tm) != num) break; if(lsda_read(handle,LSDA_FLOAT,"gas_temp", 0,num, gt) != num) break; if(lsda_read(handle,LSDA_FLOAT,"surface_area", 0,num, sa) != num) break; if(lsda_read(handle,LSDA_FLOAT,"reaction", 0,num, r) != num) break; fprintf(fp,"\n\n time airbag/cv # volume pressure internal energy"); fprintf(fp," dm/dt in density dm/dt out total mass gas temp. surface area"); fprintf(fp," reaction\n"); k=0; for(i=0; i<num; i++) { fprintf(fp,"%12.5E%8d%15.4E%15.4E%15.4E%15.4E%15.4E", time,bag_id[i],v[i],p[i],ie[i],din[i],den[i]); fprintf(fp,"%11.3E%11.3E%11.3E%11.3E%11.3E\n", dout[i],tm[i],gt[i],sa[i],r[i]); } sprintf(dirname,"/pg_stat/%s/bag_data",dname); lsda_queryvar(handle,dirname,&typid,&length,&filenum); if(typid != 0) break; lsda_cd(handle,dirname); lsda_read(handle,LSDA_FLOAT,"pressure", 0,numtot,ppres); lsda_read(handle,LSDA_FLOAT,"por_leak", 0,numtot,ppor_leak); lsda_read(handle,LSDA_FLOAT,"vent_leak", 0,numtot,pvent_leak); lsda_read(handle,LSDA_FLOAT,"area_tot", 0,numtot,parea_tot); lsda_read(handle,LSDA_FLOAT,"area_unblocked",0,numtot,parea_unblocked); lsda_read(handle,LSDA_FLOAT,"temperature", 0,numtot,ptemp); lsda_read(handle,LSDA_FLOAT,"pres+", 0,numtot,ppresp); lsda_read(handle,LSDA_FLOAT,"pres-", 0,numtot,ppresm); fprintf(fp_tmp1,"%12.4E\n",time); for(i=0; i<numtot; i++) { fprintf(fp_tmp1,"%8d%12.4E%12.4E%12.4E%12.4E%12.4E%12.4E\n %12.4E%12.4E\n", part_id[i],ppres[i],ppor_leak[i],pvent_leak[i],parea_tot[i], parea_unblocked[i],ptemp[i],ppresp[i],ppresm[i]); } if(numvent) { lsda_read(handle,LSDA_FLOAT,"nt_species",0,numspectot,pnt_spec); fprintf(fp_tmp2,"%12.4E\n",time); jj=kk=0; for(i=0; i<num; i++) { if(nspec[i]>0) { for(k=0; k<nparts[i]; k++) { if(part_type[kk+k] >= 3) { fprintf(fp_tmp2,"%8d%12.4E",part_id[kk+k],ptemp[kk+k]); for(j=0;j<=nspec[i];j++) fprintf(fp_tmp2,"%12.4E",pnt_spec[jj+j]); fprintf(fp_tmp2,"\n"); } } } kk += nparts[i]; jj += nspec[i]+1; } } if(nchm>0) { sprintf(dirname,"/pg_stat/%s/chamber_data",dname); lsda_queryvar(handle,dirname,&typid,&length,&filenum); if(typid != 0) break; lsda_cd(handle,dirname); if(lsda_read(handle,LSDA_FLOAT,"volume", 0,ntchm, c_v) != ntchm) break; if(lsda_read(handle,LSDA_FLOAT,"pressure", 0,ntchm, c_p) != ntchm) break; if(lsda_read(handle,LSDA_FLOAT,"internal_energy",0,ntchm, c_ie) != ntchm) break; if(lsda_read(handle,LSDA_FLOAT,"dm_dt_in", 0,ntchm, c_din) != ntchm) break; if(lsda_read(handle,LSDA_FLOAT,"density", 0,ntchm, c_den) != ntchm) break; if(lsda_read(handle,LSDA_FLOAT,"dm_dt_out", 0,ntchm,c_dout) != ntchm) break; if(lsda_read(handle,LSDA_FLOAT,"total_mass", 0,ntchm, c_tm) != ntchm) break; if(lsda_read(handle,LSDA_FLOAT,"gas_temp", 0,ntchm, c_gt) != ntchm) break; if(lsda_read(handle,LSDA_FLOAT,"surface_area", 0,ntchm, c_sa) != ntchm) break; if(lsda_read(handle,LSDA_FLOAT,"reaction", 0,ntchm, c_r) != ntchm) break; if(lsda_read(handle,LSDA_FLOAT,"transE", 0,ntchm, c_te) != ntchm) break; fprintf(fp_tmp3,"\n\n time airbag/cv # volume pressure internal energy"); fprintf(fp_tmp3," dm/dt in density dm/dt out total mass gas temp. surface area"); fprintf(fp_tmp3," reaction Trans E\n"); for(i=0; i<ntchm; i++) { for(j=0; j<ntchm; j++) if(chm_iid[j]==i+1) { fprintf(fp_tmp3,"%12.5E%8d%15.4E%15.4E%15.4E%15.4E%15.4E", time,chm_uid[j],c_v[i],c_p[i],c_ie[i],c_din[i],c_den[i]); fprintf(fp_tmp3,"%11.3E%11.3E%11.3E%11.3E%11.3E%11.3E\n", c_dout[i],c_tm[i],c_gt[i],c_sa[i],c_r[i],c_te[i]); } } } } fclose(fp); fclose(fp_tmp1); if(numvent) fclose(fp_tmp2); free(r); free(sa); free(gt); free(tm); free(dout); free(den); free(din); free(ie); free(p); free(v); free(ppres); free(ppor_leak); free(pvent_leak); free(parea_tot); free(parea_unblocked); free(ptemp); free(pnt_spec); free(part_type); free(part_id); free(nparts); free(nspec); free(bag_id); if(nchm>0) { fclose(fp_tmp3); free(c_te); free(c_r); free(c_sa); free(c_gt); free(c_tm); free(c_dout); free(c_den); free(c_din); free(c_ie); free(c_p); free(c_v); free(chm_uid); free(chm_iid); free(nbag_c); } printf(" %d states extracted\n",state-1); return 1; } /* PG_SENSOR file */ int translate_pg_sensor(int handle) { int i,state,nsensor,revision,newformat; LSDA_Length length; FILE *fp; float time,*dens,*pres,*temp,*velx,*vely,*velz,*velr,*xpos,*ypos,*zpos,*part; char dirname[256]; char name[15],*rev; LSDADir *dp = NULL; if (lsda_cd(handle,"/pg_sensor/metadata") == -1) return 0; /* Read metadata */ rev = (char *)malloc(10); lsda_read(handle,LSDA_I1,"../metadata/revision",0,10,rev); revision = atoi(rev); free(rev); lsda_read(handle,LSDA_INT,"../metadata/n_bags",0,1,&newformat); if (revision > 48400) { if (newformat != 0) { translate_pg_sensor_new(handle); return 0; } } lsda_read(handle,LSDA_INT,"../metadata/nsensor",0,1,&nsensor); printf("Extracting PG_SENSOR data\n"); velr = (float *) malloc(nsensor*sizeof(float)); velx = (float *) malloc(nsensor*sizeof(float)); vely = (float *) malloc(nsensor*sizeof(float)); velz = (float *) malloc(nsensor*sizeof(float)); temp = (float *) malloc(nsensor*sizeof(float)); pres = (float *) malloc(nsensor*sizeof(float)); dens = (float *) malloc(nsensor*sizeof(float)); xpos = (float *) malloc(nsensor*sizeof(float)); ypos = (float *) malloc(nsensor*sizeof(float)); zpos = (float *) malloc(nsensor*sizeof(float)); part = (float *) malloc(nsensor*sizeof(float)); /* open file and write header */ sprintf(output_file,"%spg_sensor",output_path); fp=fopen(output_file,"w"); write_message(fp,output_file); if (!fp) return 0; fprintf(fp,"Particle general sensor file\n"); fprintf(fp,"%5d%5d\n",nsensor,16); fprintf(fp," time\n"); fprintf(fp," x y z\n"); fprintf(fp," vx vy vz\n"); fprintf(fp," pres dens temp npart\n\n\n"); /* Loop through time states and write each one */ for(state=1; (dp = next_dir(handle,"/pg_sensor",dp,dirname)) != NULL; state++) { if(lsda_read(handle,LSDA_FLOAT,"time",0,1,&time) != 1) break; if(lsda_read(handle,LSDA_FLOAT,"ave_velx",0,nsensor,velx) != nsensor) break; if(lsda_read(handle,LSDA_FLOAT,"ave_vely",0,nsensor,vely) != nsensor) break; if(lsda_read(handle,LSDA_FLOAT,"ave_velz",0,nsensor,velz) != nsensor) break; if(lsda_read(handle,LSDA_FLOAT,"ave_velr",0,nsensor,velr) != nsensor) break; if(lsda_read(handle,LSDA_FLOAT,"temp",0,nsensor,temp) != nsensor) break; if(lsda_read(handle,LSDA_FLOAT,"rho",0,nsensor,dens) != nsensor) break; if(lsda_read(handle,LSDA_FLOAT,"pressure",0,nsensor,pres) != nsensor) break; if(lsda_read(handle,LSDA_FLOAT,"sensor_x",0,nsensor,xpos) != nsensor) break; if(lsda_read(handle,LSDA_FLOAT,"sensor_y",0,nsensor,ypos) != nsensor) break; if(lsda_read(handle,LSDA_FLOAT,"sensor_z",0,nsensor,zpos) != nsensor) break; if(lsda_read(handle,LSDA_FLOAT,"npart",0,nsensor,part) != nsensor) break; fprintf(fp,"%13.5E\n",time); for (i=0; i<nsensor; i++) { fprintf(fp,"%13.5E%13.5E%13.5E\n",xpos[i],ypos[i],zpos[i]); fprintf(fp,"%13.5E%13.5E%13.5E%13.5E\n",velx[i],vely[i],velz[i],velr[i]); fprintf(fp,"%13.5E%13.5E%13.5E%13d\n",pres[i],dens[i],temp[i],(int) part[i]); } } fclose(fp); free(part); free(zpos); free(ypos); free(xpos); free(dens); free(pres); free(temp); free(velz); free(vely); free(velx); free(velr); printf(" %d states extracted\n",state-1); return 0; } /* PG_SENSOR file with new format */ int translate_pg_sensor_new(int handle) { int i,j,k,state; FILE *fp; char dirname[256]; int npartgas,nhcpmsor,icpmsor_nd,ntotsor,nin; int *ids,*n_seg; float *dens,*pres,*temp,*velr,*velx,*vely,*velz,*xpos,*ypos,*zpos; float time; int m,mi,isensor; LSDADir *dp = NULL; if (lsda_cd(handle,"/pg_sensor/metadata") == -1) return 0; /* Read metadata */ lsda_read(handle,LSDA_INT,"n_bags",0,1,&npartgas); lsda_read(handle,LSDA_INT,"n_set_sensor",0,1,&nhcpmsor); lsda_read(handle,LSDA_INT,"n_struc",0,1,&icpmsor_nd); lsda_read(handle,LSDA_INT,"n_sensor",0,1,&ntotsor); nin = npartgas*nhcpmsor; ids = (int *) malloc(ntotsor*sizeof(int)); n_seg = (int *) malloc(nin*sizeof(int)); lsda_read(handle,LSDA_INT,"id_sensor",0,ntotsor,ids); lsda_read(handle,LSDA_INT,"n_seg_in_each_set",0,nin,n_seg); printf("Extracting PG_SENSOR from new database\n"); /* open file and write header */ sprintf(output_file,"%strhist_pg_sensor",output_path); fp=fopen(output_file,"w"); write_message(fp,output_file); if (!fp) return 0; fprintf(fp," CPM sensors output\n"); fprintf(fp," Number of sensors:%5d\n\n\n",ntotsor); fprintf(fp," id x y z velx vely\n"); fprintf(fp," velx velr temp dens pres\n"); /* Loop through time states and write each one */ velr = (float *) malloc(ntotsor*sizeof(float)); velx = (float *) malloc(ntotsor*sizeof(float)); vely = (float *) malloc(ntotsor*sizeof(float)); velz = (float *) malloc(ntotsor*sizeof(float)); temp = (float *) malloc(ntotsor*sizeof(float)); pres = (float *) malloc(ntotsor*sizeof(float)); dens = (float *) malloc(ntotsor*sizeof(float)); xpos = (float *) malloc(ntotsor*sizeof(float)); ypos = (float *) malloc(ntotsor*sizeof(float)); zpos = (float *) malloc(ntotsor*sizeof(float)); for(state=1; (dp = next_dir(handle,"/pg_sensor",dp,dirname)) != NULL; state++) { if(lsda_read(handle,LSDA_FLOAT,"time",0,1,&time) != 1) break; fprintf(fp," time=%13.5E\n",time); lsda_read(handle,LSDA_FLOAT,"ave_velx",0,ntotsor,velx); lsda_read(handle,LSDA_FLOAT,"ave_vely",0,ntotsor,vely); lsda_read(handle,LSDA_FLOAT,"ave_velz",0,ntotsor,velz); lsda_read(handle,LSDA_FLOAT,"ave_velr",0,ntotsor,velr); lsda_read(handle,LSDA_FLOAT,"temp",0,ntotsor,temp); lsda_read(handle,LSDA_FLOAT,"rho",0,ntotsor,dens); lsda_read(handle,LSDA_FLOAT,"pressure",0,ntotsor,pres); lsda_read(handle,LSDA_FLOAT,"sensor_x",0,ntotsor,xpos); lsda_read(handle,LSDA_FLOAT,"sensor_y",0,ntotsor,ypos); lsda_read(handle,LSDA_FLOAT,"sensor_z",0,ntotsor,zpos); k=m=0; for(i=1;i<=npartgas;i++) { for(j=1;j<=nhcpmsor;j++) { if(n_seg[k] != 0) { fprintf(fp," Bag ID, Sensor set:%10d%10d\n",i,j); for(isensor=0; isensor<n_seg[k];isensor++){ mi=m+isensor; fprintf(fp,"%10d%14.4e%14.4e%14.4e%14.4e%14.4e\n", ids[mi],xpos[mi],ypos[mi],zpos[mi],velx[mi],vely[mi]); fprintf(fp," %14.4e%14.4e%14.4e%14.4e%14.4e\n", velz[mi],velr[mi],temp[mi],dens[mi],pres[mi]); } fprintf(fp,"\n"); m += n_seg[k]; } k++; } } } fclose(fp); printf(" %d states extracted\n",state-1); free(velr); free(velx); free(vely); free(velz); free(temp); free(pres); free(dens); free(xpos); free(ypos); free(zpos); return 0; } /* NODFOR file */ int translate_nodfor(int handle) { int i,j,n,typid,filenum,state; LSDA_Length length; char dirname[256]; int *ids, *gids, *groups, *local; int nnodes, ngroups, have_local; float *xf,*yf,*zf,*e,*xt,*yt,*zt,*et,*xl,*yl,*zl; float time; FILE *fp; LSDADir *dp = NULL; if (lsda_cd(handle,"/nodfor/metadata") == -1) return 0; /* Read metadata */ lsda_queryvar(handle,"ids",&typid,&length,&filenum); if(typid < 0) return 0; nnodes = length; lsda_queryvar(handle,"groups",&typid,&length,&filenum); ngroups = length; ids = (int *) malloc(nnodes*sizeof(int)); local = (int *) malloc(nnodes*sizeof(int)); groups= (int *) malloc(ngroups*sizeof(int)); xf = (float *) malloc(nnodes*sizeof(float)); yf = (float *) malloc(nnodes*sizeof(float)); zf = (float *) malloc(nnodes*sizeof(float)); e = (float *) malloc(nnodes*sizeof(float)); xt = (float *) malloc(nnodes*sizeof(float)); yt = (float *) malloc(nnodes*sizeof(float)); zt = (float *) malloc(nnodes*sizeof(float)); et = (float *) malloc(nnodes*sizeof(float)); lsda_read(handle,LSDA_INT,"ids",0,nnodes,ids); lsda_read(handle,LSDA_INT,"local",0,ngroups,local); lsda_read(handle,LSDA_INT,"groups",0,ngroups,groups); for(i=have_local=0; !have_local && i<ngroups; i++) if(local[i] > 0) have_local=1; if(have_local) { xl = (float *) malloc(ngroups*sizeof(float)); yl = (float *) malloc(ngroups*sizeof(float)); zl = (float *) malloc(ngroups*sizeof(float)); } lsda_queryvar(handle,"legend_ids",&typid,&length,&filenum); if(typid > 0) { gids = (int *) malloc(ngroups*sizeof(int)); lsda_read(handle,LSDA_INT,"legend_ids",0,ngroups,gids); } else { gids=NULL; } /* open file and write header */ printf("Extracting NODFOR data\n"); sprintf(output_file,"%snodfor",output_path); fp=fopen(output_file,"w"); write_message(fp,output_file); if (!fp) return 0; output_title(handle,"/nodfor/metadata",fp); output_legend(handle,fp,1,1); /* Loop through time states and write each one. */ for(state=1; (dp = next_dir(handle,"/nodfor",dp,dirname)) != NULL; state++) { if(lsda_read(handle,LSDA_FLOAT,"time", 0, 1,&time) != 1) break; if(lsda_read(handle,LSDA_FLOAT,"xforce" ,0, nnodes,xf) != nnodes && lsda_read(handle,LSDA_FLOAT,"x_force",0, nnodes,xf) != nnodes) break; if(lsda_read(handle,LSDA_FLOAT,"yforce" ,0, nnodes,yf) != nnodes && lsda_read(handle,LSDA_FLOAT,"y_force",0, nnodes,yf) != nnodes) break; if(lsda_read(handle,LSDA_FLOAT,"zforce" ,0, nnodes,zf) != nnodes && lsda_read(handle,LSDA_FLOAT,"z_force",0, nnodes,zf) != nnodes) break; if(lsda_read(handle,LSDA_FLOAT,"energy",0, nnodes, e) != nnodes) break; if(lsda_read(handle,LSDA_FLOAT,"xtotal" ,0, ngroups,xt) != ngroups && lsda_read(handle,LSDA_FLOAT,"x_total",0, ngroups,xt) != ngroups) break; if(lsda_read(handle,LSDA_FLOAT,"ytotal" ,0, ngroups,yt) != ngroups && lsda_read(handle,LSDA_FLOAT,"y_total",0, ngroups,yt) != ngroups) break; if(lsda_read(handle,LSDA_FLOAT,"ztotal" ,0, ngroups,zt) != ngroups && lsda_read(handle,LSDA_FLOAT,"z_total",0, ngroups,zt) != ngroups) break; if(lsda_read(handle,LSDA_FLOAT,"etotal",0,ngroups,et) != ngroups) break; if(have_local) { if(lsda_read(handle,LSDA_FLOAT,"xlocal" ,0,ngroups,xl) != ngroups && lsda_read(handle,LSDA_FLOAT,"x_local",0,ngroups,xl) != ngroups) break; if(lsda_read(handle,LSDA_FLOAT,"ylocal" ,0,ngroups,yl) != ngroups && lsda_read(handle,LSDA_FLOAT,"y_local",0,ngroups,yl) != ngroups) break; if(lsda_read(handle,LSDA_FLOAT,"zlocal" ,0,ngroups,zl) != ngroups && lsda_read(handle,LSDA_FLOAT,"z_local",0,ngroups,zl) != ngroups) break; } fprintf(fp,"\n\n\n\n\n n o d a l f o r c e g r o u p"); fprintf(fp," o u t p u t t=%9.3E\n",time); for(i=j=0; i<ngroups; i++) { fprintf(fp,"\n\n\n\n\n nodal group output number %2d\n\n",i+1); for(n=0; n<groups[i]; n++,j++) { fprintf(fp," nd#%8d xforce=%13.4E yforce=%13.4E zforce=%13.4E energy=%13.4E", ids[j],xf[j],yf[j],zf[j],e[j]); if(gids) fprintf(fp," setid =%8d",gids[i]); fprintf(fp,"\n"); } fprintf(fp," xtotal=%13.4E ytotal=%13.4E ztotal=%13.4E etotal=%13.4E\n", xt[i],yt[i],zt[i],et[i]); if(local[i] > 0) { fprintf(fp," xlocal=%13.4E ylocal=%13.4E zlocal=%13.4E\n", xl[i],yl[i],zl[i]); } } } fclose(fp); if(have_local) { free(zl); free(yl); free(xl); } free(et); free(zt); free(yt); free(xt); free(e); free(zf); free(yf); free(xf); free(groups); free(local); free(ids); if(gids) free(gids); printf(" %d states extracted\n",state-1); return 1; } /* BNDOUT file */ int translate_bndout(int handle) { int i,k,header,typid,filenum,state; LSDA_Length length; int have_dn,have_dr,have_p,have_vn,have_vr,have_or; FILE *fp; BND_DATA dn,dr,p,vn,vr,or; float xt,yt,zt,et; char title_dir[128]; lsda_queryvar(handle,"/bndout/discrete/nodes",&typid,&length,&filenum); have_dn= (typid >= 0); lsda_queryvar(handle,"/bndout/discrete/rigidbodies",&typid,&length,&filenum); have_dr= (typid >= 0); lsda_queryvar(handle,"/bndout/pressure",&typid,&length,&filenum); have_p= (typid >= 0); lsda_queryvar(handle,"/bndout/velocity/nodes",&typid,&length,&filenum); have_vn= (typid >= 0); lsda_queryvar(handle,"/bndout/velocity/rigidbodies",&typid,&length,&filenum); have_vr= (typid >= 0); lsda_queryvar(handle,"/bndout/orientation/rigidbodies",&typid,&length,&filenum); have_or= (typid >= 0); /* Read metadata */ title_dir[0]=0; if(have_dn) { lsda_cd(handle,"/bndout/discrete/nodes/metadata"); strcpy(title_dir,"/bndout/discrete/nodes/metadata"); lsda_queryvar(handle,"ids",&typid,&length,&filenum); dn.num = length; dn.ids = (int *) malloc(dn.num*sizeof(int)); dn.xf = (float *) malloc(4*dn.num*sizeof(float)); dn.yf = dn.xf + dn.num; dn.zf = dn.yf + dn.num; dn.e = dn.zf + dn.num; lsda_read(handle,LSDA_INT,"ids",0,dn.num,dn.ids); } if(have_dr) { lsda_cd(handle,"/bndout/discrete/rigidbodies/metadata"); strcpy(title_dir,"/bndout/discrete/rigidbodies/metadata"); lsda_queryvar(handle,"ids",&typid,&length,&filenum); dr.num = length; dr.ids = (int *) malloc(dr.num*sizeof(int)); dr.xf = (float *) malloc(4*dr.num*sizeof(float)); dr.yf = dr.xf + dr.num; dr.zf = dr.yf + dr.num; dr.e = dr.zf + dr.num; lsda_read(handle,LSDA_INT,"ids",0,dr.num,dr.ids); } if(have_p) { lsda_cd(handle,"/bndout/pressure/metadata"); strcpy(title_dir,"/bndout/pressure/metadata"); lsda_queryvar(handle,"ids",&typid,&length,&filenum); p.num = length; p.ids = (int *) malloc(p.num*sizeof(int)); p.xf = (float *) malloc(4*p.num*sizeof(float)); p.yf = p.xf + p.num; p.zf = p.yf + p.num; p.e = p.zf + p.num; lsda_read(handle,LSDA_INT,"ids",0,p.num,p.ids); } if(have_vn) { lsda_cd(handle,"/bndout/velocity/nodes/metadata"); strcpy(title_dir,"/bndout/velocity/nodes/metadata"); lsda_queryvar(handle,"ids",&typid,&length,&filenum); vn.num = length; vn.ids = (int *) malloc(vn.num*sizeof(int)); vn.setid = (int *) malloc(vn.num*sizeof(int)); vn.xf = (float *) malloc(4*vn.num*sizeof(float)); vn.yf = vn.xf + vn.num; vn.zf = vn.yf + vn.num; vn.e = vn.zf + vn.num; lsda_read(handle,LSDA_INT,"ids",0,vn.num,vn.ids); lsda_read(handle,LSDA_INT,"setid",0,vn.num,vn.setid); } if(have_vr) { lsda_cd(handle,"/bndout/velocity/rigidbodies/metadata"); strcpy(title_dir,"/bndout/velocity/rigidbodies/metadata"); lsda_queryvar(handle,"ids",&typid,&length,&filenum); vr.num = length; vr.ids = (int *) malloc(vr.num*sizeof(int)); vr.xf = (float *) malloc(7*vr.num*sizeof(float)); vr.yf = vr.xf + vr.num; vr.zf = vr.yf + vr.num; vr.e = vr.zf + vr.num; vr.xm = vr.e + vr.num; vr.ym = vr.xm + vr.num; vr.zm = vr.ym + vr.num; lsda_read(handle,LSDA_INT,"ids",0,vr.num,vr.ids); } if(have_or) { lsda_cd(handle,"/bndout/orientation/rigidbodies/metadata"); strcpy(title_dir,"/bndout/orientation/rigidbodies/metadata"); lsda_queryvar(handle,"ids",&typid,&length,&filenum); or.num = length; or.ids = (int *) malloc(or.num*sizeof(int)); or.xf = (float *) malloc(7*or.num*sizeof(float)); or.yf = or.xf + or.num; or.zf = or.yf + or.num; or.e = or.zf + or.num; or.xm = or.e + or.num; or.ym = or.xm + or.num; or.zm = or.ym + or.num; lsda_read(handle,LSDA_INT,"ids",0,or.num,or.ids); } if(strlen(title_dir) == 0) return 0; /* huh? */ /* open file and write header */ printf("Extracting BNDOUT data\n"); sprintf(output_file,"%sbndout",output_path); fp=fopen(output_file,"w"); write_message(fp,output_file); if (!fp) return 0; output_title(handle,title_dir,fp); k=0; if(have_vn) { lsda_cd(handle,"/bndout/velocity/nodes/metadata"); i = have_vr ? 0 : 1; k = 1; output_legend(handle,fp,1,i); } if(have_vr) { lsda_cd(handle,"/bndout/velocity/rigidbodies/metadata"); i = !k; output_legend(handle,fp,i,1); } if(have_or) { lsda_cd(handle,"/bndout/orientation/rigidbodies/metadata"); i = !k; output_legend(handle,fp,i,1); } /* Loop through time states and write each one */ for(state=1; ; state++) { header=0; xt = yt = zt = et = 0.; if(have_dn && ! bndout_dn(fp,handle,state,&dn,&xt,&yt,&zt,&et,&header)) break; if(have_dr && ! bndout_dr(fp,handle,state,&dr,&xt,&yt,&zt,&et,&header)) break; if(have_dn || have_dr) { fprintf(fp," xtotal=%13.4E ytotal=%13.4E ztotal=%13.4E etotal=%13.4E\n", xt,yt,zt,et); } if(have_p && ! bndout_p(fp,handle,state,&p,&header)) break; xt = yt = zt = et = 0.; if(have_vn && ! bndout_vn(fp,handle,state,&vn,&xt,&yt,&zt,&et,&header)) break; if(have_vr && ! bndout_vr(fp,handle,state,&vr,&xt,&yt,&zt,&et,&header)) break; if(have_vn || have_vr) { fprintf(fp," xtotal=%13.4E ytotal=%13.4E ztotal=%13.4E etotal=%13.4E\n", xt,yt,zt,et); if(have_or && ! bndout_or(fp,handle,state,&or,&xt,&yt,&zt,&et,&header)) break; } } fclose(fp); /* free everything here.... */ if(have_dn) { free(dn.ids); free(dn.xf); } if(have_dr) { free(dr.ids); free(dr.xf); } if(have_p) { free(p.ids); free(p.xf); } if(have_vn) { free(vn.ids); free(vn.xf); free(vn.setid); } if(have_vr) { free(vr.ids); free(vr.xf); } printf(" %d states extracted\n",state-1); return 0; } int bndout_dn(FILE *fp,int handle, int state, BND_DATA *dn, float *xt, float *yt, float *zt, float *et, int *header) { char dirname[128]; float time; int typid, filenum; LSDA_Length length; int i; if(state<=999999) sprintf(dirname,"/bndout/discrete/nodes/d%6.6d",state); else sprintf(dirname,"/bndout/discrete/nodes/d%8.8d",state); lsda_queryvar(handle,dirname,&typid,&length,&filenum); if(typid != 0) return 0; lsda_cd(handle,dirname); if(lsda_read(handle,LSDA_FLOAT,"time",0,1,&time) != 1) return 0; if(lsda_read(handle,LSDA_FLOAT,"xforce" ,0,dn->num,dn->xf) != dn->num && lsda_read(handle,LSDA_FLOAT,"x_force",0,dn->num,dn->xf) != dn->num) return 0; if(lsda_read(handle,LSDA_FLOAT,"yforce" ,0,dn->num,dn->yf) != dn->num && lsda_read(handle,LSDA_FLOAT,"y_force",0,dn->num,dn->yf) != dn->num) return 0; if(lsda_read(handle,LSDA_FLOAT,"zforce" ,0,dn->num,dn->zf) != dn->num && lsda_read(handle,LSDA_FLOAT,"z_force",0,dn->num,dn->zf) != dn->num) return 0; if(lsda_read(handle,LSDA_FLOAT,"energy",0,dn->num,dn->e) != dn->num) return 0; if(lsda_read(handle,LSDA_FLOAT,"xtotal" ,0,1,xt) != 1 && lsda_read(handle,LSDA_FLOAT,"x_total",0,1,xt) != 1) return 0; if(lsda_read(handle,LSDA_FLOAT,"ytotal" ,0,1,yt) != 1 && lsda_read(handle,LSDA_FLOAT,"y_total",0,1,yt) != 1) return 0; if(lsda_read(handle,LSDA_FLOAT,"ztotal" ,0,1,zt) != 1 && lsda_read(handle,LSDA_FLOAT,"z_total",0,1,zt) != 1) return 0; if(lsda_read(handle,LSDA_FLOAT,"etotal",0,1,et) != 1) return 0; /* Output data */ fprintf(fp,"\n\n\n\n\n n o d a l f o r c e/e n e r g y"); fprintf(fp," o u t p u t t=%9.3E\n",time); *header = 1; fprintf(fp,"\n\n\n\n\n discrete nodal point forces \n\n"); for(i=0; i<dn->num; i++) { fprintf(fp," nd#%8d xforce=%13.4E yforce=%13.4E zforce=%13.4E energy=%13.4E\n", dn->ids[i],dn->xf[i],dn->yf[i],dn->zf[i],dn->e[i]); } return 1; } int bndout_dr(FILE *fp,int handle, int state, BND_DATA *dn, float *xtt, float *ytt, float *ztt, float *ett, int *header) { char dirname[128]; float time; int typid, filenum; LSDA_Length length; float xt,yt,zt,et; int i; if(state<=999999) sprintf(dirname,"/bndout/discrete/rigidbodies/d%6.6d",state); else sprintf(dirname,"/bndout/discrete/rigidbodies/d%8.8d",state); lsda_queryvar(handle,dirname,&typid,&length,&filenum); if(typid != 0) return 0; lsda_cd(handle,dirname); if(lsda_read(handle,LSDA_FLOAT,"time",0,1,&time) != 1) return 0; if(lsda_read(handle,LSDA_FLOAT,"xforce" ,0,dn->num,dn->xf) != dn->num && lsda_read(handle,LSDA_FLOAT,"x_force",0,dn->num,dn->xf) != dn->num) return 0; if(lsda_read(handle,LSDA_FLOAT,"yforce" ,0,dn->num,dn->yf) != dn->num && lsda_read(handle,LSDA_FLOAT,"y_force",0,dn->num,dn->yf) != dn->num) return 0; if(lsda_read(handle,LSDA_FLOAT,"zforce" ,0,dn->num,dn->zf) != dn->num && lsda_read(handle,LSDA_FLOAT,"z_force",0,dn->num,dn->zf) != dn->num) return 0; if(lsda_read(handle,LSDA_FLOAT,"energy",0,dn->num,dn->e) != dn->num) return 0; if(lsda_read(handle,LSDA_FLOAT,"xtotal" ,0,1,&xt) != 1 && lsda_read(handle,LSDA_FLOAT,"x_total",0,1,&xt) != 1) return 0; if(lsda_read(handle,LSDA_FLOAT,"ytotal" ,0,1,&yt) != 1 && lsda_read(handle,LSDA_FLOAT,"y_total",0,1,&yt) != 1) return 0; if(lsda_read(handle,LSDA_FLOAT,"ztotal" ,0,1,&zt) != 1 && lsda_read(handle,LSDA_FLOAT,"z_total",0,1,&zt) != 1) return 0; if(lsda_read(handle,LSDA_FLOAT,"etotal",0,1,&et) != 1) return 0; *xtt += xt; *ytt += yt; *ztt += zt; *ett += et; /* Output data */ if(! *header) { fprintf(fp,"\n\n\n\n\n n o d a l f o r c e/e n e r g y"); fprintf(fp," o u t p u t t=%9.3E\n",time); fprintf(fp,"\n\n\n\n\n discrete nodal point forces \n\n"); } *header = 2; for(i=0; i<dn->num; i++) { fprintf(fp," mt#%8d xforce=%13.4E yforce=%13.4E zforce=%13.4E energy=%13.4E\n", dn->ids[i],dn->xf[i],dn->yf[i],dn->zf[i],dn->e[i]); } return 1; } int bndout_p(FILE *fp,int handle, int state, BND_DATA *dn, int *header) { char dirname[128]; float time; int typid, filenum; LSDA_Length length; float xt,yt,zt,et; int i; if(state<=999999) sprintf(dirname,"/bndout/pressure/d%6.6d",state); else sprintf(dirname,"/bndout/pressure/d%8.8d",state); lsda_queryvar(handle,dirname,&typid,&length,&filenum); if(typid != 0) return 0; lsda_cd(handle,dirname); if(lsda_read(handle,LSDA_FLOAT,"time",0,1,&time) != 1) return 0; if(lsda_read(handle,LSDA_FLOAT,"xforce" ,0,dn->num,dn->xf) != dn->num && lsda_read(handle,LSDA_FLOAT,"x_force",0,dn->num,dn->xf) != dn->num) return 0; if(lsda_read(handle,LSDA_FLOAT,"yforce" ,0,dn->num,dn->yf) != dn->num && lsda_read(handle,LSDA_FLOAT,"y_force",0,dn->num,dn->yf) != dn->num) return 0; if(lsda_read(handle,LSDA_FLOAT,"zforce" ,0,dn->num,dn->zf) != dn->num && lsda_read(handle,LSDA_FLOAT,"z_force",0,dn->num,dn->zf) != dn->num) return 0; if(lsda_read(handle,LSDA_FLOAT,"energy",0,dn->num,dn->e) != dn->num) return 0; if(lsda_read(handle,LSDA_FLOAT,"xtotal" ,0,1,&xt) != 1 && lsda_read(handle,LSDA_FLOAT,"x_total",0,1,&xt) != 1) return 0; if(lsda_read(handle,LSDA_FLOAT,"ytotal" ,0,1,&yt) != 1 && lsda_read(handle,LSDA_FLOAT,"y_total",0,1,&yt) != 1) return 0; if(lsda_read(handle,LSDA_FLOAT,"ztotal" ,0,1,&zt) != 1 && lsda_read(handle,LSDA_FLOAT,"z_total",0,1,&zt) != 1) return 0; if(lsda_read(handle,LSDA_FLOAT,"etotal",0,1,&et) != 1) return 0; /* Output data */ fprintf(fp,"\n\n\n\n\n n o d a l f o r c e/e n e r g y"); fprintf(fp," o u t p u t t=%9.3E\n",time); *header = 3; fprintf(fp,"\n\n\n\n\n pressure boundary condition forces \n\n"); for(i=0; i<dn->num; i++) { fprintf(fp," nd#%8d xforce=%13.4E yforce=%13.4E zforce=%13.4E energy=%13.4E\n", dn->ids[i],dn->xf[i],dn->yf[i],dn->zf[i],dn->e[i]); } fprintf(fp," xtotal=%13.4E ytotal=%13.4E ztotal=%13.4E etotal=%13.4E\n", xt,yt,zt,et); return 1; } int bndout_vn(FILE *fp,int handle, int state, BND_DATA *dn, float *xt, float *yt, float *zt, float *et, int *header) { char dirname[128]; float time; int typid, filenum; LSDA_Length length; int i; if(state<=999999) sprintf(dirname,"/bndout/velocity/nodes/d%6.6d",state); else sprintf(dirname,"/bndout/velocity/nodes/d%8.8d",state); lsda_queryvar(handle,dirname,&typid,&length,&filenum); if(typid != 0) return 0; lsda_cd(handle,dirname); if(lsda_read(handle,LSDA_FLOAT,"time",0,1,&time) != 1) return 0; if(lsda_read(handle,LSDA_FLOAT,"xforce" ,0,dn->num,dn->xf) != dn->num && lsda_read(handle,LSDA_FLOAT,"x_force",0,dn->num,dn->xf) != dn->num) return 0; if(lsda_read(handle,LSDA_FLOAT,"yforce" ,0,dn->num,dn->yf) != dn->num && lsda_read(handle,LSDA_FLOAT,"y_force",0,dn->num,dn->yf) != dn->num) return 0; if(lsda_read(handle,LSDA_FLOAT,"zforce" ,0,dn->num,dn->zf) != dn->num && lsda_read(handle,LSDA_FLOAT,"z_force",0,dn->num,dn->zf) != dn->num) return 0; if(lsda_read(handle,LSDA_FLOAT,"energy",0,dn->num,dn->e) != dn->num) return 0; if(lsda_read(handle,LSDA_FLOAT,"xtotal" ,0,1,xt) != 1 && lsda_read(handle,LSDA_FLOAT,"x_total",0,1,xt) != 1) return 0; if(lsda_read(handle,LSDA_FLOAT,"ytotal" ,0,1,yt) != 1 && lsda_read(handle,LSDA_FLOAT,"y_total",0,1,yt) != 1) return 0; if(lsda_read(handle,LSDA_FLOAT,"ztotal" ,0,1,zt) != 1 && lsda_read(handle,LSDA_FLOAT,"z_total",0,1,zt) != 1) return 0; if(lsda_read(handle,LSDA_FLOAT,"etotal",0,1,et) != 1) return 0; /* Output data */ fprintf(fp,"\n\n\n\n\n n o d a l f o r c e/e n e r g y"); fprintf(fp," o u t p u t t=%9.3E\n",time); *header = 4; fprintf(fp,"\n\n\n\n\n velocity boundary condition forces/"); fprintf(fp,"rigid body moments \n\n"); for(i=0; i<dn->num; i++) { fprintf(fp," nd#%8d xforce=%13.4E yforce=%13.4E zforce=%13.4E energy=%13.4E setid =%8d\n", dn->ids[i],dn->xf[i],dn->yf[i],dn->zf[i],dn->e[i],dn->setid[i]); } return 1; } int bndout_vr(FILE *fp,int handle, int state, BND_DATA *dn, float *xtt, float *ytt, float *ztt, float *ett, int *header) { char dirname[128]; float time; int typid, filenum; LSDA_Length length; float xt,yt,zt,et; int i; if(state<=999999) sprintf(dirname,"/bndout/velocity/rigidbodies/d%6.6d",state); else sprintf(dirname,"/bndout/velocity/rigidbodies/d%8.8d",state); lsda_queryvar(handle,dirname,&typid,&length,&filenum); if(typid != 0) return 0; lsda_cd(handle,dirname); if(lsda_read(handle,LSDA_FLOAT,"time",0,1,&time) != 1) return 0; if(lsda_read(handle,LSDA_FLOAT,"xforce" ,0,dn->num,dn->xf) != dn->num && lsda_read(handle,LSDA_FLOAT,"x_force",0,dn->num,dn->xf) != dn->num) return 0; if(lsda_read(handle,LSDA_FLOAT,"yforce" ,0,dn->num,dn->yf) != dn->num && lsda_read(handle,LSDA_FLOAT,"y_force",0,dn->num,dn->yf) != dn->num) return 0; if(lsda_read(handle,LSDA_FLOAT,"zforce" ,0,dn->num,dn->zf) != dn->num && lsda_read(handle,LSDA_FLOAT,"z_force",0,dn->num,dn->zf) != dn->num) return 0; if(lsda_read(handle,LSDA_FLOAT,"energy",0,dn->num,dn->e) != dn->num) return 0; if(lsda_read(handle,LSDA_FLOAT,"xmoment",0,dn->num,dn->xm) != dn->num) return 0; if(lsda_read(handle,LSDA_FLOAT,"ymoment",0,dn->num,dn->ym) != dn->num) return 0; if(lsda_read(handle,LSDA_FLOAT,"zmoment",0,dn->num,dn->zm) != dn->num) return 0; if(lsda_read(handle,LSDA_FLOAT,"xtotal" ,0,1,&xt) != 1 && lsda_read(handle,LSDA_FLOAT,"x_total",0,1,&xt) != 1) return 0; if(lsda_read(handle,LSDA_FLOAT,"ytotal" ,0,1,&yt) != 1 && lsda_read(handle,LSDA_FLOAT,"y_total",0,1,&yt) != 1) return 0; if(lsda_read(handle,LSDA_FLOAT,"ztotal" ,0,1,&zt) != 1 && lsda_read(handle,LSDA_FLOAT,"z_total",0,1,&zt) != 1) return 0; if(lsda_read(handle,LSDA_FLOAT,"etotal",0,1,&et) != 1) return 0; *xtt += xt; *ytt += yt; *ztt += zt; *ett += et; /* Output data */ if(*header != 4) { fprintf(fp,"\n\n\n\n\n n o d a l f o r c e/e n e r g y"); fprintf(fp," o u t p u t t=%9.3E\n",time); fprintf(fp,"\n\n\n\n\n velocity boundary condition forces/"); fprintf(fp,"rigid body moments \n\n"); } *header = 5; for(i=0; i<dn->num; i++) { fprintf(fp,"mat#%8d xforce=%13.4E yforce=%13.4E zforce=%13.4E energy=%13.4E\n", dn->ids[i],dn->xf[i],dn->yf[i],dn->zf[i],dn->e[i]); fprintf(fp," xmoment=%13.4E ymoment=%13.4E zmoment=%13.4E\n", dn->xm[i],dn->ym[i],dn->zm[i]); } return 1; } /* BNDOUT - prescribed orientation start */ int bndout_or(FILE *fp,int handle, int state, BND_DATA *dn, float *xtt, float *ytt, float *ztt, float *ett, int *header) { char dirname[128]; float time; int typid, filenum; LSDA_Length length; float xt,yt,zt,et; int i; if(state<=999999) sprintf(dirname,"/bndout/orientation/rigidbodies/d%6.6d",state); else sprintf(dirname,"/bndout/orientation/rigidbodies/d%8.8d",state); lsda_queryvar(handle,dirname,&typid,&length,&filenum); if(typid != 0) return 0; lsda_cd(handle,dirname); if(lsda_read(handle,LSDA_FLOAT,"time",0,1,&time) != 1) return 0; if(lsda_read(handle,LSDA_FLOAT,"xforce" ,0,dn->num,dn->xf) != dn->num && lsda_read(handle,LSDA_FLOAT,"x_force",0,dn->num,dn->xf) != dn->num) return 0; if(lsda_read(handle,LSDA_FLOAT,"yforce" ,0,dn->num,dn->yf) != dn->num && lsda_read(handle,LSDA_FLOAT,"y_force",0,dn->num,dn->yf) != dn->num) return 0; if(lsda_read(handle,LSDA_FLOAT,"zforce" ,0,dn->num,dn->zf) != dn->num && lsda_read(handle,LSDA_FLOAT,"z_force",0,dn->num,dn->zf) != dn->num) return 0; if(lsda_read(handle,LSDA_FLOAT,"energy",0,dn->num,dn->e) != dn->num) return 0; if(lsda_read(handle,LSDA_FLOAT,"xmoment",0,dn->num,dn->xm) != dn->num) return 0; if(lsda_read(handle,LSDA_FLOAT,"ymoment",0,dn->num,dn->ym) != dn->num) return 0; if(lsda_read(handle,LSDA_FLOAT,"zmoment",0,dn->num,dn->zm) != dn->num) return 0; if(lsda_read(handle,LSDA_FLOAT,"xtotal" ,0,1,&xt) != 1 && lsda_read(handle,LSDA_FLOAT,"x_total",0,1,&xt) != 1) return 0; if(lsda_read(handle,LSDA_FLOAT,"ytotal" ,0,1,&yt) != 1 && lsda_read(handle,LSDA_FLOAT,"y_total",0,1,&yt) != 1) return 0; if(lsda_read(handle,LSDA_FLOAT,"ztotal" ,0,1,&zt) != 1 && lsda_read(handle,LSDA_FLOAT,"z_total",0,1,&zt) != 1) return 0; if(lsda_read(handle,LSDA_FLOAT,"etotal",0,1,&et) != 1) return 0; *xtt += xt; *ytt += yt; *ztt += zt; *ett += et; /* Output data */ if(*header != 4) { fprintf(fp,"\n\n\n\n\n n o d a l f o r c e/e n e r g y"); fprintf(fp," o u t p u t t=%9.3E\n",time); fprintf(fp,"\n\n\n\n\n orientation boundary condition rigid body moments \n\n"); } *header = 5; for(i=0; i<dn->num; i++) { fprintf(fp,"mat#%8d xmoment=%13.4E ymoment=%13.4E zmoment=%13.4E energy=%13.4E\n", dn->ids[i],dn->xm[i],dn->ym[i],dn->zm[i],dn->e[i]); } return 1; } /* BNDOUT - prescribed orientation end */ /* RBDOUT file */ int translate_rbdout(int handle) { int i,typid,num,filenum,state; LSDA_Length length; char dirname[256]; int num_nodal; int max_num; int *ids,cycle; float *gx,*gy,*gz; float *gdx,*gdy,*gdz,*grdx,*grdy,*grdz; float *gvx,*gvy,*gvz,*grvx,*grvy,*grvz; float *gax,*gay,*gaz,*grax,*gray,*graz; float *ldx,*ldy,*ldz,*lrdx,*lrdy,*lrdz; float *lvx,*lvy,*lvz,*lrvx,*lrvy,*lrvz; float *lax,*lay,*laz,*lrax,*lray,*lraz; float *d11,*d12,*d13,*d21,*d22,*d23,*d31,*d32,*d33; float time; FILE *fp; LSDADir *dp = NULL; if (lsda_cd(handle,"/rbdout/metadata") == -1) return 0; printf("Extracting RBDOUT data\n"); /* Read metadata In older rbdout files, there is an id vector and a "num_nodal" value in the metadata directory, and the number of entries in each state directory is the same. This was found to be a problem when rigid deformable material switching occurs, so now there is an id array and num_nodal value in each directory. Of course, we have to support both cases.... */ lsda_queryvar(handle,"ids",&typid,&length,&filenum); if(typid > 0) { max_num = num = length; ids = (int *) malloc(num*sizeof(int)); lsda_read(handle,LSDA_INT,"ids",0,num,ids); lsda_read(handle,LSDA_INT,"num_nodal",0,1,&num_nodal); } else { max_num = num = 100; ids = (int *) malloc(num*sizeof(int)); } gx = (float *) malloc(48*num*sizeof(float)); gy = gx + num; gz = gy + num; gdx = gz + num; gdy = gdx + num; gdz = gdy + num; grdx= gdz + num; grdy= grdx + num; grdz= grdy + num; gvx = grdz + num; gvy = gvx + num; gvz = gvy + num; grvx= gvz + num; grvy= grvx + num; grvz= grvy + num; gax = grvz + num; gay = gax + num; gaz = gay + num; grax= gaz + num; gray= grax + num; graz= gray + num; ldx = graz + num; ldy = ldx + num; ldz = ldy + num; lrdx= ldz + num; lrdy= lrdx + num; lrdz= lrdy + num; lvx = lrdz + num; lvy = lvx + num; lvz = lvy + num; lrvx= lvz + num; lrvy= lrvx + num; lrvz= lrvy + num; lax = lrvz + num; lay = lax + num; laz = lay + num; lrax= laz + num; lray= lrax + num; lraz= lray + num; d11 = lraz + num; d12 = d11 + num; d13 = d12 + num; d21 = d13 + num; d22 = d21 + num; d23 = d22 + num; d31 = d23 + num; d32 = d31 + num; d33 = d32 + num; /* open file and write header */ sprintf(output_file,"%srbdout",output_path); fp=fopen(output_file,"w"); write_message(fp,output_file); if (!fp) return 0; output_title(handle,"/rbdout/metadata",fp); /* Loop through time states and write each one. */ for(state=1; (dp = next_dir(handle,"/rbdout",dp,dirname)) != NULL; state++) { lsda_queryvar(handle,"ids",&typid,&length,&filenum); if(typid > 0) { num = length; if(num > max_num) { /* have to reallocate arrays */ max_num = num+10; free(ids); free(gx); ids = (int *) malloc(max_num*sizeof(int)); gx = (float *) malloc(48*max_num*sizeof(float)); gy = gx + max_num; gz = gy + max_num; gdx = gz + max_num; gdy = gdx + max_num; gdz = gdy + max_num; grdx= gdz + max_num; grdy= grdx + max_num; grdz= grdy + max_num; gvx = grdz + max_num; gvy = gvx + max_num; gvz = gvy + max_num; grvx= gvz + max_num; grvy= grvx + max_num; grvz= grvy + max_num; gax = grvz + max_num; gay = gax + max_num; gaz = gay + max_num; grax= gaz + max_num; gray= grax + max_num; graz= gray + max_num; ldx = graz + max_num; ldy = ldx + max_num; ldz = ldy + max_num; lrdx= ldz + max_num; lrdy= lrdx + max_num; lrdz= lrdy + max_num; lvx = lrdz + max_num; lvy = lvx + max_num; lvz = lvy + max_num; lrvx= lvz + max_num; lrvy= lrvx + max_num; lrvz= lrvy + max_num; lax = lrvz + max_num; lay = lax + max_num; laz = lay + max_num; lrax= laz + max_num; lray= lrax + max_num; lraz= lray + max_num; d11 = lraz + max_num; d12 = d11 + max_num; d13 = d12 + max_num; d21 = d13 + max_num; d22 = d21 + max_num; d23 = d22 + max_num; d31 = d23 + max_num; d32 = d31 + max_num; d33 = d32 + max_num; } lsda_read(handle,LSDA_INT,"ids",0,num,ids); lsda_read(handle,LSDA_INT,"num_nodal",0,1,&num_nodal); } if(num==0) continue; /* don't output a header if there is no data */ if(lsda_read(handle,LSDA_FLOAT,"time",0,1,&time) != 1) break; if(lsda_read(handle,LSDA_INT,"cycle",0,1,&cycle) != 1) break; if(lsda_read(handle,LSDA_FLOAT,"global_x",0,num,gx) != num) break; if(lsda_read(handle,LSDA_FLOAT,"global_y",0,num,gy) != num) break; if(lsda_read(handle,LSDA_FLOAT,"global_z",0,num,gz) != num) break; if(lsda_read(handle,LSDA_FLOAT,"global_dx",0,num,gdx) != num) break; if(lsda_read(handle,LSDA_FLOAT,"global_dy",0,num,gdy) != num) break; if(lsda_read(handle,LSDA_FLOAT,"global_dz",0,num,gdz) != num) break; if(lsda_read(handle,LSDA_FLOAT,"global_rdx",0,num,grdx) != num) break; if(lsda_read(handle,LSDA_FLOAT,"global_rdy",0,num,grdy) != num) break; if(lsda_read(handle,LSDA_FLOAT,"global_rdz",0,num,grdz) != num) break; if(lsda_read(handle,LSDA_FLOAT,"global_vx",0,num,gvx) != num) break; if(lsda_read(handle,LSDA_FLOAT,"global_vy",0,num,gvy) != num) break; if(lsda_read(handle,LSDA_FLOAT,"global_vz",0,num,gvz) != num) break; if(lsda_read(handle,LSDA_FLOAT,"global_rvx",0,num,grvx) != num) break; if(lsda_read(handle,LSDA_FLOAT,"global_rvy",0,num,grvy) != num) break; if(lsda_read(handle,LSDA_FLOAT,"global_rvz",0,num,grvz) != num) break; if(lsda_read(handle,LSDA_FLOAT,"global_ax",0,num,gax) != num) break; if(lsda_read(handle,LSDA_FLOAT,"global_ay",0,num,gay) != num) break; if(lsda_read(handle,LSDA_FLOAT,"global_az",0,num,gaz) != num) break; if(lsda_read(handle,LSDA_FLOAT,"global_rax",0,num,grax) != num) break; if(lsda_read(handle,LSDA_FLOAT,"global_ray",0,num,gray) != num) break; if(lsda_read(handle,LSDA_FLOAT,"global_raz",0,num,graz) != num) break; if(lsda_read(handle,LSDA_FLOAT,"dircos_11",0,num,d11) != num) break; if(lsda_read(handle,LSDA_FLOAT,"dircos_12",0,num,d12) != num) break; if(lsda_read(handle,LSDA_FLOAT,"dircos_13",0,num,d13) != num) break; if(lsda_read(handle,LSDA_FLOAT,"dircos_21",0,num,d21) != num) break; if(lsda_read(handle,LSDA_FLOAT,"dircos_22",0,num,d22) != num) break; if(lsda_read(handle,LSDA_FLOAT,"dircos_23",0,num,d23) != num) break; if(lsda_read(handle,LSDA_FLOAT,"dircos_31",0,num,d31) != num) break; if(lsda_read(handle,LSDA_FLOAT,"dircos_32",0,num,d32) != num) break; if(lsda_read(handle,LSDA_FLOAT,"dircos_33",0,num,d33) != num) break; if(lsda_read(handle,LSDA_FLOAT,"local_dx",0,num,ldx) != num) break; if(lsda_read(handle,LSDA_FLOAT,"local_dy",0,num,ldy) != num) break; if(lsda_read(handle,LSDA_FLOAT,"local_dz",0,num,ldz) != num) break; if(lsda_read(handle,LSDA_FLOAT,"local_rdx",0,num,lrdx) != num) break; if(lsda_read(handle,LSDA_FLOAT,"local_rdy",0,num,lrdy) != num) break; if(lsda_read(handle,LSDA_FLOAT,"local_rdz",0,num,lrdz) != num) break; if(lsda_read(handle,LSDA_FLOAT,"local_vx",0,num,lvx) != num) break; if(lsda_read(handle,LSDA_FLOAT,"local_vy",0,num,lvy) != num) break; if(lsda_read(handle,LSDA_FLOAT,"local_vz",0,num,lvz) != num) break; if(lsda_read(handle,LSDA_FLOAT,"local_rvx",0,num,lrvx) != num) break; if(lsda_read(handle,LSDA_FLOAT,"local_rvy",0,num,lrvy) != num) break; if(lsda_read(handle,LSDA_FLOAT,"local_rvz",0,num,lrvz) != num) break; if(lsda_read(handle,LSDA_FLOAT,"local_ax",0,num,lax) != num) break; if(lsda_read(handle,LSDA_FLOAT,"local_ay",0,num,lay) != num) break; if(lsda_read(handle,LSDA_FLOAT,"local_az",0,num,laz) != num) break; if(lsda_read(handle,LSDA_FLOAT,"local_rax",0,num,lrax) != num) break; if(lsda_read(handle,LSDA_FLOAT,"local_ray",0,num,lray) != num) break; if(lsda_read(handle,LSDA_FLOAT,"local_raz",0,num,lraz) != num) break; fprintf(fp,"1\n\n r i g i d b o d y m o t i o n a t cycle=%8d time=%15.6E\n",cycle,time); for(i=0; i<num; i++) { if(i < num-num_nodal) fprintf(fp,"\n rigid body%8d\n",ids[i]); else fprintf(fp,"\n nodal rigid body%8d\n",ids[i]); fprintf(fp," global x y z"); fprintf(fp," x-rot y-rot z-rot\n"); fprintf(fp," coordinates: %12.4E%12.4E%12.4E\n",gx[i],gy[i],gz[i]); fprintf(fp," displacements: %12.4E%12.4E%12.4E%12.4E%12.4E%12.4E\n", gdx[i],gdy[i],gdz[i],grdx[i],grdy[i],grdz[i]); fprintf(fp," velocities: %12.4E%12.4E%12.4E%12.4E%12.4E%12.4E\n", gvx[i],gvy[i],gvz[i],grvx[i],grvy[i],grvz[i]); fprintf(fp," accelerations: %12.4E%12.4E%12.4E%12.4E%12.4E%12.4E\n", gax[i],gay[i],gaz[i],grax[i],gray[i],graz[i]); fprintf(fp,"\nprincipal or user defined local coordinate direction vectors\n"); fprintf(fp," a b c\n"); fprintf(fp," row 1%15.4E%15.4E%15.4E\n",d11[i],d12[i],d13[i]); fprintf(fp," row 2%15.4E%15.4E%15.4E\n",d21[i],d22[i],d23[i]); fprintf(fp," row 3%15.4E%15.4E%15.4E\n\n",d31[i],d32[i],d33[i]); fprintf(fp," output in principal or user defined local coordinate directions\n"); fprintf(fp," a b c "); fprintf(fp,"a-rot b-rot c-rot\n"); fprintf(fp," displacements: %12.4E%12.4E%12.4E%12.4E%12.4E%12.4E\n", ldx[i],ldy[i],ldz[i],lrdx[i],lrdy[i],lrdz[i]); fprintf(fp," velocities: %12.4E%12.4E%12.4E%12.4E%12.4E%12.4E\n", lvx[i],lvy[i],lvz[i],lrvx[i],lrvy[i],lrvz[i]); fprintf(fp," accelerations: %12.4E%12.4E%12.4E%12.4E%12.4E%12.4E\n", lax[i],lay[i],laz[i],lrax[i],lray[i],lraz[i]); } } fclose(fp); free(gx); free(ids); printf(" %d states extracted\n",state-1); return 0; } /* GCEOUT file */ int translate_gceout(int handle) { int i,typid,num,filenum,state; LSDA_Length length; char dirname[256]; int *ids; float *xf,*yf,*zf,*xm,*ym,*zm,*tf,*tm; float time; FILE *fp; LSDADir *dp = NULL; if (lsda_cd(handle,"/gceout/metadata") == -1) return 0; printf("Extracting GCEOUT data\n"); /* Read metadata */ lsda_queryvar(handle,"ids",&typid,&length,&filenum); num = length; ids = (int *) malloc(num*sizeof(int)); xf = (float *) malloc(8*num*sizeof(float)); yf = xf + num; zf = yf + num; xm = zf + num; ym = xm + num; zm = ym + num; tf = zm + num; tm = tf + num; lsda_read(handle,LSDA_INT,"ids",0,num,ids); /* open file and write header */ sprintf(output_file,"%sgceout",output_path); fp=fopen(output_file,"w"); write_message(fp,output_file); if (!fp) return 0; output_title(handle,"/gceout/metadata",fp); fprintf(fp,"\n\n\n\n c o n t a c t e n t i t i e s r e s u l t"); fprintf(fp," a n t s\n\n\n\n"); fprintf(fp," material# time x-force y-force z-force"); fprintf(fp," magnitude\n"); fprintf(fp,"line#2 resultant moments x-moment y-moment z-moment"); fprintf(fp," magnitude\n"); /* Loop through time states and write each one. */ for(state=1; (dp = next_dir(handle,"/gceout",dp,dirname)) != NULL; state++) { if(lsda_read(handle,LSDA_FLOAT,"time",0,1,&time) != 1) break; if(lsda_read(handle,LSDA_FLOAT,"x_force", 0,num,xf) != num) break; if(lsda_read(handle,LSDA_FLOAT,"y_force", 0,num,yf) != num) break; if(lsda_read(handle,LSDA_FLOAT,"z_force", 0,num,zf) != num) break; if(lsda_read(handle,LSDA_FLOAT,"x_moment", 0,num,xm) != num) break; if(lsda_read(handle,LSDA_FLOAT,"y_moment", 0,num,ym) != num) break; if(lsda_read(handle,LSDA_FLOAT,"z_moment", 0,num,zm) != num) break; if(lsda_read(handle,LSDA_FLOAT,"force_magnitude", 0,num,tf) != num) break; if(lsda_read(handle,LSDA_FLOAT,"moment_magnitude",0,num,tm) != num) break; for(i=0; i<num; i++) { fprintf(fp,"%12d %12.4E%12.4E%12.4E%12.4E%12.4E\n", ids[i],time,xf[i],yf[i],zf[i],tf[i]); fprintf(fp," %12.4E%12.4E%12.4E%12.4E\n", xm[i],ym[i],zm[i],tm[i]); } fprintf(fp,"\n"); } fclose(fp); free(xf); free(ids); printf(" %d states extracted\n",state-1); return 0; } /* SLEOUT file */ int translate_sleout(int handle) { int i,j,typid,num,numm,filenum,state; LSDA_Length length; char dirname[256]; int *ids,*single_sided, have_friction = -1; int *is_transducer; float *slave, *master, *friction; float time,ts,tm,te,tf; int cycle; FILE *fp; LSDADir *dp = NULL; if (lsda_cd(handle,"/sleout/metadata") == -1) return 0; printf("Extracting SLEOUT data\n"); /* Read metadata */ lsda_queryvar(handle,"ids",&typid,&length,&filenum); num = length; ids = (int *) malloc(num*sizeof(int)); single_sided = (int *) malloc(num*sizeof(int)); lsda_read(handle,LSDA_INT,"ids",0,num,ids); lsda_read(handle,LSDA_INT,"single_sided",0,num,single_sided); lsda_queryvar(handle,"is_transducer",&typid,&length,&filenum); if(length == num) { is_transducer= (int *) malloc(num*sizeof(int)); lsda_read(handle,LSDA_INT,"is_transducer",0,num,is_transducer); } else { is_transducer= NULL; } numm = num; for(i=0; i<num; i++) if(single_sided[i]) numm--; friction = (float *) malloc(num *sizeof(float)); slave = (float *) malloc(num *sizeof(float)); master = (float *) malloc(numm*sizeof(float)); /* open file and write header */ sprintf(output_file,"%ssleout",output_path); fp=fopen(output_file,"w"); write_message(fp,output_file); if (!fp) return 0; output_title(handle,"/sleout/metadata",fp); output_legend(handle,fp,1,1); /* Loop through time states and write each one. */ for(state=1; (dp = next_dir(handle,"/sleout",dp,dirname)) != NULL; state++) { if(lsda_read(handle,LSDA_FLOAT,"time",0,1,&time) != 1) break; if(lsda_read(handle,LSDA_INT,"cycle",0,1,&cycle) != 1) break; if(lsda_read(handle,LSDA_FLOAT,"slave",0,num,slave) != num) break; if(numm > 0 && lsda_read(handle,LSDA_FLOAT,"master",0,numm,master) != numm) break; if(lsda_read(handle,LSDA_FLOAT,"total_slave",0,1,&ts) != 1) break; if(lsda_read(handle,LSDA_FLOAT,"total_master",0,1,&tm) != 1) break; if(lsda_read(handle,LSDA_FLOAT,"total_energy",0,1,&te) != 1) break; if(have_friction == -1) { /* haven't checked yet... */ lsda_queryvar(handle,"total_friction",&typid,&length,&filenum); if(length > 0) have_friction=1; else have_friction=0; } if(have_friction) { lsda_read(handle,LSDA_FLOAT,"total_friction",0,1,&tf); lsda_read(handle,LSDA_FLOAT,"friction_energy",0,num,friction); fprintf(fp,"\n\n\n contact interface energy file, time=%14.7E\n",time); fprintf(fp," # slave master cycle=%14d",cycle); if(is_transducer) { fprintf(fp," frictional transducer\n\n"); } else { fprintf(fp," frictional\n\n"); } for(i=j=0; i<num; i++) { if(single_sided[i]) fprintf(fp,"%10d%13.4E%13.4E",ids[i],slave[i],0.0); else fprintf(fp,"%10d%13.4E%13.4E",ids[i],slave[i],master[j++]); fprintf(fp," %13.4E",friction[i]); if(is_transducer) fprintf(fp,"%8d",is_transducer[i]); fprintf(fp,"\n"); } fprintf(fp,"\n summary total slave side=%14.7E\n",ts); fprintf(fp, " total mastr side=%14.7E\n",tm); fprintf(fp, " total energy =%14.7E\n",te); fprintf(fp, " friction energy =%14.7E\n\n\n\n",tf); } else { fprintf(fp,"\n\n\n contact interface energy file, time=%14.7E\n",time); fprintf(fp," # slave master cycle=%14d",cycle); if(is_transducer) { fprintf(fp," transducer\n\n"); } else { fprintf(fp,"\n\n"); } for(i=j=0; i<num; i++) { if(single_sided[i]) fprintf(fp,"%10d%13.4E%13.4E",ids[i],slave[i],0.0); else fprintf(fp,"%10d%13.4E%13.4E",ids[i],slave[i],master[j++]); if(is_transducer) fprintf(fp," %8d",is_transducer[i]); fprintf(fp,"\n"); } fprintf(fp,"\n summary total slave side=%14.7E\n",ts); fprintf(fp, " total mastr side=%14.7E\n",tm); fprintf(fp, " total energy =%14.7E\n\n\n\n",te); } } fclose(fp); free(master); free(slave); free(friction); if(is_transducer) free(is_transducer); free(single_sided); free(ids); printf(" %d states extracted\n",state-1); return 0; } /* SBTOUT file */ int translate_sbtout(int handle) { int i,typid,filenum,state; int numb,nums,numr; LSDA_Length length; char dirname[256]; int *bids,*sids,*rids; float *blength,*bforce,*slip,*pullout,*rforce; float time; FILE *fp; LSDADir *dp = NULL; if (lsda_cd(handle,"/sbtout/metadata") == -1) return 0; printf("Extracting SBTOUT data\n"); /* Read metadata */ lsda_queryvar(handle,"belt_ids",&typid,&length,&filenum); numb = length; bids = (int *) malloc(numb*sizeof(int)); blength = (float *) malloc(numb*sizeof(float)); bforce = (float *) malloc(numb*sizeof(float)); lsda_read(handle,LSDA_INT,"belt_ids",0,numb,bids); lsda_queryvar(handle,"slipring_ids",&typid,&length,&filenum); nums = length; if(typid > 0 && nums > 0) { sids = (int *) malloc(nums*sizeof(int)); slip = (float *) malloc(nums*sizeof(float)); lsda_read(handle,LSDA_INT,"slipring_ids",0,nums,sids); } else { nums=0; } lsda_queryvar(handle,"retractor_ids",&typid,&length,&filenum); numr = length; if(typid > 0 && numr > 0) { rids = (int *) malloc(numr*sizeof(int)); pullout = (float *) malloc(numr*sizeof(float)); rforce = (float *) malloc(numr*sizeof(float)); lsda_read(handle,LSDA_INT,"retractor_ids",0,numr,rids); } else { numr=0; } /* open file and write header */ sprintf(output_file,"%ssbtout",output_path); fp=fopen(output_file,"w"); write_message(fp,output_file); if (!fp) return 0; output_title(handle,"/sbtout/metadata",fp); output_legend(handle,fp,1,1); fprintf(fp,"\n\n\n\n S E A T B E L T O U T P U T\n\n"); /* Loop through time states and write each one. */ for(state=1; (dp = next_dir(handle,"/sbtout",dp,dirname)) != NULL; state++) { if(lsda_read(handle,LSDA_FLOAT,"time",0,1,&time) != 1) break; if(numb && lsda_read(handle,LSDA_FLOAT,"belt_force",0,numb,bforce) != numb) break; if(numb && lsda_read(handle,LSDA_FLOAT,"belt_length",0,numb,blength) != numb) break; if(nums && lsda_read(handle,LSDA_FLOAT,"ring_slip",0,nums,slip) != nums) break; if(numr) { if(lsda_read(handle,LSDA_FLOAT,"retractor_pull_out",0,numr,pullout) != numr) break; if(lsda_read(handle,LSDA_FLOAT,"retractor_force",0,numr,rforce) != numr) break; } fprintf(fp,"\n\n time...........................%16.5E\n",time); for(i=0; i<numb; i++) { fprintf(fp,"\n seat belt number...............%8d\n",bids[i]); fprintf(fp, " force..........................%16.5E\n",bforce[i]); fprintf(fp, " current length.................%16.5E\n",blength[i]); } for(i=0; i<nums; i++) { fprintf(fp,"\n slip ring number...............%8d\n",sids[i]); fprintf(fp, " total slip from side 1 to .....%16.5E\n",slip[i]); } for(i=0; i<numr; i++) { fprintf(fp,"\n retractor number...............%8d\n",rids[i]); fprintf(fp, " pull-out to date...............%14.5E\n",pullout[i]); fprintf(fp, " force in attached element......%14.5E\n",rforce[i]); } } fclose(fp); if(numr > 0) { free(rforce); free(pullout); free(rids); } if(nums > 0) { free(slip); free(sids); } free(bforce); free(blength); free(bids); printf(" %d states extracted\n",state-1); return 0; } /* JNTFORC file */ int translate_jntforc(int handle) { int i,j,k,typid,filenum,state; int numj,num0,num1; LSDA_Length length; char dirname[256]; int *idj,*local,*id0,*id1; int have_type1_extra = -1; float *xf,*yf,*zf,*xm,*ym,*zm,*rf,*rm; float *p0,*dpdt0,*t0,*dtdt0,*s0,*dsdt0; float *ps0,*pd0,*pt0,*ts0,*td0,*tt0,*ss0,*sd0,*st0,*je0; float *a1,*dadt1,*g1,*dgdt1,*b1,*dbdt1; float *as1,*ad1,*at1,*gsf1,*bs1,*bd1,*bt1,*je1,*jx1,*jx2; float *e; float time; FILE *fp; char title_dir[128]; printf("Extracting JNTFORC data\n"); /* Read metadata */ title_dir[0]=0; lsda_queryvar(handle,"/jntforc/joints",&typid,&length,&filenum); e=NULL; if(typid == 0) { lsda_cd(handle,"/jntforc/joints/metadata"); strcpy(title_dir,"/jntforc/joints/metadata"); lsda_queryvar(handle,"ids",&typid,&length,&filenum); numj = length; idj = (int *) malloc(numj*sizeof(int)); local = (int *) malloc(numj*sizeof(int)); xf = (float *) malloc(numj*sizeof(float)); yf = (float *) malloc(numj*sizeof(float)); zf = (float *) malloc(numj*sizeof(float)); xm = (float *) malloc(numj*sizeof(float)); ym = (float *) malloc(numj*sizeof(float)); zm = (float *) malloc(numj*sizeof(float)); rf = (float *) malloc(numj*sizeof(float)); rm = (float *) malloc(numj*sizeof(float)); lsda_read(handle,LSDA_INT,"ids",0,numj,idj); lsda_read(handle,LSDA_INT,"local",0,numj,local); lsda_query(handle,"/jntforc/joints/d000001/energy",&typid,&length); if(length==numj) e = (float *) malloc(numj*sizeof(float)); } else { numj = 0; } lsda_queryvar(handle,"/jntforc/type0",&typid,&length,&filenum); if(typid == 0) { lsda_cd(handle,"/jntforc/type0/metadata"); strcpy(title_dir,"/jntforc/type0/metadata"); lsda_queryvar(handle,"ids",&typid,&length,&filenum); num0 = length; id0 = (int *) malloc(num0*sizeof(int)); p0 = (float *) malloc(num0*sizeof(float)); dpdt0 = (float *) malloc(num0*sizeof(float)); t0 = (float *) malloc(num0*sizeof(float)); dtdt0 = (float *) malloc(num0*sizeof(float)); s0 = (float *) malloc(num0*sizeof(float)); dsdt0 = (float *) malloc(num0*sizeof(float)); ps0 = (float *) malloc(num0*sizeof(float)); pd0 = (float *) malloc(num0*sizeof(float)); pt0 = (float *) malloc(num0*sizeof(float)); ts0 = (float *) malloc(num0*sizeof(float)); td0 = (float *) malloc(num0*sizeof(float)); tt0 = (float *) malloc(num0*sizeof(float)); ss0 = (float *) malloc(num0*sizeof(float)); sd0 = (float *) malloc(num0*sizeof(float)); st0 = (float *) malloc(num0*sizeof(float)); je0 = (float *) malloc(num0*sizeof(float)); lsda_read(handle,LSDA_INT,"ids",0,num0,id0); } else { num0 = 0; } lsda_queryvar(handle,"/jntforc/type1",&typid,&length,&filenum); if(typid == 0) { lsda_cd(handle,"/jntforc/type1/metadata"); strcpy(title_dir,"/jntforc/type1/metadata"); lsda_queryvar(handle,"ids",&typid,&length,&filenum); num1 = length; id1 = (int *) malloc(num1*sizeof(int)); a1 = (float *) malloc(num1*sizeof(float)); dadt1 = (float *) malloc(num1*sizeof(float)); g1 = (float *) malloc(num1*sizeof(float)); dgdt1 = (float *) malloc(num1*sizeof(float)); b1 = (float *) malloc(num1*sizeof(float)); dbdt1 = (float *) malloc(num1*sizeof(float)); as1 = (float *) malloc(num1*sizeof(float)); ad1 = (float *) malloc(num1*sizeof(float)); at1 = (float *) malloc(num1*sizeof(float)); gsf1 = (float *) malloc(num1*sizeof(float)); bs1 = (float *) malloc(num1*sizeof(float)); bd1 = (float *) malloc(num1*sizeof(float)); bt1 = (float *) malloc(num1*sizeof(float)); je1 = (float *) malloc(num1*sizeof(float)); jx1 = (float *) malloc(num1*sizeof(float)); jx2 = (float *) malloc(num1*sizeof(float)); lsda_read(handle,LSDA_INT,"ids",0,num1,id1); } else { num1 = 0; } if(strlen(title_dir)==0) return 0; /* ?? */ /* open file and write header */ sprintf(output_file,"%sjntforc",output_path); fp=fopen(output_file,"w"); write_message(fp,output_file); if (!fp) return 0; output_title(handle,title_dir,fp); k=0; if(numj > 0) { lsda_cd(handle,"/jntforc/joints/metadata"); i=(num0+num1 > 0) ? 0 : 1; output_legend(handle,fp,1,i); k = 1; } if(num0 > 0) { lsda_cd(handle,"/jntforc/type0/metadata"); i=!k; j=(num1 > 0) ? 0 : 1; output_legend(handle,fp,i,j); k = 1; } if(num1 > 0) { lsda_cd(handle,"/jntforc/type1/metadata"); i= !k; output_legend(handle,fp,i,1); } /* Loop through time states and write each one. */ for(state=1; ; state++) { if(numj > 0) { if(state<=999999) sprintf(dirname,"/jntforc/joints/d%6.6d",state); else sprintf(dirname,"/jntforc/joints/d%8.8d",state); lsda_queryvar(handle,dirname,&typid,&length,&filenum); if(typid != 0) break; lsda_cd(handle,dirname); if(lsda_read(handle,LSDA_FLOAT,"time",0,1,&time) != 1) break; if(lsda_read(handle,LSDA_FLOAT,"x_force", 0,numj,xf) != numj) break; if(lsda_read(handle,LSDA_FLOAT,"y_force", 0,numj,yf) != numj) break; if(lsda_read(handle,LSDA_FLOAT,"z_force", 0,numj,zf) != numj) break; if(lsda_read(handle,LSDA_FLOAT,"x_moment", 0,numj,xm) != numj) break; if(lsda_read(handle,LSDA_FLOAT,"y_moment", 0,numj,ym) != numj) break; if(lsda_read(handle,LSDA_FLOAT,"z_moment", 0,numj,zm) != numj) break; if(lsda_read(handle,LSDA_FLOAT,"resultant_force", 0,numj,rf) != numj) break; if(lsda_read(handle,LSDA_FLOAT,"resultant_moment",0,numj,rm) != numj) break; if(e && lsda_read(handle,LSDA_FLOAT,"energy",0,numj,e) != numj) break; fprintf(fp,"\n\n time.........................%14.5E\n",time); for(i=0; i<numj; i++) { fprintf(fp," joint ID.....................%10d\n",idj[i]); if(local[i]) { fprintf(fp," x-force (local) ............%14.5E\n",xf[i]); fprintf(fp," y-force (local) ............%14.5E\n",yf[i]); fprintf(fp," z-force (local) ............%14.5E\n",zf[i]); fprintf(fp," x-moment (local) ............%14.5E\n",xm[i]); fprintf(fp," y-moment (local) ............%14.5E\n",ym[i]); fprintf(fp," z-moment (local) ............%14.5E\n",zm[i]); } else { fprintf(fp," x-force......................%14.5E\n",xf[i]); fprintf(fp," y-force......................%14.5E\n",yf[i]); fprintf(fp," z-force......................%14.5E\n",zf[i]); fprintf(fp," x-moment.....................%14.5E\n",xm[i]); fprintf(fp," y-moment.....................%14.5E\n",ym[i]); fprintf(fp," z-moment.....................%14.5E\n",zm[i]); } fprintf(fp," resultant force..............%14.5E\n",rf[i]); fprintf(fp," resultant moment.............%14.5E\n",rm[i]); if(e) fprintf(fp," energy.......................%14.5E\n",e[i]); } } if(num0 > 0) { if(state<=999999) sprintf(dirname,"/jntforc/type0/d%6.6d",state); else sprintf(dirname,"/jntforc/type0/d%8.8d",state); lsda_queryvar(handle,dirname,&typid,&length,&filenum); if(typid != 0) break; lsda_cd(handle,dirname); if(lsda_read(handle,LSDA_FLOAT,"phi_degrees", 0,num0, p0) != num0) break; if(lsda_read(handle,LSDA_FLOAT,"d(phi)_dt", 0,num0,dpdt0) != num0) break; if(lsda_read(handle,LSDA_FLOAT,"theta_degrees", 0,num0, t0) != num0) break; if(lsda_read(handle,LSDA_FLOAT,"d(theta)_dt", 0,num0,dtdt0) != num0) break; if(lsda_read(handle,LSDA_FLOAT,"psi_degrees", 0,num0, s0) != num0) break; if(lsda_read(handle,LSDA_FLOAT,"d(psi)_dt", 0,num0,dsdt0) != num0) break; if(lsda_read(handle,LSDA_FLOAT,"phi_moment_stiffness", 0,num0, ps0) != num0) break; if(lsda_read(handle,LSDA_FLOAT,"phi_moment_damping", 0,num0, pd0) != num0) break; if(lsda_read(handle,LSDA_FLOAT,"phi_moment_total", 0,num0, pt0) != num0) break; if(lsda_read(handle,LSDA_FLOAT,"theta_moment_stiffness",0,num0, ts0) != num0) break; if(lsda_read(handle,LSDA_FLOAT,"theta_moment_damping", 0,num0, td0) != num0) break; if(lsda_read(handle,LSDA_FLOAT,"theta_moment_total", 0,num0, tt0) != num0) break; if(lsda_read(handle,LSDA_FLOAT,"psi_moment_stiffness", 0,num0, ss0) != num0) break; if(lsda_read(handle,LSDA_FLOAT,"psi_moment_damping", 0,num0, sd0) != num0) break; if(lsda_read(handle,LSDA_FLOAT,"psi_moment_total", 0,num0, st0) != num0) break; if(lsda_read(handle,LSDA_FLOAT,"joint_energy", 0,num0, je0) != num0) break; for(i=0; i<num0; i++) { fprintf(fp," joint stiffness id number....%10d\n",id0[i]); fprintf(fp," x-displacement...............%14.5E\n",p0[i]); fprintf(fp," d(dispx)/dt..................%14.5E\n",dpdt0[i]); fprintf(fp," y-displacement...............%14.5E\n",t0[i]); fprintf(fp," d(dispy)/dt..................%14.5E\n",dtdt0[i]); fprintf(fp," z-displacement...............%14.5E\n",s0[i]); fprintf(fp," d(dispz)/dt..................%14.5E\n",dsdt0[i]); fprintf(fp," force-x-stiffness............%14.5E\n",ps0[i]); fprintf(fp," force-x-damping..............%14.5E\n",pd0[i]); fprintf(fp," force-x-total................%14.5E\n",pt0[i]); fprintf(fp," force-y-stiffness............%14.5E\n",ts0[i]); fprintf(fp," force-y-damping..............%14.5E\n",td0[i]); fprintf(fp," force-y-total................%14.5E\n",tt0[i]); fprintf(fp," force-z-stiffness............%14.5E\n",ss0[i]); fprintf(fp," force-z-damping..............%14.5E\n",sd0[i]); fprintf(fp," force-z-total................%14.5E\n",st0[i]); fprintf(fp," joint energy.................%14.5E\n",je0[i]); } } if(num1 > 0) { if(state<=999999) sprintf(dirname,"/jntforc/type1/d%6.6d",state); else sprintf(dirname,"/jntforc/type1/d%8.8d",state); lsda_queryvar(handle,dirname,&typid,&length,&filenum); if(typid != 0) break; lsda_cd(handle,dirname); if(numj == 0 & num0 ==0) { if(lsda_read(handle,LSDA_FLOAT,"time",0,1,&time) != 1) break; fprintf(fp,"\n\n time.........................%14.5E\n",time); } if(lsda_read(handle,LSDA_FLOAT,"alpha_degrees", 0,num1, a1) != num1) break; if(lsda_read(handle,LSDA_FLOAT,"d(alpha)_dt", 0,num1,dadt1) != num1) break; if(lsda_read(handle,LSDA_FLOAT,"gamma_degrees", 0,num1, g1) != num1) break; if(lsda_read(handle,LSDA_FLOAT,"d(gamma)_dt", 0,num1,dgdt1) != num1) break; if(lsda_read(handle,LSDA_FLOAT,"beta_degrees", 0,num1, b1) != num1) break; if(lsda_read(handle,LSDA_FLOAT,"d(beta)_dt", 0,num1,dbdt1) != num1) break; if(lsda_read(handle,LSDA_FLOAT,"alpha_moment_stiffness",0,num1, as1) != num1) break; if(lsda_read(handle,LSDA_FLOAT,"alpha_moment_damping", 0,num1, ad1) != num1) break; if(lsda_read(handle,LSDA_FLOAT,"alpha_moment_total", 0,num1, at1) != num1) break; if(lsda_read(handle,LSDA_FLOAT,"gamma_scale_factor", 0,num1, gsf1) != num1) break; if(lsda_read(handle,LSDA_FLOAT,"beta_moment_stiffness", 0,num1, bs1) != num1) break; if(lsda_read(handle,LSDA_FLOAT,"beta_moment_damping", 0,num1, bd1) != num1) break; if(lsda_read(handle,LSDA_FLOAT,"beta_moment_total", 0,num1, bt1) != num1) break; if(lsda_read(handle,LSDA_FLOAT,"joint_energy", 0,num1, je1) != num1) break; /* This is such a hack I don't know where to begin..... Someone somewhere decided that instead of creating a new output type (like they should have) they would override the meaning of all these arrays depending on the output of these two "extra" variables. I will change this when I get a chance, but for now we have to support this for backward compatibility. Also, these two may not be there at all, so we have to allow for that too. */ if(have_type1_extra == -1) { lsda_queryvar(handle,"joint_extra1",&typid,&length,&filenum); if(typid > 0) have_type1_extra = 1; else have_type1_extra = 0; } if(have_type1_extra) { if(lsda_read(handle,LSDA_FLOAT,"joint_extra1", 0,num1, jx1) != num1) break; if(lsda_read(handle,LSDA_FLOAT,"joint_extra2", 0,num1, jx2) != num1) break; } for(i=0; i<num1; i++) { if (have_type1_extra && jx1[i]+jx2[i] != -8){ fprintf(fp," joint stiffness id number....%10d\n",id1[i]); fprintf(fp," phi (degrees)................%14.5E\n",a1[i]); fprintf(fp," d(phi)/dt (degrees)..........%14.5E\n",dadt1[i]); fprintf(fp," theta (degrees)..............%14.5E\n",g1[i]); fprintf(fp," d(theta)/dt (degrees)........%14.5E\n",dgdt1[i]); fprintf(fp," psi (degrees)................%14.5E\n",b1[i]); fprintf(fp," d(psi)/dt (degrees)..........%14.5E\n",dbdt1[i]); fprintf(fp," phi moment-stiffness.........%14.5E\n",as1[i]); fprintf(fp," phi moment-damping...........%14.5E\n",ad1[i]); fprintf(fp," phi moment-total.............%14.5E\n",at1[i]); fprintf(fp," theta-moment-stiffness.......%14.5E\n",gsf1[i]); fprintf(fp," theta-moment-damping.........%14.5E\n",bs1[i]); fprintf(fp," theta-moment-total...........%14.5E\n",bd1[i]); fprintf(fp," psi-moment-stiffness.........%14.5E\n",bt1[i]); fprintf(fp," psi-moment-damping...........%14.5E\n",je1[i]); fprintf(fp," psi-moment-total.............%14.5E\n",jx1[i]); fprintf(fp," joint energy.................%14.5E\n",jx2[i]); } else { fprintf(fp," joint stiffness id number....%10d\n",id1[i]); fprintf(fp," alpha (degrees)..............%14.5E\n",a1[i]); fprintf(fp," d(alpha)/dt (degrees)........%14.5E\n",dadt1[i]); fprintf(fp," gamma (degrees)..............%14.5E\n",g1[i]); fprintf(fp," d(gamma)/dt (degrees)........%14.5E\n",dgdt1[i]); fprintf(fp," beta (degrees)...............%14.5E\n",b1[i]); fprintf(fp," d(beta)/dt (degrees).........%14.5E\n",dbdt1[i]); fprintf(fp," alpha-moment-stiffness.......%14.5E\n",as1[i]); fprintf(fp," alpha-moment-damping.........%14.5E\n",ad1[i]); fprintf(fp," alpha-moment-total...........%14.5E\n",at1[i]); fprintf(fp," gamma scale factor...........%14.5E\n",gsf1[i]); fprintf(fp," beta-moment-stiffness........%14.5E\n",bs1[i]); fprintf(fp," beta-moment-damping..........%14.5E\n",bd1[i]); fprintf(fp," beta-moment-total............%14.5E\n",bt1[i]); fprintf(fp," joint energy.................%14.5E\n",je1[i]); } } } } fclose(fp); if(num1 > 0) { free(je1); free(bt1); free(bd1); free(bs1); free(gsf1); free(at1); free(ad1); free(as1); free(dbdt1); free(b1); free(dgdt1); free(g1); free(dadt1); free(a1); free(id1); } if(num0 > 0) { free(je0); free(st0); free(sd0); free(ss0); free(tt0); free(td0); free(ts0); free(pt0); free(pd0); free(ps0); free(dsdt0); free(s0); free(dtdt0); free(t0); free(dpdt0); free(p0); free(id0); } if(numj > 0) { if(e) free(e); free(rm); free(rf); free(zm); free(ym); free(xm); free(zf); free(yf); free(xf); free(local); free(idj); } printf(" %d states extracted\n",state-1); return 0; } /* SPHOUT file */ int translate_sphout(int handle) { int i,j,k,typid,num,filenum,state; LSDA_Length length; char dirname[128]; int *ids,*mat; int cycle; float time; float *sig_xx,*sig_yy,*sig_zz; float *sig_xy,*sig_yz,*sig_zx; float *eps_xx,*eps_yy,*eps_zz; float *eps_xy,*eps_yz,*eps_zx; float *density,*smooth,*temp; int *neigh,*act,*nstate; float *yield,*effsg; char states[5][16]; FILE *fp; LSDADir *dp = NULL; if (lsda_cd(handle,"/sphout/metadata") == -1) return 0; printf("Extracting SPHOUT data\n"); lsda_queryvar(handle,"ids",&typid,&length,&filenum); num=length; /* allocate memory to read in 1 state */ ids = (int *) malloc(num*sizeof(int)); mat = (int *) malloc(num*sizeof(int)); sig_xx = (float *) malloc(num*sizeof(float)); sig_yy = (float *) malloc(num*sizeof(float)); sig_zz = (float *) malloc(num*sizeof(float)); sig_xy = (float *) malloc(num*sizeof(float)); sig_yz = (float *) malloc(num*sizeof(float)); sig_zx = (float *) malloc(num*sizeof(float)); eps_xx = (float *) malloc(num*sizeof(float)); eps_yy = (float *) malloc(num*sizeof(float)); eps_zz = (float *) malloc(num*sizeof(float)); eps_xy = (float *) malloc(num*sizeof(float)); eps_yz = (float *) malloc(num*sizeof(float)); eps_zx = (float *) malloc(num*sizeof(float)); density= (float *) malloc(num*sizeof(float)); smooth = (float *) malloc(num*sizeof(float)); yield = (float *) malloc(num*sizeof(float)); effsg = (float *) malloc(num*sizeof(float)); act = (int *) malloc(num*sizeof(int)); temp = (float *) malloc(num*sizeof(float)); neigh = (int *) malloc(num*sizeof(int)); nstate = (int *) malloc(num*sizeof(int)); /* Read metadata */ lsda_read(handle,LSDA_INT,"ids",0,num,ids); lsda_read(handle,LSDA_INT,"mat",0,num,mat); lsda_queryvar(handle,"states",&typid,&length,&filenum); lsda_read(handle,LSDA_I1,"states",0,length,dirname); for(i=j=k=0; i<length; i++) { if(dirname[i] == ',') { states[j][k]=0; j++; k=0; } else { states[j][k++]=dirname[i]; } } states[j][k]=0; /* open file and write header */ sprintf(output_file,"%ssphout",output_path); fp=fopen(output_file,"w"); write_message(fp,output_file); if (!fp) return 0; output_title(handle,"/sphout/metadata",fp); output_legend(handle,fp,1,1); /* Loop through time states and write each one */ for(state=1; (dp = next_dir(handle,"/sphout",dp,dirname)) != NULL; state++) { if(lsda_read(handle,LSDA_FLOAT,"time",0,1,&time) != 1) break; if(lsda_read(handle,LSDA_INT,"cycle",0,1,&cycle) != 1) break; if(lsda_read(handle,LSDA_FLOAT,"sig_xx",0,num,sig_xx) != num) break; if(lsda_read(handle,LSDA_FLOAT,"sig_yy",0,num,sig_yy) != num) break; if(lsda_read(handle,LSDA_FLOAT,"sig_zz",0,num,sig_zz) != num) break; if(lsda_read(handle,LSDA_FLOAT,"sig_xy",0,num,sig_xy) != num) break; if(lsda_read(handle,LSDA_FLOAT,"sig_yz",0,num,sig_yz) != num) break; if(lsda_read(handle,LSDA_FLOAT,"sig_zx",0,num,sig_zx) != num) break; if(lsda_read(handle,LSDA_FLOAT,"eps_xx",0,num,eps_xx) != num) break; if(lsda_read(handle,LSDA_FLOAT,"eps_yy",0,num,eps_yy) != num) break; if(lsda_read(handle,LSDA_FLOAT,"eps_zz",0,num,eps_zz) != num) break; if(lsda_read(handle,LSDA_FLOAT,"eps_xy",0,num,eps_xy) != num) break; if(lsda_read(handle,LSDA_FLOAT,"eps_yz",0,num,eps_yz) != num) break; if(lsda_read(handle,LSDA_FLOAT,"eps_zx",0,num,eps_zx) != num) break; if(lsda_read(handle,LSDA_FLOAT,"density",0,num,density) != num) break; if(lsda_read(handle,LSDA_FLOAT,"smooth",0,num,smooth) != num) break; if(lsda_read(handle,LSDA_FLOAT,"yield",0,num,yield) != num) break; if(lsda_read(handle,LSDA_FLOAT,"effsg",0,num,effsg) != num) break; if(lsda_read(handle,LSDA_INT,"neigh",0,num,neigh) != num) break; if(lsda_read(handle,LSDA_INT,"act",0,num,act) != num) break; if(lsda_read(handle,LSDA_FLOAT,"temperature",0,num,temp) != num) break; if(lsda_read(handle,LSDA_INT,"state",0,num,nstate) != num) break; fprintf(fp,"\n\n\n S P H o u t p u t at time%11.4E",time); fprintf(fp," for time step%10d\n",cycle); fprintf(fp,"\n particle mat sig-xx sig-yy sig-zz"); fprintf(fp," sig-xy sig-yz sig-zx \n"); for(i=0; i<num; i++) { fprintf(fp,"%8d%6d",ids[i],mat[i]); fprintf(fp,"%12.4E%12.4E%12.4E%12.4E%12.4E%12.4E\n", sig_xx[i],sig_yy[i],sig_zz[i],sig_xy[i],sig_yz[i],sig_zx[i]); } fprintf(fp,"\n particle mat eps-xx eps-yy eps-zz"); fprintf(fp," eps-xy eps-yz eps-zx \n"); for(i=0; i<num; i++) { fprintf(fp,"%8d%6d",ids[i],mat[i]); fprintf(fp,"%12.4E%12.4E%12.4E%12.4E%12.4E%12.4E\n", eps_xx[i],eps_yy[i],eps_zz[i],eps_xy[i],eps_yz[i],eps_zx[i]); } fprintf(fp,"\n particle mat density smooth neigh act temperature\n"); for(i=0; i<num; i++) { fprintf(fp,"%8d%6d",ids[i],mat[i]); fprintf(fp,"%12.4E%12.4E%7d%6d %12.4E\n",density[i],smooth[i],neigh[i],act[i],temp[i]); } fprintf(fp,"\n particle mat yield effsg state \n"); for(i=0; i<num; i++) { fprintf(fp,"%8d%6d",ids[i],mat[i]); fprintf(fp,"%12.4E%12.4E %7s\n",yield[i],effsg[i],states[nstate[i]-1]); } } fclose(fp); free(ids); free(mat); free(sig_xx); free(sig_yy); free(sig_zz); free(sig_xy); free(sig_yz); free(sig_zx); free(eps_xx); free(eps_yy); free(eps_zz); free(eps_xy); free(eps_yz); free(eps_zx); free(density); free(smooth); free(yield); free(effsg); free(act); free(temp); free(neigh); free(nstate); printf(" %d states extracted\n",state-1); return 1; } /* DEFGEO file */ int translate_defgeo(int handle) { int j,typid,num,filenum,state; LSDA_Length length; char dirname[256]; int *ids; float *dx,*dy,*dz; float maxdisp; int cycle; FILE *fp; char *defgeoenv, *outtype; LSDADir *dp = NULL; /* now try to find out which format should output LSTC_DEFGEO 0 - ls-dyna format chrysler - Chrysler format */ defgeoenv = (char *) malloc(20); outtype = (char *) malloc(20); defgeoenv = "LSTC_DEFGEO"; outtype = (char *) getenv(defgeoenv); if (lsda_cd(handle,"/defgeo/metadata") == -1) return 0; printf("Extracting DEFGEO data - "); /* Read metadata */ lsda_queryvar(handle,"ids",&typid,&length,&filenum); num = length; ids = (int *) malloc(num*sizeof(int)); dx = (float *) malloc(num*sizeof(float)); dy = (float *) malloc(num*sizeof(float)); dz = (float *) malloc(num*sizeof(float)); lsda_read(handle,LSDA_INT,"ids",0,num,ids); /* open file and write header */ sprintf(output_file,"%sdefgeo",output_path); fp=fopen(output_file,"w"); write_message(fp,output_file); if (!fp) return 0; /* output_title(handle,"/defgeo/metadata",fp); Loop through time states and write each one. */ for(state=1; (dp = next_dir(handle,"/defgeo",dp,dirname)) != NULL; state++) { if(lsda_read(handle,LSDA_FLOAT,"x_displacement",0,num,dx) != num) break; if(lsda_read(handle,LSDA_FLOAT,"y_displacement",0,num,dy) != num) break; if(lsda_read(handle,LSDA_FLOAT,"z_displacement",0,num,dz) != num) break; if(lsda_read(handle,LSDA_FLOAT,"max_displacement",0,1,&maxdisp) != 1) break; cycle = 1000 + state - 1; if(outtype!=NULL && (outtype[0]=='c' || outtype[0]=='C' || outtype[0]=='1')) { /* Chrysler format */ if(state==1) { printf("Chrysler format\n"); fprintf(fp,"$LABEL\n"); fprintf(fp,"LS DYNA3D 89P1\n"); } fprintf(fp,"$DISPLACEMENTS\n\n\n\n"); fprintf(fp,"%8d%8d%8d 0%8d 1 3 1 1\n", (int)cycle,(int)num,(int)cycle,(int)cycle); fprintf(fp,"%16.7E%16.7E%16.7E%16.7E\n",maxdisp,0.,0.,0.); for(j=0; j<num; j++) fprintf(fp,"%8d%16.7E%16.7E%16.7E\n",(int)ids[j],dx[j],dy[j],dz[j]); } else { /* LS-DYNA format */ if(state==1) printf("LS-DYNA format\n"); fprintf(fp," 6000 1%6d %8d\n", (int)cycle,(int)num); for(j=0; j<num; j++) fprintf(fp,"%8d%8.2g%8.2g%8.2g\n",(int)ids[j],dx[j],dy[j],dz[j]); } } fclose(fp); free(dx); free(dy); free(dz); free(ids); printf(" %d states extracted\n",state-1); return 1; } /* DCFAIL file */ int translate_dcfail(int handle) { int i,typid,num,filenum,state; LSDA_Length length; char dirname[256]; int *ids, *type; int have_torsion; float *area,*bend,*rate,*fail,*normal,*shear,*area_sol; float *axial_f,*shear_f,*torsion_m,*bending_m; float time; FILE *fp; LSDADir *dp = NULL; if (lsda_cd(handle,"/dcfail/metadata") == -1) return 0; printf("Extracting DCFAIL data\n"); /* Read metadata */ lsda_queryvar(handle,"ids",&typid,&length,&filenum); num = length; ids = (int *) malloc(num*sizeof(int)); type = (int *) malloc(num*sizeof(int)); area = (float *) malloc(11*num*sizeof(float)); bend = area + num; rate = bend + num; fail = rate + num; normal = fail + num; shear = normal + num; area_sol = shear + num; axial_f = area_sol + num; shear_f = axial_f + num; torsion_m = shear_f + num; bending_m = torsion_m + num; lsda_read(handle,LSDA_INT,"ids",0,num,ids); lsda_read(handle,LSDA_INT,"type",0,num,type); /* open file and write header */ sprintf(output_file,"%sdcfail",output_path); fp=fopen(output_file,"w"); write_message(fp,output_file); if (!fp) return 0; output_title(handle,"/dcfail/metadata",fp); /* Loop through time states and write each one. */ for(state=1; (dp = next_dir(handle,"/dcfail",dp,dirname)) != NULL; state++) { if(lsda_read(handle,LSDA_FLOAT,"time",0,1,&time) != 1) break; if(lsda_read(handle,LSDA_FLOAT,"area",0,num,area) != num) break; if(lsda_read(handle,LSDA_FLOAT,"bending_term",0,num,bend) != num) break; if(lsda_read(handle,LSDA_FLOAT,"effective_strain_rate",0,num,rate) != num) break; if(lsda_read(handle,LSDA_FLOAT,"failure_function",0,num,fail) != num) break; if(lsda_read(handle,LSDA_FLOAT,"normal_term",0,num,normal) != num) break; if(lsda_read(handle,LSDA_FLOAT,"shear_term",0,num,shear) != num) break; if(lsda_read(handle,LSDA_FLOAT,"area_sol",0,num,area_sol) != num) break; have_torsion=1; if(lsda_read(handle,LSDA_FLOAT,"axial_force",0,num,axial_f) != num) have_torsion=0; if(lsda_read(handle,LSDA_FLOAT,"shear_force",0,num,shear_f) != num) have_torsion=0; if(lsda_read(handle,LSDA_FLOAT,"torsional_moment",0,num,torsion_m) != num) have_torsion=0; if(lsda_read(handle,LSDA_FLOAT,"bending_moment",0,num,bending_m) != num) have_torsion=0; fprintf(fp,"\n define connection failure, time=%13.5E",time); fprintf(fp,"\n ele_id con_id fail_func normal "); fprintf(fp," bending shear area area_sol eff_e_rate"); if(have_torsion) fprintf(fp," axial force shear force torsion mom bending mom"); fprintf(fp,"\n"); for(i=0; i<num; i++) { fprintf(fp,"%10d%10d",ids[i],type[i]); fprintf(fp,"%13.5E%13.5E%13.5E",fail[i],normal[i],bend[i]); fprintf(fp,"%13.5E%13.5E%13.5E%13.5E",shear[i],area[i],area_sol[i],rate[i]); if(have_torsion) fprintf(fp,"%13.5E%13.5E%13.5E%13.5E",axial_f[i],shear_f[i],torsion_m[i],bending_m[i]); fprintf(fp,"\n"); } } fclose(fp); free(area); free(type); free(ids); printf(" %d states extracted\n",state-1); return 0; } /* TPRINT file */ int translate_tprint(int handle) { int i,typid,num,num0,filenum,state; LSDA_Length length; char dirname[128]; int *ids,maxnode,minnode,nstep,iteration,numsh12,numnp; float maxtemp,mintemp,*temp,temp_norm; float time,timestep,*t_bottom,*t_top; float *x_flux,*y_flux,*z_flux; FILE *fp; int *mx,nesum,itran,nummat,nbs,nfbc,ncbc,nrbc,nebc,nbnseg; int nthssf,nthssc,nthssr,nthsse,*idssfi,*idssci,*idssri,*idssei,nsl2d,nsl3d,*conid3d; float *dqgen,*qgen,*dh,*th,*esum,*sumf,*sumfdt,*sumc,*sume,*sumedt; float *sumcdt,*sumr,*sumrdt,*ebal2d,*ebal2ddt,*ebal3d,*ebal3ddt; LSDADir *dp = NULL; sprintf(dirname,"/tprint/d000001"); lsda_queryvar(handle,dirname,&typid,&length,&filenum); if(typid != 0) return 0; lsda_cd(handle,dirname); printf("Extracting TPRINT data\n"); lsda_queryvar(handle,"ids",&typid,&length,&filenum); num=length; num0=num; /* allocate memory to read in 1 state */ ids = (int *) malloc(num*sizeof(int)); temp = (float *) malloc(num*sizeof(float)); x_flux = (float *) malloc(num*sizeof(float)); y_flux = (float *) malloc(num*sizeof(float)); z_flux = (float *) malloc(num*sizeof(float)); lsda_queryvar(handle,"t_top",&typid,&length,&filenum); if(typid > 0) { t_top = (float *) malloc(num*sizeof(float)); t_bottom = (float *) malloc(num*sizeof(float)); } else { t_top = t_bottom = NULL; } lsda_queryvar(handle,"energy sum",&typid,&length,&filenum); nesum=length; esum = (float *) malloc(nesum*sizeof(int)); /* open file and write header */ sprintf(output_file,"%stprint",output_path); fp=fopen(output_file,"w"); write_message(fp,output_file); if (!fp) return 0; output_title(handle,"/tprint/metadata",fp); output_legend(handle,fp,1,1); /* Loop through time states and write each one */ for(state=1; (dp = next_dir(handle,"/tprint",dp,dirname)) != NULL; state++) { lsda_queryvar(handle,"ids",&typid,&length,&filenum); num=length; if(num > num0) { free(z_flux); free(y_flux); free(x_flux); free(temp); free(ids); ids = (int *) malloc(num*sizeof(int)); temp = (float *) malloc(num*sizeof(float)); x_flux = (float *) malloc(num*sizeof(float)); y_flux = (float *) malloc(num*sizeof(float)); z_flux = (float *) malloc(num*sizeof(float)); if(t_top) { free(t_top); free(t_bottom); t_top = (float *) malloc(num*sizeof(float)); t_bottom = (float *) malloc(num*sizeof(float)); } num0 = num; } if(lsda_read(handle,LSDA_INT,"ids",0,num,ids) != num) break; if(lsda_read(handle,LSDA_INT,"maxnode",0,1,&maxnode) != 1) break; if(lsda_read(handle,LSDA_FLOAT,"maxtemp",0,1,&maxtemp) != 1) break; if(lsda_read(handle,LSDA_INT,"minnode",0,1,&minnode) != 1) break; if(lsda_read(handle,LSDA_FLOAT,"mintemp",0,1,&mintemp) != 1) break; if(lsda_read(handle,LSDA_INT,"nstep",0,1,&nstep) != 1) break; if(lsda_read(handle,LSDA_INT,"solution_iterations",0,1,&iteration) != 1) break; if(lsda_read(handle,LSDA_FLOAT,"temperature",0,num,temp) != num) break; if(lsda_read(handle,LSDA_FLOAT,"temperature_norm",0,1,&temp_norm) != 1) break; if(lsda_read(handle,LSDA_FLOAT,"time",0,1,&time) != 1) break; if(lsda_read(handle,LSDA_FLOAT,"timestep",0,1,&timestep) != 1) break; if(lsda_read(handle,LSDA_FLOAT,"x_flux",0,num,x_flux) != num) break; if(lsda_read(handle,LSDA_FLOAT,"y_flux",0,num,y_flux) != num) break; if(lsda_read(handle,LSDA_FLOAT,"z_flux",0,num,z_flux) != num) break; if(lsda_read(handle,LSDA_INT,"itran",0,1,&itran) != 1) break; if(lsda_read(handle,LSDA_INT,"nbs",0,1,&nbs) != 1) break; if(lsda_read(handle,LSDA_INT,"nfbc",0,1,&nfbc) != 1) break; if(lsda_read(handle,LSDA_INT,"ncbc",0,1,&ncbc) != 1) break; if(lsda_read(handle,LSDA_INT,"nrbc",0,1,&nrbc) != 1) break; if(lsda_read(handle,LSDA_INT,"nebc",0,1,&nebc) != 1) break; if(lsda_read(handle,LSDA_INT,"nbnseg",0,1,&nbnseg) != 1) break; if(lsda_read(handle,LSDA_INT,"nthssf",0,1,&nthssf) != 1) break; if(lsda_read(handle,LSDA_INT,"nthssc",0,1,&nthssc) != 1) break; if(lsda_read(handle,LSDA_INT,"nthssr",0,1,&nthssr) != 1) break; if(lsda_read(handle,LSDA_INT,"nthsse",0,1,&nthsse) != 1) break; if(lsda_read(handle,LSDA_INT,"nsl2d",0,1,&nsl2d) != 1) break; if(lsda_read(handle,LSDA_INT,"nsl3d",0,1,&nsl3d) != 1) break; if(lsda_read(handle,LSDA_INT,"numnp",0,1,&numnp) != 1) break; if(lsda_read(handle,LSDA_INT,"numsh12",0,1,&numsh12) != 1) break; if(lsda_read(handle,LSDA_FLOAT,"energy sum",0,nesum,esum) != nesum) break; if (nsl2d>0) { ebal2d = (float *) malloc(nsl2d*sizeof(int)); ebal2ddt = (float *) malloc(nsl2d*sizeof(int)); if(lsda_read(handle,LSDA_FLOAT,"ebal2d",0,nsl2d,ebal2d) != nsl2d) break; if(lsda_read(handle,LSDA_FLOAT,"ebal2ddt",0,nsl2d,ebal2ddt) != nsl2d) break; } if (nsl3d>0) { conid3d = (int *) malloc(nsl3d*sizeof(int)); ebal3d = (float *) malloc(nsl3d*sizeof(int)); ebal3ddt = (float *) malloc(nsl3d*sizeof(int)); if(lsda_read(handle,LSDA_INT,"conid3d",0,nsl3d,conid3d) != nsl3d) break; if(lsda_read(handle,LSDA_FLOAT,"ebal3d",0,nsl3d,ebal3d) != nsl3d) break; if(lsda_read(handle,LSDA_FLOAT,"ebal3ddt",0,nsl3d,ebal3ddt) != nsl3d) break; } if (nbs>0) { if (nfbc>0) { if (nthssf!=0) { idssfi = (int *) malloc(nthssf*sizeof(int)); sumf = (float *) malloc(nthssf*sizeof(int)); sumfdt = (float *) malloc(nthssf*sizeof(int)); if(lsda_read(handle,LSDA_INT,"idssfi",0,nthssf,idssfi) != nthssf) break; if(lsda_read(handle,LSDA_FLOAT,"sumf",0,nthssf,sumf) != nthssf) break; if(lsda_read(handle,LSDA_FLOAT,"sumfdt",0,nthssf,sumfdt) != nthssf) break; } } if (ncbc>0) { if (nthssc!=0) { idssci = (int *) malloc(nthssc*sizeof(int)); sumc = (float *) malloc(nthssc*sizeof(int)); sumcdt = (float *) malloc(nthssc*sizeof(int)); if(lsda_read(handle,LSDA_INT,"idssci",0,nthssc,idssci) != nthssc) break; if(lsda_read(handle,LSDA_FLOAT,"sumc",0,nthssc,sumc) != nthssc) break; if(lsda_read(handle,LSDA_FLOAT,"sumcdt",0,nthssc,sumcdt) != nthssc) break; } } if (nrbc>0) { if (nthssr!=0) { idssri = (int *) malloc(nthssc*sizeof(int)); sumr = (float *) malloc(nthssr*sizeof(int)); sumrdt = (float *) malloc(nthssr*sizeof(int)); if(lsda_read(handle,LSDA_INT,"idssri",0,nthssr,idssri) != nthssr) break; if(lsda_read(handle,LSDA_FLOAT,"sumr",0,nthssr,sumr) != nthssr) break; if(lsda_read(handle,LSDA_FLOAT,"sumrdt",0,nthssr,sumrdt) != nthssr) break; } } if (nebc>0) { if (nthsse!=0) { idssei = (int *) malloc(nthsse*sizeof(int)); sume = (float *) malloc(nthsse*sizeof(int)); sumedt = (float *) malloc(nthsse*sizeof(int)); if(lsda_read(handle,LSDA_INT,"idssei",0,nthsse,idssei) != nthsse) break; if(lsda_read(handle,LSDA_FLOAT,"sume",0,nthsse,sume) != nthsse) break; if(lsda_read(handle,LSDA_FLOAT,"sumedt",0,nthsse,sumedt) != nthsse) break; } } } if(t_top) { if(lsda_read(handle,LSDA_FLOAT,"t_top",0,num,t_top) != num) break; if(lsda_read(handle,LSDA_FLOAT,"t_bottom",0,num,t_bottom) != num) break; } if(lsda_read(handle,LSDA_INT,"nummat",0,1,&nummat) != 1) break; mx = (int *) malloc(nummat*sizeof(int)); dqgen = (float *) malloc(nummat*sizeof(int)); qgen = (float *) malloc(nummat*sizeof(int)); dh = (float *) malloc(nummat*sizeof(int)); th = (float *) malloc(nummat*sizeof(int)); if(lsda_read(handle,LSDA_INT,"mat ids",0,nummat,mx) != nummat) break; if(lsda_read(handle,LSDA_FLOAT,"heat generated",0,nummat,dqgen) != nummat) break; if(lsda_read(handle,LSDA_FLOAT,"total heat gen",0,nummat,qgen) != nummat) break; if(lsda_read(handle,LSDA_FLOAT,"energy change",0,nummat,dh) != nummat) break; if(lsda_read(handle,LSDA_FLOAT,"total energy change",0,nummat,th) != nummat) break; fprintf(fp," ****************************************"); fprintf(fp,"******************************\n\n"); if (itran!=0) { fprintf(fp," time =%12.4E time step =%12.4E thermal step no.=%6d\n\n", time,timestep,nstep); } else { fprintf(fp," steady state solution\n\n"); } fprintf(fp," minimum temperature = %12.4E at node %8d\n",mintemp,minnode); fprintf(fp," maximum temperature = %12.4E at node %8d\n\n",maxtemp,maxnode); if(t_top) { fprintf(fp," node temperature t-bottom t-top x-flux y-flux z-flux\n\n"); for(i=0; i<num; i++) { /* check for valid data -- only some nodes have actual data here */ if(t_bottom[i] > -1.e+10) { fprintf(fp,"%8d%12.4E%12.4E%12.4E%12.4E%12.4E%12.4E\n",ids[i],temp[i],t_bottom[i],t_top[i],x_flux[i],y_flux[i],z_flux[i]); } else { fprintf(fp,"%8d%12.4E %12.4E%12.4E%12.4E\n",ids[i],temp[i],x_flux[i],y_flux[i],z_flux[i]); } } } else { fprintf(fp,"*TEMPERATURE_NODE numnode=%10d thkshl=%10d\n",numnp,numsh12); fprintf(fp," node temperature x-flux y-flux z-flux\n\n"); for(i=0; i<num; i++) { fprintf(fp,"%8d%12.4E%12.4E%12.4E%12.4E\n",ids[i],temp[i],x_flux[i],y_flux[i],z_flux[i]); } } if (nbs!=0) { fprintf(fp,"\n Boundary condition segment set heat transfer rate [energy/time]\n"); fprintf(fp," Positive heat flow is in direction of the surface outward normal vector\n"); fprintf(fp," NOTE: energy sum may not be 0. This depends on the model definition\n"); fprintf(fp," Such as, surfaces with temperature boundary conditions are not included.\n"); fprintf(fp,"\n*ENERGY_BOUNDARY nfbc=%10d ncbc=%10d nrbc=%10d\n",nthssf,nthssc,nthssr); fprintf(fp," bc type seg set [energy/time] [energy]\n"); if (nfbc>0) { for(i=0; i<nthssf; i++) { fprintf(fp," flux %10d%16.4E%16.4E\n",idssfi[i],sumf[i],sumfdt[i]); } } if (ncbc>0) { for(i=0; i<nthssc; i++) { fprintf(fp," convection%10d%16.4E%16.4E\n",idssci[i],sumc[i],sumcdt[i]); } } if (nrbc>0) { for(i=0; i<nthssr; i++) { fprintf(fp," radiation %10d%16.4E%16.4E\n",idssri[i],sumr[i],sumrdt[i]); } } if (nebc>0) { for(i=0; i<nthsse; i++) { fprintf(fp," enclosure %8d %12.4E %12.4E\n",idssei[i],sume[i],sumedt[i]); } } } fprintf(fp," ----------- -----------\n"); fprintf(fp," energy sum =%12.4E %12.4E\n\n",esum[0],esum[1]); if (nsl2d!=0 || nsl3d!=0) { fprintf(fp,"\n contact surface heat transfer rate\n"); fprintf(fp," positive heat flow is in direction of master-->slave\n"); if (nsl2d>0) fprintf(fp,"\n*ENERGY_CONTACT ncont=%10d\n",nsl2d); if (nsl3d>0) fprintf(fp,"\n*ENERGY_CONTACT ncont=%10d\n",nsl3d); if (nsl2d>0) fprintf(fp," order# [energy/time] [energy]\n"); if (nsl3d>0) fprintf(fp," order# contact_id [energy/time] [energy]\n"); if (nsl2d!=0) { for(i=0; i<nsl2d; i++) { fprintf(fp,"%10d%16.4E%16.4E\n",i+1,ebal2d[i],ebal2ddt[i]); } } if (nsl3d!=0) { for(i=0; i<nsl3d; i++) { fprintf(fp,"%10d%10d%16.4E%16.4E\n",i+1,conid3d[i],ebal3d[i],ebal3ddt[i]); } } } fprintf(fp,"\n*ENERGY_PART npart=%10d\n",nummat); fprintf(fp," part # Qgen_chg[energy] Qgen_tot[energy] IE_chg[energy] IE_tot[energy]\n"); for(i=0; i<nummat; i++) { fprintf(fp,"%8d%16.4E%16.4E%16.4E%16.4E\n",mx[i],dqgen[i],qgen[i],dh[i],th[i]); } fprintf(fp,"\n number of solution iterations =%5d\n\n",iteration); fprintf(fp, " QA temperature norm, Tmin, Tmax= %12.4E %12.4E %12.4E\n\n",temp_norm,mintemp,maxtemp); } fclose(fp); free(z_flux); free(y_flux); free(x_flux); free(temp); free(ids); if (nfbc>0) { free(idssfi); free(sumf); free(sumfdt); } if (ncbc>0) { free(idssci); free(sumc); free(sumcdt); } if (nrbc>0) { free(idssri); free(sumr); free(sumrdt); } if (nebc>0) { free(idssei); free(sume); free(sumedt); } if (nummat>0) { free(mx); free(dqgen); free(qgen); free(dh); free(th); } if (nesum>0) { free(esum); } if (nsl2d>0) { free(ebal2d); free(ebal2ddt); } if (nsl3d>0) { free(conid3d); free(ebal3d); free(ebal3ddt); } if(t_top) { free(t_top); free(t_bottom); } printf(" %d states extracted\n",state-1); return 0; } /* TRHIST file */ int translate_trhist(int handle) { int i,typid,num,num0,filenum,state; LSDA_Length length; char dirname[128]; int maxnode,minnode,nstep,iteration; float maxtemp,mintemp,*temp,temp_norm; float time,timestep,*t_bottom,*t_top; float *fiop,*x,*y,*z,*vx,*vy,*vz,*sx,*sy,*sz,*sxy,*syz,*szx,*efp,*rvl,*rho; FILE *fp; LSDADir *dp = NULL; if (lsda_cd(handle,"/trhist/metadata") == -1) return 0; printf("Extracting TRHIST data\n"); sprintf(dirname,"/trhist/d000001"); lsda_cd(handle,dirname); lsda_queryvar(handle,"fiop",&typid,&length,&filenum); num=length; /* allocate memory to read in 1 state */ fiop = (float *) malloc(num*sizeof(float)); x = (float *) malloc(num*sizeof(float)); y = (float *) malloc(num*sizeof(float)); z = (float *) malloc(num*sizeof(float)); vx = (float *) malloc(num*sizeof(float)); vy = (float *) malloc(num*sizeof(float)); vz = (float *) malloc(num*sizeof(float)); sx = (float *) malloc(num*sizeof(float)); sy = (float *) malloc(num*sizeof(float)); sz = (float *) malloc(num*sizeof(float)); sxy = (float *) malloc(num*sizeof(float)); syz = (float *) malloc(num*sizeof(float)); szx = (float *) malloc(num*sizeof(float)); efp = (float *) malloc(num*sizeof(float)); rvl = (float *) malloc(num*sizeof(float)); rho = (float *) malloc(num*sizeof(float)); /* open file and write header */ sprintf(output_file,"%strhist",output_path); fp=fopen(output_file,"w"); write_message(fp,output_file); if (!fp) return 0; fprintf(fp,"Tracer particle file\n"); fprintf(fp,"%5d 16\n",num); fprintf(fp," x y z vx vy vz\n"); fprintf(fp," sx sy sz sxy syz szx\n"); fprintf(fp," efp rho rvol active\n"); /* output_title(handle,"/trhist/metadata",fp); output_legend(handle,fp,1,1); Loop through time states and write each one */ for(state=1; (dp = next_dir(handle,"/trhist",dp,dirname)) != NULL; state++) { if(lsda_read(handle,LSDA_FLOAT,"time",0,1,&time) != 1) break; if(lsda_read(handle,LSDA_FLOAT,"fiop",0,num,fiop) != num) break; if(lsda_read(handle,LSDA_FLOAT,"x",0,num,x) != num) break; if(lsda_read(handle,LSDA_FLOAT,"y",0,num,y) != num) break; if(lsda_read(handle,LSDA_FLOAT,"z",0,num,z) != num) break; if(lsda_read(handle,LSDA_FLOAT,"vx",0,num,vx) != num) break; if(lsda_read(handle,LSDA_FLOAT,"vy",0,num,vy) != num) break; if(lsda_read(handle,LSDA_FLOAT,"vz",0,num,vz) != num) break; if(lsda_read(handle,LSDA_FLOAT,"sx",0,num,sx) != num) break; if(lsda_read(handle,LSDA_FLOAT,"sy",0,num,sy) != num) break; if(lsda_read(handle,LSDA_FLOAT,"sz",0,num,sz) != num) break; if(lsda_read(handle,LSDA_FLOAT,"sxy",0,num,sxy) != num) break; if(lsda_read(handle,LSDA_FLOAT,"syz",0,num,syz) != num) break; if(lsda_read(handle,LSDA_FLOAT,"szx",0,num,szx) != num) break; if(lsda_read(handle,LSDA_FLOAT,"efp",0,num,efp) != num) break; if(lsda_read(handle,LSDA_FLOAT,"rvl",0,num,rvl) != num) break; if(lsda_read(handle,LSDA_FLOAT,"rho",0,num,rho) != num) break; fprintf(fp,"%13.5E\n",time); for (i=0;i<num;i++) { fprintf(fp,"%13.5E%13.5E%13.5E%13.5E%13.5E%13.5E\n",x[i],y[i],z[i],vx[i],vy[i],vz[i]); fprintf(fp,"%13.5E%13.5E%13.5E%13.5E%13.5E%13.5E\n",sx[i],sy[i],sz[i],sxy[i],syz[i],szx[i]); fprintf(fp,"%13.5E%13.5E%13.5E%13.5E\n",efp[i],rho[i],rvl[i],fiop[i]); } } fclose(fp); free(rho); free(rvl); free(efp); free(szx); free(syz); free(sxy); free(sz); free(sy); free(sx); free(vz); free(vy); free(vx); free(z); free(y); free(x); free(fiop); printf(" %d states extracted\n",state-1); return 0; } /* ALE DBSENSOR file */ int translate_dbsensor(int handle) { int i,typid,num,num0,filenum,state; LSDA_Length length; char dirname[128]; float time,timestep; float *x,*y,*z,*pres,*temp; int *ids,*id_solid; FILE *fp; LSDADir *dp = NULL; if (lsda_cd(handle,"/dbsensor/metadata") == -1) return 0; printf("Extracting DBSENSOR data\n"); /* Read metadata */ lsda_queryvar(handle,"ids",&typid,&length,&filenum); num = length; ids = (int *) malloc(num*sizeof(int)); x = (float *) malloc(num*sizeof(float)); y = (float *) malloc(num*sizeof(float)); z = (float *) malloc(num*sizeof(float)); pres = (float *) malloc(num*sizeof(float)); temp = (float *) malloc(num*sizeof(float)); id_solid = (int *) malloc(num*sizeof(int)); lsda_read(handle,LSDA_INT,"ids",0,num,ids); /* open file and write header */ sprintf(output_file,"%sdbsensor",output_path); fp=fopen(output_file,"w"); write_message(fp,output_file); if (!fp) return 0; fprintf(fp," ALE sensors output\n"); fprintf(fp," Number of sensors:%10d\n\n\n\n",num); fprintf(fp," id x y z p Cpld Solid"); for(state=1; (dp = next_dir(handle,"/dbsensor",dp,dirname)) != NULL; state++) { if(lsda_read(handle,LSDA_FLOAT,"time",0,1,&time) != 1) break; if(lsda_read(handle,LSDA_FLOAT,"x",0,num,x) != num) break; if(lsda_read(handle,LSDA_FLOAT,"y",0,num,y) != num) break; if(lsda_read(handle,LSDA_FLOAT,"z",0,num,z) != num) break; if(lsda_read(handle,LSDA_FLOAT,"pressure",0,num,pres) != num) break; if(lsda_read(handle,LSDA_FLOAT,"temperature",0,num,temp) != num) break; if(lsda_read(handle,LSDA_INT ,"solid_id",0,num,id_solid) != num) break; fprintf(fp,"\n time=%13.5E\n",time); for (i=0;i<num;i++) { fprintf(fp,"%10d%14.4E%14.4E%14.4E%14.4E%10d%14.4E\n",ids[i],x[i],y[i],z[i],pres[i],id_solid[i],temp[i]); } } fclose(fp); free(id_solid); free(temp); free(pres); free(z); free(y); free(x); free(ids); printf(" %d states extracted\n",state-1); return 0; } /* ALE FSI file */ int translate_dbfsi(int handle) { int i,typid,num,num0,filenum,state; LSDA_Length length; char dirname[128]; float time,timestep; float *fx,*fy,*fz,*pres,*pleak,*flux,*gx,*gy,*gz,*Ptmp,*PDt; int *ids; FILE *fp; LSDADir *dp = NULL; if (lsda_cd(handle,"/dbfsi/metadata") == -1) return 0; printf("Extracting DBFSI data\n"); /* Read metadata */ lsda_queryvar(handle,"ids",&typid,&length,&filenum); num = length; ids = (int *) malloc(num*sizeof(int)); pres = (float *) malloc(num*sizeof(float)); fx = (float *) malloc(num*sizeof(float)); fy = (float *) malloc(num*sizeof(float)); fz = (float *) malloc(num*sizeof(float)); pleak = (float *) malloc(num*sizeof(float)); flux = (float *) malloc(num*sizeof(float)); gx = (float *) malloc(num*sizeof(float)); gy = (float *) malloc(num*sizeof(float)); gz = (float *) malloc(num*sizeof(float)); Ptmp = (float *) malloc(num*sizeof(float)); PDt = (float *) malloc(num*sizeof(float)); lsda_read(handle,LSDA_INT,"ids",0,num,ids); /* open file and write header */ sprintf(output_file,"%sdbfsi",output_path); fp=fopen(output_file,"w"); write_message(fp,output_file); if (!fp) return 0; fprintf(fp," Fluid-structure interaction output\n"); fprintf(fp," Number of surfaces:%10d\n\n",num); fprintf(fp," id p fx fy fz mout\n obsolete fx-lc fy-lc fz-lc Ptemp PDtmp\n"); for(state=1; (dp = next_dir(handle,"/dbfsi",dp,dirname)) != NULL; state++) { if(lsda_read(handle,LSDA_FLOAT,"time",0,1,&time) != 1) break; if(lsda_read(handle,LSDA_FLOAT,"fx",0,num,fx) != num) break; if(lsda_read(handle,LSDA_FLOAT,"fy",0,num,fy) != num) break; if(lsda_read(handle,LSDA_FLOAT,"fz",0,num,fz) != num) break; if(lsda_read(handle,LSDA_FLOAT,"pres",0,num,pres) != num) break; if(lsda_read(handle,LSDA_FLOAT,"mout",0,num,pleak) != num) break; if(lsda_read(handle,LSDA_FLOAT,"obsolete",0,num,flux) != num) break; if(lsda_read(handle,LSDA_FLOAT,"gx",0,num,gx) != num) break; if(lsda_read(handle,LSDA_FLOAT,"gy",0,num,gy) != num) break; if(lsda_read(handle,LSDA_FLOAT,"gz",0,num,gz) != num) break; if(lsda_read(handle,LSDA_FLOAT,"Ptmp",0,num,Ptmp) != num) break; if(lsda_read(handle,LSDA_FLOAT,"PDt",0,num,PDt) != num) break; fprintf(fp," time=%13.5E\n",time); for (i=0;i<num;i++) { fprintf(fp,"%10d%14.4E%14.4E%14.4E%14.4E%14.4E\n",ids[i],pres[i],fx[i],fy[i],fz[i],pleak[i]); fprintf(fp," %14.4E%14.4E%14.4E%14.4E%14.4E%14.4E\n\n",flux[i],gx[i],gy[i],gz[i],Ptmp[i],PDt[i]); } } fclose(fp); free(PDt); free(Ptmp); free(gz); free(gy); free(gx); free(flux); free(pleak); free(fz); free(fy); free(fx); free(pres); free(ids); printf(" %d states extracted\n",state-1); return 0; } static char *tochar2(float value,int len) { static char s[20]; db_floating_format(value, len, s, 0, len-1); return s; } static void db_floating_format(float a, int fw, char *output, int tzero, int nsigs) /* ============================== ** ** Takes floating point value <a> and renders it "nicely" in a field width ** of <fw>, returning the output right-justified as a character string in ** <output>. The last character + 1 will be a zero termination. ** ** "Nicely" means it does its best to utilise the field width to get the ** best precision out of the number, but culls any silly looking trailing ** zeros. It also tries to eliminate any spurious "noise" values by limiting ** mantissa digits to the precision of the incoming argument. ** ** The reason for this distinction is that we can sometimes need to restrict ** the fractional precision of the mantissa of numbers to avoid writing out ** extra, spurious digits that give noise. ** ** If <tzero> is true then trailing zeros are permitted. ** ** <nsigs> is max number of mantissa sig figures, usually 7 or 8. ** ** Field width should not exceed 80, and values less than 8 will probably ** give silly results. ** ** Modified 23/6/2004 to give slightly improved precision for numbers written ** without an exponent, and also to make numbers less than 0.1xxx be written in ** exponential form, (Previously was < 0.01xxx). This prevents unnecessary ** truncation of precision at field widths > 10. */ { double b, c, d; int j, k, l, n, np, mw, nf; char b2[81], form[20], *p; /* Zero is a special case */ if(a == 0.0) { for(j=0; j<fw-3; j++) output[j] = ' '; strcpy(output+fw-3, "0.0"); return; } /* Get magnitude power (ie exponent) of incoming value as an integer */ j = log10(fabs(a)) + 0.0000000001; /* Use an exponent if the value lies outside the range e7 : e-1, ** but we need exponential format if this is too wide for the ** data field. */ if(fw < 10) /* Small field limits precision */ { if(a < 0.0) np = 5; else np = 6; } else { np = 7; } make_exp: if(j > np || j < 0) /* Try for an exponential format */ { if(j < 0) --j; /* Puts a digit before decimal point */ c = j; d = pow(10.0, c); /* Scale factor of exponent */ c = a / d; /* Factored |mantissa| */ n = 1; /* To flag exponent size calc */ } else /* Non-exponential case */ { c = a; d = 1.0; n = 0; } loop: /* Work out how many characters the exponent will require */ if(n) { if(j > 99) n = 4; /* #characters for exponent */ else if(j > 9) n = 3; else if(j > -1) n = 2; else if(j > -10) n = 3; else if(j > -100) n = 4; else n = 5; } /* Mantissa width depends on field width, less any exponent */ mw = fw - n; /* Number of fractional places depends on magnitude, precision, and whether we ** need to add a "-" sign. */ nf = mw - 2; /* Space for leading digit and decimal point. */ if(a < 0.0) --nf; /* Space for "-" sign. */ /* Apply effect of rounding at this fractional precision, and recalculate ** exponent size if round changes order of magnitude. */ if(n) { b = -nf - 1; b = pow(10.0, b) * 5.0; if(fabs(c)+b >= 10.0) { c /= 10.0; j += 1; goto loop; } } /* Experience on different hardware shows that the 8th sig fig may vary, I presume ** because of rounding/truncation differences between single and double precision ** variables on the different machines. Trial and error shows that multiplying ** by the following factor reconciles these differences - not a lot of science ** behind this, but it has the merit of working and means that the "common" format ** can give identical output on different hardware! CB 9/9/2004 */ c *= 1.0000000001; /* Correct for rounding/truncation hardware differences */ /* We may need to restrict the resolution of the mantissa fraction to avoid ** getting nunerical noise from attempting to output significant figures for ** which we don't have sufficient data resolution. ** ** The detailed strategy varies because while the exponential case has fixed ** #decimal places, the "fixed" mantissa #decimal places varies. ** ** Note that we could write "if(!n) k = fabs(c) < 1.0 ? j : j+1;" below if we ** wished to eliminate the possibly spurious 8th sig fig. */ if(!n) k = fabs(c) < 1.0 ? j-1 : j; /* Allow for value before point */ else k = 0; /* Permit variable #sig figs */ /* if(nf > 7 - k) nf = 7 - k; */ if(nf > (l = nsigs - 1 - k)) nf = l; /* Non-exponential case, not enough space for decimal places */ if(!n) { j = fw - k - 1; /* Space for digits before point, + point itself */ if(a < 0.0) --j; /* Space for minus sign */ if(nf > j) nf = j; /* Truncate decimal places if necessary */ if(nf < 0) nf = 0; } /* Write mantissa format statement, and hence the mantissa itself */ prec: sprintf(form, "%%#%d.%df", mw, nf); sprintf(b2, form, c); /* Check for non-exponential overflow */ if(!n && !nf && b2[mw]) { j = log10(fabs(a)) + 0.0000000001; if(j < 0) --j; /* Puts a digit before decimal point */ c = j; d = pow(10.0, c); /* Scale factor of exponent */ c = a / d; /* Factored |mantissa| */ n = 1; /* To flag exponent size calc */ goto loop; } /* And for rounding up "looks odd" error in exponential cases (ie 10.0e-5 instead of 1.0e-4) */ else if(n) { if(strstr(b2, "10.")) { c = ++j; d = pow(10.0, c); /* Scale factor of exponent */ c = a / d; /* Factored |mantissa| */ n = 1; /* To flag exponent size calc */ goto loop; } } /* Remove any trailing zeros ... */ if(!tzero) { k = 0; p = b2+mw-1; while (*p == '0') { --p; ++k; } /* ... but if we've arrived at a decimal point then permit one zero. */ if(*p == '.') --k; /* Shift string to the right to permit subsequent overwrite of trailing zeros, ** filling vacated leading bytes with spaces. */ if(k > 0) { memmove(b2+k, b2, mw); /* Can copy overlapping objects */ p = b2; while(k--) *p++ = ' '; } /* Otherwise check for possible spurious 8th sig fig. Originally I thought that ** this could be limited to ...999 and ...001, but it seems that ...998 is ** possible (try value 0.9 in single precision), so I assume ...002 is too. ** Therefore I'm now looking at ...00* and ...99* where "*" is in round up/down ** territory as appropriate. */ else if(nf > 1) { p = b2+mw-3; if((strncmp(p, "00", 2) == 0 && *(p+2) < '5') || (strncmp(p, "99", 2) == 0 && *(p+2) > '5')) { --nf; goto prec; } } /* Check for "xxxxxxx00." too, which is better expressed exponentially since we ** can afford to lose the precision */ else if(nf == 0) { p = b2+mw-3; if(strcmp(p, "00.") == 0) { np = -1; goto make_exp; } } } /* Add the exponent if required, or just zero terminate string if no exponent */ switch(n) { case 0: *(b2+mw) = '\0'; break; case 2: sprintf(b2+mw, "E%1d", j); break; case 3: sprintf(b2+mw, "E%2d", j); break; case 4: sprintf(b2+mw, "E%3d", j); break; } /* Copy into output string (include terminating zero) */ memcpy(output, b2, fw+1); } /* ELOUT_SSD file */ int translate_elout_ssd(int handle) { int i,j,k,l,m,n,typid,filenum,state; LSDA_Length length; int have_solid, have_tshell, have_beam, have_shell; FILE *fp; char path[30]; int nfreq; int h_num , h_nfreq, h_ncomp, h_lnum; int t_num , t_nfreq, t_ncomp, t_maxint, t_lnum; int b_num , b_nfreq, b_ncomp, b_lnum; int s_num , s_nfreq, s_ncomp, s_maxint, s_lnum; int *h_uid; int *t_uid; int *b_uid; int *s_uid; float h_freq, *h_angle, *h_ampil; float t_freq, *t_angle, *t_ampil; float b_freq, *b_angle, *b_ampil; float s_freq, *s_angle, *s_ampil; char title_location[128]; if (lsda_cd(handle,"/elout_ssd") == -1) return 0; printf("Extracting ELOUT_SSD data\n"); lsda_queryvar(handle,"/elout_ssd/solid",&typid,&length,&filenum); have_solid= (typid >= 0); lsda_queryvar(handle,"/elout_ssd/thickshell",&typid,&length,&filenum); have_tshell= (typid >= 0); lsda_queryvar(handle,"/elout_ssd/beam",&typid,&length,&filenum); have_beam= (typid >= 0); lsda_queryvar(handle,"/elout_ssd/shell",&typid,&length,&filenum); have_shell= (typid >= 0); title_location[0]=0; /* Read metadata Solids */ if(have_solid) { lsda_cd(handle,"/elout_ssd/solid/metadata"); strcpy(title_location,"/elout_ssd/solid/metadata"); lsda_read(handle,LSDA_INT,"n_elem", 0,1,&h_num); lsda_read(handle,LSDA_INT,"nfreq_ssd",0,1,&h_nfreq); lsda_read(handle,LSDA_INT,"ncomp", 0,1,&h_ncomp); nfreq = h_nfreq; h_uid = (int *) malloc(h_num*sizeof(int)); lsda_read(handle,LSDA_INT,"uid",0,h_num,h_uid); h_lnum = h_ncomp*h_num; h_ampil = (float *) malloc(h_lnum*sizeof(float)); h_angle = (float *) malloc(h_lnum*sizeof(float)); } /* thick shells */ if(have_tshell) { lsda_cd(handle,"/elout_ssd/thickshell/metadata"); strcpy(title_location,"/elout_ssd/thickshell/metadata"); lsda_read(handle,LSDA_INT,"n_elem", 0,1,&t_num); lsda_read(handle,LSDA_INT,"nfreq_ssd",0,1,&t_nfreq); lsda_read(handle,LSDA_INT,"ncomp", 0,1,&t_ncomp); lsda_read(handle,LSDA_INT,"maxint", 0,1,&t_maxint); nfreq = t_nfreq; t_uid = (int *) malloc(t_num*sizeof(int)); lsda_read(handle,LSDA_INT,"uid",0,t_num,t_uid); t_lnum = t_ncomp*t_num; t_ampil = (float *) malloc(t_lnum*sizeof(float)); t_angle = (float *) malloc(t_lnum*sizeof(float)); } /* beams */ if(have_beam) { lsda_cd(handle,"/elout_ssd/beam/metadata"); strcpy(title_location,"/elout_ssd/beam/metadata"); lsda_read(handle,LSDA_INT,"n_elem", 0,1,&b_num); lsda_read(handle,LSDA_INT,"nfreq_ssd",0,1,&b_nfreq); lsda_read(handle,LSDA_INT,"ncomp", 0,1,&b_ncomp); nfreq = b_nfreq; b_uid = (int *) malloc(b_num*sizeof(int)); lsda_read(handle,LSDA_INT,"uid",0,b_num,b_uid); b_lnum = b_ncomp*b_num; b_ampil = (float *) malloc(b_lnum*sizeof(float)); b_angle = (float *) malloc(b_lnum*sizeof(float)); } /* shells */ if(have_shell) { lsda_cd(handle,"/elout_ssd/shell/metadata"); strcpy(title_location,"/elout_ssd/shell/metadata"); lsda_read(handle,LSDA_INT,"n_elem", 0,1,&s_num); lsda_read(handle,LSDA_INT,"nfreq_ssd",0,1,&s_nfreq); lsda_read(handle,LSDA_INT,"ncomp", 0,1,&s_ncomp); lsda_read(handle,LSDA_INT,"maxint", 0,1,&s_maxint); nfreq = s_nfreq; s_uid = (int *) malloc(s_num*sizeof(int)); lsda_read(handle,LSDA_INT,"uid",0,s_num,s_uid); s_lnum = s_ncomp*s_num; s_ampil = (float *) malloc(s_lnum*sizeof(float)); s_angle = (float *) malloc(s_lnum*sizeof(float)); } if(strlen(title_location) == 0) return 0; /* open file and write header */ sprintf(output_file,"%selout_ssd",output_path); fp=fopen(output_file,"w"); write_message(fp,output_file); if (!fp) return 0; output_title(handle,title_location,fp); output_legend(handle,fp,1,1); fprintf(fp," S t e a d y S t a t e D y n a m i c s\n\n"); /* Loop through frequency states and write each one */ for(state=1;(have_solid || have_tshell || have_beam || have_shell) && state<=nfreq ; state++) { if(have_solid) { if(state<=999999) sprintf(path,"/elout_ssd/solid/d%6.6d",state); else sprintf(path,"/elout_ssd/solid/d%8.8d",state); lsda_cd(handle,path); if(lsda_read(handle,LSDA_FLOAT,"frequency",0,1,&h_freq) != 1) break; if(lsda_read(handle,LSDA_FLOAT,"amplitude",0,h_lnum,h_ampil) != h_lnum) break; if(lsda_read(handle,LSDA_FLOAT,"angle",0,h_lnum,h_angle) != h_lnum) break; fprintf(fp,"\n element stress calculations for frequency = %12.5E\n\n",h_freq); fprintf(fp," solid sig-xx sig-yy sig-"); fprintf(fp,"zz sig-xy sig-yz sig-zx\n"); for (m=0; m<h_num; m++) { fprintf(fp,"%10d-\n",h_uid[m]); l=h_ncomp*m; fprintf(fp," amplitude %12.4E %12.4E %12.4E %12.4E %12.4E %12.4E\n",h_ampil[l],h_ampil[l+1],h_ampil[l+2],h_ampil[l+3],h_ampil[l+4],h_ampil[l+5]); fprintf(fp," angle %12.4E %12.4E %12.4E %12.4E %12.4E %12.4E\n",h_angle[l],h_angle[l+1],h_angle[l+2],h_angle[l+3],h_angle[l+4],h_angle[l+5]); } if (h_ncomp>7) { fprintf(fp,"\n"); fprintf(fp," solid eps-xx eps-yy eps-"); fprintf(fp,"zz eps-xy eps-yz eps-zx\n"); for (m=0; m<h_num; m++) { fprintf(fp,"%10d-\n",h_uid[m]); l=h_ncomp*m+7; fprintf(fp," amplitude %12.4E %12.4E %12.4E %12.4E %12.4E %12.4E\n",h_ampil[l],h_ampil[l+1],h_ampil[l+2],h_ampil[l+3],h_ampil[l+4],h_ampil[l+5]); fprintf(fp," angle %12.4E %12.4E %12.4E %12.4E %12.4E %12.4E\n",h_angle[l],h_angle[l+1],h_angle[l+2],h_angle[l+3],h_angle[l+4],h_angle[l+5]); } } } if(have_tshell) { if(state<=999999) sprintf(path,"/elout_ssd/thickshell/d%6.6d",state); else sprintf(path,"/elout_ssd/thickshell/d%8.8d",state); lsda_cd(handle,path); if(lsda_read(handle,LSDA_FLOAT,"frequency",0,1,&t_freq) != 1) break; if(lsda_read(handle,LSDA_FLOAT,"amplitude",0,t_lnum,t_ampil) != t_lnum) break; if(lsda_read(handle,LSDA_FLOAT,"angle",0,t_lnum,t_angle) != t_lnum) break; fprintf(fp,"\n element stress calculations for frequency = %12.5E\n\n",t_freq); fprintf(fp," ipt- thickshl sig-xx sig-yy sig-"); fprintf(fp,"zz sig-xy sig-yz sig-zx\n"); for (m=0; m<t_num; m++) { fprintf(fp,"%10d-\n",t_uid[m]); for(n=0;n<t_maxint;n++) { l=t_ncomp*m + 7*n; fprintf(fp,"%4d- amplitude %12.4E %12.4E %12.4E %12.4E %12.4E %12.4E\n",n+1,t_ampil[l],t_ampil[l+1],t_ampil[l+2],t_ampil[l+3],t_ampil[l+4],t_ampil[l+5]); fprintf(fp,"%4d- angle %12.4E %12.4E %12.4E %12.4E %12.4E %12.4E\n",n+1,t_angle[l],t_angle[l+1],t_angle[l+2],t_angle[l+3],t_angle[l+4],t_angle[l+5]); } } if (t_ncomp>7*t_maxint) { fprintf(fp,"\n"); fprintf(fp," ipt- thickshl eps-xx eps-yy eps-"); fprintf(fp,"zz eps-xy eps-yz eps-zx\n"); for (m=0; m<t_num; m++) { fprintf(fp,"%10d-\n",t_uid[m]); l=t_ncomp*m + 7*t_maxint; fprintf(fp," lower ipt- amp %12.4E %12.4E %12.4E %12.4E %12.4E %12.4E\n",t_ampil[l],t_ampil[l+1],t_ampil[l+2],t_ampil[l+3],t_ampil[l+4],t_ampil[l+5]); fprintf(fp," lower ipt- ang %12.4E %12.4E %12.4E %12.4E %12.4E %12.4E\n",t_angle[l],t_angle[l+1],t_angle[l+2],t_angle[l+3],t_angle[l+4],t_angle[l+5]); l=t_ncomp*m + 7*t_maxint+6; fprintf(fp," upper ipt- amp %12.4E %12.4E %12.4E %12.4E %12.4E %12.4E\n",t_ampil[l],t_ampil[l+1],t_ampil[l+2],t_ampil[l+3],t_ampil[l+4],t_ampil[l+5]); fprintf(fp," upper ipt- ang %12.4E %12.4E %12.4E %12.4E %12.4E %12.4E\n",t_angle[l],t_angle[l+1],t_angle[l+2],t_angle[l+3],t_angle[l+4],t_angle[l+5]); } } } if(have_beam) { if(state<=999999) sprintf(path,"/elout_ssd/beam/d%6.6d",state); else sprintf(path,"/elout_ssd/beam/d%8.8d",state); lsda_cd(handle,path); if(lsda_read(handle,LSDA_FLOAT,"frequency",0,1,&b_freq) != 1) break; if(lsda_read(handle,LSDA_FLOAT,"amplitude",0,b_lnum,b_ampil) != b_lnum) break; if(lsda_read(handle,LSDA_FLOAT,"angle",0,b_lnum,b_angle) != b_lnum) break; fprintf(fp,"\n\n element stress calculations for frequency = %12.5E\n\n",b_freq); fprintf(fp," resultants axial shear-s she"); fprintf(fp,"ar-t moment-s moment-t torsion\n"); for (m=0; m<b_num; m++) { fprintf(fp,"%10d-\n",b_uid[m]); l=b_ncomp*m; fprintf(fp," amplitude %12.4E %12.4E %12.4E %12.4E %12.4E %12.4E\n",b_ampil[l],b_ampil[l+1],b_ampil[l+2],b_ampil[l+3],b_ampil[l+4],b_ampil[l+5]); fprintf(fp," angle %12.4E %12.4E %12.4E %12.4E %12.4E %12.4E\n",b_angle[l],b_angle[l+1],b_angle[l+2],b_angle[l+3],b_angle[l+4],b_angle[l+5]); } if (b_ncomp>6) { fprintf(fp,"\n inte. points "); fprintf(fp,"sigma 11 sigma 12 sigma 31 plast eps axial strn\n"); for (m=0; m<b_num; m++) { fprintf(fp,"%10d-\n",b_uid[m]); l=b_ncomp*m+6; fprintf(fp," amplitude %12.4E %12.4E %12.4E %12.4E %12.4E\n",b_ampil[l],b_ampil[l+1],b_ampil[l+2],b_ampil[l+3],b_ampil[l+4]); fprintf(fp," angle %12.4E %12.4E %12.4E %12.4E %12.4E\n",b_angle[l],b_angle[l+1],b_angle[l+2],b_angle[l+3],b_angle[l+4]); } } } if(have_shell) { if(state<=999999) sprintf(path,"/elout_ssd/shell/d%6.6d",state); else sprintf(path,"/elout_ssd/shell/d%8.8d",state); lsda_cd(handle,path); if(lsda_read(handle,LSDA_FLOAT,"frequency",0,1,&s_freq) != 1) break; if(lsda_read(handle,LSDA_FLOAT,"amplitude",0,s_lnum,s_ampil) != s_lnum) break; if(lsda_read(handle,LSDA_FLOAT,"angle",0,s_lnum,s_angle) != s_lnum) break; fprintf(fp,"\n element stress calculations for frequency = %12.5E\n\n",s_freq); fprintf(fp," ipt- shl sig-xx sig-yy sig-"); fprintf(fp,"zz sig-xy sig-yz sig-zx\n"); for (m=0; m<s_num; m++) { fprintf(fp,"%10d-\n",s_uid[m]); for(n=0;n<s_maxint;n++) { l=s_ncomp*m+ 7*n; fprintf(fp,"%4d- amplitude %12.4E %12.4E %12.4E %12.4E %12.4E %12.4E\n",n+1,s_ampil[l],s_ampil[l+1],s_ampil[l+2],s_ampil[l+3],s_ampil[l+4],s_ampil[l+5]); fprintf(fp,"%4d- angle %12.4E %12.4E %12.4E %12.4E %12.4E %12.4E\n",n+1,s_angle[l],s_angle[l+1],s_angle[l+2],s_angle[l+3],s_angle[l+4],s_angle[l+5]); } } if (s_ncomp>33){ fprintf(fp,"\n"); fprintf(fp," ipt- shl eps-xx eps-yy eps-"); fprintf(fp,"zz eps-xy eps-yz eps-zx\n"); for (m=0; m<s_num; m++) { fprintf(fp,"%10d-\n",s_uid[m]); l=s_ncomp*m+ 32; fprintf(fp," lower ipt- amp %12.4E %12.4E %12.4E %12.4E %12.4E %12.4E\n",s_ampil[l],s_ampil[l+1],s_ampil[l+2],s_ampil[l+3],s_ampil[l+4],s_ampil[l+5]); fprintf(fp," lower ipt- ang %12.4E %12.4E %12.4E %12.4E %12.4E %12.4E\n",s_angle[l],s_angle[l+1],s_angle[l+2],s_angle[l+3],s_angle[l+4],s_angle[l+5]); l=s_ncomp*m+ 38; fprintf(fp," upper ipt- amp %12.4E %12.4E %12.4E %12.4E %12.4E %12.4E\n",s_ampil[l],s_ampil[l+1],s_ampil[l+2],s_ampil[l+3],s_ampil[l+4],s_ampil[l+5]); fprintf(fp," upper ipt- ang %12.4E %12.4E %12.4E %12.4E %12.4E %12.4E\n",s_angle[l],s_angle[l+1],s_angle[l+2],s_angle[l+3],s_angle[l+4],s_angle[l+5]); } } fprintf(fp,"\n"); } } fclose(fp); if(have_solid) { free (h_angle); free (h_ampil); free (h_uid); } if(have_tshell) { free (t_angle); free (t_ampil); free (t_uid); } if(have_beam) { free (b_angle); free (b_ampil); free (b_uid); } if(have_shell) { free (s_angle); free (s_ampil); free (s_uid); } printf(" %d states extracted\n",state-1); return 0; } /* ELOUT_SPCM file */ int translate_elout_spcm(int handle) { int i,j,k,l,m,n,typid,filenum,state; LSDA_Length length; int have_solid, have_tshell, have_beam, have_shell; FILE *fp; char path[30]; int h_num , h_lnum; int t_num , t_maxint, t_lnum; int b_num , b_lnum; int s_num , s_maxint, s_lnum; int *h_uid; int *t_uid; int *b_uid; int *s_uid; float *h_strs; float *t_strs; float *b_strs; float *s_strs; char title_location[128]; if (lsda_cd(handle,"/elout_spcm") == -1) return 0; printf("Extracting ELOUT_SPCM data\n"); lsda_queryvar(handle,"/elout_spcm/solid",&typid,&length,&filenum); have_solid= (typid >= 0); lsda_queryvar(handle,"/elout_spcm/thickshell",&typid,&length,&filenum); have_tshell= (typid >= 0); lsda_queryvar(handle,"/elout_spcm/beam",&typid,&length,&filenum); have_beam= (typid >= 0); lsda_queryvar(handle,"/elout_spcm/shell",&typid,&length,&filenum); have_shell= (typid >= 0); title_location[0]=0; /* Read uid and stress Solids */ if(have_solid) { lsda_cd(handle,"/elout_spcm/solid"); strcpy(title_location,"/elout_spcm/solid/metadata"); lsda_read(handle,LSDA_INT,"n_elem", 0,1,&h_num); h_uid = (int *) malloc(h_num*sizeof(int)); lsda_read(handle,LSDA_INT,"uid",0,h_num,h_uid); h_lnum = 7*h_num; h_strs= (float *) malloc(h_lnum*sizeof(float)); lsda_read(handle,LSDA_FLOAT,"stress",0,h_lnum,h_strs); lsda_cd(handle,"/elout_spcm/solid/metadata"); } /* thick shells */ if(have_tshell) { lsda_cd(handle,"/elout_spcm/thickshell"); strcpy(title_location,"/elout_spcm/thickshell/metadata"); lsda_read(handle,LSDA_INT,"n_elem", 0,1,&t_num); lsda_read(handle,LSDA_INT,"maxint", 0,1,&t_maxint); t_uid = (int *) malloc(t_num*sizeof(int)); lsda_read(handle,LSDA_INT,"uid",0,t_num,t_uid); t_lnum = 7*t_maxint*t_num; t_strs= (float *) malloc(t_lnum*sizeof(float)); lsda_read(handle,LSDA_FLOAT,"stress",0,t_lnum,t_strs); lsda_cd(handle,"/elout_spcm/thickshell/metadata"); } /* beams */ if(have_beam) { lsda_cd(handle,"/elout_spcm/beam"); strcpy(title_location,"/elout_spcm/beam/metadata"); lsda_read(handle,LSDA_INT,"n_elem", 0,1,&b_num); b_uid = (int *) malloc(b_num*sizeof(int)); lsda_read(handle,LSDA_INT,"uid",0,b_num,b_uid); b_lnum = 7*b_num; b_strs= (float *) malloc(b_lnum*sizeof(float)); lsda_read(handle,LSDA_FLOAT,"stress",0,b_lnum,b_strs); lsda_cd(handle,"/elout_spcm/beam/metadata"); } /* shells */ if(have_shell) { lsda_cd(handle,"/elout_spcm/shell"); strcpy(title_location,"/elout_spcm/shell/metadata"); lsda_read(handle,LSDA_INT,"n_elem", 0,1,&s_num); lsda_read(handle,LSDA_INT,"maxint", 0,1,&s_maxint); s_uid = (int *) malloc(s_num*sizeof(int)); lsda_read(handle,LSDA_INT,"uid",0,s_num,s_uid); s_lnum = 7*s_maxint*s_num; s_strs= (float *) malloc(s_lnum*sizeof(float)); lsda_read(handle,LSDA_FLOAT,"stress",0,s_lnum,s_strs); lsda_cd(handle,"/elout_spcm/shell/metadata"); } if(strlen(title_location) == 0) return 0; /* huh? */ /* open file and write header */ sprintf(output_file,"%selout_spcm",output_path); fp=fopen(output_file,"w"); write_message(fp,output_file); if (!fp) return 0; output_title(handle,title_location,fp); output_legend(handle,fp,1,1); fprintf(fp," R e s p o n s e S p e c t r u m\n\n"); /* write stress data */ if(have_solid) { sprintf(path,"/elout_spcm/solid"); path[17]='\0'; lsda_cd(handle,path); fprintf(fp,"\n element stress calculations \n\n"); fprintf(fp," solid sig-xx sig-yy sig-"); fprintf(fp,"zz sig-xy sig-yz sig-zx vmstress\n"); for (m=0; m<h_num; m++) { l=7*m; fprintf(fp,"%10d- %12.4E %12.4E %12.4E %12.4E %12.4E %12.4E %12.4E\n",h_uid[m],h_strs[l],h_strs[l+1],h_strs[l+2],h_strs[l+3],h_strs[l+4],h_strs[l+5],h_strs[l+6]); } } if(have_tshell) { sprintf(path,"/elout_spcm/thickshell"); path[22]='\0'; lsda_cd(handle,path); fprintf(fp,"\n element stress calculations\n\n"); fprintf(fp," ipt- thickshl sig-xx sig-yy sig-"); fprintf(fp,"zz sig-xy sig-yz sig-zx vmstress\n"); for (m=0; m<t_num; m++) { fprintf(fp,"%10d-\n",t_uid[m]); for(n=0;n<t_maxint;n++) { l=7*m*t_maxint + 7*n; fprintf(fp,"%4d- %12.4E %12.4E %12.4E %12.4E %12.4E %12.4E %12.4E\n",n+1,t_strs[l],t_strs[l+1],t_strs[l+2],t_strs[l+3],t_strs[l+4],t_strs[l+5],t_strs[l+6]); } } } if(have_beam) { sprintf(path,"/elout_spcm/beam"); path[16]='\0'; lsda_cd(handle,path); fprintf(fp,"\n element stress calculations\n\n"); fprintf(fp," beam sig-xx sig-yy sig-"); fprintf(fp,"zz sig-xy sig-yz sig-zx vmstress\n"); for (m=0; m<b_num; m++) { l=7*m; fprintf(fp,"%10d- %12.4E %12.4E %12.4E %12.4E %12.4E %12.4E %12.4E\n",b_uid[m],b_strs[l],b_strs[l+1],b_strs[l+2],b_strs[l+3],b_strs[l+4],b_strs[l+5],b_strs[l+6]); } } if(have_shell) { sprintf(path,"/elout_spcm/shell"); path[17]='\0'; lsda_cd(handle,path); fprintf(fp,"\n element stress calculations\n\n"); fprintf(fp," ipt- shl sig-xx sig-yy sig-"); fprintf(fp,"zz sig-xy sig-yz sig-zx vmstress\n"); for (m=0; m<s_num; m++) { fprintf(fp,"%10d-\n",s_uid[m]); for(n=0;n<s_maxint;n++) { l=7*m*s_maxint + 7*n; fprintf(fp,"%4d- %12.4E %12.4E %12.4E %12.4E %12.4E %12.4E %12.4E\n",n+1,s_strs[l],s_strs[l+1],s_strs[l+2],s_strs[l+3],s_strs[l+4],s_strs[l+5],s_strs[l+6]); } } fprintf(fp,"\n"); } fclose(fp); if(have_solid) { free (h_strs); free (h_uid); } if(have_tshell) { free (t_strs); free (t_uid); } if(have_beam) { free (b_strs); free (b_uid); } if(have_shell) { free (s_strs); free (s_uid); } printf(" %d states extracted\n",1); return 0; } /* ELOUT_PSD file */ int translate_elout_psd(int handle) { int i,j,k,l,m,n,typid,filenum,state; LSDA_Length length; int have_solid, have_tshell, have_beam, have_shell; FILE *fp; char path[30]; int nfreq; int h_num , h_nfreq, h_lnum; int t_num , t_nfreq, t_maxint, t_lnum; int b_num , b_nfreq, b_lnum; int s_num , s_nfreq, s_maxint, s_lnum; int *h_uid; int *t_uid; int *b_uid; int *s_uid; float h_freq, *h_strss; float t_freq, *t_strss; float b_freq, *b_strss; float s_freq, *s_strss; char title_location[128]; if (lsda_cd(handle,"/elout_psd") == -1) return 0; printf("Extracting ELOUT_PSD data\n"); lsda_queryvar(handle,"/elout_psd/solid",&typid,&length,&filenum); have_solid= (typid >= 0); lsda_queryvar(handle,"/elout_psd/thickshell",&typid,&length,&filenum); have_tshell= (typid >= 0); lsda_queryvar(handle,"/elout_psd/beam",&typid,&length,&filenum); have_beam= (typid >= 0); lsda_queryvar(handle,"/elout_psd/shell",&typid,&length,&filenum); have_shell= (typid >= 0); title_location[0]=0; /* Read metadata Solids */ if(have_solid) { lsda_cd(handle,"/elout_psd/solid/metadata"); strcpy(title_location,"/elout_psd/solid/metadata"); lsda_read(handle,LSDA_INT,"n_elem", 0,1,&h_num); lsda_read(handle,LSDA_INT,"nfreq_psd",0,1,&h_nfreq); nfreq = h_nfreq; h_uid = (int *) malloc(h_num*sizeof(int)); lsda_read(handle,LSDA_INT,"uid",0,h_num,h_uid); h_lnum = 7*h_num; h_strss = (float *) malloc(h_lnum*sizeof(float)); } /* thick shells */ if(have_tshell) { lsda_cd(handle,"/elout_psd/thickshell/metadata"); strcpy(title_location,"/elout_psd/thickshell/metadata"); lsda_read(handle,LSDA_INT,"n_elem", 0,1,&t_num); lsda_read(handle,LSDA_INT,"nfreq_psd",0,1,&t_nfreq); lsda_read(handle,LSDA_INT,"maxint", 0,1,&t_maxint); nfreq = t_nfreq; t_uid = (int *) malloc(t_num*sizeof(int)); lsda_read(handle,LSDA_INT,"uid",0,t_num,t_uid); t_lnum = 7*t_maxint*t_num; t_strss = (float *) malloc(t_lnum*sizeof(float)); } /* beams */ if(have_beam) { lsda_cd(handle,"/elout_psd/beam/metadata"); strcpy(title_location,"/elout_psd/beam/metadata"); lsda_read(handle,LSDA_INT,"n_elem", 0,1,&b_num); lsda_read(handle,LSDA_INT,"nfreq_psd",0,1,&b_nfreq); nfreq = b_nfreq; b_uid = (int *) malloc(b_num*sizeof(int)); lsda_read(handle,LSDA_INT,"uid",0,b_num,b_uid); b_lnum = 7*b_num; b_strss = (float *) malloc(b_lnum*sizeof(float)); } /* shells */ if(have_shell) { lsda_cd(handle,"/elout_psd/shell/metadata"); strcpy(title_location,"/elout_psd/shell/metadata"); lsda_read(handle,LSDA_INT,"n_elem", 0,1,&s_num); lsda_read(handle,LSDA_INT,"nfreq_psd",0,1,&s_nfreq); lsda_read(handle,LSDA_INT,"maxint", 0,1,&s_maxint); nfreq = s_nfreq; s_uid = (int *) malloc(s_num*sizeof(int)); lsda_read(handle,LSDA_INT,"uid",0,s_num,s_uid); s_lnum = 7*s_maxint*s_num; s_strss = (float *) malloc(s_lnum*sizeof(float)); } if(strlen(title_location) == 0) return 0; /* huh? */ /* open file and write header */ sprintf(output_file,"%selout_psd",output_path); fp=fopen(output_file,"w"); write_message(fp,output_file); if (!fp) return 0; output_title(handle,title_location,fp); output_legend(handle,fp,1,1); fprintf(fp," R a n d o m V i b r a t i o n\n\n"); /* Loop through frequency states and write each one */ for(state=1;(have_solid || have_tshell || have_beam || have_shell) && state<=nfreq ; state++) { if(have_solid) { if(state<=999999) sprintf(path,"/elout_psd/solid/d%6.6d",state); else sprintf(path,"/elout_psd/solid/d%8.8d",state); lsda_cd(handle,path); if(lsda_read(handle,LSDA_FLOAT,"frequency",0,1,&h_freq) != 1) break; if(lsda_read(handle,LSDA_FLOAT,"stress",0,h_lnum,h_strss) != h_lnum) break; fprintf(fp,"\n element stress calculations for frequency = %12.5E\n\n",h_freq); fprintf(fp," solid sig-xx sig-yy sig-"); fprintf(fp,"zz sig-xy sig-yz sig-zx sig-vm\n"); for (m=0; m<h_num; m++) { l=7*m; fprintf(fp,"%10d- %12.4E %12.4E %12.4E %12.4E %12.4E %12.4E %12.4E\n",h_uid[m],h_strss[l],h_strss[l+1],h_strss[l+2],h_strss[l+3],h_strss[l+4],h_strss[l+5],h_strss[l+6]); } } if(have_tshell) { if(state<=999999) sprintf(path,"/elout_psd/thickshell/d%6.6d",state); else sprintf(path,"/elout_psd/thickshell/d%8.8d",state); lsda_cd(handle,path); if(lsda_read(handle,LSDA_FLOAT,"frequency",0,1,&t_freq) != 1) break; if(lsda_read(handle,LSDA_FLOAT,"stress",0,t_lnum,t_strss) != t_lnum) break; fprintf(fp,"\n element stress calculations for frequency = %12.5E\n\n",t_freq); fprintf(fp," thickshl ipt- sig-xx sig-yy sig-"); fprintf(fp,"zz sig-xy sig-yz sig-zx sig-vm\n"); for (m=0; m<t_num; m++) { for(n=0;n<t_maxint;n++) { l=7*m*t_maxint + 7*n; fprintf(fp,"%10d-%4d- %12.4E %12.4E %12.4E %12.4E %12.4E %12.4E %12.4E\n",t_uid[m],n+1,t_strss[l],t_strss[l+1],t_strss[l+2],t_strss[l+3],t_strss[l+4],t_strss[l+5],t_strss[l+6]); } } } if(have_beam) { if(state<=999999) sprintf(path,"/elout_psd/beam/d%6.6d",state); else sprintf(path,"/elout_psd/beam/d%8.8d",state); lsda_cd(handle,path); if(lsda_read(handle,LSDA_FLOAT,"frequency",0,1,&b_freq) != 1) break; if(lsda_read(handle,LSDA_FLOAT,"stress",0,b_lnum,b_strss) != b_lnum) break; fprintf(fp,"\n element stress calculations for frequency = %12.5E\n\n",b_freq); fprintf(fp," beam sig-xx sig-yy sig-"); fprintf(fp,"zz sig-xy sig-yz sig-zx sig-vm\n"); for (m=0; m<b_num; m++) { l=7*m; fprintf(fp,"%10d- %12.4E %12.4E %12.4E %12.4E %12.4E %12.4E %12.4E\n",b_uid[m],b_strss[l],b_strss[l+1],b_strss[l+2],b_strss[l+3],b_strss[l+4],b_strss[l+5],b_strss[l+6]); } } if(have_shell) { if(state<=999999) sprintf(path,"/elout_psd/shell/d%6.6d",state); else sprintf(path,"/elout_psd/shell/d%8.8d",state); lsda_cd(handle,path); if(lsda_read(handle,LSDA_FLOAT,"frequency",0,1,&s_freq) != 1) break; if(lsda_read(handle,LSDA_FLOAT,"stress",0,s_lnum,s_strss) != s_lnum) break; fprintf(fp,"\n element stress calculations for frequency = %12.5E\n\n",s_freq); fprintf(fp," shl ipt- sig-xx sig-yy sig-"); fprintf(fp,"zz sig-xy sig-yz sig-zx sig-vm\n"); for (m=0; m<s_num; m++) { for(n=0;n<s_maxint;n++) { l=7*m*s_maxint + 7*n; fprintf(fp,"%10d-%4d- %12.4E %12.4E %12.4E %12.4E %12.4E %12.4E %12.4E\n",s_uid[m],n+1,s_strss[l],s_strss[l+1],s_strss[l+2],s_strss[l+3],s_strss[l+4],s_strss[l+5],s_strss[l+6]); } } fprintf(fp,"\n"); } } fclose(fp); if(have_solid) { free (h_strss); free (h_uid); } if(have_tshell) { free (t_strss); free (t_uid); } if(have_beam) { free (b_strss); free (b_uid); } if(have_shell) { free (s_strss); free (s_uid); } printf(" %d states extracted\n",state-1); return 0; } /* CURVOUT file */ int translate_curvout(int handle) { int i,typid,num,filenum,state; LSDA_Length length; char dirname[128]; int *ids; int cycle; float time; float *v; FILE *fp; LSDADir *dp = NULL; if (lsda_cd(handle,"/curvout/metadata") == -1) return 0; printf("Extracting CURVOUT data\n"); lsda_queryvar(handle,"ids",&typid,&length,&filenum); num=length; /* allocate memory to read in 1 state */ ids = (int *) malloc(num*sizeof(int)); v = (float *) malloc(num*sizeof(float)); /* Read metadata */ lsda_read(handle,LSDA_INT,"ids",0,num,ids); /* open file and write header */ sprintf(output_file,"%scurvout",output_path); fp=fopen(output_file,"w"); write_message(fp,output_file); if (!fp) return 0; output_title(handle,dirname,fp); output_legend(handle,fp,1,1); /* Loop through time states and write each one */ for(state=1; (dp = next_dir(handle,"/curvout",dp,dirname)) != NULL; state++) { if(lsda_read(handle,LSDA_FLOAT,"time",0,1,&time) != 1) break; if(lsda_read(handle,LSDA_INT,"cycle",0,1,&cycle) != 1) break; if(lsda_read(handle,LSDA_FLOAT,"values",0,num,v) != num) break; fprintf(fp,"\n curve data for time step %10d ( at time%12.5E )\n",cycle,time); fprintf(fp,"\n curve id ordinate\n"); for(i=0; i<num; i++) { fprintf(fp,"%9d%13.4E\n",ids[i],v[i]); } } fclose(fp); free(v); free(ids); printf(" %d states extracted\n",state-1); return 0; } /* NODOUT_SSD file */ int translate_nodout_ssd(int handle) { int i,l,m,typid,num,filenum,state; LSDA_Length length; FILE *fp; char path[30]; int nfreq,lnum; int *uid; float time; float freq, *angle,*ampil; char title_location[128]; if (lsda_cd(handle,"/nodout_ssd") == -1) return 0; printf("Extracting NODOUT_SSD data\n"); title_location[0]=0; /* Read metadata */ lsda_cd(handle,"/nodout_ssd/metadata"); strcpy(title_location,"/nodout_ssd/metadata"); lsda_read(handle,LSDA_INT,"n_node", 0,1,&num); lsda_read(handle,LSDA_INT,"nfreq_ssd",0,1,&nfreq); /* allocate memory to read in 1 state */ uid = (int *) malloc(num*sizeof(int)); lsda_read(handle,LSDA_INT,"uid",0,num,uid); lnum = 9*num; ampil = (float *) malloc(lnum*sizeof(float)); angle = (float *) malloc(lnum*sizeof(float)); if(strlen(title_location) == 0) return 0; /* huh? */ /* open file and write header */ sprintf(output_file,"%snodout_ssd",output_path); fp=fopen(output_file,"w"); write_message(fp,output_file); if (!fp) return 0; output_title(handle,title_location,fp); output_legend(handle,fp,1,1); fprintf(fp," S t e a d y S t a t e D y n a m i c s\n\n"); /* Loop through frequency states and write each one */ for(state=1; state<=nfreq; state++) { if(state<=999999) sprintf(path,"/nodout_ssd/d%6.6d",state); else sprintf(path,"/nodout_ssd/d%8.8d",state); lsda_cd(handle,path); if(lsda_read(handle,LSDA_FLOAT,"frequency",0,1,&freq) != 1) break; if(lsda_read(handle,LSDA_FLOAT,"amplitude",0,lnum,ampil) != lnum) break; if(lsda_read(handle,LSDA_FLOAT,"angle",0,lnum,angle) != lnum) break; fprintf(fp,"\n nodal print out for frequency = %12.5E\n\n",freq); fprintf(fp," nodal point x-disp y-disp z-disp "); fprintf(fp,"x-vel y-vel z-vel x-accl y-accl "); fprintf(fp,"z-accl\n"); for (m=0; m<num; m++) { fprintf(fp,"%10d-\n",uid[m]); l=9*m; fprintf(fp," amplitude %12.4E%12.4E%12.4E%12.4E%12.4E%12.4E%12.4E%12.4E%12.4E\n",ampil[l],ampil[l+3],ampil[l+6],ampil[l+1],ampil[l+4],ampil[l+7],ampil[l+2],ampil[l+5],ampil[l+8]); fprintf(fp," angle %12.4E%12.4E%12.4E%12.4E%12.4E%12.4E%12.4E%12.4E%12.4E\n",angle[l],angle[l+3],angle[l+6],angle[l+1],angle[l+4],angle[l+7],angle[l+2],angle[l+5],angle[l+8]); } } fclose(fp); free (uid); free (ampil); free (angle); printf(" %d states extracted\n",state-1); return 0; } /* NODOUT_SPCM file */ int translate_nodout_spcm(int handle) { int i,l,m,num,filenum; LSDA_Length length; FILE *fp; char path[30]; int lnum; int *uid; float *vad; char title_location[128]; if (lsda_cd(handle,"/nodout_spcm") == -1) return 0; printf("Extracting NODOUT_SPCM data\n"); title_location[0]=0; /* Read metadata */ lsda_cd(handle,"/nodout_spcm"); strcpy(title_location,"/nodout_spcm/metadata"); lsda_read(handle,LSDA_INT,"n_node", 0,1,&num); /* allocate memory to read in 1 state */ uid = (int *) malloc(num*sizeof(int)); lsda_read(handle,LSDA_INT,"uid",0,num,uid); lnum = 9*num; vad = (float *) malloc(lnum*sizeof(float)); lsda_read(handle,LSDA_FLOAT,"vad",0,lnum,vad); lsda_cd(handle,"/nodout_spcm/metadata"); if(strlen(title_location) == 0) return 0; /* huh? */ /* open file and write header */ sprintf(output_file,"%snodout_spcm",output_path); fp=fopen(output_file,"w"); write_message(fp,output_file); if (!fp) return 0; output_title(handle,title_location,fp); output_legend(handle,fp,1,1); fprintf(fp," R e s p o n s e S p e c t r u m\n\n"); /* write results */ sprintf(path,"/nodout_spcm"); path[12]='\0'; lsda_cd(handle,path); fprintf(fp,"\n nodal print out\n\n"); fprintf(fp," nodal point x-disp y-disp z-disp "); fprintf(fp,"x-vel y-vel z-vel x-accl y-accl "); fprintf(fp,"z-accl\n"); for (m=0; m<num; m++) { l=9*m; fprintf(fp,"%10d- %12.4E%12.4E%12.4E%12.4E%12.4E%12.4E%12.4E%12.4E%12.4E\n",uid[m],vad[l],vad[l+3],vad[l+6],vad[l+1],vad[l+4],vad[l+7],vad[l+2],vad[l+5],vad[l+8]); } fclose(fp); free (uid); free (vad); printf(" %d states extracted\n",1); return 0; } /* NODOUT_PSD file */ int translate_nodout_psd(int handle) { int i,l,m,typid,num,filenum,state; LSDA_Length length; FILE *fp; char path[30]; int nfreq,lnum; int *uid; float time; float freq, *disp,*vel,*acl; char title_location[128]; if (lsda_cd(handle,"/nodout_psd") == -1) return 0; printf("Extracting NODOUT_PSD data\n"); title_location[0]=0; /* Read metadata */ lsda_cd(handle,"/nodout_psd/metadata"); strcpy(title_location,"/nodout_psd/metadata"); lsda_read(handle,LSDA_INT,"n_node", 0,1,&num); lsda_read(handle,LSDA_INT,"nfreq_psd",0,1,&nfreq); /* allocate memory to read in 1 state */ uid = (int *) malloc(num*sizeof(int)); lsda_read(handle,LSDA_INT,"uid",0,num,uid); lnum = 3*num; disp = (float *) malloc(lnum*sizeof(float)); vel = (float *) malloc(lnum*sizeof(float)); acl = (float *) malloc(lnum*sizeof(float)); if(strlen(title_location) == 0) return 0; /* huh? */ /* open file and write header */ sprintf(output_file,"%snodout_psd",output_path); fp=fopen(output_file,"w"); write_message(fp,output_file); if (!fp) return 0; output_title(handle,title_location,fp); output_legend(handle,fp,1,1); fprintf(fp," R a n d o m V i b r a t i o n\n\n"); /* Loop through frequency states and write each one */ for(state=1; state<=nfreq; state++) { if(state<=999999) sprintf(path,"/nodout_psd/d%6.6d",state); else sprintf(path,"/nodout_psd/d%8.8d",state); lsda_cd(handle,path); if(lsda_read(handle,LSDA_FLOAT,"frequency",0,1,&freq) != 1) break; if(lsda_read(handle,LSDA_FLOAT,"displacement",0,lnum,disp) != lnum) break; if(lsda_read(handle,LSDA_FLOAT,"velocity",0,lnum,vel) != lnum) break; if(lsda_read(handle,LSDA_FLOAT,"acceleration",0,lnum,acl) != lnum) break; fprintf(fp,"\n nodal print out for frequency = %12.5E\n\n",freq); fprintf(fp," nodal point x-disp y-disp z-disp "); fprintf(fp,"x-vel y-vel z-vel x-accl y-accl "); fprintf(fp,"z-accl\n"); for (m=0; m<num; m++) { l=3*m; fprintf(fp,"%10d- %12.4E%12.4E%12.4E%12.4E%12.4E%12.4E%12.4E%12.4E%12.4E\n",uid[m],disp[l],disp[l+1],disp[l+2],vel[l],vel[l+1],vel[l+2],acl[l],acl[l+1],acl[l+2]); } } fclose(fp); free (uid); free (disp); free (vel); free (acl); printf(" %d states extracted\n",state-1); return 0; } /* PLLYOUT file */ int translate_pllyout(int handle) { int i,typid,num,filenum,state; LSDA_Length length; int *ids; int cycle; double time; int *b1,*b2; float *s,*sr,*f,*wa; FILE *fp; LSDADir *dp = NULL; if (lsda_cd(handle,"/pllyout/metadata") == -1) return 0; printf("Extracting PLLYOUT data\n"); lsda_queryvar(handle,"ids",&typid,&length,&filenum); num=length; /* allocate memory to read in 1 state */ ids = (int *) malloc(num*sizeof(int)); b1 = (int *) malloc(num*sizeof(int)); b2 = (int *) malloc(num*sizeof(int)); s = (float *) malloc(num*sizeof(float)); sr = (float *) malloc(num*sizeof(float)); f = (float *) malloc(num*sizeof(float)); wa = (float *) malloc(num*sizeof(float)); /* Read metadata */ lsda_read(handle,LSDA_INT,"ids",0,num,ids); /* open file and write header */ sprintf(output_file,"%spllyout",output_path); fp=fopen(output_file,"w"); write_message(fp,output_file); if (!fp) return 0; output_title(handle,"/pllyout/metadata",fp); /* no legend so far... output_legend(handle,fp,1,1); */ /* Loop through time states and write each one */ for(state=1; next_dir_6or8digitd(handle,"/pllyout",state) != 0; state++) { if(lsda_read(handle,LSDA_DOUBLE,"time",0,1,&time) != 1) break; if(lsda_read(handle,LSDA_INT,"cycle",0,1,&cycle) != 1) break; if(lsda_read(handle,LSDA_FLOAT,"slip",0,num,s) != num) break; if(lsda_read(handle,LSDA_FLOAT,"slip_rate",0,num,sr) != num) break; if(lsda_read(handle,LSDA_FLOAT,"wrap_angle",0,num,wa) != num) break; if(lsda_read(handle,LSDA_FLOAT,"force",0,num,f) != num) break; if(lsda_read(handle,LSDA_INT,"beam1",0,num,b1) != num) break; if(lsda_read(handle,LSDA_INT,"beam2",0,num,b2) != num) break; fprintf(fp,"\n\n p u l l e y e l e m e n t o u t p u t "); fprintf(fp,"f o r t i m e s t e p%9d ( at time%14.7E )\n",cycle,time); fprintf(fp,"\n pulley # beam 1 # beam 2 # slip"); fprintf(fp," sliprate force wrap angle\n"); for(i=0; i<num; i++) { fprintf(fp,"\n%12d%12d%12d%14.5E%14.5E%14.5E%14.5E\n",ids[i],b1[i],b2[i],s[i], sr[i],f[i],wa[i]); } fprintf(fp,"\n"); } fclose(fp); free(wa); free(f); free(sr); free(s); free(b2); free(b1); free(ids); printf(" %d states extracted\n",state-1); return 0; } /* DEM RCFORC file */ int translate_dem_rcforc(int handle) { int i,j,typid,num,filenum,state; LSDA_Length length; char dirname[32]; int *ids; int *sides, *single, nsingle, nsout; float *xf,*yf,*zf; float time; FILE *fp; LSDADir *dp = NULL; if (lsda_cd(handle,"/dem_rcforc/metadata") == -1) return 0; printf("Extracting DEM RCFORC data\n"); /* Read metadata */ lsda_queryvar(handle,"ids",&typid,&length,&filenum); num = length; ids = (int *) malloc(num*sizeof(int)); xf = (float *) malloc(num*sizeof(float)); yf = (float *) malloc(num*sizeof(float)); zf = (float *) malloc(num*sizeof(float)); lsda_read(handle,LSDA_INT,"ids",0,num,ids); /* open file and write header */ sprintf(output_file,"%sdemrcf",output_path); fp=fopen(output_file,"w"); write_message(fp,output_file); if (!fp) return 0; output_legend(handle,fp,1,1); /* Loop through time states and write each one. */ for(state=1; (dp = next_dir(handle,"/dem_rcforc",dp,dirname)) != NULL; state++) { if(lsda_read(handle,LSDA_FLOAT,"time",0,1,&time) != 1) break; if(lsda_read(handle,LSDA_FLOAT,"x_force",0,num,xf) != num) break; if(lsda_read(handle,LSDA_FLOAT,"y_force",0,num,yf) != num) break; if(lsda_read(handle,LSDA_FLOAT,"z_force",0,num,zf) != num) break; nsout=0; for(i=0; i<num; i++) { fprintf(fp," \n"); fprintf(fp," master%11d time",ids[i]); fprintf(fp,"%12.5E x %12.5E y %12.5E z %12.5E\n", time,xf[i],yf[i],zf[i]); } } fclose(fp); free(zf); free(yf); free(xf); free(ids); printf(" %d states extracted\n",state-1); return 0; } /* DISBOUT file */ int translate_disbout(int handle) { int i,typid,num,filenum,state,cycle; LSDA_Length length; char dirname[256]; int *nelb, *matid, *mtype; float *r_dis_axial,*r_dis_ns,*r_dis_nt,*axial_rot,*rot_s,*rot_t; float *rslt_axial,*rslt_ns,*rslt_nt,*torsion,*moment_s,*moment_t; float *axial_x,*axial_y,*axial_z,*s_dir_x,*s_dir_y,*s_dir_z,*t_dir_x,*t_dir_y,*t_dir_z; float time; FILE *fp; LSDADir *dp = NULL; if (lsda_cd(handle,"/disbout") == -1) return 0; printf("Extracting DISBOUT data\n"); /* Read metadata */ /* open file and write header */ sprintf(output_file,"%sdisbout",output_path); fp=fopen(output_file,"w"); write_message(fp,output_file); if (!fp) return 0; output_title(handle,"/disbout/metadata",fp); output_legend(handle,fp,1,1); for(state=1; (dp = next_dir(handle,"/disbout",dp,dirname)) != NULL; state++) { if(state<=999999) sprintf(dirname,"/disbout/d%6.6d",state); else sprintf(dirname,"/disbout/d%8.8d",state); lsda_queryvar(handle,dirname,&typid,&length,&filenum); /* if(typid != 0) return 0; */ lsda_cd(handle,dirname); lsda_queryvar(handle,"nelb",&typid,&length,&filenum); num = length; nelb = (int *) malloc(num*sizeof(int)); matid = (int *) malloc(num*sizeof(int)); mtype = (int *) malloc(num*sizeof(int)); r_dis_axial = (float *) malloc(num*sizeof(float)); r_dis_ns = (float *) malloc(num*sizeof(float)); r_dis_nt = (float *) malloc(num*sizeof(float)); axial_rot = (float *) malloc(num*sizeof(float)); rot_s = (float *) malloc(num*sizeof(float)); rot_t = (float *) malloc(num*sizeof(float)); rslt_axial = (float *) malloc(num*sizeof(float)); rslt_ns = (float *) malloc(num*sizeof(float)); rslt_nt = (float *) malloc(num*sizeof(float)); torsion = (float *) malloc(num*sizeof(float)); moment_s = (float *) malloc(num*sizeof(float)); moment_t = (float *) malloc(num*sizeof(float)); axial_x = (float *) malloc(num*sizeof(float)); axial_y = (float *) malloc(num*sizeof(float)); axial_z = (float *) malloc(num*sizeof(float)); s_dir_x = (float *) malloc(num*sizeof(float)); s_dir_y = (float *) malloc(num*sizeof(float)); s_dir_z = (float *) malloc(num*sizeof(float)); t_dir_x = (float *) malloc(num*sizeof(float)); t_dir_y = (float *) malloc(num*sizeof(float)); t_dir_z = (float *) malloc(num*sizeof(float)); /* Loop through time states and write each one. */ if(lsda_read(handle,LSDA_FLOAT,"time",0,1,&time) != 1) break; if(lsda_read(handle,LSDA_INT,"cycle",0,1,&cycle) != 1) break; if(lsda_read(handle,LSDA_INT,"nelb",0,num,nelb) != num) break; if(lsda_read(handle,LSDA_INT,"matid",0,num,matid) != num) break; if(lsda_read(handle,LSDA_INT,"mtype",0,num,mtype) != num) break; if(lsda_read(handle,LSDA_FLOAT,"r_dis_axial",0,num,r_dis_axial) != num) break; if(lsda_read(handle,LSDA_FLOAT,"r_dis_ns",0,num,r_dis_ns) != num) break; if(lsda_read(handle,LSDA_FLOAT,"r_dis_nt",0,num,r_dis_nt) != num) break; if(lsda_read(handle,LSDA_FLOAT,"axial_rot",0,num,axial_rot) != num) break; if(lsda_read(handle,LSDA_FLOAT,"rot_s",0,num,rot_s) != num) break; if(lsda_read(handle,LSDA_FLOAT,"rot_t",0,num,rot_t) != num) break; if(lsda_read(handle,LSDA_FLOAT,"rslt_axial",0,num,rslt_axial) != num) break; if(lsda_read(handle,LSDA_FLOAT,"rslt_ns",0,num,rslt_ns) != num) break; if(lsda_read(handle,LSDA_FLOAT,"rslt_nt",0,num,rslt_nt) != num) break; if(lsda_read(handle,LSDA_FLOAT,"torsion",0,num,torsion) != num) break; if(lsda_read(handle,LSDA_FLOAT,"moment_s",0,num,moment_s) != num) break; if(lsda_read(handle,LSDA_FLOAT,"moment_t",0,num,moment_t) != num) break; if(lsda_read(handle,LSDA_FLOAT,"axial_x",0,num,axial_x) != num) break; if(lsda_read(handle,LSDA_FLOAT,"axial_y",0,num,axial_y) != num) break; if(lsda_read(handle,LSDA_FLOAT,"axial_z",0,num,axial_z) != num) break; if(lsda_read(handle,LSDA_FLOAT,"s_dir_x",0,num,s_dir_x) != num) break; if(lsda_read(handle,LSDA_FLOAT,"s_dir_y",0,num,s_dir_y) != num) break; if(lsda_read(handle,LSDA_FLOAT,"s_dir_z",0,num,s_dir_z) != num) break; if(lsda_read(handle,LSDA_FLOAT,"t_dir_x",0,num,t_dir_x) != num) break; if(lsda_read(handle,LSDA_FLOAT,"t_dir_y",0,num,t_dir_y) != num) break; if(lsda_read(handle,LSDA_FLOAT,"t_dir_z",0,num,t_dir_z) != num) break; fprintf(fp,"\n d i s c r e t e b e a m o u t p u t f o r t i m e s t e p"); fprintf(fp,"%9d ( at time%12.5E )\n\n",cycle,time); for(i=0; i<num; i++) { fprintf(fp," beam/truss # =%8d part ID =%10d material type=%8d\n",nelb[i],matid[i],mtype[i]); fprintf(fp," relative displ. axial normal-s normal-t axial rot rotation-s rotation-t\n"); fprintf(fp," %11.3E%11.3E%11.3E%11.3E%11.3E%11.3E\n", r_dis_axial[i],r_dis_ns[i],r_dis_nt[i],axial_rot[i],rot_s[i],rot_t[i]); fprintf(fp," local resultant axial normal-s normal-t torsion moment-s moment-t\n"); fprintf(fp," %11.3E%11.3E%11.3E%11.3E%11.3E%11.3E\n", rslt_axial[i],rslt_ns[i],rslt_nt[i],torsion[i],moment_s[i],moment_t[i]); fprintf(fp," axial direction x y z\n"); fprintf(fp," %11.3E%11.3E%11.3E\n",axial_x[i],axial_y[i],axial_z[i]); fprintf(fp," s direction x y z\n"); fprintf(fp," %11.3E%11.3E%11.3E\n",s_dir_x[i],s_dir_y[i],s_dir_z[i]); fprintf(fp," t direction x y z\n"); fprintf(fp," %11.3E%11.3E%11.3E\n\n",t_dir_x[i],t_dir_y[i],t_dir_z[i]); } } fclose(fp); free(nelb); free(matid); free(mtype); free(r_dis_axial); free(r_dis_ns); free(r_dis_nt); free(axial_rot); free(rot_s); free(rot_t); free(rslt_axial); free(rslt_ns); free(rslt_nt); free(torsion); free(moment_s); free(moment_t); free(axial_x); free(axial_y); free(axial_z); free(s_dir_x); free(s_dir_y); free(s_dir_z); free(t_dir_x); free(t_dir_y); free(t_dir_z); printf(" %d states extracted\n",state-1); return 0; } /* DEM TRHIST file */ int translate_dem_trhist(int handle) { int i,typid,num,num0,filenum,state; LSDA_Length length; char dirname[128]; int maxnode,minnode,nstep,iteration; float maxtemp,mintemp,*temp,temp_norm; float time,timestep,*t_bottom,*t_top; float *fiop,*x,*y,*z,*vx,*vy,*vz,*sx,*sy,*sz,*sxy,*syz,*szx,*efp,*rvl,*rho; FILE *fp; LSDADir *dp = NULL; if (lsda_cd(handle,"/demtrh/metadata") == -1) return 0; printf("Extracting TRHIST data\n"); sprintf(dirname,"/demtrh/d000001"); lsda_cd(handle,dirname); lsda_queryvar(handle,"fiop",&typid,&length,&filenum); num=length; /* allocate memory to read in 1 state */ fiop = (float *) malloc(num*sizeof(float)); x = (float *) malloc(num*sizeof(float)); y = (float *) malloc(num*sizeof(float)); z = (float *) malloc(num*sizeof(float)); vx = (float *) malloc(num*sizeof(float)); vy = (float *) malloc(num*sizeof(float)); vz = (float *) malloc(num*sizeof(float)); /* open file and write header */ sprintf(output_file,"%sdemtrh",output_path); fp=fopen(output_file,"w"); write_message(fp,output_file); if (!fp) return 0; fprintf(fp,"DEM Tracer particle file\n"); fprintf(fp,"%5d 16\n",num); fprintf(fp," x y z vx vy vz\n"); /* output_title(handle,"/trhist/metadata",fp); output_legend(handle,fp,1,1); Loop through time states and write each one */ for(state=1; (dp = next_dir(handle,"/demtrh",dp,dirname)) != NULL; state++) { if(lsda_read(handle,LSDA_FLOAT,"time",0,1,&time) != 1) break; if(lsda_read(handle,LSDA_FLOAT,"fiop",0,num,fiop) != num) break; if(lsda_read(handle,LSDA_FLOAT,"x",0,num,x) != num) break; if(lsda_read(handle,LSDA_FLOAT,"y",0,num,y) != num) break; if(lsda_read(handle,LSDA_FLOAT,"z",0,num,z) != num) break; if(lsda_read(handle,LSDA_FLOAT,"vx",0,num,vx) != num) break; if(lsda_read(handle,LSDA_FLOAT,"vy",0,num,vy) != num) break; if(lsda_read(handle,LSDA_FLOAT,"vz",0,num,vz) != num) break; fprintf(fp,"%13.5E\n",time); for (i=0;i<num;i++) { fprintf(fp,"%13.5E%13.5E%13.5E%13.5E%13.5E%13.5E\n",x[i],y[i],z[i],vx[i],vy[i],vz[i]); } } fclose(fp); free(vz); free(vy); free(vx); free(z); free(y); free(x); free(fiop); printf(" %d states extracted\n",state-1); return 0; } /* TRALEH file */ int translate_traleh(int handle) { int i,typid,num,num0,filenum,state; LSDA_Length length; char dirname[128]; int maxnode,minnode,nstep,iteration; float maxtemp,mintemp,*temp,temp_norm; float time,timestep,*t_bottom,*t_top; int *iop; float *x,*y,*z,*vx,*vy,*vz,*sx,*sy,*sz,*sxy,*syz,*szx,*efp,*rho,*rvol; float *hv01,*hv02,*hv03,*hv04,*hv05,*hv06,*hv07,*hv08,*hv09; float *hv10,*hv11,*hv12,*hv13,*hv14,*hv15; FILE *fp; LSDADir *dp = NULL; if (lsda_cd(handle,"/traleh/metadata") == -1) return 0; printf("Extracting TRALEH data\n"); sprintf(dirname,"/traleh/d000001"); lsda_cd(handle,dirname); lsda_queryvar(handle,"iop",&typid,&length,&filenum); num=length; /* allocate memory to read in 1 state */ iop = (int *) malloc(num*sizeof(int)); x = (float *) malloc(num*sizeof(float)); y = (float *) malloc(num*sizeof(float)); z = (float *) malloc(num*sizeof(float)); vx = (float *) malloc(num*sizeof(float)); vy = (float *) malloc(num*sizeof(float)); vz = (float *) malloc(num*sizeof(float)); sx = (float *) malloc(num*sizeof(float)); sy = (float *) malloc(num*sizeof(float)); sz = (float *) malloc(num*sizeof(float)); sxy = (float *) malloc(num*sizeof(float)); syz = (float *) malloc(num*sizeof(float)); szx = (float *) malloc(num*sizeof(float)); efp = (float *) malloc(num*sizeof(float)); rho = (float *) malloc(num*sizeof(float)); rvol = (float *) malloc(num*sizeof(float)); hv01 = (float *) malloc(num*sizeof(float)); hv02 = (float *) malloc(num*sizeof(float)); hv03 = (float *) malloc(num*sizeof(float)); hv04 = (float *) malloc(num*sizeof(float)); hv05 = (float *) malloc(num*sizeof(float)); hv06 = (float *) malloc(num*sizeof(float)); hv07 = (float *) malloc(num*sizeof(float)); hv08 = (float *) malloc(num*sizeof(float)); hv09 = (float *) malloc(num*sizeof(float)); hv10 = (float *) malloc(num*sizeof(float)); hv11 = (float *) malloc(num*sizeof(float)); hv12 = (float *) malloc(num*sizeof(float)); hv13 = (float *) malloc(num*sizeof(float)); hv14 = (float *) malloc(num*sizeof(float)); hv15 = (float *) malloc(num*sizeof(float)); /* open file and write header */ sprintf(output_file,"%straleh",output_path); fp=fopen(output_file,"w"); write_message(fp,output_file); if (!fp) return 0; fprintf(fp,"ALE Tracer particle file\n"); fprintf(fp,"%5d 30\n",num); fprintf(fp," elemID\n"); fprintf(fp," x y z vx vy vz\n"); fprintf(fp," sx sy sz sxy syz szx\n"); fprintf(fp," efp rho rvol hisv1 hisv2 hsiv3\n"); fprintf(fp," hisv4 hisv5 hisv6 hisv7 hisv8 hisv9\n"); fprintf(fp," hisv10 hisv11 hisv12 hisv13 hisv14 hisv15\n"); /* output_title(handle,"/traleh/metadata",fp); output_legend(handle,fp,1,1); Loop through time states and write each one */ for(state=1; (dp = next_dir(handle,"/traleh",dp,dirname)) != NULL; state++) { if(lsda_read(handle,LSDA_FLOAT,"time",0,1,&time) != 1) break; if(lsda_read(handle,LSDA_INT,"iop",0,num,iop) != num) break; if(lsda_read(handle,LSDA_FLOAT,"x",0,num,x) != num) break; if(lsda_read(handle,LSDA_FLOAT,"y",0,num,y) != num) break; if(lsda_read(handle,LSDA_FLOAT,"z",0,num,z) != num) break; if(lsda_read(handle,LSDA_FLOAT,"vx",0,num,vx) != num) break; if(lsda_read(handle,LSDA_FLOAT,"vy",0,num,vy) != num) break; if(lsda_read(handle,LSDA_FLOAT,"vz",0,num,vz) != num) break; if(lsda_read(handle,LSDA_FLOAT,"sx",0,num,sx) != num) break; if(lsda_read(handle,LSDA_FLOAT,"sy",0,num,sy) != num) break; if(lsda_read(handle,LSDA_FLOAT,"sz",0,num,sz) != num) break; if(lsda_read(handle,LSDA_FLOAT,"sxy",0,num,sxy) != num) break; if(lsda_read(handle,LSDA_FLOAT,"syz",0,num,syz) != num) break; if(lsda_read(handle,LSDA_FLOAT,"szx",0,num,szx) != num) break; if(lsda_read(handle,LSDA_FLOAT,"efp",0,num,efp) != num) break; if(lsda_read(handle,LSDA_FLOAT,"rho",0,num,rho) != num) break; if(lsda_read(handle,LSDA_FLOAT,"rvol",0,num,rvol) != num) break; if(lsda_read(handle,LSDA_FLOAT,"hv01",0,num,hv01) != num) break; if(lsda_read(handle,LSDA_FLOAT,"hv02",0,num,hv02) != num) break; if(lsda_read(handle,LSDA_FLOAT,"hv03",0,num,hv03) != num) break; if(lsda_read(handle,LSDA_FLOAT,"hv04",0,num,hv04) != num) break; if(lsda_read(handle,LSDA_FLOAT,"hv05",0,num,hv05) != num) break; if(lsda_read(handle,LSDA_FLOAT,"hv06",0,num,hv06) != num) break; if(lsda_read(handle,LSDA_FLOAT,"hv07",0,num,hv07) != num) break; if(lsda_read(handle,LSDA_FLOAT,"hv08",0,num,hv08) != num) break; if(lsda_read(handle,LSDA_FLOAT,"hv09",0,num,hv09) != num) break; if(lsda_read(handle,LSDA_FLOAT,"hv10",0,num,hv10) != num) break; if(lsda_read(handle,LSDA_FLOAT,"hv11",0,num,hv11) != num) break; if(lsda_read(handle,LSDA_FLOAT,"hv12",0,num,hv12) != num) break; if(lsda_read(handle,LSDA_FLOAT,"hv13",0,num,hv13) != num) break; if(lsda_read(handle,LSDA_FLOAT,"hv14",0,num,hv14) != num) break; if(lsda_read(handle,LSDA_FLOAT,"hv15",0,num,hv15) != num) break; fprintf(fp,"%13.5E\n",time); for (i=0;i<num;i++) { fprintf(fp,"%16d\n",iop[i]); fprintf(fp,"%13.5E%13.5E%13.5E%13.5E%13.5E%13.5E\n",x[i],y[i],z[i],vx[i],vy[i],vz[i]); fprintf(fp,"%13.5E%13.5E%13.5E%13.5E%13.5E%13.5E\n",sx[i],sy[i],sz[i],sxy[i],syz[i],szx[i]); fprintf(fp,"%13.5E%13.5E%13.5E%13.5E%13.5E%13.5E\n",efp[i],rho[i],rvol[i],hv01[i],hv02[i],hv03[i]); fprintf(fp,"%13.5E%13.5E%13.5E%13.5E%13.5E%13.5E\n",hv04[i],hv05[i],hv06[i],hv07[i],hv08[i],hv09[i]); fprintf(fp,"%13.5E%13.5E%13.5E%13.5E%13.5E%13.5E\n",hv10[i],hv11[i],hv12[i],hv13[i],hv14[i],hv15[i]); } } fclose(fp); free(hv15); free(hv14); free(hv13); free(hv12); free(hv11); free(hv10); free(hv09); free(hv08); free(hv07); free(hv06); free(hv05); free(hv04); free(hv03); free(hv02); free(hv01); free(rvol); free(rho); free(efp); free(szx); free(syz); free(sxy); free(sz); free(sy); free(sx); free(vz); free(vy); free(vx); free(z); free(y); free(x); free(iop); printf(" %d states extracted\n",state-1); return 0; }
36.329544
195
0.593831
[ "vector", "model", "3d", "solid" ]
d86055a9ccfad6a7db67f09ac0cddbd285a7c8ec
17,932
h
C
aws-cpp-sdk-compute-optimizer/include/aws/compute-optimizer/model/UtilizationMetric.h
Eliyahu-Machluf/aws-sdk-cpp
97b8d6cdc16df298b80941b94327a5026efa7f8c
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-compute-optimizer/include/aws/compute-optimizer/model/UtilizationMetric.h
Eliyahu-Machluf/aws-sdk-cpp
97b8d6cdc16df298b80941b94327a5026efa7f8c
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-compute-optimizer/include/aws/compute-optimizer/model/UtilizationMetric.h
Eliyahu-Machluf/aws-sdk-cpp
97b8d6cdc16df298b80941b94327a5026efa7f8c
[ "Apache-2.0" ]
1
2022-03-23T15:17:18.000Z
2022-03-23T15:17:18.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/compute-optimizer/ComputeOptimizer_EXPORTS.h> #include <aws/compute-optimizer/model/MetricName.h> #include <aws/compute-optimizer/model/MetricStatistic.h> #include <utility> namespace Aws { namespace Utils { namespace Json { class JsonValue; class JsonView; } // namespace Json } // namespace Utils namespace ComputeOptimizer { namespace Model { /** * <p>Describes a utilization metric of a resource, such as an Amazon EC2 * instance.</p> <p>Compare the utilization metric data of your resource against * its projected utilization metric data to determine the performance difference * between your current resource and the recommended option.</p><p><h3>See * Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/compute-optimizer-2019-11-01/UtilizationMetric">AWS * API Reference</a></p> */ class AWS_COMPUTEOPTIMIZER_API UtilizationMetric { public: UtilizationMetric(); UtilizationMetric(Aws::Utils::Json::JsonView jsonValue); UtilizationMetric& operator=(Aws::Utils::Json::JsonView jsonValue); Aws::Utils::Json::JsonValue Jsonize() const; /** * <p>The name of the utilization metric.</p> <p>The following utilization metrics * are available:</p> <ul> <li> <p> <code>Cpu</code> - The percentage of allocated * EC2 compute units that are currently in use on the instance. This metric * identifies the processing power required to run an application on the * instance.</p> <p>Depending on the instance type, tools in your operating system * can show a lower percentage than CloudWatch when the instance is not allocated a * full processor core.</p> <p>Units: Percent</p> </li> <li> <p> * <code>Memory</code> - The percentage of memory that is currently in use on the * instance. This metric identifies the amount of memory required to run an * application on the instance.</p> <p>Units: Percent</p> <p>The * <code>Memory</code> metric is returned only for resources that have the unified * CloudWatch agent installed on them. For more information, see <a * href="https://docs.aws.amazon.com/compute-optimizer/latest/ug/metrics.html#cw-agent">Enabling * Memory Utilization with the CloudWatch Agent</a>.</p> </li> <li> <p> * <code>EBS_READ_OPS_PER_SECOND</code> - The completed read operations from all * EBS volumes attached to the instance in a specified period of time.</p> <p>Unit: * Count</p> </li> <li> <p> <code>EBS_WRITE_OPS_PER_SECOND</code> - The completed * write operations to all EBS volumes attached to the instance in a specified * period of time.</p> <p>Unit: Count</p> </li> <li> <p> * <code>EBS_READ_BYTES_PER_SECOND</code> - The bytes read from all EBS volumes * attached to the instance in a specified period of time.</p> <p>Unit: Bytes</p> * </li> <li> <p> <code>EBS_WRITE_BYTES_PER_SECOND</code> - The bytes written to * all EBS volumes attached to the instance in a specified period of time.</p> * <p>Unit: Bytes</p> </li> </ul> */ inline const MetricName& GetName() const{ return m_name; } /** * <p>The name of the utilization metric.</p> <p>The following utilization metrics * are available:</p> <ul> <li> <p> <code>Cpu</code> - The percentage of allocated * EC2 compute units that are currently in use on the instance. This metric * identifies the processing power required to run an application on the * instance.</p> <p>Depending on the instance type, tools in your operating system * can show a lower percentage than CloudWatch when the instance is not allocated a * full processor core.</p> <p>Units: Percent</p> </li> <li> <p> * <code>Memory</code> - The percentage of memory that is currently in use on the * instance. This metric identifies the amount of memory required to run an * application on the instance.</p> <p>Units: Percent</p> <p>The * <code>Memory</code> metric is returned only for resources that have the unified * CloudWatch agent installed on them. For more information, see <a * href="https://docs.aws.amazon.com/compute-optimizer/latest/ug/metrics.html#cw-agent">Enabling * Memory Utilization with the CloudWatch Agent</a>.</p> </li> <li> <p> * <code>EBS_READ_OPS_PER_SECOND</code> - The completed read operations from all * EBS volumes attached to the instance in a specified period of time.</p> <p>Unit: * Count</p> </li> <li> <p> <code>EBS_WRITE_OPS_PER_SECOND</code> - The completed * write operations to all EBS volumes attached to the instance in a specified * period of time.</p> <p>Unit: Count</p> </li> <li> <p> * <code>EBS_READ_BYTES_PER_SECOND</code> - The bytes read from all EBS volumes * attached to the instance in a specified period of time.</p> <p>Unit: Bytes</p> * </li> <li> <p> <code>EBS_WRITE_BYTES_PER_SECOND</code> - The bytes written to * all EBS volumes attached to the instance in a specified period of time.</p> * <p>Unit: Bytes</p> </li> </ul> */ inline bool NameHasBeenSet() const { return m_nameHasBeenSet; } /** * <p>The name of the utilization metric.</p> <p>The following utilization metrics * are available:</p> <ul> <li> <p> <code>Cpu</code> - The percentage of allocated * EC2 compute units that are currently in use on the instance. This metric * identifies the processing power required to run an application on the * instance.</p> <p>Depending on the instance type, tools in your operating system * can show a lower percentage than CloudWatch when the instance is not allocated a * full processor core.</p> <p>Units: Percent</p> </li> <li> <p> * <code>Memory</code> - The percentage of memory that is currently in use on the * instance. This metric identifies the amount of memory required to run an * application on the instance.</p> <p>Units: Percent</p> <p>The * <code>Memory</code> metric is returned only for resources that have the unified * CloudWatch agent installed on them. For more information, see <a * href="https://docs.aws.amazon.com/compute-optimizer/latest/ug/metrics.html#cw-agent">Enabling * Memory Utilization with the CloudWatch Agent</a>.</p> </li> <li> <p> * <code>EBS_READ_OPS_PER_SECOND</code> - The completed read operations from all * EBS volumes attached to the instance in a specified period of time.</p> <p>Unit: * Count</p> </li> <li> <p> <code>EBS_WRITE_OPS_PER_SECOND</code> - The completed * write operations to all EBS volumes attached to the instance in a specified * period of time.</p> <p>Unit: Count</p> </li> <li> <p> * <code>EBS_READ_BYTES_PER_SECOND</code> - The bytes read from all EBS volumes * attached to the instance in a specified period of time.</p> <p>Unit: Bytes</p> * </li> <li> <p> <code>EBS_WRITE_BYTES_PER_SECOND</code> - The bytes written to * all EBS volumes attached to the instance in a specified period of time.</p> * <p>Unit: Bytes</p> </li> </ul> */ inline void SetName(const MetricName& value) { m_nameHasBeenSet = true; m_name = value; } /** * <p>The name of the utilization metric.</p> <p>The following utilization metrics * are available:</p> <ul> <li> <p> <code>Cpu</code> - The percentage of allocated * EC2 compute units that are currently in use on the instance. This metric * identifies the processing power required to run an application on the * instance.</p> <p>Depending on the instance type, tools in your operating system * can show a lower percentage than CloudWatch when the instance is not allocated a * full processor core.</p> <p>Units: Percent</p> </li> <li> <p> * <code>Memory</code> - The percentage of memory that is currently in use on the * instance. This metric identifies the amount of memory required to run an * application on the instance.</p> <p>Units: Percent</p> <p>The * <code>Memory</code> metric is returned only for resources that have the unified * CloudWatch agent installed on them. For more information, see <a * href="https://docs.aws.amazon.com/compute-optimizer/latest/ug/metrics.html#cw-agent">Enabling * Memory Utilization with the CloudWatch Agent</a>.</p> </li> <li> <p> * <code>EBS_READ_OPS_PER_SECOND</code> - The completed read operations from all * EBS volumes attached to the instance in a specified period of time.</p> <p>Unit: * Count</p> </li> <li> <p> <code>EBS_WRITE_OPS_PER_SECOND</code> - The completed * write operations to all EBS volumes attached to the instance in a specified * period of time.</p> <p>Unit: Count</p> </li> <li> <p> * <code>EBS_READ_BYTES_PER_SECOND</code> - The bytes read from all EBS volumes * attached to the instance in a specified period of time.</p> <p>Unit: Bytes</p> * </li> <li> <p> <code>EBS_WRITE_BYTES_PER_SECOND</code> - The bytes written to * all EBS volumes attached to the instance in a specified period of time.</p> * <p>Unit: Bytes</p> </li> </ul> */ inline void SetName(MetricName&& value) { m_nameHasBeenSet = true; m_name = std::move(value); } /** * <p>The name of the utilization metric.</p> <p>The following utilization metrics * are available:</p> <ul> <li> <p> <code>Cpu</code> - The percentage of allocated * EC2 compute units that are currently in use on the instance. This metric * identifies the processing power required to run an application on the * instance.</p> <p>Depending on the instance type, tools in your operating system * can show a lower percentage than CloudWatch when the instance is not allocated a * full processor core.</p> <p>Units: Percent</p> </li> <li> <p> * <code>Memory</code> - The percentage of memory that is currently in use on the * instance. This metric identifies the amount of memory required to run an * application on the instance.</p> <p>Units: Percent</p> <p>The * <code>Memory</code> metric is returned only for resources that have the unified * CloudWatch agent installed on them. For more information, see <a * href="https://docs.aws.amazon.com/compute-optimizer/latest/ug/metrics.html#cw-agent">Enabling * Memory Utilization with the CloudWatch Agent</a>.</p> </li> <li> <p> * <code>EBS_READ_OPS_PER_SECOND</code> - The completed read operations from all * EBS volumes attached to the instance in a specified period of time.</p> <p>Unit: * Count</p> </li> <li> <p> <code>EBS_WRITE_OPS_PER_SECOND</code> - The completed * write operations to all EBS volumes attached to the instance in a specified * period of time.</p> <p>Unit: Count</p> </li> <li> <p> * <code>EBS_READ_BYTES_PER_SECOND</code> - The bytes read from all EBS volumes * attached to the instance in a specified period of time.</p> <p>Unit: Bytes</p> * </li> <li> <p> <code>EBS_WRITE_BYTES_PER_SECOND</code> - The bytes written to * all EBS volumes attached to the instance in a specified period of time.</p> * <p>Unit: Bytes</p> </li> </ul> */ inline UtilizationMetric& WithName(const MetricName& value) { SetName(value); return *this;} /** * <p>The name of the utilization metric.</p> <p>The following utilization metrics * are available:</p> <ul> <li> <p> <code>Cpu</code> - The percentage of allocated * EC2 compute units that are currently in use on the instance. This metric * identifies the processing power required to run an application on the * instance.</p> <p>Depending on the instance type, tools in your operating system * can show a lower percentage than CloudWatch when the instance is not allocated a * full processor core.</p> <p>Units: Percent</p> </li> <li> <p> * <code>Memory</code> - The percentage of memory that is currently in use on the * instance. This metric identifies the amount of memory required to run an * application on the instance.</p> <p>Units: Percent</p> <p>The * <code>Memory</code> metric is returned only for resources that have the unified * CloudWatch agent installed on them. For more information, see <a * href="https://docs.aws.amazon.com/compute-optimizer/latest/ug/metrics.html#cw-agent">Enabling * Memory Utilization with the CloudWatch Agent</a>.</p> </li> <li> <p> * <code>EBS_READ_OPS_PER_SECOND</code> - The completed read operations from all * EBS volumes attached to the instance in a specified period of time.</p> <p>Unit: * Count</p> </li> <li> <p> <code>EBS_WRITE_OPS_PER_SECOND</code> - The completed * write operations to all EBS volumes attached to the instance in a specified * period of time.</p> <p>Unit: Count</p> </li> <li> <p> * <code>EBS_READ_BYTES_PER_SECOND</code> - The bytes read from all EBS volumes * attached to the instance in a specified period of time.</p> <p>Unit: Bytes</p> * </li> <li> <p> <code>EBS_WRITE_BYTES_PER_SECOND</code> - The bytes written to * all EBS volumes attached to the instance in a specified period of time.</p> * <p>Unit: Bytes</p> </li> </ul> */ inline UtilizationMetric& WithName(MetricName&& value) { SetName(std::move(value)); return *this;} /** * <p>The statistic of the utilization metric.</p> <p>The following statistics are * available:</p> <ul> <li> <p> <code>Average</code> - This is the value of Sum / * SampleCount during the specified period, or the average value observed during * the specified period.</p> </li> <li> <p> <code>Maximum</code> - The highest * value observed during the specified period. Use this value to determine high * volumes of activity for your application.</p> </li> </ul> */ inline const MetricStatistic& GetStatistic() const{ return m_statistic; } /** * <p>The statistic of the utilization metric.</p> <p>The following statistics are * available:</p> <ul> <li> <p> <code>Average</code> - This is the value of Sum / * SampleCount during the specified period, or the average value observed during * the specified period.</p> </li> <li> <p> <code>Maximum</code> - The highest * value observed during the specified period. Use this value to determine high * volumes of activity for your application.</p> </li> </ul> */ inline bool StatisticHasBeenSet() const { return m_statisticHasBeenSet; } /** * <p>The statistic of the utilization metric.</p> <p>The following statistics are * available:</p> <ul> <li> <p> <code>Average</code> - This is the value of Sum / * SampleCount during the specified period, or the average value observed during * the specified period.</p> </li> <li> <p> <code>Maximum</code> - The highest * value observed during the specified period. Use this value to determine high * volumes of activity for your application.</p> </li> </ul> */ inline void SetStatistic(const MetricStatistic& value) { m_statisticHasBeenSet = true; m_statistic = value; } /** * <p>The statistic of the utilization metric.</p> <p>The following statistics are * available:</p> <ul> <li> <p> <code>Average</code> - This is the value of Sum / * SampleCount during the specified period, or the average value observed during * the specified period.</p> </li> <li> <p> <code>Maximum</code> - The highest * value observed during the specified period. Use this value to determine high * volumes of activity for your application.</p> </li> </ul> */ inline void SetStatistic(MetricStatistic&& value) { m_statisticHasBeenSet = true; m_statistic = std::move(value); } /** * <p>The statistic of the utilization metric.</p> <p>The following statistics are * available:</p> <ul> <li> <p> <code>Average</code> - This is the value of Sum / * SampleCount during the specified period, or the average value observed during * the specified period.</p> </li> <li> <p> <code>Maximum</code> - The highest * value observed during the specified period. Use this value to determine high * volumes of activity for your application.</p> </li> </ul> */ inline UtilizationMetric& WithStatistic(const MetricStatistic& value) { SetStatistic(value); return *this;} /** * <p>The statistic of the utilization metric.</p> <p>The following statistics are * available:</p> <ul> <li> <p> <code>Average</code> - This is the value of Sum / * SampleCount during the specified period, or the average value observed during * the specified period.</p> </li> <li> <p> <code>Maximum</code> - The highest * value observed during the specified period. Use this value to determine high * volumes of activity for your application.</p> </li> </ul> */ inline UtilizationMetric& WithStatistic(MetricStatistic&& value) { SetStatistic(std::move(value)); return *this;} /** * <p>The value of the utilization metric.</p> */ inline double GetValue() const{ return m_value; } /** * <p>The value of the utilization metric.</p> */ inline bool ValueHasBeenSet() const { return m_valueHasBeenSet; } /** * <p>The value of the utilization metric.</p> */ inline void SetValue(double value) { m_valueHasBeenSet = true; m_value = value; } /** * <p>The value of the utilization metric.</p> */ inline UtilizationMetric& WithValue(double value) { SetValue(value); return *this;} private: MetricName m_name; bool m_nameHasBeenSet; MetricStatistic m_statistic; bool m_statisticHasBeenSet; double m_value; bool m_valueHasBeenSet; }; } // namespace Model } // namespace ComputeOptimizer } // namespace Aws
57.845161
119
0.680683
[ "model" ]
d86471c3db83db4eaff84b4c048d97bc1bab17d5
2,457
h
C
include/ossim/base/ossimConnectionEvent.h
DigitalGlobe/ossim
a03729866f15bcf3bf210e14d395c683321b12bc
[ "MIT" ]
null
null
null
include/ossim/base/ossimConnectionEvent.h
DigitalGlobe/ossim
a03729866f15bcf3bf210e14d395c683321b12bc
[ "MIT" ]
null
null
null
include/ossim/base/ossimConnectionEvent.h
DigitalGlobe/ossim
a03729866f15bcf3bf210e14d395c683321b12bc
[ "MIT" ]
1
2018-10-11T11:36:16.000Z
2018-10-11T11:36:16.000Z
//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimConnectionEvent.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimConnectionEvent_HEADER #define ossimConnectionEvent_HEADER #include <vector> #include <ossim/base/ossimEventIds.h> #include <ossim/base/ossimEvent.h> #include <ossim/base/ossimConnectableObject.h> class OSSIMDLLEXPORT ossimConnectionEvent : public ossimEvent { public: enum ossimConnectionDirectionType { OSSIM_DIRECTION_UNKNOWN = 0, OSSIM_INPUT_DIRECTION = 1, OSSIM_OUTPUT_DIRECTION = 2, OSSIM_INPUT_OUTPUT_DIRECTION = 3 }; ossimConnectionEvent(ossimObject* object=NULL, long id=OSSIM_EVENT_NULL_ID); ossimConnectionEvent(ossimObject* object, long id, const ossimConnectableObject::ConnectableObjectList& newList, const ossimConnectableObject::ConnectableObjectList& oldList, ossimConnectionDirectionType whichDirection); ossimConnectionEvent(ossimObject* object, long id, ossimConnectableObject* newConnectableObject, ossimConnectableObject* oldConnectableObject, ossimConnectionDirectionType whichDirection); ossimConnectionEvent(const ossimConnectionEvent& rhs); ossimObject* dup()const; virtual void setDirection(ossimConnectionDirectionType direction); virtual ossimConnectionDirectionType getDirection()const; virtual ossim_uint32 getNumberOfNewObjects()const; virtual ossim_uint32 getNumberOfOldObjects()const; virtual ossimConnectableObject* getOldObject(ossim_uint32 i=0); virtual ossimConnectableObject* getNewObject(ossim_uint32 i=0); virtual bool isDisconnect()const; virtual bool isConnect()const; virtual bool isInputDirection()const; virtual bool isOutputDirection()const; protected: ossimConnectableObject::ConnectableObjectList theNewObjectList; ossimConnectableObject::ConnectableObjectList theOldObjectList; ossimConnectionDirectionType theDirectionType; TYPE_DATA }; #endif
30.7125
85
0.665853
[ "object", "vector" ]
d867b1b53d57414f0719b59dea44ad912640ef05
3,217
c
C
infoprinters.c
Kaaos/Bathytools
03f30e233d02e3b2db00eb3bd373121c63ea84a1
[ "MIT" ]
3
2019-03-31T09:19:41.000Z
2020-11-13T12:58:43.000Z
infoprinters.c
tfilppula/Bathytools
03f30e233d02e3b2db00eb3bd373121c63ea84a1
[ "MIT" ]
null
null
null
infoprinters.c
tfilppula/Bathytools
03f30e233d02e3b2db00eb3bd373121c63ea84a1
[ "MIT" ]
null
null
null
#include "bathymetrictools.h" /* * This file contains: * - Printer functions for structured data types sto help with development * - Help */ /* * Prints help */ void printHelp(void) { printf("Bathymetric surface tools - help:\n"); printf("\n 1. To launch user interface use -ui flag:\n\n\tsurfacetools -ui\n"); printf("\n 2. CLI (use for scripting):\n\n\tsurfacetools [full inputfilepath] [full outputfilepath] -methodflag P -methodflag P -trimflag(Rolling Coin only) \n"); printf("\n\tMethods:\n\t -buffer = Buffer shoals (3x3 cell focal max filter)\n\t\t* No parameters\n\t\t* Use example: surfacetools [inputfile] [outputfile] -buffer"); printf("\n\t -offset = Vertical surface offset in meters\n\t\t* Parameters: [h] = offset in meters (float), can be positive or negative (addition to cell value)\n\t\t* Use example: surfacetools [inputfile] [outputfile] -offset -0.25"); printf("\n\t -laplacian = Laplacian smoothing\n\t\t* Parameters: [N] = number of iterations (integer)\n\t\t* Use example: surfacetools [inputfile] [outputfile] -laplacian 25"); printf("\n\t -rollcoin = Rolling Coin smoothing\n\t\t* Parameters: [R] = coin radius in cells (integer), [trim/notrim] = trim flag (coin edge trimming)"); printf("\n\t\t* Use example: surfacetools [inputfile] [outputfile] -rollcoin 15 trim"); printf("\n\n\tExamples:\n"); printf("\t\tBuffer shoals: surfacetools inputfile.tiff outputfile.tiff -buffer\n"); printf("\t\tOffset: surfacetools inputfile.tiff outputfile.tiff -offset -0.55\n"); printf("\t\tLaplacian smoothing, 10 iterations: surfacetools inputfile.tiff outputfile.tiff -laplacian 10\n"); printf("\t\tRolling Coin, radius 15, trimmed coin edges: surfacetools inputfile.tiff outputfile.tiff -rollcoin 15 trim\n"); printf("\t\t\nChaining process steps (Shoal Buffering >> Rolling Coin >> Laplacian Smoothing >> Offset):\n\t\t surfacetools inputfile.tiff outputfile.tiff -buffer -rollcoin 13 notrim -laplacian 10 -offset 0.35\n\n"); } /* * Prints info of depth model surface */ void printFloatSurfaceInfo(struct FloatSurface *input) { printf("\n\nStruct FloatSurface content:\n"); printf("Filepath (input): %s\n", input->inputfp); printf("\nProjection: %s\n", input->projection); printf("\nNodata value: %f\n", input->nodata); printf("Rows: %d, Columns: %d\n", input->rows, input->cols); printf("Georeferencing information: %f, %f, %f, %f, %f, %f \n", input->geotransform[0], input->geotransform[1], input->geotransform[2], input->geotransform[3], input->geotransform[4], input->geotransform[5]); printf("Test from array[%d][%d]: %f\n\n", input->rows / 2, input->cols / 2, input->array[input->rows / 2][input->cols / 2]); } /* * Prints coin */ void printCoin(struct Coin *penny) { printf("\nCoin information:\nDiameter: %d (Radius: %d)\n\n", penny->diameter, penny->radius); for (int row = 0; row < penny->diameter; row++) { for (int col = 0; col < penny->diameter; col++) { if (penny->array[row][col] == 1) { printf("1"); } else { printf(" "); } printf(" "); } printf("\n"); } }
52.737705
240
0.655891
[ "model" ]
d86c0108c90baef3218247ad439386afb042d1d3
417
h
C
MyOne/Pods/DKNightVersion/Classes/Helper/DKNightVersionUtility.h
guansenH/MyOne-iOS-master
1c50cb8deb2038a4a955794e1f5459b73217e5be
[ "MIT" ]
554
2015-12-05T10:30:37.000Z
2022-03-21T10:15:59.000Z
MyOne/Pods/DKNightVersion/Classes/Helper/DKNightVersionUtility.h
guansenH/MyOne-iOS-master
1c50cb8deb2038a4a955794e1f5459b73217e5be
[ "MIT" ]
3
2016-04-09T10:42:09.000Z
2017-03-23T13:05:18.000Z
MyOne/Pods/DKNightVersion/Classes/Helper/DKNightVersionUtility.h
guansenH/MyOne-iOS-master
1c50cb8deb2038a4a955794e1f5459b73217e5be
[ "MIT" ]
219
2015-12-02T15:34:24.000Z
2022-01-31T03:52:02.000Z
// // DKNightVersionUtility.h // DKNightVersion // // Created by apple on 15/5/20. // Copyright (c) 2015年 DeltaX. All rights reserved. // #import <UIKit/UIKit.h> @interface DKNightVersionUtility : NSObject /** * Whether the object should change color * * @param object Object which should change color * * @return Whether the object should change color */ + (BOOL)shouldChangeColor:(id)object; @end
17.375
52
0.702638
[ "object" ]
9cad30b59600d354a2403b8532f037b05404dca1
13,887
h
C
ios/CouchbaseLite.framework/Headers/CBLQuery.h
joesonw/react-native-exp
982a58190e1a3675214211eeb0cbb889775dbb73
[ "ISC", "Apache-2.0", "MIT" ]
4
2015-04-15T15:34:40.000Z
2016-02-15T23:11:09.000Z
CouchbaseLite.framework/Headers/CBLQuery.h
scalbatty/Pokeping
134fc0838606cc4bdbd020bff4b8340fb54abd86
[ "MIT" ]
7
2015-08-20T15:02:48.000Z
2015-10-22T16:37:04.000Z
vendor/osx/CouchbaseLite.framework/Versions/A/Headers/CBLQuery.h
ndouglas/ReactiveCouchbaseLite
e93aad809173f0d8a57eaa16e6cb712fc2a2c38f
[ "Unlicense" ]
null
null
null
// // CBLQuery.h // CouchbaseLite // // Created by Jens Alfke on 6/18/12. // Copyright (c) 2012-2013 Couchbase, Inc. All rights reserved. // #import "CBLBase.h" @class CBLDatabase, CBLDocument; @class CBLLiveQuery, CBLQueryEnumerator, CBLQueryRow, CBLRevision; NS_ASSUME_NONNULL_BEGIN typedef NS_ENUM(unsigned, CBLAllDocsMode) { kCBLAllDocs, /**< Normal behavior for all-docs query */ kCBLIncludeDeleted, /**< Will include rows for deleted documents */ kCBLShowConflicts, /**< Rows will indicate conflicting revisions */ kCBLOnlyConflicts, /**< Will _only_ return rows for docs in conflict */ kCBLBySequence /**< Order by sequence number (i.e. chronologically) */ }; /** Query options to allow out-of-date results to be returned in return for faster queries. */ typedef NS_ENUM(unsigned, CBLIndexUpdateMode) { kCBLUpdateIndexBefore, /**< Always update index if needed before querying (default) */ kCBLUpdateIndexNever, /**< Don't update the index; results may be out of date */ kCBLUpdateIndexAfter /**< Update index _after_ querying (results may still be out of date) */ }; /** Represents a query of a CouchbaseLite 'view', or of a view-like resource like _all_documents. */ @interface CBLQuery : NSObject /** The database that contains this view. */ @property (readonly) CBLDatabase* database; /** The maximum number of rows to return. Defaults to 'unlimited' (UINT_MAX). */ @property NSUInteger limit; /** The number of initial rows to skip. Default value is 0. Should only be used with small values. For efficient paging, use startKey and limit.*/ @property NSUInteger skip; /** Should the rows be returned in descending key order? Default value is NO. */ @property BOOL descending; /** If non-nil, the key value to start at. */ @property (copy, nullable) id startKey; /** If non-nil, the key value to end after. */ @property (copy, nullable) id endKey; /** If non-nil, the document ID to start at. (Useful if the view contains multiple identical keys, making .startKey ambiguous.) */ @property (copy, nullable) NSString* startKeyDocID; /** If non-nil, the document ID to end at. (Useful if the view contains multiple identical keys, making .endKey ambiguous.) */ @property (copy, nullable) NSString* endKeyDocID; /** If YES (the default) the startKey (or startKeyDocID) comparison uses ">=". Else it uses ">". */ @property BOOL inclusiveStart; /** If YES (the default) the endKey (or endKeyDocID) comparison uses "<=". Else it uses "<". */ @property BOOL inclusiveEnd; /** If nonzero, enables prefix matching of string or array keys. * A value of 1 treats the endKey itself as a prefix: if it's a string, keys in the index that come after the endKey, but begin with the same prefix, will be matched. (For example, if the endKey is "foo" then the key "foolish" in the index will be matched, but not "fong".) Or if the endKey is an array, any array beginning with those elements will be matched. (For example, if the endKey is [1], then [1, "x"] will match, but not [2].) If the key is any other type, there is no effect. * A value of 2 assumes the endKey is an array and treats its final item as a prefix, using the rules above. (For example, an endKey of [1, "x"] will match [1, "xtc"] but not [1, "y"].) * A value of 3 assumes the key is an array of arrays, etc. Note that if the .descending property is also set, the search order is reversed and the above discussion applies to the startKey, _not_ the endKey. */ @property NSUInteger prefixMatchLevel; /** An optional array of NSSortDescriptor objects; overrides the default by-key ordering. Key-paths are interpreted relative to a CBLQueryRow object, so they should start with "value" to refer to the value, or "key" to refer to the key. A limited form of array indexing is supported, so you can refer to "key[1]" or "value[0]" if the key or value are arrays. This only works with indexes from 0 to 3. */ @property (copy, nullable) CBLArrayOf(NSSortDescriptor*)* sortDescriptors; /** An optional predicate that filters the resulting query rows. If present, it's called on every row returned from the query, and if it returns NO the row is skipped. Key-paths are interpreted relative to a CBLQueryRow, so they should start with "value" to refer to the value, or "key" to refer to the key. */ @property (strong, nullable) NSPredicate* postFilter; /** Determines whether or when the view index is updated. By default, the index will be updated if necessary before the query runs -- this guarantees up-to-date results but can cause a delay. The "Never" mode skips updating the index, so it's faster but can return out of date results. The "After" mode is a compromise that may return out of date results but if so will start asynchronously updating the index after the query so future results are accurate. */ @property CBLIndexUpdateMode indexUpdateMode; /** If non-nil, the query will fetch only the rows with the given keys. */ @property (copy, nullable) NSArray* keys; /** If set to YES, disables use of the reduce function. (Equivalent to setting "?reduce=false" in the REST API.) */ @property BOOL mapOnly; /** If non-zero, enables grouping of results, in views that have reduce functions. */ @property NSUInteger groupLevel; /** If set to YES, the results will include the entire document contents of the associated rows. These can be accessed via CBLQueryRow's -documentProperties property. This slows down the query, but can be a good optimization if you know you'll need the entire contents of each document. */ @property BOOL prefetch; /** Changes the behavior of a query created by -createAllDocumentsQuery. * In mode kCBLAllDocs (the default), the query simply returns all non-deleted documents. * In mode kCBLIncludeDeleted, it also returns deleted documents. * In mode kCBLShowConflicts, the .conflictingRevisions property of each row will return the conflicting revisions, if any, of that document. * In mode kCBLOnlyConflicts, _only_ documents in conflict will be returned. (This mode is especially useful for use with a CBLLiveQuery, so you can be notified of conflicts as they happen, i.e. when they're pulled in by a replication.) */ @property CBLAllDocsMode allDocsMode; /** Sends the query to the server and returns an enumerator over the result rows (Synchronous). Note: In a CBLLiveQuery you should access the .rows property instead. */ - (nullable CBLQueryEnumerator*) run: (NSError**)outError; /** Starts an asynchronous query. Returns immediately, then calls the onComplete block when the query completes, passing it the row enumerator (or an error). */ - (void) runAsync: (void (^)(CBLQueryEnumerator*, NSError*))onComplete __attribute__((nonnull)); /** Returns a live query with the same parameters. */ - (CBLLiveQuery*) asLiveQuery; - (instancetype) init NS_UNAVAILABLE; @end /** A CBLQuery subclass that automatically refreshes the result rows every time the database changes. All you need to do is use KVO to observe changes to the .rows property. */ @interface CBLLiveQuery : CBLQuery /** The shortest interval at which the query will update, regardless of how often the database changes. Defaults to 0.5 sec. Increase this if the query is expensive and the database updates frequently, to limit CPU consumption. */ @property (nonatomic) NSTimeInterval updateInterval; /** Starts observing database changes. The .rows property will now update automatically. (You usually don't need to call this yourself, since accessing or observing the .rows property will call -start for you.) */ - (void) start; /** Stops observing database changes. Calling -start or .rows will restart it. */ - (void) stop; /** The current query results; this updates as the database changes, and can be observed using KVO. Its value will be nil until the initial asynchronous query finishes. */ @property (readonly, strong, nullable) CBLQueryEnumerator* rows; /** Blocks until the intial asynchronous query finishes. After this call either .rows or .lastError will be non-nil. */ - (BOOL) waitForRows; /** If non-nil, the error of the last execution of the query. If nil, the last execution of the query was successful. */ @property (readonly, nullable) NSError* lastError; /** Call this method to notify that the query parameters have been changed, the CBLLiveQuery object should re-run the query. */ - (void) queryOptionsChanged; @end /** Enumerator on a CBLQuery's result rows. The objects returned are instances of CBLQueryRow. */ @interface CBLQueryEnumerator : NSEnumerator <NSCopying, NSFastEnumeration> /** The number of rows returned in this enumerator */ @property (readonly) NSUInteger count; /** The database's current sequenceNumber at the time the view was generated. */ @property (readonly) UInt64 sequenceNumber; /** YES if the database has changed since the view was generated. */ @property (readonly) BOOL stale; /** The next result row. This is the same as -nextObject but with a checked return type. */ - (nullable CBLQueryRow*) nextRow; /** Random access to a row in the result */ - (CBLQueryRow*) rowAtIndex: (NSUInteger)index; /** Re-sorts the rows based on the given sort descriptors. This operation requires that all rows be loaded into memory, so you can't have previously called -nextObject, -nextRow or for...in on this enumerator. (But it's fine to use them _after_ calling this method.) You can call this method multiple times with different sort descriptors, but the effects on any in-progress enumeration are undefined. The items in the array can be NSSortDescriptors or simply NSStrings. An NSString will be treated as an NSSortDescriptor with the string as the keyPath; prefix with a "-" for descending sort. Key-paths are interpreted relative to a CBLQueryRow, so they should start with "value" to refer to the value, or "key" to refer to the key. A limited form of array indexing is supported, so you can refer to "key[1]" or "value[0]" if the key or value are arrays. This only works with indexes from 0 to 3. */ - (void) sortUsingDescriptors: (NSArray*)sortDescriptors; - (instancetype) init NS_UNAVAILABLE; - (void) reset __attribute__((deprecated("call allObjects and iterate that array multiple times"))); @end /** A result row from a CouchbaseLite view query. Full-text and geo queries return subclasses -- see CBLFullTextQueryRow and CBLGeoQueryRow. */ @interface CBLQueryRow : NSObject /** The row's key: this is the first parameter passed to the emit() call that generated the row. */ @property (readonly) id key; /** The row's value: this is the second parameter passed to the emit() call that generated the row. */ @property (readonly, nullable) id value; /** The ID of the document described by this view row. This is not necessarily the same as the document that caused this row to be emitted; see the discussion of the .sourceDocumentID property for details. */ @property (readonly, nullable) NSString* documentID; /** The ID of the document that caused this view row to be emitted. This is the value of the "id" property of the JSON view row. It will be the same as the .documentID property, unless the map function caused a related document to be linked by adding an "_id" key to the emitted value; in this case .documentID will refer to the linked document, while sourceDocumentID always refers to the original document. In a reduced or grouped query the value will be nil, since the rows don't correspond to individual documents. */ @property (readonly, nullable) NSString* sourceDocumentID; /** The revision ID of the document this row was mapped from. */ @property (readonly) NSString* documentRevisionID; @property (readonly) CBLDatabase* database; /** The document this row was mapped from. This will be nil if a grouping was enabled in the query, because then the result rows don't correspond to individual documents. */ @property (readonly, nullable) CBLDocument* document; /** The properties of the document this row was mapped from. To get this, you must have set the .prefetch property on the query; else this will be nil. (You can still get the document properties via the .document property, of course. But it takes a separate call to the database. So if you're doing it for every row, using .prefetch and .documentProperties is faster.) */ @property (readonly, nullable) CBLJSONDict* documentProperties; /** If this row's key is an array, returns the item at that index in the array. If the key is not an array, index=0 will return the key itself. If the index is out of range, returns nil. */ - (nullable id) keyAtIndex: (NSUInteger)index; /** Convenience for use in keypaths. Returns the key at the given index. */ //@property (readonly, nullable) id key0, key1, key2, key3; @property (readonly, nullable) id key0; @property (readonly, nullable) id key1; @property (readonly, nullable) id key2; @property (readonly, nullable) id key3; /** The database sequence number of the associated doc/revision. */ @property (readonly) UInt64 sequenceNumber; /** Returns all conflicting revisions of the document, as an array of CBLRevision, or nil if the document is not in conflict. The first object in the array will be the default "winning" revision that shadows the others. This is only valid in an allDocuments query whose allDocsMode is set to kCBLShowConflicts or kCBLOnlyConflicts; otherwise it returns nil. */ @property (readonly, nullable) CBLArrayOf(CBLRevision*)* conflictingRevisions; - (instancetype) init NS_UNAVAILABLE; @end NS_ASSUME_NONNULL_END
47.395904
101
0.734716
[ "object" ]
9cc01a0067d17d97fcb0dca1262f441158b1b479
1,783
h
C
Prj-Linux/hyperlpr/include/Pipeline.h
kitten23/HyperLPR
a0061b188324e001ce153b3274e5ff1348d8066d
[ "Apache-2.0" ]
1,104
2016-07-11T11:20:32.000Z
2022-03-31T08:44:48.000Z
Prj-Linux/hyperlpr/include/Pipeline.h
kitten23/HyperLPR
a0061b188324e001ce153b3274e5ff1348d8066d
[ "Apache-2.0" ]
48
2017-04-12T06:01:07.000Z
2022-03-15T05:49:45.000Z
Prj-Linux/hyperlpr/include/Pipeline.h
kitten23/HyperLPR
a0061b188324e001ce153b3274e5ff1348d8066d
[ "Apache-2.0" ]
360
2016-07-11T11:20:34.000Z
2022-03-29T06:31:38.000Z
// // Created by Jack Yu on 22/10/2017. // #ifndef HYPERPR_PIPLINE_H #define HYPERPR_PIPLINE_H #include "CNNRecognizer.h" #include "FastDeskew.h" #include "FineMapping.h" #include "PlateDetection.h" #include "PlateInfo.h" #include "PlateSegmentation.h" #include "Recognizer.h" #include "SegmentationFreeRecognizer.h" namespace pr { const std::vector<std::string> CH_PLATE_CODE{ "京", "沪", "津", "渝", "冀", "晋", "蒙", "辽", "吉", "黑", "苏", "浙", "皖", "闽", "赣", "鲁", "豫", "鄂", "湘", "粤", "桂", "琼", "川", "贵", "云", "藏", "陕", "甘", "青", "宁", "新", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "J", "K", "L", "M", "N", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "港", "学", "使", "警", "澳", "挂", "军", "北", "南", "广", "沈", "兰", "成", "济", "海", "民", "航", "空"}; const int SEGMENTATION_FREE_METHOD = 0; const int SEGMENTATION_BASED_METHOD = 1; class PipelinePR { public: GeneralRecognizer *generalRecognizer; PlateDetection *plateDetection; PlateSegmentation *plateSegmentation; FineMapping *fineMapping; SegmentationFreeRecognizer *segmentationFreeRecognizer; PipelinePR(std::string detector_filename, std::string finemapping_prototxt, std::string finemapping_caffemodel, std::string segmentation_prototxt, std::string segmentation_caffemodel, std::string charRecognization_proto, std::string charRecognization_caffemodel, std::string segmentationfree_proto, std::string segmentationfree_caffemodel); ~PipelinePR(); std::vector<std::string> plateRes; std::vector<PlateInfo> RunPiplineAsImage(cv::Mat plateImage, int method); }; } // namespace pr #endif // HYPERPR_PIPLINE_H
32.418182
77
0.591699
[ "vector" ]
9cc74d9218ab82b9343ecc3d544b31b29e441e23
718
h
C
src/jpeg/CompareDialog.h
d8euAI8sMs/it-9-jpeg
e40fb9870ad4fadd72b1597f63f8cb1add51b87b
[ "Apache-2.0" ]
null
null
null
src/jpeg/CompareDialog.h
d8euAI8sMs/it-9-jpeg
e40fb9870ad4fadd72b1597f63f8cb1add51b87b
[ "Apache-2.0" ]
null
null
null
src/jpeg/CompareDialog.h
d8euAI8sMs/it-9-jpeg
e40fb9870ad4fadd72b1597f63f8cb1add51b87b
[ "Apache-2.0" ]
null
null
null
#pragma once #include <util/common/gui/PlotControl.h> #include "model.h" // CCompareDialog dialog class CCompareDialog : public CDialogEx { DECLARE_DYNAMIC(CCompareDialog) public: CCompareDialog(CWnd* pParent, model::model_data * d, size_t mag); // standard constructor virtual ~CCompareDialog(); // Dialog Data enum { IDD = IDD_COMPAREDIALOG }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support model::model_data * m_data; size_t m_mag; DECLARE_MESSAGE_MAP() public: CPlotControl m_img; virtual BOOL OnInitDialog(); afx_msg void OnLButtonDown(UINT nFlags, CPoint point); afx_msg void OnLButtonUp(UINT nFlags, CPoint point); };
22.4375
95
0.718663
[ "model" ]
9cc876ebc8e8d7792b0174f0ec274e6a83296dfd
355
h
C
Clerk/UI/Charts/PieChart.h
sergeylenkov/Clerk
b220864e89559207c5eeea113668891236fcbfb9
[ "MIT" ]
14
2016-11-01T15:48:02.000Z
2020-07-15T13:00:27.000Z
Clerk/UI/Charts/PieChart.h
sergeylenkov/Clerk
b220864e89559207c5eeea113668891236fcbfb9
[ "MIT" ]
29
2017-11-16T04:15:33.000Z
2021-12-22T07:15:42.000Z
Clerk/UI/Charts/PieChart.h
sergeylenkov/Clerk
b220864e89559207c5eeea113668891236fcbfb9
[ "MIT" ]
2
2018-08-15T15:25:11.000Z
2019-01-28T12:49:50.000Z
#include <wx/wx.h> #include <vector> #include <algorithm> #include <map> #include <numeric> using namespace std; class PieChart : public wxPanel { public: PieChart(wxWindow *parent, wxWindowID id); ~PieChart(); void SetValues(map<wxString, float> values); void Draw(); private: map<wxString, float> _values; void OnPaint(wxPaintEvent& event); };
17.75
45
0.723944
[ "vector" ]
9ccc93bdf5bee852e4b4774f48ba32c2179cce63
4,347
h
C
cinn/frontend/decomposer_registry.h
SunNy820828449/CINN
6384f730867132508c2c60f5ff2aae12959143d7
[ "Apache-2.0" ]
57
2020-10-09T12:18:48.000Z
2022-03-12T07:58:55.000Z
cinn/frontend/decomposer_registry.h
SunNy820828449/CINN
6384f730867132508c2c60f5ff2aae12959143d7
[ "Apache-2.0" ]
380
2020-10-09T08:28:08.000Z
2022-03-31T09:17:36.000Z
cinn/frontend/decomposer_registry.h
SunNy820828449/CINN
6384f730867132508c2c60f5ff2aae12959143d7
[ "Apache-2.0" ]
34
2020-10-09T08:46:45.000Z
2022-03-05T09:29:54.000Z
// Copyright (c) 2021 CINN 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. #pragma once #include <functional> #include <string> #include <unordered_map> #include "cinn/common/target.h" #include "cinn/frontend/cinn_builder.h" #include "cinn/frontend/syntax.h" namespace cinn { namespace frontend { class Decomposer; class DecomposerContext { public: explicit DecomposerContext(CinnBuilder* builder, absl::flat_hash_map<std::string, Variable>* var_map) : builder_(builder), var_map_(var_map) {} CinnBuilder* builder() const { return builder_; }; // Map the new var to the original var. void MapOutToOrigin(const Variable& new_var, const Variable& ori_var) const { if (new_var->shape != ori_var->shape) { LOG(FATAL) << "The output shape shoule be equal to the original. But received : " << new_var->id << ".shape=[" << utils::Join(new_var->shape, ", ") << "] and the original var " << ori_var->id << ".shape=[" << utils::Join(ori_var->shape, ", ") << "]."; } (*var_map_)[new_var->id] = ori_var; } private: CinnBuilder* builder_{nullptr}; absl::flat_hash_map<std::string, Variable>* var_map_{nullptr}; }; class InstrDecomposerRegistry : public Registry<Decomposer> { public: static InstrDecomposerRegistry* Global() { static InstrDecomposerRegistry x; return &x; } inline const Decomposer* Get(const std::string& op_name, const common::Target& target) { const Decomposer* decomposer = Find(op_name, target); CHECK(decomposer) << "Decomposer for [" << op_name << ", " << target << "] is not registered"; return decomposer; } inline const Decomposer* Find(const std::string& name, const common::Target& target) { return Registry<Decomposer>::Find(name + "_" + target.arch_str()); } private: InstrDecomposerRegistry() = default; CINN_DISALLOW_COPY_AND_ASSIGN(InstrDecomposerRegistry); }; class Decomposer { public: using DecomposerKernel = std::function<void(const Instruction& instr, const DecomposerContext&)>; Decomposer& SetBody(const DecomposerKernel& kernel) { kernel_ = kernel; return *this; } void Run(const Instruction& instr, const DecomposerContext& context) const { kernel_(instr, context); } std::string name; private: DecomposerKernel kernel_; }; #define CINN_DECOMPOSER_REGISTER_CORE(name, target, kernel) \ ::cinn::frontend::InstrDecomposerRegistry::Global() \ ->__REGISTER__(std::string(#name) + "_" + target.arch_str()) \ .SetBody(kernel) #define CINN_DECOMPOSER_REGISTER_ALL(name, kernel) \ static std::vector<::cinn::common::Target> all_targets = {::cinn::common::DefaultHostTarget(), \ ::cinn::common::DefaultNVGPUTarget()}; \ for (auto& target : all_targets) { \ ::cinn::frontend::InstrDecomposerRegistry::Global() \ ->__REGISTER__(std::string(#name) + "_" + target.arch_str()) \ .SetBody(kernel); \ } /** * @def CINN_DECOMPOSER_REGISTER * \brief Register a decomposer kernel * * Register a decomposer on the specific target: * \code * CINN_DECOMPOSER_REGISTER(name, target, kernel); * \endcode * * Register a decomposer on all default targets: * \code * CINN_DECOMPOSER_REGISTER(name, kernel); * \endcode */ #define GET_MACRO(_0, _1, _2, FUNC, ...) FUNC #define CINN_DECOMPOSER_REGISTER(...) \ GET_MACRO(__VA_ARGS__, CINN_DECOMPOSER_REGISTER_CORE, CINN_DECOMPOSER_REGISTER_ALL)(__VA_ARGS__) } // namespace frontend } // namespace cinn
34.776
116
0.645963
[ "shape", "vector" ]
9cd2bc06e27e88d2ed489de5a4503a6d1dacd9f2
28,303
c
C
lib/EMBOSS-6.6.0/nucleus/embpdb.c
alegione/CodonShuffle
bd6674b2eb21ee144a39d6d1e9b7264aba887240
[ "MIT" ]
5
2016-11-11T21:57:49.000Z
2021-07-27T14:13:31.000Z
lib/EMBOSS-6.6.0/nucleus/embpdb.c
frantallukas10/CodonShuffle
4c408e1a8617f2a52dcb0329bba9617e1be17313
[ "MIT" ]
4
2016-05-15T07:56:25.000Z
2020-05-20T05:21:48.000Z
lib/EMBOSS-6.6.0/nucleus/embpdb.c
frantallukas10/CodonShuffle
4c408e1a8617f2a52dcb0329bba9617e1be17313
[ "MIT" ]
10
2015-08-19T20:37:46.000Z
2020-04-07T06:49:23.000Z
/* @source embpdb ************************************************************* ** ** Algorithms for handling protein structural data. ** For use with the Atom, Chain and Pdb objects defined in ajpdb.h ** Also for use with Hetent, Het, Vdwres, Vdwall, Cmap and Pdbtosp objects ** (also in ajpdb.h). ** ** @author CopyrightCopyright (c) 2004 Jon Ison ** @version $Revision: 1.24 $ ** @modified $Date: 2012/07/14 14:52:40 $ by $Author: rice $ ** @@ ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library 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 ** Lesser General Public License for more details. ** ** You should have received a copy of the GNU Lesser General Public ** License along with this library; if not, write to the Free Software ** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, ** MA 02110-1301, USA. ** ****************************************************************************/ #include "ajlib.h" #include "embpdb.h" #include "ajpdb.h" #include "ajdomain.h" #include "ajlist.h" #include <math.h> /* ======================================================================= */ /* ============================ private data ============================= */ /* ======================================================================= */ /* ======================================================================= */ /* ================= Prototypes for private functions ==================== */ /* ======================================================================= */ /* ======================================================================= */ /* ========================== private functions ========================== */ /* ======================================================================= */ /* ======================================================================= */ /* =========================== constructors ============================== */ /* ======================================================================= */ /* @section Constructors **************************************************** ** ** All constructors return a pointer to a new instance. It is the ** responsibility of the user to first destroy any previous instance. The ** target pointer does not need to be initialised to NULL, but it is good ** programming practice to do so anyway. ** ****************************************************************************/ /* ======================================================================= */ /* =========================== destructors =============================== */ /* ======================================================================= */ /* @section Structure Destructors ******************************************* ** ** All destructor functions receive the address of the instance to be ** deleted. The original pointer is set to NULL so is ready for re-use. ** ****************************************************************************/ /* ======================================================================= */ /* ============================ Assignments ============================== */ /* ======================================================================= */ /* @section Assignments ***************************************************** ** ** These functions overwrite the instance provided as the first argument ** A NULL value is always acceptable so these functions are often used to ** create a new instance by assignment. ** ****************************************************************************/ /* ======================================================================= */ /* ============================= Modifiers =============================== */ /* ======================================================================= */ /* @section Modifiers ******************************************************* ** ** These functions use the contents of an instance and update them. ** ****************************************************************************/ /* ======================================================================= */ /* ========================== Operators ===================================*/ /* ======================================================================= */ /* @section Operators ******************************************************* ** ** These functions use the contents of an instance but do not make any ** changes. ** ****************************************************************************/ /* @func embPdbidToSp ********************************************************* ** ** Read a pdb identifier code and writes the equivalent swissprot identifier ** code. Relies on list of Pdbtosp objects sorted by PDB code, which is ** usually obtained by a call to ajPdbtospReadAllNew. ** ** @param [r] pdb [const AjPStr] Pdb identifier code ** @param [w] spr [AjPStr*] Swissprot identifier code ** @param [r] list [const AjPList] Sorted list of Pdbtosp objects ** ** @return [AjBool] True if a swissprot identifier code was found ** for the Pdb code. ** ** @release 2.9.0 ** @@ ****************************************************************************/ AjBool embPdbidToSp(const AjPStr pdb, AjPStr *spr, const AjPList list) { AjPPdbtosp *arr = NULL; /* Array derived from list */ ajint dim = 0; /* Size of array */ ajint idx = 0; /* Index into array for the Pdb code */ if(!pdb || !list) { ajWarn("Bad args passed to embPdbidToSp"); return ajFalse; } dim = (ajuint) ajListToarray(list, (void ***) &(arr)); if(!dim) { ajWarn("Empty list passed to embPdbidToSp"); return ajFalse; } if( (idx = ajPdbtospArrFindPdbid(arr, dim, pdb))==-1) return ajFalse; ajStrAssignS(spr, arr[idx]->Spr[0]); return ajTrue; } /* @func embPdbidToAcc ******************************************************** ** ** Read a pdb identifier code and writes the equivalent accession number. ** Relies on list of Pdbtosp objects sorted by PDB code, which is usually ** obtained by a call to ajPdbtospReadAllNew. ** ** @param [r] pdb [const AjPStr] Pdb identifier code ** @param [w] acc [AjPStr*] Accession number ** @param [r] list [const AjPList] Sorted list of Pdbtosp objects ** ** @return [AjBool] True if a swissprot identifier code was found for the ** Pdb code. ** ** @release 2.9.0 ** @@ ****************************************************************************/ AjBool embPdbidToAcc(const AjPStr pdb, AjPStr *acc, const AjPList list) { AjPPdbtosp *arr = NULL; /* Array derived from list */ AjPPdbtosp *arrfree = NULL; ajint dim = 0; /* Size of array */ ajint idx = 0; /* Index into array for the Pdb code */ if(!pdb || !list) { ajWarn("Bad args passed to embPdbidToAcc"); return ajFalse; } dim = (ajuint) ajListToarray(list, (void ***) &(arr)); if(!dim) { ajWarn("Empty list passed to embPdbidToAcc"); return ajFalse; } if( (idx = ajPdbtospArrFindPdbid(arr, dim, pdb))==-1) { arrfree = (AjPPdbtosp*) arr; AJFREE(arrfree); return ajFalse; } ajStrAssignS(acc, arr[idx]->Acc[0]); arrfree = (AjPPdbtosp*) arr; AJFREE(arrfree); return ajTrue; } /* @func embPdbidToScop ****************************************************** ** ** Writes a list of scop identifier codes for the domains that a Pdb object ** contains. The domain data is taken from a list of scop objects. ** ** @param [r] pdb [const AjPPdb] Pointer to pdb object ** @param [r] list_allscop [const AjPList] Pointer to SCOP list of SCOP ** classification objects ** @param [w] list_pdbscopids [AjPList*] Pointer to list of scop domain ids ** in the current pdb object ** ** @return [AjBool] ajTrue on success ** ** @release 2.9.0 ** @@ ****************************************************************************/ AjBool embPdbidToScop(const AjPPdb pdb, const AjPList list_allscop, AjPList *list_pdbscopids) { AjIList iter = NULL; /* List iterator for SCOP classification list */ AjPScop ptr = NULL; AjPStr tmpPdbId = NULL; AjPStr tmpDomId = NULL; ajint found = 0; iter=ajListIterNewread(list_allscop); while((ptr=(AjPScop)ajListIterGet(iter))) { ajStrAssignS(&tmpPdbId, ptr->Pdb); ajStrFmtLower(&tmpPdbId); if(ajStrMatchS(pdb->Pdb, tmpPdbId)) { ajStrAssignS(&tmpDomId, ptr->Entry); ajStrFmtLower(&tmpDomId); ajListPushAppend(*list_pdbscopids, tmpDomId); tmpDomId = NULL; found = 1; } } ajListIterDel(&iter); ajStrDel(&tmpPdbId); ajStrDel(&tmpDomId); if(found==1) return ajTrue; return ajFalse; } /* @func embAtomInContact ***************************************************** ** ** Determines whether two atoms are in physical contact ** ** @param [r] atm1 [const AjPAtom] Atom 1 object ** @param [r] atm2 [const AjPAtom] Atom 1 object ** @param [r] thresh [float] Threshold contact distance ** @param [r] vdw [const AjPVdwall] Vdwall object ** ** Contact between two atoms is defined as when the van der Waals surface of ** the first atom comes within the threshold contact distance (thresh) of ** the van der Waals surface of the second atom. ** ** @return [AjBool] True if the two atoms form contact ** ** @release 2.9.0 ** @@ ** ****************************************************************************/ AjBool embAtomInContact(const AjPAtom atm1, const AjPAtom atm2, float thresh, const AjPVdwall vdw) { float val = 0.0; float val1 = 0.0; /* Check args */ if(!atm1 || !atm2 || !vdw) { ajWarn("Bad args passed to embAtomInContact"); return ajFalse; } val=((atm1->X - atm2->X) * (atm1->X - atm2->X)) + ((atm1->Y - atm2->Y) * (atm1->Y - atm2->Y)) + ((atm1->Z - atm2->Z) * (atm1->Z - atm2->Z)); /* This calculation uses square root if((sqrt(val) - embVdwRad(atm1, vdw) - embVdwRad(atm2, vdw)) <= thresh) return ajTrue; */ /* Same calculation avoiding square root */ val1 = embVdwRad(atm1, vdw) + embVdwRad(atm2, vdw) + thresh; if(val <= (val1*val1)) return ajTrue; return ajFalse; } /* @func embAtomDistance ****************************************************** ** ** Returns the distance (Angstroms) between two atoms. ** ** @param [r] atm1 [const AjPAtom] Atom 1 object ** @param [r] atm2 [const AjPAtom] Atom 1 object ** @param [r] vdw [const AjPVdwall] Vdwall object ** ** Returns the distance (Angstroms) between the van der Waals surface of two ** atoms. ** ** @return [float] Distance (Angstroms) between two atoms. ** ** @release 2.9.0 ** @@ ** ****************************************************************************/ float embAtomDistance(const AjPAtom atm1, const AjPAtom atm2, const AjPVdwall vdw) { float val = 0.0; float val1 = 0.0; val=((atm1->X - atm2->X) * (atm1->X - atm2->X)) + ((atm1->Y - atm2->Y) * (atm1->Y - atm2->Y)) + ((atm1->Z - atm2->Z) * (atm1->Z - atm2->Z)); /* This calculation uses square root */ val1= (float) (sqrt(val) - embVdwRad(atm1, vdw) - embVdwRad(atm2, vdw)); return val1; } /* ======================================================================= */ /* ============================== Casts ===================================*/ /* ======================================================================= */ /* @section Casts *********************************************************** ** ** These functions examine the contents of an instance and return some ** derived information. Some of them provide access to the internal ** components of an instance. They are provided for programming convenience ** but should be used with caution. ** ****************************************************************************/ /* ======================================================================= */ /* =========================== Reporters ==================================*/ /* ======================================================================= */ /* @section Reporters ******************************************************* ** ** These functions return the contents of an instance but do not make any ** changes. ** ****************************************************************************/ /* @func embVdwRad ************************************************************ ** ** Returns the van der Waals radius of an atom. Returns 1.2 as default. ** ** @param [r] atm [const AjPAtom] Atom object ** @param [r] vdw [const AjPVdwall] Vdwall object ** ** @return [float] van der Waals radius of the atom ** ** @release 2.9.0 ** @@ ** ****************************************************************************/ float embVdwRad(const AjPAtom atm, const AjPVdwall vdw) { ajuint x = 0U; ajuint y = 0U; for(x = 0U; x < vdw->N; x++) for(y = 0; y < vdw->Res[x]->N; y++) if(ajStrMatchS(atm->Atm, vdw->Res[x]->Atm[y])) return vdw->Res[x]->Rad[y]; return (float) 1.2; } /* @func embPdbToIdx ********************************************************** ** ** Reads a Pdb object and writes an integer which gives the index into the ** protein sequence for a residue with a specified pdb residue number and a ** specified chain number. ** ** @param [w] idx [ajint*] Residue number (index into sequence) ** @param [r] pdb [const AjPPdb] Pdb object ** @param [r] res [const AjPStr] Residue number (PDB numbering) ** @param [r] chn [ajuint] Chain number ** ** @return [AjBool] True on succcess (res was found in pdb object) ** ** @release 2.9.0 ** @@ ****************************************************************************/ AjBool embPdbToIdx(ajint *idx, const AjPPdb pdb, const AjPStr res, ajuint chn) { AjIList iter = NULL; AjPResidue residue = NULL; if(!pdb || !(res) || !(idx)) { ajWarn("Bad arg's passed to embPdbToIdx"); return ajFalse; } if((chn > pdb->Nchn) || (!pdb->Chains) || (chn<1)) { ajWarn("Bad arg's passed to embPdbToIdx"); return ajFalse; } /* Initialise the iterator */ iter=ajListIterNewread(pdb->Chains[chn-1]->Residues); /* Iterate through the list of residues */ while((residue = (AjPResidue)ajListIterGet(iter))) { if(residue->Chn!=chn) continue; /* ** Hard-coded to work on model 1 ** Continue / break if a non-protein residue is found or model no. !=1 */ if(residue->Mod!=1) break; /* if(residue->Type!='P') continue; */ /* If we have found the residue */ if(ajStrMatchS(res, residue->Pdb)) { ajListIterDel(&iter); *idx = residue->Idx; return ajTrue; } } ajWarn("Residue number not found in embPdbToIdx"); ajListIterDel(&iter); return ajFalse; } /* ======================================================================= */ /* ========================== Input & Output ============================= */ /* ======================================================================= */ /* @section Input & output ************************************************** ** ** These functions are used for formatted input and output to file. ** ****************************************************************************/ /* ======================================================================= */ /* ======================== Miscellaneous =================================*/ /* ======================================================================= */ /* @section Miscellaneous *************************************************** ** ** These functions may have diverse functions that do not fit into the other ** categories. ** ****************************************************************************/ /* @func embPdbListHeterogens ************************************************* ** ** Function to create a list of arrays of Atom objects for ligands in the ** current Pdb object (a single array for each ligand). An array of int's ** giving the number of Atom objects in each array, is also written. The ** number of ligands is also written. ** ** @param [r] pdb [const AjPPdb] Pointer to pdb object ** @param [w] list_heterogens [AjPList*] Pointer to list of heterogen Atom ** arrays ** @param [w] siz_heterogens [AjPInt*] Pointer to integer array of sizes ** (number of Atom objects in each ** array). ** @param [w] nhet [ajint*] Number of arrays in the list that ** was written. ** @param [u] logfile [AjPFile] Log file for error messages ** ** @return [AjBool] ajTrue on success ** ** @release 2.9.0 ** @@ ****************************************************************************/ AjBool embPdbListHeterogens(const AjPPdb pdb, AjPList *list_heterogens, AjPInt *siz_heterogens, ajint *nhet, AjPFile logfile) { /* ** NOTE: EVERYTHING IN THE CLEAN PDB FILES IS CURRENTLY CHAIN ** ASSOCIATED! THIS WILL BE CHANGED IN FUTURE */ AjIList iter = NULL; /* Iterator for atoms in current pdb object */ AjPAtom hetat = NULL; /* Pointer to current Atom object */ ajuint i = 0U; /* Counter for chains */ ajint prev_gpn = -10000; /* Group number of atom object from previous iteration */ AjPList GrpAtmList = NULL; /* List to hold atoms from the current group */ AjPAtom *AtmArray = NULL; /* Array of atom objects */ ajint n=0; /* number of elements in AtmArray */ ajint grp_count = 0; /* No. of groups */ ajint arr_count = 0; /* Index for siz_heterogens */ /* Check args */ if((pdb==NULL)||(list_heterogens==NULL)||(siz_heterogens==NULL)) { ajWarn("Bad args passed to embPdbListHeterogens\n"); return ajFalse; } if((!(*list_heterogens))||(!(*siz_heterogens))) { ajWarn("Bad args passed to embPdbListHeterogens\n"); return ajFalse; } if(pdb->Ngp>0) ajFmtPrintF(logfile, "\tNGP:%d\n", pdb->Ngp); if(pdb->Nchn>0) { for(i = 0U; i < pdb->Nchn; i++) { prev_gpn=-100000; /* Reset prev_gpn for each chain */ /* initialise iterator for pdb->Chains[i]->Atoms */ iter=ajListIterNewread(pdb->Chains[i]->Atoms); /* Iterate through list of Atom objects */ while((hetat=(AjPAtom)ajListIterGet(iter))) { /* check for type */ if(hetat->Type != 'H') continue; /* TEST FOR A NEW GROUP */ if(prev_gpn != hetat->Gpn) { grp_count++; if(GrpAtmList) { n=(ajuint) (ajListToarray(GrpAtmList, (void ***) &AtmArray)); ajListPushAppend(*list_heterogens, AtmArray); /* ** So that ajListToarray doesn't try and free the ** non-NULL pointer */ AtmArray=NULL; ajIntPut(siz_heterogens, arr_count, n); (*nhet)++; ajListFree(&GrpAtmList); GrpAtmList=NULL; arr_count++; } GrpAtmList=ajListNew(); prev_gpn=hetat->Gpn; } /* End of new group loop */ ajListPushAppend(GrpAtmList, (AjPAtom) hetat); } /* End of list iteration loop */ /* Free list iterator */ ajListIterDel(&iter); } /* End of chain for loop */ if(GrpAtmList) { n=(ajuint) (ajListToarray(GrpAtmList, (void ***) &AtmArray)); ajListPushAppend(*list_heterogens, AtmArray); /* ** So that ajListToarray doesn't try and free the non-NULL ** pointer */ AtmArray=NULL; ajIntPut(siz_heterogens, arr_count, n); (*nhet)++; ajListFree(&GrpAtmList); GrpAtmList=NULL; } GrpAtmList = NULL; prev_gpn = -10000; } /* End of chain loop */ return ajTrue; } /* @func embPdbResidueIndexI ************************************************** ** ** Reads a Pdb object and writes an integer array which gives the index into ** the protein sequence for structured residues (residues for which electron ** density was determined) for a given chain. The array length is of course ** equal to the number of structured residues. ** ** @param [r] pdb [const AjPPdb] Pdb object ** @param [r] chn [ajuint] Chain number ** @param [w] idx [AjPInt*] Index array ** ** @return [AjBool] True on succcess ** ** @release 3.0.0 ** @@ ****************************************************************************/ AjBool embPdbResidueIndexI(const AjPPdb pdb, ajuint chn, AjPInt *idx) { AjIList iter = NULL; AjPResidue res = NULL; /* ajint this_rn = 0; ajint last_rn = -1000; */ ajint resn = 0; if(!pdb || !(*idx)) { ajWarn("Bad arg's passed to embPdbResidueIndexI"); return ajFalse; } if((chn > pdb->Nchn) || (!pdb->Chains)) { ajWarn("Bad arg's passed to embPdbResidueIndexI"); return ajFalse; } /* Initialise the iterator */ iter=ajListIterNewread(pdb->Chains[chn-1]->Residues); /* Iterate through the list of residues */ while((res=(AjPResidue)ajListIterGet(iter))) { if(res->Chn!=chn) continue; /* Hard-coded to work on model 1 */ /* Continue / break if a non-protein residue is found or model no. !=1 */ if(res->Mod!=1) break; /* if(res->Type!='P') continue; */ /* If we are onto a new residue */ /* this_rn=res->Idx; if(this_rn!=last_rn) { ajIntPut(&(*idx), resn++, res->Idx); last_rn=this_rn; }*/ ajIntPut(&(*idx), resn++, res->Idx); } if(resn==0) { ajWarn("Chain not found in embPdbResidueIndexI"); ajListIterDel(&iter); return ajFalse; } ajListIterDel(&iter); return ajTrue; } /* @func embPdbResidueIndexC ************************************************** ** ** Reads a Pdb object and writes an integer array which gives the index into ** the protein sequence for structured residues (residues for which electron ** density was determined) for a given chain. The array length is of course ** equal to the number of structured residues. ** ** @param [r] pdb [const AjPPdb] Pdb object ** @param [r] chn [char] Chain identifier ** @param [w] idx [AjPInt*] Index array ** ** @return [AjBool] True on succcess ** ** @release 3.0.0 ** @@ ****************************************************************************/ AjBool embPdbResidueIndexC(const AjPPdb pdb, char chn, AjPInt *idx) { ajuint chnn = 0U; if(!ajPdbChnidToNum(chn, pdb, &chnn)) { ajWarn("Chain not found in embPdbResidueIndexC"); return ajFalse; } if(!embPdbResidueIndexI(pdb, chnn, idx)) return ajFalse; return ajTrue; } /* @func embPdbResidueIndexICA ************************************************ ** ** Reads a Pdb object and writes an integer array which gives the index into ** the protein sequence for structured residues (residues for which electron ** density was determined) for a given chain, EXCLUDING those residues for ** which CA atoms are missing. The array length is of course equal to the ** number of structured residues. ** ** @param [r] pdb [const AjPPdb] Pdb object ** @param [r] chn [ajuint] Chain number ** @param [w] idx [AjPUint*] Index array ** @param [w] nres [ajint*] Array length ** ** @return [AjBool] True on succcess ** ** @release 3.0.0 ** @@ ****************************************************************************/ AjBool embPdbResidueIndexICA(const AjPPdb pdb, ajuint chn, AjPUint *idx, ajint *nres) { AjIList iter = NULL; AjPAtom atm = NULL; ajint this_rn = 0; ajint last_rn = -1000; ajint resn = 0; /* Sequential count of residues */ if(!pdb || !(*idx)) { ajWarn("Bad arg's passed to embPdbResidueIndexICA"); return ajFalse; } if((chn > pdb->Nchn) || (!pdb->Chains)) { ajWarn("Bad arg's passed to embPdbResidueIndexICA"); return ajFalse; } /* Initialise the iterator */ iter=ajListIterNewread(pdb->Chains[chn-1]->Atoms); /* Iterate through the list of atoms */ while((atm=(AjPAtom)ajListIterGet(iter))) { if(atm->Chn!=chn) continue; /* ** Hard-coded to work on model 1 ** Continue / break if a non-protein atom is found or model no. !=1 */ if(atm->Mod!=1) break; if(atm->Type!='P') continue; /* If we are onto a new residue */ this_rn=atm->Idx; if(this_rn!=last_rn && ajStrMatchC(atm->Atm, "CA")) { ajUintPut(&(*idx), resn++, atm->Idx); last_rn=this_rn; } } if(resn==0) { ajWarn("Chain not found in embPdbResidueIndexICA"); ajListIterDel(&iter); return ajFalse; } *nres=resn; ajListIterDel(&iter); return ajTrue; } /* @func embPdbResidueIndexCCA ************************************************ ** ** Reads a Pdb object and writes an integer array which gives the index into ** the protein sequence for structured residues (residues for which electron ** density was determined) for a given chain, EXCLUDING those residues for ** which CA atoms are missing. The array length is of course equal to the ** number of structured residues. ** ** @param [r] pdb [const AjPPdb] Pdb object ** @param [r] chn [char] Chain identifier ** @param [w] idx [AjPUint*] Index array ** @param [w] nres [ajint*] Array length ** ** @return [AjBool] True on succcess ** ** @release 3.0.0 ** @@ ****************************************************************************/ AjBool embPdbResidueIndexCCA(const AjPPdb pdb, char chn, AjPUint *idx, ajint *nres) { ajuint chnn = 0U; if(!ajPdbChnidToNum(chn, pdb, &chnn)) { ajWarn("Chain not found in embPdbResidueIndexCCA"); return ajFalse; } if(!embPdbResidueIndexICA(pdb, chnn, idx, nres)) return ajFalse; return ajTrue; } /* @func embStrideToThree ***************************************************** ** ** Reads a string that contains an 8-state STRIDE secondary structure ** assignment and writes a string with the corresponding 3-state assignment. ** The 8 states used in STRIDE are 'H' (alpha helix), 'G' (3-10 helix), ** 'I' (Pi-helix), 'E' (extended conformation), 'B' or 'b' (isolated bridge), ** 'T' (turn) or 'C' (coil, i.e. none of the above). The 3 states used ** are 'H' (STRIDE 'H', 'G' or 'I'), 'E' (STRIDE 'E', 'B' or 'b') and 'C' ** (STRIDE 'T' or 'C'). The string is allocated if necessary. ** ** @param [w] to [AjPStr*] String to write ** @param [r] from [const AjPStr] String to read ** ** @return [AjBool] True on succcess ** ** @release 2.9.0 ** @@ ****************************************************************************/ AjBool embStrideToThree(AjPStr *to, const AjPStr from) { if(!from) { ajWarn("Bad args passed to embStrideToThree"); return ajFalse; } else ajStrAssignS(to, from); ajStrExchangeKK(to, 'G', 'H'); ajStrExchangeKK(to, 'I', 'H'); ajStrExchangeKK(to, 'B', 'E'); ajStrExchangeKK(to, 'b', 'E'); ajStrExchangeKK(to, 'T', 'C'); return ajTrue; }
27.451988
85
0.486592
[ "object", "model" ]
9cd5927e9e3a907e4102bec7c013b9b42ac157b1
7,440
h
C
src/tprdp/include/stream.h
atzitiondev/thinpi
1d5c9edac37a10326721b131945d01a83d00c648
[ "Apache-2.0" ]
null
null
null
src/tprdp/include/stream.h
atzitiondev/thinpi
1d5c9edac37a10326721b131945d01a83d00c648
[ "Apache-2.0" ]
null
null
null
src/tprdp/include/stream.h
atzitiondev/thinpi
1d5c9edac37a10326721b131945d01a83d00c648
[ "Apache-2.0" ]
1
2022-01-22T09:26:04.000Z
2022-01-22T09:26:04.000Z
#ifndef _STREAM_H #define _STREAM_H /* Parser state */ typedef struct stream { unsigned char *p; unsigned char *end; unsigned char *data; unsigned int size; /* Offsets of various headers */ unsigned char *iso_hdr; unsigned char *mcs_hdr; unsigned char *sec_hdr; unsigned char *rdp_hdr; unsigned char *channel_hdr; } *STREAM; /* Return a newly allocated STREAM object of the specified size */ STREAM s_alloc(unsigned int size); /* Wrap an existing buffer in a STREAM object, transferring ownership */ STREAM s_inherit(unsigned char *data, unsigned int size); /* Resize an existing STREAM object, keeping all data and offsets intact */ void s_realloc(STREAM s, unsigned int size); /* Free STREAM object and its associated buffer */ void s_free(STREAM s); /* Reset all internal offsets, but keep the allocated size */ void s_reset(STREAM s); void out_utf16s(STREAM s, const char *string); void out_utf16s_padded(STREAM s, const char *string, size_t width, unsigned char pad); void out_utf16s_no_eos(STREAM s, const char *string); size_t in_ansi_string(STREAM s, char *string, size_t len); /* Store current offset as header h and skip n bytes */ #define s_push_layer(s,h,n) { (s)->h = (s)->p; (s)->p += n; } /* Set header h as current offset */ #define s_pop_layer(s,h) (s)->p = (s)->h; /* Mark current offset as end of readable data */ #define s_mark_end(s) (s)->end = (s)->p; /* Return current read offset in the STREAM */ #define s_tell(s) (size_t)((s)->p - (s)->data) /* Set current read offset in the STREAM */ #define s_seek(s,o) (s)->p = (s)->data; s_assert_r(s,o); (s)->p += o; /* Returns number of bytes that can still be read from STREAM */ #define s_remaining(s) (size_t)((s)->end - (s)->p) /* True if at least n bytes can still be read */ #define s_check_rem(s,n) (((s)->p <= (s)->end) && ((size_t)n <= s_remaining(s))) /* True if all data has been read */ #define s_check_end(s) ((s)->p == (s)->end) /* Return the total number of bytes that can be read */ #define s_length(s) ((s)->end - (s)->data) /* Return the number of bytes that can still be written */ #define s_left(s) ((s)->size - (size_t)((s)->p - (s)->data)) /* Verify that there is enough data/space before accessing a STREAM */ #define s_assert_r(s,n) { if (!s_check_rem(s, n)) rdp_protocol_error( "unexpected stream overrun", s); } #define s_assert_w(s,n) { if (s_left(s) < (size_t)n) { logger(Core, Error, "%s:%d: %s(), %s", __FILE__, __LINE__, __func__, "unexpected stream overrun"); exit(0); } } /* Read/write an unsigned integer in little-endian order */ #if defined(L_ENDIAN) && !defined(NEED_ALIGN) #define in_uint16_le(s,v) { s_assert_r(s, 2); v = *(uint16 *)((s)->p); (s)->p += 2; } #define in_uint32_le(s,v) { s_assert_r(s, 4); v = *(uint32 *)((s)->p); (s)->p += 4; } #define in_uint64_le(s,v) { s_assert_r(s, 8); v = *(uint64 *)((s)->p); (s)->p += 8; } #define out_uint16_le(s,v) { s_assert_w(s, 2); *(uint16 *)((s)->p) = v; (s)->p += 2; } #define out_uint32_le(s,v) { s_assert_w(s, 4); *(uint32 *)((s)->p) = v; (s)->p += 4; } #define out_uint64_le(s,v) { s_assert_w(s, 8); *(uint64 *)((s)->p) = v; (s)->p += 8; } #else #define in_uint16_le(s,v) { s_assert_r(s, 2); v = *((s)->p++); v += *((s)->p++) << 8; } #define in_uint32_le(s,v) { s_assert_r(s, 4); in_uint16_le(s,v) \ v += *((s)->p++) << 16; v += *((s)->p++) << 24; } #define in_uint64_le(s,v) { s_assert_r(s, 8); in_uint32_le(s,v) \ v += *((s)->p++) << 32; v += *((s)->p++) << 40; \ v += *((s)->p++) << 48; v += *((s)->p++) << 56; } #define out_uint16_le(s,v) { s_assert_w(s, 2); *((s)->p++) = (v) & 0xff; *((s)->p++) = ((v) >> 8) & 0xff; } #define out_uint32_le(s,v) { s_assert_w(s, 4); out_uint16_le(s, (v) & 0xffff); out_uint16_le(s, ((v) >> 16) & 0xffff); } #define out_uint64_le(s,v) { s_assert_w(s, 8); out_uint32_le(s, (v) & 0xffffffff); out_uint32_le(s, ((v) >> 32) & 0xffffffff); } #endif /* Read/write an unsigned integer in big-endian order */ #if defined(B_ENDIAN) && !defined(NEED_ALIGN) #define in_uint16_be(s,v) { s_assert_r(s, 2); v = *(uint16 *)((s)->p); (s)->p += 2; } #define in_uint32_be(s,v) { s_assert_r(s, 4); v = *(uint32 *)((s)->p); (s)->p += 4; } #define in_uint64_be(s,v) { s_assert_r(s, 8); v = *(uint64 *)((s)->p); (s)->p += 8; } #define out_uint16_be(s,v) { s_assert_w(s, 2); *(uint16 *)((s)->p) = v; (s)->p += 2; } #define out_uint32_be(s,v) { s_assert_w(s, 4); *(uint32 *)((s)->p) = v; (s)->p += 4; } #define out_uint64_be(s,v) { s_assert_w(s, 8); *(uint64 *)((s)->p) = v; (s)->p += 8; } #define B_ENDIAN_PREFERRED #define in_uint16(s,v) in_uint16_be(s,v) #define in_uint32(s,v) in_uint32_be(s,v) #define in_uint64(s,v) in_uint64_be(s,v) #define out_uint16(s,v) out_uint16_be(s,v) #define out_uint32(s,v) out_uint32_be(s,v) #define out_uint64(s,v) out_uint64_be(s,v) #else #define in_uint16_be(s,v) { s_assert_r(s, 2); v = *((s)->p++); next_be(s,v); } #define in_uint32_be(s,v) { s_assert_r(s, 4); in_uint16_be(s,v); next_be(s,v); next_be(s,v); } #define in_uint64_be(s,v) { s_assert_r(s, 8); in_uint32_be(s,v); next_be(s,v); next_be(s,v); next_be(s,v); next_be(s,v); } #define out_uint16_be(s,v) { s_assert_w(s, 2); *((s)->p++) = ((v) >> 8) & 0xff; *((s)->p++) = (v) & 0xff; } #define out_uint32_be(s,v) { s_assert_w(s, 4); out_uint16_be(s, ((v) >> 16) & 0xffff); out_uint16_be(s, (v) & 0xffff); } #define out_uint64_be(s,v) { s_assert_w(s, 8); out_uint32_be(s, ((v) >> 32) & 0xffffffff); out_uint32_be(s, (v) & 0xffffffff); } #endif #ifndef B_ENDIAN_PREFERRED #define in_uint16(s,v) in_uint16_le(s,v) #define in_uint32(s,v) in_uint32_le(s,v) #define in_uint64(s,v) in_uint64_le(s,v) #define out_uint16(s,v) out_uint16_le(s,v) #define out_uint32(s,v) out_uint32_le(s,v) #define out_uint64(s,v) out_uint64_le(s,v) #endif /* Read a single unsigned byte in v from STREAM s */ #define in_uint8(s,v) { s_assert_r(s, 1); v = *((s)->p++); } /* Return a pointer in v to manually read n bytes from STREAM s */ #define in_uint8p(s,v,n) { s_assert_r(s, n); v = (s)->p; (s)->p += n; } /* Copy n bytes from STREAM s in to array v */ #define in_uint8a(s,v,n) { s_assert_r(s, n); memcpy(v,(s)->p,n); (s)->p += n; } /* Skip reading n bytes in STREAM s */ #define in_uint8s(s,n) { s_assert_r(s, n); (s)->p += n; } /* Write a single unsigned byte from v to STREAM s */ #define out_uint8(s,v) { s_assert_w(s, 1); *((s)->p++) = v; } /* Return a pointer in v to manually fill in n bytes in STREAM s */ #define out_uint8p(s,v,n) { s_assert_w(s, n); v = (s)->p; (s)->p += n; } /* Copy n bytes from array v in to STREAM s */ #define out_uint8a(s,v,n) { s_assert_w(s, n); memcpy((s)->p,v,n); (s)->p += n; } /* Fill n bytes with 0:s in STREAM s */ #define out_uint8s(s,n) { s_assert_w(s, n); memset((s)->p,0,n); (s)->p += n; } /* Copy n bytes from STREAM s in to STREAM v */ #define in_uint8stream(s,v,n) { s_assert_r(s, n); out_uint8a((v), (s)->p, n); (s)->p += n; } /* Copy n bytes in to STREAM s from STREAM v */ #define out_uint8stream(s,v,n) in_uint8stream(v,s,n) /* Copy the entire STREAM v (ignoring offsets) in to STREAM s */ #define out_stream(s, v) out_uint8a(s, (v)->data, s_length((v))) /* Return a pointer in v to manually modify n bytes of STREAM s in place */ #define inout_uint8p(s,v,n) { s_assert_r(s, n); s_assert_w(s, n); v = (s)->p; (s)->p += n; } /* Read one more byte of an unsigned big-endian integer */ #define next_be(s,v) { s_assert_r(s, 1); v = ((v) << 8) + *((s)->p++); } #endif /* _STREAM_H */
48.311688
167
0.624866
[ "object" ]
9cdfc0d732f78d664ad05795ca05cf52a2924d77
1,347
h
C
2D/serial/trunk/fixedgrid.h
jlinford/fixedgrid
90147defe10a0d3c03a7c97207caea66928f4fbb
[ "BSD-3-Clause" ]
1
2019-07-26T19:59:01.000Z
2019-07-26T19:59:01.000Z
2D/serial/trunk/fixedgrid.h
jlinford/fixedgrid
90147defe10a0d3c03a7c97207caea66928f4fbb
[ "BSD-3-Clause" ]
null
null
null
2D/serial/trunk/fixedgrid.h
jlinford/fixedgrid
90147defe10a0d3c03a7c97207caea66928f4fbb
[ "BSD-3-Clause" ]
null
null
null
/* * fixedgrid.h * * Created by John Linford on 4/8/08. * Copyright 2008 Transatlantic Giraffe. All rights reserved. * */ #ifndef __FIXEDGRID_H__ #define __FIXEDGRID_H__ /************************************************** * Includes * **************************************************/ #include <stdint.h> #include "params.h" #include "timer.h" /************************************************** * Macros * **************************************************/ #define TRUE 1 #define FALSE 0 /************************************************** * Data types * **************************************************/ typedef short bool; /* Program state (global variables) */ typedef struct fixedgrid { /* Concentration field */ real_t conc[NSPEC][NROWS][NCOLS]; /* Wind vector field */ real_t wind_u[NROWS][NCOLS]; real_t wind_v[NROWS][NCOLS]; /* Diffusion tensor field */ real_t diff[NROWS][NCOLS]; /* Time (seconds) */ real_t time; real_t tstart; real_t tend; real_t dt; /* Parallelization */ /* This is always == 1 for serial code */ uint32_t nprocs; /* Metrics */ metrics_t metrics; } fixedgrid_t; #endif
21.046875
62
0.420935
[ "vector" ]
9ce31b17cf89625bf2084d3a7076f0b7074262f1
1,304
h
C
MeshModelingToolCP_Solution/Codes/include/igl/moments.h
PacosLelouch/MeshModelingToolCP
22965f7d0bc2dd14cfa372c023b041a0bbf152ed
[ "BSD-2-Clause" ]
null
null
null
MeshModelingToolCP_Solution/Codes/include/igl/moments.h
PacosLelouch/MeshModelingToolCP
22965f7d0bc2dd14cfa372c023b041a0bbf152ed
[ "BSD-2-Clause" ]
null
null
null
MeshModelingToolCP_Solution/Codes/include/igl/moments.h
PacosLelouch/MeshModelingToolCP
22965f7d0bc2dd14cfa372c023b041a0bbf152ed
[ "BSD-2-Clause" ]
null
null
null
// This file is part of libigl, a simple c++ geometry processing library. // // Copyright (C) 2022 Alec Jacobson <alecjacobson@gmail.com> // // This Source Code Form is subject to the terms of the Mozilla Public License // v. 2.0. If a copy of the MPL was not distributed with this file, You can // obtain one at http://mozilla.org/MPL/2.0/. #ifndef IGL_MOMENTS_H #define IGL_MOMENTS_H #include "igl_inline.h" #include <Eigen/Core> namespace igl { // Computes the moments of mass for a solid object bound by a triangle mesh. // // Inputs: // V #V by dim list of rest domain positions // F #F by 3 list of triangle indices into V // Outputs: // m0 zeroth moment of mass, total signed volume of solid. // m1 first moment of mass, center of mass times total mass // m2 second moment of mass, moment of inertia with center of mass as reference point template < typename DerivedV, typename DerivedF, typename Derivedm0, typename Derivedm1, typename Derivedm2> IGL_INLINE void moments( const Eigen::MatrixBase<DerivedV>& V, const Eigen::MatrixBase<DerivedF>& F, Derivedm0 & m0, Eigen::PlainObjectBase<Derivedm1>& m1, Eigen::PlainObjectBase<Derivedm2>& m2); } #ifndef IGL_STATIC_LIBRARY # include "moments.cpp" #endif #endif
31.804878
90
0.701687
[ "mesh", "geometry", "object", "solid" ]
9ce8ae6e0e385d86de82689db7432131901f31bc
1,929
c
C
blakserv/files.c
jfaubert087/Meridian59_202
8f52d210c9c266978c07ebdad35168a548c3bde6
[ "FTL", "OML" ]
1
2021-05-19T02:13:59.000Z
2021-05-19T02:13:59.000Z
blakserv/files.c
siwithaneye/Meridian59
9dc8df728d41ba354c9b11574484da5b3e013a87
[ "FSFAP" ]
null
null
null
blakserv/files.c
siwithaneye/Meridian59
9dc8df728d41ba354c9b11574484da5b3e013a87
[ "FSFAP" ]
null
null
null
// Meridian 59, Copyright 1994-2012 Andrew Kirmse and Chris Kirmse. // All rights reserved. // // This software is distributed under a license that is described in // the LICENSE file that accompanies it. // // Meridian is a registered trademark. /* * files.c * */ #include "blakserv.h" bool FindMatchingFiles(const char *path, std::vector<std::string> *files) { #ifdef BLAK_PLATFORM_WINDOWS HANDLE hFindFile; WIN32_FIND_DATA search_data; files->clear(); hFindFile = FindFirstFile(path, &search_data); if (hFindFile == INVALID_HANDLE_VALUE) return false; do { files->push_back(search_data.cFileName); } while (FindNextFile(hFindFile,&search_data)); FindClose(hFindFile); return true; #elif BLAK_PLATFORM_LINUX struct dirent *entry; DIR *dir = opendir(path); // XXX Need to parse out path name if (dir == NULL) return false; while (entry = readdir(dir)) { std::string filename = entry->d_name; if (filename != "." && filename != "..") files->push_back(filename); } closedir(dir); // XXX Need to pattern match return true; #else #error No platform implementation of FindMatchingFiles #endif } bool BlakMoveFile(const char *source, const char *dest) { #ifdef BLAK_PLATFORM_WINDOWS if (!CopyFile(source,dest,FALSE)) { eprintf("BlakMoveFile error moving %s to %s (%s)\n",source,dest,GetLastErrorStr()); return false; } if (!DeleteFile(source)) { eprintf("BlakMoveFile error deleting %s (%s)\n",source,GetLastErrorStr()); return false; } return true; #elif BLAK_PLATFORM_LINUX // Doesn't work across filesystems, but probably fine for our purposes. return 0 == rename(source, dest); #else #error No platform implementation of BlakMoveFile #endif }
22.694118
90
0.636081
[ "vector" ]
9cea3b8fcea5f1ce076fe16f3d1e8dbb2b8d233e
3,407
h
C
Code/Sources/MacRunTime/TimingUtilitiesOSX.h
Synclavier/Software
a237bf2a6698bf7bc6c8282227fc22b627e512cc
[ "MIT" ]
5
2017-10-26T03:02:21.000Z
2021-06-24T23:32:25.000Z
Code/Sources/MacRunTime/TimingUtilitiesOSX.h
Synclavier/Software
a237bf2a6698bf7bc6c8282227fc22b627e512cc
[ "MIT" ]
null
null
null
Code/Sources/MacRunTime/TimingUtilitiesOSX.h
Synclavier/Software
a237bf2a6698bf7bc6c8282227fc22b627e512cc
[ "MIT" ]
2
2020-11-04T04:07:33.000Z
2021-06-24T23:32:30.000Z
// TimingUtilitiesOSX.h #ifndef __TIMINGUTILITIES__ #define __TIMINGUTILITIES__ // Mac OS Includes // This implementation is used both in the kernel driver and in the user space application #ifdef COMPILE_OSX_KERNEL #include <IOKit/IOLib.h> #include <kern/clock.h> #else #include <mach/mach_time.h> #endif #include "Standard.h" typedef uint64_t TU_nanos; extern TU_nanos TU_ComputeNanosecondTimeBase(); // compute computes a linear nanosecond time base static __inline__ void TU_ReadTBR(TU_nanos &nano_ref) { nano_ref = TU_ComputeNanosecondTimeBase(); } static __inline__ TU_nanos TU_GetProcessorTime() { return TU_ComputeNanosecondTimeBase(); } static __inline__ uint32 TU_ReadTBRLsb() { return (uint32) TU_ComputeNanosecondTimeBase(); } // Variables extern TU_nanos TU_atic_time_root; // AbsoluteTime of time == 0 extern TU_nanos TU_atic_time_of_last_msec_boundary; // AbsoluteTime when simulated D16 wrapped extern TU_nanos TU_atic_time_of_next_msec_boundary; // AbsoluteTime when simulated D16 will wrap next extern unsigned int TU_next_atic_time_lsb; extern unsigned int* TU_next_atic_time_lsb_ptr; extern uint32 TU_real_time_milliseconds; // Millisecond real time counter extern uint32 TU_host_nsecs_per_real_time_msec; // Nanoseconds of CPU time per millisecond of Synclavier real time extern uint32 TU_100micro_shift_factor; // shift right factor to scale processor host time to approximately 100 microseconds per tick extern uint32 TU_host_nsecs_per_100micros; // Nanoseconds of CPU time per 100 microseconds of Synclavier real time extern uint32 TU_100micro_magnitude; // smallest power of 2 > TU_host_nsecs_per_100micros // Routines extern int TU_PerformLinearComparison(unsigned int val1, unsigned int val2); // Check for wrap from val1 to val2 extern uint32 TU_UnsignedFractionalMultiply32x32(uint32 arg_a, uint32 arg_b); // 32bit x 32 bit unsigned fractional multiply extern void TU_InitializeTimingUtilities(uint32_ratio known_ratio); // setup timing utilities extern void TU_FastAdvanceRealTimeMilliseconds(); // advance real time milliseconds quickly according to processor time base register extern TU_nanos TU_ComputeMicrosecondTimeBase(); // compute computes a linear microsecond time base extern uint32_ratio TU_MeasureUPTimeUsingD16Timer(volatile unsigned int* fifoLoc, unsigned int fifoData); // Calibrate using D16 timer - use D16 timer on M64k board extern uint32_ratio TU_MeasureUPTimeUsingD03Timer(volatile unsigned int* fifoLoc, unsigned int fifoData, unsigned int fifoWrites); // Calibrate using D03 timer - matches Model D implementation extern void TU_PublishNewRatios(uint32_ratio known_ratio); // update new values after measuring metronome typedef bool (*TU_CheckD03)(); extern uint32_ratio TU_MeasureUPTimeUsingD03Timer(TU_CheckD03 d3_reader); // Calibrate using D03 timer - matches Model D implementation extern bool TU_Abort_Measurement; #endif
49.376812
192
0.704139
[ "model" ]
9ceac543176c2e94c9cb6828799d41e117a85f67
1,149
h
C
src/jsonrpccpp/common/specificationwriter.h
cpp-ethereum-ios/libjson-rpc-cpp
b1c49a8243df6dd4cd3ad318f81206c0ab146afd
[ "MIT" ]
5
2021-10-07T15:36:37.000Z
2022-03-01T07:21:49.000Z
src/jsonrpccpp/common/specificationwriter.h
cpp-ethereum-ios/libjson-rpc-cpp
b1c49a8243df6dd4cd3ad318f81206c0ab146afd
[ "MIT" ]
null
null
null
src/jsonrpccpp/common/specificationwriter.h
cpp-ethereum-ios/libjson-rpc-cpp
b1c49a8243df6dd4cd3ad318f81206c0ab146afd
[ "MIT" ]
1
2022-03-01T07:21:51.000Z
2022-03-01T07:21:51.000Z
/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file specificationwriter.h * @date 30.04.2013 * @author Peter Spiess-Knafl <peter.knafl@gmail.com> * @license See attached LICENSE.txt ************************************************************************/ #ifndef JSONRPC_CPP_SPECIFICATIONWRITER_H #define JSONRPC_CPP_SPECIFICATIONWRITER_H #include "procedure.h" #include "specification.h" namespace jsonrpc { class SpecificationWriter { public: static Json::Value toJsonValue (const std::vector<Procedure>& procedures); static std::string toString (const std::vector<Procedure>& procedures); static bool toFile (const std::string& filename, const std::vector<Procedure>& procedures); private: static Json::Value toJsonLiteral (jsontype_t type); static void procedureToJsonValue (const Procedure& procedure, Json::Value& target); }; } #endif // JSONRPC_CPP_SPECIFICATIONWRITER_H
37.064516
116
0.5396
[ "vector" ]
9ceb80aa0119211c51f1a7b9c7dd912ddd779448
979
h
C
data.h
honzaq/logan
5a3c65885e902ff1a72ba31c64389cc5b0c1f1cf
[ "MIT" ]
null
null
null
data.h
honzaq/logan
5a3c65885e902ff1a72ba31c64389cc5b0c1f1cf
[ "MIT" ]
null
null
null
data.h
honzaq/logan
5a3c65885e902ff1a72ba31c64389cc5b0c1f1cf
[ "MIT" ]
null
null
null
#pragma once namespace logan { struct sum_data_item { uint32_t count = 0; }; struct time_data_item { FILETIME time = { 0 }; std::string msg; }; struct analyzed_data { std::string file_name; std::map<std::string, sum_data_item> sum_items; std::vector<time_data_item> time_items; }; using sum_map = std::map<std::string, sum_data_item>; struct global_data { sum_map gsum_items; std::map<std::string, std::vector<time_data_item>> gtime_items; void append(const analyzed_data& data) { gtime_items.emplace(data.file_name, data.time_items); for(const auto item : data.sum_items) { auto it = gsum_items.find(item.first); if(it != gsum_items.end()) { it->second.count += it->second.count; } else { gsum_items.emplace(item.first, item.second); } } } }; class data_export : logger_holder { public: data_export(logger_ptr logger); bool serialize_to_json(const wchar_t* file_path, const global_data& data); }; } // end of namespace logan
20.829787
75
0.707865
[ "vector" ]
9cf0c84c3519bb53448562a01e5507560d32b3ff
1,314
h
C
test/TexturedQuadTest/TexturedQuadTest.h
rfruesmer/rfx
96c15a11ee8e2192c9d2ff233924eee884835f17
[ "MIT" ]
null
null
null
test/TexturedQuadTest/TexturedQuadTest.h
rfruesmer/rfx
96c15a11ee8e2192c9d2ff233924eee884835f17
[ "MIT" ]
null
null
null
test/TexturedQuadTest/TexturedQuadTest.h
rfruesmer/rfx
96c15a11ee8e2192c9d2ff233924eee884835f17
[ "MIT" ]
null
null
null
#pragma once #include "rfx/application/Application.h" namespace rfx::test { class TexturedQuadTest : public Application { private: struct UniformBufferObject { glm::mat4 model; glm::mat4 view; glm::mat4 proj; float lodBias = 0.0f; }; void initGraphics() override; void buildScene(); void createVertexBuffer(); void createIndexBuffer(); void createUniformBuffers(); void createDescriptorPool(); void createDescriptorSetLayout(); void createDescriptorSets(); void createRenderPass(); void createGraphicsPipeline(); void createCommandBuffers(); void createTexture(); void update(float deltaTime) override; void updateDevTools() override; void cleanup() override; void cleanupSwapChain() override; void recreateSwapChain() override; VkPipelineLayout pipelineLayout = VK_NULL_HANDLE; VkPipeline pipeline = VK_NULL_HANDLE; VkDescriptorSetLayout descriptorSetLayout = VK_NULL_HANDLE; std::vector<VkDescriptorSet> descriptorSets; VertexBufferPtr vertexBuffer; IndexBufferPtr indexBuffer; VertexShaderPtr vertexShader; FragmentShaderPtr fragmentShader; std::vector<BufferPtr> uniformBuffers; Texture2DPtr texture; UniformBufferObject ubo; }; } // namespace rfx
24.792453
63
0.718417
[ "vector", "model" ]
9cf5caa986102aa4d96885bdbac6d1b780b66079
23,792
h
C
ros/third_party/cepton_sdk/include/cepton_sdk.h
Ly0n/cepton_sdk_redist
5b4bf24edadb4fdaf9b8149a70c60d207922a1ad
[ "BSD-3-Clause" ]
3
2020-08-07T23:16:10.000Z
2021-09-10T14:37:38.000Z
include/cepton_sdk.h
Ly0n/cepton_sdk_redist
5b4bf24edadb4fdaf9b8149a70c60d207922a1ad
[ "BSD-3-Clause" ]
null
null
null
include/cepton_sdk.h
Ly0n/cepton_sdk_redist
5b4bf24edadb4fdaf9b8149a70c60d207922a1ad
[ "BSD-3-Clause" ]
1
2021-03-19T17:19:32.000Z
2021-03-19T17:19:32.000Z
/* Copyright Cepton Technologies Inc., All rights reserved. Cepton Sensor SDK C interface. */ #ifndef CEPTON_SDK_H #define CEPTON_SDK_H #include <stddef.h> #include <stdint.h> #ifdef __cplusplus extern "C" { #endif //------------------------------------------------------------------------------ // Macros //------------------------------------------------------------------------------ // CEPTON_SDK_EXPORT #ifndef CEPTON_SDK_EXPORT #ifdef CEPTON_SDK_COMPILING // Export #ifdef _MSC_VER #define CEPTON_SDK_EXPORT __declspec(dllexport) #elif __GNUC__ #define CEPTON_SDK_EXPORT __attribute__((visibility("default"))) #else #define CEPTON_SDK_EXPORT #endif #elif defined(CEPTON_SDK_STATIC) // Import static #define CEPTON_SDK_EXPORT #else // Import shared #ifdef _MSC_VER #define CEPTON_SDK_EXPORT __declspec(dllimport) #else #define CEPTON_SDK_EXPORT #endif #endif #endif // CEPTON_DEPRECATED #ifndef CEPTON_DEPRECATED #if defined(_MSC_VER) #define CEPTON_DEPRECATED __declspec(deprecated) #elif defined(__GNUC__) #define CEPTON_DEPRECATED __attribute__((deprecated)) #else #define CEPTON_DEPRECATED #endif #endif //------------------------------------------------------------------------------ // Errors //------------------------------------------------------------------------------ /// Error code returned by most library functions. /** * Must call `cepton_sdk_get_error` if nonzero error code is returned. */ typedef int32_t CeptonSensorErrorCode; enum _CeptonSensorErrorCode { /// No error. CEPTON_SUCCESS = 0, /// Generic error. CEPTON_ERROR_GENERIC = -1, /// Failed to allocate heap memory. CEPTON_ERROR_OUT_OF_MEMORY = -2, /// Could not find sensor. CEPTON_ERROR_SENSOR_NOT_FOUND = -4, /// SDK version mismatch. CEPTON_ERROR_SDK_VERSION_MISMATCH = -5, /// Networking error. CEPTON_ERROR_COMMUNICATION = -6, /// Callback already set. CEPTON_ERROR_TOO_MANY_CALLBACKS = -7, /// Invalid value or uninitialized struct. CEPTON_ERROR_INVALID_ARGUMENTS = -8, /// Already initialized. CEPTON_ERROR_ALREADY_INITIALIZED = -9, /// Not initialized. CEPTON_ERROR_NOT_INITIALIZED = -10, /// Invalid file type. CEPTON_ERROR_INVALID_FILE_TYPE = -11, /// File IO error. CEPTON_ERROR_FILE_IO = -12, /// Corrupt/invalid file. CEPTON_ERROR_CORRUPT_FILE = -13, /// Not open. CEPTON_ERROR_NOT_OPEN = -14, /// End of file. CEPTON_ERROR_EOF = -15, /// Internal sensor parameter out of range. CEPTON_FAULT_INTERNAL = -1000, /// Extreme sensor temperature fault. CEPTON_FAULT_EXTREME_TEMPERATURE = -1001, /// Extreme sensor humidity fault. CEPTON_FAULT_EXTREME_HUMIDITY = -1002, /// Extreme sensor acceleration fault. CEPTON_FAULT_EXTREME_ACCELERATION = -1003, /// Abnormal sensor FOV fault. CEPTON_FAULT_ABNORMAL_FOV = -1004, /// Abnormal sensor frame rate fault. CEPTON_FAULT_ABNORMAL_FRAME_RATE = -1005, /// Sensor motor malfunction fault. CEPTON_FAULT_MOTOR_MALFUNCTION = -1006, /// Sensor laser malfunction fault. CEPTON_FAULT_LASER_MALFUNCTION = -1007, /// Sensor detector malfunction fault. CEPTON_FAULT_DETECTOR_MALFUNCTION = -1008, }; /// Returns error code name string. /** * Returns empty string if error code is invalid. * * @return Error code name string. Owned by SDK. Valid until next SDK call in * current thread. */ CEPTON_SDK_EXPORT const char *cepton_get_error_code_name( CeptonSensorErrorCode error_code); /// Returns whether `error_code` is of the form `CEPTON_ERROR_*`. CEPTON_SDK_EXPORT int cepton_is_error_code(CeptonSensorErrorCode error_code); /// Returns whether `error_code` is of the form `CEPTON_FAULT_*`. CEPTON_SDK_EXPORT int cepton_is_fault_code(CeptonSensorErrorCode error_code); /// Returns and clears last sdk error. /** * @param error_msg Returned error message string. Owned by the SDK, and valid * until next SDK call in the current thread. * @return Error code. */ CEPTON_SDK_EXPORT CeptonSensorErrorCode cepton_sdk_get_error(const char **error_msg); //------------------------------------------------------------------------------ // Types //------------------------------------------------------------------------------ /// Sensor identifier. /** * Generated from sensor IP address. */ typedef uint64_t CeptonSensorHandle; /// Internal use only. static const CeptonSensorHandle CEPTON_NULL_HANDLE = 0LL; /// Internal use only. static const CeptonSensorHandle CEPTON_SENSOR_HANDLE_FLAG_MOCK = 0x100000000LL; /// Sensor model. typedef uint16_t CeptonSensorModel; enum _CeptonSensorModel { HR80W = 3, HR80T_R2 = 6, VISTA_860_GEN2 = 7, VISTA_X120 = 10, SORA_P60 = 11, VISTA_P60 = 12, VISTA_X15 = 13, VISTA_P90 = 14, SORA_P90 = 15, VISTA_P61 = 16, SORA_P61 = 17, VISTA_H120 = 18, CEPTON_SENSOR_MODEL_MAX = 18, }; /// Returns whether sensor model is of the form `SORA_*`. CEPTON_SDK_EXPORT int cepton_is_sora(CeptonSensorModel model); /// Returns whether sensor model is of the form `HR80_*`. CEPTON_SDK_EXPORT int cepton_is_hr80(CeptonSensorModel model); /// Returns whether sensor model is of the form `VISTA_*`. CEPTON_SDK_EXPORT int cepton_is_vista(CeptonSensorModel model); /// Sensor information struct. /** * Returned by `cepton_sdk_get_sensor_information*`. */ struct CEPTON_SDK_EXPORT CeptonSensorInformation { /// Sensor identifier (generated from IP address). CeptonSensorHandle handle; /// Sensor serial number. uint64_t serial_number; /// Full sensor model name. char model_name[28]; /// Sensor model. CeptonSensorModel model; uint16_t reserved; /// Firmware version string. char firmware_version[28]; #ifdef CEPTON_SIMPLE /// Firmware version struct. uint32_t formal_firmware_version; #else /// Firmware version struct. struct { /// Major firmware version. uint8_t major; /// Minor firmware version. uint8_t minor; uint8_t unused[2]; } formal_firmware_version; #endif /// [celsius]. float last_reported_temperature; /// [%]. float last_reported_humidity; /// [hours]. float last_reported_age; /// Time between measurements [seconds]. float measurement_period; /// PTP time [microseconds]. int64_t ptp_ts; // GPS time parsed from NMEA sentence. uint8_t gps_ts_year; ///< (0-99) (e.g. 2017 -> 17) uint8_t gps_ts_month; ///< (1-12) uint8_t gps_ts_day; ///< (1-31) uint8_t gps_ts_hour; ///< (0-23) uint8_t gps_ts_min; ///< (0-59) uint8_t gps_ts_sec; ///< (0-59) /// Number of returns per measurement. uint8_t return_count; /// Number of image segments. uint8_t segment_count; #ifdef CEPTON_SIMPLE /// Bit flags. uint32_t flags; #else union { /// Bit flags. uint32_t flags; struct { /// Created by capture replay. uint32_t is_mocked : 1; /// GPS PPS is available. uint32_t is_pps_connected : 1; /// GPS NMEA is available. uint32_t is_nmea_connected : 1; /// PTP is available. uint32_t is_ptp_connected : 1; /// Calibration loaded. uint32_t is_calibrated : 1; /// Hit temperature limit. uint32_t is_over_heated : 1; /// Sync fire enabled (disabled by default). uint32_t is_sync_firing_enabled : 1; }; }; #endif }; /// Internal use only. CEPTON_SDK_EXPORT extern const size_t cepton_sensor_information_size; /// Measurement return type flags (for multi-return). typedef uint8_t CeptonSensorReturnType; enum _CeptonSensorReturnType { /// Highest intensity return. CEPTON_RETURN_STRONGEST = 1 << 0, /// Farthest return. CEPTON_RETURN_FARTHEST = 1 << 1, }; /// Point in pinhole image coordinates (focal length = 1). /** * To convert to 3d point, use * `cepton_sdk::util::convert_sensor_image_point_to_point`. */ struct CEPTON_SDK_EXPORT CeptonSensorImagePoint { /// Unix time [microseconds]. int64_t timestamp; /// x image coordinate. float image_x; /// Distance [meters]. float distance; /// z image coordinate. float image_z; /// Diffuse reflectance (normal: [0-1], retroreflective: >1). float intensity; /// Return type flags. CeptonSensorReturnType return_type; #ifdef CEPTON_SIMPLE /// Bit flags. uint8_t flags; #else union { /// Bit flags. uint8_t flags; struct { /// If `false`, then `distance` and `intensity` are invalid. uint8_t valid : 1; /// If `true`, then `intensity` is invalid, and the `distance` is /// innacurate. uint8_t saturated : 1; }; }; #endif uint8_t segment_id; uint8_t reserved[1]; }; /// Internal use only. CEPTON_SDK_EXPORT extern const size_t cepton_sensor_image_point_size; //------------------------------------------------------------------------------ // Constants //------------------------------------------------------------------------------ // Limits for preallocating buffers. // These numbers are guaranteed to be safe for 6 months from SDK release. #define CEPTON_SDK_MAX_POINTS_PER_PACKET 400 #define CEPTON_SDK_MAX_POINTS_PER_FRAME 50000 #define CEPTON_SDK_MAX_POINTS_PER_SECOND 1000000 #define CEPTON_SDK_MAX_FRAMES_PER_SECOND 40 //------------------------------------------------------------------------------ // SDK Setup //------------------------------------------------------------------------------ /// API version. /** * Used in `cepton_sdk_initialize` to validate shared library API. */ #define CEPTON_SDK_VERSION 19 /// Returns library version string. /** * This is different from `CEPTON_SDK_VERSION`. * * @return Version string. Owned by SDK. Valid until next SDK call in current * thread. */ CEPTON_SDK_EXPORT const char *cepton_sdk_get_version_string(); /// Returns library version major. CEPTON_SDK_EXPORT int cepton_sdk_get_version_major(); /// Returns library version minor. CEPTON_SDK_EXPORT int cepton_sdk_get_version_minor(); /// Returns library version patch. CEPTON_SDK_EXPORT int cepton_sdk_get_version_patch(); /// SDK setup flags. typedef uint32_t CeptonSDKControl; enum _CeptonSDKControl { /// Disable networking operations. /** * Useful for running multiple instances of sdk in different processes. * Must pass packets manually to `cepton_sdk::mock_network_receive`. */ CEPTON_SDK_CONTROL_DISABLE_NETWORK = 1 << 1, /// Enable multiple returns. /** * When set, `cepton_sdk::SensorInformation::return_count` will indicate the * number of returns per laser. * Can only be set at SDK initialization. */ CEPTON_SDK_CONTROL_ENABLE_MULTIPLE_RETURNS = 1 << 4, /// Always use packet timestamps (disable GPS/PTP timestamps). CEPTON_SDK_CONTROL_HOST_TIMESTAMPS = 1 << 6, CEPTON_SDK_CONTROL_RESERVED = 1 << 7, }; /// Controls frequency of points being reported. typedef uint32_t CeptonSDKFrameMode; enum _CeptonSDKFrameMode { /// Report points by packet. CEPTON_SDK_FRAME_STREAMING = 0, /// Report points at fixed time intervals. /** * Interval controlled by `CeptonSDKFrameOptions::length`. */ CEPTON_SDK_FRAME_TIMED = 1, /// Report points when the field of view is covered once. /** * Use this for a fast frame rate. * - For Sora series, detects scanline (left-to-right or right-to-left). * - For HR80 series, detects half scan cycle (left-to-right or * right-to-left). * - For Vista series, detects half scan cycle. */ CEPTON_SDK_FRAME_COVER = 2, /// Report points when the scan pattern goes through a full cycle. /** * Use this for a consistent, repeating frame. * Typically 2x longer frame than `CEPTON_SDK_FRAME_COVER` mode. */ CEPTON_SDK_FRAME_CYCLE = 3, CEPTON_SDK_FRAME_MODE_MAX = 3 }; /// SDK frame options. /** * Must use `cepton_sdk_create_frame_options` to create. */ struct CEPTON_SDK_EXPORT CeptonSDKFrameOptions { /// Internal use only. size_t signature; /// Default: `CEPTON_SDK_FRAME_STREAMING`. CeptonSDKFrameMode mode; /// Frame length [seconds]. /** * Default: 0.05. * Only used if `mode`=`CEPTON_SDK_FRAME_TIMED`. */ float length; }; /// Create frame options. CEPTON_SDK_EXPORT struct CeptonSDKFrameOptions cepton_sdk_create_frame_options(); /// SDK initialization options. /** * Must call `cepton_sdk_create_options` to create. */ struct CEPTON_SDK_EXPORT CeptonSDKOptions { /// Internal use only. size_t signature; /// Default: 0. CeptonSDKControl control_flags; struct CeptonSDKFrameOptions frame; /// Network listen port. Default: 8808. uint16_t port; }; /// Create SDK options. CEPTON_SDK_EXPORT struct CeptonSDKOptions cepton_sdk_create_options(); /// Callback for receiving sdk and sensor errors. /** * @param handle Associated sensor handle. * @param error_code Error code. * @param error_msg Error message string. Owned by SDK. * @param error_data Not implemented. * @param error_data_size Not implemented. * @param user_data User instance pointer. */ typedef void (*FpCeptonSensorErrorCallback)(CeptonSensorHandle handle, CeptonSensorErrorCode error_code, const char *error_msg, const void *error_data, size_t error_data_size, void *user_data); /// Returns true if sdk is initialized. CEPTON_SDK_EXPORT int cepton_sdk_is_initialized(); /// Initializes settings and networking. /** * Must be called before any other sdk function listed below. * * @param ver `CEPTON_SDK_VERSION` * @param options SDK options. * @param cb Error callback. * @param user_data Error callback user instance pointer. */ CEPTON_SDK_EXPORT CeptonSensorErrorCode cepton_sdk_initialize(int ver, const struct CeptonSDKOptions *const options, FpCeptonSensorErrorCallback cb, void *const user_data); /// Resets everything and deallocates memory. CEPTON_SDK_EXPORT CeptonSensorErrorCode cepton_sdk_deinitialize(); /// Sets SDK control flags. /** * @param mask Bit mask for selecting flags to change. * @param flags Bit flag values. */ CEPTON_SDK_EXPORT CeptonSensorErrorCode cepton_sdk_set_control_flags(CeptonSDKControl mask, CeptonSDKControl flags); /// Returns SDK control flag. CEPTON_SDK_EXPORT CeptonSDKControl cepton_sdk_get_control_flags(); /// Returns whether SDK control flag is set. CEPTON_SDK_EXPORT int cepton_sdk_has_control_flag(CeptonSDKControl flag); /// Clears sensors. /** * Use when loading/unloading capture file. */ CEPTON_SDK_EXPORT CeptonSensorErrorCode cepton_sdk_clear(); /// Sets network listen port. /** * Default: 8808. */ CEPTON_SDK_EXPORT CeptonSensorErrorCode cepton_sdk_set_port(uint16_t port); /// Returns network listen port. CEPTON_SDK_EXPORT uint16_t cepton_sdk_get_port(); /// Sets frame options. CEPTON_SDK_EXPORT CeptonSensorErrorCode cepton_sdk_set_frame_options(const struct CeptonSDKFrameOptions *const options); /// Returns frame mode. CEPTON_SDK_EXPORT CeptonSDKFrameMode cepton_sdk_get_frame_mode(); /// Returns frame length. CEPTON_SDK_EXPORT float cepton_sdk_get_frame_length(); //------------------------------------------------------------------------------ // Points //------------------------------------------------------------------------------ /// Callback for receiving image points. /** * Set the frame options to control the callback rate. * @param handle Sensor handle. * @param n_points Points array size. * @param c_points Points array. Owned by SDK. * @param user_data User instance pointer. */ typedef void (*FpCeptonSensorImageDataCallback)( CeptonSensorHandle handle, size_t n_points, const struct CeptonSensorImagePoint *c_points, void *user_data); /// Sets image frame callback. /** * Returns points at frequency specified by `cepton_sdk::FrameOptions::mode`. * Each frame contains all possible points (use * `cepton_sdk::SensorImagePoint::valid` to filter points). Points are ordered * by measurement, segment, and return: * * ``` * measurement_count = n_points / (segment_count * return_count) * idx = ((i_measurement) * segment_count + i_segment) * return_count + i_return * ``` * * Returns error if callback already registered. */ CEPTON_SDK_EXPORT CeptonSensorErrorCode cepton_sdk_listen_image_frames( FpCeptonSensorImageDataCallback cb, void *const user_data); /// Clears image frame callback. CEPTON_SDK_EXPORT CeptonSensorErrorCode cepton_sdk_unlisten_image_frames(); //------------------------------------------------------------------------------ // Sensors //------------------------------------------------------------------------------ /** * Get number of sensors attached. * Use to check for new sensors. Sensors are not deleted until deinitialization. */ CEPTON_SDK_EXPORT size_t cepton_sdk_get_n_sensors(); /// Looks up sensor handle by serial number. /** * Returns error if sensor not found. * * @param serial_number Sensor serial number. * @param handle Sensor handle. */ CEPTON_SDK_EXPORT CeptonSensorErrorCode cepton_sdk_get_sensor_handle_by_serial_number(uint64_t serial_number, CeptonSensorHandle *const handle); /// Returns sensor information by sensor index. /** * Useful for getting information for all sensors. * Valid indices are in range [0, `cepton_sdk_get_n_sensors()`). * * Returns error if index invalid. * * @param idx Sensor index. Returns error if invalid. * @param info Sensor information. */ CEPTON_SDK_EXPORT CeptonSensorErrorCode cepton_sdk_get_sensor_information_by_index( size_t idx, struct CeptonSensorInformation *const info); /// Returns sensor information by sensor handle. /** * @param handle Sensor handle. Returns error if invalid. * @param info Sensor information. */ CEPTON_SDK_EXPORT CeptonSensorErrorCode cepton_sdk_get_sensor_information( CeptonSensorHandle handle, struct CeptonSensorInformation *const info); //------------------------------------------------------------------------------ // Serial //------------------------------------------------------------------------------ /// Callback for receiving serial data (e.g. NMEA). /** * @param handle Sensor handle. * @param str Serial line string. Owned by SDK. * @param user_data User instance pointer. */ typedef void (*FpCeptonSerialReceiveCallback)(CeptonSensorHandle handle, const char *str, void *user_data); /// Sets serial line callback. /** * Useful for listening to NMEA data from GPS attached to sensor. * Each callback contains 1 line of serial data (including newline characters). * * Returns error if callback already registered. * * @param cb Callback. * @param user_data User instance pointer. */ CEPTON_SDK_EXPORT CeptonSensorErrorCode cepton_sdk_listen_serial_lines( FpCeptonSerialReceiveCallback cb, void *const user_data); /// Clears serial line callback. CEPTON_SDK_EXPORT CeptonSensorErrorCode cepton_sdk_unlisten_serial_lines(); //------------------------------------------------------------------------------ // Networking //------------------------------------------------------------------------------ /// Callback for receiving network packets. /** * Returns error if callback already set. * * @param handle Sensor handle. * @param timestamp Packet Unix timestamp [microseconds]. * @param buffer Packet bytes. * @param buffer_size Buffer size. * @param user_data User instance pointer. */ typedef void (*FpCeptonNetworkReceiveCallback)(CeptonSensorHandle handle, int64_t timestamp, const uint8_t *buffer, size_t buffer_size, void *user_data); /// Sets network packets callback. /** * For internal use. * * Returns error if callback already registered. * * @param cb Callback. * @param user_data User instance pointer. */ CEPTON_SDK_EXPORT CeptonSensorErrorCode cepton_sdk_listen_network_packet( FpCeptonNetworkReceiveCallback cb, void *const user_data); /// Clears network packet callback. CEPTON_SDK_EXPORT CeptonSensorErrorCode cepton_sdk_unlisten_network_packet(); /// Manually passes packets to sdk. /** * Blocks while processing, and calls listener callbacks synchronously before * returning. * * @param handle Sensor handle. * @param timestamp Unix timestamp [microseconds]. * @param buffer Packet bytes. * @param buffer_size Packet size. */ CEPTON_SDK_EXPORT CeptonSensorErrorCode cepton_sdk_mock_network_receive( CeptonSensorHandle handle, int64_t timestamp, const uint8_t *const buffer, size_t buffer_size); //------------------------------------------------------------------------------ // Capture Replay //------------------------------------------------------------------------------ /// Returns whether capture replay is open. CEPTON_SDK_EXPORT int cepton_sdk_capture_replay_is_open(); /// Opens capture replay. /** * Must be called before any other replay functions listed below. * * @param path Path to PCAP capture file. */ CEPTON_SDK_EXPORT CeptonSensorErrorCode cepton_sdk_capture_replay_open(const char *const path); /// Closes capture replay. CEPTON_SDK_EXPORT CeptonSensorErrorCode cepton_sdk_capture_replay_close(); /// Returns capture replay file name. CEPTON_SDK_EXPORT const char *cepton_sdk_capture_replay_get_filename(); /// Returns capture start Unix timestamp [microseconds]. CEPTON_SDK_EXPORT int64_t cepton_sdk_capture_replay_get_start_time(); /// Returns capture file position [seconds]. CEPTON_SDK_EXPORT float cepton_sdk_capture_replay_get_position(); /// Returns capture file length [seconds]. CEPTON_SDK_EXPORT float cepton_sdk_capture_replay_get_length(); /// Returns whether at end of capture file. /** * This is only relevant when using `resume_blocking` methods. */ CEPTON_SDK_EXPORT int cepton_sdk_capture_replay_is_end(); /// Rewinds capture replay to beginning. /** * DEPRECATED: use `cepton_sdk_capture_replay_seek(0)`. */ CEPTON_DEPRECATED CEPTON_SDK_EXPORT CeptonSensorErrorCode cepton_sdk_capture_replay_rewind(); /// Seek to capture file position [seconds]. /** * @param position Seek position in range [0.0, capture length). */ CEPTON_SDK_EXPORT CeptonSensorErrorCode cepton_sdk_capture_replay_seek(float position); /// Sets capture replay looping. /** * If enabled, replay will automatically rewind at end. */ CEPTON_SDK_EXPORT CeptonSensorErrorCode cepton_sdk_capture_replay_set_enable_loop(int enable_loop); /// Returns whether capture replay looping is enabled. CEPTON_SDK_EXPORT int cepton_sdk_capture_replay_get_enable_loop(); /// Sets speed multiplier for asynchronous replay. CEPTON_SDK_EXPORT CeptonSensorErrorCode cepton_sdk_capture_replay_set_speed(float speed); /// Returns capture replay speed. CEPTON_SDK_EXPORT float cepton_sdk_capture_replay_get_speed(); /// Replay next packet in current thread without sleeping. /** * Pauses replay thread if running. */ CEPTON_SDK_EXPORT CeptonSensorErrorCode cepton_sdk_capture_replay_resume_blocking_once(); /// Replay multiple packets synchronously. /** * No sleep between packets. Pauses replay thread if running. * * @param duration Duration to replay. Must be non-negative. */ CEPTON_SDK_EXPORT CeptonSensorErrorCode cepton_sdk_capture_replay_resume_blocking(float duration); /// Returns true if replay thread is running. CEPTON_SDK_EXPORT int cepton_sdk_capture_replay_is_running(); /// Resumes asynchronous replay thread. /** * Packets are replayed in realtime. Replay thread sleeps in between packets. */ CEPTON_SDK_EXPORT CeptonSensorErrorCode cepton_sdk_capture_replay_resume(); /// Pauses asynchronous replay thread. CEPTON_SDK_EXPORT CeptonSensorErrorCode cepton_sdk_capture_replay_pause(); #ifdef __cplusplus } // extern "C" #endif #endif // CEPTON_SDK_H
32.151351
80
0.688593
[ "model", "3d" ]
9cf7ec5ea9198d9ecb28a064f99ffd2652297cb6
3,001
h
C
uwsim_resources/uwsim_osgbullet/include/osgbCollision/VertexAggOp.h
epsilonorion/usv_lsa_sim_copy
d189f172dc1d265b7688c7dc8375a65ac4a9c048
[ "Apache-2.0" ]
1
2020-11-30T09:55:33.000Z
2020-11-30T09:55:33.000Z
uwsim_resources/uwsim_osgbullet/include/osgbCollision/VertexAggOp.h
epsilonorion/usv_lsa_sim_copy
d189f172dc1d265b7688c7dc8375a65ac4a9c048
[ "Apache-2.0" ]
null
null
null
uwsim_resources/uwsim_osgbullet/include/osgbCollision/VertexAggOp.h
epsilonorion/usv_lsa_sim_copy
d189f172dc1d265b7688c7dc8375a65ac4a9c048
[ "Apache-2.0" ]
2
2020-11-21T19:50:54.000Z
2020-12-27T09:35:29.000Z
/*************** <auto-copyright.pl BEGIN do not edit this line> ************** * * osgBullet is (C) Copyright 2009-2012 by Kenneth Mark Bryden * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1 as published by the Free Software Foundation. * * This library 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 * Library General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * *************** <auto-copyright.pl END do not edit this line> ***************/ #ifndef __OSGBCOLLISION_VERTEX_AGG_OP_H__ #define __OSGBCOLLISION_VERTEX_AGG_OP_H__ 1 #include <osgbCollision/Export.h> #include <osgwTools/GeometryOperation.h> #include <osg/CopyOp> #include <osg/Object> #include <osg/Vec3> namespace osgbCollision { // Forward struct Octree; /** \class VertexAggOp VertexAggOp.h <osgbCollision/VertexAggOp.h> \brief A geometry reduction method that produces a convex hull, suitable for low-resolution collision shapes. */ class OSGBCOLLISION_EXPORT VertexAggOp : public osgwTools::GeometryOperation { public: VertexAggOp(); VertexAggOp( const VertexAggOp& rhs, const osg::CopyOp& copyOp=osg::CopyOp::SHALLOW_COPY ); META_Object(osgbInteraction,VertexAggOp); virtual osg::Geometry* operator()( osg::Geometry& geom ); void setMaxVertsPerCell( unsigned int n ) { _maxVertsPerCell = n; } unsigned int getMaxVertsPerCell() const { return( _maxVertsPerCell ); } void setMinCellSize( osg::Vec3 v ) { _minCellSize = v; _useMinCellSize = true; } const osg::Vec3& getMinCellSize() const { return( _minCellSize ); } void setUseMinCellSize( bool use ) { _useMinCellSize = use; } bool getUseMinCellSize() const { return( _useMinCellSize ); } void setCreateHullPerGeometry( bool createHull ) { _createHull = createHull; } bool setCreateHullPerGeometry() const { return( _createHull ); } typedef enum { GEOMETRIC_MEAN, BOUNDING_BOX_CENTER, } PointSelectionMethod; void setPointSelectionMethod( PointSelectionMethod psm ) { _psm = psm; } PointSelectionMethod getPointSelectionMethod() const { return( _psm ); } protected: ~VertexAggOp(); void recurseBuild( Octree* cell ) const; void gatherVerts( Octree* cell, osg::Vec3Array* verts ) const; osg::Vec3 representativeVert( osg::Vec3Array* verts ) const; void createHull( osg::Geometry& geom ); unsigned int _maxVertsPerCell; osg::Vec3 _minCellSize; bool _useMinCellSize; bool _createHull; PointSelectionMethod _psm; }; // osgbCollision } // __OSGBCOLLISION_VERTEX_AGG_OP_H__ #endif
31.589474
95
0.721093
[ "geometry", "object" ]
9cfccf2b64e5be20c3fe4e39a4d091b3aa8886d4
1,667
h
C
launcherprofileloader.h
huanghongxun/HMCLCPP
f0d86c61b1f6e9b687bd09e930d9296c886bef28
[ "MIT" ]
7
2015-12-17T07:52:03.000Z
2022-03-10T11:35:20.000Z
launcherprofileloader.h
huanghongxun/HMCLCPP
f0d86c61b1f6e9b687bd09e930d9296c886bef28
[ "MIT" ]
null
null
null
launcherprofileloader.h
huanghongxun/HMCLCPP
f0d86c61b1f6e9b687bd09e930d9296c886bef28
[ "MIT" ]
4
2016-02-10T02:18:38.000Z
2022-03-10T11:35:22.000Z
#ifndef LAUNCHERPROFILELOADER_H #define LAUNCHERPROFILELOADER_H #include <QString> #include <string> #include <vector> #include <json/reader.h> #include <json/writer.h> #include <json/value.h> #include "settingsmanager.h" #include "FileUtilities.h" using namespace Json; using namespace std; extern QString playerName, minecraftPath, javaPath, launchMode, last; extern int maxMemory; extern bool loaded, debug; class LauncherProfileLoader; extern bool lpLoaded; extern LauncherProfileLoader *loader; class Authentication { public: QString username, accessToken, uuid, displayName; }; class Resolution { public: int height, width; Resolution(){} Resolution(int w, int h):height(h), width(w){} }; class Profile { public: QString name, gameDir, javaDir, javaArgs, lastVersionId,playerUUID; bool hasGameDir, hasJavaDir, hasJavaArgs; bool hasResolution, hasAllowedReleaseTypes; bool hasLastVersionId, hasPlayerUUID, hasFullScreen; bool fullscreen; Resolution r; Profile(){} Profile(QString n):name(n){ hasAllowedReleaseTypes = hasGameDir = hasJavaArgs = hasJavaDir = hasLastVersionId = hasPlayerUUID = hasResolution = hasFullScreen = false; } }; class LauncherProfileLoader { public: QString selectedProfile, clientToken; vector<Profile> profiles; vector<Authentication> authenticationDatabase; LauncherProfileLoader(QString lp); QString generateString(); }; class ProfilesManager { public: static void load(); static void save(); static void add(Profile p); static Profile *find(QString name); }; #endif // LAUNCHERPROFILELOADER_H
21.649351
71
0.728854
[ "vector" ]
14029943240f1af0449d0ca55b3a8fd3c51a07ad
1,402
h
C
Win32xx/tutorials/Tutorial9/src/View.h
mufunyo/VisionRGBApp
c09092770032150083eda171a22b1a3ef0914dab
[ "Unlicense" ]
2
2021-03-25T04:19:22.000Z
2021-05-03T03:23:30.000Z
Win32xx/tutorials/Tutorial9/src/View.h
mufunyo/VisionRGBApp
c09092770032150083eda171a22b1a3ef0914dab
[ "Unlicense" ]
null
null
null
Win32xx/tutorials/Tutorial9/src/View.h
mufunyo/VisionRGBApp
c09092770032150083eda171a22b1a3ef0914dab
[ "Unlicense" ]
1
2020-12-28T08:53:42.000Z
2020-12-28T08:53:42.000Z
////////////////////////////////////////////////////// // View.h // Declaration of the CView class #ifndef VIEW_H #define VIEW_H #include "Doc.h" // Message - sent to the parent (Frame) window when a file is dropped on the View window // WPARAM: A pointer to the filename (LPCTSTR) // LPARAM: unused #define UWM_DROPFILE (WM_APP + 0x0001) class CView : public CWnd { public: CView(); virtual ~CView(); CDoc& GetDoc(); std::vector<PlotPoint>& GetAllPoints(); COLORREF GetPenColor() { return m_penColor; } void Print(LPCTSTR docName); void PrintPage(CDC& dc, UINT page = 1); void QuickPrint(LPCTSTR docName); void SetPenColor(COLORREF color) { m_penColor = color; } protected: virtual int OnCreate(CREATESTRUCT&); virtual void OnDraw(CDC& dc); virtual LRESULT OnDropFiles(UINT msg, WPARAM wparam, LPARAM lparam); virtual LRESULT OnLButtonDown(UINT msg, WPARAM wparam, LPARAM lparam); virtual LRESULT OnLButtonUp(UINT msg, WPARAM wparam, LPARAM lparam); virtual LRESULT OnMouseMove(UINT msg, WPARAM wparam, LPARAM lparam); virtual void PreCreate(CREATESTRUCT& cs); virtual void PreRegisterClass(WNDCLASS& wc); virtual LRESULT WndProc(UINT msg, WPARAM wparam, LPARAM lparam); private: CDC Draw(); void DrawLine(int x, int y); CDoc m_doc; CBrush m_brush; COLORREF m_penColor; }; #endif // CVIEW_H
25.962963
88
0.672611
[ "vector" ]
1402aa2721068dafbd81c95758e25e391ebcb74f
4,496
c
C
WebAssemblyTest/array.c
sasmaster/uncensored3D
9a8b926920a37b2a072d064e98bd7901fc256ace
[ "MIT" ]
4
2018-10-26T05:51:31.000Z
2019-05-30T12:57:57.000Z
WebAssemblyTest/array.c
sasmaster/uncensored3D
9a8b926920a37b2a072d064e98bd7901fc256ace
[ "MIT" ]
null
null
null
WebAssemblyTest/array.c
sasmaster/uncensored3D
9a8b926920a37b2a072d064e98bd7901fc256ace
[ "MIT" ]
null
null
null
/* * Copyright (C) 2007 The Android Open Source Project * * 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 "array.h" #include <assert.h> #include <stdlib.h> #include <string.h> #include <limits.h> #define INITIAL_CAPACITY (4) #define MAX_CAPACITY ((int)(UINT_MAX/sizeof(void*))) struct Array { void** contents; int size; int capacity; }; Array* arrayCreate() { //printf("arrs size:%zu\n", sizeof(struct Array)); // return malloc(sizeof(struct Array)); //must use calloc,otherwise we get uninitialized object return calloc(1, sizeof(struct Array)); } void arrayFree(Array* array) { assert(array != NULL); // Free internal array. free(array->contents); // Free the Array itself. free(array); } /** Returns 0 if successful, < 0 otherwise.. */ static int ensureCapacity(Array* array, int capacity) { int oldCapacity = array->capacity; if (capacity > oldCapacity) { int newCapacity = (oldCapacity == 0) ? INITIAL_CAPACITY : oldCapacity; // Ensure we're not doing something nasty if (capacity > MAX_CAPACITY) return -1; // Keep doubling capacity until we surpass necessary capacity. while (newCapacity < capacity) { int newCap = newCapacity*2; // Handle integer overflows if (newCap < newCapacity || newCap > MAX_CAPACITY) { newCap = MAX_CAPACITY; } newCapacity = newCap; } // Should not happen, but better be safe than sorry if (newCapacity < 0 || newCapacity > MAX_CAPACITY) return -1; void** newContents; if (array->contents == NULL) { // Allocate new array. newContents = malloc(newCapacity * sizeof(void*)); if (newContents == NULL) { return -1; } } else { // Expand existing array. newContents = realloc(array->contents, sizeof(void*) * newCapacity); if (newContents == NULL) { return -1; } } array->capacity = newCapacity; array->contents = newContents; } return 0; } int arrayAdd(Array* array, void* pointer) { assert(array != NULL); int size = array->size; int result = ensureCapacity(array, size + 1); if (result < 0) { return result; } array->contents[size] = pointer; array->size++; return 0; } static inline void checkBounds(Array* array, int index) { assert(array != NULL); assert(index < array->size); assert(index >= 0); } void* arrayGet(Array* array, int index) { checkBounds(array, index); return array->contents[index]; } void* arrayRemove(Array* array, int index) { checkBounds(array, index); void* pointer = array->contents[index]; int newSize = array->size - 1; // Shift entries left. if (index != newSize) { memmove(array->contents + index, array->contents + index + 1, (sizeof(void*)) * (newSize - index)); } array->size = newSize; return pointer; } void* arraySet(Array* array, int index, void* pointer) { checkBounds(array, index); void* old = array->contents[index]; array->contents[index] = pointer; return old; } int arraySetSize(Array* array, int newSize) { assert(array != NULL); assert(newSize >= 0); int oldSize = array->size; if (newSize > oldSize) { // Expand. int result = ensureCapacity(array, newSize); if (result < 0) { return result; } // Zero out new entries. memset(array->contents + sizeof(void*) * oldSize, 0, sizeof(void*) * (newSize - oldSize)); } array->size = newSize; return 0; } int arraySize(Array* array) { assert(array != NULL); return array->size; } const void** arrayUnwrap(Array* array) { return (const void**)array->contents; }
25.83908
80
0.601201
[ "object" ]
140e08b5980074117b675d657c11f292b0d750bb
2,885
h
C
wrappers/8.1.1/vtkStatisticalOutlierRemovalWrap.h
axkibe/node-vtk
900ad7b5500f672519da5aa24c99aa5a96466ef3
[ "BSD-3-Clause" ]
6
2016-02-03T12:48:36.000Z
2020-09-16T15:07:51.000Z
wrappers/8.1.1/vtkStatisticalOutlierRemovalWrap.h
axkibe/node-vtk
900ad7b5500f672519da5aa24c99aa5a96466ef3
[ "BSD-3-Clause" ]
4
2016-02-13T01:30:43.000Z
2020-03-30T16:59:32.000Z
wrappers/8.1.1/vtkStatisticalOutlierRemovalWrap.h
axkibe/node-vtk
900ad7b5500f672519da5aa24c99aa5a96466ef3
[ "BSD-3-Clause" ]
null
null
null
/* this file has been autogenerated by vtkNodeJsWrap */ /* editing this might proof futile */ #ifndef NATIVE_EXTENSION_VTK_VTKSTATISTICALOUTLIERREMOVALWRAP_H #define NATIVE_EXTENSION_VTK_VTKSTATISTICALOUTLIERREMOVALWRAP_H #include <nan.h> #include <vtkSmartPointer.h> #include <vtkStatisticalOutlierRemoval.h> #include "vtkPointCloudFilterWrap.h" #include "../../plus/plus.h" class VtkStatisticalOutlierRemovalWrap : public VtkPointCloudFilterWrap { public: using Nan::ObjectWrap::Wrap; static void Init(v8::Local<v8::Object> exports); static void InitPtpl(); static void ConstructorGetter( v8::Local<v8::String> property, const Nan::PropertyCallbackInfo<v8::Value>& info); VtkStatisticalOutlierRemovalWrap(vtkSmartPointer<vtkStatisticalOutlierRemoval>); VtkStatisticalOutlierRemovalWrap(); ~VtkStatisticalOutlierRemovalWrap( ); static Nan::Persistent<v8::FunctionTemplate> ptpl; private: static void New(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetComputedMean(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetComputedMeanMaxValue(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetComputedMeanMinValue(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetComputedStandardDeviation(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetComputedStandardDeviationMaxValue(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetComputedStandardDeviationMinValue(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetLocator(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetSampleSize(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetSampleSizeMaxValue(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetSampleSizeMinValue(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetStandardDeviationFactor(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetStandardDeviationFactorMaxValue(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetStandardDeviationFactorMinValue(const Nan::FunctionCallbackInfo<v8::Value>& info); static void NewInstance(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SafeDownCast(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetComputedMean(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetComputedStandardDeviation(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetLocator(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetSampleSize(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetStandardDeviationFactor(const Nan::FunctionCallbackInfo<v8::Value>& info); #ifdef VTK_NODE_PLUS_VTKSTATISTICALOUTLIERREMOVALWRAP_CLASSDEF VTK_NODE_PLUS_VTKSTATISTICALOUTLIERREMOVALWRAP_CLASSDEF #endif }; #endif
48.083333
101
0.805893
[ "object" ]
141409343e1422eb3cecd703ee56405e373e74b1
21,626
c
C
test/core/my-object.c
sailfishos-mirror/dbus-glib
6ab7c2c6a2a389d6bf01387966e9debbb6b6ee77
[ "AFL-2.1" ]
8
2018-12-04T08:55:46.000Z
2021-08-08T01:43:53.000Z
test/core/my-object.c
sailfishos-mirror/dbus-glib
6ab7c2c6a2a389d6bf01387966e9debbb6b6ee77
[ "AFL-2.1" ]
null
null
null
test/core/my-object.c
sailfishos-mirror/dbus-glib
6ab7c2c6a2a389d6bf01387966e9debbb6b6ee77
[ "AFL-2.1" ]
null
null
null
/* SPDX-License-Identifier: AFL-2.1 OR GPL-2.0-or-later */ #include <config.h> #undef G_DISABLE_ASSERT #include <string.h> #include <glib/gi18n.h> #include <glib-object.h> #include "my-object.h" #include "test-service-glib-glue.h" /* Properties */ enum { PROP_0, PROP_THIS_IS_A_STRING, PROP_NO_TOUCHING, PROP_SUPER_STUDLY, PROP_SHOULD_BE_HIDDEN }; enum { FROBNICATE, OBJECTIFIED, SIG0, SIG1, SIG2, LAST_SIGNAL }; static guint signals[LAST_SIGNAL] = { 0 }; G_DEFINE_TYPE(MyObject, my_object, G_TYPE_OBJECT) static void my_object_finalize (GObject *object) { MyObject *mobject = MY_OBJECT (object); g_free (mobject->this_is_a_string); g_clear_error (&mobject->saved_error); (G_OBJECT_CLASS (my_object_parent_class)->finalize) (object); } static void my_object_set_property (GObject *object, guint prop_id, const GValue *value, GParamSpec *pspec) { MyObject *mobject; mobject = MY_OBJECT (object); switch (prop_id) { case PROP_THIS_IS_A_STRING: g_free (mobject->this_is_a_string); mobject->this_is_a_string = g_value_dup_string (value); break; case PROP_NO_TOUCHING: mobject->notouching = g_value_get_uint (value); break; case PROP_SUPER_STUDLY: mobject->super_studly = g_value_get_double (value); break; case PROP_SHOULD_BE_HIDDEN: mobject->should_be_hidden = g_value_get_boolean (value); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); break; } } static void my_object_get_property (GObject *object, guint prop_id, GValue *value, GParamSpec *pspec) { MyObject *mobject; mobject = MY_OBJECT (object); switch (prop_id) { case PROP_THIS_IS_A_STRING: g_value_set_string (value, mobject->this_is_a_string); break; case PROP_NO_TOUCHING: g_value_set_uint (value, mobject->notouching); break; case PROP_SUPER_STUDLY: g_value_set_double (value, mobject->super_studly); break; case PROP_SHOULD_BE_HIDDEN: g_value_set_boolean (value, mobject->should_be_hidden); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); break; } } static void my_object_init (MyObject *obj) { obj->val = 0; obj->notouching = 42; obj->saved_error = g_error_new_literal (MY_OBJECT_ERROR, MY_OBJECT_ERROR_FOO, "this method always loses"); } static void my_object_class_init (MyObjectClass *mobject_class) { GObjectClass *gobject_class = G_OBJECT_CLASS (mobject_class); dbus_g_object_type_install_info (MY_TYPE_OBJECT, &dbus_glib_my_object_object_info); gobject_class->finalize = my_object_finalize; gobject_class->set_property = my_object_set_property; gobject_class->get_property = my_object_get_property; g_object_class_install_property (gobject_class, PROP_THIS_IS_A_STRING, g_param_spec_string ("this_is_a_string", _("Sample string"), _("Example of a string property"), "default value", G_PARAM_READWRITE)); g_object_class_install_property (gobject_class, PROP_NO_TOUCHING, g_param_spec_uint ("no_touching", _("Don't touch"), _("Example of a readonly property (for export)"), 0, 100, 42, G_PARAM_READWRITE)); g_object_class_install_property (gobject_class, PROP_SUPER_STUDLY, g_param_spec_double ("super-studly", _("In Studly Caps"), _("Example of a StudlyCaps property"), 0, 256, 128, G_PARAM_READWRITE)); g_object_class_install_property (gobject_class, PROP_SHOULD_BE_HIDDEN, g_param_spec_boolean ("should-be-hidden", _("A non-exported property"), _("Example of a property we don't want exported"), FALSE, G_PARAM_READWRITE)); signals[FROBNICATE] = g_signal_new ("frobnicate", G_OBJECT_CLASS_TYPE (mobject_class), G_SIGNAL_RUN_LAST | G_SIGNAL_DETAILED, 0, NULL, NULL, g_cclosure_marshal_VOID__INT, G_TYPE_NONE, 1, G_TYPE_INT); signals[OBJECTIFIED] = g_signal_new ("objectified", G_OBJECT_CLASS_TYPE (mobject_class), G_SIGNAL_RUN_LAST | G_SIGNAL_DETAILED, 0, NULL, NULL, g_cclosure_marshal_VOID__OBJECT, G_TYPE_NONE, 1, G_TYPE_OBJECT); signals[SIG0] = g_signal_new ("sig0", G_OBJECT_CLASS_TYPE (mobject_class), G_SIGNAL_RUN_LAST | G_SIGNAL_DETAILED, 0, NULL, NULL, NULL, G_TYPE_NONE, 3, G_TYPE_STRING, G_TYPE_INT, G_TYPE_STRING); signals[SIG1] = g_signal_new ("sig1", G_OBJECT_CLASS_TYPE (mobject_class), G_SIGNAL_RUN_LAST | G_SIGNAL_DETAILED, 0, NULL, NULL, NULL, G_TYPE_NONE, 2, G_TYPE_STRING, G_TYPE_VALUE); signals[SIG2] = g_signal_new ("sig2", G_OBJECT_CLASS_TYPE (mobject_class), G_SIGNAL_RUN_LAST | G_SIGNAL_DETAILED, 0, NULL, NULL, g_cclosure_marshal_VOID__BOXED, G_TYPE_NONE, 1, DBUS_TYPE_G_STRING_STRING_HASHTABLE); } GQuark my_object_error_quark (void) { static GQuark quark = 0; if (!quark) quark = g_quark_from_static_string ("my_object_error"); return quark; } /* This should really be standard. */ #define ENUM_ENTRY(NAME, DESC) { NAME, "" #NAME "", DESC } GType my_object_error_get_type (void) { static GType etype = 0; if (etype == 0) { static const GEnumValue values[] = { ENUM_ENTRY (MY_OBJECT_ERROR_FOO, "Foo"), ENUM_ENTRY (MY_OBJECT_ERROR_BAR, "Bar"), ENUM_ENTRY (MY_OBJECT_ERROR_MULTI_WORD, "Multi-word"), ENUM_ENTRY (MY_OBJECT_ERROR_UNDER_SCORE, "Under_score"), { 0, 0, 0 } }; etype = g_enum_register_static ("MyObjectError", values); } return etype; } gboolean my_object_do_nothing (MyObject *obj, GError **error) { return TRUE; } gboolean my_object_increment (MyObject *obj, gint32 x, gint32 *ret, GError **error) { *ret = x +1; return TRUE; } gint32 my_object_increment_retval (MyObject *obj, gint32 x) { return x + 1; } gint32 my_object_increment_retval_error (MyObject *obj, gint32 x, GError **error) { if (x + 1 > 10) { g_set_error (error, MY_OBJECT_ERROR, MY_OBJECT_ERROR_FOO, "%s", "x is bigger than 9"); return FALSE; } return x + 1; } void my_object_save_error (MyObject *obj, GQuark domain, gint code, const gchar *message) { g_clear_error (&obj->saved_error); g_set_error_literal (&obj->saved_error, domain, code, message); } gboolean my_object_throw_error (MyObject *obj, GError **error) { g_set_error_literal (error, obj->saved_error->domain, obj->saved_error->code, obj->saved_error->message); return FALSE; } gboolean my_object_throw_unregistered_error (MyObject *obj, GError **error) { /* Unregistered errors shouldn't cause a dbus abort. See * https://bugzilla.redhat.com/show_bug.cgi?id=581794 * * This is arguably invalid usage - a domain of 0 (which stringifies * to NULL) is meaningless. (See GNOME#660731.) * * We can't just use my_object_save_error() and ThrowError() for * this, because g_error_new() is stricter about the domain than * g_error_new_valist(). Perhaps this method should be removed entirely, * though. */ g_set_error (error, 0, 0, "%s", "this method always loses more"); return FALSE; } gboolean my_object_uppercase (MyObject *obj, const char *str, char **ret, GError **error) { *ret = g_ascii_strup (str, -1); return TRUE; } gboolean my_object_many_args (MyObject *obj, guint32 x, const char *str, double trouble, double *d_ret, char **str_ret, GError **error) { *d_ret = trouble + (x * 2); *str_ret = g_ascii_strup (str, -1); return TRUE; } gboolean my_object_many_return (MyObject *obj, guint32 *arg0, char **arg1, gint32 *arg2, guint32 *arg3, guint32 *arg4, const char **arg5, GError **error) { *arg0 = 42; *arg1 = g_strdup ("42"); *arg2 = -67; *arg3 = 2; *arg4 = 26; *arg5 = "hello world"; /* Annotation specifies as const */ return TRUE; } gboolean my_object_stringify (MyObject *obj, GValue *value, char **ret, GError **error) { GValue valstr = {0, }; g_value_init (&valstr, G_TYPE_STRING); if (!g_value_transform (value, &valstr)) { g_set_error (error, MY_OBJECT_ERROR, MY_OBJECT_ERROR_FOO, "couldn't transform value"); return FALSE; } *ret = g_value_dup_string (&valstr); g_value_unset (&valstr); return TRUE; } gboolean my_object_unstringify (MyObject *obj, const char *str, GValue *value, GError **error) { if (str[0] == '\0' || !g_ascii_isdigit (str[0])) { g_value_init (value, G_TYPE_STRING); g_value_set_string (value, str); } else { g_value_init (value, G_TYPE_INT); g_value_set_int (value, (int) g_ascii_strtoull (str, NULL, 10)); } return TRUE; } gboolean my_object_recursive1 (MyObject *obj, GArray *array, guint32 *len_ret, GError **error) { *len_ret = array->len; return TRUE; } gboolean my_object_recursive2 (MyObject *obj, guint32 reqlen, GArray **ret, GError **error) { guint32 val; GArray *array; array = g_array_new (FALSE, TRUE, sizeof (guint32)); while (reqlen > 0) { val = 42; g_array_append_val (array, val); val = 26; g_array_append_val (array, val); reqlen--; } val = 2; g_array_append_val (array, val); *ret = array; return TRUE; } gboolean my_object_many_uppercase (MyObject *obj, const char * const *in, char ***out, GError **error) { int len; int i; len = g_strv_length ((char**) in); *out = g_new0 (char *, len + 1); for (i = 0; i < len; i++) { (*out)[i] = g_ascii_strup (in[i], -1); } (*out)[i] = NULL; return TRUE; } static void hash_foreach_stringify (gpointer key, gpointer val, gpointer user_data) { const char *keystr = key; const GValue *value = val; GValue *sval; GHashTable *ret = user_data; sval = g_new0 (GValue, 1); g_value_init (sval, G_TYPE_STRING); if (!g_value_transform (value, sval)) g_assert_not_reached (); g_hash_table_insert (ret, g_strdup (keystr), sval); } static void unset_and_free_gvalue (gpointer val) { g_value_unset (val); g_free (val); } gboolean my_object_many_stringify (MyObject *obj, GHashTable /* char * -> GValue * */ *vals, GHashTable /* char * -> GValue * */ **ret, GError **error) { *ret = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, unset_and_free_gvalue); g_hash_table_foreach (vals, hash_foreach_stringify, *ret); return TRUE; } gboolean my_object_rec_arrays (MyObject *obj, GPtrArray *in, GPtrArray **ret, GError **error) { char **strs; GArray *ints; guint v_UINT; if (in->len != 2) { g_set_error (error, MY_OBJECT_ERROR, MY_OBJECT_ERROR_FOO, "invalid array len"); return FALSE; } strs = g_ptr_array_index (in, 0); if (!*strs || strcmp (*strs, "foo")) { g_set_error (error, MY_OBJECT_ERROR, MY_OBJECT_ERROR_FOO, "invalid string 0"); return FALSE; } strs++; if (!*strs || strcmp (*strs, "bar")) { g_set_error (error, MY_OBJECT_ERROR, MY_OBJECT_ERROR_FOO, "invalid string 1"); return FALSE; } strs++; if (*strs) { g_set_error (error, MY_OBJECT_ERROR, MY_OBJECT_ERROR_FOO, "invalid string array len in pos 0"); return FALSE; } strs = g_ptr_array_index (in, 1); if (!*strs || strcmp (*strs, "baz")) { g_set_error (error, MY_OBJECT_ERROR, MY_OBJECT_ERROR_FOO, "invalid string 0"); return FALSE; } strs++; if (!*strs || strcmp (*strs, "whee")) { g_set_error (error, MY_OBJECT_ERROR, MY_OBJECT_ERROR_FOO, "invalid string 1"); return FALSE; } strs++; if (!*strs || strcmp (*strs, "moo")) { g_set_error (error, MY_OBJECT_ERROR, MY_OBJECT_ERROR_FOO, "invalid string 2"); return FALSE; } strs++; if (*strs) { g_set_error (error, MY_OBJECT_ERROR, MY_OBJECT_ERROR_FOO, "invalid string array len in pos 1"); return FALSE; } *ret = g_ptr_array_new (); ints = g_array_new (TRUE, TRUE, sizeof (guint)); v_UINT = 10; g_array_append_val (ints, v_UINT); v_UINT = 42; g_array_append_val (ints, v_UINT); v_UINT = 27; g_array_append_val (ints, v_UINT); g_ptr_array_add (*ret, ints); ints = g_array_new (TRUE, TRUE, sizeof (guint)); v_UINT = 30; g_array_append_val (ints, v_UINT); g_ptr_array_add (*ret, ints); return TRUE; } gboolean my_object_objpath (MyObject *obj, const char *incoming, const char **outgoing, GError **error) { if (strcmp (incoming, "/org/freedesktop/DBus/GLib/Tests/MyTestObject")) { g_set_error (error, MY_OBJECT_ERROR, MY_OBJECT_ERROR_FOO, "invalid incoming object"); return FALSE; } *outgoing = "/org/freedesktop/DBus/GLib/Tests/MyTestObject2"; return TRUE; } gboolean my_object_get_objs (MyObject *obj, GPtrArray **objs, GError **error) { *objs = g_ptr_array_new (); g_ptr_array_add (*objs, g_strdup ("/org/freedesktop/DBus/GLib/Tests/MyTestObject")); g_ptr_array_add (*objs, g_strdup ("/org/freedesktop/DBus/GLib/Tests/MyTestObject2")); return TRUE; } static void hash_foreach (gpointer key, gpointer val, gpointer user_data) { const char *keystr = key; const char *valstr = val; guint *count = user_data; *count += (strlen (keystr) + strlen (valstr)); g_print ("%s -> %s\n", keystr, valstr); } gboolean my_object_str_hash_len (MyObject *obj, GHashTable *table, guint *len, GError **error) { *len = 0; g_hash_table_foreach (table, hash_foreach, len); return TRUE; } gboolean my_object_send_car (MyObject *obj, GValueArray *invals, GValueArray **outvals, GError **error) { if (invals->n_values != 3 || G_VALUE_TYPE (g_value_array_get_nth (invals, 0)) != G_TYPE_STRING || G_VALUE_TYPE (g_value_array_get_nth (invals, 1)) != G_TYPE_UINT || G_VALUE_TYPE (g_value_array_get_nth (invals, 2)) != G_TYPE_VALUE) { g_set_error (error, MY_OBJECT_ERROR, MY_OBJECT_ERROR_FOO, "invalid incoming values"); return FALSE; } *outvals = g_value_array_new (2); g_value_array_append (*outvals, NULL); g_value_init (g_value_array_get_nth (*outvals, (*outvals)->n_values - 1), G_TYPE_UINT); g_value_set_uint (g_value_array_get_nth (*outvals, (*outvals)->n_values - 1), g_value_get_uint (g_value_array_get_nth (invals, 1)) + 1); g_value_array_append (*outvals, NULL); g_value_init (g_value_array_get_nth (*outvals, (*outvals)->n_values - 1), DBUS_TYPE_G_OBJECT_PATH); g_value_set_boxed (g_value_array_get_nth (*outvals, (*outvals)->n_values - 1), g_strdup ("/org/freedesktop/DBus/GLib/Tests/MyTestObject2")); return TRUE; } gboolean my_object_get_hash (MyObject *obj, GHashTable **ret, GError **error) { GHashTable *table; table = g_hash_table_new (g_str_hash, g_str_equal); g_hash_table_insert (table, "foo", "bar"); g_hash_table_insert (table, "baz", "whee"); g_hash_table_insert (table, "cow", "crack"); *ret = table; return TRUE; } gboolean my_object_increment_val (MyObject *obj, GError **error) { obj->val++; return TRUE; } gboolean my_object_get_val (MyObject *obj, guint *ret, GError **error) { *ret = obj->val; return TRUE; } gboolean my_object_get_value (MyObject *obj, guint *ret, GError **error) { *ret = obj->val; return TRUE; } gboolean my_object_echo_variant (MyObject *obj, GValue *variant, GValue *ret, GError **error) { GType t; obj->echo_variant_called++; t = G_VALUE_TYPE(variant); g_value_init (ret, t); g_value_copy (variant, ret); return TRUE; } gboolean my_object_echo_signature (MyObject *obj, const gchar *in, gchar **out, GError **error) { *out = g_strdup (in); return TRUE; } gboolean my_object_process_variant_of_array_of_ints123 (MyObject *obj, GValue *variant, GError **error) { GArray *array; int i; int j; j = 0; array = (GArray *)g_value_get_boxed (variant); for (i = 0; i <= 2; i++) { j = g_array_index (array, int, i); if (j != i + 1) goto error; } return TRUE; error: *error = g_error_new (MY_OBJECT_ERROR, MY_OBJECT_ERROR_FOO, "Error decoding a variant of type ai (i + 1 = %i, j = %i)", i, j + 1); return FALSE; } typedef struct _HashAndString HashAndString; struct _HashAndString { GHashTable *hash; gchar* string; }; static void hash_foreach_prepend_string (gpointer key, gpointer val, gpointer user_data) { HashAndString *data = (HashAndString*) user_data; gchar *in = (gchar*) val; g_hash_table_insert (data->hash, g_strdup ((gchar*) key), g_strjoin (" ", data->string, in, NULL)); } static void hash_foreach_mangle_dict_of_strings (gpointer key, gpointer val, gpointer user_data) { GHashTable *out = (GHashTable*) user_data; GHashTable *in_dict = (GHashTable *) val; HashAndString *data = g_new0 (HashAndString, 1); data->string = (gchar*) key; data->hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free); g_hash_table_foreach (in_dict, hash_foreach_prepend_string, data); g_hash_table_insert(out, g_strdup ((gchar*) key), data->hash); } gboolean my_object_dict_of_dicts (MyObject *obj, GHashTable *in, GHashTable **out, GError **error) { *out = g_hash_table_new_full (g_str_hash, g_str_equal, (GDestroyNotify) g_free, (GDestroyNotify) g_hash_table_destroy); g_hash_table_foreach (in, hash_foreach_mangle_dict_of_strings, *out); return TRUE; } void my_object_dict_of_sigs (MyObject *obj, GHashTable *dict, DBusGMethodInvocation *context) { dbus_g_method_return (context, dict); } void my_object_dict_of_objs (MyObject *obj, GHashTable *dict, DBusGMethodInvocation *context) { dbus_g_method_return (context, dict); } gboolean my_object_emit_frobnicate (MyObject *obj, GError **error) { g_signal_emit (obj, signals[FROBNICATE], 0, 42); return TRUE; } gboolean my_object_emit_signals (MyObject *obj, GError **error) { GValue val = {0, }; g_signal_emit (obj, signals[SIG0], 0, "foo", 22, "moo"); g_value_init (&val, G_TYPE_STRING); g_value_set_string (&val, "bar"); g_signal_emit (obj, signals[SIG1], 0, "baz", &val); g_value_unset (&val); return TRUE; } gboolean my_object_emit_signal2 (MyObject *obj, GError **error) { GHashTable *table; table = g_hash_table_new (g_str_hash, g_str_equal); g_hash_table_insert (table, "baz", "cow"); g_hash_table_insert (table, "bar", "foo"); g_signal_emit (obj, signals[SIG2], 0, table); g_hash_table_destroy (table); return TRUE; } typedef struct { gint32 x; DBusGMethodInvocation *context; } IncrementData; static gboolean do_async_increment (IncrementData *data) { gint32 newx = data->x + 1; dbus_g_method_return (data->context, newx); g_free (data); return FALSE; } void my_object_async_increment (MyObject *obj, gint32 x, DBusGMethodInvocation *context) { IncrementData *data = g_new0 (IncrementData, 1); data->x = x; data->context = context; g_idle_add ((GSourceFunc)do_async_increment, data); } typedef struct { GError *error; DBusGMethodInvocation *context; } ErrorData; static gboolean do_async_error (ErrorData *data) { dbus_g_method_return_error (data->context, data->error); g_error_free (data->error); g_free (data); return FALSE; } void my_object_async_throw_error (MyObject *obj, DBusGMethodInvocation *context) { ErrorData *data = g_new0 (ErrorData, 1); data->error = g_error_copy (obj->saved_error); data->context = context; g_idle_add ((GSourceFunc) do_async_error, data); } gboolean my_object_unsafe_disable_legacy_property_access (MyObject *obj, GError **error) { dbus_glib_global_set_disable_legacy_property_access (); return TRUE; } extern GMainLoop *loop; gboolean my_object_terminate (MyObject *obj, GError **error) { g_main_loop_quit (loop); return TRUE; } void my_object_emit_objectified (MyObject *obj, GObject *other) { g_signal_emit (obj, signals[OBJECTIFIED], 0, other); }
24.659065
144
0.633173
[ "object", "transform" ]
14153783e676c8345945dc158ee6c167c8a8b6a1
1,719
h
C
game/events/Spawn.h
ngc92/SpaTacS
c8689b4262171f7169c5600c5251c307915a961c
[ "MIT" ]
null
null
null
game/events/Spawn.h
ngc92/SpaTacS
c8689b4262171f7169c5600c5251c307915a961c
[ "MIT" ]
null
null
null
game/events/Spawn.h
ngc92/SpaTacS
c8689b4262171f7169c5600c5251c307915a961c
[ "MIT" ]
null
null
null
// // Created by erik on 1/2/17. // #ifndef SPATACS_GAME_SPAWN_H #define SPATACS_GAME_SPAWN_H #include <memory> #include "game/Damage.h" #include <vector> #include "game/entity/fwd.h" #include "context.h" //! \todo write tests for this file! namespace spatacs { namespace game { namespace events { class Spawn { public: Spawn(const length_vec& pos, const velocity_vec& vel); virtual ~Spawn() = default; protected: GameEntityHandle spawn(EventContext& context) const; length_vec mPosition; velocity_vec mVelocity; }; class SpawnProjectile : public Spawn { public: SpawnProjectile(GameEntityID shooter, length_vec pos, velocity_vec vel, mass_t mass, length_t rad, game::Damage dmg); void apply(EventContext& context) const; private: GameEntityID mShooter; mass_t mMass; length_t mRadius; game::Damage mDamage; }; class SpawnShip : public Spawn { public: SpawnShip(std::uint64_t team, std::string name, std::string type, const length_vec& position); virtual void apply(EventContext& context) const; void addAmmunition(std::string name, std::size_t amount); void setFuel(mass_t f); private: std::uint64_t mTeam; std::string mName; std::string mType; mass_t mFuel = 0.0_kg; struct AmmoData { AmmoData(const std::string& type, size_t amount); std::string type; std::size_t amount; }; std::vector<AmmoData> mAmmo; }; } } } #endif //SPATACS_GAME_SPAWN_H
20.710843
102
0.598604
[ "vector" ]
141e1256ff10de0af9c2f83c727bd4f841d464da
38,826
c
C
src/nvim/api/command.c
JonatanLima/neovim
279bc71f3c24928de7d46034168fa105592eb1fa
[ "Vim" ]
null
null
null
src/nvim/api/command.c
JonatanLima/neovim
279bc71f3c24928de7d46034168fa105592eb1fa
[ "Vim" ]
null
null
null
src/nvim/api/command.c
JonatanLima/neovim
279bc71f3c24928de7d46034168fa105592eb1fa
[ "Vim" ]
null
null
null
// This is an open source non-commercial project. Dear PVS-Studio, please check // it. PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com #include <stdbool.h> #include <stdint.h> #include <stdlib.h> #include "nvim/api/command.h" #include "nvim/api/private/converter.h" #include "nvim/api/private/defs.h" #include "nvim/api/private/helpers.h" #include "nvim/autocmd.h" #include "nvim/ex_docmd.h" #include "nvim/lua/executor.h" #include "nvim/ops.h" #include "nvim/window.h" #ifdef INCLUDE_GENERATED_DECLARATIONS # include "api/command.c.generated.h" #endif /// Parse command line. /// /// Doesn't check the validity of command arguments. /// /// @param str Command line string to parse. Cannot contain "\n". /// @param opts Optional parameters. Reserved for future use. /// @param[out] err Error details, if any. /// @return Dictionary containing command information, with these keys: /// - cmd: (string) Command name. /// - range: (array) Command <range>. Can have 0-2 elements depending on how many items the /// range contains. Has no elements if command doesn't accept a range or if /// no range was specified, one element if only a single range item was /// specified and two elements if both range items were specified. /// - count: (number) Any |<count>| that was supplied to the command. -1 if command cannot /// take a count. /// - reg: (number) The optional command |<register>|, if specified. Empty string if not /// specified or if command cannot take a register. /// - bang: (boolean) Whether command contains a |<bang>| (!) modifier. /// - args: (array) Command arguments. /// - addr: (string) Value of |:command-addr|. Uses short name. /// - nargs: (string) Value of |:command-nargs|. /// - nextcmd: (string) Next command if there are multiple commands separated by a |:bar|. /// Empty if there isn't a next command. /// - magic: (dictionary) Which characters have special meaning in the command arguments. /// - file: (boolean) The command expands filenames. Which means characters such as "%", /// "#" and wildcards are expanded. /// - bar: (boolean) The "|" character is treated as a command separator and the double /// quote character (\") is treated as the start of a comment. /// - mods: (dictionary) |:command-modifiers|. /// - silent: (boolean) |:silent|. /// - emsg_silent: (boolean) |:silent!|. /// - sandbox: (boolean) |:sandbox|. /// - noautocmd: (boolean) |:noautocmd|. /// - browse: (boolean) |:browse|. /// - confirm: (boolean) |:confirm|. /// - hide: (boolean) |:hide|. /// - keepalt: (boolean) |:keepalt|. /// - keepjumps: (boolean) |:keepjumps|. /// - keepmarks: (boolean) |:keepmarks|. /// - keeppatterns: (boolean) |:keeppatterns|. /// - lockmarks: (boolean) |:lockmarks|. /// - noswapfile: (boolean) |:noswapfile|. /// - tab: (integer) |:tab|. /// - verbose: (integer) |:verbose|. -1 when omitted. /// - vertical: (boolean) |:vertical|. /// - split: (string) Split modifier string, is an empty string when there's no split /// modifier. If there is a split modifier it can be one of: /// - "aboveleft": |:aboveleft|. /// - "belowright": |:belowright|. /// - "topleft": |:topleft|. /// - "botright": |:botright|. Dictionary nvim_parse_cmd(String str, Dictionary opts, Error *err) FUNC_API_SINCE(10) FUNC_API_FAST { Dictionary result = ARRAY_DICT_INIT; if (opts.size > 0) { api_set_error(err, kErrorTypeValidation, "opts dict isn't empty"); return result; } // Parse command line exarg_T ea; CmdParseInfo cmdinfo; char *cmdline = string_to_cstr(str); char *errormsg = NULL; if (!parse_cmdline(cmdline, &ea, &cmdinfo, &errormsg)) { if (errormsg != NULL) { api_set_error(err, kErrorTypeException, "Error while parsing command line: %s", errormsg); } else { api_set_error(err, kErrorTypeException, "Error while parsing command line"); } goto end; } // Parse arguments Array args = ARRAY_DICT_INIT; size_t length = STRLEN(ea.arg); // For nargs = 1 or '?', pass the entire argument list as a single argument, // otherwise split arguments by whitespace. if (ea.argt & EX_NOSPC) { if (*ea.arg != NUL) { ADD(args, STRING_OBJ(cstrn_to_string((char *)ea.arg, length))); } } else { size_t end = 0; size_t len = 0; char *buf = xcalloc(length, sizeof(char)); bool done = false; while (!done) { done = uc_split_args_iter(ea.arg, length, &end, buf, &len); if (len > 0) { ADD(args, STRING_OBJ(cstrn_to_string(buf, len))); } } xfree(buf); } ucmd_T *cmd = NULL; if (ea.cmdidx == CMD_USER) { cmd = USER_CMD(ea.useridx); } else if (ea.cmdidx == CMD_USER_BUF) { cmd = USER_CMD_GA(&curbuf->b_ucmds, ea.useridx); } if (cmd != NULL) { PUT(result, "cmd", CSTR_TO_OBJ((char *)cmd->uc_name)); } else { PUT(result, "cmd", CSTR_TO_OBJ((char *)get_command_name(NULL, ea.cmdidx))); } if ((ea.argt & EX_RANGE) && ea.addr_count > 0) { Array range = ARRAY_DICT_INIT; if (ea.addr_count > 1) { ADD(range, INTEGER_OBJ(ea.line1)); } ADD(range, INTEGER_OBJ(ea.line2)); PUT(result, "range", ARRAY_OBJ(range)); } else { PUT(result, "range", ARRAY_OBJ(ARRAY_DICT_INIT)); } if (ea.argt & EX_COUNT) { if (ea.addr_count > 0) { PUT(result, "count", INTEGER_OBJ(ea.line2)); } else if (cmd != NULL) { PUT(result, "count", INTEGER_OBJ(cmd->uc_def)); } else { PUT(result, "count", INTEGER_OBJ(0)); } } else { PUT(result, "count", INTEGER_OBJ(-1)); } char reg[2]; reg[0] = (char)ea.regname; reg[1] = '\0'; PUT(result, "reg", CSTR_TO_OBJ(reg)); PUT(result, "bang", BOOLEAN_OBJ(ea.forceit)); PUT(result, "args", ARRAY_OBJ(args)); char nargs[2]; if (ea.argt & EX_EXTRA) { if (ea.argt & EX_NOSPC) { if (ea.argt & EX_NEEDARG) { nargs[0] = '1'; } else { nargs[0] = '?'; } } else if (ea.argt & EX_NEEDARG) { nargs[0] = '+'; } else { nargs[0] = '*'; } } else { nargs[0] = '0'; } nargs[1] = '\0'; PUT(result, "nargs", CSTR_TO_OBJ(nargs)); const char *addr; switch (ea.addr_type) { case ADDR_LINES: addr = "line"; break; case ADDR_ARGUMENTS: addr = "arg"; break; case ADDR_BUFFERS: addr = "buf"; break; case ADDR_LOADED_BUFFERS: addr = "load"; break; case ADDR_WINDOWS: addr = "win"; break; case ADDR_TABS: addr = "tab"; break; case ADDR_QUICKFIX: addr = "qf"; break; case ADDR_NONE: addr = "none"; break; default: addr = "?"; break; } PUT(result, "addr", CSTR_TO_OBJ(addr)); PUT(result, "nextcmd", CSTR_TO_OBJ((char *)ea.nextcmd)); Dictionary mods = ARRAY_DICT_INIT; PUT(mods, "silent", BOOLEAN_OBJ(cmdinfo.cmdmod.cmod_flags & CMOD_SILENT)); PUT(mods, "emsg_silent", BOOLEAN_OBJ(cmdinfo.cmdmod.cmod_flags & CMOD_ERRSILENT)); PUT(mods, "sandbox", BOOLEAN_OBJ(cmdinfo.cmdmod.cmod_flags & CMOD_SANDBOX)); PUT(mods, "noautocmd", BOOLEAN_OBJ(cmdinfo.cmdmod.cmod_flags & CMOD_NOAUTOCMD)); PUT(mods, "tab", INTEGER_OBJ(cmdinfo.cmdmod.cmod_tab)); PUT(mods, "verbose", INTEGER_OBJ(cmdinfo.cmdmod.cmod_verbose - 1)); PUT(mods, "browse", BOOLEAN_OBJ(cmdinfo.cmdmod.cmod_flags & CMOD_BROWSE)); PUT(mods, "confirm", BOOLEAN_OBJ(cmdinfo.cmdmod.cmod_flags & CMOD_CONFIRM)); PUT(mods, "hide", BOOLEAN_OBJ(cmdinfo.cmdmod.cmod_flags & CMOD_HIDE)); PUT(mods, "keepalt", BOOLEAN_OBJ(cmdinfo.cmdmod.cmod_flags & CMOD_KEEPALT)); PUT(mods, "keepjumps", BOOLEAN_OBJ(cmdinfo.cmdmod.cmod_flags & CMOD_KEEPJUMPS)); PUT(mods, "keepmarks", BOOLEAN_OBJ(cmdinfo.cmdmod.cmod_flags & CMOD_KEEPMARKS)); PUT(mods, "keeppatterns", BOOLEAN_OBJ(cmdinfo.cmdmod.cmod_flags & CMOD_KEEPPATTERNS)); PUT(mods, "lockmarks", BOOLEAN_OBJ(cmdinfo.cmdmod.cmod_flags & CMOD_LOCKMARKS)); PUT(mods, "noswapfile", BOOLEAN_OBJ(cmdinfo.cmdmod.cmod_flags & CMOD_NOSWAPFILE)); PUT(mods, "vertical", BOOLEAN_OBJ(cmdinfo.cmdmod.cmod_split & WSP_VERT)); const char *split; if (cmdinfo.cmdmod.cmod_split & WSP_BOT) { split = "botright"; } else if (cmdinfo.cmdmod.cmod_split & WSP_TOP) { split = "topleft"; } else if (cmdinfo.cmdmod.cmod_split & WSP_BELOW) { split = "belowright"; } else if (cmdinfo.cmdmod.cmod_split & WSP_ABOVE) { split = "aboveleft"; } else { split = ""; } PUT(mods, "split", CSTR_TO_OBJ(split)); PUT(result, "mods", DICTIONARY_OBJ(mods)); Dictionary magic = ARRAY_DICT_INIT; PUT(magic, "file", BOOLEAN_OBJ(cmdinfo.magic.file)); PUT(magic, "bar", BOOLEAN_OBJ(cmdinfo.magic.bar)); PUT(result, "magic", DICTIONARY_OBJ(magic)); end: xfree(cmdline); return result; } /// Executes an Ex command. /// /// Unlike |nvim_command()| this command takes a structured Dictionary instead of a String. This /// allows for easier construction and manipulation of an Ex command. This also allows for things /// such as having spaces inside a command argument, expanding filenames in a command that otherwise /// doesn't expand filenames, etc. /// /// On execution error: fails with VimL error, updates v:errmsg. /// /// @see |nvim_exec()| /// @see |nvim_command()| /// /// @param cmd Command to execute. Must be a Dictionary that can contain the same values as /// the return value of |nvim_parse_cmd()| except "addr", "nargs" and "nextcmd" /// which are ignored if provided. All values except for "cmd" are optional. /// @param opts Optional parameters. /// - output: (boolean, default false) Whether to return command output. /// @param[out] err Error details, if any. /// @return Command output (non-error, non-shell |:!|) if `output` is true, else empty string. String nvim_cmd(uint64_t channel_id, Dict(cmd) *cmd, Dict(cmd_opts) *opts, Error *err) FUNC_API_SINCE(10) { exarg_T ea; memset(&ea, 0, sizeof(ea)); CmdParseInfo cmdinfo; memset(&cmdinfo, 0, sizeof(cmdinfo)); char *cmdline = NULL; char *cmdname = NULL; char **args = NULL; size_t argc = 0; String retv = (String)STRING_INIT; #define OBJ_TO_BOOL(var, value, default, varname) \ do { \ (var) = api_object_to_bool(value, varname, default, err); \ if (ERROR_SET(err)) { \ goto end; \ } \ } while (0) #define OBJ_TO_CMOD_FLAG(flag, value, default, varname) \ do { \ if (api_object_to_bool(value, varname, default, err)) { \ cmdinfo.cmdmod.cmod_flags |= (flag); \ } \ if (ERROR_SET(err)) { \ goto end; \ } \ } while (0) #define VALIDATION_ERROR(...) \ do { \ api_set_error(err, kErrorTypeValidation, __VA_ARGS__); \ goto end; \ } while (0) bool output; OBJ_TO_BOOL(output, opts->output, false, "'output'"); // First, parse the command name and check if it exists and is valid. if (!HAS_KEY(cmd->cmd) || cmd->cmd.type != kObjectTypeString || cmd->cmd.data.string.data[0] == NUL) { VALIDATION_ERROR("'cmd' must be a non-empty String"); } cmdname = string_to_cstr(cmd->cmd.data.string); ea.cmd = cmdname; char *p = find_ex_command(&ea, NULL); // If this looks like an undefined user command and there are CmdUndefined // autocommands defined, trigger the matching autocommands. if (p != NULL && ea.cmdidx == CMD_SIZE && ASCII_ISUPPER(*ea.cmd) && has_event(EVENT_CMDUNDEFINED)) { p = xstrdup(cmdname); int ret = apply_autocmds(EVENT_CMDUNDEFINED, p, p, true, NULL); xfree(p); // If the autocommands did something and didn't cause an error, try // finding the command again. p = (ret && !aborting()) ? find_ex_command(&ea, NULL) : ea.cmd; } if (p == NULL || ea.cmdidx == CMD_SIZE) { VALIDATION_ERROR("Command not found: %s", cmdname); } if (is_cmd_ni(ea.cmdidx)) { VALIDATION_ERROR("Command not implemented: %s", cmdname); } // Get the command flags so that we can know what type of arguments the command uses. // Not required for a user command since `find_ex_command` already deals with it in that case. if (!IS_USER_CMDIDX(ea.cmdidx)) { ea.argt = get_cmd_argt(ea.cmdidx); } // Parse command arguments since it's needed to get the command address type. if (HAS_KEY(cmd->args)) { if (cmd->args.type != kObjectTypeArray) { VALIDATION_ERROR("'args' must be an Array"); } // Check if every argument is valid for (size_t i = 0; i < cmd->args.data.array.size; i++) { Object elem = cmd->args.data.array.items[i]; if (elem.type != kObjectTypeString) { VALIDATION_ERROR("Command argument must be a String"); } else if (string_iswhite(elem.data.string)) { VALIDATION_ERROR("Command argument must have non-whitespace characters"); } } argc = cmd->args.data.array.size; bool argc_valid; // Check if correct number of arguments is used. switch (ea.argt & (EX_EXTRA | EX_NOSPC | EX_NEEDARG)) { case EX_EXTRA | EX_NOSPC | EX_NEEDARG: argc_valid = argc == 1; break; case EX_EXTRA | EX_NOSPC: argc_valid = argc <= 1; break; case EX_EXTRA | EX_NEEDARG: argc_valid = argc >= 1; break; case EX_EXTRA: argc_valid = true; break; default: argc_valid = argc == 0; break; } if (!argc_valid) { argc = 0; // Ensure that args array isn't erroneously freed at the end. VALIDATION_ERROR("Incorrect number of arguments supplied"); } if (argc != 0) { args = xcalloc(argc, sizeof(char *)); for (size_t i = 0; i < argc; i++) { args[i] = string_to_cstr(cmd->args.data.array.items[i].data.string); } } } // Simply pass the first argument (if it exists) as the arg pointer to `set_cmd_addr_type()` // since it only ever checks the first argument. set_cmd_addr_type(&ea, argc > 0 ? (char_u *)args[0] : NULL); if (HAS_KEY(cmd->range)) { if (!(ea.argt & EX_RANGE)) { VALIDATION_ERROR("Command cannot accept a range"); } else if (cmd->range.type != kObjectTypeArray) { VALIDATION_ERROR("'range' must be an Array"); } else if (cmd->range.data.array.size > 2) { VALIDATION_ERROR("'range' cannot contain more than two elements"); } Array range = cmd->range.data.array; ea.addr_count = (int)range.size; for (size_t i = 0; i < range.size; i++) { Object elem = range.items[i]; if (elem.type != kObjectTypeInteger || elem.data.integer < 0) { VALIDATION_ERROR("'range' element must be a non-negative Integer"); } } if (range.size > 0) { ea.line1 = (linenr_T)range.items[0].data.integer; ea.line2 = (linenr_T)range.items[range.size - 1].data.integer; } if (invalid_range(&ea) != NULL) { VALIDATION_ERROR("Invalid range provided"); } } if (ea.addr_count == 0) { if (ea.argt & EX_DFLALL) { set_cmd_dflall_range(&ea); // Default range for range=% } else { ea.line1 = ea.line2 = get_cmd_default_range(&ea); // Default range. if (ea.addr_type == ADDR_OTHER) { // Default is 1, not cursor. ea.line2 = 1; } } } if (HAS_KEY(cmd->count)) { if (!(ea.argt & EX_COUNT)) { VALIDATION_ERROR("Command cannot accept a count"); } else if (cmd->count.type != kObjectTypeInteger || cmd->count.data.integer < 0) { VALIDATION_ERROR("'count' must be a non-negative Integer"); } set_cmd_count(&ea, cmd->count.data.integer, true); } if (HAS_KEY(cmd->reg)) { if (!(ea.argt & EX_REGSTR)) { VALIDATION_ERROR("Command cannot accept a register"); } else if (cmd->reg.type != kObjectTypeString || cmd->reg.data.string.size != 1) { VALIDATION_ERROR("'reg' must be a single character"); } char regname = cmd->reg.data.string.data[0]; if (regname == '=') { VALIDATION_ERROR("Cannot use register \"="); } else if (!valid_yank_reg(regname, ea.cmdidx != CMD_put && !IS_USER_CMDIDX(ea.cmdidx))) { VALIDATION_ERROR("Invalid register: \"%c", regname); } ea.regname = (uint8_t)regname; } OBJ_TO_BOOL(ea.forceit, cmd->bang, false, "'bang'"); if (ea.forceit && !(ea.argt & EX_BANG)) { VALIDATION_ERROR("Command cannot accept a bang"); } if (HAS_KEY(cmd->magic)) { if (cmd->magic.type != kObjectTypeDictionary) { VALIDATION_ERROR("'magic' must be a Dictionary"); } Dict(cmd_magic) magic = { 0 }; if (!api_dict_to_keydict(&magic, KeyDict_cmd_magic_get_field, cmd->magic.data.dictionary, err)) { goto end; } OBJ_TO_BOOL(cmdinfo.magic.file, magic.file, ea.argt & EX_XFILE, "'magic.file'"); OBJ_TO_BOOL(cmdinfo.magic.bar, magic.bar, ea.argt & EX_TRLBAR, "'magic.bar'"); } else { cmdinfo.magic.file = ea.argt & EX_XFILE; cmdinfo.magic.bar = ea.argt & EX_TRLBAR; } if (HAS_KEY(cmd->mods)) { if (cmd->mods.type != kObjectTypeDictionary) { VALIDATION_ERROR("'mods' must be a Dictionary"); } Dict(cmd_mods) mods = { 0 }; if (!api_dict_to_keydict(&mods, KeyDict_cmd_mods_get_field, cmd->mods.data.dictionary, err)) { goto end; } if (HAS_KEY(mods.tab)) { if (mods.tab.type != kObjectTypeInteger || mods.tab.data.integer < 0) { VALIDATION_ERROR("'mods.tab' must be a non-negative Integer"); } cmdinfo.cmdmod.cmod_tab = (int)mods.tab.data.integer + 1; } if (HAS_KEY(mods.verbose)) { if (mods.verbose.type != kObjectTypeInteger) { VALIDATION_ERROR("'mods.verbose' must be a Integer"); } else if ((int)mods.verbose.data.integer >= 0) { // Silently ignore negative integers to allow mods.verbose to be set to -1. cmdinfo.cmdmod.cmod_verbose = (int)mods.verbose.data.integer + 1; } } bool vertical; OBJ_TO_BOOL(vertical, mods.vertical, false, "'mods.vertical'"); cmdinfo.cmdmod.cmod_split |= (vertical ? WSP_VERT : 0); if (HAS_KEY(mods.split)) { if (mods.split.type != kObjectTypeString) { VALIDATION_ERROR("'mods.split' must be a String"); } if (*mods.split.data.string.data == NUL) { // Empty string, do nothing. } else if (STRCMP(mods.split.data.string.data, "aboveleft") == 0 || STRCMP(mods.split.data.string.data, "leftabove") == 0) { cmdinfo.cmdmod.cmod_split |= WSP_ABOVE; } else if (STRCMP(mods.split.data.string.data, "belowright") == 0 || STRCMP(mods.split.data.string.data, "rightbelow") == 0) { cmdinfo.cmdmod.cmod_split |= WSP_BELOW; } else if (STRCMP(mods.split.data.string.data, "topleft") == 0) { cmdinfo.cmdmod.cmod_split |= WSP_TOP; } else if (STRCMP(mods.split.data.string.data, "botright") == 0) { cmdinfo.cmdmod.cmod_split |= WSP_BOT; } else { VALIDATION_ERROR("Invalid value for 'mods.split'"); } } OBJ_TO_CMOD_FLAG(CMOD_SILENT, mods.silent, false, "'mods.silent'"); OBJ_TO_CMOD_FLAG(CMOD_ERRSILENT, mods.emsg_silent, false, "'mods.emsg_silent'"); OBJ_TO_CMOD_FLAG(CMOD_SANDBOX, mods.sandbox, false, "'mods.sandbox'"); OBJ_TO_CMOD_FLAG(CMOD_NOAUTOCMD, mods.noautocmd, false, "'mods.noautocmd'"); OBJ_TO_CMOD_FLAG(CMOD_BROWSE, mods.browse, false, "'mods.browse'"); OBJ_TO_CMOD_FLAG(CMOD_CONFIRM, mods.confirm, false, "'mods.confirm'"); OBJ_TO_CMOD_FLAG(CMOD_HIDE, mods.hide, false, "'mods.hide'"); OBJ_TO_CMOD_FLAG(CMOD_KEEPALT, mods.keepalt, false, "'mods.keepalt'"); OBJ_TO_CMOD_FLAG(CMOD_KEEPJUMPS, mods.keepjumps, false, "'mods.keepjumps'"); OBJ_TO_CMOD_FLAG(CMOD_KEEPMARKS, mods.keepmarks, false, "'mods.keepmarks'"); OBJ_TO_CMOD_FLAG(CMOD_KEEPPATTERNS, mods.keeppatterns, false, "'mods.keeppatterns'"); OBJ_TO_CMOD_FLAG(CMOD_LOCKMARKS, mods.lockmarks, false, "'mods.lockmarks'"); OBJ_TO_CMOD_FLAG(CMOD_NOSWAPFILE, mods.noswapfile, false, "'mods.noswapfile'"); if ((cmdinfo.cmdmod.cmod_flags & CMOD_SANDBOX) && !(ea.argt & EX_SBOXOK)) { VALIDATION_ERROR("Command cannot be run in sandbox"); } } // Finally, build the command line string that will be stored inside ea.cmdlinep. // This also sets the values of ea.cmd, ea.arg, ea.args and ea.arglens. build_cmdline_str(&cmdline, &ea, &cmdinfo, args, argc); ea.cmdlinep = &cmdline; garray_T capture_local; const int save_msg_silent = msg_silent; garray_T * const save_capture_ga = capture_ga; if (output) { ga_init(&capture_local, 1, 80); capture_ga = &capture_local; } TRY_WRAP({ try_start(); if (output) { msg_silent++; } WITH_SCRIPT_CONTEXT(channel_id, { execute_cmd(&ea, &cmdinfo, false); }); if (output) { capture_ga = save_capture_ga; msg_silent = save_msg_silent; } try_end(err); }); if (ERROR_SET(err)) { goto clear_ga; } if (output && capture_local.ga_len > 1) { retv = (String){ .data = capture_local.ga_data, .size = (size_t)capture_local.ga_len, }; // redir usually (except :echon) prepends a newline. if (retv.data[0] == '\n') { memmove(retv.data, retv.data + 1, retv.size - 1); retv.data[retv.size - 1] = '\0'; retv.size = retv.size - 1; } goto end; } clear_ga: if (output) { ga_clear(&capture_local); } end: xfree(cmdline); xfree(cmdname); xfree(ea.args); xfree(ea.arglens); for (size_t i = 0; i < argc; i++) { xfree(args[i]); } xfree(args); return retv; #undef OBJ_TO_BOOL #undef OBJ_TO_CMOD_FLAG #undef VALIDATION_ERROR } /// Check if a string contains only whitespace characters. static bool string_iswhite(String str) { for (size_t i = 0; i < str.size; i++) { if (!ascii_iswhite(str.data[i])) { // Found a non-whitespace character return false; } else if (str.data[i] == NUL) { // Terminate at first occurrence of a NUL character break; } } return true; } /// Build cmdline string for command, used by `nvim_cmd()`. /// /// @return OK or FAIL. static void build_cmdline_str(char **cmdlinep, exarg_T *eap, CmdParseInfo *cmdinfo, char **args, size_t argc) { StringBuilder cmdline = KV_INITIAL_VALUE; // Add command modifiers if (cmdinfo->cmdmod.cmod_tab != 0) { kv_printf(cmdline, "%dtab ", cmdinfo->cmdmod.cmod_tab - 1); } if (cmdinfo->cmdmod.cmod_verbose > 0) { kv_printf(cmdline, "%dverbose ", cmdinfo->cmdmod.cmod_verbose - 1); } if (cmdinfo->cmdmod.cmod_flags & CMOD_ERRSILENT) { kv_concat(cmdline, "silent! "); } else if (cmdinfo->cmdmod.cmod_flags & CMOD_SILENT) { kv_concat(cmdline, "silent "); } switch (cmdinfo->cmdmod.cmod_split & (WSP_ABOVE | WSP_BELOW | WSP_TOP | WSP_BOT)) { case WSP_ABOVE: kv_concat(cmdline, "aboveleft "); break; case WSP_BELOW: kv_concat(cmdline, "belowright "); break; case WSP_TOP: kv_concat(cmdline, "topleft "); break; case WSP_BOT: kv_concat(cmdline, "botright "); break; default: break; } #define CMDLINE_APPEND_IF(cond, str) \ do { \ if (cond) { \ kv_concat(cmdline, str); \ } \ } while (0) CMDLINE_APPEND_IF(cmdinfo->cmdmod.cmod_split & WSP_VERT, "vertical "); CMDLINE_APPEND_IF(cmdinfo->cmdmod.cmod_flags & CMOD_SANDBOX, "sandbox "); CMDLINE_APPEND_IF(cmdinfo->cmdmod.cmod_flags & CMOD_NOAUTOCMD, "noautocmd "); CMDLINE_APPEND_IF(cmdinfo->cmdmod.cmod_flags & CMOD_BROWSE, "browse "); CMDLINE_APPEND_IF(cmdinfo->cmdmod.cmod_flags & CMOD_CONFIRM, "confirm "); CMDLINE_APPEND_IF(cmdinfo->cmdmod.cmod_flags & CMOD_HIDE, "hide "); CMDLINE_APPEND_IF(cmdinfo->cmdmod.cmod_flags & CMOD_KEEPALT, "keepalt "); CMDLINE_APPEND_IF(cmdinfo->cmdmod.cmod_flags & CMOD_KEEPJUMPS, "keepjumps "); CMDLINE_APPEND_IF(cmdinfo->cmdmod.cmod_flags & CMOD_KEEPMARKS, "keepmarks "); CMDLINE_APPEND_IF(cmdinfo->cmdmod.cmod_flags & CMOD_KEEPPATTERNS, "keeppatterns "); CMDLINE_APPEND_IF(cmdinfo->cmdmod.cmod_flags & CMOD_LOCKMARKS, "lockmarks "); CMDLINE_APPEND_IF(cmdinfo->cmdmod.cmod_flags & CMOD_NOSWAPFILE, "noswapfile "); #undef CMDLINE_APPEND_IF // Command range / count. if (eap->argt & EX_RANGE) { if (eap->addr_count == 1) { kv_printf(cmdline, "%" PRIdLINENR, eap->line2); } else if (eap->addr_count > 1) { kv_printf(cmdline, "%" PRIdLINENR ",%" PRIdLINENR, eap->line1, eap->line2); eap->addr_count = 2; // Make sure address count is not greater than 2 } } // Keep the index of the position where command name starts, so eap->cmd can point to it. size_t cmdname_idx = cmdline.size; kv_printf(cmdline, "%s", eap->cmd); // Command bang. if (eap->argt & EX_BANG && eap->forceit) { kv_printf(cmdline, "!"); } // Command register. if (eap->argt & EX_REGSTR && eap->regname) { kv_printf(cmdline, " %c", eap->regname); } // Iterate through each argument and store the starting index and length of each argument size_t *argidx = xcalloc(argc, sizeof(size_t)); eap->argc = argc; eap->arglens = xcalloc(argc, sizeof(size_t)); for (size_t i = 0; i < argc; i++) { argidx[i] = cmdline.size + 1; // add 1 to account for the space. eap->arglens[i] = STRLEN(args[i]); kv_printf(cmdline, " %s", args[i]); } // Now that all the arguments are appended, use the command index and argument indices to set the // values of eap->cmd, eap->arg and eap->args. eap->cmd = cmdline.items + cmdname_idx; eap->args = xcalloc(argc, sizeof(char *)); for (size_t i = 0; i < argc; i++) { eap->args[i] = cmdline.items + argidx[i]; } // If there isn't an argument, make eap->arg point to end of cmdline. eap->arg = argc > 0 ? eap->args[0] : cmdline.items + cmdline.size; // Finally, make cmdlinep point to the cmdline string. *cmdlinep = cmdline.items; xfree(argidx); // Replace, :make and :grep with 'makeprg' and 'grepprg'. char *p = replace_makeprg(eap, eap->arg, cmdlinep); if (p != eap->arg) { // If replace_makeprg modified the cmdline string, correct the argument pointers. assert(argc == 1); eap->arg = p; eap->args[0] = p; } } /// Create a new user command |user-commands| /// /// {name} is the name of the new command. The name must begin with an uppercase letter. /// /// {command} is the replacement text or Lua function to execute. /// /// Example: /// <pre> /// :call nvim_create_user_command('SayHello', 'echo "Hello world!"', {}) /// :SayHello /// Hello world! /// </pre> /// /// @param name Name of the new user command. Must begin with an uppercase letter. /// @param command Replacement command to execute when this user command is executed. When called /// from Lua, the command can also be a Lua function. The function is called with a /// single table argument that contains the following keys: /// - args: (string) The args passed to the command, if any |<args>| /// - fargs: (table) The args split by unescaped whitespace (when more than one /// argument is allowed), if any |<f-args>| /// - bang: (boolean) "true" if the command was executed with a ! modifier |<bang>| /// - line1: (number) The starting line of the command range |<line1>| /// - line2: (number) The final line of the command range |<line2>| /// - range: (number) The number of items in the command range: 0, 1, or 2 |<range>| /// - count: (number) Any count supplied |<count>| /// - reg: (string) The optional register, if specified |<reg>| /// - mods: (string) Command modifiers, if any |<mods>| /// - smods: (table) Command modifiers in a structured format. Has the same /// structure as the "mods" key of |nvim_parse_cmd()|. /// @param opts Optional command attributes. See |command-attributes| for more details. To use /// boolean attributes (such as |:command-bang| or |:command-bar|) set the value to /// "true". In addition to the string options listed in |:command-complete|, the /// "complete" key also accepts a Lua function which works like the "customlist" /// completion mode |:command-completion-customlist|. Additional parameters: /// - desc: (string) Used for listing the command when a Lua function is used for /// {command}. /// - force: (boolean, default true) Override any previous definition. /// - preview: (function) Preview callback for 'inccommand' |:command-preview| /// @param[out] err Error details, if any. void nvim_create_user_command(String name, Object command, Dict(user_command) *opts, Error *err) FUNC_API_SINCE(9) { create_user_command(name, command, opts, 0, err); } /// Delete a user-defined command. /// /// @param name Name of the command to delete. /// @param[out] err Error details, if any. void nvim_del_user_command(String name, Error *err) FUNC_API_SINCE(9) { nvim_buf_del_user_command(-1, name, err); } /// Create a new user command |user-commands| in the given buffer. /// /// @param buffer Buffer handle, or 0 for current buffer. /// @param[out] err Error details, if any. /// @see nvim_create_user_command void nvim_buf_create_user_command(Buffer buffer, String name, Object command, Dict(user_command) *opts, Error *err) FUNC_API_SINCE(9) { buf_T *target_buf = find_buffer_by_handle(buffer, err); if (ERROR_SET(err)) { return; } buf_T *save_curbuf = curbuf; curbuf = target_buf; create_user_command(name, command, opts, UC_BUFFER, err); curbuf = save_curbuf; } /// Delete a buffer-local user-defined command. /// /// Only commands created with |:command-buffer| or /// |nvim_buf_create_user_command()| can be deleted with this function. /// /// @param buffer Buffer handle, or 0 for current buffer. /// @param name Name of the command to delete. /// @param[out] err Error details, if any. void nvim_buf_del_user_command(Buffer buffer, String name, Error *err) FUNC_API_SINCE(9) { garray_T *gap; if (buffer == -1) { gap = &ucmds; } else { buf_T *buf = find_buffer_by_handle(buffer, err); gap = &buf->b_ucmds; } for (int i = 0; i < gap->ga_len; i++) { ucmd_T *cmd = USER_CMD_GA(gap, i); if (!STRCMP(name.data, cmd->uc_name)) { free_ucmd(cmd); gap->ga_len -= 1; if (i < gap->ga_len) { memmove(cmd, cmd + 1, (size_t)(gap->ga_len - i) * sizeof(ucmd_T)); } return; } } api_set_error(err, kErrorTypeException, "No such user-defined command: %s", name.data); } void create_user_command(String name, Object command, Dict(user_command) *opts, int flags, Error *err) { uint32_t argt = 0; long def = -1; cmd_addr_T addr_type_arg = ADDR_NONE; int compl = EXPAND_NOTHING; char *compl_arg = NULL; char *rep = NULL; LuaRef luaref = LUA_NOREF; LuaRef compl_luaref = LUA_NOREF; LuaRef preview_luaref = LUA_NOREF; if (!uc_validate_name(name.data)) { api_set_error(err, kErrorTypeValidation, "Invalid command name"); goto err; } if (mb_islower(name.data[0])) { api_set_error(err, kErrorTypeValidation, "'name' must begin with an uppercase letter"); goto err; } if (HAS_KEY(opts->range) && HAS_KEY(opts->count)) { api_set_error(err, kErrorTypeValidation, "'range' and 'count' are mutually exclusive"); goto err; } if (opts->nargs.type == kObjectTypeInteger) { switch (opts->nargs.data.integer) { case 0: // Default value, nothing to do break; case 1: argt |= EX_EXTRA | EX_NOSPC | EX_NEEDARG; break; default: api_set_error(err, kErrorTypeValidation, "Invalid value for 'nargs'"); goto err; } } else if (opts->nargs.type == kObjectTypeString) { if (opts->nargs.data.string.size > 1) { api_set_error(err, kErrorTypeValidation, "Invalid value for 'nargs'"); goto err; } switch (opts->nargs.data.string.data[0]) { case '*': argt |= EX_EXTRA; break; case '?': argt |= EX_EXTRA | EX_NOSPC; break; case '+': argt |= EX_EXTRA | EX_NEEDARG; break; default: api_set_error(err, kErrorTypeValidation, "Invalid value for 'nargs'"); goto err; } } else if (HAS_KEY(opts->nargs)) { api_set_error(err, kErrorTypeValidation, "Invalid value for 'nargs'"); goto err; } if (HAS_KEY(opts->complete) && !argt) { api_set_error(err, kErrorTypeValidation, "'complete' used without 'nargs'"); goto err; } if (opts->range.type == kObjectTypeBoolean) { if (opts->range.data.boolean) { argt |= EX_RANGE; addr_type_arg = ADDR_LINES; } } else if (opts->range.type == kObjectTypeString) { if (opts->range.data.string.data[0] == '%' && opts->range.data.string.size == 1) { argt |= EX_RANGE | EX_DFLALL; addr_type_arg = ADDR_LINES; } else { api_set_error(err, kErrorTypeValidation, "Invalid value for 'range'"); goto err; } } else if (opts->range.type == kObjectTypeInteger) { argt |= EX_RANGE | EX_ZEROR; def = opts->range.data.integer; addr_type_arg = ADDR_LINES; } else if (HAS_KEY(opts->range)) { api_set_error(err, kErrorTypeValidation, "Invalid value for 'range'"); goto err; } if (opts->count.type == kObjectTypeBoolean) { if (opts->count.data.boolean) { argt |= EX_COUNT | EX_ZEROR | EX_RANGE; addr_type_arg = ADDR_OTHER; def = 0; } } else if (opts->count.type == kObjectTypeInteger) { argt |= EX_COUNT | EX_ZEROR | EX_RANGE; addr_type_arg = ADDR_OTHER; def = opts->count.data.integer; } else if (HAS_KEY(opts->count)) { api_set_error(err, kErrorTypeValidation, "Invalid value for 'count'"); goto err; } if (opts->addr.type == kObjectTypeString) { if (parse_addr_type_arg(opts->addr.data.string.data, (int)opts->addr.data.string.size, &addr_type_arg) != OK) { api_set_error(err, kErrorTypeValidation, "Invalid value for 'addr'"); goto err; } if (addr_type_arg != ADDR_LINES) { argt |= EX_ZEROR; } } else if (HAS_KEY(opts->addr)) { api_set_error(err, kErrorTypeValidation, "Invalid value for 'addr'"); goto err; } if (api_object_to_bool(opts->bang, "bang", false, err)) { argt |= EX_BANG; } else if (ERROR_SET(err)) { goto err; } if (api_object_to_bool(opts->bar, "bar", false, err)) { argt |= EX_TRLBAR; } else if (ERROR_SET(err)) { goto err; } if (api_object_to_bool(opts->register_, "register", false, err)) { argt |= EX_REGSTR; } else if (ERROR_SET(err)) { goto err; } if (api_object_to_bool(opts->keepscript, "keepscript", false, err)) { argt |= EX_KEEPSCRIPT; } else if (ERROR_SET(err)) { goto err; } bool force = api_object_to_bool(opts->force, "force", true, err); if (ERROR_SET(err)) { goto err; } if (opts->complete.type == kObjectTypeLuaRef) { compl = EXPAND_USER_LUA; compl_luaref = api_new_luaref(opts->complete.data.luaref); } else if (opts->complete.type == kObjectTypeString) { if (parse_compl_arg(opts->complete.data.string.data, (int)opts->complete.data.string.size, &compl, &argt, &compl_arg) != OK) { api_set_error(err, kErrorTypeValidation, "Invalid value for 'complete'"); goto err; } } else if (HAS_KEY(opts->complete)) { api_set_error(err, kErrorTypeValidation, "Invalid value for 'complete'"); goto err; } if (opts->preview.type == kObjectTypeLuaRef) { argt |= EX_PREVIEW; preview_luaref = api_new_luaref(opts->preview.data.luaref); } else if (HAS_KEY(opts->preview)) { api_set_error(err, kErrorTypeValidation, "Invalid value for 'preview'"); goto err; } switch (command.type) { case kObjectTypeLuaRef: luaref = api_new_luaref(command.data.luaref); if (opts->desc.type == kObjectTypeString) { rep = opts->desc.data.string.data; } else { snprintf((char *)IObuff, IOSIZE, "<Lua function %d>", luaref); rep = (char *)IObuff; } break; case kObjectTypeString: rep = command.data.string.data; break; default: api_set_error(err, kErrorTypeValidation, "'command' must be a string or Lua function"); goto err; } if (uc_add_command(name.data, name.size, rep, argt, def, flags, compl, compl_arg, compl_luaref, preview_luaref, addr_type_arg, luaref, force) != OK) { api_set_error(err, kErrorTypeException, "Failed to create user command"); // Do not goto err, since uc_add_command now owns luaref, compl_luaref, and compl_arg } return; err: NLUA_CLEAR_REF(luaref); NLUA_CLEAR_REF(compl_luaref); xfree(compl_arg); } /// Gets a map of global (non-buffer-local) Ex commands. /// /// Currently only |user-commands| are supported, not builtin Ex commands. /// /// @param opts Optional parameters. Currently only supports /// {"builtin":false} /// @param[out] err Error details, if any. /// /// @returns Map of maps describing commands. Dictionary nvim_get_commands(Dict(get_commands) *opts, Error *err) FUNC_API_SINCE(4) { return nvim_buf_get_commands(-1, opts, err); } /// Gets a map of buffer-local |user-commands|. /// /// @param buffer Buffer handle, or 0 for current buffer /// @param opts Optional parameters. Currently not used. /// @param[out] err Error details, if any. /// /// @returns Map of maps describing commands. Dictionary nvim_buf_get_commands(Buffer buffer, Dict(get_commands) *opts, Error *err) FUNC_API_SINCE(4) { bool global = (buffer == -1); bool builtin = api_object_to_bool(opts->builtin, "builtin", false, err); if (ERROR_SET(err)) { return (Dictionary)ARRAY_DICT_INIT; } if (global) { if (builtin) { api_set_error(err, kErrorTypeValidation, "builtin=true not implemented"); return (Dictionary)ARRAY_DICT_INIT; } return commands_array(NULL); } buf_T *buf = find_buffer_by_handle(buffer, err); if (builtin || !buf) { return (Dictionary)ARRAY_DICT_INIT; } return commands_array(buf); }
34.057895
100
0.631149
[ "object" ]