repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
skn123/penguinV
src/math/math_base.h
#pragma once #include <cmath> #include <vector> namespace pvmath { const double pi = std::acos(-1); const double epsilonDouble = 1e-9; const double epsilonFloat = 1e-5f; template <typename _Type> bool isEqual( const _Type & value1, const _Type & value2 ) { return ( value1 == value2 ); } template <typename _Type> bool isEqual( const _Type & value1, const _Type & value2, const _Type ) { return ( value1 == value2 ); } template <> bool isEqual<double>( const double & value1, const double & value2 ); template <> bool isEqual<float>( const float & value1, const float & value2 ); template <> bool isEqual<double>( const double & value1, const double & value2, const double epsilonMultiplier ); template <> bool isEqual<float>( const float & value1, const float & value2, const float epsilonMultiplier ); double toRadians(double angleDegree); double toDegrees(double angleRadians); void getMatrixRoots( const std::vector<double> & squareMatrix, const std::vector<double> freeTerms, std::vector<double> & roots ); } template <typename _Type> struct PointBase2D { PointBase2D( _Type _x = 0, _Type _y = 0 ) : x( _x ) , y( _y ) { } bool operator == ( const PointBase2D & point ) const { return pvmath::isEqual( x, point.x ) && pvmath::isEqual( y, point.y ); } bool operator != ( const PointBase2D & point ) const { return !( *this == point ); } PointBase2D & operator += ( const PointBase2D & point ) { x += point.x; y += point.y; return *this; } PointBase2D & operator -= ( const PointBase2D & point ) { x -= point.x; y -= point.y; return *this; } PointBase2D operator + ( const PointBase2D & point ) const { return PointBase2D( x + point.x, y + point.y ); } PointBase2D operator - ( const PointBase2D & point ) const { return PointBase2D( x - point.x, y - point.y ); } PointBase2D operator * ( const _Type & value ) const { return PointBase2D( value * x, value * y ); } _Type x; _Type y; }; template <typename _Type, typename T> PointBase2D<_Type> operator * ( const T & value, const PointBase2D<_Type> & point ) { return PointBase2D<_Type>( static_cast<_Type>( value ) * point.x, static_cast<_Type>( value ) * point.y ); } template <typename _Type> struct PointBase3D : public PointBase2D<_Type> { PointBase3D( _Type _x = 0, _Type _y = 0, _Type _z = 0 ) : PointBase2D<_Type>( _x, _y ) , z( _z ) { } bool operator == ( const PointBase3D & point ) const { return PointBase2D<_Type>::operator==( point ) && pvmath::isEqual( z, point.z ); } PointBase3D & operator += ( const PointBase3D & point ) { PointBase2D<_Type>::operator+=( point ); z += point.z; return *this; } PointBase3D & operator -= ( const PointBase3D & point ) { PointBase2D<_Type>::operator-=( point ); z -= point.z; return *this; } PointBase3D operator + ( const PointBase3D & point ) const { return PointBase3D( PointBase2D<_Type>::x + point.x, PointBase2D<_Type>::y + point.y, z + point.z ); } PointBase3D operator - ( const PointBase3D & point ) const { return PointBase3D( PointBase2D<_Type>::x - point.x, PointBase2D<_Type>::y - point.y, z - point.z ); } _Type z; }; template <typename _Type> class LineBase2D { public: LineBase2D( const PointBase2D<_Type> & point1 = PointBase2D<_Type>(), const PointBase2D<_Type> & point2 = PointBase2D<_Type>() ) : _position( point1 ) { if ( point1 == point2 ) { _direction = PointBase2D<_Type>( 1, 0 ); // we could raise an exception here instead } else { const _Type xDiff = point2.x - point1.x; const _Type yDiff = point2.y - point1.y; const _Type length = std::sqrt( xDiff * xDiff + yDiff * yDiff ); // here we might need more specific code for non-double cases _direction = PointBase2D<_Type>( xDiff / length, yDiff / length ); } } // Angle is in radians LineBase2D( const PointBase2D<_Type> & position_, _Type angle_ ) : _position( position_ ) , _direction( std::cos(angle_), std::sin(angle_) ) { } bool operator == ( const LineBase2D & line ) const { return parallel( line ) && pvmath::isEqual<_Type>( distance(line._position), 0 ); } // This is translation (shift) function LineBase2D operator + ( const PointBase2D<_Type> & offset ) const { return LineBase2D( _position + offset, angle() ); } LineBase2D & operator += ( const PointBase2D<_Type> & offset ) { _position += offset; return *this; } _Type angle() const { return std::atan2( _direction.y, _direction.x ); } PointBase2D<_Type> position() const { return _position; } bool intersection( const LineBase2D & line, PointBase2D<_Type> & point ) const { // based on Graphics Gems III, Faster Line Segment Intersection, p. 199-202 // http://www.realtimerendering.com/resources/GraphicsGems/gems.html#gemsiii const _Type denominator = _direction.y * line._direction.x - _direction.x * line._direction.y; if ( pvmath::isEqual<_Type>( denominator, 0, 10 ) ) return false; // they are parallel const PointBase2D<_Type> offset = _position - line._position; const _Type na = (line._direction.y * offset.x - line._direction.x * offset.y) / denominator; point = _position + PointBase2D<_Type>( _direction.x * na, _direction.y * na ); return true; } bool isParallel( const LineBase2D & line ) const { const _Type denominator = _direction.y * line._direction.x - _direction.x * line._direction.y; return pvmath::isEqual<_Type>( denominator, 0, 10 ); } bool isIntersect( const LineBase2D & line ) const { return !isParallel( line ); } _Type distance( const PointBase2D<_Type> & point ) const { // Line equation in the Cartesian coordinate system is // y = a * x + b or A * x + B * y + C = 0 // A distance from a point to a line can be calculated as: // |A * x0 + B * y0 + C| / sqrt(A * A + B * B) const _Type distanceToLine = _direction.y * (point.x - _position.x) + _direction.x * (_position.y - point.y); return (distanceToLine < 0 ? -distanceToLine : distanceToLine); } PointBase2D<_Type> projection( const PointBase2D<_Type> & point ) const { const _Type dotProduct = _direction.x * ( point.x - _position.x ) + _direction.y * ( point.y - _position.y ); const PointBase2D<_Type> offset( _direction.x * dotProduct, _direction.y * dotProduct ); return _position + offset; } PointBase2D<_Type> opposite( const PointBase2D<_Type> & point ) const { return 2 * projection( point ) - point; } template <template <typename, typename...> class _container> static LineBase2D bestFittingLine( const _container< PointBase2D<_Type> > & points ) { if ( points.size() < 2 ) return LineBase2D(); _Type sumX = 0; _Type sumY = 0; _Type sumXX = 0; _Type sumYY = 0; _Type sumXY = 0; for ( typename _container< PointBase2D<_Type> >::const_iterator point = points.begin(); point != points.end(); ++point ) { const _Type x = point->x; const _Type y = point->y; sumX += x; sumXX += x * x; sumY += y; sumYY += y * y; sumXY += x * y; } const _Type size = static_cast<_Type>( points.size() ); sumX /= size; sumY /= size; sumXX /= size; sumYY /= size; sumXY /= size; const PointBase2D<_Type> position( sumX, sumY ); const _Type sigmaX = sumXX - sumX * sumX; const _Type sigmaY = sumYY - sumY * sumY; PointBase2D<_Type> direction; if ( sigmaX > sigmaY ) { direction.y = sumXY - sumX * sumY; direction.x = sumXX - sumX * sumX; } else { direction.x = sumXY - sumX * sumY; direction.y = sumYY - sumY * sumY; } return LineBase2D( position, std::atan2( direction.y, direction.x ) ); } private: PointBase2D<_Type> _position; PointBase2D<_Type> _direction; }; typedef PointBase2D<double> Point2d; typedef PointBase3D<double> Point3d; typedef LineBase2D<double> Line2d;
skn123/penguinV
test/performance_tests/performance_test_filtering.h
<filename>test/performance_tests/performance_test_filtering.h #pragma once class PerformanceTestFramework; void addTests_Filtering( PerformanceTestFramework & framework );
skn123/penguinV
src/thread_pool.h
<filename>src/thread_pool.h<gh_stars>100-1000 #pragma once #include <atomic> #include <condition_variable> #include <cstdint> #include <list> #include <mutex> #include <thread> #include <vector> class ThreadPool; // General abstract class to work with thread pool class AbstractTaskProvider { public: friend class ThreadPool; friend class TaskProvider; friend class TaskProviderSingleton; AbstractTaskProvider(); AbstractTaskProvider( const AbstractTaskProvider & ); virtual ~AbstractTaskProvider(); AbstractTaskProvider & operator=( const AbstractTaskProvider & ); protected: virtual void _task( size_t ) = 0; // this function must be overrided in child class and should contain a code specific to task ID // parameter in the function is task ID. This function must be called by thread pool bool _wait(); // waits for all task execution completions. Returns true in case of success, false when an exception is raised bool _ready() const; // this function tells whether class is able to use thread pool private: std::atomic < size_t > _taskCount; // number of tasks to do std::atomic < size_t > _givenTaskCount; // number of tasks which were given to thread pool std::atomic < size_t > _completedTaskCount; // number of completed tasks bool _running; // boolean variable specifies the state of tasks processing std::mutex _completion; // mutex for synchronization reporting about completion of all tasks // this mutex is waited in _wait() function std::condition_variable _waiting; // condition variable for verification that all tasks are really completed bool _exceptionRaised; // notifies whether an exception raised during task execution void _taskRun( bool skip ); // function is called only by thread pool to call _task() function and increment counters }; // Concrete class of task provider for case when thread pool is not a singleton class TaskProvider : public AbstractTaskProvider { public: TaskProvider(); explicit TaskProvider( ThreadPool * pool ); TaskProvider( const TaskProvider & provider ); virtual ~TaskProvider(); TaskProvider & operator=( const TaskProvider & provider ); void setThreadPool( ThreadPool * pool ); protected: void _run( size_t taskCount ); bool _ready() const; private: ThreadPool * _threadPool; // a pointer to a thread pool }; class ThreadPool { public: explicit ThreadPool( size_t threads = 0u ); ThreadPool & operator=( const ThreadPool & ) = delete; ThreadPool( const ThreadPool & ) = delete; ~ThreadPool(); void resize( size_t threads ); size_t threadCount() const; void add( AbstractTaskProvider * provider, size_t taskCount ); // add tasks for specific provider void remove( AbstractTaskProvider * provider ); // remove all tasks related to specific provider bool empty(); // tells whether thread pool contains any tasks void clear(); // remove all tasks from thread pool void stop(); // stop all working threads private: std::vector < std::thread > _worker; // an array of worker threads std::vector < uint8_t > _run; // indicator for threads to run tasks std::vector < uint8_t > _exit; // indicator for threads to close themselfs std::condition_variable _waiting; // condition variable for synchronization of threads std::mutex _creation; // mutex for thread creation verification std::atomic < size_t > _runningThreadCount; // variable used to calculate a number of running threads std::condition_variable _completeCreation; // condition variable for verification that all threads are created std::size_t _threadCount; // current number of threads in pool bool _threadsCreated; // indicator for pool that all threads are created std::list < AbstractTaskProvider * > _task; // a list of tasks to perform std::mutex _taskInfo; // mutex for synchronization between threads and pool to manage tasks static void _workerThread( ThreadPool * pool, size_t threadId ); }; // Thread pool singleton (or monoid class) for whole application // In most situations thread pool must be one class ThreadPoolMonoid { public: static ThreadPool & instance(); // function returns a reference to global (static) thread pool ThreadPoolMonoid & operator=( const ThreadPoolMonoid & ) = delete; ThreadPoolMonoid( const ThreadPoolMonoid & ) = delete; ~ThreadPoolMonoid() { } private: ThreadPoolMonoid() { } ThreadPool _pool; // one and only thread pool }; // Concrete class of task provider with thread pool singleton class TaskProviderSingleton : public AbstractTaskProvider { public: TaskProviderSingleton(); TaskProviderSingleton( const TaskProviderSingleton & provider ); virtual ~TaskProviderSingleton(); TaskProviderSingleton & operator=( const TaskProviderSingleton & ); protected: void _run( size_t taskCount ); };
skn123/penguinV
test/unit_tests/unit_test_math.h
#pragma once class UnitTestFramework; void addTests_Math( UnitTestFramework & framework );
skn123/penguinV
test/unit_tests/unit_test_fft.h
#pragma once class UnitTestFramework; void addTests_FFT( UnitTestFramework & framework );
skn123/penguinV
src/parameter_validation.h
<reponame>skn123/penguinV #pragma once #include <limits> #include <utility> namespace Image_Function { template <typename TImage> uint8_t CheckCommonColorCount( const TImage & image1, const TImage & image2 ) { if ( image1.colorCount() != image2.colorCount() ) throw penguinVException( "The number of color channels in images is different" ); return image1.colorCount(); } template <typename TImage> uint8_t CheckCommonColorCount( const TImage & image1, const TImage & image2, const TImage & image3 ) { if ( image1.colorCount() != image2.colorCount() || image1.colorCount() != image3.colorCount() ) throw penguinVException( "The number of color channels in images is different" ); return image1.colorCount(); } template <typename TImage> bool IsCorrectColorCount( const TImage & image ) { return image.colorCount() == penguinV::GRAY_SCALE || image.colorCount() == penguinV::RGB || image.colorCount() == penguinV::RGBA; } template <typename TImage> void VerifyRGBImage( const TImage & image ) { if ( image.colorCount() != penguinV::RGB ) throw penguinVException( "Bad input parameters in image function: colored image has different than 3 color channels" ); } template <typename TImage> void VerifyRGBAImage( const TImage & image ) { if ( image.colorCount() != penguinV::RGBA ) throw penguinVException( "Bad input parameters in image function: colored image has different than 4 color channels" ); } template <typename TImage, typename... Args> void VerifyRGBImage( const TImage & image, Args... args) { VerifyRGBImage( image ); VerifyRGBImage( args... ); } template <typename TImage> void VerifyGrayScaleImage( const TImage & image ) { if ( image.colorCount() != penguinV::GRAY_SCALE ) throw penguinVException( "Bad input parameters in image function: gray-scaled image has more than 1 color channels" ); } template <typename TImage, typename... Args> void VerifyGrayScaleImage( const TImage & image, Args... args) { VerifyGrayScaleImage( image ); VerifyGrayScaleImage( args... ); } template <typename TImage> void ValidateImageParameters( const TImage & image1 ) { if ( image1.empty() || !IsCorrectColorCount( image1 ) ) throw penguinVException( "Bad input parameters in image function" ); } template <typename TImage> void ValidateImageParameters( const TImage & image1, const TImage & image2 ) { if( image1.empty() || image2.empty() || !IsCorrectColorCount( image1 ) || !IsCorrectColorCount( image2 ) || image1.width() != image2.width() || image1.height() != image2.height() ) throw penguinVException( "Bad input parameters in image function" ); } template <typename TImage, typename... Args> void ValidateImageParameters( const TImage & image1, const TImage & image2, Args... args ) { ValidateImageParameters( image1, image2 ); ValidateImageParameters( image2, args... ); } template <typename _Type> std::pair<_Type, _Type> ExtractRoiSize( _Type width, _Type height ) { return std::pair<_Type, _Type>( width, height ); } template <typename TImage, typename... Args> std::pair<uint32_t, uint32_t> ExtractRoiSize( const TImage &, uint32_t, uint32_t, Args... args ) { return ExtractRoiSize( args... ); } template <typename TImage> void ValidateImageParameters( const TImage & image, uint32_t startX, uint32_t startY, uint32_t width, uint32_t height ) { if( image.empty() || !IsCorrectColorCount( image ) || width == 0 || height == 0 || startX + width > image.width() || startY + height > image.height() || startX + width < width || startY + height < height ) throw penguinVException( "Bad input parameters in image function" ); } template <typename TImage, typename... Args> void ValidateImageParameters( const TImage & image1, uint32_t startX1, uint32_t startY1, Args... args ) { const std::pair<uint32_t, uint32_t> & dimensions = ExtractRoiSize( args... ); ValidateImageParameters( image1, startX1, startY1, dimensions.first, dimensions.second ); ValidateImageParameters( args... ); } template <typename TImage> bool IsFullImageRow( uint32_t width, const TImage & image ) { return image.rowSize() == width; } template <typename TImage, typename... Args> bool IsFullImageRow( uint32_t width, const TImage & image, Args... args ) { if ( !IsFullImageRow( width, image ) ) return false; return IsFullImageRow( width, args... ); } template <typename TImage, typename... Args> void OptimiseRoi( uint32_t & width, uint32_t & height, const TImage & image, Args... args ) { if( IsFullImageRow(width, image, args...) && ( width < (std::numeric_limits<uint32_t>::max() / height) ) ) { width = width * height; height = 1u; } } }
skn123/penguinV
test/unit_tests/unit_test_blob_detection.h
#pragma once class UnitTestFramework; void addTests_Blob_Detection( UnitTestFramework & framework );
skn123/penguinV
test/performance_tests/performance_test_image_function.h
#pragma once class PerformanceTestFramework; void addTests_Image_Function( PerformanceTestFramework & framework );
GuilhermeSbizero0804/Estrutura-de-Dados
Aulas Estrutura de Dados/5_Unip_for/main.c
#include <stdio.h> #include <stdlib.h> int main() { for (int i; i < 5; i++) { printf("UNIP! \n"); } return 0; }
GuilhermeSbizero0804/Estrutura-de-Dados
Aulas Estrutura de Dados/Programa_Maior/main.c
#include <stdio.h> #include <stdlib.h> int main() { int a, b; printf("Digite o valor de A: "); scanf("%d", &a); printf("Digite o valor de B: "); scanf("%d", &b); if (a > b) { printf("O valor de A eh o maior!"); } else if (a < b) { printf("O valor de B eho maior!"); } else { printf("A e B sao iguais!"); } return 0; }
GuilhermeSbizero0804/Estrutura-de-Dados
Aulas Estrutura de Dados/AritimeticaPonteiros/main.c
<filename>Aulas Estrutura de Dados/AritimeticaPonteiros/main.c #include <stdio.h> #include <stdlib.h> int main() { int i; int *p = &i; printf("Endereco em p: %x \n", p); printf("Endereco em p + 1 %d \n", p + 1); printf("Endereco em p + 2 %d \n", p + 2); return 0; }
GuilhermeSbizero0804/Estrutura-de-Dados
Aulas Estrutura de Dados/Opcao_Switch/main.c
<filename>Aulas Estrutura de Dados/Opcao_Switch/main.c<gh_stars>0 #include <stdio.h> #include <stdlib.h> int main() { int opc; printf("Digite a opcao 1 -> A ou 2 -> B"); scanf("%d", &opc); switch (opc) { case 1: printf("A opcao escolhida foi A!"); break; case 2: printf("A opcao escohida foi B!"); break; default: printf("A opcao digitsda nao eh valida"); break; } return 0; }
GuilhermeSbizero0804/Estrutura-de-Dados
Aulas Estrutura de Dados/5_Unip/main.c
#include <stdio.h> #include <stdlib.h> int main() { int cont = 0; while (cont <= 4) { printf("UNIP! \n"); cont = cont + 1 ; } return 0; }
GuilhermeSbizero0804/Estrutura-de-Dados
Aulas Estrutura de Dados/Programa_Raio_1/main.c
#include <stdio.h> #include <stdlib.h> int main() { float comprimento, raio; printf("Digite o valor do raio: "); scanf("%f", &raio); comprimento = 2 * 3.1416 * raio; printf("O comprimento da circunferencia eh: %f", comprimento); return 0; }
GuilhermeSbizero0804/Estrutura-de-Dados
Aulas Estrutura de Dados/TrocaFuncao/main.c
<reponame>GuilhermeSbizero0804/Estrutura-de-Dados #include <stdio.h> #include <stdlib.h> void roca (int *a, int *b) { int aux; aux = *a; *a = *b; *b = aux; printf ("\n Na funcao \n Valor de a: %d \t Valor de b: %d", a, b); } int main() { int a = 7, b = 5; troca (&a, &b); printf("\n Fora da funcao: \n Valor de a: %d \t Valor de b: %d", a, b); return 0; }
GuilhermeSbizero0804/Estrutura-de-Dados
Aulas Estrutura de Dados/VetorComPonteriro/main.c
<filename>Aulas Estrutura de Dados/VetorComPonteriro/main.c #include <stdio.h> #include <stdlib.h> int main() { int v[5] = (1, 2, 3, 4, 5); int *p = v; (for int i = 0; i < 5; i++ ){ printf("%d \t", p[1]); } return 0; }
jyz0309/nebula
src/storage/query/GetPropProcessor.h
/* Copyright (c) 2020 vesoft inc. All rights reserved. * * This source code is licensed under Apache 2.0 License. */ #ifndef STORAGE_QUERY_GETPROPPROCESSOR_H_ #define STORAGE_QUERY_GETPROPPROCESSOR_H_ #include "common/base/Base.h" #include "storage/exec/StoragePlan.h" #include "storage/query/QueryBaseProcessor.h" namespace nebula { namespace storage { extern ProcessorCounters kGetPropCounters; class GetPropProcessor : public QueryBaseProcessor<cpp2::GetPropRequest, cpp2::GetPropResponse> { public: static GetPropProcessor* instance(StorageEnv* env, const ProcessorCounters* counters = &kGetPropCounters, folly::Executor* executor = nullptr) { return new GetPropProcessor(env, counters, executor); } void process(const cpp2::GetPropRequest& req) override; void doProcess(const cpp2::GetPropRequest& req); protected: GetPropProcessor(StorageEnv* env, const ProcessorCounters* counters, folly::Executor* executor) : QueryBaseProcessor<cpp2::GetPropRequest, cpp2::GetPropResponse>(env, counters, executor) {} private: StoragePlan<VertexID> buildTagPlan(RuntimeContext* context, nebula::DataSet* result); StoragePlan<cpp2::EdgeKey> buildEdgePlan(RuntimeContext* context, nebula::DataSet* result); void onProcessFinished() override; nebula::cpp2::ErrorCode checkAndBuildContexts(const cpp2::GetPropRequest& req) override; nebula::cpp2::ErrorCode checkRequest(const cpp2::GetPropRequest& req); nebula::cpp2::ErrorCode buildTagContext(const cpp2::GetPropRequest& req); nebula::cpp2::ErrorCode buildEdgeContext(const cpp2::GetPropRequest& req); void buildTagColName(const std::vector<cpp2::VertexProp>& tagProps); void buildEdgeColName(const std::vector<cpp2::EdgeProp>& edgeProps); void runInSingleThread(const cpp2::GetPropRequest& req); void runInMultipleThread(const cpp2::GetPropRequest& req); folly::Future<std::pair<nebula::cpp2::ErrorCode, PartitionID>> runInExecutor( RuntimeContext* context, nebula::DataSet* result, PartitionID partId, const std::vector<nebula::Row>& rows); private: std::vector<RuntimeContext> contexts_; std::vector<nebula::DataSet> results_; bool isEdge_ = false; // true for edge, false for tag std::size_t limit_{std::numeric_limits<std::size_t>::max()}; }; } // namespace storage } // namespace nebula #endif // STORAGE_QUERY_GETPROPPROCESSOR_H_
jijo733/MyTests
puts.c
<gh_stars>0 #include<stdio.h> int main() { puts("Hello Jijo."); return 0; }
jijo733/MyTests
print.c
<reponame>jijo733/MyTests #include <stdio.h> int main(int argc, char* argv[]) { int age; int height; age=150; printf("age is %d , height is :%d \n",age,height); return 0; }
jijo733/MyTests
hello_world.c
<reponame>jijo733/MyTests #include<stdio.h> int main (int argc, char* argv[]) { puts("Hello world of puts \n"); fprintf(stdout, "hello this is jijo kick starting \n "); printf("The value i passed : %c ", *argv[0]); return 0; }
HPCGraphAnalysis/bicc
bcc-hipc14/util.h
#ifndef __util_h__ #define __util_h__ double timer(); #endif
HPCGraphAnalysis/bicc
bcc-dist-3/comms.h
/* //@HEADER // ***************************************************************************** // // HPCGraph: Graph Computation on High Performance Computing Systems // Copyright (2016) Sandia Corporation // // Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, // the U.S. Government retains certain rights in this software. // // 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 Corporation nor the names of the // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "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 SANDIA CORPORATION OR THE // 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. // // Questions? Contact <NAME> (<EMAIL>) // <NAME> (<EMAIL>) // <NAME> (<EMAIL>) // // ***************************************************************************** //@HEADER */ #ifndef _COMMS_H_ #define _COMMS_H_ #include <mpi.h> #include <omp.h> #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <assert.h> #include "dist_graph.h" #include "util.h" extern int procid, nprocs; extern bool verbose, debug, debug2, verify, output; #define MAX_SEND_SIZE 268435456 #define THREAD_QUEUE_SIZE 3072 struct mpi_data_t { int32_t* sendcounts; int32_t* recvcounts; int32_t* sdispls; int32_t* rdispls; int32_t* sdispls_cpy; uint64_t* recvcounts_temp; uint64_t* sendcounts_temp; uint64_t* sdispls_temp; uint64_t* rdispls_temp; uint64_t* sdispls_cpy_temp; uint64_t* sendbuf_vert; uint64_t* sendbuf_data; double* sendbuf_data_flt; uint64_t* recvbuf_vert; uint64_t* recvbuf_data; double* recvbuf_data_flt; uint64_t total_recv; uint64_t total_send; uint64_t global_queue_size; } ; struct queue_data_t { uint64_t* queue; uint64_t* queue_next; uint64_t* queue_send; uint64_t queue_size; uint64_t next_size; uint64_t send_size; } ; struct thread_queue_t { int32_t tid; uint64_t* thread_queue; uint64_t* thread_send; uint64_t thread_queue_size; uint64_t thread_send_size; } ; struct thread_comm_t { int32_t tid; bool* v_to_rank; uint64_t* sendcounts_thread; uint64_t* sendbuf_vert_thread; uint64_t* sendbuf_data_thread; double* sendbuf_data_thread_flt; int32_t* sendbuf_rank_thread; uint64_t* thread_starts; uint64_t thread_queue_size; } ; void init_queue_data(dist_graph_t* g, queue_data_t* q); void clear_queue_data(queue_data_t* q); void init_comm_data(mpi_data_t* comm); void clear_comm_data(mpi_data_t* comm); void init_thread_queue(thread_queue_t* tq); void clear_thread_queue(thread_queue_t* tq); void init_thread_comm(thread_comm_t* tc); void clear_thread_comm(thread_comm_t* tc); void init_thread_comm_flt(thread_comm_t* tc); void clear_thread_commflt(thread_comm_t* tc); void init_sendbuf_vid_data(mpi_data_t* comm); void init_recvbuf_vid_data(mpi_data_t* comm); void init_sendbuf_vid_data_flt(mpi_data_t* comm); void init_recvbuf_vid_data_flt(mpi_data_t* comm); void clear_recvbuf_vid_data(mpi_data_t* comm); void clear_allbuf_vid_data(mpi_data_t* comm); inline void exchange_verts(dist_graph_t* g, mpi_data_t* comm, queue_data_t* q); inline void exchange_verts_bicc(dist_graph_t* g, mpi_data_t* comm, queue_data_t* q); inline void exchange_verts(mpi_data_t* comm); inline void exchange_data(mpi_data_t* comm); inline void exchange_data_flt(mpi_data_t* comm); inline void exchange_vert_data(dist_graph_t* g, mpi_data_t* comm, queue_data_t* q); inline void exchange_vert_data(dist_graph_t* g, mpi_data_t* comm); inline void update_sendcounts_thread(dist_graph_t* g, thread_comm_t* tc, uint64_t vert_index); inline void update_sendcounts_thread(dist_graph_t* g, thread_comm_t* tc, uint64_t vert_index, uint64_t count_data); inline void update_vid_data_queues(dist_graph_t* g, thread_comm_t* tc, mpi_data_t* comm, uint64_t vert_index, uint64_t data); inline void update_vid_data_queues(dist_graph_t* g, thread_comm_t* tc, mpi_data_t* comm, uint64_t vert_index, uint64_t data1, uint64_t data2, uint64_t data3); inline void add_vid_to_queue(thread_queue_t* tq, queue_data_t* q, uint64_t vertex_id); inline void add_vid_to_queue(thread_queue_t* tq, queue_data_t* q, uint64_t vertex_id1, uint64_t vertex_id2); inline void empty_queue(thread_queue_t* tq, queue_data_t* q); inline void add_vid_to_send(thread_queue_t* tq, queue_data_t* q, uint64_t vertex_id); inline void add_vid_to_send(thread_queue_t* tq, queue_data_t* q, uint64_t vertex_id1, uint64_t vertex_id2); inline void empty_send(thread_queue_t* tq, queue_data_t* q); inline void add_vid_data_to_send(thread_comm_t* tc, mpi_data_t* comm, uint64_t vertex_id, uint64_t data_val, int32_t send_rank); inline void add_vid_data_to_send_flt(thread_comm_t* tc, mpi_data_t* comm, uint64_t vertex_id, double data_val, int32_t send_rank); inline void empty_vid_data(thread_comm_t* tc, mpi_data_t* comm); inline void empty_vid_data_flt(thread_comm_t* tc, mpi_data_t* comm); inline void exchange_verts(dist_graph_t* g, mpi_data_t* comm, queue_data_t* q) { comm->global_queue_size = 0; uint64_t task_queue_size = q->next_size + q->send_size; MPI_Allreduce(&task_queue_size, &comm->global_queue_size, 1, MPI_UINT64_T, MPI_SUM, MPI_COMM_WORLD); uint64_t num_comms = comm->global_queue_size / (uint64_t)MAX_SEND_SIZE + 1; uint64_t sum_recv = 0; for (uint64_t c = 0; c < num_comms; ++c) { uint64_t send_begin = (q->send_size * c) / num_comms; uint64_t send_end = (q->send_size * (c + 1)) / num_comms; if (c == (num_comms-1)) send_end = q->send_size; for (int32_t i = 0; i < nprocs; ++i) { comm->sendcounts[i] = 0; comm->recvcounts[i] = 0; } for (uint64_t i = send_begin; i < send_end; ++i) { uint64_t ghost_index = q->queue_send[i] - g->n_local; uint64_t ghost_task = g->ghost_tasks[ghost_index]; ++comm->sendcounts[ghost_task]; } MPI_Alltoall(comm->sendcounts, 1, MPI_INT32_T, comm->recvcounts, 1, MPI_INT32_T, MPI_COMM_WORLD); comm->sdispls[0] = 0; comm->sdispls_cpy[0] = 0; comm->rdispls[0] = 0; for (int32_t i = 1; i < nprocs; ++i) { comm->sdispls[i] = comm->sdispls[i-1] + comm->sendcounts[i-1]; comm->rdispls[i] = comm->rdispls[i-1] + comm->recvcounts[i-1]; comm->sdispls_cpy[i] = comm->sdispls[i]; } int32_t cur_send = comm->sdispls[nprocs-1] + comm->sendcounts[nprocs-1]; int32_t cur_recv = comm->rdispls[nprocs-1] + comm->recvcounts[nprocs-1]; comm->sendbuf_vert = (uint64_t*)malloc((uint64_t)(cur_send+1)*sizeof(uint64_t)); if (comm->sendbuf_vert == NULL) throw_err("exchange_verts(), unable to allocate comm buffers", procid); for (uint64_t i = send_begin; i < send_end; ++i) { uint64_t ghost_index = q->queue_send[i] - g->n_local; uint64_t ghost_task = g->ghost_tasks[ghost_index]; uint64_t vert = g->ghost_unmap[ghost_index]; comm->sendbuf_vert[comm->sdispls_cpy[ghost_task]++] = vert; } MPI_Alltoallv(comm->sendbuf_vert, comm->sendcounts, comm->sdispls, MPI_UINT64_T, q->queue_next+q->next_size+sum_recv, comm->recvcounts, comm->rdispls, MPI_UINT64_T, MPI_COMM_WORLD); free(comm->sendbuf_vert); sum_recv += cur_recv; } q->queue_size = q->next_size + sum_recv; q->next_size = 0; q->send_size = 0; uint64_t* temp = q->queue; q->queue = q->queue_next; q->queue_next = temp; } inline void exchange_verts_bicc(dist_graph_t* g, mpi_data_t* comm, queue_data_t* q) { comm->global_queue_size = 0; uint64_t task_queue_size = q->next_size + q->send_size; MPI_Allreduce(&task_queue_size, &comm->global_queue_size, 1, MPI_UINT64_T, MPI_SUM, MPI_COMM_WORLD); uint64_t num_comms = comm->global_queue_size / (uint64_t)MAX_SEND_SIZE + 1; uint64_t sum_recv = 0; for (uint64_t c = 0; c < num_comms; ++c) { uint64_t send_begin = (q->send_size * c) / num_comms; uint64_t send_end = (q->send_size * (c + 1)) / num_comms; if (c == (num_comms-1)) send_end = q->send_size; if (send_begin % 2 != 0) send_begin++; if (send_end % 2 != 0) send_end++; for (int32_t i = 0; i < nprocs; ++i) { comm->sendcounts[i] = 0; comm->recvcounts[i] = 0; } for (uint64_t i = send_begin; i < send_end; i += 2) { uint64_t ghost_index = q->queue_send[i] - g->n_local; uint64_t ghost_task = g->ghost_tasks[ghost_index]; comm->sendcounts[ghost_task] += 2; } MPI_Alltoall(comm->sendcounts, 1, MPI_INT32_T, comm->recvcounts, 1, MPI_INT32_T, MPI_COMM_WORLD); comm->sdispls[0] = 0; comm->sdispls_cpy[0] = 0; comm->rdispls[0] = 0; for (int32_t i = 1; i < nprocs; ++i) { comm->sdispls[i] = comm->sdispls[i-1] + comm->sendcounts[i-1]; comm->rdispls[i] = comm->rdispls[i-1] + comm->recvcounts[i-1]; comm->sdispls_cpy[i] = comm->sdispls[i]; } int32_t cur_send = comm->sdispls[nprocs-1] + comm->sendcounts[nprocs-1]; int32_t cur_recv = comm->rdispls[nprocs-1] + comm->recvcounts[nprocs-1]; comm->sendbuf_vert = (uint64_t*)malloc((uint64_t)(cur_send+1)*sizeof(uint64_t)); if (comm->sendbuf_vert == NULL) throw_err("exchange_verts(), unable to allocate comm buffers", procid); for (uint64_t i = send_begin; i < send_end; i += 2) { uint64_t ghost_index = q->queue_send[i] - g->n_local; uint64_t ghost_task = g->ghost_tasks[ghost_index]; uint64_t vert = g->ghost_unmap[ghost_index]; uint64_t parent = q->queue_send[i+1]; comm->sendbuf_vert[comm->sdispls_cpy[ghost_task]++] = vert; comm->sendbuf_vert[comm->sdispls_cpy[ghost_task]++] = parent; } MPI_Alltoallv(comm->sendbuf_vert, comm->sendcounts, comm->sdispls, MPI_UINT64_T, q->queue_next+q->next_size+sum_recv, comm->recvcounts, comm->rdispls, MPI_UINT64_T, MPI_COMM_WORLD); free(comm->sendbuf_vert); sum_recv += cur_recv; } q->queue_size = q->next_size + sum_recv; q->next_size = 0; q->send_size = 0; uint64_t* temp = q->queue; q->queue = q->queue_next; q->queue_next = temp; } inline void exchange_vert_data(dist_graph_t* g, mpi_data_t* comm, queue_data_t* q) { for (int32_t i = 0; i < nprocs; ++i) comm->recvcounts_temp[i] = 0; MPI_Alltoall(comm->sendcounts_temp, 1, MPI_UINT64_T, comm->recvcounts_temp, 1, MPI_UINT64_T, MPI_COMM_WORLD); comm->total_recv = 0; for (int i = 0; i < nprocs; ++i) comm->total_recv += comm->recvcounts_temp[i]; comm->recvbuf_vert = (uint64_t*)malloc(comm->total_recv*sizeof(uint64_t)); comm->recvbuf_data = (uint64_t*)malloc(comm->total_recv*sizeof(uint64_t)); comm->recvbuf_data_flt = NULL; if (comm->recvbuf_vert == NULL || comm->recvbuf_data == NULL) throw_err("exchange_vert_data() unable to allocate comm buffers", procid); comm->global_queue_size = 0; uint64_t task_queue_size = comm->total_send; MPI_Allreduce(&task_queue_size, &comm->global_queue_size, 1, MPI_UINT64_T, MPI_SUM, MPI_COMM_WORLD); uint64_t num_comms = comm->global_queue_size / (uint64_t)MAX_SEND_SIZE + 1; uint64_t sum_recv = 0; uint64_t sum_send = 0; for (uint64_t c = 0; c < num_comms; ++c) { for (int32_t i = 0; i < nprocs; ++i) { uint64_t send_begin = (comm->sendcounts_temp[i] * c) / num_comms; uint64_t send_end = (comm->sendcounts_temp[i] * (c + 1)) / num_comms; if (c == (num_comms-1)) send_end = comm->sendcounts_temp[i]; comm->sendcounts[i] = (int32_t)(send_end - send_begin); assert(comm->sendcounts[i] >= 0); } MPI_Alltoall(comm->sendcounts, 1, MPI_INT32_T, comm->recvcounts, 1, MPI_INT32_T, MPI_COMM_WORLD); comm->sdispls[0] = 0; comm->sdispls_cpy[0] = 0; comm->rdispls[0] = 0; for (int32_t i = 1; i < nprocs; ++i) { comm->sdispls[i] = comm->sdispls[i-1] + comm->sendcounts[i-1]; comm->rdispls[i] = comm->rdispls[i-1] + comm->recvcounts[i-1]; comm->sdispls_cpy[i] = comm->sdispls[i]; } int32_t cur_send = comm->sdispls[nprocs-1] + comm->sendcounts[nprocs-1]; int32_t cur_recv = comm->rdispls[nprocs-1] + comm->recvcounts[nprocs-1]; uint64_t* buf_v = (uint64_t*)malloc((uint64_t)(cur_send)*sizeof(uint64_t)); uint64_t* buf_d = (uint64_t*)malloc((uint64_t)(cur_send)*sizeof(uint64_t)); if (buf_v == NULL || buf_d == NULL) throw_err("exchange_verts(), unable to allocate comm buffers", procid); for (int32_t i = 0; i < nprocs; ++i) { uint64_t send_begin = (comm->sendcounts_temp[i] * c) / num_comms; uint64_t send_end = (comm->sendcounts_temp[i] * (c + 1)) / num_comms; if (c == (num_comms-1)) send_end = comm->sendcounts_temp[i]; for (uint64_t j = send_begin; j < send_end; ++j) { uint64_t vert = comm->sendbuf_vert[comm->sdispls_temp[i]+j]; uint64_t data = comm->sendbuf_data[comm->sdispls_temp[i]+j]; buf_v[comm->sdispls_cpy[i]] = vert; buf_d[comm->sdispls_cpy[i]++] = data; } } MPI_Alltoallv(buf_v, comm->sendcounts, comm->sdispls, MPI_UINT64_T, comm->recvbuf_vert+sum_recv, comm->recvcounts, comm->rdispls, MPI_UINT64_T, MPI_COMM_WORLD); MPI_Alltoallv(buf_d, comm->sendcounts, comm->sdispls, MPI_UINT64_T, comm->recvbuf_data+sum_recv, comm->recvcounts, comm->rdispls, MPI_UINT64_T, MPI_COMM_WORLD); free(buf_v); free(buf_d); sum_recv += cur_recv; sum_send += cur_send; } assert(sum_recv == comm->total_recv); assert(sum_send == comm->total_send); comm->global_queue_size = 0; task_queue_size = comm->total_recv + q->next_size; MPI_Allreduce(&task_queue_size, &comm->global_queue_size, 1, MPI_UINT64_T, MPI_SUM, MPI_COMM_WORLD); q->send_size = 0; } inline void exchange_verts(mpi_data_t* comm) { if (debug) { printf("Task %d exchange_verts() start\n", procid); } uint64_t num_comms = comm->global_queue_size / (uint64_t)MAX_SEND_SIZE + 1; uint64_t sum_recv = 0; uint64_t sum_send = 0; for (uint64_t c = 0; c < num_comms; ++c) { for (int32_t i = 0; i < nprocs; ++i) { uint64_t send_begin = (comm->sendcounts_temp[i] * c) / num_comms; uint64_t send_end = (comm->sendcounts_temp[i] * (c + 1)) / num_comms; if (c == (num_comms-1)) send_end = comm->sendcounts_temp[i]; comm->sendcounts[i] = (int32_t)(send_end - send_begin); assert(comm->sendcounts[i] >= 0); } MPI_Alltoall(comm->sendcounts, 1, MPI_INT32_T, comm->recvcounts, 1, MPI_INT32_T, MPI_COMM_WORLD); comm->sdispls[0] = 0; comm->sdispls_cpy[0] = 0; comm->rdispls[0] = 0; for (int32_t i = 1; i < nprocs; ++i) { comm->sdispls[i] = comm->sdispls[i-1] + comm->sendcounts[i-1]; comm->rdispls[i] = comm->rdispls[i-1] + comm->recvcounts[i-1]; comm->sdispls_cpy[i] = comm->sdispls[i]; } int32_t cur_send = comm->sdispls[nprocs-1] + comm->sendcounts[nprocs-1]; int32_t cur_recv = comm->rdispls[nprocs-1] + comm->recvcounts[nprocs-1]; uint64_t* buf_v = (uint64_t*)malloc((uint64_t)(cur_send)*sizeof(uint64_t)); if (buf_v == NULL) throw_err("exchange_verts(), unable to allocate comm buffers", procid); for (int32_t i = 0; i < nprocs; ++i) { uint64_t send_begin = (comm->sendcounts_temp[i] * c) / num_comms; uint64_t send_end = (comm->sendcounts_temp[i] * (c + 1)) / num_comms; if (c == (num_comms-1)) send_end = comm->sendcounts_temp[i]; for (uint64_t j = send_begin; j < send_end; ++j) { uint64_t vert = comm->sendbuf_vert[comm->sdispls_temp[i]+j]; buf_v[comm->sdispls_cpy[i]++] = vert; } } MPI_Alltoallv(buf_v, comm->sendcounts, comm->sdispls, MPI_UINT64_T, comm->recvbuf_vert+sum_recv, comm->recvcounts, comm->rdispls, MPI_UINT64_T, MPI_COMM_WORLD); free(buf_v); sum_recv += cur_recv; sum_send += cur_send; } assert(sum_recv == comm->total_recv); assert(sum_send == comm->total_send); if (debug) { printf("Task %d exchange_verts() success\n", procid); } } inline void exchange_data(mpi_data_t* comm) { if (debug) { printf("Task %d exchange_data() start\n", procid); } uint64_t num_comms = comm->global_queue_size / (uint64_t)MAX_SEND_SIZE + 1; uint64_t sum_recv = 0; uint64_t sum_send = 0; for (uint64_t c = 0; c < num_comms; ++c) { for (int32_t i = 0; i < nprocs; ++i) { uint64_t send_begin = (comm->sendcounts_temp[i] * c) / num_comms; uint64_t send_end = (comm->sendcounts_temp[i] * (c + 1)) / num_comms; if (c == (num_comms-1)) send_end = comm->sendcounts_temp[i]; comm->sendcounts[i] = (int32_t)(send_end - send_begin); assert(comm->sendcounts[i] >= 0); } MPI_Alltoall(comm->sendcounts, 1, MPI_INT32_T, comm->recvcounts, 1, MPI_INT32_T, MPI_COMM_WORLD); comm->sdispls[0] = 0; comm->sdispls_cpy[0] = 0; comm->rdispls[0] = 0; for (int32_t i = 1; i < nprocs; ++i) { comm->sdispls[i] = comm->sdispls[i-1] + comm->sendcounts[i-1]; comm->rdispls[i] = comm->rdispls[i-1] + comm->recvcounts[i-1]; comm->sdispls_cpy[i] = comm->sdispls[i]; } int32_t cur_send = comm->sdispls[nprocs-1] + comm->sendcounts[nprocs-1]; int32_t cur_recv = comm->rdispls[nprocs-1] + comm->recvcounts[nprocs-1]; uint64_t* buf_d = (uint64_t*)malloc((uint64_t)(cur_send)*sizeof(uint64_t)); if (buf_d == NULL) throw_err("exchange_data(), unable to allocate comm buffers", procid); for (int32_t i = 0; i < nprocs; ++i) { uint64_t send_begin = (comm->sendcounts_temp[i] * c) / num_comms; uint64_t send_end = (comm->sendcounts_temp[i] * (c + 1)) / num_comms; if (c == (num_comms-1)) send_end = comm->sendcounts_temp[i]; for (uint64_t j = send_begin; j < send_end; ++j) { uint64_t data = comm->sendbuf_data[comm->sdispls_temp[i]+j]; buf_d[comm->sdispls_cpy[i]++] = data; } } MPI_Alltoallv(buf_d, comm->sendcounts, comm->sdispls, MPI_UINT64_T, comm->recvbuf_data+sum_recv, comm->recvcounts, comm->rdispls, MPI_UINT64_T, MPI_COMM_WORLD); free(buf_d); sum_recv += cur_recv; sum_send += cur_send; } assert(sum_recv == comm->total_recv); assert(sum_send == comm->total_send); if (debug) { printf("Task %d exchange_data() success\n", procid); } } inline void exchange_data_flt(mpi_data_t* comm) { if (debug) { printf("Task %d exchange_data_flt() start\n", procid); } uint64_t num_comms = comm->global_queue_size / (uint64_t)MAX_SEND_SIZE + 1; uint64_t sum_recv = 0; uint64_t sum_send = 0; for (uint64_t c = 0; c < num_comms; ++c) { for (int32_t i = 0; i < nprocs; ++i) { uint64_t send_begin = (comm->sendcounts_temp[i] * c) / num_comms; uint64_t send_end = (comm->sendcounts_temp[i] * (c + 1)) / num_comms; if (c == (num_comms-1)) send_end = comm->sendcounts_temp[i]; comm->sendcounts[i] = (int32_t)(send_end - send_begin); assert(comm->sendcounts[i] >= 0); } MPI_Alltoall(comm->sendcounts, 1, MPI_INT32_T, comm->recvcounts, 1, MPI_INT32_T, MPI_COMM_WORLD); comm->sdispls[0] = 0; comm->sdispls_cpy[0] = 0; comm->rdispls[0] = 0; for (int32_t i = 1; i < nprocs; ++i) { comm->sdispls[i] = comm->sdispls[i-1] + comm->sendcounts[i-1]; comm->rdispls[i] = comm->rdispls[i-1] + comm->recvcounts[i-1]; comm->sdispls_cpy[i] = comm->sdispls[i]; } int32_t cur_send = comm->sdispls[nprocs-1] + comm->sendcounts[nprocs-1]; int32_t cur_recv = comm->rdispls[nprocs-1] + comm->recvcounts[nprocs-1]; double* buf_d = (double*)malloc((double)(cur_send)*sizeof(double)); if (buf_d == NULL) throw_err("exchange_data_flt(), unable to allocate comm buffers", procid); for (int32_t i = 0; i < nprocs; ++i) { uint64_t send_begin = (comm->sendcounts_temp[i] * c) / num_comms; uint64_t send_end = (comm->sendcounts_temp[i] * (c + 1)) / num_comms; if (c == (num_comms-1)) send_end = comm->sendcounts_temp[i]; for (uint64_t j = send_begin; j < send_end; ++j) { double data = comm->sendbuf_data_flt[comm->sdispls_temp[i]+j]; buf_d[comm->sdispls_cpy[i]++] = data; } } MPI_Alltoallv(buf_d, comm->sendcounts, comm->sdispls, MPI_DOUBLE, comm->recvbuf_data_flt+sum_recv, comm->recvcounts, comm->rdispls, MPI_DOUBLE, MPI_COMM_WORLD); free(buf_d); sum_recv += cur_recv; sum_send += cur_send; } assert(sum_recv == comm->total_recv); assert(sum_send == comm->total_send); if (debug) { printf("Task %d exchange_data_flt() success\n", procid); } } inline void update_sendcounts_thread(dist_graph_t* g, thread_comm_t* tc, uint64_t vert_index) { for (int32_t i = 0; i < nprocs; ++i) tc->v_to_rank[i] = false; uint64_t out_degree = out_degree(g, vert_index); uint64_t* outs = out_vertices(g, vert_index); for (uint64_t j = 0; j < out_degree; ++j) { uint64_t out_index = outs[j]; if (out_index >= g->n_local) { int32_t out_rank = g->ghost_tasks[out_index-g->n_local]; if (!tc->v_to_rank[out_rank]) { tc->v_to_rank[out_rank] = true; ++tc->sendcounts_thread[out_rank]; } } } } inline void update_sendcounts_thread(dist_graph_t* g, thread_comm_t* tc, uint64_t vert_index, uint64_t count_data) { for (int32_t i = 0; i < nprocs; ++i) tc->v_to_rank[i] = false; uint64_t out_degree = out_degree(g, vert_index); uint64_t* outs = out_vertices(g, vert_index); for (uint64_t j = 0; j < out_degree; ++j) { uint64_t out_index = outs[j]; if (out_index >= g->n_local) { int32_t out_rank = g->ghost_tasks[out_index-g->n_local]; if (!tc->v_to_rank[out_rank]) { tc->v_to_rank[out_rank] = true; tc->sendcounts_thread[out_rank] += count_data; } } } } inline void update_vid_data_queues(dist_graph_t* g, thread_comm_t* tc, mpi_data_t* comm, uint64_t vert_index, uint64_t data) { for (int32_t i = 0; i < nprocs; ++i) tc->v_to_rank[i] = false; uint64_t out_degree = out_degree(g, vert_index); uint64_t* outs = out_vertices(g, vert_index); for (uint64_t j = 0; j < out_degree; ++j) { uint64_t out_index = outs[j]; if (out_index >= g->n_local) { int32_t out_rank = g->ghost_tasks[out_index - g->n_local]; if (!tc->v_to_rank[out_rank]) { tc->v_to_rank[out_rank] = true; add_vid_data_to_send(tc, comm, g->local_unmap[vert_index], data, out_rank); } } } } inline void update_vid_data_queues(dist_graph_t* g, thread_comm_t* tc, mpi_data_t* comm, uint64_t vert_index, uint64_t data1, uint64_t data2, uint64_t data3) { for (int32_t i = 0; i < nprocs; ++i) tc->v_to_rank[i] = false; uint64_t out_degree = out_degree(g, vert_index); uint64_t* outs = out_vertices(g, vert_index); for (uint64_t j = 0; j < out_degree; ++j) { uint64_t out_index = outs[j]; if (out_index >= g->n_local) { int32_t out_rank = g->ghost_tasks[out_index - g->n_local]; if (!tc->v_to_rank[out_rank]) { tc->v_to_rank[out_rank] = true; add_vid_data_to_send(tc, comm, g->local_unmap[vert_index], data1, out_rank); add_vid_data_to_send(tc, comm, g->local_unmap[vert_index], data2, out_rank); add_vid_data_to_send(tc, comm, g->local_unmap[vert_index], data3, out_rank); } } } } inline void add_vid_to_queue(thread_queue_t* tq, queue_data_t* q, uint64_t vertex_id) { tq->thread_queue[tq->thread_queue_size++] = vertex_id; if (tq->thread_queue_size == THREAD_QUEUE_SIZE) empty_queue(tq, q); } inline void add_vid_to_queue(thread_queue_t* tq, queue_data_t* q, uint64_t vertex_id1, uint64_t vertex_id2) { tq->thread_queue[tq->thread_queue_size++] = vertex_id1; tq->thread_queue[tq->thread_queue_size++] = vertex_id2; if (tq->thread_queue_size == THREAD_QUEUE_SIZE) empty_queue(tq, q); } inline void empty_queue(thread_queue_t* tq, queue_data_t* q) { uint64_t start_offset; #pragma omp atomic capture start_offset = q->next_size += tq->thread_queue_size; start_offset -= tq->thread_queue_size; for (uint64_t i = 0; i < tq->thread_queue_size; ++i) q->queue_next[start_offset + i] = tq->thread_queue[i]; tq->thread_queue_size = 0; } inline void add_vid_to_send(thread_queue_t* tq, queue_data_t* q, uint64_t vertex_id) { tq->thread_send[tq->thread_send_size++] = vertex_id; if (tq->thread_send_size == THREAD_QUEUE_SIZE) empty_send(tq, q); } inline void add_vid_to_send(thread_queue_t* tq, queue_data_t* q, uint64_t vertex_id1, uint64_t vertex_id2) { tq->thread_send[tq->thread_send_size++] = vertex_id1; tq->thread_send[tq->thread_send_size++] = vertex_id2; if (tq->thread_send_size == THREAD_QUEUE_SIZE) empty_send(tq, q); } inline void empty_send(thread_queue_t* tq, queue_data_t* q) { uint64_t start_offset; #pragma omp atomic capture start_offset = q->send_size += tq->thread_send_size; start_offset -= tq->thread_send_size; for (uint64_t i = 0; i < tq->thread_send_size; ++i) q->queue_send[start_offset + i] = tq->thread_send[i]; tq->thread_send_size = 0; } inline void add_vid_data_to_send(thread_comm_t* tc, mpi_data_t* comm, uint64_t vertex_id, uint64_t data_val, int32_t send_rank) { tc->sendbuf_vert_thread[tc->thread_queue_size] = vertex_id; tc->sendbuf_data_thread[tc->thread_queue_size] = data_val; tc->sendbuf_rank_thread[tc->thread_queue_size] = send_rank; ++tc->thread_queue_size; ++tc->sendcounts_thread[send_rank]; if (tc->thread_queue_size == THREAD_QUEUE_SIZE) empty_vid_data(tc, comm); } inline void add_vid_data_to_send_flt(thread_comm_t* tc, mpi_data_t* comm, uint64_t vertex_id, double data_val, int32_t send_rank) { tc->sendbuf_vert_thread[tc->thread_queue_size] = vertex_id; tc->sendbuf_data_thread_flt[tc->thread_queue_size] = data_val; tc->sendbuf_rank_thread[tc->thread_queue_size] = send_rank; ++tc->thread_queue_size; ++tc->sendcounts_thread[send_rank]; if (tc->thread_queue_size == THREAD_QUEUE_SIZE) empty_vid_data_flt(tc, comm); } inline void empty_vid_data(thread_comm_t* tc, mpi_data_t* comm) { for (int32_t i = 0; i < nprocs; ++i) { #pragma omp atomic capture tc->thread_starts[i] = comm->sdispls_cpy_temp[i] += tc->sendcounts_thread[i]; tc->thread_starts[i] -= tc->sendcounts_thread[i]; } for (uint64_t i = 0; i < tc->thread_queue_size; ++i) { int32_t cur_rank = tc->sendbuf_rank_thread[i]; comm->sendbuf_vert[tc->thread_starts[cur_rank]] = tc->sendbuf_vert_thread[i]; comm->sendbuf_data[tc->thread_starts[cur_rank]] = tc->sendbuf_data_thread[i]; ++tc->thread_starts[cur_rank]; } for (int32_t i = 0; i < nprocs; ++i) { tc->thread_starts[i] = 0; tc->sendcounts_thread[i] = 0; } tc->thread_queue_size = 0; } inline void empty_vid_data_flt(thread_comm_t* tc, mpi_data_t* comm) { for (int32_t i = 0; i < nprocs; ++i) { #pragma omp atomic capture tc->thread_starts[i] = comm->sdispls_cpy_temp[i] += tc->sendcounts_thread[i]; tc->thread_starts[i] -= tc->sendcounts_thread[i]; } for (uint64_t i = 0; i < tc->thread_queue_size; ++i) { int32_t cur_rank = tc->sendbuf_rank_thread[i]; comm->sendbuf_vert[tc->thread_starts[cur_rank]] = tc->sendbuf_vert_thread[i]; comm->sendbuf_data_flt[tc->thread_starts[cur_rank]] = tc->sendbuf_data_thread_flt[i]; ++tc->thread_starts[cur_rank]; } for (int32_t i = 0; i < nprocs; ++i) { tc->thread_starts[i] = 0; tc->sendcounts_thread[i] = 0; } tc->thread_queue_size = 0; } #endif
HPCGraphAnalysis/bicc
bcc-ice/label_prop.h
<gh_stars>1-10 #ifndef __label_prop_h__ #define __label_prop_h__ #include<mpi.h> #include<omp.h> #include "dist_graph.h" #include<iostream> #include<vector> #include<queue> #include<set> #define FIRST 0 #define SECOND 2 #define FIRST_SENDER 1 #define SECOND_SENDER 3 #define BCC_NAME 4 extern int procid, nprocs; extern bool verbose, debug, verify, output; enum Grounding_Status {FULL=2, HALF =1, NONE=0}; Grounding_Status get_grounding_status(int* label){ return (Grounding_Status)((label[FIRST] != -1) + (label[SECOND]!=-1)); } void communicate(dist_graph_t *g, int** labels, std::queue<int>& reg, std::queue<int>& art,uint64_t* potential_artpts){ //printf("task %d: Attempting to communicate\n",procid); int* sendcnts = new int[nprocs]; for(int i = 0; i < nprocs; i++){ sendcnts[i] = 0; } //printf("task %d: Accessing g->n_local: %d, g->n_total: %d, and g->ghost_tasks: %x\n",procid, g->n_local,g->n_total,g->ghost_tasks); for(int i = g->n_local; i < g->n_total; i++){ sendcnts[g->ghost_tasks[i-g->n_local]] += 6; } //printf("task %d: done creating sendcnts\n",procid); int* recvcnts = new int[nprocs]; for(int i = 0; i < nprocs; i++) recvcnts[i] = 0; int status = MPI_Alltoall(sendcnts,1,MPI_INT,recvcnts,1,MPI_INT,MPI_COMM_WORLD); int* sdispls = new int[nprocs]; int* rdispls = new int[nprocs]; sdispls[0] = 0; rdispls[0] = 0; for(int i = 1; i < nprocs; i++){ sdispls[i] = sdispls[i-1] + sendcnts[i-1]; rdispls[i] = rdispls[i-1] + recvcnts[i-1]; } int sendsize = 0; int recvsize = 0; int* sentcount = new int[nprocs]; for(int i = 0; i < nprocs; i++){ sendsize += sendcnts[i]; recvsize += recvcnts[i]; sentcount[i] = 0; } int* sendbuf = new int[sendsize]; int* recvbuf = new int[recvsize]; //go through all the ghosted vertices, and send their labels to the owning processor for(int i = g->n_local; i < g->n_total; i++){ int proc_to_send = g->ghost_tasks[i-g->n_local]; int sendbufidx = sdispls[proc_to_send] + sentcount[proc_to_send]; sentcount[proc_to_send] += 6; sendbuf[sendbufidx++] = g->ghost_unmap[i-g->n_local]; sendbuf[sendbufidx++] = labels[i][FIRST]; sendbuf[sendbufidx++] = labels[i][FIRST_SENDER]; sendbuf[sendbufidx++] = labels[i][SECOND]; sendbuf[sendbufidx++] = labels[i][SECOND_SENDER]; sendbuf[sendbufidx++] = labels[i][BCC_NAME]; } status = MPI_Alltoallv(sendbuf, sendcnts, sdispls, MPI_INT, recvbuf,recvcnts,rdispls,MPI_INT,MPI_COMM_WORLD); //exchange labels between local label array and the labels present in recvbuf. int exchangeidx = 0; while(exchangeidx < recvsize){ int gid = recvbuf[exchangeidx++]; int lid = get_value(g->map,gid); int first = recvbuf[exchangeidx++]; int first_sender = recvbuf[exchangeidx++]; int second = recvbuf[exchangeidx++]; int second_sender = recvbuf[exchangeidx++]; int bcc_name = recvbuf[exchangeidx++]; Grounding_Status copy_gs = (Grounding_Status)((first != -1)+(second!=-1)); Grounding_Status owned_gs = get_grounding_status(labels[lid]); //printf("Task %d: sentvtx %d: (%d, %d), (%d, %d), gs: %d\n",procid,gid,first,first_sender,second,second_sender,copy_gs); //printf("Task %d: ownedvtx %d: (%d, %d), (%d, %d), gs: %d\n",procid,g->local_unmap[lid],labels[lid][FIRST],labels[lid][FIRST_SENDER],labels[lid][SECOND],labels[lid][SECOND_SENDER],owned_gs); if(owned_gs < copy_gs){ labels[lid][FIRST] = first; labels[lid][FIRST_SENDER] = first_sender; labels[lid][SECOND] = second; labels[lid][SECOND_SENDER] = second_sender; labels[lid][BCC_NAME] = bcc_name; } else if(owned_gs == copy_gs && owned_gs == HALF){ if(first != labels[lid][FIRST]){ labels[lid][SECOND] = first; labels[lid][SECOND_SENDER] = first_sender; labels[lid][BCC_NAME] = bcc_name;//not sure if this actually changes anything (will be -1?) } } if(get_grounding_status(labels[lid]) != owned_gs){ if(potential_artpts[lid]) art.push(lid); else reg.push(lid); } } //at this point, the owned vertices are all up to date, need to send them back. //recvbuf contains ghosts from each processor, ordered by the processor. //if we overwrite the labels with the owned version's labels, we can use the recvbuf as the sendbuf, //and the sendbuf as the recvbuf, for ease. int updateidx = 0; while(updateidx < recvsize){ int gid = recvbuf[updateidx++]; int lid = get_value(g->map,gid); recvbuf[updateidx++] = labels[lid][FIRST]; recvbuf[updateidx++] = labels[lid][FIRST_SENDER]; recvbuf[updateidx++] = labels[lid][SECOND]; recvbuf[updateidx++] = labels[lid][SECOND_SENDER]; recvbuf[updateidx++] = labels[lid][BCC_NAME]; } //send back the updated labels to the relevant processorss status = MPI_Alltoallv(recvbuf,recvcnts,rdispls, MPI_INT, sendbuf,sendcnts,sdispls,MPI_INT,MPI_COMM_WORLD); updateidx = 0; while(updateidx < sendsize){ //update the ghosts on the current processor int gid = sendbuf[updateidx++]; int lid = get_value(g->map,gid); /*int first = recvbuf[updateidx++]; int first_sender = recvbuf[updateidx++]; int second = recvbuf[updateidx++]; int second_sender = recvbuf[updateidx++]; int bcc_name = recvbuf[updateidx++]; Grounding_Status local_gs = get_grounding_status(labels[lid]); Grounding_Status sent_gs = (Grounding_Status)((first != -1)+(second!=-1)); if(local_gs < sent_gs){ labels[lid][FIRST] = first; labels[lid][FIRST_SENDER] = first_sender; labels[lid][SECOND] = second; labels[lid][SECOND_SENDER] = second_sender; labels[lid][BCC_NAME] = bcc_name; } else if (local_gs == sent_gs && sent_gs == HALF){ if(first != labels[lid][FIRST]){ labels[lid][SECOND] = second; labels[lid][SECOND_SENDER] = second_sender; labels[lid][BCC_NAME] = bcc_name; } }*/ Grounding_Status local_gs = get_grounding_status(labels[lid]); labels[lid][FIRST] = sendbuf[updateidx++]; labels[lid][FIRST_SENDER] = sendbuf[updateidx++]; labels[lid][SECOND] = sendbuf[updateidx++]; labels[lid][SECOND_SENDER] = sendbuf[updateidx++]; labels[lid][BCC_NAME] = sendbuf[updateidx++]; if(get_grounding_status(labels[lid]) != local_gs){ if(potential_artpts[lid])art.push(lid); else reg.push(lid); } } //printf("task %d: Concluding communication\n",procid); } //pass labels between two neighboring vertices void give_labels(dist_graph_t* g,int curr_node, int neighbor, int** labels, bool curr_is_art){ Grounding_Status curr_gs = get_grounding_status(labels[curr_node]); Grounding_Status nbor_gs = get_grounding_status(labels[neighbor]); int curr_node_gid = g->local_unmap[curr_node]; //if the neighbor is full, we don't need to pass labels if(nbor_gs == FULL) return; //if the current node is empty (shouldn't happen) we can't pass any labels if(curr_gs == NONE) return; //if the current node is full (and not an articulation point), pass both labels on if(curr_gs == FULL && !curr_is_art){ labels[neighbor][FIRST] = labels[curr_node][FIRST]; labels[neighbor][FIRST_SENDER] = curr_node_gid; labels[neighbor][SECOND] = labels[curr_node][SECOND]; labels[neighbor][SECOND_SENDER] = curr_node_gid; labels[neighbor][BCC_NAME] = labels[curr_node][BCC_NAME]; return; } else if (curr_gs == FULL){ //if it is an articulation point, and it hasn't sent to this neighbor if(labels[neighbor][FIRST_SENDER] != curr_node_gid){ //send itself as a label if(nbor_gs == NONE){ labels[neighbor][FIRST] = curr_node_gid; labels[neighbor][FIRST_SENDER] = curr_node_gid; } else if (nbor_gs == HALF){ if(labels[neighbor][FIRST] != curr_node_gid){ labels[neighbor][SECOND] = curr_node_gid; labels[neighbor][SECOND_SENDER] = curr_node_gid; } } } return; } //if the current node has only one label if(curr_gs == HALF){ //pass that on appropriately if(nbor_gs == NONE){ labels[neighbor][FIRST] = labels[curr_node][FIRST]; labels[neighbor][FIRST_SENDER] = curr_node_gid; labels[neighbor][BCC_NAME] = labels[curr_node][BCC_NAME]; } else if(nbor_gs == HALF){ //make sure you aren't giving a duplicate label, //and that you haven't sent a label to this neighbor before if(labels[neighbor][FIRST] != labels[curr_node][FIRST] && labels[neighbor][FIRST_SENDER] != curr_node_gid){ labels[neighbor][SECOND] = labels[curr_node][FIRST]; labels[neighbor][SECOND_SENDER] = curr_node_gid; labels[neighbor][BCC_NAME] = labels[curr_node][BCC_NAME]; } } } } void bfs_prop(dist_graph_t *g, std::queue<int>& reg_frontier,std::queue<int>& art_frontier, int** labels, uint64_t* potential_artpts){ //printf("task %d: starting propagation sweep\n",procid); int done = 0; while(!done){ std::queue<int>* curr = &reg_frontier; if(reg_frontier.empty()) curr = &art_frontier; while(!curr->empty()){ int curr_node = curr->front(); curr->pop(); //if the current node is a ghost, it should not propagate if(curr_node >= g->n_local) continue; int out_degree = out_degree(g, curr_node); uint64_t* outs = out_vertices(g,curr_node); //printf("Task %d: starting to check neighbors\n",procid); for(int i = 0; i < out_degree; i++){ int neighbor = outs[i]; //printf("Task %d: checking %d to %d\n",procid, curr_node, neighbor); Grounding_Status old_gs = get_grounding_status(labels[neighbor]); //printf("task %d: starting give labels\n",procid); //give curr_node's neighbor some more labels give_labels(g,curr_node, neighbor, labels, potential_artpts[curr_node] >= 1); //printf("task %d: ending give labels\n",procid); if(old_gs != get_grounding_status(labels[neighbor])){ if(potential_artpts[neighbor]) art_frontier.push(neighbor); else reg_frontier.push(neighbor); } } if(curr->empty()){ if(curr == &reg_frontier) curr = &art_frontier; else curr = &reg_frontier; } } //printf("Task %d: BEFORE COMMUNICATE\n",procid); for(int i = 0; i < g->n_total; i++){ int gid = g->local_unmap[i]; if(i >= g->n_local) gid = g->ghost_unmap[i-g->n_local]; //printf("Task %d: vtx %d (%d, %d), (%d, %d)\n",procid, gid,labels[i][0],labels[i][1], labels[i][2], labels[i][3]); } //communicate from owned to ghosts and back communicate(g,labels, reg_frontier,art_frontier,potential_artpts); //printf("Task %d: AFTER COMMUNICATE\n",procid); for(int i = 0; i < g->n_total; i++){ int gid = g->local_unmap[i]; if(i >= g->n_local) gid = g->ghost_unmap[i-g->n_local]; //printf("Task %d: vtx %d (%d, %d), (%d, %d)\n",procid, gid,labels[i][0],labels[i][1], labels[i][2], labels[i][3]); } //do MPI_Allreduce on each processor's local done values int local_done = reg_frontier.empty() && art_frontier.empty(); MPI_Allreduce(&local_done,&done,1,MPI_INT,MPI_MIN,MPI_COMM_WORLD); } //printf("task %d: finished propagation sweep\n",procid); } int* propagate(dist_graph_t *g, std::queue<int>&reg_frontier,std::queue<int>&art_frontier,int**labels,uint64_t*potential_artpts){ //propagate initially //printf("task %d: initiating propagation\n",procid); bfs_prop(g,reg_frontier,art_frontier,labels,potential_artpts); //printf("task %d: after initial propagation sweep\n",procid); for(int i = 0; i < g->n_total; i++){ int gid = g->local_unmap[i]; if(i >= g->n_local) gid = g->ghost_unmap[i-g->n_local]; //printf("Task %d: vtx %d (%d, %d), (%d, %d)\n",procid, gid,labels[i][0],labels[i][1], labels[i][2], labels[i][3]); } //fix incomplete propagation while(true){ //printf("task %d: fixing incomplete propagation\n",procid); //check for incomplete propagation for(int i = 0; i < g->n_local; i++){ if(potential_artpts[i] && get_grounding_status(labels[i]) == FULL){ int out_degree = out_degree(g, i); uint64_t* outs = out_vertices(g, i); for(int j = 0; j < out_degree; j++){ int neighbor = outs[j]; if(get_grounding_status(labels[neighbor]) == HALF && labels[neighbor][FIRST] != i && labels[neighbor][FIRST_SENDER] == i){ reg_frontier.push(i); } } } } int local_done = reg_frontier.empty(); int done = 0; MPI_Allreduce(&local_done,&done,1,MPI_INT,MPI_MIN,MPI_COMM_WORLD); //if(!done) printf("task %d: continuing to fix incomplete propagation\n",procid); //else printf("task %d: done fixing incomplete propagation\n",procid); //if no incomplete propagation, we're done if(done) break; //clear out half-full labels for(int i = 0; i < g->n_total; i++){ if(get_grounding_status(labels[i]) == HALF){ labels[i][FIRST] = -1; labels[i][FIRST_SENDER] = -1; labels[i][SECOND] = -1; labels[i][SECOND_SENDER] = -1; labels[i][BCC_NAME] = -1; } } //repropagate bfs_prop(g,reg_frontier,art_frontier,labels,potential_artpts); } int* removed = new int[g->n_total]; for(int i = 0; i < g->n_total; i++){ Grounding_Status gs = get_grounding_status(labels[i]); if(gs == FULL) removed[i] = -2; else if(gs == HALF) removed[i] = labels[i][FIRST]; else removed[i] = -1; } //printf("task %d: finishing propagation\n",procid); return removed; } int** bcc_bfs_prop_driver(dist_graph_t *g, uint64_t* potential_artpts, int**labels){ int done = 0; std::queue<int> reg_frontier; std::queue<int> art_frontier; std::queue<int> art_queue; int bcc_count = 0; int* articulation_point_flags = new int[g->n_local]; for(int i = 0; i < g->n_local; i ++){ articulation_point_flags[i] = 0; } //while there are empty vertices while(!done){ //printf("task %d: initial grounding\n",procid); //see how many articulation points all processors know about int globalArtPtCount = 0; int localArtPtCount = art_queue.size(); MPI_Allreduce(&localArtPtCount,&globalArtPtCount,1,MPI_INT,MPI_SUM,MPI_COMM_WORLD); //if none, no one is making progress, so ground two empty neighbors if(globalArtPtCount == 0){ //search for a pair of empty vertices where one is ghosted on a processor int foundGhostPair = 0; int ownedVtx = -1, ghostVtx = -1; for(int i = 0; i < g->n_local; i++){ if(get_grounding_status(labels[i]) == NONE){ int out_degree = out_degree(g,i); uint64_t* outs = (out_vertices(g,i)); for(int j = 0; j < out_degree; j++){ if(outs[j] >= g->n_local){ //the neighbor is ghosted if(get_grounding_status(labels[outs[j]])==NONE){ ownedVtx = i; ghostVtx = outs[j]; foundGhostPair = 1; break; } } } } if(foundGhostPair) break; } //if you found a ghost pair, send your own procID, otherwise send -1 int neighborProc = -1; int neighborSend = -1; if(foundGhostPair) neighborSend = procid; MPI_Allreduce(&neighborSend, &neighborProc,1,MPI_INT,MPI_MAX,MPI_COMM_WORLD); //if neighborProc is me, I have to ground the neighbors if(neighborProc == procid){ int firstNeighbor_gid = g->local_unmap[ownedVtx]; int secondNeighbor_gid = g->ghost_unmap[ghostVtx-g->n_local]; labels[ownedVtx][FIRST] = firstNeighbor_gid; labels[ownedVtx][FIRST_SENDER] = firstNeighbor_gid; labels[ownedVtx][BCC_NAME] = bcc_count*nprocs + procid; labels[ghostVtx][FIRST] = secondNeighbor_gid; labels[ghostVtx][FIRST_SENDER] = secondNeighbor_gid; labels[ghostVtx][BCC_NAME] = bcc_count*nprocs+procid; reg_frontier.push(ownedVtx); reg_frontier.push(ghostVtx); } else if(neighborProc == -1){ int foundEmptyPair = 0; int vtx1 = -1, vtx2 = -1; //if none are found, find any pair of empty vertices for(int i = 0; i < g->n_local; i++){ if(get_grounding_status(labels[i]) == NONE){ int out_degree = out_degree(g, i); uint64_t* outs = (out_vertices(g, i)); for(int j = 0; j < out_degree; j++){ if(get_grounding_status(labels[outs[j]]) == NONE){ foundEmptyPair = 1; vtx1 = i; vtx2 = outs[j]; break; } } } if(foundEmptyPair) break; } int emptyProc = -1; int emptySend = -1; if(foundEmptyPair) { emptySend = procid; printf("task %d: found %d and %d to ground\n",procid,vtx1,vtx2); } MPI_Allreduce(&emptySend,&emptyProc,1,MPI_INT,MPI_MAX,MPI_COMM_WORLD); if(emptyProc == -1){ break; // we're done here } else if(emptyProc == procid){ int firstNeighbor_gid = g->local_unmap[vtx1]; int secondNeighbor_gid = g->local_unmap[vtx2]; labels[vtx1][FIRST] = firstNeighbor_gid; labels[vtx1][FIRST_SENDER] = firstNeighbor_gid; labels[vtx1][BCC_NAME] = bcc_count*nprocs + procid; labels[vtx2][FIRST] = secondNeighbor_gid; labels[vtx2][FIRST_SENDER] = secondNeighbor_gid; labels[vtx2][BCC_NAME] = bcc_count*nprocs + procid; reg_frontier.push(vtx1); reg_frontier.push(vtx2); } } } else { //if this processor knows about articulation points if(!art_queue.empty()){ //look at the front, and ground a neighbor. int art_pt = art_queue.front(); int out_degree = out_degree(g, art_pt); uint64_t* outs = (out_vertices(g, art_pt)); for(int i = 0; i < out_degree; i++){ if(get_grounding_status(labels[outs[i]]) == NONE){ int neighbor_gid = -1; if(outs[i] >= g->n_local) neighbor_gid = g->ghost_unmap[outs[i]-g->n_local]; else neighbor_gid = g->local_unmap[outs[i]]; labels[outs[i]][FIRST] = neighbor_gid; labels[outs[i]][FIRST_SENDER] = neighbor_gid; labels[outs[i]][BCC_NAME] = bcc_count*nprocs + procid; reg_frontier.push(art_pt); reg_frontier.push(outs[i]); break; } } } } printf("task %d: completed grounding\n",procid); //communicate the grounding to other (maybe push this out of the whole grounding?) communicate(g,labels, reg_frontier,art_frontier,potential_artpts); //printf("task %d: BEFORE Prop\n",procid); //for(int i = 0; i < g->n_total; i++){ // printf("task %d: %d, %d; %d, %d; %d\n",procid, labels[i][0],labels[i][1], labels[i][2],labels[i][3],labels[i][4]); //} int* t = propagate(g,reg_frontier,art_frontier,labels,potential_artpts); //printf("task %d: AFTER Prop\n",procid); //for(int i = 0; i < g->n_total; i++){ // printf("task %d: %d, %d; %d, %d; %d\n",procid, labels[i][0],labels[i][1], labels[i][2],labels[i][3],labels[i][4]); //} //break; bcc_count++; delete [] t; //check for owned articulation points for(int i = 0; i < g->n_local; i++){ if(get_grounding_status(labels[i]) == FULL){ int out_degree = out_degree(g, i); uint64_t* outs = (out_vertices(g, i)); for(int j =0; j < out_degree; j++){ if(get_grounding_status(labels[outs[j]]) < FULL){ art_queue.push(i); articulation_point_flags[i] = 1; break; } } } } //clear half labels for(int i = 0; i < g->n_total; i++){ if(get_grounding_status(labels[i]) == HALF){ labels[i][FIRST] = -1; labels[i][FIRST_SENDER] = -1; labels[i][BCC_NAME] = -1; } } //pop articulation points off of the art_queue if necessary if(!art_queue.empty()){ bool pop_art = true; while(pop_art && !art_queue.empty()){ int top_art_degree = out_degree(g,art_queue.front()); uint64_t* art_outs = (out_vertices(g,art_queue.front())); for(int i = 0; i < top_art_degree; i++){ if(get_grounding_status(labels[art_outs[i]]) < FULL){ pop_art = false; } } if(pop_art) art_queue.pop(); } } //check for empty labels int emptylabelcount = 0; for(int i = 0; i < g->n_total; i++){ emptylabelcount += (get_grounding_status(labels[i])==NONE); } int all_empty = 0; MPI_Allreduce(&emptylabelcount,&all_empty,1,MPI_INT,MPI_SUM,MPI_COMM_WORLD); if(all_empty == 0) break; } //std::cout<<me<<": found "<<bcc_count<<" biconnected components\n"; return labels; } //int* ice_bfs_prop_driver(graph *g, int *boundary_flags, int *ground_flags){ //} #endif
HPCGraphAnalysis/bicc
bcc-dist-3/reduce_graph.h
<reponame>HPCGraphAnalysis/bicc<filename>bcc-dist-3/reduce_graph.h #ifndef _REDUCE_GRAPH_H_ #define _REDUCE_GRAPH_H_ #include <mpi.h> #include <omp.h> #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <fstream> #include "dist_graph.h" #include "comms.h" #include "util.h" #include "bfs.h" dist_graph_t* reduce_graph(dist_graph_t* g, mpi_data_t* comm, queue_data_t* q); int bicc_bfs_pull_reduced(dist_graph_t* g, mpi_data_t* comm, queue_data_t* q, uint64_t* parents_old, uint64_t* parents, uint64_t* levels, uint64_t root); int spanning_tree(dist_graph_t* g, mpi_data_t* comm, queue_data_t* q, uint64_t* parents, uint64_t* levels, uint64_t root); int connected_components(dist_graph_t* g, mpi_data_t* comm, queue_data_t* q, uint64_t* parents, uint64_t* labels); int spanning_forest(dist_graph_t* g, mpi_data_t* comm, queue_data_t* q, uint64_t* parents_old, uint64_t* parents, uint64_t* levels, uint64_t* labels); #endif
HPCGraphAnalysis/bicc
bcc-dist/lca_comms.h
<gh_stars>1-10 /* //@HEADER // ***************************************************************************** // // XtraPuLP: Xtreme-Scale Graph Partitioning using Label Propagation // Copyright (2016) Sandia Corporation // // Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, // the U.S. Government retains certain rights in this software. // // 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 Corporation nor the names of the // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "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 SANDIA CORPORATION OR THE // 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. // // Questions? Contact <NAME> (<EMAIL>) // <NAME> (<EMAIL>) // <NAME> (<EMAIL>) // // ***************************************************************************** //@HEADER */ #ifndef _LCA_COMMS_H_ #define _LCA_COMMS_H_ #include <mpi.h> #include <omp.h> #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <assert.h> #include "comms.h" #include "bicc_dist.h" #include "util.h" extern int procid, nprocs; extern bool verbose, debug, verify; #define MAX_SEND_SIZE 2147483648 #define THREAD_QUEUE_SIZE 1024 struct lca_thread_data_t { int32_t tid; uint64_t* thread_queue; uint64_t* thread_finish; uint64_t thread_queue_size; uint64_t thread_finish_size; }; struct lca_queue_data_t { uint64_t* queue; uint64_t* queue_next; uint64_t* finish; uint64_t queue_size; uint64_t next_size; uint64_t finish_size; }; inline void init_queue_lca(dist_graph_t* g, lca_queue_data_t* lcaq){ if (debug) { printf("Task %d init_queue_lca() start\n", procid);} uint64_t queue_size = g->n_local + g->n_ghost; lcaq->queue = (uint64_t*)malloc(100*queue_size*sizeof(uint64_t)); lcaq->queue_next = (uint64_t*)malloc(100*queue_size*sizeof(uint64_t)); lcaq->finish = (uint64_t*)malloc(100*queue_size*sizeof(uint64_t)); if (lcaq->queue == NULL || lcaq->queue_next == NULL || lcaq->finish == NULL) throw_err("init_queue_lca(), unable to allocate resources\n",procid); lcaq->queue_size = 0; lcaq->next_size = 0; lcaq->finish_size = 0; if(debug){printf("Task %d init_queue_lca() success\n", procid); } } inline void clear_queue_lca(lca_queue_data_t* lcaq){ if(debug){ printf("Task %d clear_queue_lca() start\n",procid); } free(lcaq->queue); free(lcaq->queue_next); free(lcaq->finish); if(debug) {printf("Task %d clear_queue_lca() success\n", procid); } } inline void init_thread_lca(lca_thread_data_t* lcat) { if (debug) { printf("Task %d init_thread_queue() start\n", procid);} lcat->tid = omp_get_thread_num(); lcat->thread_queue = (uint64_t*)malloc(THREAD_QUEUE_SIZE*sizeof(uint64_t)); lcat->thread_finish = (uint64_t*)malloc(THREAD_QUEUE_SIZE*sizeof(uint64_t)); if (lcat->thread_queue == NULL || lcat->thread_finish == NULL) throw_err("init_thread_lca(), unable to allocate resources\n", procid, lcat->tid); lcat->tid = omp_get_thread_num(); lcat->thread_queue_size = 0; lcat->thread_finish_size = 0; if (debug) {printf("Task %d init_thread_queue() success\n", procid); } } inline void clear_thread_lca(lca_thread_data_t* lcat){ free(lcat->thread_queue); free(lcat->thread_finish); } inline void init_sendbuf_lca(mpi_data_t* comm){ comm->sdispls_temp[0] = 0; comm->total_send = comm->sendcounts_temp[0]; for (int32_t i = 1; i < nprocs; ++i){ comm->sdispls_temp[i] = comm->sdispls_temp[i-1] + comm->sendcounts_temp[i-1]; comm->total_send += comm->sendcounts_temp[i]; } if (debug) printf("Task %d total_send %lu\n", procid, comm->total_send); comm->sendbuf_vert = (uint64_t*)malloc(comm->total_send*sizeof(uint64_t)); if (comm->sendbuf_vert == NULL) throw_err("init_sendbuf_lca(), unable to allocate resources\n", procid); } inline void clear_recvbuf_lca(mpi_data_t* comm){ free(comm->recvbuf_vert); for (int32_t i = 0; i < nprocs; ++i) comm->sendcounts[i] = 0; for (int32_t i = 0; i < nprocs; ++i) comm->sendcounts_temp[i] = 0; } inline void add_to_lca(lca_thread_data_t* lcat, lca_queue_data_t* lcaq, uint64_t vert1, uint64_t pred1, uint64_t level1, uint64_t vert2, uint64_t pred2, uint64_t level2); inline void empty_lca_queue(lca_thread_data_t* lcat, lca_queue_data_t* lcaq); inline void add_to_finish(lca_thread_data_t* lcat, lca_queue_data_t* lcaq, uint64_t vert1, uint64_t pred1, uint64_t level1); inline void empty_finish_queue(lca_thread_data_t* lcat, lca_queue_data_t* lcaq); inline void update_lca_send(thread_comm_t* tc, mpi_data_t* comm, lca_queue_data_t* lcaq, uint64_t index, int32_t send_rank); inline void empty_lca_send(thread_comm_t* tc, mpi_data_t* comm, lca_queue_data_t* lcaq); inline void update_lca_finish(thread_comm_t* tc, mpi_data_t* comm, lca_queue_data_t* lcaq, uint64_t index, int32_t send_rank); //(dist_graph_t* g, thread_comm_t* tc, mpi_data_t* comm, // lca_queue_data_t* lcaq, uint64_t index, int32_t send_rank); inline void empty_lca_finish(thread_comm_t* tc, mpi_data_t* comm, lca_queue_data_t* lcaq); inline void exchange_lca(dist_graph_t* g, mpi_data_t* comm); inline void add_to_lca(lca_thread_data_t* lcat, lca_queue_data_t* lcaq, uint64_t vert1, uint64_t pred1, uint64_t level1, uint64_t vert2, uint64_t pred2, uint64_t level2) { lcat->thread_queue[lcat->thread_queue_size++] = vert1; lcat->thread_queue[lcat->thread_queue_size++] = pred1; lcat->thread_queue[lcat->thread_queue_size++] = level1; lcat->thread_queue[lcat->thread_queue_size++] = vert2; lcat->thread_queue[lcat->thread_queue_size++] = pred2; lcat->thread_queue[lcat->thread_queue_size++] = level2; if (lcat->thread_queue_size+6 >= THREAD_QUEUE_SIZE) empty_lca_queue(lcat, lcaq); } inline void empty_lca_queue(lca_thread_data_t* lcat, lca_queue_data_t* lcaq) { uint64_t start_offset; #pragma omp atomic capture start_offset = lcaq->next_size += lcat->thread_queue_size; start_offset -= lcat->thread_queue_size; for (uint64_t i = 0; i < lcat->thread_queue_size; ++i) lcaq->queue_next[start_offset + i] = lcat->thread_queue[i]; lcat->thread_queue_size = 0; } inline void add_to_finish(lca_thread_data_t* lcat, lca_queue_data_t* lcaq, uint64_t vert1, uint64_t pred1, uint64_t level1) { lcat->thread_finish[lcat->thread_finish_size++] = vert1; lcat->thread_finish[lcat->thread_finish_size++] = pred1; lcat->thread_finish[lcat->thread_finish_size++] = level1; if (lcat->thread_finish_size+3 >= THREAD_QUEUE_SIZE) empty_finish_queue(lcat, lcaq); } inline void empty_finish_queue(lca_thread_data_t* lcat, lca_queue_data_t* lcaq) { uint64_t start_offset; #pragma omp atomic capture start_offset = lcaq->finish_size += lcat->thread_finish_size; start_offset -= lcat->thread_finish_size; for (uint64_t i = 0; i < lcat->thread_finish_size; ++i) lcaq->finish[start_offset + i] = lcat->thread_finish[i]; lcat->thread_finish_size = 0; } inline void update_lca_send(thread_comm_t* tc, mpi_data_t* comm, lca_queue_data_t* lcaq, uint64_t index, int32_t send_rank) { tc->sendbuf_rank_thread[tc->thread_queue_size/6] = send_rank; tc->sendbuf_vert_thread[tc->thread_queue_size++] = lcaq->queue_next[index]; tc->sendbuf_vert_thread[tc->thread_queue_size++] = lcaq->queue_next[index+1]; tc->sendbuf_vert_thread[tc->thread_queue_size++] = lcaq->queue_next[index+2]; tc->sendbuf_vert_thread[tc->thread_queue_size++] = lcaq->queue_next[index+3]; tc->sendbuf_vert_thread[tc->thread_queue_size++] = lcaq->queue_next[index+4]; tc->sendbuf_vert_thread[tc->thread_queue_size++] = lcaq->queue_next[index+5]; //++tc->thread_queue_size; //++tc->sendcounts_thread[send_rank]; if (tc->thread_queue_size+6 >= THREAD_QUEUE_SIZE) empty_lca_send(tc, comm, lcaq); } inline void empty_lca_send(thread_comm_t* tc, mpi_data_t* comm, lca_queue_data_t* lcaq) { for (int32_t i = 0; i < nprocs; ++i) { #pragma omp atomic capture tc->thread_starts[i] = comm->sdispls_temp[i] += tc->sendcounts_thread[i]; tc->thread_starts[i] -= tc->sendcounts_thread[i]; } for (uint64_t i = 0; i < tc->thread_queue_size; i+=6) { int32_t cur_rank = tc->sendbuf_rank_thread[i/6]; comm->sendbuf_vert[tc->thread_starts[cur_rank]] = tc->sendbuf_vert_thread[i]; comm->sendbuf_vert[tc->thread_starts[cur_rank]+1] = tc->sendbuf_vert_thread[i+1]; comm->sendbuf_vert[tc->thread_starts[cur_rank]+2] = tc->sendbuf_vert_thread[i+2]; comm->sendbuf_vert[tc->thread_starts[cur_rank]+3] = tc->sendbuf_vert_thread[i+3]; comm->sendbuf_vert[tc->thread_starts[cur_rank]+4] = tc->sendbuf_vert_thread[i+4]; comm->sendbuf_vert[tc->thread_starts[cur_rank]+5] = tc->sendbuf_vert_thread[i+5]; tc->thread_starts[cur_rank] += 6; } for (int32_t i = 0; i < nprocs; ++i) { tc->thread_starts[i] = 0; tc->sendcounts_thread[i] = 0; } tc->thread_queue_size = 0; } inline void update_lca_finish(thread_comm_t* tc, mpi_data_t* comm, lca_queue_data_t* lcaq, uint64_t index, int32_t send_rank) { // for (int32_t i = 0; i < nprocs; ++i) // tc->v_to_rank[i] = false; // uint64_t out_degree = out_degree(g, vert_index); // uint64_t* outs = out_vertices(g, vert_index); // for (uint64_t j = 0; j < out_degree; ++j) // { // uint64_t out_index = outs[j]; // if (out_index >= g->n_local) // { // int32_t out_rank = g->ghost_tasks[out_index - g->n_local]; // if (!tc->v_to_rank[out_rank]) // { // tc->v_to_rank[out_rank] = true; // add_vid_data_to_send(tc, comm, // g->local_unmap[vert_index], data, out_rank); // } // } // } tc->sendbuf_rank_thread[tc->thread_queue_size/3] = send_rank; tc->sendbuf_vert_thread[tc->thread_queue_size++] = lcaq->finish[index]; tc->sendbuf_vert_thread[tc->thread_queue_size++] = lcaq->finish[index+1]; tc->sendbuf_vert_thread[tc->thread_queue_size++] = lcaq->finish[index+2]; //++tc->thread_queue_size; //++tc->sendcounts_thread[send_rank]; if (tc->thread_queue_size+6 >= THREAD_QUEUE_SIZE) empty_lca_finish(tc, comm, lcaq); } // inline void add_data_to_finish(thread_comm_t* tc, mpi_data_t* comm, // lca_queue_data_t* lcaq, uint64_t index, int32_t send_rank) // { // tc->sendbuf_rank_thread[tc->thread_queue_size/3] = send_rank; // tc->sendbuf_vert_thread[tc->thread_queue_size++] = lcaq->queue_next[index]; // tc->sendbuf_vert_thread[tc->thread_queue_size++] = lcaq->queue_next[index+1]; // tc->sendbuf_vert_thread[tc->thread_queue_size++] = lcaq->queue_next[index+2]; // ++tc->thread_queue_size; // ++tc->sendcounts_thread[send_rank]; // if (tc->thread_queue_size+3 >= THREAD_QUEUE_SIZE) // empty_lca_finish(tc, comm, lcaq); // } inline void empty_lca_finish(thread_comm_t* tc, mpi_data_t* comm, lca_queue_data_t* lcaq) { for (int32_t i = 0; i < nprocs; ++i) { #pragma omp atomic capture tc->thread_starts[i] = comm->sdispls_temp[i] += tc->sendcounts_thread[i]; tc->thread_starts[i] -= tc->sendcounts_thread[i]; } for (uint64_t i = 0; i < tc->thread_queue_size; i+=3) { int32_t cur_rank = tc->sendbuf_rank_thread[i/3]; comm->sendbuf_vert[tc->thread_starts[cur_rank]] = tc->sendbuf_vert_thread[i]; comm->sendbuf_vert[tc->thread_starts[cur_rank]+1] = tc->sendbuf_vert_thread[i+1]; comm->sendbuf_vert[tc->thread_starts[cur_rank]+2] = tc->sendbuf_vert_thread[i+2]; tc->thread_starts[cur_rank] += 3; } for (int32_t i = 0; i < nprocs; ++i) { tc->thread_starts[i] = 0; tc->sendcounts_thread[i] = 0; } tc->thread_queue_size = 0; } inline void exchange_lca(dist_graph_t* g, mpi_data_t* comm) { for (int32_t i = 0; i < nprocs; ++i) comm->recvcounts_temp[i] = 0; for (int32_t i = 0; i < nprocs; ++i) comm->sdispls_temp[i] -= comm->sendcounts_temp[i]; MPI_Alltoall(comm->sendcounts_temp, 1, MPI_UINT64_T, comm->recvcounts_temp, 1, MPI_UINT64_T, MPI_COMM_WORLD); comm->total_recv = 0; for (int i = 0; i < nprocs; ++i) comm->total_recv += comm->recvcounts_temp[i]; comm->recvbuf_vert = (uint64_t*)malloc(comm->total_recv*sizeof(uint64_t)); if (comm->recvbuf_vert == NULL) throw_err("exchange_lca() unable to allocate recv buffers", procid); uint64_t task_queue_size = comm->total_send; uint64_t current_global_size = 0; MPI_Allreduce(&task_queue_size, &current_global_size, 1, MPI_UINT64_T, MPI_SUM, MPI_COMM_WORLD); uint64_t num_comms = current_global_size / (uint64_t)MAX_SEND_SIZE + 1; uint64_t sum_recv = 0; uint64_t sum_send = 0; for (uint64_t c = 0; c < num_comms; ++c) { for (int32_t i = 0; i < nprocs; ++i) { uint64_t send_begin = (comm->sendcounts_temp[i] * c) / num_comms; uint64_t send_end = (comm->sendcounts_temp[i] * (c + 1)) / num_comms; if (c == (num_comms-1)) send_end = comm->sendcounts_temp[i]; comm->sendcounts[i] = (int32_t)(send_end - send_begin); assert(comm->sendcounts[i] >= 0); } MPI_Alltoall(comm->sendcounts, 1, MPI_INT32_T, comm->recvcounts, 1, MPI_INT32_T, MPI_COMM_WORLD); comm->sdispls[0] = 0; comm->sdispls_cpy[0] = 0; comm->rdispls[0] = 0; for (int32_t i = 1; i < nprocs; ++i) { comm->sdispls[i] = comm->sdispls[i-1] + comm->sendcounts[i-1]; comm->rdispls[i] = comm->rdispls[i-1] + comm->recvcounts[i-1]; comm->sdispls_cpy[i] = comm->sdispls[i]; } int32_t cur_send = comm->sdispls[nprocs-1] + comm->sendcounts[nprocs-1]; int32_t cur_recv = comm->rdispls[nprocs-1] + comm->recvcounts[nprocs-1]; uint64_t* buf_v = (uint64_t*)malloc((uint64_t)(cur_send)*sizeof(uint64_t)); if (buf_v == NULL) throw_err("exchange_verts(), unable to allocate comm buffers", procid); for (int32_t i = 0; i < nprocs; ++i) { uint64_t send_begin = (comm->sendcounts_temp[i] * c) / num_comms; uint64_t send_end = (comm->sendcounts_temp[i] * (c + 1)) / num_comms; if (c == (num_comms-1)) send_end = comm->sendcounts_temp[i]; for (uint64_t j = send_begin; j < send_end; ++j) { uint64_t data = comm->sendbuf_vert[comm->sdispls_temp[i]+j]; buf_v[comm->sdispls_cpy[i]++] = data; } } MPI_Alltoallv(buf_v, comm->sendcounts, comm->sdispls, MPI_UINT64_T, comm->recvbuf_vert+sum_recv, comm->recvcounts, comm->rdispls, MPI_UINT64_T, MPI_COMM_WORLD); free(buf_v); sum_recv += cur_recv; sum_send += cur_send; } free(comm->sendbuf_vert); assert(sum_recv == comm->total_recv); assert(sum_send == comm->total_send); } #endif
HPCGraphAnalysis/bicc
bcc-dist-3/wbter.h
#ifndef _WBTER_H_ #define _WBTER_H_ #include <cstdint> struct xs1024star_t { uint64_t s[16]; int64_t p; } ; uint64_t xs1024star_next(xs1024star_t* xs); double xs1024star_next_real(xs1024star_t* xs); void xs1024star_seed(uint64_t seed, xs1024star_t* xs); void xs1024star_seed(xs1024star_t* xs); int read_nd_cd(char* nd_filename, char* cd_filename, uint64_t*& nd, double*& cd, uint64_t& num_verts, uint64_t& num_edges, uint64_t& dmax); int initialize_bter_data( uint64_t* nd, double* cd, uint64_t dmax, uint64_t& num_verts, uint64_t* id, double*& wd, double* rdfill, uint64_t* ndfill, double*& wg, uint64_t* ig, uint64_t* bg, uint64_t* ng, double* pg, uint64_t* ndprime, uint64_t& num_groups, uint64_t& num_blocks, double& w1, double& w2); int calculate_parallel_distribution( uint64_t* nd, double* wd, uint64_t* ig, uint64_t* bg, uint64_t*& bg_ps, uint64_t* ng, double* pg, uint64_t& start_p1, uint64_t& end_p1, uint64_t& start_p2, uint64_t& end_p2, uint64_t& my_gen_edges, uint64_t num_groups, uint64_t num_blocks, double w2); int generate_bter_edges(uint64_t dmax, uint64_t* gen_edges, uint64_t* id, uint64_t* nd, double* wd, double* rdfill, uint64_t* ndfill, uint64_t* ig, uint64_t* bg, uint64_t* bg_ps, uint64_t* ng, double* pg, uint64_t start_p1, uint64_t end_p1, uint64_t start_p2, uint64_t end_p2, uint64_t& phase1_edges, uint64_t& phase2_edges, uint64_t& phase3_edges, uint64_t& num_gen_edges, uint64_t num_groups, double w2); int generate_bter_MPI(char* nd_filename, char* cd_filename, uint64_t*& gen_edges, int64_t*& ground_truth, uint64_t& num_local_edges, uint64_t& num_local_verts, uint64_t& local_offset, bool remove_zeros); int exchange_edges(uint64_t* nd, uint64_t dmax, uint64_t* id, uint64_t*& gen_edges, uint64_t& num_edges, uint64_t& num_gen_edges, uint64_t num_verts, uint64_t& local_offset); int assign_ground_truth(uint64_t* bg, uint64_t* ng, uint64_t& num_groups, uint64_t num_verts, int64_t*& ground_truth); int assign_ground_truth_no_zeros(uint64_t* nd, uint64_t dmax, uint64_t* id, uint64_t* bg, uint64_t* ng, uint64_t& num_groups, uint64_t& num_gen_edges, uint64_t num_verts, int64_t*& ground_truth); int remove_zero_degrees(uint64_t* nd, uint64_t dmax, uint64_t* id, uint64_t*& gen_edges, uint64_t& num_edges, uint64_t& num_gen_edges, uint64_t& num_verts, int64_t*& ground_truth, uint64_t& num_local_verts, uint64_t& num_local_edges); void parallel_prefixsums( uint64_t* in_array, uint64_t* out_array, uint64_t size); void parallel_prefixsums(double* in_array, double* out_array, uint64_t size); int32_t binary_search(uint64_t* array, uint64_t value, int32_t max_index); uint64_t binary_search(double* array, double value, uint64_t max_index); uint64_t binary_search(uint64_t* array, uint64_t value, uint64_t max_index); #endif
HPCGraphAnalysis/bicc
tcc/tcc_bfs.h
#ifndef _TCC_BFS_H_ #define _TCC_BFS_H_ #include "graph.h" void tcc_bfs_do_bfs(graph* g, int root, int* parents, int* levels, int**& level_queues, int* level_counts, int& num_levels); void tcc_bfs_find_separators(graph* g, int* parents, int* levels, int** level_queues, int* level_counts, int num_levels, int* high, int* low, int* tcc_labels, int* separators, int& num_separators); void tcc_bfs(graph* g); #endif
HPCGraphAnalysis/bicc
bcc-hipc14/thread.h
#ifndef __thread_h__ #define __thread_h__ #define THREAD_QUEUE_SIZE 1024 inline void add_to_queue(int* thread_queue, int& thread_queue_size, int* queue_next, int& queue_size_next, int vert); inline void empty_queue(int* thread_queue, int& thread_queue_size, int* queue_next, int& queue_size_next); inline void add_to_queue(int* thread_queue, int& thread_queue_size, int* queue_next, int& queue_size_next, int vert) { thread_queue[thread_queue_size++] = vert; if (thread_queue_size == THREAD_QUEUE_SIZE) empty_queue(thread_queue, thread_queue_size, queue_next, queue_size_next); } inline void empty_queue(int* thread_queue, int& thread_queue_size, int* queue_next, int& queue_size_next) { int start_offset; #pragma omp atomic capture start_offset = queue_size_next += thread_queue_size; start_offset -= thread_queue_size; for (int i = 0; i < thread_queue_size; ++i) queue_next[start_offset + i] = thread_queue[i]; thread_queue_size = 0; } #endif
HPCGraphAnalysis/bicc
bcc-dist/art_pt_heuristic.h
#ifndef __ART_PT_HEURISTIC_H__ #define __ART_PT_HEURISTIC_H__ #include "bicc_dist.h" #include "dist_graph.h" #include "comms.h" void art_pt_heuristic(dist_graph_t* g, mpi_data_t* comm, queue_data_t* q, uint64_t* parents, uint64_t* levels, uint64_t* art_pt_flags); #endif
HPCGraphAnalysis/bicc
bcc-dist-2/label_prop.h
#ifndef __label_prop_h__ #define __label_prop_h__ #include<mpi.h> #include<omp.h> #include "dist_graph.h" #include<iostream> #include<fstream> #include<vector> #include<queue> #include<set> #include<algorithm> extern int procid, nprocs; extern bool verbose, debug, verify, output; //do abbreviated LCA traversals to higher-level LCAs //need the queue because if the traversal is incomplete, we resume it later //(there is a situation where another traversal would allow progress, but this approach is more general) bool reduce_labels(dist_graph_t *g, uint64_t curr_vtx, uint64_t* levels, std::vector<std::set<uint64_t>>& LCA_labels, std::unordered_map<uint64_t, std::set<uint64_t>>& remote_LCA_labels, std::unordered_map<uint64_t, uint64_t>& remote_LCA_levels, std::queue<uint64_t>* prop_queue, std::queue<uint64_t>* irreducible_prop_queue, std::set<uint64_t>& irreducible_verts, bool* did_recv_remote_LCA){ //reduce the lowest-level label until all LCA labels point to the same LCA vertex bool done = false; uint64_t curr_GID = curr_vtx; if(curr_vtx < g->n_local) curr_GID = g->local_unmap[curr_vtx]; else curr_GID = g->ghost_unmap[curr_vtx-g->n_local]; if(irreducible_verts.count(curr_GID) == 1){ return false; } while(!done){ //if there's only one label, we're completely reduced. if(LCA_labels[curr_vtx].size() == 1){ done = true; //slightly redundant, but whatever. break; } uint64_t highest_level_gid = *LCA_labels[curr_vtx].begin(); uint64_t highest_level = 0; //see if the label is remote or local, set levels accordingly if(get_value(g->map, highest_level_gid) == NULL_KEY){ highest_level = remote_LCA_levels[highest_level_gid]; } else { highest_level = levels[ get_value(g->map, highest_level_gid) ]; } for(auto it = LCA_labels[curr_vtx].begin(); it != LCA_labels[curr_vtx].end(); ++it){ uint64_t curr_level = 0; bool is_remote = false; //set the level correctly, depending on whether or not this is a remote LCA. if(get_value(g->map, *it) == NULL_KEY /*|| get_value(g->map, *it) >= g->n_local*/){ curr_level = remote_LCA_levels[ *it ]; is_remote = true; if(did_recv_remote_LCA[*it] == false){ //can't reduce this, it is irreducible irreducible_verts.insert(curr_GID); irreducible_prop_queue->push(curr_vtx); return false; } } else { curr_level = levels[ get_value(g->map, *it) ]; } if(curr_level > highest_level){ highest_level_gid = *it; highest_level = curr_level; } } //we aren't done and we need to reduce the highest-level-valued label //remove the ID under consideration from the current label LCA_labels[curr_vtx].erase(highest_level_gid); std::set<uint64_t> labels_of_highest_label; if(get_value(g->map, highest_level_gid) == NULL_KEY){ labels_of_highest_label = remote_LCA_labels[ highest_level_gid ]; } else { labels_of_highest_label = LCA_labels[get_value(g->map, highest_level_gid)]; } uint64_t level_of_labels_of_highest_label = 0; if(labels_of_highest_label.size() > 0 && get_value(g->map, *labels_of_highest_label.begin()) == NULL_KEY){ level_of_labels_of_highest_label = remote_LCA_levels[*labels_of_highest_label.begin()]; } else if( labels_of_highest_label.size() > 0){ level_of_labels_of_highest_label = levels[get_value(g->map,*labels_of_highest_label.begin())]; } if(labels_of_highest_label.count(curr_GID) == 1 && highest_level > levels[curr_vtx]){ continue; } if(labels_of_highest_label.size() == 1){ //perform reduction successfully LCA_labels[curr_vtx].insert(*labels_of_highest_label.begin()); } else { LCA_labels[curr_vtx].insert(highest_level_gid); if(irreducible_verts.count(highest_level_gid) == 1){ //this reduction is irreducible. Abort and add to irreducibility queue/set irreducible_verts.insert(curr_GID); irreducible_prop_queue->push(curr_vtx); return false; } else if(labels_of_highest_label.size() != 1 && get_value(g->map, highest_level_gid) >= g->n_local) { //the LCA which has no information is a ghost, so it is irreducible until communication. irreducible_verts.insert(curr_GID); irreducible_prop_queue->push(curr_vtx); return false; } else if(labels_of_highest_label.size() == 0){ //in distributed memory, impossible to tell wether this is actually going to be reducible without comm, so save for after comm. irreducible_verts.insert(curr_GID); irreducible_prop_queue->push(curr_vtx); return false; } else if(labels_of_highest_label.size() == 1 && highest_level < level_of_labels_of_highest_label){ irreducible_verts.insert(curr_GID); irreducible_prop_queue->push(curr_vtx); return false; } else { //irreducible_set doesn't contain the unreduced/empty LCA label, so it's local. just wait for it. //irreducible flag is not set, but there are multiple labels, cannot tell it's irreducible yet, //put it back on the local prop queue and abort current reduction. prop_queue->push(curr_vtx); return false; } } } //if we get here, reduction was successful. return true; } //Just one at a time, please void reduce_label(dist_graph_t* g, std::vector<uint64_t>& entry, std::queue<std::vector<uint64_t>>& redux_send_queue, const std::vector<std::set<uint64_t>>& LCA_labels, const std::unordered_map<uint64_t,int>& LCA_owner, uint64_t* levels, const std::unordered_map<uint64_t, int>& remote_levels){ //Entry has the structure: //------------------------------------------------------------------------------------ //| |original | current| num | label_0|level of | owner of| | //|GID |owning | owning | labels | | label_0 | label_0 | (other labels here)| //| |proc | proc | | | | | | //------------------------------------------------------------------------------------ //0 1 2 3 4 //find lowest LCA label in entry uint64_t lowest_level = entry[5]; uint64_t lowest_LCA = entry[4]; uint64_t lowest_owner = entry[6]; uint64_t lowest_idx = 4; uint64_t num_labels = entry[3]; for(int i = 4; i < 4+num_labels*3; i+= 3){ if(entry[i+1] > lowest_level){ lowest_idx = i; lowest_LCA = entry[i]; lowest_level = entry[i+1]; lowest_owner = entry[i+2]; } } //if owned, replace that label with its label, if there is a single label. // also ensure the replaced label does not already exist in the label. (no duplicates) if(lowest_owner == procid){ uint64_t lowest_lid = get_value(g->map, lowest_LCA); if(LCA_labels.at(lowest_lid).size() == 1){ entry.erase(entry.begin()+lowest_idx); entry.erase(entry.begin()+lowest_idx); entry.erase(entry.begin()+lowest_idx); uint64_t new_LCA = *LCA_labels.at(lowest_lid).begin(); uint64_t new_level = 0; uint64_t new_owner = 0; if(get_value(g->map, new_LCA) != NULL_KEY){ new_owner = procid; new_level = levels[get_value(g->map, new_LCA)]; } else { new_owner = LCA_owner.at(new_LCA); new_level = remote_levels.at(new_LCA); } //only re-insert the new LCA if it doesn't already exist if(std::count(entry.begin()+4,entry.end(),new_LCA) == 0){ entry.push_back(new_LCA); entry.push_back(new_level); entry.push_back(new_owner); } else{ //need to reduce the number of labels present in the entry entry[3]--; } } } else { //if not owned, set the owner to whichever process owns the vertex in the label entry[2] = lowest_owner; } //put the entry on the send queue. redux_send_queue.push(entry); } void communicate_redux(dist_graph_t* g, std::queue<std::vector<uint64_t>>* redux_send_queue, std::queue<std::vector<uint64_t>>* next_redux_queue, std::vector<std::set<uint64_t>>& LCA_labels, bool* potential_artpt_did_prop_lower, uint64_t* potential_artpts, std::queue<uint64_t>* next_prop_queue, std::unordered_map<uint64_t,int>& LCA_owner, std::unordered_map<uint64_t, int>& remote_levels, std::queue<std::vector<uint64_t>>* irredux_queue){ //read each entry, send to the current owner. int* sendcnts = new int[nprocs]; int* recvcnts = new int[nprocs]; for(int i = 0; i < nprocs; i++){ sendcnts[i] = 0; recvcnts[i] = 0; } int queue_size = redux_send_queue->size(); for(int i = 0; i < queue_size; i++){ std::vector<uint64_t> curr_entry = redux_send_queue->front(); /*std::cout<<"sending entry with size "<<curr_entry.size()<<" to proc "<<curr_entry[2]<<"\n"; std::cout<<"entry for vertex "<<curr_entry[0]<<" contains "<<curr_entry[3]<<" labels\n";*/ if(curr_entry[0] == 191817){ std::cout<<"sending entry for vertex "<<curr_entry[0]<<" with "<<curr_entry[3]<<" labels, with size "<<curr_entry.size() <<" starting at sendbuf idx "<<sendcnts[curr_entry[2]]<<"\n" ; } redux_send_queue->pop(); sendcnts[curr_entry[2]] += curr_entry.size(); redux_send_queue->push(curr_entry); } MPI_Alltoall(sendcnts, 1, MPI_INT, recvcnts, 1, MPI_INT, MPI_COMM_WORLD); int sendsize = 0; int recvsize = 0; int* sdispls = new int[nprocs+1]; int* rdispls = new int[nprocs+1]; sdispls[0] = 0; rdispls[0] = 0; for(int i = 1; i <= nprocs; i++){ sdispls[i] = sdispls[i-1] + sendcnts[i-1]; rdispls[i] = rdispls[i-1] + recvcnts[i-1]; sendsize += sendcnts[i-1]; recvsize += recvcnts[i-1]; } int* sendbuf = new int[sendsize]; int* recvbuf = new int[recvsize]; int sendidx[nprocs]; for(int i = 0; i < nprocs; i++) sendidx[i] = sdispls[i]; while(redux_send_queue->size() > 0){ std::vector<uint64_t> curr_entry = redux_send_queue->front(); redux_send_queue->pop(); //Entry has the structure: //------------------------------------------------------------------------------------ //| |original | current| num | label_0|level of | owner of| | //|GID |owning | owning | labels | | label_0 | label_0 | (other labels here)| //| |proc | proc | | | | | | //------------------------------------------------------------------------------------ //0 1 2 3 4 int proc_to_send = curr_entry[2]; int num_labels = curr_entry[3]; int entry_size = num_labels*3+4; //std::cout<<"vertex "<<curr_entry[0]<<"\n"; assert(entry_size == curr_entry.size()); if(curr_entry[0] == 853019){ //std::cout<<"inserting vertex "<<curr_entry[0]<<" at index "<<sendidx[proc_to_send]<<"\n"; } for(int i = 0; i < entry_size; i++){ sendbuf[sendidx[proc_to_send]++] = curr_entry[i]; } } //MPI_Alltoallv MPI_Alltoallv(sendbuf, sendcnts, sdispls, MPI_INT, recvbuf, recvcnts, rdispls, MPI_INT, MPI_COMM_WORLD); //on recv, update local labels for traversals that have finished (sent to this proc but multi-labeled and lowest owner is not procid) int ridx = 0; //std::cout<<"recvsize = "<<recvsize<<"\n"; while(ridx < recvsize){ //std::cout<<"ridx = "<<ridx<<"\n"; //read in the current entry's info uint64_t gid = recvbuf[ridx]; if(gid == 853019){ //std::cout<<"comm_redux: processing recvbuf, vertex "<<gid<<"\n"; //std::cout<<"\t has "<<recvbuf[ridx+3]<< " labels, at ridx "<<ridx<<" with recvsize "<<recvsize<<"\n"; } uint64_t og_owner = recvbuf[ridx+1]; uint64_t curr_owner = recvbuf[ridx+2]; uint64_t num_labels = recvbuf[ridx+3]; uint64_t entry_size = num_labels*3 +4; uint64_t lid = get_value(g->map, gid); if(num_labels == 1){ //update label, and stop the traversal LCA_labels[lid].clear(); uint64_t curr_label = recvbuf[ridx+4]; uint64_t curr_label_level = recvbuf[ridx+4+1]; uint64_t curr_label_owner = recvbuf[ridx+4+2]; LCA_labels[lid].insert(curr_label); //if the LCA label is owned, we don't need to update any local info, //if it is NOT owned, mark the level and owner for future use. if(get_value(g->map, curr_label) == NULL_KEY){ remote_levels[curr_label] = recvbuf[ridx+4+1]; LCA_owner[curr_label] = recvbuf[ridx+4+2]; } if(potential_artpts[lid]){ potential_artpt_did_prop_lower[lid] = false; } if(lid == 816028) std::cout<<"Reduced vertex "<<lid<<"\n"; next_prop_queue->push(lid); //do nothing, this traversal is done. } else { //construct entry, and find owner of lowest LCA std::vector<uint64_t> entry; entry.push_back(gid); entry.push_back(og_owner); entry.push_back(curr_owner); entry.push_back(num_labels); uint64_t lowest_label = recvbuf[ridx+4]; uint64_t lowest_level = recvbuf[ridx+4+1]; uint64_t lowest_owner = recvbuf[ridx+4+2]; //add the label info to the entry, we might put it back on the queue. //also, find the owner of the lowest label for(int i = 0; i < num_labels*3; i+=3){ entry.push_back(recvbuf[ridx+4+i]); entry.push_back(recvbuf[ridx+4+i+1]); entry.push_back(recvbuf[ridx+4+i+2]); if(recvbuf[ridx+4+i+1] > lowest_level){ lowest_label = recvbuf[ridx+4+i]; lowest_level = recvbuf[ridx+4+i+1]; lowest_owner = recvbuf[ridx+4+i+2]; } } //On a traversal received, progress can only be made if (lowest_owner == procid && LCA_labels[lid].size() == 1) if(lowest_owner == procid && LCA_labels[get_value(g->map, lowest_label)].size() == 1){ //put on the next_redux_queue next_redux_queue->push(entry); //if progress cannot be made, update the label and do not attempt to continue traversing } else{ //update the label and put on irredux_queue LCA_labels[lid].clear(); for(int i = 0; i < num_labels*3; i+=3){ uint64_t lca_label = recvbuf[ridx+4+i]; uint64_t lca_level = recvbuf[ridx+4+i+1]; uint64_t lca_owner = recvbuf[ridx+4+i+2]; LCA_labels[lid].insert(lca_label); if(get_value(g->map,lca_label) == NULL_KEY){ LCA_owner[lca_label] = lca_owner; remote_levels[lca_label] = lca_level; } } irredux_queue->push(entry); } } /*if(procid == og_owner && og_owner == curr_owner){ uint64_t lid = get_value(g->map, gid); std::vector<uint64_t> entry; entry.push_back(gid); entry.push_back(og_owner); entry.push_back(curr_owner); entry.push_back(num_labels); //std::cout<<"updating labels for vertex "<<lid<<"\n"; LCA_labels[lid].clear(); for(int i = 0; i < num_labels*3; i+=3){ //std::cout<<"\tadding label "<<recvbuf[ridx+4+i]<<"\n"; entry.push_back(recvbuf[ridx+4+i]); entry.push_back(recvbuf[ridx+4+i+1]); entry.push_back(recvbuf[ridx+4+i+2]); LCA_labels[lid].insert(recvbuf[ridx+4+i]); } if(num_labels == 1){ //put vert on the next_prop_queue next_prop_queue->push(lid); if(potential_artpts[lid]){ potential_artpt_did_prop_lower[lid] = false; } } else { //if the lowest vertex is not owned by this proc, do not put on next_redux_queue. //if //next_redux_queue->push(entry); } } else { std::vector<uint64_t> entry; entry.push_back(gid); entry.push_back(og_owner); entry.push_back(curr_owner); entry.push_back(num_labels); for(int i = 0; i < num_labels*3; i+=1){ entry.push_back(recvbuf[ridx+4+i]); } next_redux_queue->push(entry); }*/ ridx += entry_size; } } //pass LCA and low labels between two neighboring vertices void pass_labels(dist_graph_t* g,uint64_t curr_vtx, uint64_t nbor, std::vector<std::set<uint64_t>>& LCA_labels, std::unordered_map<uint64_t, int>& remote_levels, uint64_t* low_labels, uint64_t* levels, uint64_t* potential_artpts, bool* potential_artpt_did_prop_lower, std::queue<uint64_t>* prop_queue, std::queue<uint64_t>* next_prop_queue, std::set<uint64_t>& verts_to_send, std::unordered_map<uint64_t, std::set<int>>& procs_to_send, bool full_reduce, bool reduction_needed){ if(curr_vtx == 816028 && nbor == 815634){ std::cout<<curr_vtx<<" passing labels to "<<nbor<<"\n"; std::cout<<"full_reduce = "<<full_reduce<<" reduction_needed = "<<reduction_needed<<"\n"; std::cout<<"LCA_labels[curr_vtx].size() = "<<LCA_labels[curr_vtx].size()<<"\n"; std::cout<<"LCA_labels[curr_vtx]: "; for(auto it = LCA_labels[curr_vtx].begin(); it != LCA_labels[curr_vtx].end(); it++){ std::cout<<*it<<" "; } std::cout<<"\n"; } //if curr_vert is an potential_artpt // if nbor has a level <= curr_vert // pass received LCA labels to nbor (if different) // else // pass only GID of curr_vert to nbor (if different) // pass low_label to nbor if LCA is the same. // //else // pass LCA labels to nbor (if different) // pass low label to nbor if LCA is the same. // //if nbor was updated, add to prop_queue bool nbor_changed = false; //if the curr_vtx is an LCA if(potential_artpts[curr_vtx] != 0){ //if the neighboring vertex is higher in the tree if((levels[nbor] <= levels[curr_vtx] && full_reduce && reduction_needed) || (levels[nbor] == levels[curr_vtx] && full_reduce)){ //see if curr_vtx has any labels that nbor doesn't std::vector<uint64_t> diff; std::set_difference(LCA_labels[curr_vtx].begin(), LCA_labels[curr_vtx].end(), LCA_labels[nbor].begin(), LCA_labels[nbor].end(), std::inserter(diff, diff.begin())); //if so, pass missing IDs to nbor if(diff.size() > 0){ for(size_t i = 0; i < diff.size(); i++){ //don't give a vertex its own label, it causes headaches in label reduction. uint64_t nbor_gid = nbor; if(nbor < g->n_local) nbor_gid = g->local_unmap[nbor]; else nbor_gid = g->ghost_unmap[nbor - g->n_local]; if(diff[i] != nbor_gid) { LCA_labels[nbor].insert(diff[i]); nbor_changed = true; } } } } else if(levels[nbor] > levels[curr_vtx]){ //ONLY propagate to lower level neighbors if it has not //happened up until this point. We can't check the contents //of the label, because reductions may eliminate the ID of this //LCA from its lower neighbors' labels. re-adding this label later would //trigger more reductions than necessary. if(!potential_artpt_did_prop_lower[curr_vtx] || (full_reduce && reduction_needed)){ if(curr_vtx < g->n_local){ if(LCA_labels[nbor].count(g->local_unmap[curr_vtx]) == 0){ LCA_labels[nbor].insert(g->local_unmap[curr_vtx]); nbor_changed = true; } } else { if(LCA_labels[nbor].count(g->ghost_unmap[curr_vtx - g->n_local]) == 0){ LCA_labels[nbor].insert(g->ghost_unmap[curr_vtx - g->n_local]); nbor_changed = true; } } } } //pass low_label to neighbor if LCA_labels are the same, and if it is lower. uint64_t curr_gid = curr_vtx; if(curr_vtx < g->n_local) curr_gid = g->local_unmap[curr_vtx]; else curr_gid = g->ghost_unmap[curr_vtx-g->n_local]; if(LCA_labels[curr_vtx] == LCA_labels[nbor] && (levels[nbor] <= levels[curr_vtx] || *LCA_labels[nbor].begin() != curr_gid)){ uint64_t curr_low_label = low_labels[curr_vtx]; uint64_t nbor_low_label = low_labels[nbor]; uint64_t curr_low_label_level = 0; if(get_value(g->map, curr_low_label) == NULL_KEY){ curr_low_label_level = remote_levels[curr_low_label]; } else { curr_low_label_level = levels[get_value(g->map, curr_low_label)]; } uint64_t nbor_low_label_level = 0; if(get_value(g->map, nbor_low_label) == NULL_KEY){ nbor_low_label_level = remote_levels[nbor_low_label]; } else { nbor_low_label_level = levels[get_value(g->map,nbor_low_label)]; } if(curr_low_label_level > nbor_low_label_level || (curr_low_label_level == nbor_low_label_level && curr_low_label > nbor_low_label)){ low_labels[nbor] = low_labels[curr_vtx]; nbor_changed = true; } } } else { //for non-LCA verts, only pass labels if if((levels[nbor] > levels[curr_vtx] ) || // the neighbor is lower and has no labels, or (levels[nbor] <= levels[curr_vtx] && full_reduce )){ //the neighbor is higher and the current label was recently reduced. std::vector<uint64_t> diff; std::set_difference(LCA_labels[curr_vtx].begin(), LCA_labels[curr_vtx].end(), LCA_labels[nbor].begin(), LCA_labels[nbor].end(), std::inserter(diff, diff.begin())); if(diff.size() > 0){ for(size_t i = 0; i < diff.size(); i++){ //don't give a vertex its own label, it causes headaches in label reduction. uint64_t nbor_gid = nbor; if(nbor < g->n_local) nbor_gid = g->local_unmap[nbor]; else nbor_gid = g->ghost_unmap[nbor - g->n_local]; //check that label of diff[i] doesn't contain the gid of nbor std::set<uint64_t> labels_of_diff; uint64_t level_of_diff = 0; if(get_value(g->map, diff[i]) == NULL_KEY){ //make sure we have the necessary data for looking up labels and levels level_of_diff = remote_levels[diff[i]]; } else { level_of_diff = levels[get_value(g->map, diff[i])]; } if(diff[i] != nbor_gid && level_of_diff < levels[nbor]) { LCA_labels[nbor].insert(diff[i]); nbor_changed = true; } } } } if(LCA_labels[curr_vtx] == LCA_labels[nbor]){ uint64_t curr_low_label = low_labels[curr_vtx]; uint64_t nbor_low_label = low_labels[nbor]; uint64_t curr_low_label_level = 0; if(get_value(g->map, curr_low_label) == NULL_KEY){ curr_low_label_level = remote_levels[curr_low_label]; } else { curr_low_label_level = levels[get_value(g->map, curr_low_label)]; } uint64_t nbor_low_label_level = 0; if(get_value(g->map, nbor_low_label) == NULL_KEY){ nbor_low_label_level = remote_levels[nbor_low_label]; } else { nbor_low_label_level = levels[get_value(g->map, nbor_low_label)]; } if(curr_low_label_level > nbor_low_label_level || (curr_low_label_level == nbor_low_label_level && curr_low_label > nbor_low_label)){ low_labels[nbor] = low_labels[curr_vtx]; nbor_changed = true; } } } if(nbor_changed){ //if we need to send this vert to remote procs, //add it to verts_to_send. if(procs_to_send[nbor].size() > 0){ verts_to_send.insert(nbor); } next_prop_queue->push(nbor); } } void communicate_prop(dist_graph_t* g, std::set<uint64_t> verts_to_send, std::unordered_map<uint64_t, std::set<int>>& procs_to_send, std::vector<std::set<uint64_t>>& LCA_labels, uint64_t* low_labels, std::unordered_map<uint64_t, int>& LCA_owner, uint64_t* levels, std::unordered_map<uint64_t, int>& remote_levels, std::queue<uint64_t>* next_prop_queue){ bool already_sent[g->n_local]; int* sendcnts = new int[nprocs]; int* recvcnts = new int[nprocs]; for(int i = 0; i < nprocs; i++){ sendcnts[i] = 0; recvcnts[i] = 0; } for(int i = 0; i < g->n_local; i++) already_sent[i] = false; for(auto vtxit = verts_to_send.begin(); vtxit != verts_to_send.end(); vtxit++){ uint64_t curr_vtx = *vtxit; if(LCA_labels[curr_vtx].size() == 1 && !already_sent[curr_vtx]){ for(auto it = procs_to_send[curr_vtx].begin(); it != procs_to_send[curr_vtx].end(); ++it){ sendcnts[*it] += 6; } already_sent[curr_vtx] = true; } } MPI_Alltoall(sendcnts, 1, MPI_INT, recvcnts, 1, MPI_INT, MPI_COMM_WORLD); int sendsize = 0; int recvsize = 0; int* sdispls = new int[nprocs+1]; int* rdispls = new int[nprocs+1]; sdispls[0] = 0; rdispls[0] = 0; for(int i = 1; i <= nprocs; i++){ sdispls[i] = sdispls[i-1] + sendcnts[i-1]; rdispls[i] = rdispls[i-1] + recvcnts[i-1]; sendsize += sendcnts[i-1]; recvsize += recvcnts[i-1]; } int* sendbuf = new int[sendsize]; int* recvbuf = new int[recvsize]; int sendidx[nprocs]; for(int i = 0; i < nprocs; i++) sendidx[i] = sdispls[i]; for(int i = 0; i < g->n_local; i++) already_sent[i] = false; for(auto it = verts_to_send.begin(); it != verts_to_send.end(); it++){ if(LCA_labels[*it].size() == 1 && !already_sent[*it]){ uint64_t LCA_gid = *LCA_labels[*it].begin(); int lca_level = 0; int lca_owner = procid; int low_level = 0; if(get_value(g->map, LCA_gid) == NULL_KEY){ lca_level = remote_levels[LCA_gid]; lca_owner = LCA_owner[LCA_gid]; } else { lca_level = levels[get_value(g->map, LCA_gid)]; } if(get_value(g->map, low_labels[*it]) == NULL_KEY){ low_level = remote_levels[low_labels[*it]]; } else { low_level = levels[low_labels[*it]]; } for(auto p_it = procs_to_send[*it].begin(); p_it != procs_to_send[*it].end(); ++p_it){ sendbuf[sendidx[*p_it]++] = g->local_unmap[*it]; sendbuf[sendidx[*p_it]++] = LCA_gid; sendbuf[sendidx[*p_it]++] = lca_level; sendbuf[sendidx[*p_it]++] = lca_owner; sendbuf[sendidx[*p_it]++] = low_labels[*it]; sendbuf[sendidx[*p_it]++] = low_level; } already_sent[*it] = true; } } MPI_Alltoallv(sendbuf, sendcnts, sdispls, MPI_INT, recvbuf, recvcnts, rdispls, MPI_INT, MPI_COMM_WORLD); for(int i = 0; i < recvsize; i+=6){ uint64_t lid = get_value(g->map,recvbuf[i]);//should always be a ghost. No completely remote vertices here. uint64_t lca_gid = recvbuf[i+1]; //might be a remote LCA, need to set the owner uint64_t lca_level = recvbuf[i+2]; uint64_t lca_owner = recvbuf[i+3]; uint64_t low_label = recvbuf[i+4]; uint64_t low_level = recvbuf[i+5]; LCA_labels[lid].clear(); LCA_labels[lid].insert(lca_gid); low_labels[lid] = low_label; //if LCA is not owned, add to LCA_owner //same with remote_levels if(get_value(g->map,lca_gid) == NULL_KEY){ LCA_owner[lca_gid] = lca_owner; remote_levels[lca_gid] = lca_level; } //if low label is not owned, add level to remote_levels if(get_value(g->map,low_label) == NULL_KEY){ remote_levels[low_label] = low_level; } } delete [] sendcnts; delete [] recvcnts; } void pull_low_labels(uint64_t curr_vtx, uint64_t nbor, dist_graph_t* g, std::vector<uint64_t>& ghost_offsets, std::vector<uint64_t>& ghost_adjs, std::vector<std::set<uint64_t>>& LCA_labels, uint64_t* potential_artpts, uint64_t* low_labels, std::set<uint64_t>& verts_to_send, std::unordered_map<uint64_t, std::set<int>>& procs_to_send, uint64_t* levels, std::unordered_map<uint64_t,int>& remote_levels){ int out_degree = 0; uint64_t* nbors = nullptr; if(curr_vtx < g->n_local){ out_degree = out_degree(g, curr_vtx); nbors = out_vertices(g,curr_vtx); } else { out_degree = ghost_offsets[curr_vtx+1 - g->n_local] - ghost_offsets[curr_vtx - g->n_local]; nbors = &ghost_adjs[ghost_offsets[curr_vtx-g->n_local]]; } for(int nbor_idx = 0; nbor_idx < out_degree; nbor_idx++){ uint64_t nbor = nbors[nbor_idx]; uint64_t nbor_gid = nbors[nbor_idx]; if(nbors[nbor_idx] < g->n_local){ nbor_gid = g->local_unmap[nbors[nbor_idx]]; } else { nbor_gid = g->ghost_unmap[nbors[nbor_idx]-g->n_local]; } if(LCA_labels[curr_vtx] == LCA_labels[nbors[nbor_idx]] && ((levels[curr_vtx] <= levels[nbors[nbor_idx]]) || (potential_artpts[nbors[nbor_idx]] == 0) || (potential_artpts[nbors[nbor_idx]] != 0 && *LCA_labels[curr_vtx].begin() != nbor_gid))){ uint64_t curr_low_label = low_labels[curr_vtx]; uint64_t nbor_low_label = low_labels[nbor]; uint64_t curr_low_label_level = 0; if(get_value(g->map, curr_low_label) == NULL_KEY){ curr_low_label_level = remote_levels.at(curr_low_label); } else { curr_low_label_level = levels[get_value(g->map, curr_low_label)]; } uint64_t nbor_low_label_level = 0; if(get_value(g->map, nbor_low_label) == NULL_KEY){ nbor_low_label_level = remote_levels.at(nbor_low_label); } else { nbor_low_label_level = levels[get_value(g->map, nbor_low_label)]; } if(curr_low_label_level < nbor_low_label_level || (curr_low_label_level == nbor_low_label_level && curr_low_label < nbor_low_label)){ low_labels[curr_vtx] = low_labels[nbor]; if(procs_to_send[curr_vtx].size() > 0) verts_to_send.insert(curr_vtx); } } } } void print_labels(dist_graph_t *g, uint64_t vertex, std::vector<std::set<uint64_t>> LCA_labels, uint64_t* low_labels, uint64_t* potential_artpts, uint64_t* levels){ if(vertex < g->n_local) std::cout<<"Task "<<procid<<": vertex "<<g->local_unmap[vertex]<<" has LCA label "<<*LCA_labels[vertex].begin()<<", low label "<<low_labels[vertex]<<" and level "<<levels[vertex]; else std::cout<<"vertex "<<g->ghost_unmap[vertex - g->n_local]<<" has LCA label "<<*LCA_labels[vertex].begin()<<", low label "<<low_labels[vertex]<<" and level "<<levels[vertex]; if(vertex >= g->n_local) std::cout<<" and is a ghost"; if(potential_artpts[vertex] != 0){ std::cout<<" and is an LCA vertex, which neighbors:\n\t"; } else std::cout<<" neighbors:\n\t"; uint64_t vertex_out_degree = out_degree(g, vertex); uint64_t* vertex_nbors = out_vertices(g, vertex); for(uint64_t i = 0; i < vertex_out_degree; i++){ if(vertex_nbors[i] < g->n_local) std::cout<<"vertex "<<g->local_unmap[vertex_nbors[i]]<<" has LCA label "<<*LCA_labels[vertex_nbors[i]].begin()<<", low label " <<low_labels[vertex_nbors[i]]<<" and level "<<levels[vertex_nbors[i]]; else std::cout<<"vertex "<<g->ghost_unmap[vertex_nbors[i]-g->n_local]<<" has LCA label "<<*LCA_labels[vertex_nbors[i]].begin()<<", low label "<<low_labels[vertex_nbors[i]]<<" and level "<<levels[vertex_nbors[i]]; if(potential_artpts[vertex_nbors[i]] != 0){ std::cout<<" and is an LCA vertex"; } if(vertex_nbors[i] >= g->n_local) std::cout<<" and is a ghost"; std::cout<<"\n\t"; } std::cout<<"\n"; } void bcc_bfs_prop_driver(dist_graph_t *g,std::vector<uint64_t>& ghost_offsets, std::vector<uint64_t>& ghost_adjs, uint64_t* potential_artpts, std::vector<std::set<uint64_t>>& LCA_labels, uint64_t* low_labels, uint64_t* levels, int* articulation_point_flags, std::unordered_map<uint64_t, std::set<int>>& procs_to_send){ //keep track of ghosts we need to send std::set<uint64_t> verts_to_send; //keep track of propagation std::queue<uint64_t> prop_queue; std::queue<uint64_t> n_prop_queue; //keep track of reduction std::queue<std::vector<uint64_t>> reduction_queue; std::queue<std::vector<uint64_t>> n_reduction_queue; std::queue<std::vector<uint64_t>> irreducible_queue; std::queue<std::vector<uint64_t>> reduction_to_send_queue; //need to know LCA owners, levels std::unordered_map<uint64_t, int> LCA_owner; std::unordered_map<uint64_t, int> remote_levels; //aliases for easy queue switching std::queue<uint64_t> * curr_prop_queue = &prop_queue; std::queue<uint64_t> * next_prop_queue = &n_prop_queue; std::queue<std::vector<uint64_t>>* curr_redux_queue = &reduction_queue; std::queue<std::vector<uint64_t>>* next_redux_queue = &n_reduction_queue; std::queue<std::vector<uint64_t>>* irredux_queue = &irreducible_queue; std::queue<std::vector<uint64_t>>* redux_to_send_queue = &reduction_to_send_queue; bool* potential_artpt_did_prop_lower = new bool[g->n_total]; bool* did_recv_remote_LCA = new bool[g->n]; for(uint64_t i = 0; i < g->n; i++) did_recv_remote_LCA[i] = false; std::set<uint64_t> irreducible_verts; double total_comm_time = 0.0; int total_send_size = 0; for(uint64_t i = 0; i < g->n_total; i++){ if(potential_artpts[i] != 0) { curr_prop_queue->push(i); if(procs_to_send[i].size() > 0){ verts_to_send.insert(i); } } potential_artpt_did_prop_lower[i] = false; if(levels[i] == 0) { if(i < g->n_local) LCA_labels[i].insert(g->local_unmap[i]); else LCA_labels[i].insert(g->ghost_unmap[i-g->n_local]); if(procs_to_send[i].size() > 0){ verts_to_send.insert(i); } } } uint64_t done = curr_prop_queue->size(); uint64_t global_done = 0; MPI_Allreduce(&done, &global_done, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD); bool prop_till_done = true; bool redux_till_done = true; bool reduction_needed[g->n_total]; for(int i = 0; i < g->n_total; i++) reduction_needed[i] = false; //continue propagating and reducing until the propagations and reductions are all completed. while( global_done > 0){ //check the size of the global queue, propagate until the current queue is empty. uint64_t global_prop_size = 0; uint64_t local_prop_size = curr_prop_queue->size(); MPI_Allreduce(&local_prop_size, &global_prop_size,1,MPI_INT,MPI_SUM,MPI_COMM_WORLD); std::cout<<"Passing labels\n"; //prop_till_done lets us propagate until no further propagation is possible, //otherwise it just propagates until the current queue is empty. while((prop_till_done && global_prop_size > 0) || (!prop_till_done && curr_prop_queue->size() > 0)){ //go through curr_prop_queue and propagate, filling next_prop_queue with everything that propagates next. uint64_t curr_vtx = curr_prop_queue->front(); curr_prop_queue->pop(); uint64_t curr_gid = curr_vtx; if(curr_vtx < g->n_local) curr_gid = g->local_unmap[curr_vtx]; else curr_gid = g->ghost_unmap[curr_vtx - g->n_local]; int out_degree = 0; uint64_t* nbors = nullptr; if(curr_vtx < g->n_local){ out_degree = out_degree(g, curr_vtx); nbors = out_vertices(g, curr_vtx); } else { out_degree = ghost_offsets[curr_vtx+1 - g->n_local] - ghost_offsets[curr_vtx - g->n_local]; nbors = &ghost_adjs[ghost_offsets[curr_vtx-g->n_local]]; } bool full_reduce = LCA_labels[curr_vtx].size() == 1; //bool reduction_needed = false; for(int nbor_idx = 0; nbor_idx < out_degree; nbor_idx++){ if(full_reduce && reduction_needed[curr_vtx]){ pull_low_labels(curr_vtx, nbors[nbor_idx],g,ghost_offsets,ghost_adjs, LCA_labels,potential_artpts,low_labels, verts_to_send,procs_to_send,levels,remote_levels); } if(nbors[nbor_idx] == 1){ /*std::cout<<"before vertex "<<curr_vtx<<"passes, vertex 1 has labels:\n"; for(auto it = LCA_labels[1].begin(); it != LCA_labels[1].end(); it++){ std::cout<<*it<<" "; } std::cout<<"\n";*/ } pass_labels(g,curr_vtx,nbors[nbor_idx],LCA_labels, remote_levels, low_labels, levels, potential_artpts, potential_artpt_did_prop_lower, curr_prop_queue, next_prop_queue, verts_to_send, procs_to_send, full_reduce, reduction_needed[curr_vtx]); if(nbors[nbor_idx] == 1){ /*std::cout<<"after vertex "<<curr_vtx<<"passes, vertex 1 has labels:\n"; for(auto it = LCA_labels[1].begin(); it != LCA_labels[1].end(); it++){ std::cout<<*it<<" "; } std::cout<<"\n";*/ } } if(potential_artpts[curr_vtx] && !potential_artpt_did_prop_lower[curr_vtx]){ potential_artpt_did_prop_lower[curr_vtx] = true; } //if prop_till_done is set, we need to update the global_prop_size with next_prop_queue->size() //and swap next_prop_queue with curr_prop_queue. if(prop_till_done && curr_prop_queue->size() == 0){ communicate_prop(g,verts_to_send,procs_to_send,LCA_labels,low_labels,LCA_owner,levels,remote_levels,next_prop_queue); std::swap(curr_prop_queue,next_prop_queue); local_prop_size = next_prop_queue->size(); global_prop_size = 0; MPI_Allreduce(&local_prop_size,&global_prop_size,1,MPI_INT,MPI_SUM,MPI_COMM_WORLD); } } std::cout<<"Done propagating\n"; if(!prop_till_done){ communicate_prop(g,verts_to_send,procs_to_send,LCA_labels,low_labels,LCA_owner,levels,remote_levels,next_prop_queue); std::swap(curr_prop_queue, next_prop_queue); } while(irredux_queue->size()) irredux_queue->pop(); std::cout<<"Finding vertices in need of reduction\n"; for(int i = 0; i < g->n_local; i++){ if(LCA_labels[i].size() > 1){ reduction_needed[i] = true; //entries in the reduction queue are of the form //----------------------------------------------------------------------------------------------------- //| GID | owner |current_owner| #labels | label_0, level_0, owner_0 | ... | label_n, level_n, owner_n | //----------------------------------------------------------------------------------------------------- std::vector<uint64_t> temp_entry; temp_entry.push_back(g->local_unmap[i]);//GID temp_entry.push_back(procid);//original owner of vertex (generated this entry) temp_entry.push_back(procid);//current owner (currently has the entry) temp_entry.push_back(LCA_labels[i].size());//number of labels (3*this number is the size of this entry) for(auto it = LCA_labels[i].begin(); it != LCA_labels[i].end(); it++){ temp_entry.push_back(*it); //std::cout<<"vertex "<<i<<" pushing back label "<<*it<<"\n"; if(get_value(g->map,*it) == NULL_KEY){ temp_entry.push_back(remote_levels[*it]); } else { temp_entry.push_back(levels[get_value(g->map,*it)]); } temp_entry.push_back(LCA_owner[*it]); } /*if(i == 1){ std::cout<<"entry for vertex 1 is size "<<temp_entry.size()<<" with "<<LCA_labels[i].size()<<" labels, should be "<<4+LCA_labels[i].size()*3<<"\n"; }*/ curr_redux_queue->push(temp_entry); } else { reduction_needed[i] = false; } } std::cout<<"Done finding vertices in need of reduction\n"; uint64_t local_redux_size = curr_redux_queue->size(); uint64_t global_redux_size = 0; MPI_Allreduce(&local_redux_size,&global_redux_size,1,MPI_INT,MPI_SUM,MPI_COMM_WORLD); std::queue<std::vector<uint64_t>> redux_send_queue; std::cout<<"Reducing labels\n"; while((redux_till_done && global_redux_size > 0) || (!redux_till_done && curr_redux_queue->size() > 0)){ std::vector<uint64_t> curr_reduction = curr_redux_queue->front(); curr_redux_queue->pop(); /*if(curr_redux_queue->size() == 42019){ std::cout<<" first reduction has gid "<<curr_reduction[0]<<"\n"; }*/ /*if(curr_reduction[0] == 243){ std::cout<<"entry size = "<<curr_reduction.size()<<"\n"; std::cout<<"before reduction, vertex "<<curr_reduction[0]<<" has labels:\n"; for(auto it = LCA_labels[curr_reduction[0]].begin(); it != LCA_labels[curr_reduction[0]].end(); it++){ std::cout<<*it<<" "; } std::cout<<"\n"; }*/ reduce_label(g, curr_reduction,redux_send_queue, LCA_labels, LCA_owner, levels, remote_levels); /*if(curr_reduction[0] == 243){ std::cout<<"after reduction, vertex "<<curr_reduction[0]<<" has labels:\n"; for(auto it = LCA_labels[curr_reduction[0]].begin(); it != LCA_labels[curr_reduction[0]].end(); it++){ std::cout<<*it<<" (level "<<levels[*it]<<", has "<<LCA_labels[*it].size()<<" labels) "; } std::cout<<"\n"; }*/ //TODO: Make sure that fully reduced LCA vertices (LCAs that had multiple labels but now only have 1) // get potential_artpt_did_prop_lower set to true on their owning process. //reduce labels: // - do local reductions // - send reductions whose lowest level LCA is owned by another process to that process // - send reductions for a vertex owned by another process back to the owner if progress cannot be made // - update local labels // - repeat until no progress can be made. if(redux_till_done && curr_redux_queue->size() == 0){ //std::cout<<"communicating reductions\n"; communicate_redux(g,&redux_send_queue,next_redux_queue,LCA_labels, potential_artpt_did_prop_lower, potential_artpts, curr_prop_queue,LCA_owner, remote_levels,irredux_queue); //std::cout<<"done communicating reductions, next_redux_queue->size() = "<<next_redux_queue->size()<<"\n"; /*std::cout<<"after communicating, vertex 1 has labels:\n"; for(auto it = LCA_labels[1].begin(); it != LCA_labels[1].end(); it++){ std::cout<<*it<<" "; } std::cout<<"\n";*/ std::swap(curr_redux_queue,next_redux_queue); local_redux_size = curr_redux_queue->size(); global_redux_size = 0; MPI_Allreduce(&local_redux_size, &global_redux_size,1,MPI_INT,MPI_SUM,MPI_COMM_WORLD); } } if(!redux_till_done){ //communicate reductions communicate_redux(g,&redux_send_queue, next_redux_queue, LCA_labels, potential_artpt_did_prop_lower, potential_artpts, next_prop_queue,LCA_owner, remote_levels,irredux_queue); std::swap(curr_redux_queue, next_redux_queue); } done = curr_prop_queue->size() + next_prop_queue->size() + curr_redux_queue->size() + next_redux_queue->size() + irredux_queue->size(); MPI_Allreduce(&done, &global_done, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD); //std::cout<<"global done: "<<global_done<<"\n"; } std::cout<<"Done reducing labels\n"; //set the return values int num_artpts = 0; int num_unreduced = 0; for(uint64_t i = 0; i < g->n_local; i++){ if(LCA_labels[i].size() > 1) num_unreduced ++; articulation_point_flags[i] = 0; if(potential_artpts[i] != 0){ int out_degree = out_degree(g,i); uint64_t* nbors = out_vertices(g, i); for(int nbor = 0; nbor < out_degree; nbor++){ if(levels[i] < levels[nbors[nbor]] && (LCA_labels[i] != LCA_labels[nbors[nbor]] || low_labels[i] != low_labels[nbors[nbor]])){ articulation_point_flags[i] = 1; num_artpts++; break; } } } } //std::cout<<"there are "<<num_unreduced<<" unreduced labels\n"; print_labels(g, 816028, LCA_labels, low_labels, potential_artpts, levels); /*int global_send_total = 0; MPI_Allreduce(&total_send_size, &global_send_total, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD); if(procid == 0){ std::cout<<"Comm Time: "<<total_comm_time<<"\n"; std::cout<<"Total send size: "<<global_send_total<<"\n"; std::cout<<"Num comms: "<<num_comms<<"\n"; }*/ } #endif
HPCGraphAnalysis/bicc
bcc-hipc14/graph.h
#ifndef __graph_h__ #define __graph_h__ typedef struct { int n; unsigned m; int* out_array; unsigned* out_degree_list; int max_degree_vert; double avg_out_degree; } graph; #define out_degree(g, n) (g->out_degree_list[n+1] - g->out_degree_list[n]) #define out_vertices(g, n) (&g->out_array[g->out_degree_list[n]]) #endif
HPCGraphAnalysis/bicc
bcc-dist-3/fast_map.h
/* //@HEADER // ***************************************************************************** // // HPCGraph: Graph Computation on High Performance Computing Systems // Copyright (2016) Sandia Corporation // // Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, // the U.S. Government retains certain rights in this software. // // 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 Corporation nor the names of the // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "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 SANDIA CORPORATION OR THE // 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. // // Questions? Contact <NAME> (<EMAIL>) // <NAME> (<EMAIL>) // <NAME> (<EMAIL>) // // ***************************************************************************** //@HEADER */ #ifndef _FAST_MAP_H_ #define _FAST_MAP_H_ #include <omp.h> #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <vector> extern int procid, nprocs; extern bool verbose, debug, verify, output; #define NULL_KEY 18446744073709551615U struct fast_map { uint64_t* arr; uint64_t* unique_keys; uint64_t* unique_indexes; uint64_t capacity; uint64_t num_unique; bool hashing; } ; bool is_init(fast_map* map); void init_map(fast_map* map); void init_map(fast_map* map, uint64_t init_size); void init_map_nohash(fast_map* map, uint64_t init_size); void clear_map(fast_map* map); void empty_map(fast_map* map); inline uint64_t mult_hash(fast_map* map, uint64_t key); inline void set_value(fast_map* map, uint64_t key, uint64_t value); inline void set_value_uq(fast_map* map, uint64_t key, uint64_t value); inline uint64_t get_value(fast_map* map, uint64_t key); inline uint64_t get_max_key(fast_map* map); inline uint64_t mult_hash(fast_map* map, uint64_t key) { if (map->hashing) return (key*2654435761 % map->capacity); else return key; } inline void set_value(fast_map* map, uint64_t key, uint64_t value) { uint64_t cur_index = mult_hash(map, key)*2; uint64_t count = 0; uint64_t j = 0; while (map->arr[cur_index] != key && map->arr[cur_index] != NULL_KEY) { ++j; cur_index = (cur_index + (j * j * 2)) % (map->capacity*2); //cur_index = mult_hash(map, cur_index + key + 2)*2; //cur_index = (cur_index + 2) % (map->capacity*2); //cur_index = (cur_index + key*2) % (map->capacity*2); ++count; if (debug && count % 100 == 0) fprintf(stderr, "Warning: fast_map set_value(): Big Count %d -- %lu - %lu, %lu, %lu\n", procid, count, cur_index, key, value); } if (map->arr[cur_index] == NULL_KEY) { map->arr[cur_index] = key; } map->arr[cur_index+1] = value; } inline void set_value_uq(fast_map* map, uint64_t key, uint64_t value) { uint64_t cur_index = mult_hash(map, key)*2; uint64_t count = 0; uint64_t j = 0; while (map->arr[cur_index] != key && map->arr[cur_index] != NULL_KEY) { ++j; cur_index = (cur_index + (j * j * 2)) % (map->capacity*2); //cur_index = mult_hash(map, cur_index + key + 2)*2; //cur_index = (cur_index + 2) % (map->capacity*2); //cur_index = (cur_index + key*2) % (map->capacity*2); ++count; if (debug && count % 100 == 0) fprintf(stderr, "Warning: fast_map set_value_uq(): Big Count %d -- %lu - %lu, %lu, %lu\n", procid, count, cur_index, key, value); } if (map->arr[cur_index] == NULL_KEY) { map->arr[cur_index] = key; map->unique_keys[map->num_unique] = key; map->unique_indexes[map->num_unique] = cur_index; ++map->num_unique; } map->arr[cur_index+1] = value; } inline uint64_t get_value(fast_map* map, uint64_t key) { uint64_t cur_index = mult_hash(map, key)*2; uint64_t count = 0; uint64_t j = 0; while (map->arr[cur_index] != key && map->arr[cur_index] != NULL_KEY) { ++j; cur_index = (cur_index + (j * j * 2)) % (map->capacity*2); //cur_index = mult_hash(map, cur_index + key + 2)*2; //cur_index = (cur_index + key*2) % (map->capacity*2); //cur_index = (cur_index + 2) % (map->capacity*2); ++count; if (debug && count % 100 == 0) fprintf(stderr, "Warning: fast_map set_value_uq(): Big Count %d -- %lu - %lu, %lu\n", procid, count, cur_index, key); } if (map->arr[cur_index] == NULL_KEY) return NULL_KEY; else return map->arr[cur_index+1]; } inline uint64_t get_max_key(fast_map* map) { uint64_t max_val = 0; uint64_t max_key = NULL_KEY; std::vector<uint64_t> vec; for (uint64_t i = 0; i < map->num_unique; ++i) if (map->arr[map->unique_indexes[i]+1] > max_val) { max_val = map->arr[map->unique_indexes[i]+1]; vec.clear(); vec.push_back(map->arr[map->unique_indexes[i]]); } else if (map->arr[map->unique_indexes[i]+1] == max_val) { vec.push_back(map->arr[map->unique_indexes[i]]); } if (vec.size() > 0) max_key = vec[(int)rand() % vec.size()]; return max_key; } #endif
HPCGraphAnalysis/bicc
tcc/fast_ts_map.h
<filename>tcc/fast_ts_map.h #ifndef _FAST_TS_MAP_H_ #define _FAST_TS_MAP_H_ #include <omp.h> #include <stdio.h> #include <stdlib.h> #include <stdint.h> #define NULL_KEY 0 struct entry { uint64_t key; bool val; } ; struct fast_ts_map { entry* arr; uint64_t capacity; } ; void init_map(fast_ts_map* map, uint64_t init_size) { map->arr = (entry*)malloc(init_size*sizeof(entry)); if (map->arr == NULL) { printf("init_map(), unable to allocate resources\n"); exit(0); } map->capacity = init_size; #pragma omp parallel for for (uint64_t i = 0; i < map->capacity; ++i) { map->arr[i].key = NULL_KEY; map->arr[i].val = false; } } void clear_map(fast_ts_map* map) { free(map->arr); map->capacity = 0; } inline uint64_t hash64(uint64_t x) { x = (x ^ (x >> 30)) * UINT64_C(0xbf58476d1ce4e5b9); x = (x ^ (x >> 27)) * UINT64_C(0x94d049bb133111eb); x = x ^ (x >> 31); return x; } inline bool test_set_value(fast_ts_map* map, uint32_t src, uint32_t dst) { uint64_t key = (((uint64_t)src << 32) | (uint64_t)dst); uint64_t init_idx = hash64(key) % map->capacity; for (uint64_t idx = init_idx;; idx = (idx+1) % map->capacity) { bool test = false; //test = __sync_fetch_and_or(&map->arr[idx].val, true); #pragma omp atomic capture { test = map->arr[idx].val; map->arr[idx].val = true; } // race condition handling below // - other thread which won slot might have not yet set key if (test == false) { // this thread got empty slot map->arr[idx].key = key; return false; } else if (test == true) {// key already exists in table // wait for key to get set if it isn't yet while (map->arr[idx].key == NULL_KEY) { printf("."); // can comment this out and do other trivial work } if (map->arr[idx].key == key) // this key already exists in table return true; } // else slot is taken by another key, loop and increment } return false; } #endif
HPCGraphAnalysis/bicc
bcc-dist-2/dist_graph.h
/* //@HEADER // ***************************************************************************** // // XtraPuLP: Xtreme-Scale Graph Partitioning using Label Propagation // Copyright (2016) Sandia Corporation // // Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, // the U.S. Government retains certain rights in this software. // // 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 Corporation nor the names of the // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "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 SANDIA CORPORATION OR THE // 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. // // Questions? Contact <NAME> (<EMAIL>) // <NAME> (<EMAIL>) // <NAME> (<EMAIL>) // // ***************************************************************************** //@HEADER */ #ifndef _DIST_GRAPH_H_ #define _DIST_GRAPH_H_ #include <stdint.h> #include "fast_map.h" extern int procid, nprocs; extern bool verbose, debug, verify; struct dist_graph_t; struct mpi_data_t; struct queue_data_t; struct graph_gen_data_t { uint64_t n; uint64_t m; uint64_t n_local; uint64_t n_offset; uint64_t m_local_read; uint64_t m_local_edges; uint64_t *gen_edges; }; struct dist_graph_t { uint64_t n; uint64_t m; uint64_t m_local; uint64_t n_local; uint64_t n_offset; uint64_t n_ghost; uint64_t n_total; uint64_t max_degree_vert; uint64_t max_degree; uint64_t* out_edges; uint64_t* out_degree_list; uint64_t* ghost_degrees; uint64_t* local_unmap; uint64_t* ghost_unmap; uint64_t* ghost_tasks; uint64_t* n_offsets; fast_map* map; } ; #define out_degree(g, n) (g->out_degree_list[n+1] - g->out_degree_list[n]) #define out_vertices(g, n) &g->out_edges[g->out_degree_list[n]] int create_graph(graph_gen_data_t *ggi, dist_graph_t *g); int create_graph_serial(graph_gen_data_t *ggi, dist_graph_t *g); int create_graph(dist_graph_t* g, uint64_t n_global, uint64_t m_global, uint64_t n_local, uint64_t m_local, uint64_t* local_offsets, uint64_t* local_adjs, uint64_t* global_ids); int create_graph_serial(dist_graph_t* g, uint64_t n_global, uint64_t m_global, uint64_t n_local, uint64_t m_local, uint64_t* local_offsets, uint64_t* local_adjs); int clear_graph(dist_graph_t *g); int relabel_edges(dist_graph_t *g); int relabel_edges(dist_graph_t* g, int32_t* part_list); int get_max_degree_vert(dist_graph_t *g); int get_ghost_degrees(dist_graph_t* g); int get_ghost_degrees(dist_graph_t* g, mpi_data_t* comm, queue_data_t* q); int repart_graph(dist_graph_t *g, mpi_data_t* comm, int32_t* part_list); int determine_edge_block(dist_graph_t* g, int32_t*& part_list); inline int32_t highest_less_than(uint64_t* prefix_sums, uint64_t val) { bool found = false; int32_t rank = 0; int32_t bound_low = 0; int32_t bound_high = nprocs; while (!found) { rank = (bound_high + bound_low) / 2; if (prefix_sums[rank] <= val && prefix_sums[rank+1] > val) { found = true; } else if (prefix_sums[rank] < val) bound_low = rank; else if (prefix_sums[rank] > val) bound_high = rank; } return rank; } inline int32_t get_rank(dist_graph_t* g, uint64_t vert) { if (vert >= g->n_offsets[procid] && vert < g->n_offsets[procid+1]) return procid; else { bool found = false; int32_t index = 0; int32_t bound_low = 0; int32_t bound_high = nprocs; while (!found) { index = (bound_high + bound_low) / 2; if (g->n_offsets[index] <= vert && g->n_offsets[index+1] > vert) { return index; } else if (g->n_offsets[index] <= vert) bound_low = index+1; else if (g->n_offsets[index] > vert) bound_high = index; } return index; } return -1; } #endif
HPCGraphAnalysis/bicc
bcc-hipc14/bcc_bfs.h
#ifndef __bcc_bfs_h__ #define __bcc_bfs_h__ #include "graph.h" void bcc_bfs(graph* g, int* bcc_maps, int max_levels); void bcc_bfs_do_bfs(graph* g, int root, int* parents, int* levels, int**& level_queues, int* level_counts, int& num_levels); void bcc_bfs_find_arts(graph* g, int* parents, int* levels, int** level_queues, int* level_counts, int num_levels, int* high, int* low, bool* art_point); void bcc_bfs_do_final_bfs(graph* g, int root, int* parents, int* levels, int** level_queues, int* level_counts, int num_levels, int* high, int* low, bool* art_point); void bcc_bfs_do_labeling(graph* g, int* labels, int& num_bcc, int& num_art, bool* art_point, int* high, int* low, int* levels, int* parents); #endif
HPCGraphAnalysis/bicc
utils/fast_ts_map.h
<reponame>HPCGraphAnalysis/bicc<filename>utils/fast_ts_map.h #ifndef _FAST_TS_MAP_H_ #define _FAST_TS_MAP_H_ #define NULL_KEY 0 #define NULL_KEY32 4294967295U #define NULL_KEY64 18446744073709551615UL #include "stdint.h" struct entry { uint64_t key; uint64_t val; bool test; } ; struct fast_ts_map { entry* arr; uint64_t capacity; } ; void init_map(fast_ts_map* map, uint64_t init_size); void clear_map(fast_ts_map* map); int64_t test_set_value(fast_ts_map* map, uint32_t src, uint32_t dst, uint64_t val); uint64_t get_value(fast_ts_map* map, uint32_t src, uint32_t dst); #endif
HPCGraphAnalysis/bicc
bcc-hipc14/bcc_color.h
<reponame>HPCGraphAnalysis/bicc #ifndef __bcc_color_h__ #define __bcc_color_h__ #include "graph.h" void bcc_color(graph* g, int* bcc_maps); void bcc_color_do_bfs(graph* g, int root, int* parents, int* levels); int bcc_mutual_parent(graph* g, int* levels, int* parents, int vert, int out); void bcc_color_init_mutual_parents(graph* g, int* parents, int* levels, int* high, int* low); void bcc_color_do_coloring(graph* g, int root, int* parents, int* levels, int* high, int* low); void bcc_color_do_labeling(graph* g, int root, int* labels, int& num_bcc, int& num_art, int* high, int* low, int* levels, int* parents); #endif
zheng-rong/vicon_mocap
vicon/include/vicon/ViconVelocity.h
<reponame>zheng-rong/vicon_mocap #ifndef __VICON_VELOCITY_H__ #define __VICON_VELOCITY_H__ #include <ros/ros.h> #include <tf/transform_datatypes.h> #include <geometry_msgs/Twist.h> #include <Eigen/Geometry> class ViconVelocity { public: ViconVelocity(); geometry_msgs::Twist getTwist(const tf::Pose &pose, const ros::Time &timestamp); private: bool initialized; Eigen::Affine3d pose_history[2]; ros::Time timestamp_history[2]; }; #endif
zheng-rong/vicon_mocap
vicon/include/vicon/ViconSubjectPublisher.h
#ifndef __VICON_VICON_SUBJECT_PUBLISHER_H__ #define __VICON_VICON_SUBJECT_PUBLISHER_H__ #include <ros/ros.h> #include "vicon/Subject.h" #include <Eigen/Geometry> class ViconSubjectPublisher { public: ViconSubjectPublisher(ros::Publisher &pub); void publish(vicon::Subject &subject); void calcAndSetTwist(vicon::Subject &subject); private: ros::Publisher publisher_; bool initialized_; Eigen::Vector3d position_history_[2]; Eigen::Matrix3d orientation_history_[2]; ros::Time timestamp_history_[2]; }; #endif
zheng-rong/vicon_mocap
libvicon_driver/include/ViconDriver.h
<gh_stars>1-10 #ifndef __VICON_DRIVER_H__ #define __VICON_DRIVER_H__ #include <stdint.h> #include <string> #include <vector> #include <pthread.h> namespace ViconDataStreamSDK { namespace CPP { class Client; } } class ViconDriver { public: typedef struct _Marker { std::string name; std::string subject_name; double translation[3]; bool occluded; } Marker; typedef struct _Subject { int64_t time_usec; int32_t frame_number; std::string name; bool occluded; double translation[3]; double rotation[4]; // Quaternion(x,y,z,w) std::vector<ViconDriver::Marker> markers; } Subject; typedef struct _Markers { int64_t time_usec; int32_t frame_number; std::vector<ViconDriver::Marker> markers; } Markers; typedef void (*SubjectPubCallback_t)(const ViconDriver::Subject &subject); typedef void (*MarkersPubCallback_t)(const ViconDriver::Markers &markers); ViconDriver(); ~ViconDriver(); bool init(std::string host); // Starts the vicon thread which grabs and processes frames from the server bool start(void); bool shutdown(void); bool enableUnlabeledMarkerData(bool enable); void setSubjectPubCallback(SubjectPubCallback_t callback); void setUnlabeledMarkersPubCallback(MarkersPubCallback_t callback); private: static void *grabThread(void *arg); bool processFrame(int64_t frame_time_usec, unsigned int frame_number); void processSubjects(int64_t frame_time_usec, unsigned int frame_number); void processUnlabeledMarkers(int64_t frame_time_usec, unsigned int frame_number); ViconDataStreamSDK::CPP::Client *client_; bool connected_, running_; SubjectPubCallback_t subject_callback_; MarkersPubCallback_t unlabeled_markers_callback_; pthread_t grab_thread_; bool grab_frames_; bool unlabeled_marker_data_enabled_; }; #endif
zheng-rong/vicon_mocap
vicon_odom/include/vicon_odom/filter.h
<reponame>zheng-rong/vicon_mocap<filename>vicon_odom/include/vicon_odom/filter.h<gh_stars>1-10 #include <Eigen/Core> class KalmanFilter { public: static const int n_states = 6; static const int n_meas = 3; typedef Eigen::Matrix<double, n_states, 1> State_t; typedef Eigen::Matrix<double, n_states, n_states> ProcessCov_t; typedef Eigen::Matrix<double, n_meas, 1> Measurement_t; typedef Eigen::Matrix<double, n_meas, n_meas> MeasurementCov_t; KalmanFilter(); KalmanFilter(const State_t &state, const ProcessCov_t &initial_cov, const ProcessCov_t &process_noise, const MeasurementCov_t &meas_noise); void initialize(const State_t &state, const ProcessCov_t &initial_cov, const ProcessCov_t &process_noise, const MeasurementCov_t &meas_noise); void processUpdate(double dt); void measurementUpdate(const Measurement_t &meas, double dt); void setProcessNoise(const ProcessCov_t &process_noise); void setMeasurementNoise(const MeasurementCov_t &meas_noise); const State_t &getState(void); const ProcessCov_t &getProcessNoise(void); private: State_t x; ProcessCov_t P, Q; MeasurementCov_t R; };
zheng-rong/vicon_mocap
libvicon_driver/include/ViconCalib.h
#ifndef __VICON_CALIB_H__ #define __VICON_CALIB_H__ #include <Eigen/Geometry> #include <vector> #include <map> namespace ViconCalib { bool loadZeroPoseFromFile(const std::string &filename, Eigen::Affine3d &zero_pose); bool saveZeroPoseToFile(const Eigen::Affine3d &zero_pose, const std::string &filename); bool getTransform(const std::vector<Eigen::Vector3d> &reference_points, const std::vector<Eigen::Vector3d> &actual_points, Eigen::Affine3d &transform); bool loadCalibMarkerPos(const std::string &filename, std::map<std::string, Eigen::Vector3d> &marker_pos_map); } #endif
Brandhoej/Y86-64-VM
src/writer.h
<filename>src/writer.h #ifndef cero_writer_h #define cero_writer_h #include "common.h" #include "value.h" /* Encodings */ #define REG_SPEC_ENC_RARB(rA, rB) ((rA << 4) | rB) #define REG_SPEC_ENC_RA(ra) (REG_SPEC_ENC_RARB(ra, REG_F)) #define REG_SPEC_ENC_RB(rb) (REG_SPEC_ENC_RARB(REG_F, rb)) /* Decodings */ #define REG_SPEC_DEC_RA(regSpec) (regSpec >> 4) #define REG_SPEC_DEC_RB(regSpec) (regSpec & 0x0F) typedef struct { uint32_t offset; vm_byte_t* destination; } Writer; void initWriter(Writer* writer, vm_byte_t* destination, uint32_t offset); void freeWriter(Writer* writer); /* Execution */ void haltWrite(Writer* writer); void nopWrite(Writer* writer); /* Register */ void rrmovqWrite(Writer* writer, vm_ubyte_t rA, vm_ubyte_t rB); void irmovqWrite(Writer* writer, vm_ubyte_t rB, vm_quad_t v); void rmmovqWrite(Writer* writer, vm_ubyte_t rA, vm_ubyte_t rB, vm_quad_t d); void mrmovqWrite(Writer* writer, vm_ubyte_t rA, vm_ubyte_t rB, vm_quad_t d); /* Operations */ void addqWrite(Writer* writer, vm_ubyte_t rA, vm_ubyte_t rB); void subqWrite(Writer* writer, vm_ubyte_t rA, vm_ubyte_t rB); void andqWrite(Writer* writer, vm_ubyte_t rA, vm_ubyte_t rB); void xorqWrite(Writer* writer, vm_ubyte_t rA, vm_ubyte_t rB); /* Branches */ void jmpWrite(Writer* writer, vm_quad_t dest); void jleWrite(Writer* writer, vm_quad_t dest); void jlWrite(Writer* writer, vm_quad_t dest); void jeWrite(Writer* writer, vm_quad_t dest); void jneWrite(Writer* writer, vm_quad_t dest); void jgeWrite(Writer* writer, vm_quad_t dest); void jgWrite(Writer* writer, vm_quad_t dest); /* Moves */ void cmovleWrite(Writer* writer, vm_ubyte_t rA, vm_ubyte_t rB); void cmovlWrite(Writer* writer, vm_ubyte_t rA, vm_ubyte_t rB); void cmoveWrite(Writer* writer, vm_ubyte_t rA, vm_ubyte_t rB); void cmovneWrite(Writer* writer, vm_ubyte_t rA, vm_ubyte_t rB); void cmovgeWrite(Writer* writer, vm_ubyte_t rA, vm_ubyte_t rB); void cmovgWrite(Writer* writer, vm_ubyte_t rA, vm_ubyte_t rB); /* Computation */ void callWrite(Writer* writer, vm_quad_t dest); void retWrite(Writer* writer); /* Stack */ void pushqWrite(Writer* writer, vm_ubyte_t rA); void popqWrite(Writer* writer, vm_ubyte_t rA); #endif
Brandhoej/Y86-64-VM
src/vm.c
<reponame>Brandhoej/Y86-64-VM<gh_stars>0 #include <stdio.h> #include <inttypes.h> #include <math.h> #include "common.h" #include "vm.h" #include "memory.h" #include "writer.h" #include "printer.h" void initVM(VM* vm) { vm->registers = NULL; vm->memory = NULL; vm->registers = INIT_ARRAY(vm_quad_t, vm->registers, REG_COUNT); vm->memory = INIT_ARRAY(vm_byte_t, vm->memory, MEM_MAX); vm->pc = 0; vm->registers[REG_RBP] = MEM_MAX; vm->registers[REG_RSP] = vm->registers[REG_RBP]; vm->statusCondition = STAT_AOK; } void freeVM(VM* vm) { } bool inline zf(VM* vm) { return (vm->conditionCodes & 0b0001) >> CC_ZF; } bool inline sf(VM* vm) { return (vm->conditionCodes & 0b0010) >> CC_SF; } bool inline of(VM* vm) { return (vm->conditionCodes & 0b0100) >> CC_OF; } static bool inline addrInHighMem(VM* vm, vm_quad_t addr) { vm_quad_t rsp = vm->registers[REG_RSP]; return addr >= rsp; } static bool inline addrInLowMem(VM* vm, vm_quad_t addr) { vm_quad_t rsp = vm->registers[REG_RSP]; return addr < rsp; } vm_ubyte_t inline m1r(VM* vm, vm_quad_t offset) { return vm->memory[offset]; } vm_quad_t inline m8r(VM* vm, vm_quad_t offset) { vm_quad_t quad = 0; quad |= m1r(vm, offset + 0); quad <<= 8; quad |= m1r(vm, offset + 1); quad <<= 8; quad |= m1r(vm, offset + 2); quad <<= 8; quad |= m1r(vm, offset + 3); quad <<= 8; quad |= m1r(vm, offset + 4); quad <<= 8; quad |= m1r(vm, offset + 5); quad <<= 8; quad |= m1r(vm, offset + 6); quad <<= 8; quad |= m1r(vm, offset + 7); quad <<= 0; return quad; } vm_ubyte_t m1w(VM* vm, vm_quad_t offset, vm_ubyte_t byte) { vm->memory[offset] = byte; } vm_quad_t m8w(VM* vm, vm_quad_t offset, vm_quad_t quad) { m1w(vm, offset + 7, (quad >> 0) & 0xFF); m1w(vm, offset + 6, (quad >> 8) & 0xFF); m1w(vm, offset + 5, (quad >> 16) & 0xFF); m1w(vm, offset + 4, (quad >> 24) & 0xFF); m1w(vm, offset + 3, (quad >> 32) & 0xFF); m1w(vm, offset + 2, (quad >> 40) & 0xFF); m1w(vm, offset + 1, (quad >> 48) & 0xFF); m1w(vm, offset + 0, (quad >> 56) & 0xFF); } /* -----Information about standards----- * Fetch: Read instruction from memory * Decode: Read program registers * Execute: Compute value or address * Memory: Read or write data * Write Back: write program registers * PC: Update program counter * * Instruction format (10 bytes max) * Instruction byte: icode:ifun * Optional register byte: rA:rB * Optional constant word: valC * * https://w3.cs.jmu.edu/lam2mo/cs261_2018_08/files/y86-isa.pdf */ /* 0 1 2 3 4 5 6 7 8 9 10 */ /* 00 */ static inline void halt(VM* vm) { CERO_DEBUG("ins::halt\n"); /* Fetch */ vm_quad_t valP = vm->pc + 1; /* Decode */ /* Execute */ /* Memory */ /* Write back */ vm->statusCondition = STAT_HLT; /* PC update */ vm->pc = valP; } /* 0 1 2 3 4 5 6 7 8 9 10 */ /* 10 */ static inline void nop(VM* vm) { CERO_DEBUG("ins::nop\n"); /* Fetch */ vm_quad_t valP = vm->pc + 1; /* Decode */ /* Execute */ /* Memory */ /* Write back */ /* PC update */ vm->pc = valP; } /* 0 1 2 3 4 5 6 7 8 9 10 */ /* 20 AB */ static inline void rrmovq(VM* vm) { CERO_DEBUG("ins::rrmovq\n"); /* Fetch */ vm_ubyte_t rArB = m1r(vm, vm->pc + 1); vm_ubyte_t rA = REG_SPEC_DEC_RA(rArB); vm_ubyte_t rB = REG_SPEC_DEC_RB(rArB); vm_quad_t valP = vm->pc + 2; /* Decode */ vm_quad_t valB = vm->registers[rB]; /* Execute */ /* Memory */ /* Write back */ vm->registers[rA] = valB; /* PC update */ vm->pc = valP; } /* 0 1 2 3 4 5 6 7 8 9 10 */ /* 30 FB -----------V----------- */ static inline void irmovq(VM* vm) { CERO_DEBUG("ins::irmovq\n"); /* Fetch */ vm_ubyte_t rArB = m1r(vm, vm->pc + 1); vm_ubyte_t rB = REG_SPEC_DEC_RB(rArB); vm_quad_t valC = m8r(vm, vm->pc + 2); vm_quad_t valP = vm->pc + 10; /* Decode */ /* Execute */ vm_quad_t valE = valC; /* Memory */ /* Write back */ vm->registers[rB] = valE; /* PC update */ vm->pc = valP; } /* 0 1 2 3 4 5 6 7 8 9 10 */ /* 40 AB -----------D----------- */ static inline void rmmovq(VM* vm) { CERO_DEBUG("ins::rmmovq\n"); /* Fetch */ vm_ubyte_t rArB = m1r(vm, vm->pc + 1); vm_ubyte_t rA = REG_SPEC_DEC_RA(rArB); vm_ubyte_t rB = REG_SPEC_DEC_RB(rArB); vm_quad_t valC = m8r(vm, vm->pc + 2); vm_quad_t valP = vm->pc + 10; /* Decode */ vm_quad_t valA = vm->registers[rA]; vm_quad_t valB = vm->registers[rB]; /* Execute */ vm_quad_t valE = valA + valC; CERO_DEBUG("valE %" PRId64 "\n", valE); /* Memory */ if (addrInHighMem(vm, valE) || addrInHighMem(vm, valE + 8)) { vm->statusCondition = STAT_ADR; return; } m8w(vm, valE, valB); /* Write back */ /* PC update */ vm->pc = valP; } /* 0 1 2 3 4 5 6 7 8 9 10 */ /* 50 AB -----------D----------- */ static inline void mrmovq(VM* vm) { CERO_DEBUG("ins::mrmovq\n"); /* Fetch */ vm_ubyte_t rArB = m1r(vm, vm->pc + 1); vm_ubyte_t rA = REG_SPEC_DEC_RA(rArB); vm_ubyte_t rB = REG_SPEC_DEC_RB(rArB); vm_quad_t valC = m8r(vm, vm->pc + 2); vm_quad_t valP = vm->pc + 10; /* Decode */ vm_quad_t valA = vm->registers[rA]; vm_quad_t valB = vm->registers[rB]; /* Execute */ vm_quad_t valE = valB + valC; /* Memory */ vm_quad_t valM = m8r(vm, valE); /* Write back */ vm->registers[rA] = valM; /* PC update */ vm->pc = valP; } /* 0 1 2 3 4 5 6 7 8 9 10 */ /* 60 AB */ static inline void addq(VM* vm) { CERO_DEBUG("ins::addq\n"); /* Fetch */ vm_ubyte_t rArB = m1r(vm, vm->pc + 1); vm_ubyte_t rA = REG_SPEC_DEC_RA(rArB); vm_ubyte_t rB = REG_SPEC_DEC_RB(rArB); vm_quad_t valP = vm->pc + 2; /* Decode */ vm_quad_t valA = vm->registers[rA]; vm_quad_t valB = vm->registers[rB]; /* Execute */ vm_quad_t valE = valB + valA; vm->conditionCodes |= (valE == 0 ? 1 : 0) << CC_ZF | (valE < 0 ? 1 : 0) << CC_SF | (((valA > 0 && valB > INT64_MAX - valA) || (valA < 0 && valB < INT64_MIN - valA)) ? 1 : 0) << CC_OF; /* Memory */ /* Write back */ vm->registers[rB] = valE; /* PC update */ vm->pc = valP; } /* 0 1 2 3 4 5 6 7 8 9 10 */ /* 61 AB */ static inline void subq(VM* vm) { CERO_DEBUG("ins::subq\n"); /* Fetch */ vm_ubyte_t rArB = m1r(vm, vm->pc + 1); vm_ubyte_t rA = REG_SPEC_DEC_RA(rArB); vm_ubyte_t rB = REG_SPEC_DEC_RB(rArB); vm_quad_t valP = vm->pc + 2; /* Decode */ vm_quad_t valA = vm->registers[rA]; vm_quad_t valB = vm->registers[rB]; /* Execute */ vm_quad_t valE = valB - valA; vm->conditionCodes |= (valE == 0 ? 1 : 0) << CC_ZF | (valE < 0 ? 1 : 0) << CC_SF | (((valA > 0 && valB > INT64_MAX - valA) || (valA < 0 && valB < INT64_MIN - valA)) ? 1 : 0) << CC_OF; /* Memory */ /* Write back */ vm->registers[rB] = valE; /* PC update */ vm->pc = valP; } /* 0 1 2 3 4 5 6 7 8 9 10 */ /* 62 AB */ static inline void andq(VM* vm) { CERO_DEBUG("ins::andq\n"); /* Fetch */ vm_ubyte_t rArB = m1r(vm, vm->pc + 1); vm_ubyte_t rA = REG_SPEC_DEC_RA(rArB); vm_ubyte_t rB = REG_SPEC_DEC_RB(rArB); vm_quad_t valP = vm->pc + 2; /* Decode */ vm_quad_t valA = vm->registers[rA]; vm_quad_t valB = vm->registers[rB]; /* Execute */ vm_quad_t valE = valB & valA; vm->conditionCodes |= (valE == 0 ? 1 : 0) << CC_ZF | (valE < 0 ? 1 : 0) << CC_SF | (((valA > 0 && valB > INT64_MAX - valA) || (valA < 0 && valB < INT64_MIN - valA)) ? 1 : 0) << CC_OF; /* Memory */ /* Write back */ vm->registers[rB] = valE; /* PC update */ vm->pc = valP; } /* 0 1 2 3 4 5 6 7 8 9 10 */ /* 63 AB */ static inline void xorq(VM* vm) { CERO_DEBUG("ins::xorq\n"); /* Fetch */ vm_ubyte_t rArB = m1r(vm, vm->pc + 1); vm_ubyte_t rA = REG_SPEC_DEC_RA(rArB); vm_ubyte_t rB = REG_SPEC_DEC_RB(rArB); vm_quad_t valP = vm->pc + 2; /* Decode */ vm_quad_t valA = vm->registers[rA]; vm_quad_t valB = vm->registers[rB]; /* Execute */ vm_quad_t valE = valB ^ valA; vm->conditionCodes |= (valE == 0 ? 1 : 0) << CC_ZF | (valE < 0 ? 1 : 0) << CC_SF | (((valA > 0 && valB > INT64_MAX - valA) || (valA < 0 && valB < INT64_MIN - valA)) ? 1 : 0) << CC_OF; /* Memory */ /* Write back */ vm->registers[rB] = valE; /* PC update */ vm->pc = valP; } /* 0 1 2 3 4 5 6 7 8 9 10 */ /* 70 ---------Dest---------- */ static inline void jmp(VM* vm) { CERO_DEBUG("ins::jmp\n"); /* Fetch */ vm_quad_t valC = m8r(vm, vm->pc + 1); vm_quad_t valP = vm->pc + 9; /* Decode */ /* Execute */ bool cnd = true; /* Memory */ /* Write back */ /* PC update */ vm->pc = cnd ? valC : valP; } /* 0 1 2 3 4 5 6 7 8 9 10 */ /* 71 ---------Dest---------- */ static inline void jle(VM* vm) { CERO_DEBUG("ins::jle\n"); /* Fetch */ vm_quad_t valC = m8r(vm, vm->pc + 1); vm_quad_t valP = vm->pc + 9; /* Decode */ /* Execute */ bool cnd = sf(vm) | zf(vm); /* Memory */ /* Write back */ /* PC update */ vm->pc = cnd ? valC : valP; } /* 0 1 2 3 4 5 6 7 8 9 10 */ /* 72 ---------Dest---------- */ static inline void jl(VM* vm) { CERO_DEBUG("ins::jl\n"); /* Fetch */ vm_quad_t valC = m8r(vm, vm->pc + 1); vm_quad_t valP = vm->pc + 9; /* Decode */ /* Execute */ bool cnd = sf(vm); /* Memory */ /* Write back */ /* PC update */ vm->pc = cnd ? valC : valP; } /* 0 1 2 3 4 5 6 7 8 9 10 */ /* 73 ---------Dest---------- */ static inline void je(VM* vm) { CERO_DEBUG("ins::je\n"); /* Fetch */ vm_quad_t valC = m8r(vm, vm->pc + 1); vm_quad_t valP = vm->pc + 9; /* Decode */ /* Execute */ bool cnd = zf(vm); /* Memory */ /* Write back */ /* PC update */ vm->pc = cnd ? valC : valP; } /* 0 1 2 3 4 5 6 7 8 9 10 */ /* 74 ---------Dest---------- */ static inline void jne(VM* vm) { CERO_DEBUG("ins::jne\n"); /* Fetch */ vm_quad_t valC = m8r(vm, vm->pc + 1); vm_quad_t valP = vm->pc + 9; /* Decode */ /* Execute */ bool cnd = !zf(vm); /* Memory */ /* Write back */ /* PC update */ vm->pc = cnd ? valC : valP; } /* 0 1 2 3 4 5 6 7 8 9 10 */ /* 75 ---------Dest---------- */ static inline void jge(VM* vm) { CERO_DEBUG("ins::jge\n"); /* Fetch */ vm_quad_t valC = m8r(vm, vm->pc + 1); vm_quad_t valP = vm->pc + 9; /* Decode */ /* Execute */ bool cnd = !sf(vm); /* Memory */ /* Write back */ /* PC update */ vm->pc = cnd ? valC : valP; } /* 0 1 2 3 4 5 6 7 8 9 10 */ /* 76 ---------Dest---------- */ static inline void jg(VM* vm) { CERO_DEBUG("ins::jg\n"); /* Fetch */ vm_quad_t valC = m8r(vm, vm->pc + 1); vm_quad_t valP = vm->pc + 9; /* Decode */ /* Execute */ bool cnd = !sf(vm) & !zf(vm); /* Memory */ /* Write back */ /* PC update */ vm->pc = cnd ? valC : valP; } /* 0 1 2 3 4 5 6 7 8 9 10 */ /* 21 AB */ static inline void cmovle(VM* vm) { CERO_DEBUG("ins::cmovle\n"); /* Fetch */ vm_ubyte_t rArB = m1r(vm, vm->pc + 1); vm_ubyte_t rA = REG_SPEC_DEC_RA(rArB); vm_ubyte_t rB = REG_SPEC_DEC_RB(rArB); vm_quad_t valP = vm->pc + 2; /* Decode */ vm_quad_t valA = vm->registers[rA]; /* Execute */ vm_quad_t valE = valA; bool cnd = sf(vm) | zf(vm); /* Memory */ /* Write back */ if (cnd) { vm->registers[rB] = valE; } /* PC update */ vm->pc = valP; } /* 0 1 2 3 4 5 6 7 8 9 10 */ /* 22 AB */ static inline void cmovl(VM* vm) { CERO_DEBUG("ins::cmovl\n"); /* Fetch */ vm_ubyte_t rArB = m1r(vm, vm->pc + 1); vm_ubyte_t rA = REG_SPEC_DEC_RA(rArB); vm_ubyte_t rB = REG_SPEC_DEC_RB(rArB); vm_quad_t valP = vm->pc + 2; /* Decode */ vm_quad_t valA = vm->registers[rA]; /* Execute */ vm_quad_t valE = valA; bool cnd = sf(vm); /* Memory */ /* Write back */ if (cnd) { vm->registers[rB] = valE; } /* PC update */ vm->pc = valP; } /* 0 1 2 3 4 5 6 7 8 9 10 */ /* 23 AB */ static inline void cmove(VM* vm) { CERO_DEBUG("ins::cmove\n"); /* Fetch */ vm_ubyte_t rArB = m1r(vm, vm->pc + 1); vm_ubyte_t rA = REG_SPEC_DEC_RA(rArB); vm_ubyte_t rB = REG_SPEC_DEC_RB(rArB); vm_quad_t valP = vm->pc + 2; /* Decode */ vm_quad_t valA = vm->registers[rA]; /* Execute */ vm_quad_t valE = valA; bool cnd = zf(vm); /* Memory */ /* Write back */ if (cnd) { vm->registers[rB] = valE; } /* PC update */ vm->pc = valP; } /* 0 1 2 3 4 5 6 7 8 9 10 */ /* 24 AB */ static inline void cmovne(VM* vm) { CERO_DEBUG("ins::cmovne\n"); /* Fetch */ vm_ubyte_t rArB = m1r(vm, vm->pc + 1); vm_ubyte_t rA = REG_SPEC_DEC_RA(rArB); vm_ubyte_t rB = REG_SPEC_DEC_RB(rArB); vm_quad_t valP = vm->pc + 2; /* Decode */ vm_quad_t valA = vm->registers[rA]; /* Execute */ vm_quad_t valE = valA; bool cnd = !zf(vm); /* Memory */ /* Write back */ if (cnd) { vm->registers[rB] = valE; } /* PC update */ vm->pc = valP; } /* 0 1 2 3 4 5 6 7 8 9 10 */ /* 25 AB */ static inline void cmovge(VM* vm) { CERO_DEBUG("ins::cmovge\n"); /* Fetch */ vm_ubyte_t rArB = m1r(vm, vm->pc + 1); vm_ubyte_t rA = REG_SPEC_DEC_RA(rArB); vm_ubyte_t rB = REG_SPEC_DEC_RB(rArB); vm_quad_t valP = vm->pc + 2; /* Decode */ vm_quad_t valA = vm->registers[rA]; /* Execute */ vm_quad_t valE = valA; bool cnd = !sf(vm); /* Memory */ /* Write back */ if (cnd) { vm->registers[rB] = valE; } /* PC update */ vm->pc = valP; } /* 0 1 2 3 4 5 6 7 8 9 10 */ /* 80 ---------Dest---------- */ static inline void cmovg(VM* vm) { CERO_DEBUG("ins::cmovg\n"); /* Fetch */ vm_ubyte_t rArB = m1r(vm, vm->pc + 1); vm_ubyte_t rA = REG_SPEC_DEC_RA(rArB); vm_ubyte_t rB = REG_SPEC_DEC_RB(rArB); vm_quad_t valP = vm->pc + 2; /* Decode */ vm_quad_t valA = vm->registers[rA]; /* Execute */ vm_quad_t valE = valA; bool cnd = !sf(vm) & !zf(vm); /* Memory */ /* Write back */ if (cnd) { vm->registers[rB] = valE; } /* PC update */ vm->pc = valP; } /* 0 1 2 3 4 5 6 7 8 9 10 */ /* 80 AB */ static inline void call(VM* vm) { CERO_DEBUG("ins::call\n"); /* Fetch */ vm_quad_t valC = m8r(vm, vm->pc + 1); vm_quad_t valP = vm->pc + 9; /* Decode */ vm_quad_t valB = vm->registers[REG_RSP]; /* Execute */ vm_quad_t valE = valB - 8; /* Memory */ if (addrInHighMem(vm, valE) || addrInHighMem(vm, valE + 8)) { vm->statusCondition = STAT_ADR; return; } m8w(vm, valE, valP); /* Write back */ vm->registers[REG_RSP] = valE; /* PC update */ vm->pc = valP; } /* 0 1 2 3 4 5 6 7 8 9 10 */ /* 90 */ static inline void ret(VM* vm) { CERO_DEBUG("ins::ret\n"); /* Fetch */ vm_quad_t valP = vm->pc + 1; /* Decode */ vm_quad_t valA = vm->registers[REG_RSP]; vm_quad_t valB = vm->registers[REG_RSP]; /* Execute */ vm_quad_t valE = valB + 8; /* Memory */ vm_quad_t valM = m8r(vm, valA); /* Write back */ vm->registers[REG_RSP] = valE; /* PC update */ vm->pc = valP; } /* 0 1 2 3 4 5 6 7 8 9 10 */ /* 20 AF */ static inline void pushq(VM* vm) { CERO_DEBUG("ins::pushq\n"); /* Fetch */ vm_ubyte_t rArB = m1r(vm, vm->pc + 1); vm_ubyte_t rA = REG_SPEC_DEC_RA(rArB); vm_quad_t valP = vm->pc + 2; /* Decode */ vm_quad_t valA = vm->registers[rA]; vm_quad_t valB = vm->registers[REG_RSP]; /* Execute */ vm_quad_t valE = valB - 8; /* Memory */ m8w(vm, valE, valA); /* Write back */ vm->registers[REG_RSP] = valE; /* PC update */ vm->pc = valP; } /* 0 1 2 3 4 5 6 7 8 9 10 */ /* 20 AF */ static inline void popq(VM* vm) { CERO_DEBUG("ins::popq\n"); /* Fetch */ vm_ubyte_t rArB = m1r(vm, vm->pc + 1); vm_ubyte_t rA = REG_SPEC_DEC_RA(rArB); vm_quad_t valP = vm->pc + 2; /* Decode */ vm_quad_t valA = vm->registers[REG_RSP]; vm_quad_t valB = vm->registers[REG_RSP]; /* Execute */ vm_quad_t valE = valB + 8; /* Memory */ vm_quad_t valM = m8r(vm, valA); /* Write back */ vm->registers[REG_RSP] = valE; vm->registers[rA] = valM; /* PC update */ vm->pc = valP; } void run(VM* vm) { while(vm->statusCondition == STAT_AOK) { switch ((vm_ubyte_t)m1r(vm, vm->pc)) { case INS_HALT: halt(vm); break; case INS_NOP: nop(vm); break; case INS_RRMOVQ: rrmovq(vm); break; case INS_IRMOVQ: irmovq(vm); break; case INS_RMMOVQ: rmmovq(vm); break; case INS_MRMOVQ: mrmovq(vm); break; case INS_ADDQ: addq(vm); break; case INS_SUBQ: subq(vm); break; case INS_ANDQ: andq(vm); break; case INS_XORQ: xorq(vm); break; case INS_JMP: jmp(vm); break; case INS_JLE: jle(vm); break; case INS_JL: jl(vm); break; case INS_JE: je(vm); break; case INS_JNE: jne(vm); break; case INS_JGE: jge(vm); break; case INS_JG: jg(vm); break; case INS_CMOVLE: cmovle(vm); break; case INS_CMOVL: cmovl(vm); break; case INS_CMOVE: cmove(vm); break; case INS_CMOVNE: cmovne(vm); break; case INS_CMOVGE: cmovge(vm); break; case INS_CMOVG: cmovg(vm); break; case INS_CALL: call(vm); break; case INS_RET: ret(vm); break; case INS_PUSHQ: pushq(vm); break; case INS_POPQ: popq(vm); break; default: vm->conditionCodes = STAT_INS; break; } printMemory(vm); printRegisters(vm); printStack(vm); printFlagsAndStatusAndPc(vm); } }
Brandhoej/Y86-64-VM
src/printer.c
#include "printer.h" void printRegisters(VM* vm) { const vm_quad_t columnCount = 3; const vm_quad_t rowCount = REG_COUNT / columnCount + 1; const vm_quad_t offset = rowCount * columnCount - REG_COUNT; for (vm_quad_t r = 0; r < rowCount; ++r) { CERO_TRACE(); for (vm_quad_t c = 0; c < columnCount; ++c) { vm_quad_t offsetR = rowCount - r - 1; vm_quad_t offsetC = columnCount - c - 1; vm_quad_t i = (REG_COUNT - 1) - (offsetR + offsetC * rowCount); if (i < 0 || i >= REG_COUNT) { CERO_PRINT(" "); continue; } switch (i) { case 0: CERO_PRINT("RAX "); break; case 1: CERO_PRINT("RCX "); break; case 2: CERO_PRINT("RDX "); break; case 3: CERO_PRINT("RBX "); break; case 4: CERO_PRINT("RSP "); break; case 5: CERO_PRINT("RBP "); break; case 6: CERO_PRINT("RSI "); break; case 7: CERO_PRINT("RDI "); break; case 8: CERO_PRINT("R8 "); break; case 9: CERO_PRINT("R9 "); break; case 10: CERO_PRINT("R10 "); break; case 11: CERO_PRINT("R11 "); break; case 12: CERO_PRINT("R12 "); break; case 13: CERO_PRINT("R13 "); break; case 14: CERO_PRINT("R14 "); break; case 15: CERO_PRINT("F "); break; } CERO_PRINT("0x%016" PRIx64, vm->registers[i]); CERO_PRINT(" "); } CERO_PRINT("\n"); } } void printFlagsAndStatusAndPc(VM* vm) { CERO_TRACE(); CERO_PRINT("ZF:%d ", (vm->conditionCodes & 0b0001) >> CC_ZF); CERO_PRINT("SF:%d ", (vm->conditionCodes & 0b0010) >> CC_SF); CERO_PRINT("OF:%d ", (vm->conditionCodes & 0b0100) >> CC_OF); CERO_PRINT("STAT:"); switch (vm->statusCondition) { case STAT_AOK: CERO_PRINT("AOK"); break; case STAT_HLT: CERO_PRINT("HLT"); break; case STAT_ADR: CERO_PRINT("ADR"); break; case STAT_INS: CERO_PRINT("INS"); break; } CERO_PRINT(" "); CERO_PRINT("PC:0x%06" PRIxPTR, vm->pc); CERO_PRINT("\n"); } void printStack(VM* vm) { vm_quad_t rbp = vm->registers[REG_RBP]; vm_quad_t rsp = vm->registers[REG_RSP]; if (rbp == rsp) { CERO_TRACE("[ ]"); } else { CERO_TRACE(); for (vm_quad_t mem = rsp; mem < rbp; mem += 8) { CERO_PRINT("[ %" PRId64 " ]", m8r(vm, mem)); } } CERO_PRINT("\n"); } void printMemory(VM* vm) { vm_quad_t rbp = vm->registers[REG_RBP]; vm_quad_t rsp = vm->registers[REG_RSP]; const vm_quad_t memorySize = MEM_MAX; const vm_quad_t bytesPerItem = 8; const vm_quad_t columnCount = 3; const vm_quad_t bytesPerColumn = columnCount * bytesPerItem; const vm_quad_t rowCount = (memorySize + bytesPerColumn) / bytesPerColumn; for (vm_quad_t row = 0; row < rowCount; ++row) { CERO_TRACE(); for (vm_quad_t column = 0; column < bytesPerColumn; ++column) { vm_quad_t iRow = rowCount - row - 1; vm_quad_t iColumn = bytesPerColumn - column - 1; vm_quad_t iByte = ((rowCount * bytesPerItem * (iColumn / bytesPerItem)) + (iRow * bytesPerItem) + (bytesPerItem - 1) - ((iRow * bytesPerItem) + iColumn) % bytesPerItem); if (iColumn % bytesPerItem == bytesPerItem - 1) { CERO_PRINT("0x%04" PRIx64, iByte); CERO_PRINT(" 0x"); } if (iByte >= 0 && iByte < memorySize) { CERO_PRINT("%02" PRIx8, vm->memory[iByte]); } else { CERO_PRINT("__"); } if (iColumn > 0 && iColumn % 8 == 0) { bool printRBP = false, printRSP = false; if (rsp > iByte - 8 && rsp <= iByte) { printRSP = true; } if(rbp > iByte - 8 && rbp <= iByte) { printRBP = true; } if (printRBP && printRSP) { CERO_PRINT("<RBP RSP "); } else if (printRBP) { CERO_PRINT("<RBP "); } else if (printRSP) { CERO_PRINT("<RSP "); } else { CERO_PRINT(" "); } } } CERO_PRINT("\n"); } }
Brandhoej/Y86-64-VM
src/memory.c
<filename>src/memory.c<gh_stars>0 #include <stdlib.h> #include "memory.h" /* Operation to perform based on the actual parameters: * /---------------------------------------------------------------\ * | oldSize | newSize | Operation | * |----------+----------------------+-----------------------------| * | 0 | Non-zero | Allocate new block. | * | Non-zero | 0 | Free allocation. | * | Non-zero | Smaller than oldSize | Shrink existing allocation. | * | Non-zero | Greater than oldSize | Grow existing allocation. | * \---------------------------------------------------------------/ * Handles allocating memoty, freeing it and changing the size of an * existing allocation. Routing all of those operations through a single function * is done for the convenience of the garbage collector (GC) and statistics. * */ void* reallocate(void* pointer, size_t oldSize, size_t newSize) { if (newSize == 0) { free(pointer); return NULL; } /* realloc handles cases: 1, 3, 4. * * If the new size is smaller than the existing block of memory, * it simply updates the size of the block and returns the same pointer you gave it. * If the new size is larger, it attempts to grow the existing block of memory. * * It can do that only if the memory after that block isn’t already in use. * If there isn’t room to grow the block, realloc() instead allocates a new * block of memory of the desired size, copies over the old bytes, * frees the old block, and then returns a pointer to the new block. */ void* result = realloc(pointer, newSize); if (result == NULL) { exit(1); } /* We assume the need of reseting all bits when creating a new array */ if (oldSize == 0) { result = memset(result, 0, newSize); } return result; }
Brandhoej/Y86-64-VM
src/common.h
#ifndef cero_common_h #define cero_common_h #include <stdbool.h> #include <stddef.h> #include <stdint.h> #include <inttypes.h> #include "logger.h" #define DEBUG_TRACE_EXECUTION #endif
Brandhoej/Y86-64-VM
src/printer.h
<reponame>Brandhoej/Y86-64-VM #ifndef cero_printer_h #define cero_printer_h #include "common.h" #include "vm.h" #define DEBUG_TRACE_EXECUTION #include "printer.h" void printRegisters(VM* vm); void printFlagsAndStatusAndPc(VM* vm); void printStack(VM* vm); void printMemory(VM* vm); #endif
Brandhoej/Y86-64-VM
src/main.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "writer.h" #include "common.h" #include "vm.h" int main(int argc, const char* argv[]) { VM vm; initVM(&vm); Writer writer; initWriter(&writer, vm.memory, 0); irmovqWrite(&writer, REG_R10, 0); irmovqWrite(&writer, REG_R11, 0); addqWrite(&writer, REG_R10, REG_R11); jneWrite(&writer, writer.offset + 1); // Skips nop if true nopWrite(&writer); haltWrite(&writer); run(&vm); freeVM(&vm); return 0; }
Brandhoej/Y86-64-VM
src/vm.h
<gh_stars>0 #ifndef creo_vm_h #define creo_vm_h #include "value.h" /* This is the memory for the VM */ #define MEM_MAX (256) /* How to reserve memory: Expand the */ /* Conceptually, the stack is divided into two areas: * high addresses are all in use and reserved (you can't change these values!), * and lower addresses that are unused (free or scratch space). * The stack pointer points to the last in-use byte of the stack. * The standard convention is that when your function starts up, * you can claim some of the stack by moving the stack pointer down--this indicates * to any functions you might call that you're using those bytes of the stack. * You can then use that memory for anything you want, * as long as you move the stack pointer back before your function returns. */ /* (0) -> Caller-save * (X) -> Callee-save * (A) -> Args */ #define REG_RAX (0x00) /* ( O) */ #define REG_RCX (0x01) /* (AO) */ #define REG_RDX (0x02) /* (AO) */ #define REG_RBX (0x03) /* ( X) */ #define REG_RSP (0x04) /* ( ) The top pointer of the current stack (RSP >= RBP) */ #define REG_RBP (0x05) /* ( X) The base pointer of the current stack (RBP <= RSP) */ #define REG_RSI (0x06) /* (AO) */ #define REG_RDI (0x07) /* (AO) */ #define REG_R8 (0x08) /* (AO) */ #define REG_R9 (0x09) /* (AO) */ #define REG_R10 (0x0A) /* ( O) */ #define REG_R11 (0x0B) /* ( O) */ #define REG_R12 (0x0C) /* ( X) */ #define REG_R13 (0x0D) /* ( X) */ #define REG_R14 (0x0E) /* ( X) */ #define REG_F (0x0F) /* ( ) */ #define REG_COUNT (16) /* icode:ifun <- M1[PC] */ #define INS_HALT (0x00) #define INS_NOP (0x10) #define INS_RRMOVQ (0x20) #define INS_IRMOVQ (0x30) #define INS_RMMOVQ (0x40) #define INS_MRMOVQ (0x50) #define INS_ADDQ (0x60) #define INS_SUBQ (0x61) #define INS_ANDQ (0x62) #define INS_XORQ (0x63) #define INS_JMP (0x70) #define INS_JLE (0x71) #define INS_JL (0x72) #define INS_JE (0x73) #define INS_JNE (0x74) #define INS_JGE (0x75) #define INS_JG (0x76) #define INS_CMOVLE (0x21) #define INS_CMOVL (0x22) #define INS_CMOVE (0x23) #define INS_CMOVNE (0x24) #define INS_CMOVGE (0x25) #define INS_CMOVG (0x26) #define INS_CALL (0x80) #define INS_RET (0x90) #define INS_PUSHQ (0xA0) #define INS_POPQ (0xB0) /* Set by arithmetic and logical operations */ #define CC_ZF (0x00) /* Zero */ #define CC_SF (0x01) /* Negative sign */ #define CC_OF (0x02) /* Overflow */ typedef enum { STAT_AOK, /* Normal operation */ STAT_HLT, /* Halt instruciton encountered */ STAT_ADR, /* Bad address (either instruction or data) encountered */ STAT_INS /* Invalid instruction encountered */ } StatusCondition; typedef struct { vm_quad_t pc; /* The Program Counter pointing at the current isntruction in the chunk opCode */ StatusCondition statusCondition; /* The status of the VM */ vm_ubyte_t conditionCodes; /* Byte container for the CC_ZF, CC_SF and CC_OF */ vm_quad_t* registers; /* The 16 registers used by the y86-64 mapped with REG_X */ vm_ubyte_t* memory; /* The virtual memory stack used by this VM */ } VM; void initVM(VM* vm); void freeVM(VM* vm); bool zf(VM* vm); bool sf(VM* vm); bool of(VM* vm); vm_ubyte_t m1r(VM* vm, vm_quad_t offset); vm_quad_t m8r(VM* vm, vm_quad_t offset); vm_ubyte_t m1w(VM* vm, vm_quad_t offset, vm_ubyte_t byte); vm_quad_t m8w(VM* vm, vm_quad_t offset, vm_quad_t quad); void run(VM* vm); #endif
Brandhoej/Y86-64-VM
src/value.h
<gh_stars>0 #ifndef cero_value_h #define cero_value_h #include "common.h" typedef uint8_t vm_ubyte_t; typedef int8_t vm_byte_t; typedef int16_t vm_word_t; typedef int32_t vm_double_t; typedef int64_t vm_quad_t; #endif
Brandhoej/Y86-64-VM
src/writer.c
<reponame>Brandhoej/Y86-64-VM #include "writer.h" #include "vm.h" void initWriter(Writer* writer, vm_byte_t* destination, uint32_t offset) { writer->offset = offset; writer->destination = destination; } void freeWriter(Writer* writer) { initWriter(writer, NULL, 0); } static inline void writeBytes(Writer* writer, vm_ubyte_t* bytes, uint32_t length) { for (uint32_t i = 0; i < length; ++i) { writer->destination[writer->offset + i] = bytes[i]; } writer->offset += length; } static inline void writeInsFun(Writer* writer, vm_ubyte_t insFun) { vm_ubyte_t bytes[1]; bytes[0] = insFun; writeBytes(writer, bytes, 1); } static inline void writeInsFunRegs(Writer* writer, vm_ubyte_t insFun, vm_ubyte_t rArB) { vm_ubyte_t bytes[2]; bytes[0] = insFun; bytes[1] = rArB; writeBytes(writer, bytes, 2); } static inline void writeInsFunRegsQuad(Writer* writer, vm_ubyte_t insFun, vm_ubyte_t rArB, vm_quad_t q) { vm_ubyte_t bytes[10]; bytes[0] = insFun; bytes[1] = rArB; bytes[9] = (q >> 0) & 0xFF; bytes[8] = (q >> 8) & 0xFF; bytes[7] = (q >> 16) & 0xFF; bytes[6] = (q >> 24) & 0xFF; bytes[5] = (q >> 32) & 0xFF; bytes[4] = (q >> 40) & 0xFF; bytes[3] = (q >> 48) & 0xFF; bytes[2] = (q >> 56) & 0xFF; writeBytes(writer, bytes, 10); } static inline void writeInsFunQuad(Writer* writer, vm_ubyte_t insFun, vm_quad_t q) { vm_ubyte_t bytes[9]; bytes[0] = insFun; bytes[8] = (q >> 0) & 0xFF; bytes[7] = (q >> 8) & 0xFF; bytes[6] = (q >> 16) & 0xFF; bytes[5] = (q >> 24) & 0xFF; bytes[4] = (q >> 32) & 0xFF; bytes[3] = (q >> 40) & 0xFF; bytes[2] = (q >> 48) & 0xFF; bytes[1] = (q >> 56) & 0xFF; writeBytes(writer, bytes, 9); } void haltWrite(Writer* writer) { writeInsFun(writer, INS_HALT); } void nopWrite(Writer* writer) { writeInsFun(writer, INS_NOP); } void rrmovqWrite(Writer* writer, vm_ubyte_t rA, vm_ubyte_t rB) { writeInsFunRegs(writer, INS_RRMOVQ, REG_SPEC_ENC_RARB(rA, rB)); } void irmovqWrite(Writer* writer, vm_ubyte_t rB, vm_quad_t v) { writeInsFunRegsQuad(writer, INS_IRMOVQ, REG_SPEC_ENC_RB(rB), v); } void rmmovqWrite(Writer* writer, vm_ubyte_t rA, vm_ubyte_t rB, vm_quad_t d) { writeInsFunRegsQuad(writer, INS_RMMOVQ, REG_SPEC_ENC_RARB(rA, rB), d); } void mrmovqWrite(Writer* writer, vm_ubyte_t rA, vm_ubyte_t rB, vm_quad_t d) { writeInsFunRegsQuad(writer, INS_MRMOVQ, REG_SPEC_ENC_RARB(rA, rB), d); } void addqWrite(Writer* writer, vm_ubyte_t rA, vm_ubyte_t rB) { writeInsFunRegs(writer, INS_ADDQ, REG_SPEC_ENC_RARB(rA, rB)); } void subqWrite(Writer* writer, vm_ubyte_t rA, vm_ubyte_t rB) { writeInsFunRegs(writer, INS_SUBQ, REG_SPEC_ENC_RARB(rA, rB)); } void andqWrite(Writer* writer, vm_ubyte_t rA, vm_ubyte_t rB) { writeInsFunRegs(writer, INS_ANDQ, REG_SPEC_ENC_RARB(rA, rB)); } void xorqWrite(Writer* writer, vm_ubyte_t rA, vm_ubyte_t rB) { writeInsFunRegs(writer, INS_XORQ, REG_SPEC_ENC_RARB(rA, rB)); } void jmpWrite(Writer* writer, vm_quad_t dest) { writeInsFunQuad(writer, INS_JMP, dest); } void jleWrite(Writer* writer, vm_quad_t dest) { writeInsFunQuad(writer, INS_JLE, dest); } void jlWrite(Writer* writer, vm_quad_t dest) { writeInsFunQuad(writer, INS_JL, dest); } void jeWrite(Writer* writer, vm_quad_t dest) { writeInsFunQuad(writer, INS_JE, dest); } void jneWrite(Writer* writer, vm_quad_t dest) { writeInsFunQuad(writer, INS_JNE, dest); } void jgeWrite(Writer* writer, vm_quad_t dest) { writeInsFunQuad(writer, INS_JGE, dest); } void jgWrite(Writer* writer, vm_quad_t dest) { writeInsFunQuad(writer, INS_JG, dest); } void cmovleWrite(Writer* writer, vm_ubyte_t rA, vm_ubyte_t rB) { writeInsFunRegs(writer, INS_CMOVLE, REG_SPEC_ENC_RARB(rA, rB)); } void cmovlWrite(Writer* writer, vm_ubyte_t rA, vm_ubyte_t rB) { writeInsFunRegs(writer, INS_CMOVL, REG_SPEC_ENC_RARB(rA, rB)); } void cmoveWrite(Writer* writer, vm_ubyte_t rA, vm_ubyte_t rB) { writeInsFunRegs(writer, INS_CMOVE, REG_SPEC_ENC_RARB(rA, rB)); } void cmovneWrite(Writer* writer, vm_ubyte_t rA, vm_ubyte_t rB) { writeInsFunRegs(writer, INS_CMOVNE, REG_SPEC_ENC_RARB(rA, rB)); } void cmovgeWrite(Writer* writer, vm_ubyte_t rA, vm_ubyte_t rB) { writeInsFunRegs(writer, INS_CMOVGE, REG_SPEC_ENC_RARB(rA, rB)); } void cmovgWrite(Writer* writer, vm_ubyte_t rA, vm_ubyte_t rB) { writeInsFunRegs(writer, INS_CMOVG, REG_SPEC_ENC_RARB(rA, rB)); } void callWrite(Writer* writer, vm_quad_t dest) { writeInsFunQuad(writer, INS_CALL, dest); } void retWrite(Writer* writer) { writeInsFun(writer, INS_RET); } void pushqWrite(Writer* writer, vm_ubyte_t rA) { writeInsFunRegs(writer, INS_PUSHQ, REG_SPEC_ENC_RA(rA)); } void popqWrite(Writer* writer, vm_ubyte_t rA) { writeInsFunRegs(writer, INS_POPQ, REG_SPEC_ENC_RA(rA)); }
Brandhoej/Y86-64-VM
src/logger.h
#ifndef cero_logger_h #define cero_logger_h #include <stdio.h> #include <stdarg.h> #include <stdbool.h> #include <time.h> #include <string.h> #include <stdlib.h> #include "common.h" #define ANSI_COLOR_BLACK "\x1b[30m" #define ANSI_COLOR_RED "\x1b[31m" #define ANSI_COLOR_GREEN "\x1b[32m" #define ANSI_COLOR_YELLOW "\x1b[33m" #define ANSI_COLOR_BLUE "\x1b[34m" #define ANSI_COLOR_MAGENTA "\x1b[35m" #define ANSI_COLOR_CYAN "\x1b[36m" #define ANSI_COLOR_WHITE "\x1b[37m" #define ANSI_COLOR_BRIGHT_BLACK "\x1b[30;1m" #define ANSI_COLOR_BRIGHT_RED "\x1b[31;1m" #define ANSI_COLOR_BRIGHT_GREEN "\x1b[32;1m" #define ANSI_COLOR_BRIGHT_YELLOW "\x1b[33;1m" #define ANSI_COLOR_BRIGHT_BLUE "\x1b[34;1m" #define ANSI_COLOR_BRIGHT_MAGENTA "\x1b[35;1m" #define ANSI_COLOR_BRIGHT_CYAN "\x1b[36;1m" #define ANSI_COLOR_BRIGHT_WHITE "\x1b[37;1m" #define ANSI_COLOR_RESET "\x1b[0m" #define GENERATE_ENUM(ENUM) ENUM, #define GENERATE_STRING(STRING) #STRING, #define FOREACH_LOGGER_LEVEL(wrapper)\ wrapper(LOG_TRACE)\ wrapper(LOG_DEBUG)\ wrapper(LOG_INFO)\ wrapper(LOG_WARN)\ wrapper(LOG_ERROR)\ wrapper(LOG_FATAL)\ typedef enum { FOREACH_LOGGER_LEVEL(GENERATE_ENUM) } LoggerLevel; static const char* loggerLevelStrings[6] = { FOREACH_LOGGER_LEVEL(GENERATE_STRING) }; static const char* loggerLevelAnsiColorStrings[6] = { ANSI_COLOR_CYAN, /* LOG_TRACE */ ANSI_COLOR_MAGENTA, /* LOG_DEBUG */ ANSI_COLOR_BLUE, /* LOG_INFO */ ANSI_COLOR_YELLOW, /* LOG_WARN */ ANSI_COLOR_RED, /* LOG_ERROR */ ANSI_COLOR_BRIGHT_RED, /* LOG_FATAL */ }; #undef GENERATE_ENUM #undef GENERATE_STRING #define LOGGER_LOG_TIME #define LOGGER_LOG_FILE #define CERO_PRINT(...) (printf(__VA_ARGS__)) #define CERO_LEVEL_LOG(level, fileName, lineNumber) \ do { \ time_t t = time(NULL); \ struct tm* tm = localtime(&t); \ CERO_PRINT(ANSI_COLOR_BRIGHT_BLACK"%02i:%02i:%02i"ANSI_COLOR_RESET \ " " \ "%s%-5s"ANSI_COLOR_RESET \ " " \ ANSI_COLOR_BRIGHT_BLACK"%10s:%03u:"ANSI_COLOR_RESET, \ tm->tm_hour, tm->tm_min, tm->tm_sec, \ loggerLevelAnsiColorStrings[level], loggerLevelStrings[level] + 4,\ fileName, lineNumber); \ } while (false) #define CERO_LOG(level, fileName, lineNumber, ...) \ do { \ CERO_LEVEL_LOG(level, fileName, lineNumber);\ printf(" "__VA_ARGS__); \ } while (false) #define CERO_TRACE(...) CERO_LOG(LOG_TRACE, __FILE__, __LINE__, __VA_ARGS__) #define CERO_DEBUG(...) CERO_LOG(LOG_DEBUG, __FILE__, __LINE__, __VA_ARGS__) #define CERO_INFO(...) CERO_LOG(LOG_INFO, __FILE__, __LINE__, __VA_ARGS__) #define CERO_WARN(...) CERO_LOG(LOG_WARN, __FILE__, __LINE__, __VA_ARGS__) #define CERO_ERROR(...) CERO_LOG(LOG_ERROR, __FILE__, __LINE__, __VA_ARGS__) #define CERO_FATAL(...) CERO_LOG(LOG_FATAL, __FILE__, __LINE__, __VA_ARGS__) #endif
JBlaschke/cctbx_project
iotbx/pdb/modified_rna_dna_names.h
/* This file contains all residue names for modified RNA/DNAs. This file is generated by the following procedure: phenix.python elbow/elbow/scripts/process_amino_acid_parentage_from_chemical_componts.py This file is intended to be generated monthly. The date of file generation: Fri Feb 28 14:23:03 2020 */ #include <string> #include <set> namespace iotbx { namespace pdb { namespace common_residue_names { static const char* modified_rna_dna[] = { "12A", // parent is A "1MA", "2MA", "31H", "31M", "45A", "5FA", "6IA", "6MA", "6MC", "6MT", "6MZ", "6NW", "7AT", "8AN", "A23", "A2L", "A2M", "A39", "A3P", "A44", "A5O", "A6A", "A7E", "A9Z", "AET", "AP7", "AVC", "F3N", "LCA", "M7A", "MA6", "MAD", "MGQ", "MIA", "MTU", "O2Z", "P5P", "PPU", "PR5", "PU", "RIA", "SRA", "T6A", "V3L", "ZAD", "10C", // parent is C "1SC", "4OC", "5HM", "5IC", "5MC", "6OO", "73W", "A5M", "A6C", "B8Q", "B8T", "B9H", "C25", "C2L", "C31", "C43", "C5L", "CBV", "CCC", "CH", "CSF", "E3C", "IC", "JMH", "LC", "LHH", "M4C", "M5M", "N5M", "OMC", "PMT", "RPC", "RSP", "RSQ", "S4C", "TC", "ZBC", "ZCY", "0AM", // parent is DA "0AV", "0SP", "1AP", "2AR", "2BU", "2DA", "3DA", "5AA", "6HA", "6HB", "7DA", "8BA", "A34", "A35", "A38", "A3A", "A40", "A43", "A47", "A5L", "ABR", "ABS", "AD2", "AF2", "AS", "DZM", "E", "E1X", "EDA", "FA2", "MA7", "PRN", "R", "RBD", "RMP", "S4A", "SDE", "SMP", "TCY", "TFO", "XAD", "XAL", "XUA", "Y", "0AP", // parent is DC "0R8", "1CC", "1FC", "47C", "4PC", "4PD", "4PE", "4SC", "4U3", "5CM", "5FC", "5HC", "5NC", "5PC", "6HC", "8RO", "8YN", "B7C", "C2S", "C32", "C34", "C36", "C37", "C38", "C42", "C45", "C46", "C49", "C4S", "C7R", "C7S", "CAR", "CB2", "CBR", "CDW", "CFL", "CFZ", "CMR", "CP1", "CSL", "CX2", "D00", "D4B", "DCT", "DFC", "DNR", "DOC", "EXC", "F7H", "GCK", "I5C", "IMC", "MCY", "ME6", "NCU", "PVX", "SC", "TC1", "TCJ", "TPC", "XCL", "XCR", "XCT", "XCY", "YCO", "Z", "0AD", // parent is DG "0UH", "2JV", "2PR", "5CG", "63G", "63H", "68Z", "6FK", "6HG", "6OG", "6PO", "7BG", "7GU", "8AG", "8FG", "8MG", "8OG", "8PY", "AFG", "BGM", "C6G", "DCG", "DDG", "DFG", "DG8", "DGI", "EHG", "F4Q", "F74", "F7K", "FDG", "FMG", "FOX", "G2S", "G31", "G32", "G33", "G36", "G38", "G42", "G47", "G49", "GDR", "GF2", "GFL", "GMS", "GN7", "GS", "GSR", "GSS", "GX1", "HN0", "HN1", "IGU", "LCG", "LGP", "M1G", "MFO", "MG1", "MRG", "OGX", "P", "PG7", "PGN", "PPW", "PZG", "RDG", "S4G", "S6G", "SDG", "SDH", "TGP", "X", "XGL", "XGR", "XGU", "XPB", "XUG", "2BD", // parent is DI "OIP", "2AT", // parent is DT "2BT", "2DT", "2GT", "2NT", "2OT", "2ST", "5AT", "5HT", "5IT", "5PY", "64T", "6CT", "6HT", "94O", "ATD", "ATL", "ATM", "BOE", "CTG", "D3T", "D4M", "DPB", "DRT", "EAN", "EIT", "F3H", "F4H", "JDT", "LSH", "LST", "MMT", "MTR", "NMS", "NMT", "NTT", "P2T", "PST", "S2M", "SMT", "SPT", "T32", "T36", "T37", "T38", "T39", "T3P", "T41", "T48", "T49", "T4S", "T5S", "T64", "TA3", "TAF", "TCP", "TDY", "TED", "TFE", "TFF", "TFT", "TLC", "TP1", "TSP", "TTD", "TTM", "US3", "XTF", "XTH", "XTL", "XTR", "0AU", // parent is DU "18Q", "5HU", "5IU", "5SE", "77Y", "8DT", "BRU", "BVP", "DDN", "DRM", "DUZ", "GMU", "HDP", "HEU", "NDN", "NDU", "OHU", "P2U", "PDU", "T5O", "TLN", "TTI", "U2N", "U33", "UBI", "UBR", "UCL", "UF2", "UFR", "UFT", "UMS", "UMX", "UPE", "UPS", "URX", "US1", "US2", "USM", "UVX", "ZDU", "18M", // parent is G "1MG", "23G", "2EG", "2MG", "2SG", "7MG", "8AA", "8OS", "A6G", "B8K", "B8W", "B9B", "BGH", "CG1", "E6G", "E7G", "EQ4", "G25", "G2L", "G46", "G48", "G7M", "GAO", "GDO", "GDP", "GH3", "GOM", "GRB", "IG", "KAG", "KAK", "LG", "M2G", "MGV", "MHG", "N6G", "O2G", "OMG", "P7G", "PGP", "QUO", "TG", "TPG", "XTS", "YG", "YYG", "ZGU", "8RJ", // parent is T "92F", "QBT", "RT", "T23", "T2S", "ZTH", "125", // parent is U "126", "127", "1RN", "2AU", "2MU", "2OM", "3AU", "3ME", "3MU", "3TD", "4SU", "5BU", "5FU", "5MU", "70U", "75B", "85Y", "9QV", "A6U", "B8H", "CNU", "DHU", "F2T", "FHU", "FNU", "H2U", "I4U", "IU", "LHU", "MEP", "MNU", "OMU", "ONE", "P4U", "PSU", "PYO", "RUS", "S4U", "SSU", "SUR", "T31", "U25", "U2L", "U2P", "U31", "U34", "U36", "U37", "U8U", "UAR", "UBD", "UD5", "UPV", "UR3", "URD", "US5", "ZBU", 0 }; }}} // namespace iotbx::pdb::common_residue_names
JBlaschke/cctbx_project
iotbx/detectors/display.h
/* -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 8 -*- */ #ifndef DETECTORS_IMAGE_DISPV_H #define DETECTORS_IMAGE_DISPV_H #include <vector> #include <algorithm> #include <limits> #include <boost/python.hpp> #include <boost/shared_ptr.hpp> #include <scitbx/constants.h> #include <scitbx/array_family/flex_types.h> #include <scitbx/array_family/versa.h> #include <scitbx/array_family/shared.h> #include <scitbx/vec3.h> #include <scitbx/vec2.h> #include <scitbx/mat3.h> #include <scitbx/mat2.h> #include <scitbx/array_family/accessors/c_grid.h> #include <scitbx/graphics_utils/colors.h> #include <iotbx/detectors/context/spot_xy_convention.h> #include <scitbx/random.h> #include <scitbx/math/r3_rotation.h> #include <scitbx/math/polygon_intersection.h> namespace af = scitbx::af; namespace iotbx { namespace detectors { namespace display { struct Color { af::tiny<int,3> RGB; inline Color(int r,int g,int b):RGB(r,g,b){} inline af::tiny<double,3> as_unit_rgb(){ af::tiny<double,3> rv; for (int i=0;i<3;++i){rv[i]=(RGB[i]/255.);} return rv; } }; class ActiveAreaDefault { public: inline virtual bool is_active_area(const int&,const int&){return true;} inline virtual bool is_active_area_by_linear_index(const int&){return true;} }; typedef boost::shared_ptr<ActiveAreaDefault> ptr_area; class ActiveAreaPilatus6M: public ActiveAreaDefault { public: inline virtual bool is_active_area(const int& x,const int& y){ /* x, vertical, slow, size1: 12 blocks of 195, separated by 11 stripes of 17, giving 2527. y horizont, fast, size2: 5 blocks of 487, separated by 4 stripes of 7, giving 2463. Takes 0.02 seconds extra to apply this test to entire Pilatus 6M image. */ return ( (x%212<195) && (y%494<487) ); } inline virtual bool is_active_area_by_linear_index(const int& i){ return is_active_area(i/2463,i%2463); } }; class ActiveAreaPilatus2M: public ActiveAreaDefault { public: inline virtual bool is_active_area(const int& x,const int& y){ /* x, vertical, slow, size1: 8 blocks of 195, separated by 7 stripes of 17, giving 1679. y horizont, fast, size2: 3 blocks of 487, separated by 2 stripes of 7, giving 1475. */ return ( (x%212<195) && (y%494<487) ); } inline virtual bool is_active_area_by_linear_index(const int& i){ return is_active_area(i/1475,i%1475); } }; class ActiveAreaPilatus300K: public ActiveAreaDefault { public: inline virtual bool is_active_area(const int& x,const int& y){ /* x, vertical, slow, size1: 3 blocks of 195, separated by 2 stripes of 17, giving 619. y horizont, fast, size2: 1 blocks of 487, separated by 0 stripes of 7, giving 487. */ return ( (x%212<195) && (y%494<487) ); } inline virtual bool is_active_area_by_linear_index(const int& i){ return is_active_area(i/487,i%487); } }; template <int FastModules> class ActiveAreaEigerX: public ActiveAreaDefault { public: inline virtual bool is_active_area(const int& x,const int& y){ /* EigerX-16M, FastModules=4 x, vertical, slow, size1: 8 blocks of 514, separated by 7 stripes of 37, giving 4371. y horizont, fast, size2: 4 blocks of 1030, separated by 3 stripes of 10, giving 4150. EigerX-9M, FastModules=3 x, vertical, slow, size1: 6 blocks of 514, separated by 5 stripes of 37, giving 3269. y horizont, fast, size2: 3 blocks of 1030, separated by 2 stripes of 10, giving 3110. EigerX=4M, FastModules=2 x, vertical, slow, size1: 4 blocks of 514, separated by 3 stripes of 37, giving 2167. y horizont, fast, size2: 2 blocks of 1030, separated by 1 stripes of 10, giving 2070. EigerX-1M, FastModules=1 x, vertical, slow, size1: 2 blocks of 514, separated by 1 stripes of 37, giving 1065. y horizont, fast, size2: 1 blocks of 1030, separated by 0 stripes of 10, giving 1030. EigerX-500K, FastModules=1 (no inactive areas, do not instantiate) x, vertical, slow, size1: 1 blocks of 514, separated by 0 stripes of 37, giving 514. y horizont, fast, size2: 1 blocks of 1030, separated by 0 stripes of 10, giving 1030. */ return ( (x%551<514) && (y%1040<1030) ); } inline virtual bool is_active_area_by_linear_index(const int& i){ return is_active_area(i/(FastModules*1030+(FastModules-1)*10),i%(FastModules*1030+(FastModules-1)*10)); } }; template <int FastModules> class ActiveAreaEiger2X: public ActiveAreaDefault { public: inline virtual bool is_active_area(const int& x,const int& y){ /* Eiger2X-16M, FastModules=4 x, vertical, slow, size1: 8 blocks of 512, separated by 7 stripes of 38, giving 4362. y horizont, fast, size2: 4 blocks of 1028, separated by 3 stripes of 12, giving 4148. Eiger2X-9M, FastModules=3 x, vertical, slow, size1: 6 blocks of 512, separated by 5 stripes of 38, giving 3262. y horizont, fast, size2: 3 blocks of 1028, separated by 2 stripes of 12, giving 3108. Eiger2X=4M, FastModules=2 x, vertical, slow, size1: 4 blocks of 512, separated by 3 stripes of 38, giving 2162. y horizont, fast, size2: 2 blocks of 1028, separated by 1 stripes of 12, giving 2068. Eiger2X-1M, FastModules=1 x, vertical, slow, size1: 2 blocks of 512, separated by 1 stripes of 38, giving 1062. y horizont, fast, size2: 1 blocks of 1028, separated by 0 stripes of 12, giving 1028. Eiger2X-500K, FastModules=1 (no inactive areas, do not instantiate) x, vertical, slow, size1: 1 blocks of 512, separated by 0 stripes of 38, giving 512. y horizont, fast, size2: 1 blocks of 1028, separated by 0 stripes of 12, giving 1028. */ return ( (x%550<512) && (y%1040<1028) ); } inline virtual bool is_active_area_by_linear_index(const int& i){ return is_active_area(i/(FastModules*1040+(FastModules-1)*12),i%(FastModules*1040+(FastModules-1)*12)); } }; inline int iround(double const& x) {if (x < 0) return static_cast<int>(x-0.5); return static_cast<int>(x+.5);} #define COLOR_GRAY 0 #define COLOR_RAINBOW 1 #define COLOR_HEAT 2 #define COLOR_INVERT 3 template <typename DataType = int> class FlexImage { public: typedef af::versa< DataType, af::flex_grid<> > array_t; typedef DataType data_t; array_t rawdata; // original image af::versa<int, af::c_grid<3> > channels; // half-size 3-channel cont./bright. adjusted af::versa<int, af::c_grid<2> > export_m; int export_size_uncut1; int export_size_uncut2; int export_size_cut1; int export_size_cut2; int export_anchor_x; int export_anchor_y; const int nchannels; int color_scheme_state; bool show_untrusted; inline af::versa<DataType, af::c_grid<2> > raw_to_sampled( const af::versa<DataType, af::c_grid<2> >& raw) const { af::c_grid<2> rawsize = raw.accessor(); af::c_grid<2> sample_size(rawsize[0]/binning, rawsize[1]/binning); af::versa<DataType, af::c_grid<2> > sampled(sample_size); /* if (binning==2) { for (std::size_t i = 0; i < sample_size[0]; ++i) { for (std::size_t j = 0; j < sample_size[1]; ++j) { sampled(i,j) = (raw(2*i,2*j) + raw(2*i+1,2*j+1))/2; } } } else */ if (binning==1) { return raw; } else { //binning is a larger power of two. Take the max pixel for each chunk std::vector<DataType> candidate_max; for (std::size_t i = 0; i < sample_size[0]; ++i) { for (std::size_t j = 0; j < sample_size[1]; ++j) { for (std::size_t isample = 0; isample < binning; ++isample){ for (std::size_t jsample = 0; jsample < binning; ++jsample){ candidate_max.push_back(raw(binning*i+isample,binning*j+jsample)); } } sampled(i,j) = *std::max_element(candidate_max.begin(), candidate_max.end()); SCITBX_ASSERT(candidate_max.size()==binning*binning); candidate_max.clear(); SCITBX_ASSERT(candidate_max.size()==0); } } } return sampled; } inline af::versa<int, af::c_grid<2> > bright_contrast( af::versa<DataType, af::c_grid<2> > raw) const { const double outscale = 256; af::versa<int, af::c_grid<2> > z(raw.accessor()); bool has_pilatus_inactive_flag = false; ptr_area detector_location = ptr_area(new ActiveAreaDefault()); if (vendortype=="Pilatus-6M") { detector_location = ptr_area(new ActiveAreaPilatus6M()); has_pilatus_inactive_flag = true; } else if (vendortype=="Pilatus-2M") { detector_location = ptr_area(new ActiveAreaPilatus2M()); has_pilatus_inactive_flag = true; } else if (vendortype=="Pilatus-300K") { detector_location = ptr_area(new ActiveAreaPilatus300K()); has_pilatus_inactive_flag = true; } else if (vendortype=="Eiger-16M") { detector_location = ptr_area(new ActiveAreaEigerX<4>()); has_pilatus_inactive_flag = true; } else if (vendortype=="Eiger-9M") { detector_location = ptr_area(new ActiveAreaEigerX<3>()); has_pilatus_inactive_flag = true; } else if (vendortype=="Eiger-4M") { detector_location = ptr_area(new ActiveAreaEigerX<2>()); has_pilatus_inactive_flag = true; } else if (vendortype=="Eiger-1M") { detector_location = ptr_area(new ActiveAreaEigerX<1>()); has_pilatus_inactive_flag = true; } else if (vendortype=="Eiger2-16M") { detector_location = ptr_area(new ActiveAreaEiger2X<4>()); has_pilatus_inactive_flag = true; } else if (vendortype=="Eiger2-9M") { detector_location = ptr_area(new ActiveAreaEiger2X<3>()); has_pilatus_inactive_flag = true; } else if (vendortype=="Eiger2-4M") { detector_location = ptr_area(new ActiveAreaEiger2X<2>()); has_pilatus_inactive_flag = true; } else if (vendortype=="Eiger2-1M") { detector_location = ptr_area(new ActiveAreaEiger2X<1>()); has_pilatus_inactive_flag = true; } for (std::size_t i=0; i<raw.accessor()[0]; i++) { int slow = binning * i; int idx_slow = slow * rawdata.accessor().focus()[1]; int idx_i = i * raw.accessor()[1]; for (std::size_t j=0; j< raw.accessor()[1]; j++) { int fast = binning * j; int idx = idx_slow + fast; int idx_ij = idx_i + j; if (detector_location->is_active_area(slow, fast)) { //fractional input value: double corrected = raw[idx_ij]*correction; double outvalue = outscale * ( 1.0 - corrected ); if (has_pilatus_inactive_flag && raw[idx_ij]==-2){ //an ad hoc flag to aimed at coloring red the inactive pixels (-2) on Pilatus z[idx_ij]=1000; //flag value used is out of range of the 256-pt grey scale but in range int datatype. continue; } else if (raw[idx_ij]== std::numeric_limits<int>::min()){ //flag value for explicitly-masked pixels z[idx_ij]=1000; if (has_pilatus_inactive_flag){ //to avoid confusion, reset flagged pixels for Pilatus-like detectors to -2 raw[idx_ij]=-2; } continue; } else if (raw[idx_ij]>saturation){ z[idx_ij]=2000; //an ad hoc flag to aimed at coloring yellow the saturated pixels continue; } if (outvalue<0.0) { z[idx_ij]=0; } else if (outvalue>=outscale) { z[idx_ij]=int(outscale)-1; } else { z[idx_ij] = int(outvalue); } } } } return z; } inline double global_bright_contrast() const { ptr_area detector_location = ptr_area(new ActiveAreaDefault()); if (vendortype=="Pilatus-6M") { detector_location = ptr_area(new ActiveAreaPilatus6M()); } else if (vendortype=="Pilatus-2M") { detector_location = ptr_area(new ActiveAreaPilatus2M()); } else if (vendortype=="Pilatus-300K") { detector_location = ptr_area(new ActiveAreaPilatus300K()); } else if (vendortype=="Eiger-16M") { detector_location = ptr_area(new ActiveAreaEigerX<4>()); } else if (vendortype=="Eiger-9M") { detector_location = ptr_area(new ActiveAreaEigerX<3>()); } else if (vendortype=="Eiger-4M") { detector_location = ptr_area(new ActiveAreaEigerX<2>()); } else if (vendortype=="Eiger-1M") { detector_location = ptr_area(new ActiveAreaEigerX<1>()); } else if (vendortype=="Eiger2-16M") { detector_location = ptr_area(new ActiveAreaEiger2X<4>()); } else if (vendortype=="Eiger2-9M") { detector_location = ptr_area(new ActiveAreaEiger2X<3>()); } else if (vendortype=="Eiger2-4M") { detector_location = ptr_area(new ActiveAreaEiger2X<2>()); } else if (vendortype=="Eiger2-1M") { detector_location = ptr_area(new ActiveAreaEiger2X<1>()); } af::shared<data_t> raw_active; //first pass through data calculate average for (std::size_t i = 0; i < rawdata.accessor().focus()[0]; i++) { for (std::size_t j = 0; j < rawdata.accessor().focus()[1]; j++) { if (detector_location->is_active_area(i, j)) { raw_active.push_back(rawdata(i,j)); } } } /* data_t active_mean = af::mean(raw_active.const_ref()); SCITBX_EXAMINE(active_mean); data_t active_min= af::min(raw_active.const_ref()); SCITBX_EXAMINE(active_min); data_t active_max = af::max(raw_active.const_ref()); SCITBX_EXAMINE(active_max); */ std::size_t active_count = raw_active.size(); double PERCENTILE_TARGET = 0.90; // targets the 90th percentile pixel value. std::size_t nth_offset = PERCENTILE_TARGET*active_count; std::nth_element(raw_active.begin(), raw_active.begin()+nth_offset, raw_active.end()); if (vendortype=="Pilatus-6M") { SCITBX_ASSERT( (active_count == 60*195*487 || active_count == 5*195*487) ); } else if (vendortype=="Pilatus-2M") { SCITBX_ASSERT( (active_count == 24*195*487 || active_count == 3*195*487) ); } else if (vendortype=="Pilatus-300K") { SCITBX_ASSERT( (active_count == 3*195*487) ); } else if (vendortype=="Eiger-16M") { SCITBX_ASSERT( (active_count == 32*514*1030 || active_count == 4*514*1030) ); } double percentile = *(raw_active.begin()+nth_offset); double adjlevel = 0.4; return (percentile>0.) ? brightness * adjlevel/percentile : brightness / 5.0; } int binning; // either 1 (unbinned) or a power of 2 (binned) std::string vendortype; double brightness, correction; DataType saturation; double zoom; bool supports_rotated_tiles_antialiasing_recommended; //whether the client viewer should apply extra antialiasing /* Relationship between binning & zoom for this class: zoom level zoom binning magnification factor ---------- ---- ------- -------------------- -3 0.125 8 1/8 x -2 0.25 4 1/4 x -1 0.5 2 1/2 x 0 1 1 1x 1 2 1 2x 2 4 1 4x etc. */ public: inline FlexImage(array_t rawdata, const int& power_of_two, const double& brightness = 1.0, const DataType& saturation = 1.0, const bool& show_untrusted = false, const int& color_scheme_state = COLOR_GRAY): rawdata(rawdata), brightness(brightness),saturation(saturation), nchannels(4), supports_rotated_tiles_antialiasing_recommended(false), color_scheme_state(color_scheme_state),show_untrusted(show_untrusted), binning(power_of_two){} inline FlexImage(array_t rawdata, const int& power_of_two, const std::string& vendortype, const double& brightness = 1.0, const DataType& saturation = 65535, const bool& show_untrusted = false, const int& color_scheme_state = COLOR_GRAY): brightness(brightness), saturation(saturation), rawdata(rawdata), nchannels(4), supports_rotated_tiles_antialiasing_recommended(false), color_scheme_state(color_scheme_state), binning(power_of_two), vendortype(vendortype), show_untrusted(show_untrusted){ //Assert that binning is a power of two SCITBX_ASSERT ( binning > 0 && (binning & (binning-1) )==0 ); zoom = 1./ binning; export_size_uncut1 = size1()/binning; export_size_uncut2 = size2()/binning; channels = af::versa<int, af::c_grid<3> >(af::c_grid<3>(nchannels, export_size_uncut1,export_size_uncut2),af::init_functor_null<int>()); correction = global_bright_contrast(); } //change raw data to reflect different view inline void spot_convention(const int & conv){ if (conv==0) {return;} int size1 = rawdata.accessor().focus()[0]; //the slow size int size2 = rawdata.accessor().focus()[1]; //the fast size array_t z(af::flex_grid<>(size1,size2)); DataType* zac = z.begin(); DataType* raw = rawdata.begin(); // The only conventions used so far are 0 & 2, so no need to make this // general yet. if (conv==2) { for (int i = 0; i<size1; ++i){ for (int j = 0; j<size2; ++j){ zac[size1*i+j] = raw[size1*(size1-1-i)+j]; } } } //generalize using the XY convention mechanism // later modify the mosflm orientation writer to work with spot conventions like 4. else { iotbx::detectors::context::spot_xy_convention XY(size1,size2,1,conv); //third arg is dummy "1" for (int i = 0; i<size1; ++i){ for (int j = 0; j<size2; ++j){ scitbx::vec2<int> ptr(i,j); scitbx::vec2<int> transformed = XY.call( &ptr, scitbx::type_holder<int>()); zac[size1*i+j] = raw[size1*transformed[0]+transformed[1]]; } } } rawdata = z; } inline int size1() const {return rawdata.accessor().focus()[0];} inline int size2() const {return rawdata.accessor().focus()[1];} inline void setWindow( const double& wxafrac, const double& wyafrac,const double& fraction){ int apply_zoom = (binning == 1)? zoom : 1; export_size_cut1 = export_size_uncut1*fraction*apply_zoom; export_size_cut2 = export_size_uncut2*fraction*apply_zoom; export_m = af::versa<int, af::c_grid<2> >( af::c_grid<2>(export_size_cut1,export_size_cut2)); //Compute integer anchor index based on input fractional dimension: export_anchor_x = export_size_uncut1*wxafrac*apply_zoom; export_anchor_y = export_size_uncut2*wyafrac*apply_zoom; } inline void setWindowCart( const double& xtile, const double& ytile,const double& fraction){ // fractional coverage of image is defined on dimension 1 (slow) only, // allowing square subarea display of a rectangular detector image // tile coverage is specified in cartesian rather than fractional image coordinates int apply_zoom = (binning == 1)? zoom : 1; export_size_cut1 = iround((double(size1())/binning)*fraction*apply_zoom); export_size_cut2 = iround((double(size2())/binning)*fraction*apply_zoom*(double(size1())/double(size2()))); export_m = af::versa<int, af::c_grid<2> >( af::c_grid<2>(export_size_cut1,export_size_cut2)); //Compute integer anchor index based on input fractional dimension: export_anchor_x = iround(export_size_uncut1*xtile*fraction*apply_zoom); export_anchor_y = iround(export_size_uncut2*ytile*fraction*apply_zoom*(double(size1())/double(size2()))); } inline int ex_size1() const {return export_m.accessor()[0];} inline int ex_size2() const {return export_m.accessor()[1];} inline void setZoom( const int& zoom_level) { zoom = std::pow(2.,double(zoom_level)); int potential_binning = int(std::ceil(1./double(zoom))); if (potential_binning != binning) { binning = potential_binning; export_size_uncut1 = size1()/binning; export_size_uncut2 = size2()/binning; channels = af::versa<int, af::c_grid<3> >(af::c_grid<3>(nchannels, export_size_uncut1,export_size_uncut2)); adjust(color_scheme_state); } } void adjust(int color_scheme=COLOR_GRAY) { color_scheme_state = color_scheme; using scitbx::graphics_utils::hsv2rgb; using scitbx::graphics_utils::get_heatmap_color; af::versa<DataType, af::c_grid<2> > sam(rawdata, af::c_grid<2>(rawdata.accessor())); af::versa<int, af::c_grid<2> > data = bright_contrast( raw_to_sampled(sam)); for (int i=0; i< nchannels; ++i) { int idx_i = i * export_size_uncut1; for (int j=0; j< export_size_uncut1; ++j) { int idx_ij = (idx_i + j) * export_size_uncut2; int idx_j = j * export_size_uncut2; for (int k=0; k<export_size_uncut2; ++k) { int idx_jk = idx_j + k; int idx_ijk = idx_ij + k; if (data[idx_jk] == 1000){ //ad hoc method to color inactive pixels red if (color_scheme == COLOR_GRAY || color_scheme == COLOR_INVERT) { if (i==0) {channels[idx_ijk] = 254;} else {channels[idx_ijk] = 1;} } else { // or black, if displaying a rainbow or heatmap channels[idx_ijk] = 0; } continue; } else if (data[idx_jk] == 2000){ //ad hoc method to color saturated pixels yellow if (color_scheme == COLOR_GRAY || color_scheme == COLOR_INVERT) { if (i==0 || i==1) {channels[idx_ijk] = 254;} else {channels[idx_ijk] = 1;} } else if (color_scheme == COLOR_RAINBOW) { // or white, if displaying a rainbow channels[idx_ijk] = 255; } else { // heatmap if (i == 1) { channels[idx_ijk] = 255; } else { channels[idx_ijk] = 0; } } continue; } if (color_scheme == COLOR_GRAY) { channels[idx_ijk] = data[idx_jk]; } else if (color_scheme == COLOR_INVERT) { channels[idx_ijk] = 255. - data[idx_jk]; } else if (color_scheme == COLOR_RAINBOW) { // rainbow double h = 255 * std::pow(((double) data[idx_jk]) / 255., 0.5); scitbx::vec3<double> rgb = hsv2rgb(h, 1.0, 1.0); channels[idx_ijk] = (int) (rgb[i] * 255.); } else { // heatmap double ratio = std::pow((double) (255. - data[idx_jk]) / 255., 2); scitbx::vec3<double> rgb = get_heatmap_color(ratio); channels[idx_ijk] = (int) (rgb[i] * 255.); } } } } } inline af::versa<int, af::c_grid<2> > channel(const int& c){ for (int i=export_anchor_x; i< export_anchor_x+export_size_cut1; ++i) { for (int j=export_anchor_y; j< export_anchor_y+export_size_cut2; ++j) { export_m(i,j) = channels(c,i,j); } } return export_m; } inline void point_overlay(const int& x, const int& y, const Color& c){ if ( x >= 0 && x < size1() && y >= 0 && y < size2() ) { //must be a better way to do this test within af::shared framework int sampled_x = x/binning; int sampled_y = y/binning; for (int i=0; i<3; ++i){ channels(i,sampled_x,sampled_y) = c.RGB[i]; } } } /* there's probably considerable room to improve this if the is_valid_index() were not tested each time. Instead break the export window into 4 sections, only one of which has valid data in it. Populate the export_s for the valid section first, then put pink in the other sections. */ inline void prep_string(){ typedef af::c_grid<3> t_C; const t_C& acc = channels.accessor(); ptr_area detector_location = ptr_area(new ActiveAreaDefault()); if (vendortype=="Pilatus-6M") { detector_location = ptr_area(new ActiveAreaPilatus6M()); } else if (vendortype=="Pilatus-2M") { detector_location = ptr_area(new ActiveAreaPilatus2M()); } else if (vendortype=="Pilatus-300K") { detector_location = ptr_area(new ActiveAreaPilatus300K()); } else if (vendortype=="Eiger-16M") { detector_location = ptr_area(new ActiveAreaEigerX<4>()); } else if (vendortype=="Eiger-9M") { detector_location = ptr_area(new ActiveAreaEigerX<3>()); } else if (vendortype=="Eiger-4M") { detector_location = ptr_area(new ActiveAreaEigerX<2>()); } else if (vendortype=="Eiger-1M") { detector_location = ptr_area(new ActiveAreaEigerX<1>()); } else if (vendortype=="Eiger2-16M") { detector_location = ptr_area(new ActiveAreaEiger2X<4>()); } else if (vendortype=="Eiger2-9M") { detector_location = ptr_area(new ActiveAreaEiger2X<3>()); } else if (vendortype=="Eiger2-4M") { detector_location = ptr_area(new ActiveAreaEiger2X<2>()); } else if (vendortype=="Eiger2-1M") { detector_location = ptr_area(new ActiveAreaEiger2X<1>()); } export_s = ""; export_s.reserve(export_size_cut1*export_size_cut2*3); if (zoom > 1.){ for (int zoom_x=export_anchor_x; zoom_x< export_anchor_x+export_size_cut1; ++zoom_x) { for (int zoom_y=export_anchor_y; zoom_y< export_anchor_y+export_size_cut2; ++zoom_y) { int i = zoom_x / zoom; int j = zoom_y / zoom; if (acc.is_valid_index(0,i,j) && detector_location->is_active_area(i*binning,j*binning)){ for (int c=0; c<3; ++c) { export_s.push_back((char)channels(c,i,j)); } } else { //pixels not in-bounds within the image get a pink tint export_s.push_back((char)255); export_s.push_back((char)228); export_s.push_back((char)228); } } } } else { for (int i=export_anchor_x; i< export_anchor_x+export_size_cut1; ++i) { for (int j=export_anchor_y; j< export_anchor_y+export_size_cut2; ++j) { if (acc.is_valid_index(0,i,j) && detector_location->is_active_area(i*binning,j*binning)){ for (int c=0; c<3; ++c) { export_s.push_back((char)channels(c,i,j)); } } else { //pixels not in-bounds within the image get a pink tint export_s.push_back((char)255); export_s.push_back((char)228); export_s.push_back((char)228); } } } } } inline void prep_string_monochrome(){ typedef af::c_grid<3> t_C; const t_C& acc = channels.accessor(); export_s = ""; export_s.reserve(export_size_cut1*export_size_cut2); for (int i=export_anchor_x; i< export_anchor_x+export_size_cut1; ++i) { for (int j=export_anchor_y; j< export_anchor_y+export_size_cut2; ++j) { if (acc.is_valid_index(0,i,j)){ export_s.push_back((char)channels(0,i,j)); } else { //pixels not in-bounds within the image get a white tint export_s.push_back((char)255); } } } } std::string export_s; //export data in string form; make public for readonly /** * Return data in bytes form */ inline boost::python::object as_bytes(){ // Convert to a python bytes object boost::python::object data_bytes( boost::python::handle<>(PyBytes_FromStringAndSize(export_s.c_str(), export_s.size())) ); return data_bytes; } inline void circle_overlay(const double& pixel_size, af::shared<scitbx::vec3<double> > centers, const double& radius, const double& thickness, const Color& color){ //centers is actually a list of circle center coordinates, given in mm //pixel_size is the conversion factor to integer point coordinates //radius, thickness are given in points typedef af::shared<scitbx::vec3<double> >::const_iterator afsi; afsi c_end=centers.end(); for (double r = iround(radius - 0.5*thickness); r<iround(radius + 0.5*thickness); r+=1.) { double trial_angle = 0.9/r; //in radians; angle subtended by 0.9 pixel at radius r int increments = scitbx::constants::two_pi / trial_angle; double angle = scitbx::constants::two_pi / (increments - increments%4); for (double theta=0.0;theta<scitbx::constants::two_pi; theta+=angle){ int delta_x = iround(r * std::cos(theta)); int delta_y = iround(r * std::sin(theta)); for (afsi c=centers.begin(); c!=c_end; ++c) { int x = 0.5 + ((*c)[0] / pixel_size); //rounding of a positive number int y = 0.5 + ((*c)[1] / pixel_size); //rounding of a positive number point_overlay(x+delta_x,y+delta_y,color); } } } } }; class generic_flex_image: public FlexImage<double>{ public: scitbx::vec3<double> axis; scitbx::mat3<double> rotation; scitbx::mat2<double> rotation2; scitbx::af::shared<scitbx::mat2<double> > transformations; scitbx::af::shared<scitbx::vec2<double> > translations; std::vector<int> windowed_readouts; int size1_readout; int size2_readout; typedef af::c_grid<3> t_C; t_C acc; // The ASIC:s stacked within rawdata must be padded in each // dimension to multiples of eight. Hence, the unpadded size of a // readout is passed in size_readout1 and size_readout2. inline generic_flex_image( array_t rawdata, const int& power_of_two, const int& size1_readout, const int& size2_readout, const double& brightness = 1.0, const double& saturation = 1.0, const bool& show_untrusted = false, const int& color_scheme_state = COLOR_GRAY ) : FlexImage<double>(rawdata, power_of_two, brightness, saturation, show_untrusted, color_scheme_state), size1_readout(size1_readout), size2_readout(size2_readout) { supports_rotated_tiles_antialiasing_recommended=true; zoom = 1./ binning; export_size_uncut1 = size1()/binning; export_size_uncut2 = size2()/binning; channels = af::versa<int, af::c_grid<3> >(af::c_grid<3>(nchannels, export_size_uncut1,export_size_uncut2),af::init_functor_null<int>()); axis = scitbx::vec3<double>(0.,0.,1.); rotation = scitbx::math::r3_rotation::axis_and_angle_as_matrix<double>(axis,4.,true); rotation2 = scitbx::mat2<double>(rotation[0],rotation[1],rotation[3],rotation[4]); correction = 1.0; //requires followup brightness scaling; use separate function } inline void setWindow( const double& wxafrac, const double& wyafrac,const double& fraction){ int apply_zoom = (binning == 1)? zoom : 1; //Compute integer anchor index based on input fractional dimension: export_anchor_x = export_size_uncut1*wxafrac*apply_zoom; export_anchor_y = export_size_uncut2*wyafrac*apply_zoom; export_size_cut1 = export_size_uncut1; export_size_cut2 = export_size_uncut2; // Calculate the limits of the output window by iterating over all tiles for (size_t k = 0; k < transformations.size(); k++) { for (size_t islow=0; islow <= size1_readout; islow+=size1_readout) { for (size_t ifast=0; ifast <= size2_readout; ifast+=size2_readout) { scitbx::vec2<double> point_p = tile_readout_to_picture(k,islow,ifast); export_size_cut1 = std::max( export_size_cut1, int(std::ceil(point_p[0]))); export_size_cut2 = std::max( export_size_cut2, int(std::ceil(point_p[1]))); } } } //Find out which readouts have any intersection with this Window windowed_readouts.clear(); //Define the 4 corners of the Window rectangle A B C D, counterclockwise from top left, af::shared<scitbx::vec2<double> > window_polygon; /*A*/window_polygon.push_back( scitbx::vec2<double>(export_anchor_x - 1. ,export_anchor_y - 1.)); /*B*/window_polygon.push_back( scitbx::vec2<double>(export_size_cut1 + 1. ,export_anchor_y - 1.)); /*C*/window_polygon.push_back( scitbx::vec2<double>(export_size_cut1 + 1. ,export_size_cut2 + 1. )); /*D*/window_polygon.push_back( scitbx::vec2<double>(export_anchor_x - 1. ,export_size_cut2 + 1. )); for (size_t k = 0; k < transformations.size(); k++) { //loop through all readout tiles af::shared<scitbx::vec2<double> > readout_polygon; for (size_t islow=0; islow <= size1_readout; islow+=size1_readout) { for (size_t ifast=0; ifast <= size2_readout; ifast+=size2_readout) { scitbx::vec2<double> point_p = tile_readout_to_picture(k,islow,ifast); readout_polygon.push_back(point_p); } } std::swap<scitbx::vec2<double> >(readout_polygon[2],readout_polygon[3]); if (scitbx::math::convex_polygons_intersect_2D(window_polygon, readout_polygon)) { windowed_readouts.push_back(k); } } export_size_cut1 = iround((export_size_cut1/binning)*fraction*apply_zoom); export_size_cut2 = iround((export_size_cut2/binning)*fraction*apply_zoom); export_m = af::versa<int, af::c_grid<2> >( af::c_grid<2>(export_size_cut1,export_size_cut2)); } // Identical to base class, except for computation of export_anchor & // just-in-time calculation of window/readout intersections inline void setWindowCart( const double& xtile, const double& ytile,const double& fraction){ // fractional coverage of image is defined on dimension 1 (slow) only, // allowing square subarea display of a rectangular detector image // tile coverage is specified in cartesian rather than fractional image coordinates int apply_zoom = (binning == 1)? zoom : 1; export_size_cut1 = iround((double(size1())/binning)*fraction*apply_zoom); export_size_cut2 = iround((double(size2())/binning)*fraction*apply_zoom*(double(size1())/double(size2()))); export_m = af::versa<int, af::c_grid<2> >( af::c_grid<2>(export_size_cut1,export_size_cut2)); //Compute integer anchor index based on input fractional dimension: export_anchor_x = xtile * export_size_cut2; export_anchor_y = ytile * export_size_cut1; //Find out which readouts have any intersection with this WindowCart windowed_readouts.clear(); //Define the 4 corners of the WindowCart rectangle A B C D, counterclockwise from top left, af::shared<scitbx::vec2<double> > window_polygon; /*A*/window_polygon.push_back( scitbx::vec2<double>((export_anchor_x/zoom) - 1. ,(export_anchor_y/zoom) - 1. )); /*B*/window_polygon.push_back( scitbx::vec2<double>((((xtile+1) * export_size_cut2)/zoom) + 1. ,(export_anchor_y/zoom) - 1. )); /*C*/window_polygon.push_back( scitbx::vec2<double>((((xtile+1) * export_size_cut2)/zoom) + 1. ,(((ytile+1) * export_size_cut1)/zoom) + 1. )); /*D*/window_polygon.push_back( scitbx::vec2<double>((export_anchor_x/zoom) - 1. ,(((ytile+1) * export_size_cut1)/zoom) + 1. )); for (size_t k = 0; k < transformations.size(); k++) { //loop through all readout tiles af::shared<scitbx::vec2<double> > readout_polygon; for (size_t islow=0; islow <= size1_readout; islow+=size1_readout) { for (size_t ifast=0; ifast <= size2_readout; ifast+=size2_readout) { scitbx::vec2<double> point_p = tile_readout_to_picture(k,islow,ifast); readout_polygon.push_back(point_p); } } std::swap<scitbx::vec2<double> >(readout_polygon[2],readout_polygon[3]); if (scitbx::math::convex_polygons_intersect_2D(window_polygon, readout_polygon)) { windowed_readouts.push_back(k); } } } inline scitbx::vec2<double> tile_readout_to_picture_f( int const& tile, double const& islow, double const& ifast) const { scitbx::vec2<double> fpicture = transformations[tile].inverse() * ( scitbx::vec2<double>(islow, ifast) - translations[tile]); return fpicture; } inline scitbx::vec2<double> tile_readout_to_picture( int const& tile, int const& islow, int const& ifast) const { return tile_readout_to_picture_f( tile, double(islow), double(ifast)); } inline af::shared<double> picture_to_readout_f(double const& i,double const& j) const { af::shared<double> z; if (transformations.size() == 0) { scitbx::vec2<double> rdout = rotation2 * scitbx::vec2<double>(i,j); z.push_back(rdout[0]); z.push_back(rdout[1]); return z; } // The length of a padded readout in the slow dimension, assuming // all readouts are the same size, and that the number of // transformation matrices is equal to the number of readouts. const std::size_t dim_slow = size1() / transformations.size(); for (size_t k = 0; k < transformations.size(); k++) { scitbx::vec2<double> rdout = transformations[k] * scitbx::vec2<double>(i, j) + translations[k]; scitbx::vec2<int> irdout(iround(rdout[0]), iround(rdout[1])); if (irdout[0] >= 0 && irdout[0] < size1_readout && irdout[1] >= 0 && irdout[1] < size2_readout) { // Since acc may be binned, irdout must take it into account. if (acc.is_valid_index( 0, (k * dim_slow + irdout[0]) / binning, irdout[1] / binning)) { z.push_back(rdout[0]); z.push_back(rdout[1]); z.push_back(k); return z; } } } z.push_back(0); z.push_back(0); z.push_back(-1); return z; } inline scitbx::vec2<int> picture_to_readout(double const& i,double const& j) const { if (transformations.size() == 0) { //return scitbx::vec2<int>(iround(i),iround(j)); scitbx::vec2<double> rdout = rotation2 * scitbx::vec2<double>(i,j); return scitbx::vec2<int>(iround(rdout[0]),iround(rdout[1])); } // The length of a binned and padded readout in the slow // dimension. const std::size_t dim_slow = size1() / transformations.size() / binning; for (size_t k = 0; k < windowed_readouts.size(); k++) { scitbx::vec2<double> rdout = transformations[windowed_readouts[k]] * scitbx::vec2<double>(i, j) + translations[windowed_readouts[k]] / binning; scitbx::vec2<int> irdout(iround(rdout[0]), iround(rdout[1])); if (irdout[0] >= 0 && irdout[0] < size1_readout / binning && irdout[1] >= 0 && irdout[1] < size2_readout / binning) { irdout[0] += windowed_readouts[k] * dim_slow; if (acc.is_valid_index(0, irdout[0], irdout[1])){ return irdout; } } } return scitbx::vec2<int>(-1, -1); } inline void prep_string(){ //const t_C& acc = channels.accessor(); acc = channels.accessor(); export_s = ""; export_s.reserve(export_size_cut1*export_size_cut2*3); //scitbx::vec3<int> datafocus = channels.accessor().focus(); if (zoom <= 1.){ for (int i=export_anchor_x; i< export_anchor_x+export_size_cut1; ++i) { for (int j=export_anchor_y; j< export_anchor_y+export_size_cut2; ++j) { scitbx::vec2<int> irdjrd = picture_to_readout(i,j); if (acc.is_valid_index(0,irdjrd[0],irdjrd[1])){ for (int c=0; c<3; ++c) { export_s.push_back((char)channels(c,irdjrd[0],irdjrd[1])); } } else { //pixels not in-bounds within the image get a pink tint export_s.push_back((char)255); export_s.push_back((char)228); export_s.push_back((char)228); } } } } else { for (int zoom_x=export_anchor_x; zoom_x< export_anchor_x+export_size_cut1; ++zoom_x) { double i = zoom_x / zoom; for (int zoom_y=export_anchor_y; zoom_y< export_anchor_y+export_size_cut2; ++zoom_y) { double j = zoom_y / zoom; scitbx::vec2<int> irdjrd = picture_to_readout(i,j); if (acc.is_valid_index(0,irdjrd[0],irdjrd[1])){ for (int c=0; c<3; ++c) { export_s.push_back((char)channels(c,irdjrd[0],irdjrd[1])); } } else { //pixels not in-bounds within the image get a pink tint export_s.push_back((char)255); export_s.push_back((char)228); export_s.push_back((char)228); } } } } application_specific_anti_aliasing(); } inline void application_specific_anti_aliasing(){ // no implementation at present } inline void add_transformation_and_translation( const scitbx::mat2<double>& T, const scitbx::vec2<double>& t) { transformations.push_back(T); translations.push_back(t); } inline void followup_brightness_scale(){ //first pass through data calculate average double qave = af::mean(rawdata.const_ref()); //std::cout<<"ave shown pixel value is "<<qave<<std::endl; //second pass calculate histogram data_t* data_ptr = rawdata.begin(); int hsize=100; array_t histogram(hsize); std::size_t data_sz = rawdata.size(); double bins_per_pixel_unit = (hsize/2)/qave; int temp; for (std::size_t i = 0; i < data_sz; i++) { temp = int(bins_per_pixel_unit*(*data_ptr++)); if (temp<0){histogram[0]+=1;} else if (temp>=hsize){histogram[hsize-1]+=1;} else {histogram[temp]+=1;} } //third pass calculate 90% double percentile=0; double accum=0; for (std::size_t i = 0; i<hsize; i++) { accum+=histogram[i]; if (accum > 0.9*rawdata.size()) { percentile=i*qave/(hsize/2); break; } } //std::cout<<"the 90-percentile pixel value is "<<percentile<<std::endl; double adjlevel = 0.4; correction = (percentile>0.) ? brightness * adjlevel/percentile : brightness / 5.0; } }; }}} //namespace #endif //DETECTORS_IMAGE_DISPV_H
sopig/PGNetworking
Classes/encryption/JXRSA.h
<reponame>sopig/PGNetworking<gh_stars>1-10 // // JXRSA.h // jiuxian // // Created by Dely on 15/9/11. // Copyright (c) 2015年 <EMAIL>. All rights reserved. // /** * 本类主要des加密的base64编码后的key进行加解密 */ #import <Foundation/Foundation.h> #import "CRSA.h" #import <Base64.h> @interface JXRSA : NSObject /** * 导入本地公钥是否成功 * * @return 成功标志 */ + (BOOL)importRSAPublicKey; /** * 导入本地私钥是否成功 * * @return 成功标志 */ + (BOOL)importRSAPrivateKey; #pragma mark ---------------------------加密------------------------------- /** * RSA加密数据NSString * * @param cipherString 需要RSA加密的NSString * * @return 加密后的base64编码的NSString */ + (NSString *)encryptToStringWithCipherString:(NSString *)cipherString; #pragma mark ---------------------------解密------------------------------- /** * RSA解密数据NSString * * @param cipherString 需要RSA解密的NSString(经过base64编码) * * @return 解密后的NSString */ + (NSString *)decryptToStringWithCipherString:(NSString *)cipherString; @end
sopig/PGNetworking
Classes/PGLogs.h
// // PGLogs.h // Pods // // Created by 张正超 on 16/6/22. // // #import <Foundation/Foundation.h> #import "PGASLMessage.h" FOUNDATION_EXPORT NSString *const PGLogEnable; @interface PGLogs : NSObject + (void)log:(NSString *)content, ... ; + (NSMutableArray *)fetchLog; @end
sopig/PGNetworking
Classes/PGNetworking.h
<filename>Classes/PGNetworking.h // // PGNetworking.h // PGNetworking // // Created by 张正超 on 16/4/5. // Copyright © 2016年 张正超. All rights reserved. // #ifndef PGNetworking_h #define PGNetworking_h #import <ReactiveCocoa.h> #import <AFNetworking.h> #import <YTKKeyValueStore.h> #import <MJExtension.h> #import "PGNetworkingReachability.h" #import "PGNetworkingConfig.h" #import "PGNetwokingType.h" #import "PGBaseAPIEntity.h" #import "PGAPIResponse.h" #import "PGAPIEngine.h" #import "PGMacros.h" #import "NSString+urlEncoding.h" #import "PGAPIBase.h" #import "PGNetworkingPrivate.h" #import "JXCommonParamsGenerator.h" #import "JXAppContext.h" #import "PGLogs.h" #endif /* PGNetworking_h */
sopig/PGNetworking
Classes/encryption/JXUUID.h
<gh_stars>1-10 // // JXUUID.h // jiuxian // // Created by Dely on 15/9/11. // Copyright (c) 2015年 <EMAIL>. All rights reserved. // /** * 本类主要生成des加密的随机数 */ #import <Foundation/Foundation.h> #import <Base64.h> @interface JXUUID : NSObject /** * 获取uuid * * @return 获取uudid String */ + (NSString *)uuid; /** * 获取des加解密的key * * @return 加解密的key */ + (NSString *)desKeyString; /** * 获取UUID的base编码,用于网络传输 * * @param desKeyString des加解密的真实的key * * @return 编码后的key */ + (NSString *)base64DesKeyString:(NSString *)desKeyString; /** * 直接获取des加解密的key 进行base64编码后的base64Key * * @return 编码后key base64Key */ + (NSString *)base64DesKeyString; @end
sopig/PGNetworking
Classes/PGNetwokingType.h
// // PGNetwokingType.h // PGNetworking // // Created by tolly on 16/4/5. // Copyright © 2016年 张正超. All rights reserved. // #ifndef PGNetwokingType_h #define PGNetwokingType_h ///////////////////////////////////////////////////////////////////// typedef NS_ENUM (NSUInteger, PGNetworkingServiceType){ PGNetworkingServiceTypeDefault, PGNetworkingServiceTypeHome, PGNetworkingServiceTypeOMS, PGNetworkingServiceTypeProduct, PGNetworkingServiceTypeUser, PGNetworkingServiceTypeJiuzhang, PGNetworkingServiceTypePromotion, PGNetworkingServiceTypePay = PGNetworkingServiceTypePromotion, PGNetworkingServiceTypeFORUM, PGNetworkingServiceTypeCOMMENT }; //不用bool值是为了以后方便扩展 typedef NS_ENUM (NSUInteger, PGNetworkingEncryptionType){ PGNetworkingEncryptionTypeNotUse, PGNetworkingEncryptionTypeUse }; ////////////////////////////////////////////////////////////////// typedef NS_ENUM (NSUInteger, PGAPIEntityResponseType){ PGAPIEntityResponseTypeDefault = 0, //API还没有起飞,默认 PGAPIEntityResponseTypeSuccess, //API请求成功且返回数据正确, PGAPIEntityResponseTypeNoContent, //API请求成功但返回数据不正确。 PGAPIEntityResponseTypeParamsError, //参数是错误的 PGAPIEntityResponseTypeTimeout, //请求超时。 PGAPIEntityResponseTypeNOJsonObject, // PGAPIEntityResponseTypeErrDetail, // PGAPIEntityResponseTypeNoNetWork //网络不通。 }; ////////////////////////////////////////////////////////////////// typedef NS_ENUM (NSUInteger, PGAPIEntityRequestType){ PGAPIEntityRequestTypeGet, PGAPIEntityRequestTypePost }; ////////////////////////////////////////////////////////////////// #endif /* PGNetwokingType_h */
sopig/PGNetworking
APILookUP.h
<reponame>sopig/PGNetworking // // APILookUP.h // PGNetworking // // Created by 张正超 on 16/7/6. // Copyright © 2016年 张正超. All rights reserved. // #import <PGNetworking/PGNetworking.h> @interface APILookUP : PGAPIBase @end
sopig/PGNetworking
Classes/encryption/JXEncryption.h
<gh_stars>1-10 // // JXEncryption.h // PGNetworking // // Created by tolly on 16/4/11. // Copyright © 2016年 张正超. All rights reserved. // #ifndef JXEncryption_h #define JXEncryption_h #import "CRSA.h" #import "JXDES.h" #import "JXRSA.h" #import "CRSA.h" #import "JXUUID.h" #endif /* JXEncryption_h */
sopig/PGNetworking
PGNetworking/APIRegion.h
<reponame>sopig/PGNetworking // // APIRegion.h // PGNetworking // // Created by 张正超 on 16/4/12. // Copyright © 2016年 张正超. All rights reserved. // #import "PGBaseAPIEntity.h" #import "PGAPIBase.h" @interface APIRegion : PGAPIBase @end
sopig/PGNetworking
PGNetworking/APIFunctionSwitch.h
// // APIFunctionSwitch.h // PGNetworking // // Created by 张正超 on 16/6/12. // Copyright © 2016年 张正超. All rights reserved. // #import <PGNetworking/PGNetworking.h> @interface APIFunctionSwitch : PGAPIBase @end
sopig/PGNetworking
Classes/PGBaseModel.h
<gh_stars>1-10 // // PGBaseModel.h // Pods // // Created by 张正超 on 16/4/14. // // #import <Foundation/Foundation.h> @interface PGBaseModel : NSObject @property (nonatomic , strong) NSString *errCode; @property (nonatomic , strong) NSString *errMsg; @property (nonatomic , strong) NSDictionary *result; @property (nonatomic , strong) NSString *success; @property (nonatomic , strong) NSString *toast; @end
sopig/PGNetworking
Classes/encryption/JXDES.h
<gh_stars>1-10 // // JXDES.h // jiuxian // // Created by Dely on 15/9/10. // Copyright (c) 2015年 <EMAIL>. All rights reserved. // /** * 本类主要对传输数据进行加解密 */ #import <Foundation/Foundation.h> #import <CommonCrypto/CommonDigest.h> #import <CommonCrypto/CommonCryptor.h> #import <Security/Security.h> #import <Base64.h> @interface JXDES : NSObject /** * 3Des 加解密 对明文加密和密文解密 * * @param plainString 需要加解密的数据 * @param encryptOrDecrypt 加解密模式 kCCEncrypt-加密 kCCDecrypt-解密 * @param base64KeyString 进行base编码过后的keyString * * @return 返回加解密的结果String */ + (NSString *)tripleDES:(NSString *)plainString encryptOrDecrypt:(CCOperation)encryptOrDecrypt DESBase64Key:(NSString *)base64KeyString; @end
sopig/PGNetworking
Classes/PGNetworkingPrivate.h
// // PGNetworkingPrivate.h // Pods // // Created by 张正超 on 16/6/14. // // #import <Foundation/Foundation.h> @interface PGNetworkingPrivate : NSObject //+ (BOOL)checkJson:(id)json; + (BOOL)checkJson:(id)json withValidator:(id)validatorJson ; @end
sopig/PGNetworking
Classes/PGAPIResponse.h
<reponame>sopig/PGNetworking<filename>Classes/PGAPIResponse.h // // PGAPIResponse.h // PGNetworking // // Created by 张正超 on 16/4/6. // Copyright © 2016年 张正超. All rights reserved. // #import <Foundation/Foundation.h> #import "PGNetwokingType.h" @interface PGAPIResponse : NSObject @property (nonatomic, assign) PGAPIEntityResponseType responseType; @property (nonatomic, copy) NSURLRequest *request; @property (nonatomic, copy) NSHTTPURLResponse *response; @property (nonatomic, copy) NSURLSessionDataTask *task; @property (nonatomic, copy) id content; @property (nonatomic, copy) NSData *responseData; @property (nonatomic, copy) NSString *contentString; @property (nonatomic, assign) NSInteger requestId; @property (nonatomic, copy) NSDictionary *requestParams; @property (nonatomic, assign) BOOL isCache; @property (nonatomic, copy) NSError *error; @property (nonatomic, copy) NSString *errorMsg; @end
sopig/PGNetworking
regionModel.h
<filename>regionModel.h // // regionModel.h // PGNetworking // // Created by tolly on 16/4/14. // Copyright © 2016年 张正超. All rights reserved. // #import <PGNetworking/PGNetworking.h> #import <PGBaseModel.h> @interface regionModel : PGBaseModel @end
sopig/PGNetworking
Classes/Assistants/NSString+urlEncoding.h
// // NSString+urlEncoding.h // PGNetworking // // Created by tolly on 16/4/8. // Copyright © 2016年 张正超. All rights reserved. // #import <Foundation/Foundation.h> @interface NSString (urlEncoding) - (NSString *)trimLeftAndRight; - (NSString *)urlEncoding; - (NSString *)urlDecoding; @end
sopig/PGNetworking
Classes/Cache/JXCache.h
<filename>Classes/Cache/JXCache.h<gh_stars>1-10 // // JXCache.h // jiuxian // // Created by 张正超 on 15/12/10. // Copyright © 2015年 jiux<EMAIL>. All rights reserved. // #import <Foundation/Foundation.h> #import "YTKKeyValueStore.h" #import "PGNetworking.h" @interface JXCache : NSObject + (instancetype)cache; // - (NSDictionary *)fetchCachedDataForkey:(NSString *)key; - (void)saveCacheWithData:(NSDictionary *)responseData forKey:(NSString *)key; //基础方法 - (void)putObject:(id)obj forKey:(NSString *)sKey; - (id)getObjectByKey:(NSString *)sKey; - (YTKKeyValueItem *)getItemByKey:(NSString *)sKey; - (void)deleteObjectByKey:(NSString *)sKey; - (void)clearAllCache; @end
sopig/PGNetworking
lib/lib/lib.h
// // lib.h // lib // // Created by tolly on 16/4/16. // Copyright © 2016年 tolly. All rights reserved. // #import <Foundation/Foundation.h> @interface lib : NSObject + (void)copyRight; @end
sopig/PGNetworking
Classes/encryption/CRSA.h
// // CRSA.h // MGJH5ContainerDemo // // Created by xinba on 4/28/14. // Copyright (c) 2014年 juangua. All rights reserved. // #import <Foundation/Foundation.h> #include <openssl/rsa.h> #include <openssl/pem.h> #include <openssl/err.h> typedef enum { KeyTypePublic, KeyTypePrivate }KeyType; typedef enum { RSA_PADDING_TYPE_NONE = RSA_NO_PADDING, RSA_PADDING_TYPE_PKCS1 = RSA_PKCS1_PADDING, RSA_PADDING_TYPE_SSLV23 = RSA_SSLV23_PADDING }RSA_PADDING_TYPE; @interface CRSA : NSObject{ } + (id)shareInstance; - (RSA *)importRSAKeyWithType:(KeyType)type; - (int)getBlockSizeWithRSA_PADDING_TYPE:(RSA_PADDING_TYPE)padding_type rsa:(RSA *)rsa; - (NSString *) encryptByRsa:(NSString*)content withKeyType:(KeyType)keyType; - (NSString *) decryptByRsa:(NSString*)content withKeyType:(KeyType)keyType; @end
sopig/PGNetworking
Classes/PGAPIEngine.h
<reponame>sopig/PGNetworking // // PGAPIEngine.h // PGNetworking // // Created by tolly on 16/4/6. // Copyright © 2016年 张正超. All rights reserved. // #import <Foundation/Foundation.h> #import "PGNetworking.h" FOUNDATION_EXPORT NSString * const rawDecryptString ; @interface PGAPIEngine : NSObject + (instancetype)shareInstance; - (NSInteger)callGETWithParams:(NSDictionary *)params apiEntity:(PGBaseAPIEntity *)api success:(void (^)(PGAPIResponse *res))success fail:(void (^)(PGAPIResponse *res))fail; - (NSInteger)callPOSTWithParams:(NSDictionary *)params apiEntity:(PGBaseAPIEntity *)api success:(void (^)(PGAPIResponse *res))success fail:(void (^)(PGAPIResponse *res))fail; - (void)cancelRequestWithRequestID:(NSInteger)requestID; - (void)cancelRequestWithRequestIDs:(NSArray *)requestIDs; @end
sopig/PGNetworking
Classes/JXAppContext.h
// // JXAppContext.h // PGNetworking // // Created by 张正超 on 16/4/5. // Copyright © 2016年 张正超. All rights reserved. // #import <Foundation/Foundation.h> #import "PGNetworking.h" @interface JXAppContext : NSObject<PGCommonParams> @end
sopig/PGNetworking
PGNetworking/APIBestPay.h
// // APIBestPay.h // jiuxian // // Created by 张正超 on 16/6/12. // Copyright © 2016年 <EMAIL>. All rights reserved. // #import <PGNetworking/PGNetworking.h> #import <PGAPIBase.h> @interface APIBestPay : PGAPIBase @end
sopig/PGNetworking
Classes/PGMacros.h
// // PGMacros.h // PGNetworking // // Created by tolly on 16/4/6. // Copyright © 2016年 张正超. All rights reserved. // #ifndef PGMacros_h #define PGMacros_h #ifndef weakify #if __has_feature(objc_arc) #define weakify(x) autoreleasepool {} __weak __typeof__(x) __weak_ ## x ## __ = x; #else // #if __has_feature(objc_arc) #define weakify(x) autoreleasepool {} __block __typeof__(x) __block_ ## x ## __ = x; #endif // #if __has_feature(objc_arc) #endif // #ifndef weakify #ifndef strongify #if __has_feature(objc_arc) #define strongify(x) try {} @finally {} __typeof__(x) x = __weak_ ## x ## __; #else // #if __has_feature(objc_arc) #define strongify(x) try {} @finally {} __typeof__(x) x = __block_ ## x ## __; #endif // #if __has_feature(objc_arc) #endif // #ifndef @normalize #if __has_feature(objc_instancetype) #undef AS_SINGLETON #define AS_SINGLETON #undef AS_SINGLETON #define AS_SINGLETON( ... ) \ - (instancetype)sharedInstance; \ + (instancetype)sharedInstance; #undef DEF_SINGLETON #define DEF_SINGLETON \ - (instancetype)sharedInstance \ { \ return [[self class] sharedInstance]; \ } \ + (instancetype)sharedInstance \ { \ static dispatch_once_t once; \ static id __singleton__; \ dispatch_once( &once, ^{ __singleton__ = [[self alloc] init]; } ); \ return __singleton__; \ } #undef DEF_SINGLETON #define DEF_SINGLETON( ... ) \ - (instancetype)sharedInstance \ { \ return [[self class] sharedInstance]; \ } \ + (instancetype)sharedInstance \ { \ static dispatch_once_t once; \ static id __singleton__; \ dispatch_once( &once, ^{ __singleton__ = [[self alloc] init]; } ); \ return __singleton__; \ } #else // #if __has_feature(objc_instancetype) #undef AS_SINGLETON #define AS_SINGLETON( __class ) \ - (__class *)sharedInstance; \ + (__class *)sharedInstance; #undef DEF_SINGLETON #define DEF_SINGLETON( __class ) \ - (__class *)sharedInstance \ { \ return [__class sharedInstance]; \ } \ + (__class *)sharedInstance \ { \ static dispatch_once_t once; \ static __class * __singleton__; \ dispatch_once( &once, ^{ __singleton__ = [[[self class] alloc] init]; } ); \ return __singleton__; \ } #endif // #if __has_feature(objc_instancetype) #undef DEF_SINGLETON_AUTOLOAD #define DEF_SINGLETON_AUTOLOAD( __class ) \ DEF_SINGLETON( __class ) \ + (void)load \ { \ [self sharedInstance]; \ } #define APILog(__apiResponse) [PGLogs log:@"\n======sopig.cc start========\n[requestID] %@\n[URI] %@\n[requestParams] %@\n[Method] %@\n[RequestHeaderFields] %@\n[MIMEType] %@\n[Status] %@\n[ResponseHeaderFields] %@\n[contentString] %@\n[errorReason] %@\n======sopig.cc end=========\n",\ __apiResponse.task.taskDescription,\ [NSString stringWithFormat:@"%@://%@%@",__apiResponse.request.URL.scheme,__apiResponse.request.URL.host,__apiResponse.request.URL.path],\ __apiResponse.requestParams, \ __apiResponse.request.HTTPMethod, \ __apiResponse.request.allHTTPHeaderFields,\ __apiResponse.response.MIMEType,\ [NSString stringWithFormat:@"%ld '%@'",__apiResponse.response.statusCode,[NSHTTPURLResponse localizedStringForStatusCode:__apiResponse.response.statusCode]],\ __apiResponse.response.allHeaderFields,\ __apiResponse.contentString,\ __apiResponse.error.localizedFailureReason]; //#define APILog(__apiResponse) NSLog(@"\n======sopig.cc start========\n[requestID] %@\n[URI] %@\n[requestParams] %@\n[RequestHeaderFields] %@\n[MIMEType] %@\n[ResponseHeaderFields] %@\n[contentString] %@\n[errorReason] %@\n======sopig.cc end=========\n",\ // __apiResponse.task.taskDescription,\ // [NSString stringWithFormat:@"%@://%@%@",__apiResponse.request.URL.scheme,__apiResponse.request.URL.host,__apiResponse.request.URL.path],\ // __apiResponse.requestParams, \ // __apiResponse.request.allHTTPHeaderFields,\ // __apiResponse.response.MIMEType,\ // __apiResponse.response.allHeaderFields,\ // __apiResponse.contentString,\ // __apiResponse.error.localizedFailureReason); #define JX_DEFAULTS [NSUserDefaults standardUserDefaults] #endif /* PGMacros_h */
sopig/PGNetworking
Classes/PGNetworkingConfig.h
// // PGNetworkingConfig.h // PGNetworking // // Created by 张正超 on 16/4/5. // Copyright © 2016年 张正超. All rights reserved. // #import <Foundation/Foundation.h> #import "PGBaseAPIEntity.h" #define DATAKEY @"k1" //加密数据key #define ENCRPTYKEY @"k2" //密钥数据key #define HTTPTYPE @"k3" //系统型号参数 #define HTTPDEVICE @"IOS" //ios //是否使用缓存 #define kPGNetworkingShouldCache NO //使用什么加密方式 #define kPGNetworkingEncrypType PGNetworkingEncryptionTypeUse static NSTimeInterval kCacheOutdateTimeSeconds = 100; static NSTimeInterval kPGNetworkingTimeoutSeconds = 10; @interface PGNetworkingConfig : NSObject @property (nonatomic, strong, nonnull) NSObject<PGCommonParamsGenerator> *commonParamsGenerator; + (NSString *_Nonnull)baseUrlWithServiceType:(PGNetworkingServiceType)serviceType; + (BOOL)shouldEncryption; @end
sopig/PGNetworking
Classes/PGNetworkingReachability.h
// // PGNetworkingReachability.h // PGNetworking // // Created by tolly on 16/4/6. // Copyright © 2016年 张正超. All rights reserved. // #import <Foundation/Foundation.h> #import <AFNetworkReachabilityManager.h> #import <ReactiveCocoa.h> @interface PGNetworkingReachability : NSObject + (RACSignal *)openNetworkCheck; + (void)closeNetworkingCheck; + (BOOL)isReachable; + (AFNetworkReachabilityStatus )netStatus; @end
sopig/PGNetworking
Classes/PGASLMessage.h
// // PGASLMessage.h // Pods // // Created by 张正超 on 16/6/27. // // #import <Foundation/Foundation.h> #import <asl.h> @interface PGASLMessage : NSObject @property (nonatomic , nullable , copy) NSString *ASL_TIME; @property (nonatomic , nullable , copy) NSString *ASL_SENDER; @property (nonatomic , nullable , copy) NSString *ASL_MSG_ID; @property (nonatomic , nullable , copy) NSString *ASL_LEVEL; @property (nonatomic , nullable , copy) NSString *ASL_HOST; @property (nonatomic , nullable , copy) NSString *ASL_MSG; - (nonnull instancetype)initWithASL:(nonnull aslmsg)aslmsg; - (void)showDescription; @end
sopig/PGNetworking
Classes/PGBaseAPIEntity.h
// // PGBaseAPIManager.h // PGNetworking // // Created by tolly on 16/4/5. // Copyright © 2016年 张正超. All rights reserved. // #import <Foundation/Foundation.h> #import "PGNetwokingType.h" //调用成功之后的params里取出 requestId static NSString *_Nonnull const kPGBaseAPIEntityRequestID = @"kPGBaseAPIEntityRequestID"; @class RACSignal; @class RACCommand; @class PGBaseAPIEntity; @class PGAPIResponse; ///////////////////////////////////////////////////////////////////////// @protocol PGAppContext <NSObject> @end ///////////////////////////////////////////////////////////////////////// @protocol PGCommonParams <NSObject> @required - (nonnull NSDictionary *)commonParams; //组装公共参数 @end ///////////////////////////////////////////////////////////////////////// @protocol PGCommonParamsGenerator <NSObject> @required + (nonnull NSObject<PGCommonParams> *)appContext; + (nonnull NSDictionary *)commonParamsDictionary; @end ///////////////////////////////////////////////////////////////////////// @protocol PGAPIEntity <NSObject> @required - (NSString *_Nonnull)apiName; - (PGNetworkingServiceType)serviceType; - (PGAPIEntityRequestType)requestType; @optional - (void)cleanData; - (nullable NSDictionary *)reformParams:(nullable NSDictionary *)params; - (BOOL)shouldCache; @end ///////////////////////////////////////////////////////////////////////// @protocol PGAPIResponseDelegate <NSObject> @required - (void)doSuccess:(__kindof PGBaseAPIEntity *_Nonnull)api; - (void)doFailed:(__kindof PGBaseAPIEntity *_Nonnull)api; @end ///////////////////////////////////////////////////////////////////////// //数据的转化 @protocol PGAPIResponseDataReformer <NSObject> @required - (id _Nullable)api:(PGBaseAPIEntity *_Nonnull)api reformData:(NSDictionary *_Nonnull)data; @end ///////////////////////////////////////////////////////////////////////// @protocol PGAPIValidator <NSObject> @optional //数据格式的验证 - (BOOL)api:(PGBaseAPIEntity *_Nonnull)api isCorrectWithCallBackData:(NSDictionary *_Nullable)data; - (BOOL)api:(PGBaseAPIEntity *_Nonnull)api isCorrectWithParamsData:(NSDictionary *_Nullable)data; @end ///////////////////////////////////////////////////////////////////////// @protocol PGAPIParamsDataSource <NSObject> - (NSDictionary *_Nullable)paramsForApi:(PGBaseAPIEntity *_Nullable)api; @end ///////////////////////////////////////////////////////////////////////// @protocol PGApiInterceptor <NSObject> @optional - (void)api:(PGBaseAPIEntity *_Nonnull)api beforePerformSuccessWithResponse:(PGAPIResponse *_Nonnull)response; - (void)api:(PGBaseAPIEntity *_Nonnull)api afterPerformSuccessWithResponse:(PGAPIResponse *_Nonnull)response; - (void)api:(PGBaseAPIEntity *_Nonnull)api beforePerformFailWithResponse:(PGAPIResponse *_Nonnull)response; - (void)api:(PGBaseAPIEntity *_Nonnull)api afterPerformFailWithResponse:(PGAPIResponse *_Nonnull)response; - (BOOL)api:(PGBaseAPIEntity *_Nonnull)api shouldCallAPIWithParams:(NSDictionary *_Nonnull)params; - (void)api:(PGBaseAPIEntity *_Nonnull)api afterCallingAPIWithParams:(NSDictionary *_Nonnull)params; @end ///////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////// @interface PGBaseAPIEntity : NSObject @property (nonatomic, weak, nullable) id<PGAPIResponseDelegate> delegate; @property (nonatomic, weak, nullable) id<PGAPIParamsDataSource> paramSource; @property (nonatomic, weak, nullable) id<PGAPIValidator> validator; @property (nonatomic, weak, nullable) NSObject<PGAPIEntity> *child; @property (nonatomic, weak, nullable) id<PGApiInterceptor> interceptor; @property (nonatomic, copy, readonly) NSString *_Nullable errorMessage; @property (nonatomic, readonly) PGAPIEntityResponseType responseType; @property (nonatomic, assign, readonly) BOOL isReachable; @property (nonatomic, assign, readonly) BOOL isLoading; - (NSString *)fetchContentString; - (nullable id)fetchPureData; - (NSDictionary * _Nullable)fetchData; - (id _Nullable)fetchDataWithReformer:(id<PGAPIResponseDataReformer> _Nullable)reformer; - (NSInteger)loadData; - (void)cancelAllRequests; - (void)cancelRequestWithRequestId:(NSInteger)requestID; // 拦截器方法,继承之后需要调用一下super - (void)beforePerformSuccessWithResponse:(PGAPIResponse *_Nonnull)response; - (void)afterPerformSuccessWithResponse:(PGAPIResponse *_Nonnull)response; - (void)beforePerformFailWithResponse:(PGAPIResponse *_Nonnull)response; - (void)afterPerformFailWithResponse:(PGAPIResponse *_Nonnull)response; - (BOOL)shouldCallAPIWithParams:(NSDictionary *_Nonnull)params; - (void)afterCallingAPIWithParams:(NSDictionary *_Nonnull)params; - (NSDictionary *_Nullable)reformParams:(NSDictionary *_Nullable)params; - (void)cleanData; - (BOOL)shouldCache; - (BOOL)shouldEncrypt; - (BOOL)logEnable; @end
sopig/PGNetworking
Classes/PGAPIBase.h
<gh_stars>1-10 // // APIBase.h // PGNetworking // // Created by tolly on 16/4/12. // Copyright © 2016年 张正超. All rights reserved. // #import "PGBaseAPIEntity.h" #import "PGBaseModel.h" #define PGDeprecated(instead) NS_DEPRECATED_IOS(2_0, 2_0, instead) @interface PGAPIBase : PGBaseAPIEntity<PGAPIEntity,PGAPIResponseDelegate,PGAPIResponseDataReformer,PGAPIParamsDataSource,PGAPIValidator,PGApiInterceptor> //请求落地的回调 @property (nonatomic ,copy) void (^whenSuccess)(PGBaseAPIEntity *api); @property (nonatomic ,copy) void (^whenFail)(PGBaseAPIEntity *api); ///////////////////// - (BOOL)shouldCache; - (BOOL)shouldEncrypt; ///////////////////// - (PGNetworkingServiceType)serviceType ; -(PGAPIBase *)paramsForApiWithParams:(NSDictionary *(^)(void))block; - (NSString *)apiName; //请求参数 - (NSDictionary *)paramsForApi:(PGBaseAPIEntity *)api; //数据转化为model - (id)api:(PGBaseAPIEntity *)api reformData:(NSDictionary *)data; ////////////////////////////////////////////////////////////////////////////////////////////////////// - (PGAPIEntityRequestType)requestType;//如果是get方式,不用覆写 ////////////////////////////////////////////////////////////////////////////////////////////////////// //取数据 - (NSDictionary *)fetchData; - (id)fetchModel; //请求起飞 - (PGAPIBase *)send; - (RACSignal *)sendSignal; - (RACCommand *)sendCmd; - (void)cancelSend; @end
FabiSparbi/depth_nav_tools_cp
laserscan_kinect/include/laserscan_kinect/laserscan_kinect.h
/****************************************************************************** * Software License Agreement (BSD License) * * Copyright (c) 2016, <NAME> (<EMAIL>) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. 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. *****************************************************************************/ /** * @file laserscan_kinect.h * @author <NAME> (<EMAIL>) * @brief laserscan_kinect package */ #pragma once #include <ros/console.h> #include <sensor_msgs/Image.h> #include <sensor_msgs/LaserScan.h> #include <sensor_msgs/image_encodings.h> #include <image_geometry/pinhole_camera_model.h> #include <vector> #include <string> constexpr double SCAN_TIME = 1.0 / 30.0; namespace laserscan_kinect { class LaserScanKinect { public: LaserScanKinect(): scan_msg_(new sensor_msgs::LaserScan()) { } ~LaserScanKinect() = default; /** * @brief prepareLaserScanMsg converts depthimage and prepare new LaserScan message * * @param depth_msg Message that contains depth image which will be converted to LaserScan. * @param info_msg Message which contains depth sensor parameters. * * @return Return pointer to LaserScan message. */ sensor_msgs::LaserScanPtr getLaserScanMsg(const sensor_msgs::ImageConstPtr& depth_msg, const sensor_msgs::CameraInfoConstPtr& info_msg); /** * @brief setOutputFrame sets the frame to output laser scan * @param frame */ void setOutputFrame (const std::string frame) { output_frame_id_ = frame; } /** * @brief setRangeLimits sets depth sensor min and max ranges * * @param rmin Minimum sensor range (below it is death zone) in meters. * @param rmax Maximum sensor range in meters. */ void setRangeLimits(const float rmin, const float rmax); /** * @brief setScanHeight sets height of depth image which will be used in conversion process * * @param scan_height Height of used part of depth image in pixels. */ void setScanHeight(const int scan_height); /** * @brief setDepthImgRowStep * * @param row_step */ void setDepthImgRowStep(const int row_step); /** * @brief setCamModelUpdate sets the camera parameters * * @param enable */ void setCamModelUpdate (const bool enable) { cam_model_update_ = enable; } /** * @brief setSensorMountHeight sets the height of sensor mount (in meters) */ void setSensorMountHeight (const float height); /** * @brief setSensorTiltAngle sets the sensor tilt angle (in degrees) * * @param angle */ void setSensorTiltAngle (const float angle); /** * @brief setGroundRemove enables or disables the feature which remove ground from scan * * @param enable */ void setGroundRemove (const bool enable) { ground_remove_enable_ = enable; } /** * @brief setGroundMargin sets the floor margin (in meters) * * @param margin */ void setGroundMargin (const float margin); /** * @brief setTiltCompensation enables or disables the feature which compensates sensor tilt * * @param enable */ void setTiltCompensation (const bool enable) { tilt_compensation_enable_ = enable; } /** * @brief setScanConfigurated sets the configuration status * * @param enable */ void setScanConfigurated (const bool configurated) { is_scan_msg_configurated_ = configurated; } protected: /** * @brief lengthOfVector calculate length of 3D vector * * @param ray * @return */ double lengthOfVector(const cv::Point3d& ray) const; /** * @brief angleBetweenRays calculate angle between two rays in degrees * @return */ double angleBetweenRays(const cv::Point3d& ray1, const cv::Point3d& ray2) const; /** * @brief fieldOfView calculate field of view (angle) */ void calcFieldOfView( const cv::Point2d && left, const cv::Point2d && center, const cv::Point2d && right, double & min, double & max); /** * @brief calcGroundDistancesForImgRows calculate coefficients used in ground removing from scan * * @param vertical_fov */ void calcGroundDistancesForImgRows(double vertical_fov); /** * @brief calcTiltCompensationFactorsForImgRows calculate factors used in tilt compensation * * @param vertical_fov */ void calcTiltCompensationFactorsForImgRows(double vertical_fov); /** * @brief calcScanMsgIndexForImgCols * * @param depth_msg */ void calcScanMsgIndexForImgCols(const sensor_msgs::ImageConstPtr& depth_msg); /** * @brief getSmallestValueInColumn finds smallest values in depth image columns */ template <typename T> float getSmallestValueInColumn(const T* depth_row, int row_size, int col) { float depth_min = std::numeric_limits<float>::max(); const unsigned range_min_mm = range_min_ * 1000; const unsigned range_max_mm = range_max_ * 1000; // Loop over pixels in column. Calculate z_min in column for (size_t i = image_vertical_offset_; i < image_vertical_offset_ + scan_height_; i += depth_img_row_step_) { unsigned depth_raw_mm; float depth_m; if (typeid(T) == typeid(uint16_t)) { depth_raw_mm = static_cast<unsigned>(depth_row[row_size * i + col]); depth_m = static_cast<float>(depth_raw_mm) / 1000.0; } else if (typeid(T) == typeid(float)) { depth_m = static_cast<float>(depth_row[row_size * i + col]); depth_raw_mm = static_cast<unsigned>(depth_m * 1000.0); } if (tilt_compensation_enable_) // Check if tilt compensation is enabled { depth_m *= tilt_compensation_factor_[i]; } // Check if point is in ranges and find min value in column if (depth_raw_mm >= range_min_mm && depth_raw_mm <= range_max_mm) { if (ground_remove_enable_) { if (depth_m < depth_min && depth_raw_mm < dist_to_ground_corrected[i]) { depth_min = depth_m; } } else { if (depth_m < depth_min) { depth_min = depth_m; } } } } return depth_min; } /** * @brief convertDepthToPolarCoords converts depth map to 2D * * @param depth_msg */ template <typename T> void convertDepthToPolarCoords(const sensor_msgs::ImageConstPtr& depth_msg); private: //----------------------------------------------------------------------------------------------- // ROS parameters configurated with configuration file or dynamic_reconfigure std::string output_frame_id_; ///< Output frame_id for laserscan message. float range_min_{0}; ///< Stores the current minimum range to use float range_max_{0}; ///< Stores the current maximum range to use unsigned scan_height_{0}; ///< Number of pixel rows used to scan computing unsigned depth_img_row_step_{0}; ///< Row step in depth map processing bool cam_model_update_{false}; ///< If continously calibration update required float sensor_mount_height_{0}; ///< Height of sensor mount from ground float sensor_tilt_angle_{0}; ///< Angle of sensor tilt bool ground_remove_enable_{false}; ///< Determines if remove ground from output scan float ground_margin_{0}; ///< Margin for floor remove feature (in meters) bool tilt_compensation_enable_{false}; ///< Determines if tilt compensation feature is on //----------------------------------------------------------------------------------------------- /// Published scan message sensor_msgs::LaserScanPtr scan_msg_; /// Class for managing CameraInfo messages image_geometry::PinholeCameraModel cam_model_; /// Determines if laser scan message is configurated bool is_scan_msg_configurated_{false}; /// Calculated laser scan msg indexes for each depth image column std::vector<unsigned> scan_msg_index_; /// Calculated maximal distances for measurements not included as floor std::vector<unsigned> dist_to_ground_corrected; /// Calculated sensor tilt compensation factors std::vector<float> tilt_compensation_factor_; /// The vertical offset of image based on calibration data int image_vertical_offset_{0}; }; };
FabiSparbi/depth_nav_tools_cp
cliff_detector/include/cliff_detector/cliff_detector_node.h
<reponame>FabiSparbi/depth_nav_tools_cp<filename>cliff_detector/include/cliff_detector/cliff_detector_node.h /****************************************************************************** * Software License Agreement (BSD License) * * Copyright (c) 2015, <NAME> (<EMAIL>) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. 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. *****************************************************************************/ /** * @file cliff_detector_node.h * @author <NAME> (<EMAIL>) * @date 10.2015 * @brief cliff_detector package */ #ifndef CLIFF_DETECTOR_NODE #define CLIFF_DETECTOR_NODE #include <ros/ros.h> #include <image_transport/image_transport.h> #include <boost/thread/mutex.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <cv_bridge/cv_bridge.h> #include <sensor_msgs/Image.h> #include <std_msgs/Float64.h> #include <sensor_msgs/image_encodings.h> #include <depth_nav_msgs/Point32List.h> #include <dynamic_reconfigure/server.h> #include <cliff_detector/CliffDetectorConfig.h> #include <cliff_detector/cliff_detector.h> namespace cliff_detector { class CliffDetectorNode { public: CliffDetectorNode(ros::NodeHandle& n, ros::NodeHandle& pnh); ~CliffDetectorNode(); /** * @brief setNodeRate sets rate of processing data loop in node. * * @param rate Frequency of data processing loop in Hz. */ void setNodeRate(const unsigned int rate); /** * @brief getNodeRate gets rate of data processing loop in node. * @return Returns data processing loop rate in Hz. */ unsigned int getNodeRate(); private: // Private methods /** * @brief depthCb is callback which is called when new depth image appear * * Callback for depth image and camera info. * It converts depth image to laserscan and publishes it at the end. * * @param depth_msg Depth image provided by image_transport. * @param info_msg CameraInfo provided by image_transport. */ void depthCb( const sensor_msgs::ImageConstPtr& depth_msg, const sensor_msgs::CameraInfoConstPtr& info_msg); /** * @brief connectCb is callback which is called when new subscriber connected. * * It allow to subscribe depth image and publish laserscan message only when * is laserscan subscriber appear. * * @param pub Publisher which subscribers are checked. */ void connectCb(); /** * @brief disconnectCb is called when a subscriber stop subscribing * * When no one subscribers subscribe laserscan topic, then it stop to subscribe depth image. * * @param pub Publisher which subscribers are checked. */ void disconnectCb(); /** * @brief reconfigureCb is dynamic reconfigure callback * * Callback is necessary to set ROS parameters with dynamic reconfigure server. * * @param config Dynamic Reconfigure object. * @param level Dynamic Reconfigure level. */ void reconfigureCb(cliff_detector::CliffDetectorConfig& config, uint32_t level); private: // Private fields // Node loop frequency in Hz unsigned int node_rate_hz_; /// Private node handler used to generate the transport hints in the connectCb. ros::NodeHandle pnh_; /// Subscribes to synchronized Image CameraInfo pairs. image_transport::ImageTransport it_; /// Subscriber for image_transport image_transport::CameraSubscriber sub_; /// Publisher for image_transport image_transport::Publisher pub_; /// Publisher for publishing messages with stairs points ros::Publisher pub_points_; /// Dynamic reconfigure server dynamic_reconfigure::Server<cliff_detector::CliffDetectorConfig> reconf_srv_; /// Contains cliff detection method implementation cliff_detector::CliffDetector detector_; /// Prevents the connectCb and disconnectCb from being called until everything is initialized. boost::mutex connection_mutex_; }; }; #endif
FabiSparbi/depth_nav_tools_cp
cliff_detector/include/cliff_detector/cliff_detector.h
/****************************************************************************** * Software License Agreement (BSD License) * * Copyright (c) 2015, <NAME> (<EMAIL>) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. 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. *****************************************************************************/ /** * @file cliff_detector.h * @author <NAME> (<EMAIL>) * @date 03.2016 * @brief cliff_detector package */ #ifndef CLIFF_DETECTOR #define CLIFF_DETECTOR #include <ros/console.h> #include <sensor_msgs/Image.h> #include <sensor_msgs/image_encodings.h> #include <image_geometry/pinhole_camera_model.h> #include <depth_nav_msgs/Point32List.h> #include <geometry_msgs/Point32.h> #include <sstream> #include <limits.h> #include <math.h> #include <cmath> #include <string> #include <boost/lexical_cast.hpp> #include <iostream> #include <fstream> #include <utility> #include <cstdlib> #include <vector> namespace cliff_detector { /** * @brief The CliffDetector class detect cliff based on depth image */ class CliffDetector { //--------------------------------------------------------------------------------------------- public: // Public methods CliffDetector(); ~CliffDetector() { } /** * @brief detectCliff detects descending stairs based on the information in a depth image * * This function detects descending stairs based on the information * in the depth encoded image (UInt16 encoding). To do this, it requires * the synchornized Image/CameraInfo pair associated with the image. * * @param depth_msg UInt16 encoded depth image. * @param info_msg CameraInfo associated with depth_msg */ void detectCliff( const sensor_msgs::ImageConstPtr& depth_msg, const sensor_msgs::CameraInfoConstPtr& info_msg); /** * @brief setRangeLimits sets the minimum and maximum range of depth value from RGBD sensor. * * @param rmin Minimum of depth value which will be used in data processing. * @param rmin Maximum of depth value which will be used in data processing. */ void setRangeLimits(const float rmin, const float rmax); /** * @brief setSensorMountHeight sets the height of sensor mount (in meters) from ground * * @param height Value of sensor mount height (in meters). */ void setSensorMountHeight (const float height); /** * @brief getSensorMountHeight gets sensor mount height * * @return Return sensor mount height in meters */ float getSensorMountHeight () { return sensor_mount_height_; } /** * @brief setSensorTiltAngle sets the sensor tilt angle (in degrees) * @param angle */ void setSensorTiltAngle (const float angle); /** * @brief getSensorTiltAngle gets sensor tilt angle in degrees * * @return Return sensor tilt angle in degrees */ float getSensorTiltAngle () { return sensor_tilt_angle_; } /** * @brief setPublishDepthEnable * @param enable */ void setPublishDepthEnable (const bool enable) { publish_depth_enable_ = enable; } /** * @brief getPublishDepthEnable * @return */ bool getPublishDepthEnable () const { return publish_depth_enable_; } /** * @brief Sets the number of image rows to use in data processing. * * scan_height is the number of rows (pixels) to use in the output. * * @param scan_height Number of pixels centered around the center of * the image to data processing * */ /** * @brief Set value which determine if sensor params needs continously update */ /** * @brief setCamModelUpdate * @param u */ void setCamModelUpdate (const bool u) { cam_model_update_ = u; } /** * @brief setUsedDepthHeight * @param height */ void setUsedDepthHeight(const unsigned int height); /** * @brief setBlockSize sets size of square block (subimage) used in cliff detector * * @param size Size of square block in pixels */ void setBlockSize(const int size); /** * @brief setBlockPointsThresh sets threshold value of pixels in block to set block as stairs * * @param thresh Value of threshold in pixels. */ void setBlockPointsThresh(const int thresh); /** * @brief setDepthImgStepRow * @param step */ void setDepthImgStepRow(const int step); /** * @brief setDepthImgStepCol * @param step */ void setDepthImgStepCol(const int step); /** * @brief setGroundMargin sets the floor margin (in meters) * @param margin */ void setGroundMargin (const float margin); /** * @brief setParametersConfigurated * @param u */ void setParametersConfigurated (const bool u) { depth_sensor_params_update = u; } //--------------------------------------------------------------------------------------------- private: // Private methods /** * @brief lengthOfVector calculates length of 3D vector. * * Method calculates the length of 3D vector assumed to be a vector with start at the (0,0,0). * * @param vec Vector 3D which lenght will be calculated. * @return Returns the length of 3D vector. */ double lengthOfVector(const cv::Point3d& vec) const; /** * Computes the angle between two cv::Point3d * * Computes the angle of two cv::Point3d assumed to be vectors starting * at the origin (0,0,0). Uses the following equation: * angle = arccos(a*b/(|a||b|)) where a = ray1 and b = ray2. * * @param ray1 The first ray * @param ray2 The second ray * @return The angle between the two rays (in radians) */ double angleBetweenRays(const cv::Point3d& ray1, const cv::Point3d& ray2) const; /** * Find 2D points relative to robots where stairs are detected * * This uses a method * * @param depth_msg The UInt16 encoded depth message. */ void findCliffInDepthImage(const sensor_msgs::ImageConstPtr& depth_msg); /** * Calculate vertical angle_min and angle_max by measuring angles between * the top ray, bottom ray, and optical center ray * * @param camModel The image_geometry camera model for this image. * @param min_angle The minimum vertical angle * @param max_angle The maximum vertical angle */ void fieldOfView(double & min, double & max, double x1, double y1, double xc, double yc, double x2, double y2); /** * @brief calcDeltaAngleForImgRows * @param vertical_fov */ void calcDeltaAngleForImgRows(double vertical_fov); /** * @brief Calculates distances to ground for every row of depth image * * Calculates distances to ground for rows of depth image based on known height of sensor * mount and tilt angle. It assume that sensor height and tilt angle in relative to ground * is constant. * * Calculated values are placed in vector dist_to_ground_. */ void calcGroundDistancesForImgRows(double vertical_fov); /** * @brief calcTiltCompensationFactorsForImgRows calculate factors used in tilt compensation * * @param vertical_fov */ void calcTiltCompensationFactorsForImgRows(double vertical_fov); private: // Private fields //----------------------------------------------------------------------------------------------- // ROS parameters configurated with config file or dynamic_reconfigure std::string outputFrameId_; ///< Output frame_id for laserscan. float range_min_; ///< Stores the current minimum range to use float range_max_; ///< Stores the current maximum range to use float sensor_mount_height_; ///< Height of sensor mount from ground float sensor_tilt_angle_; ///< Sensor tilt angle (degrees) bool publish_depth_enable_; ///< Determines if depth should be republished bool cam_model_update_; ///< Determines if continuously cam model update required unsigned int used_depth_height_; ///< Used depth height from img bottom (px) unsigned int block_size_; ///< Square block (subimage) size (px). unsigned int block_points_thresh_; ///< Threshold value of points in block to admit stairs unsigned int depth_image_step_row_; ///< Rows step in depth processing (px). unsigned int depth_image_step_col_; ///< Columns step in depth processing (px). float ground_margin_; ///< Margin for ground points feature detector (m) //----------------------------------------------------------------------------------------------- bool depth_sensor_params_update; /// Class for managing sensor_msgs/CameraInfo messages image_geometry::PinholeCameraModel camera_model_; /// Calculated distances to ground for every row of depth image in mm std::vector<unsigned int> dist_to_ground_; /// Calculated sensor tilt compensation factors std::vector<double> tilt_compensation_factor_; std::vector<double> delta_row_; //----------------------------------------------------------------------------------------------- public: // Public fields sensor_msgs::Image new_depth_msg_; sensor_msgs::ImageConstPtr depth_msg_to_pub_; ///< Store points which contain stairs depth_nav_msgs::Point32List stairs_points_msg_; }; }; // cliff_detector #endif
FabiSparbi/depth_nav_tools_cp
laserscan_kinect/include/laserscan_kinect/laserscan_kinect_node.h
/****************************************************************************** * Software License Agreement (BSD License) * * Copyright (c) 2016, <NAME> (<EMAIL>) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. 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. *****************************************************************************/ /** * @file main.cpp * @author <NAME> (<EMAIL>) * @brief laserscan_kinect package */ #pragma once #include <mutex> #include <ros/ros.h> #include <image_transport/image_transport.h> #include <sensor_msgs/Image.h> #include <sensor_msgs/LaserScan.h> #include <dynamic_reconfigure/server.h> #include <laserscan_kinect/LaserscanKinectConfig.h> #include <laserscan_kinect/laserscan_kinect.h> namespace laserscan_kinect { class LaserScanKinectNode { public: /** * @brief LaserScanKinectNode constructor. * * @param n Node handler. * @param pnh Private node handler. */ LaserScanKinectNode(ros::NodeHandle& n, ros::NodeHandle& pnh); ~LaserScanKinectNode(); private: /** * @brief depthCb is callback which is called when new depth image appear * * Callback for depth image and camera info. * It converts depth image to laserscan and publishes it at the end. * * @param depth_msg Depth image provided by image_transport. * @param info_msg CameraInfo provided by image_transport. */ void depthCb(const sensor_msgs::ImageConstPtr& depth_msg, const sensor_msgs::CameraInfoConstPtr& info_msg); /** * @brief connectCb is callback which is called when new subscriber connected. * * It allow to subscribe depth image and publish laserscan message only when * is laserscan subscriber appear. * * @param pub Publisher which subscribers are checked. */ void connectCb(const ros::SingleSubscriberPublisher& pub); /** * @brief disconnectCb is called when a subscriber stop subscribing * * When no one subscribers subscribe laserscan topic, then it stop to subscribe depth image. * * @param pub Publisher which subscribers are checked. */ void disconnectCb(const ros::SingleSubscriberPublisher& pub); /** * @brief reconfigureCb is dynamic reconfigure callback * * Callback is necessary to set ROS parameters with dynamic reconfigure server. * * @param config Dynamic Reconfigure object. * @param level Dynamic Reconfigure level. */ void reconfigureCb(laserscan_kinect::LaserscanKinectConfig &config, uint32_t level); /// Private node handler used to generate the transport hints in the connectCb. ros::NodeHandle pnh_; /// Subscribes to synchronized Image CameraInfo pairs. image_transport::ImageTransport it_; /// Subscriber for image_transport image_transport::CameraSubscriber sub_; /// Publisher for output LaserScan messages ros::Publisher pub_; /// Dynamic reconfigure server dynamic_reconfigure::Server<laserscan_kinect::LaserscanKinectConfig> srv_; /// Object which convert depth image to laserscan and store all parameters laserscan_kinect::LaserScanKinect converter_; /// Prevents the connectCb and disconnectCb from being called until everything is initialized. std::mutex connect_mutex_; }; };
FabiSparbi/depth_nav_tools_cp
depth_sensor_pose/include/depth_sensor_pose/depth_sensor_pose.h
<filename>depth_sensor_pose/include/depth_sensor_pose/depth_sensor_pose.h /****************************************************************************** * Software License Agreement (BSD License) * * Copyright (c) 2016, <NAME> (<EMAIL>) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. 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. *****************************************************************************/ /** * @file depth_sensor_pose.h * @author <NAME> (<EMAIL>) * @brief depth_sensor_pose package */ #pragma once #include <ros/console.h> #include <ros/ros.h> #include <sensor_msgs/Image.h> #include <sensor_msgs/LaserScan.h> #include <sensor_msgs/image_encodings.h> #include <image_geometry/pinhole_camera_model.h> #include <sstream> #include <limits> #include <vector> #include <cmath> #include <string> #include <iostream> #include <fstream> #include <pcl/point_types.h> #include <pcl/sample_consensus/ransac.h> #include <pcl/sample_consensus/sac_model_plane.h> #include <pcl/sample_consensus/method_types.h> #include <pcl/sample_consensus/model_types.h> #include <pcl/segmentation/sac_segmentation.h> #include <Eigen/Core> //#define DEBUG 1 //#define DATA_TO_FILE //#define DEBUG_INFO //#define DEBUG_CALIBRATION namespace depth_sensor_pose { class DepthSensorPose { public: DepthSensorPose() = default; ~DepthSensorPose() = default; DepthSensorPose (const DepthSensorPose &) = delete; DepthSensorPose & operator= (const DepthSensorPose &) = delete; /** * Converts the information in a depth image (sensor_msgs::Image) to a sensor_msgs::LaserScan. * * This function converts the information in the depth encoded image (UInt16) into * a sensor_msgs::LaserScan as accurately as possible. To do this, it requires the * synchornized Image/CameraInfo pair associated with the image. * * @param depth_msg UInt16 or Float32 encoded depth image. * @param info_msg CameraInfo associated with depth_msg * @return sensor_msgs::LaserScanPtr for the center row(s) of the depth image. * */ void estimateParams(const sensor_msgs::ImageConstPtr& depth_msg, const sensor_msgs::CameraInfoConstPtr& info_msg); /** * Sets the minimum and maximum range for the sensor_msgs::LaserScan. * * rangeMin is used to determine how close of a value to allow through when multiple radii * correspond to the same angular increment. rangeMax is used to set the output message. * * @param rangeMin Minimum range to assign points to the laserscan, also minimum range to use points in the output scan. * @param rangeMax Maximum range to use points in the output scan. * */ void setRangeLimits(const float rmin, const float rmax); /** * @brief setSensorMountHeight sets the height of sensor mount (in meters) from ground * * @param height Value of sensor mount height (in meters). */ void setSensorMountHeightMin (const float height); /** * @brief setSensorMountHeight sets the height of sensor mount (in meters) from ground * * @param height Value of sensor mount height (in meters). */ void setSensorMountHeightMax (const float height); /** * @brief setSensorTiltAngle sets the sensor tilt angle (in degrees) * @param angle */ void setSensorTiltAngleMin (const float angle); /** * @brief setSensorTiltAngle sets the sensor tilt angle (in degrees) * @param angle */ void setSensorTiltAngleMax (const float angle); /** * @brief setPublishDepthEnable * @param enable */ void setPublishDepthEnable (const bool enable) { publish_depth_enable_ = enable; } /** * @brief getPublishDepthEnable * @return */ bool getPublishDepthEnable () const { return publish_depth_enable_; } /** * @brief setCamModelUpdate * @param u */ void setCamModelUpdate (const bool u) { cam_model_update_ = u; } /** * @brief setUsedDepthHeight * @param height */ void setUsedDepthHeight(const unsigned int height); /** * @brief setDepthImgStepRow * @param step */ void setDepthImgStepRow(const int step); /** * @brief setDepthImgStepCol * @param step */ void setDepthImgStepCol(const int step); /** * @brief setReconfParamsUpdated * @param updated */ void setReconfParamsUpdated (bool updated) {reconf_serv_params_updated_ = updated; } void setRansacMaxIter (const unsigned int u) { ransacMaxIter_ = u; } void setRansacDistanceThresh (const float u) { ransacDistanceThresh_ = u; } void setGroundMaxPoints (const unsigned int u) { max_ground_points_ = u; } //------------------------------------------------------------------------ float getSensorTiltAngle () const { return tilt_angle_est_; } float getSensorMountHeight () const { return mount_height_est_; } //--------------------------------------------------------------------------------------------- private: // Private methods /** * Computes euclidean length of a cv::Point3d (as a ray from origin) * * This function computes the length of a cv::Point3d assumed to be a vector starting at the origin (0,0,0). * * @param ray The ray for which the magnitude is desired. * @return Returns the magnitude of the ray. * */ double lengthOfVector( const cv::Point3d& ray) const; /** * Computes the angle between two cv::Point3d * * Computes the angle of two cv::Point3d assumed to be vectors starting at the origin (0,0,0). * Uses the following equation: angle = arccos(a*b/(|a||b|)) where a = ray1 and b = ray2. * * @param ray1 The first ray * @param ray2 The second ray * @return The angle between the two rays (in radians) * */ double angleBetweenRays( const cv::Point3d& ray1, const cv::Point3d& ray2) const; /** * Calculate vertical angle_min and angle_max by measuring angles between the top * ray, bottom ray, and optical center ray * * @param camModel The image_geometry camera model for this image. * @param min_angle The minimum vertical angle * @param max_angle The maximum vertical angle */ void fieldOfView( double & min, double & max, double x1, double y1, double xc, double yc, double x2, double y2 ); /** * @brief calcDeltaAngleForImgRows * @param vertical_fov */ void calcDeltaAngleForImgRows( double vertical_fov); /** * @brief Calculates distances to ground for every row of depth image * * Calculates distances to ground for rows of depth image based on known height of sensor * mount and tilt angle. It assume that sensor height and tilt angle in relative to ground * is constant. * * Calculated values are placed in vector dist_to_ground_. */ void calcGroundDistancesForImgRows( double mount_height, double tilt_angle, std::vector<unsigned int>& distances); /** * @brief */ void getGroundPoints(const sensor_msgs::ImageConstPtr& depth_msg, pcl::PointCloud<pcl::PointXYZ>::Ptr& points); /** * @brief */ void sensorPoseCalibration(const sensor_msgs::ImageConstPtr& depth_msg, double & tilt, double & height); //----------------------------------------------------------------------------------------------- public: sensor_msgs::Image new_depth_msg_; private: // ROS parameters configurated with config files or dynamic_reconfigure float range_min_{0}; ///< Stores the current minimum range to use float range_max_{0}; ///< Stores the current maximum range to use float mount_height_min_{0}; ///< Min height of sensor mount from ground float mount_height_max_{0}; ///< Max height of sensor mount from ground float tilt_angle_min_{0}; ///< Min angle of sensor tilt in degrees float tilt_angle_max_{0}; ///< Max angle of sensor tilt in degrees bool publish_depth_enable_{false}; ///< Determines if modified depth image should be published bool cam_model_update_{false}; ///< Determines if continuously cam model update is required unsigned int used_depth_height_{0}; ///< Used depth height from img bottom (px) unsigned int depth_image_step_row_{0}; ///< Rows step in depth processing (px). unsigned int depth_image_step_col_{0}; ///< Columns step in depth processing (px). unsigned int max_ground_points_{0}; unsigned int ransacMaxIter_{0}; float ransacDistanceThresh_{0}; float groundDistTolerance_{0}; //---------------------------------------------------------------------------- ///< Class for managing sensor_msgs/CameraInfo messages image_geometry::PinholeCameraModel camera_model_; float mount_height_est_{0}; float tilt_angle_est_{0}; bool reconf_serv_params_updated_{true}; std::vector<double> delta_row_; std::vector<unsigned int>dist_to_ground_max_; std::vector<unsigned int>dist_to_ground_min_; }; template <typename T> std::string NumberToString ( T Number ) { std::ostringstream ss; ss << Number; return ss.str(); } }
FabiSparbi/depth_nav_tools_cp
nav_layer_from_points/include/nav_layer_from_points/costmap_layer.h
/****************************************************************************** * Software License Agreement (BSD License) * * Copyright (c) 2015, <NAME> (<EMAIL>) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. 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. *****************************************************************************/ /** * @file main.cpp * @author <NAME> (<EMAIL>) * @date 10.2015 * @brief nav_layer_from_points package */ #ifndef COSTMAP_LAYER_H #define COSTMAP_LAYER_H #include <ros/ros.h> #include <costmap_2d/layered_costmap.h> #include <costmap_2d/footprint.h> #include <costmap_2d/layer.h> #include <pluginlib/class_list_macros.h> #include <depth_nav_msgs/Point32List.h> #include <geometry_msgs/PointStamped.h> #include <boost/thread.hpp> #include <tf/transform_listener.h> #include <math.h> #include <algorithm> #include <angles/angles.h> #include <dynamic_reconfigure/server.h> #include <nav_layer_from_points/NavLayerFromPointsConfig.h> namespace nav_layer_from_points { class NavLayerFromPoints : public costmap_2d::Layer { public: NavLayerFromPoints() { layered_costmap_ = NULL; } virtual void onInitialize(); virtual void updateBounds( double origin_x, double origin_y, double origin_yaw, double* min_x, double* min_y, double* max_x, double* max_y); virtual void updateCosts( costmap_2d::Costmap2D& master_grid, int min_i, int min_j, int max_i, int max_j); void updateBoundsFromPoints( double* min_x, double* min_y, double* max_x, double* max_y); bool isDiscretized() { return false; } protected: void pointsCallback(const depth_nav_msgs::Point32List& points); /** * @brief clearTransformedPoints clears points from list transformed_points_ after some time */ void clearTransformedPoints(); void configure(NavLayerFromPointsConfig &config, uint32_t level); protected: // Protected fields ros::Subscriber sub_points_; ///< Subscriber for points depth_nav_msgs::Point32List points_list_; ///< List of received points tf::TransformListener tf_; std::list<geometry_msgs::PointStamped> transformed_points_; // After this time points will be delete ros::Duration points_keep_time_; boost::recursive_mutex lock_; bool first_time_; double last_min_x_, last_min_y_, last_max_x_, last_max_y_; private: //----------------------------------------------------------------------------------------------- // ROS parameters configurated with config file or dynamic_reconfigure double point_radius_; double robot_radius_; //----------------------------------------------------------------------------------------------- dynamic_reconfigure::Server<NavLayerFromPointsConfig>* rec_server_; dynamic_reconfigure::Server<NavLayerFromPointsConfig>::CallbackType f_; }; } // end of namespace #endif
FabiSparbi/depth_nav_tools_cp
depth_sensor_pose/include/depth_sensor_pose/depth_sensor_pose_node.h
/****************************************************************************** * Software License Agreement (BSD License) * * Copyright (c) 2015, <NAME> (<EMAIL>) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. 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. *****************************************************************************/ /** * @file depth_sensor_pose_node.h * @author <NAME> (<EMAIL>) * @brief depth_sensor_pose package */ #pragma once #include <mutex> #include <ros/ros.h> #include <image_transport/image_transport.h> #include <dynamic_reconfigure/server.h> #include <std_msgs/Float64.h> #include <sensor_msgs/Image.h> #include <sensor_msgs/image_encodings.h> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <cv_bridge/cv_bridge.h> #include <depth_sensor_pose/DepthSensorPoseConfig.h> #include <depth_sensor_pose/depth_sensor_pose.h> namespace depth_sensor_pose { class DepthSensorPoseNode { public: DepthSensorPoseNode(ros::NodeHandle& n, ros::NodeHandle& pnh); ~DepthSensorPoseNode(); DepthSensorPoseNode (const DepthSensorPoseNode &) = delete; DepthSensorPoseNode & operator= (const DepthSensorPoseNode &) = delete; /** * @brief setNodeRate sets rate of processing data loop in node. * * @param rate Frequency of data processing loop in Hz. */ void setNodeRate(const float rate); /** * @brief getNodeRate gets rate of data processing loop in node. * * @return Returns data processing loop rate in Hz. */ float getNodeRate(); private: /** * @brief depthCb is callback which is called when new depth image appear * * Callback for depth image and camera info. * It runs sensor mount parameters estimation algorithms * * @param depth_msg Depth image provided by image_transport. * @param info_msg CameraInfo provided by image_transport. */ void depthCb(const sensor_msgs::ImageConstPtr& depth_msg, const sensor_msgs::CameraInfoConstPtr& info_msg); /** * @brief connectCb is callback which is called when new subscriber connected. * * It allow to subscribe depth image and publish prepared message only when * is subscriber appear. * * @param pub Publisher which subscribers are checked. */ void connectCb(); /** * @brief disconnectCb is called when a subscriber stop subscribing * * When no one subscribers subscribe topics, then it stop to subscribe depth image. * * @param pub Publisher which subscribers are checked. */ void disconnectCb(); /** * @brief reconfigureCb is dynamic reconfigure callback * * Callback is necessary to set ROS parameters with dynamic reconfigure server. * * @param config Dynamic Reconfigure object. * @param level Dynamic Reconfigure level. */ void reconfigureCb(depth_sensor_pose::DepthSensorPoseConfig& config, uint32_t level); //------------------------------------------------------------------------------------------------- private: float node_rate_hz_{1}; ///< Node loop frequency in Hz ros::NodeHandle pnh_; ///< Private node handler image_transport::ImageTransport it_; ///< Subscribes to synchronized Image CameraInfo pairs image_transport::CameraSubscriber sub_; ///< Subscriber for image_transport ros::Publisher pub_height_; ///< Publisher for estimated sensor height ros::Publisher pub_angle_; ///< Publisher for estimated sensor tilt angle image_transport::Publisher pub_; ///< Publisher for image_transport /// Dynamic reconfigure server dynamic_reconfigure::Server<depth_sensor_pose::DepthSensorPoseConfig> srv_; /// Object which contain estimation methods depth_sensor_pose::DepthSensorPose estimator_; /// Prevents the connectCb and disconnectCb from being called until everything is initialized std::mutex connection_mutex_; }; }
ahurta92/nwchem-1
src/tce/ccsd_t/hybrid.c
<filename>src/tce/ccsd_t/hybrid.c<gh_stars>1-10 /*------------------------------------------hybrid execution------------*/ /* $Id$ */ #include <assert.h> ///#define NUM_DEVICES 1 #define OLD_CUDA 1 static long long device_id=-1; #include <stdio.h> #include <stdlib.h> #ifdef TCE_HIP #include <hip/hip_runtime_api.h> #endif #ifdef TCE_CUDA #ifdef OLD_CUDA #include <cuda_runtime_api.h> #else #include <cuda.h> #endif #endif #include "ga.h" #include "typesf2c.h" extern void FATR util_getppn_(Integer *); extern int util_my_smp_index(); int check_device_(long *icuda) { /* Check whether this process is associated with a GPU */ if((util_my_smp_index())<*icuda) return 1; return 0; } //void device_init_(int *icuda) { int device_init_(long *icuda,long *cuda_device_number ) { /* Set device_id */ int dev_count_check=0; device_id = util_my_smp_index(); #ifdef TCE_CUDA cudaGetDeviceCount(&dev_count_check); #endif #ifdef TCE_HIP hipGetDeviceCount(&dev_count_check); #endif if(dev_count_check < *icuda){ printf("Warning: Please check whether you have %ld cuda devices per node\n",*icuda); fflush(stdout); *cuda_device_number = 30; } else { #ifdef TCE_CUDA cudaSetDevice(device_id); #endif #ifdef TCE_HIP hipSetDevice(device_id); #endif } return 1; }
mscherotter/Microsoft.Mixer.MixPlay
Microsoft.Mixer/ControlProperty.h
#pragma once typedef void* interactive_session; namespace Microsoft { namespace Mixer { namespace MixPlay { public enum class PropertyType { interactive_unknown_t, interactive_int_t, interactive_bool_t, interactive_float_t, interactive_string_t, interactive_array_t, interactive_object_t }; public ref class ControlProperty sealed { public: property Platform::String^ Name; property PropertyType PropertyType; property int Integer { int get(); } property Platform::String^ String { Platform::String^ get(); void set(Platform::String^ value); } internal: ControlProperty(interactive_session session, const char* controlId); private: interactive_session _session; std::string _controlId; }; } } }
mscherotter/Microsoft.Mixer.MixPlay
Microsoft.Mixer/InputEventArgs.h
<reponame>mscherotter/Microsoft.Mixer.MixPlay #pragma once namespace Microsoft { namespace Mixer { namespace MixPlay { public ref class InputEventArgs sealed { public: InputEventArgs(); property Platform::String^ ControlId; property Platform::String^ ParticipantId; property bool IsDown; }; } } }
mscherotter/Microsoft.Mixer.MixPlay
Microsoft.Mixer/Group.h
#pragma once struct interactive_group; namespace Microsoft { namespace Mixer { namespace MixPlay { public ref class Group sealed { public: property Platform::String^ Id; property Platform::String^ SceneId; internal : Group(const interactive_group* pGroup); }; } } }
mscherotter/Microsoft.Mixer.MixPlay
Microsoft.Mixer/MoveEventArgs.h
#pragma once namespace Microsoft { namespace Mixer { namespace MixPlay { public ref class MoveEventArgs sealed { public: MoveEventArgs(float x, float y, Platform::String^ participantId); property float X; property float Y; property Platform::String^ ParticipantId; property Platform::String^ ControlId; }; } } }
mscherotter/Microsoft.Mixer.MixPlay
Microsoft.Mixer/StateChangedEventArgs.h
<filename>Microsoft.Mixer/StateChangedEventArgs.h #pragma once namespace Microsoft { namespace Mixer { namespace MixPlay { public enum class InteractiveState { interactive_disconnected, interactive_connecting, interactive_connected, interactive_ready }; public ref class StateChangedEventArgs sealed { public: StateChangedEventArgs(); property InteractiveState PreviousState; property InteractiveState NewState; }; } } }
mscherotter/Microsoft.Mixer.MixPlay
Microsoft.Mixer/Interactive.h
<filename>Microsoft.Mixer/Interactive.h<gh_stars>0 #pragma once struct InteractiveImpl; struct interactive_input; enum interactive_state; typedef void* interactive_session; namespace Microsoft { namespace Mixer { namespace MixPlay { ref class InputEventArgs; ref class LaunchEventArgs; ref class MoveEventArgs; ref class ErrorEventArgs; ref class StateChangedEventArgs; ref class CustomEventArgs; ref class Group; ref class Control; ref class ControlProperty; public delegate void InputHandler(Platform::Object^ sender, InputEventArgs^ args); public delegate void LaunchHandler(Platform::Object^ sender, LaunchEventArgs^ args); public delegate void MoveHandler(Platform::Object^ sender, MoveEventArgs^ args); public delegate void ErrorHandler(Platform::Object^ sender, ErrorEventArgs^ args); public delegate void StateChangedHandler(Platform::Object^ sender, StateChangedEventArgs^ args); public delegate void CustomEventHandler(Platform::Object^ sender, CustomEventArgs^ args); /// <summary>Mixer Interactive Component</summary> /// <remarks>This uses the Mixer C++ interactive SDK https://github.com/mixer/interactive-cpp </remarks> public ref class Interactive sealed { public: ///<summary>Initializes a new instance of the Interactive class</summary> Interactive(); ///<summary>Close the connection to Mixer</summary> virtual ~Interactive(); /// <summary>Gets a value indicating whether the connection to Mixer is open</summary> property bool IsRunning { bool get(); } /// <summary>Disconnects from Mixer.com</summary> void Disconnect(); /// <summary>Startup the interactive SDK and Connect to the Mixer platform</summary> /// <param name="clientId">the Mixer OAuth Client ID from https://mixer.com/lab/oauth</param> /// <param name="interactiveId">the Mixer MixPlay Version ID (found in the Code tab of the MixPlay editor)</param> /// <param name="shareCode">the Mixer MixPlay Share Code (found in the Publish tab of the MixPlay editor)</param> /// <returns>0 if the user authenticated with Mixer successfully, otherwise an error code from Mixer</returns> Windows::Foundation::IAsyncOperation<int>^ StartupAsync(Platform::String^ clientId, Platform::String^ interactiveId, Platform::String^ shareCode); /// <summary>Gets the user name for a participant Id</summary> /// <param name="participantId">the participant id</param> Platform::String^ GetUserName(Platform::String^ participantId); /// <summary>Create a participant group</summary> /// <param name="groupId">the group id</param> /// <param name="sceneId">the MixPlay scene id</param> void CreateGroup(Platform::String^ groupId, Platform::String^ sceneId); /// <summary>Sets the group Id for a participant </summary> /// <param name="groupId">the group id</param> /// <param name="sceneId">the participant id</param> void SetGroup(Platform::String^ groupId, Platform::String^ participantId); /// <summary>Gets the groups in the MixPlay</summary> Windows::Foundation::IAsyncOperation<Windows::Foundation::Collections::IVector<Group^>^>^ GetGroupsAsync(); /// <summary>Gets a control property</summary> /// <param name="controlId">the control id</param> /// <param name="propertyName">the property name</param> ControlProperty^ GetControlProperty(Platform::String^ controlId, Platform::String^ propertyName); /// <summary>Gets the properties for a specific control</summary> /// <param name="controlId">the control Id</param> Windows::Foundation::Collections::IVector<ControlProperty^>^ GetProperties(Platform::String^ controlId); /// <summary>Gets the control for a specific scene</summary> /// <param name="sceneId">the scene id</param> Windows::Foundation::Collections::IVector<Control^>^ GetControls(Platform::String^ sceneId); float GetMetaPropertyFloat(Platform::String^ controlId, Platform::String^ propertyName); /// <summary>Launch handler for the app to launch an URI in the UI thread</summary> /// <example> /// <code> /// Interactive.Launch += Interactive_Launch; /// ... /// private async void Interactive_Launch(object sender, LaunchEventArgs args) /// { /// await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async delegate /// { /// await Launcher.LaunchUriAsync(args.Uri); /// }); /// } /// </code> /// </example> event LaunchHandler^ Launch; /// <summary>Button input handler</summary> event InputHandler^ InputReceived; /// <summary>Joystick or mouse moved handler</summary> event MoveHandler^ Moved; /// <summary>Error handler</summary> event ErrorHandler^ Error; /// <summary>State changed handler</summary> event StateChangedHandler^ StateChanged; /// <summary>Custom input handler</summary> event CustomEventHandler^ CustomEventTriggered; private: static void OnInput(void* context, interactive_session session, const interactive_input* input); static void OnError(void* context, interactive_session session, int errorCode, const char* errorMessage, size_t errorMessageLength); static void OnTransactionComplete(void* context, interactive_session session, const char* transactionId, size_t transactionIdLength, unsigned int error, const char* errorMessage, size_t errorMessageLength); static void OnStateChanged(void *context, interactive_session session, interactive_state previousState, interactive_state newState); int Interactive::authorize(std::string& authorization, const char* shortCodeHandle); InteractiveImpl* _pImpl; }; } } }
mscherotter/Microsoft.Mixer.MixPlay
Microsoft.Mixer/Conversion.h
<gh_stars>0 #pragma once using namespace Platform; Platform::String^ ToPlatformString(const char* pString, size_t length); const std::string ToString(Platform::String^ pString); const std::string ToString(const std::wstring& string_to_convert); const std::wstring ToWString(const std::string& str);
mscherotter/Microsoft.Mixer.MixPlay
Microsoft.Mixer/LaunchEventArgs.h
<reponame>mscherotter/Microsoft.Mixer.MixPlay<filename>Microsoft.Mixer/LaunchEventArgs.h #pragma once namespace Microsoft { namespace Mixer { namespace MixPlay { public ref class LaunchEventArgs sealed { public: LaunchEventArgs(Windows::Foundation::Uri^ uri); property Windows::Foundation::Uri^ Uri; }; } } }
mscherotter/Microsoft.Mixer.MixPlay
Microsoft.Mixer/ErrorEventArgs.h
<reponame>mscherotter/Microsoft.Mixer.MixPlay<gh_stars>0 #pragma once namespace Microsoft { namespace Mixer { namespace MixPlay { public ref class ErrorEventArgs sealed { public: ErrorEventArgs(); property int Error; property Platform::String^ Message; }; } } }
mscherotter/Microsoft.Mixer.MixPlay
Microsoft.Mixer/Control.h
<reponame>mscherotter/Microsoft.Mixer.MixPlay #pragma once namespace Microsoft { namespace Mixer { namespace MixPlay { public ref class Control sealed { public: Control(); property Platform::String^ Kind; property Platform::String^ Id; }; } } }