repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
RogerNogue/MVJ_Engine_base
ModuleRender.h
<gh_stars>0 #ifndef __ModuleRender_H__ #define __ModuleRender_H__ #include "Module.h" #include "MathGeoLib.h" class ComponentMesh; class GameObject; struct SDL_Texture; struct SDL_Renderer; struct SDL_Rect; class ModuleRender : public Module { public: ModuleRender(); ~ModuleRender(); bool Init(); update_status PreUpdate() override; void Draw(); update_status PostUpdate()override; bool CleanUp(); void WindowResized(unsigned width, unsigned height); ComponentMesh createComponentMesh(GameObject* dad); void UpdateEditorCamera(); void setUpViewport(); //variables void* context = nullptr; unsigned editorCameraBuffer = 0; unsigned editorTexture = 0; unsigned int frameBuffer = 0; unsigned int renderTexture = 0; unsigned int depthBuffer = 0; unsigned gizmoTransf = 0; private: void RenderMeshes(); void RenderShapes(); void RenderWithNormals(); void RenderWithNoNormals(); void drawGizmo(); //variables float screenWidth = 0; float screenHeight = 0; float texWidth = 0; float texHeight = 0; }; #endif
RogerNogue/MVJ_Engine_base
ModuleScene.h
<filename>ModuleScene.h #ifndef __ModuleScene_H__ #define __ModuleScene_H__ #include "Module.h" #include <vector> #include "MathGeoLib.h" class GameObject; class QuadTreeGnoblin; class ModuleScene : public Module { public: ModuleScene(); ~ModuleScene(); bool Init()override; void createGameObject(const char* c); void setUpGameObjectMenu(); void addIntoQuadTree(GameObject* obj); //add a save and load function void saveScene(const char* name); void loadScene(const char* name); //mouse picking function void mouseClick(int mouseXi, int mouseYi); //variables GameObject* objectSelected = nullptr; GameObject* baseObject = nullptr; std::vector<GameObject*> allObjects; std::vector<GameObject*> allLights; QuadTreeGnoblin* quadTree; bool drawQuadTree = false; char* folderPath = "Scenes/"; math::LineSegment ray = LineSegment(float3(-100, -100, -100), float3(-100, -100, -100)); bool drawSegment = false; float sceneScale = 200; private: int sceneNum = 1; AABB sceneBoundingBox; void paintGameObjectTree(GameObject* go); GameObject* closestToCam(GameObject* go1, GameObject* go2); }; #endif
RogerNogue/MVJ_Engine_base
ModuleInput.h
<gh_stars>0 #ifndef __ModuleInput_H__ #define __ModuleInput_H__ #include "Module.h" typedef unsigned __int8 Uint8; class ModuleInput : public Module { public: ModuleInput(); ~ModuleInput(); bool Init() override; update_status PreUpdate() override; bool CleanUp() override; //vars int wheelScroll; const Uint8 *keyboard = nullptr; int x, y, xdiff, ydiff; bool cameraMoved; bool rightclickPressed; bool firstFrameRightClick; private: }; #endif
RogerNogue/MVJ_Engine_base
Serializer.h
<filename>Serializer.h #ifndef __Serializer_H__ #define __Serializer_H__ #include "rapidjson/rapidjson.h" #include "rapidjson/document.h" #include "rapidjson/prettywriter.h" #include "rapidjson/filewritestream.h" #include "rapidjson/filereadstream.h" #include "MathGeoLib.h" class GameObject; class ComponentMesh; class ComponentMaterial; class ComponentTransform; struct JSON_Value { public: JSON_Value(rapidjson::Document::AllocatorType* allocator) : allocator(allocator) { value = new rapidjson::Value(rapidjson::kObjectType); } ~JSON_Value(); //This will remove all added elements of the JSON_Value void convertToArray(); void addInt(const char* name, int value); void addUint(const char* name, unsigned int value); void addFloat(const char* name, float value); void addString(const char* name, const char* value); void addBool(const char* name, bool value); void addVector2(const char* name, float2 vec); void addVector3(const char* name, float3 vec); void addVector4(const char* name, float4 vec); void addQuat(const char* name, Quat quat); void addTransformMat(const char* name, float4x4 mat); void setUint(const char* name, unsigned int value); int getInt(const char* name); unsigned int getUint(const char* name); float getFloat(const char* name); char* getString(char* name); bool getBool(const char* name); float2 getVector2(const char* name); float3 getVector3(const char* name); float4 getVector4(const char* name); Quat getQuat(const char* name); float4x4 getTransform(const char* name); JSON_Value* createValue(); void addValue(const char* name, JSON_Value* value); JSON_Value* getValue(const char* name); JSON_Value* getValueFromArray(int index); void setValue(const char* name, JSON_Value* value); void setValue(rapidjson::Value* value); rapidjson::Value* getRapidJSONValue(); private: rapidjson::Value* value = nullptr; rapidjson::Document::AllocatorType* allocator = nullptr; std::vector<JSON_Value*> allocatedValues; }; struct JSON_File { public: JSON_File(rapidjson::FileWriteStream* os, FILE* fp); JSON_File(rapidjson::FileReadStream* is, FILE* fp); JSON_File(); ~JSON_File(); bool Write(); JSON_Value* createValue(); void addValue(const char* name, JSON_Value* value); JSON_Value* getValue(const char* name); void setValue(const char* name, JSON_Value* value); void closeFile(); private: FILE* fp = nullptr; rapidjson::Document* document = nullptr; rapidjson::FileWriteStream* writeStream = nullptr; rapidjson::FileReadStream* readStream = nullptr; rapidjson::Document::AllocatorType* allocator = nullptr; std::vector<JSON_Value*> allocatedValues; }; class Serializer { public: Serializer(); ~Serializer(); static JSON_File* openReadJSON(const char* path); static JSON_File* openWriteJSON(const char* path); private: }; #endif
RogerNogue/MVJ_Engine_base
ModuleMenu.h
#ifndef __ModuleMenu_h__ #define __ModuleMenu_h__ #include "Module.h" #include "imgui.h" class ModuleMenu : public Module { public: ModuleMenu(); ~ModuleMenu(); bool Init(); update_status PreUpdate() override; update_status Update() override; bool CleanUp() override; void DrawMenu(); void consoleLog(const char* str); struct ExampleAppLog { ImGuiTextBuffer Buf; bool ScrollToBottom; void Clear() { Buf.clear(); } void AddLog(const char* fmt, ...) //IM_PRINTFARGS(2) { va_list args; va_start(args, fmt); Buf.appendf(fmt, args); va_end(args); ScrollToBottom = true; } void Draw(const char* title, bool* p_opened = NULL) { ImGui::Begin(title, p_opened); ImGui::TextUnformatted(Buf.begin()); if (ScrollToBottom) ImGui::SetScrollHere(1.0f); ScrollToBottom = false; ImGui::End(); } }; //variables int frames; double lastFrameTime; double lastSecondTime; int logMSIterator; int logFPSIterator; float* fps_log = nullptr; float* ms_log = nullptr; ExampleAppLog console; float menubarWidth, menubarHeight; private: void updateFramerates(); //variables ImVec2 viewportSize; bool nameCopied = false; }; #endif /* __ModuleMenu_h__ */
RogerNogue/MVJ_Engine_base
ModuleCamera.h
#ifndef __ModuleCamera_H__ #define __ModuleCamera_H__ #include "Module.h" #include "MathGeoLib.h" class ComponentCamera; class GameObject; class ModuleCamera : public Module { public: ModuleCamera(); ~ModuleCamera(); bool Init() override; update_status Update() override; void camRotationX(float angle); void camRotationY(float angle); void updateCam(); void SetAspectRatio(float w, float h); void mewModelLoaded(); ComponentCamera createComponentCamera(GameObject* dad); //variables float aspectRatio; float screenWidth; float screenHeight; math::float4x4 camera; float movementSpeed; float mouseRotSpeed; math::float4x4 model; math::float4x4 view; math::float4x4 projection; Frustum frustum; float3 modelCenter; float modelWidth, modelHeight; bool cameraChanged; float znear = 1.0f; float zfar = 100.0f; private: //variables float distCamVrp; math::float3 vrp; }; #endif
RogerNogue/MVJ_Engine_base
Application.h
#ifndef __Application_H__ #define __Application_H__ #include<list> #include "Globals.h" #include "Module.h" class ModuleRender; class ModuleWindow; class ModuleTextures; class ModuleInput; class ModuleProgram; class ModuleMenu; class ModuleCamera; class ModuleModelLoader; class ModuleTimer; class ModuleScene; class ModuleDebugDraw; class Application { public: Application(); ~Application(); bool Init(); update_status Update(); bool CleanUp(); unsigned int generateID(); public: ModuleRender* renderer = nullptr; ModuleWindow* window = nullptr; ModuleTextures* textures = nullptr; ModuleInput* input = nullptr; ModuleProgram* shaderProgram = nullptr; ModuleMenu* menu = nullptr; ModuleCamera* camera = nullptr; ModuleModelLoader* modelLoader = nullptr; ModuleTimer* timer = nullptr; ModuleScene* scene = nullptr; ModuleDebugDraw* debugDraw = nullptr; private: std::list<Module*> modules; }; extern Application* App; #endif
RogerNogue/MVJ_Engine_base
Component.h
<reponame>RogerNogue/MVJ_Engine_base #ifndef __Component_H__ #define __Component_H__ #include "Globals.h" class GameObject; class Component { public: Component(GameObject* dad) { this->dad = dad; }; virtual bool Init() { return true; }; virtual bool CleanUp(){ return true; }; virtual update_status Update() { return UPDATE_CONTINUE; }; virtual void Enable() { active = true; }; virtual void Disable() { active = false; }; //variables unsigned int id; component_type type; GameObject* dad = nullptr; bool active; }; #endif
RogerNogue/MVJ_Engine_base
ComponentCamera.h
<gh_stars>0 #ifndef __ComponentCamera_H__ #define __ComponentCamera_H__ #include "Component.h" #include "MathGeoLib.h" //class for the cameras that are not the editor camera class JSON_Value; class ComponentCamera : public Component { public: ComponentCamera(GameObject* dad); ComponentCamera(JSON_Value* camFile, GameObject* dad); ~ComponentCamera(); bool Init() override; update_status Update() override; bool CleanUp() override; void camRotationX(float angle); void camRotationY(float angle); void updateCam(); void SetAspectRatio(float w, float h); void mewModelLoaded(); ComponentCamera createComponentCamera(GameObject* dad); void saveCamera(JSON_Value* val); //variables float aspectRatio; float screenWidth; float screenHeight; float distCamVrp; math::float3 vrp; math::float4x4 camera; float movementSpeed; float mouseRotSpeed; math::float4x4 model; math::float4x4 view; math::float4x4 projection; Frustum frustum; float3 modelCenter; float modelWidth, modelHeight; bool cameraChanged; }; #endif
RogerNogue/MVJ_Engine_base
Globals.h
#ifndef __Globals_H__ #define __Globals_H__ #include <windows.h> #include <stdio.h> #define LOG(format, ...) log(__FILE__, __LINE__, format, __VA_ARGS__); void log(const char file[], int line, const char* format, ...); enum update_status{ UPDATE_CONTINUE = 1, UPDATE_STOP, UPDATE_ERROR }; enum component_type{ CAMERA, MESH, MATERIAL, TRANSFORM, SHAPE, OBJECT }; enum shape_type { SPHERE, CUBE, TORUS, CYLINDER }; // Configuration ----------- #define SCREEN_WIDTH 1600 #define SCREEN_HEIGHT 1000 #define FULLSCREEN false #define BORDERLESS false #define RESIZABLE_WINDOW true #define VSYNC true #define TITLE "GNOBLIN" #define GLSL_VERSION "#version 330" #endif
RogerNogue/MVJ_Engine_base
GameObject.h
<gh_stars>0 #ifndef __ModuleGameObject_H__ #define __ModuleGameObject_H__ #include "Globals.h" #include "MathGeoLib/include/Geometry/AABB.h" #include <vector> class ComponentMesh; class ComponentMaterial; class ComponentCamera; class ComponentTransform; class ComponentShape; class QuadNode; class JSON_Value; class GameObject { public: GameObject(const char* n); GameObject(const char* n, GameObject* parent); GameObject(const char* n, GameObject* parent, bool physical); GameObject(const char* n, GameObject* parent, int signal, bool light); GameObject(JSON_Value* objValue); ~GameObject(); void CleanUp(); void deleteObject(); void deleteChild(unsigned idc); void calculateAABB(); void ChangeName(char* n); void activeToggled(); void staticToggled(bool first); void updateQuadTree(); void saveObject(JSON_Value* objValue); inline bool isPhysical() { return Physical; } inline bool IsLight() { return light; } void DrawProperties(); void DrawShapeEditor(); void LoadNextMaterial(); void DrawMaterialCreator(); //variables unsigned int id = 0u; unsigned int parentId = 0u; bool active = true; bool isStatic = true; bool paintBB = false; const char* name = nullptr; bool hascamera = false; bool hasmesh = false; bool hasmaterial = false; bool hasShape = false; ComponentMesh* mesh = nullptr; ComponentShape* shape = nullptr; std::vector<GameObject*> meshesOrShapes; ComponentCamera* camera = nullptr; std::vector<ComponentMaterial*> materials; ComponentTransform* transform = nullptr; std::vector<GameObject*> children; GameObject* parent = nullptr; float minX, maxX, minY, maxY, minZ, maxZ;//variables for the bounding box AABB boundingBox; std::vector<QuadNode*> nodesItAppears; private: //functions void toggleMeshActivation(); void DrawComboBoxMaterials(const char* id, ComponentMaterial mat, static std::string& currentTexture); //variables bool light = false; bool Physical = false; bool BBGenerated = false; }; #endif
RogerNogue/MVJ_Engine_base
ModuleTimer.h
#ifndef __ModuleTimer_H__ #define __ModuleTimer_H__ #include "Module.h" #include "SDL.h" class ModuleTimer : public Module { public: ModuleTimer(); ~ModuleTimer(); bool Init() override; update_status Update() override; double getRealTime(); double getRealHighPrecisionTime(); //variables float timeScale; unsigned frameCount; double initialTime; double realDeltaTime; double deltaTime; double lastFrameTime; //high precision variables double initialHighTime; static const double highFreq; private: }; #endif
RogerNogue/MVJ_Engine_base
ComponentShape.h
#ifndef __ComponentShape_H__ #define __ComponentShape_H__ #include "Component.h" class JSON_Value; class par_shapes_mesh; class ComponentShape : public Component { public: ComponentShape(GameObject* dad, shape_type type); ComponentShape(JSON_Value* shapeFile, GameObject* dad); ~ComponentShape(); bool CleanUp()override; void saveShape(JSON_Value* val); void drawEditorMenu(); //variables shape_type shapeType; int slices = 20; int stacks = 20; float size1 = 1; float size2 = 2; float size3 = 2; float ambient = 0.3f; unsigned vbo = 0; unsigned vio = 0; unsigned material = 0; unsigned numVertices = 0; unsigned numIndices = 0; unsigned texCoords_offset = 0; unsigned normals_offset = 0; private: void SphereEditor(); void CubeEditor(); void CylinderEditor(); void TorusEditor(); //variables par_shapes_mesh* mesh = nullptr; }; #endif
RogerNogue/MVJ_Engine_base
ModuleTextures.h
<filename>ModuleTextures.h #ifndef __ModuleTextures_H__ #define __ModuleTextures_H__ #include<list> #include "Module.h" class GameObject; class ComponentMaterial; struct SDL_Texture; class ModuleTextures : public Module { public: ModuleTextures(); ~ModuleTextures(); bool Init() override; unsigned Load(const char* path, bool mipmaps, float* width, float* height); void Unload(unsigned id); ComponentMaterial createComponentMaterial(GameObject* dad); unsigned createFrameBuffer(char* name, float width, float height); void deleteFrameBuffer(unsigned buffer); void CreateMaterial(std::string path, unsigned& textureID, int& width, int& height); private: }; #endif
RogerNogue/MVJ_Engine_base
QuadNode.h
<reponame>RogerNogue/MVJ_Engine_base #ifndef __QuadNode_H__ #define __QuadNode_H__ #include "MathGeoLib.h" #include <vector> class GameObject; class QuadNode { public: QuadNode(AABB section, QuadNode* parent, int num); QuadNode(AABB section); ~QuadNode(); void addNode(GameObject* node); void deleteObject(GameObject* obj); void getIntersections(std::vector<GameObject*>& objects); void drawTree(); void CleanUp(); void deletechild1(); void deletechild2(); void deletechild3(); void deletechild4(); //variables bool rootNode = false; AABB area; QuadNode* parent = nullptr; //north west child QuadNode* child1 = nullptr; //north east child QuadNode* child2 = nullptr; //south east child QuadNode* child3 = nullptr; //south west child QuadNode* child4 = nullptr; int treeDepth; int maxDepth = 50; int maxObjectsPerNode = 2; std::vector <GameObject*> belongings; private: int childNumber = 0; //to see if its child 1, 2, 3 or 4 }; #endif
MSIhub/Vive_SpatialTrackingStudy
03_DataCollectionAPI/ClientParallel/ClientParallel/src/main.h
#ifndef MAIN_H_ #define MAIN_H_ #pragma once #include <iostream> #include <fstream> #include <string> #include <WS2tcpip.h> #include <iomanip> #include <intrin.h> #include <exception> #include <chrono> #include <Windows.h> #include <stdio.h> #include <cstdint> #include <thread> #pragma comment(lib, "ws2_32.lib") #define DEFAULT_BUFLEN 4096 #define FLOAT_PRECISION 8 #define DELIMITER "," #define IP_COMAU "172.22.121.2" // ipAddress of Comau to listen to #define PORT_COMAU 98765 // Port to listen #define IP_VIVE #define PORT_Vive struct data_packet_vive { uint64_t timestamp; double transform00; double transform01; double transform02; double transform03; double transform10; double transform11; double transform12; double transform13; double transform20; double transform21; double transform22; double transform23; int id; // member initialisation list/constructur data_packet_vive() { timestamp = 0; transform00 = 0.0; transform01 = 0.0; transform02 = 0.0; transform03 = 0.0; transform10 = 0.0; transform11 = 0.0; transform12 = 0.0; transform13 = 0.0; transform20 = 0.0; transform21 = 0.0; transform22 = 0.0; transform23 = 0.0; id = 0; } ~data_packet_vive() {} }; struct data_packet_comau { int timestamp; float cp1; float cp2; float cp3; float cp4; float cp5; float cp6; float vel; // member init data_packet_comau() { timestamp = 0; cp1 = 0.0; cp2 = 0.0; cp3 = 0.0; cp4 = 0.0; cp5 = 0.0; cp6 = 0.0; vel = 0.0; } ~data_packet_comau() {} }; uint64_t GetCurrentTimeNs(); void tcpClient_Comau(); void tcpClient_Vive(); bool isDataValid(data_packet_vive dd); bool isDataValidComau(data_packet_comau dd); #endif // !MAIN_H_
MSIhub/Vive_SpatialTrackingStudy
02_VLTSandC16ServerSetup/OpenVRServer/ViveTrack/main.h
#pragma once #undef UNICODE #define WIN32_LEAN_AND_MEAN #define FLOAT_PRECISION 8 #define DEFAULT_DELAYSECS 8 // 120Hz sampling , time in milliseconds #include <iostream> #include <fstream> #include <stdio.h> #include <stdlib.h> #include "LighthouseTracking.h" #include "cpTime.h" #include <cstring> #include <strings.h> #include <chrono> #include <inttypes.h> #include <unistd.h> #include <csignal> #include <exception> #include <string> void openFiles(); uint64_t GetCurrentTimeNs(); void signalHandler( int signum);
MSIhub/Vive_SpatialTrackingStudy
02_VLTSandC16ServerSetup/OpenVRServer/ViveTrack/TcpServer.h
<reponame>MSIhub/Vive_SpatialTrackingStudy<filename>02_VLTSandC16ServerSetup/OpenVRServer/ViveTrack/TcpServer.h #ifndef TCPSERVER_H_ #define TCPSERVER_H_ #pragma once #undef UNICODE #include <iostream> #include <WS2tcpip.h> #include <windows.h> #include <iomanip> #include <intrin.h> #define WIN32_LEAN_AND_MEAN #define DEFAULT_BUFLEN 4096 #define DEFAULT_PORT "54000" struct data_packet { uint64_t timestamp; double transform00; double transform01; double transform02; double transform03; double transform10; double transform11; double transform12; double transform13; double transform20; double transform21; double transform22; double transform23; int id; // HMD=1, CONT = 2, TRACK = 3 // member initialisation list/constructur data_packet() { timestamp = 0; transform00 = 0.0; transform01 = 0.0; transform02 = 0.0; transform03 = 0.0; transform10 = 0.0; transform11 = 0.0; transform12 = 0.0; transform13 = 0.0; transform20 = 0.0; transform21 = 0.0; transform22 = 0.0; transform23 = 0.0; id = 0; } ~data_packet() {} }; // Server Socket void tcpipServerSetupTest(); SOCKET startServerConn(); void endServerConn(SOCKET ClientSocket); void sendDataServer(SOCKET ClientSocket, data_packet td); #endif
arpnetwork/libarpcap
include/ScreenCapture.h
<gh_stars>1-10 /* * Copyright 2018 ARP Network * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef ARP_SCREEN_CAPTURE_H_ #define ARP_SCREEN_CAPTURE_H_ #include <stdint.h> #ifdef __cplusplus extern "C" { #endif enum { // // these constants need to match those // in graphics/PixelFormat.java & pixelflinger/format.h // PIXEL_FORMAT_UNKNOWN = 0, PIXEL_FORMAT_NONE = 0, // logical pixel formats used by the SurfaceFlinger ----------------------- PIXEL_FORMAT_CUSTOM = -4, // Custom pixel-format described by a PixelFormatInfo structure PIXEL_FORMAT_TRANSLUCENT = -3, // System chooses a format that supports translucency (many alpha bits) PIXEL_FORMAT_TRANSPARENT = -2, // System chooses a format that supports transparency // (at least 1 alpha bit) PIXEL_FORMAT_OPAQUE = -1, // System chooses an opaque format (no alpha bits required) // real pixel formats supported for rendering ----------------------------- PIXEL_FORMAT_RGBA_8888 = 1, // 4x8-bit RGBA PIXEL_FORMAT_RGBX_8888 = 2, // 4x8-bit RGB0 PIXEL_FORMAT_RGB_888 = 3, // 3x8-bit RGB PIXEL_FORMAT_RGB_565 = 4, // 16-bit RGB PIXEL_FORMAT_BGRA_8888 = 5, // 4x8-bit BGRA PIXEL_FORMAT_RGBA_5551 = 6, // 16-bit ARGB PIXEL_FORMAT_RGBA_4444 = 7, // 16-bit ARGB PIXEL_FORMAT_RGBA_FP16 = 22, // 64-bit RGBA PIXEL_FORMAT_RGBA_1010102 = 43, // 32-bit RGB }; /* Display orientations as defined in Surface.java and ISurfaceComposer.h. */ enum { DISPLAY_ORIENTATION_0 = 0, DISPLAY_ORIENTATION_90 = 1, DISPLAY_ORIENTATION_180 = 2, DISPLAY_ORIENTATION_270 = 3 }; typedef struct ARPDisplayInfo { uint32_t width{0}; uint32_t height{0}; uint8_t orientation{0}; } ARPDisplayInfo; typedef struct displayinfo { uint32_t width{0}; uint32_t height{0}; uint8_t orientation{0}; } displayinfo; typedef struct ARPFrameBuffer { uint8_t *data; uint32_t width; uint32_t height; int32_t format; uint32_t stride; int64_t timestamp; uint64_t frame_number; } ARPFrameBuffer; typedef void (*arp_callback)(uint64_t frame_number, int64_t timestamp); void arpcap_init(); void arpcap_fini(); int arpcap_get_display_info(ARPDisplayInfo *info); int arpcap_create( uint32_t paddingTop, uint32_t paddingBottom, uint32_t width, uint32_t height, arp_callback cb); void arpcap_destroy(); int arpcap_acquire_frame_buffer(ARPFrameBuffer *fb); void arpcap_release_frame_buffer(); #ifdef __cplusplus } #endif #endif // ARP_SCREEN_CAPTURE_H_
suesai/muduo
contrib/thrift/ThriftServer.h
#ifndef MUDUO_CONTRIB_THRIFT_THRIFTSERVER_H #define MUDUO_CONTRIB_THRIFT_THRIFTSERVER_H #include <map> #include <boost/bind.hpp> #include <boost/noncopyable.hpp> #include "muduo/base/ThreadPool.h" #include "muduo/net/TcpServer.h" #include <thrift/server/TServer.h> #include "contrib/thrift/ThriftConnection.h" using apache::thrift::TProcessor; using apache::thrift::TProcessorFactory; using apache::thrift::protocol::TProtocolFactory; using apache::thrift::server::TServer; using apache::thrift::transport::TTransportFactory; class ThriftServer : boost::noncopyable, public TServer { public: template <typename ProcessorFactory> ThriftServer(const boost::shared_ptr<ProcessorFactory>& processorFactory, muduo::net::EventLoop* eventloop, const muduo::net::InetAddress& addr, const muduo::string& name, THRIFT_OVERLOAD_IF(ProcessorFactory, TProcessorFactory)) : TServer(processorFactory), server_(eventloop, addr, name), numWorkerThreads_(0), workerThreadPool_(name + muduo::string("WorkerThreadPool")) { server_.setConnectionCallback(boost::bind(&ThriftServer::onConnection, this, _1)); } template <typename Processor> ThriftServer(const boost::shared_ptr<Processor>& processor, muduo::net::EventLoop* eventloop, const muduo::net::InetAddress& addr, const muduo::string& name, THRIFT_OVERLOAD_IF(Processor, TProcessor)) : TServer(processor), server_(eventloop, addr, name), numWorkerThreads_(0), workerThreadPool_(name + muduo::string("WorkerThreadPool")) { server_.setConnectionCallback(boost::bind(&ThriftServer::onConnection, this, _1)); } template <typename ProcessorFactory> ThriftServer(const boost::shared_ptr<ProcessorFactory>& processorFactory, const boost::shared_ptr<TProtocolFactory>& protocolFactory, muduo::net::EventLoop* eventloop, const muduo::net::InetAddress& addr, const muduo::string& name, THRIFT_OVERLOAD_IF(ProcessorFactory, TProcessorFactory)) : TServer(processorFactory), server_(eventloop, addr, name), numWorkerThreads_(0), workerThreadPool_(name + muduo::string("WorkerThreadPool")) { server_.setConnectionCallback(boost::bind(&ThriftServer::onConnection, this, _1)); setInputProtocolFactory(protocolFactory); setOutputProtocolFactory(protocolFactory); } template <typename Processor> ThriftServer(const boost::shared_ptr<Processor>& processor, const boost::shared_ptr<TProtocolFactory>& protocolFactory, muduo::net::EventLoop* eventloop, const muduo::net::InetAddress& addr, const muduo::string& name, THRIFT_OVERLOAD_IF(Processor, TProcessor)) : TServer(processor), server_(eventloop, addr, name), numWorkerThreads_(0), workerThreadPool_(name + muduo::string("WorkerThreadPool")) { server_.setConnectionCallback(boost::bind(&ThriftServer::onConnection, this, _1)); setInputProtocolFactory(protocolFactory); setOutputProtocolFactory(protocolFactory); } template <typename ProcessorFactory> ThriftServer(const boost::shared_ptr<ProcessorFactory>& processorFactory, const boost::shared_ptr<TTransportFactory>& transportFactory, const boost::shared_ptr<TProtocolFactory>& protocolFactory, muduo::net::EventLoop* eventloop, const muduo::net::InetAddress& addr, const muduo::string& name, THRIFT_OVERLOAD_IF(ProcessorFactory, TProcessorFactory)) : TServer(processorFactory), server_(eventloop, addr, name), numWorkerThreads_(0), workerThreadPool_(name + muduo::string("WorkerThreadPool")) { server_.setConnectionCallback(boost::bind(&ThriftServer::onConnection, this, _1)); setInputTransportFactory(transportFactory); setOutputTransportFactory(transportFactory); setInputProtocolFactory(protocolFactory); setOutputProtocolFactory(protocolFactory); } template <typename Processor> ThriftServer(const boost::shared_ptr<Processor>& processor, const boost::shared_ptr<TTransportFactory>& transportFactory, const boost::shared_ptr<TProtocolFactory>& protocolFactory, muduo::net::EventLoop* eventloop, const muduo::net::InetAddress& addr, const muduo::string& name, THRIFT_OVERLOAD_IF(Processor, TProcessor)) : TServer(processor), server_(eventloop, addr, name), numWorkerThreads_(0), workerThreadPool_(name + muduo::string("WorkerThreadPool")) { server_.setConnectionCallback(boost::bind(&ThriftServer::onConnection, this, _1)); setInputTransportFactory(transportFactory); setOutputTransportFactory(transportFactory); setInputProtocolFactory(protocolFactory); setOutputProtocolFactory(protocolFactory); } template <typename ProcessorFactory> ThriftServer(const boost::shared_ptr<ProcessorFactory>& processorFactory, const boost::shared_ptr<TTransportFactory>& inputTransportFactory, const boost::shared_ptr<TTransportFactory>& outputTransportFactory, const boost::shared_ptr<TProtocolFactory>& inputProtocolFactory, const boost::shared_ptr<TProtocolFactory>& outputProtocolFactory, muduo::net::EventLoop* eventloop, const muduo::net::InetAddress& addr, const muduo::string& name, THRIFT_OVERLOAD_IF(ProcessorFactory, TProcessorFactory)) : TServer(processorFactory), server_(eventloop, addr, name), numWorkerThreads_(0), workerThreadPool_(name + muduo::string("WorkerThreadPool")) { server_.setConnectionCallback(boost::bind(&ThriftServer::onConnection, this, _1)); setInputTransportFactory(inputTransportFactory); setOutputTransportFactory(outputTransportFactory); setInputProtocolFactory(inputProtocolFactory); setOutputProtocolFactory(outputProtocolFactory); } template <typename Processor> ThriftServer(const boost::shared_ptr<Processor>& processor, const boost::shared_ptr<TTransportFactory>& inputTransportFactory, const boost::shared_ptr<TTransportFactory>& outputTransportFactory, const boost::shared_ptr<TProtocolFactory>& inputProtocolFactory, const boost::shared_ptr<TProtocolFactory>& outputProtocolFactory, muduo::net::EventLoop* eventloop, const muduo::net::InetAddress& addr, const muduo::string& name, THRIFT_OVERLOAD_IF(Processor, TProcessor)) : TServer(processor), server_(eventloop, addr, name), numWorkerThreads_(0), workerThreadPool_(name + muduo::string("WorkerThreadPool")) { server_.setConnectionCallback(boost::bind(&ThriftServer::onConnection, this, _1)); setInputTransportFactory(inputTransportFactory); setOutputTransportFactory(outputTransportFactory); setInputProtocolFactory(inputProtocolFactory); setOutputProtocolFactory(outputProtocolFactory); } virtual ~ThriftServer(); void serve(); void start(); void stop(); muduo::ThreadPool& workerThreadPool() { return workerThreadPool_; } bool isWorkerThreadPoolProcessing() const { return numWorkerThreads_ != 0; } void setThreadNum(int numThreads) { server_.setThreadNum(numThreads); } void setWorkerThreadNum(int numWorkerThreads) { assert(numWorkerThreads > 0); numWorkerThreads_ = numWorkerThreads; } private: friend class ThriftConnection; void onConnection(const muduo::net::TcpConnectionPtr& conn); private: muduo::net::TcpServer server_; int numWorkerThreads_; muduo::ThreadPool workerThreadPool_; muduo::MutexLock mutex_; std::map<muduo::string, ThriftConnectionPtr> conns_; }; #endif // MUDUO_CONTRIB_THRIFT_THRIFTSERVER_H
peejster/stream_monitor
simplesample_http.c
<reponame>peejster/stream_monitor // Copyright (c) Microsoft. All rights reserved. // Licesendnsed under the MIT license. See LICENSE file in the project root for full license information. #include <stdlib.h> #include <stdio.h> #include <stdint.h> #include <pgmspace.h> /* This sample uses the _LL APIs of iothub_client for example purposes. That does not mean that HTTP only works with the _LL APIs. Simply changing the using the convenience layer (functions not having _LL) and removing calls to _DoWork will yield the same results. */ #include "AzureIoT.h" static const char* connectionString = "HostName=<your IoT Hub>.azure-devices.net;DeviceId=<your device id>;SharedAccessKey=<your access key>"; // switch to determine whether or not to send air temp data to cloud bool sendAirTemp = true; // switch to determine whether or not device info has been sent bool deviceInfoSent = false; // Define the Model BEGIN_NAMESPACE(StreamStation); DECLARE_STRUCT(DeviceProperties, ascii_char_ptr, DeviceID, _Bool, HubEnabledState, ascii_char_ptr, DeviceState, ascii_char_ptr, Manufacturer, ascii_char_ptr, ModelNumber, ascii_char_ptr, FirmwareVersion, int, Latitude, int, Longitude ); DECLARE_MODEL(WaterSensor, // Event data sent by the device WITH_DATA(ascii_char_ptr, DeviceId), WITH_DATA(int, WaterTemp), WITH_DATA(int, AirTemp), WITH_DATA(ascii_char_ptr, TimeStamp), // Info about the device WITH_DATA(ascii_char_ptr, ObjectType), WITH_DATA(_Bool, IsSimulatedDevice), WITH_DATA(ascii_char_ptr, Version), WITH_DATA(DeviceProperties, DeviceProperties), WITH_DATA(ascii_char_ptr_no_quotes, Commands), // Commands supported by the device WITH_ACTION(TurnOnAir), WITH_ACTION(TurnOffAir) ); END_NAMESPACE(StreamStation); DEFINE_ENUM_STRINGS(IOTHUB_CLIENT_CONFIRMATION_RESULT, IOTHUB_CLIENT_CONFIRMATION_RESULT_VALUES) EXECUTE_COMMAND_RESULT TurnOnAir(WaterSensor* device) { (void)device; sendAirTemp = true; LogInfo("Turning air temp readings on.\r\n"); return EXECUTE_COMMAND_SUCCESS; } EXECUTE_COMMAND_RESULT TurnOffAir(WaterSensor* device) { (void)device; sendAirTemp = false; LogInfo("Turning air temp readings off.\r\n"); return EXECUTE_COMMAND_SUCCESS; } // callback function which is invoked when message is sent void sendCallback(IOTHUB_CLIENT_CONFIRMATION_RESULT result, void* userContextCallback) { int messageTrackingId = (intptr_t)userContextCallback; LogInfo("Message Id: %d Received.\r\n", messageTrackingId); LogInfo("Result Call Back Called! Result is: %s \r\n", ENUM_TO_STRING(IOTHUB_CLIENT_CONFIRMATION_RESULT, result)); } /*this function "links" IoTHub to the serialization library*/ static IOTHUBMESSAGE_DISPOSITION_RESULT IoTHubMessage(IOTHUB_MESSAGE_HANDLE message, void* userContextCallback) { IOTHUBMESSAGE_DISPOSITION_RESULT result; const unsigned char* buffer; size_t size; if (IoTHubMessage_GetByteArray(message, &buffer, &size) != IOTHUB_MESSAGE_OK) { LogInfo("unable to IoTHubMessage_GetByteArray\r\n"); result = EXECUTE_COMMAND_ERROR; } else { /*buffer is not zero terminated*/ char* temp = malloc(size + 1); if (temp == NULL) { LogInfo("failed to malloc\r\n"); result = EXECUTE_COMMAND_ERROR; } else { memcpy(temp, buffer, size); temp[size] = '\0'; EXECUTE_COMMAND_RESULT executeCommandResult = EXECUTE_COMMAND(userContextCallback, temp); result = (executeCommandResult == EXECUTE_COMMAND_ERROR) ? IOTHUBMESSAGE_ABANDONED : (executeCommandResult == EXECUTE_COMMAND_SUCCESS) ? IOTHUBMESSAGE_ACCEPTED : IOTHUBMESSAGE_REJECTED; free(temp); } } return result; } void simplesample_http_run(int air, int water, char* sampleTime) { // initialize the serializer if (serializer_init(NULL) != SERIALIZER_OK) { LogInfo("Failed on serializer_init\r\n"); } else { // allocate an IoT Hub client handle // using the device connection string // designate protocol - i.e. http IOTHUB_CLIENT_LL_HANDLE iotHubClientHandle = IoTHubClient_LL_CreateFromConnectionString(connectionString, HTTP_Protocol); if (iotHubClientHandle == NULL) { LogInfo("Failed on IoTHubClient_LL_Create\r\n"); } else { WaterSensor* myStream = CREATE_MODEL_INSTANCE(StreamStation, WaterSensor); if (myStream == NULL) { LogInfo("Failed on CREATE_MODEL_INSTANCE\r\n"); } else { //STRING_HANDLE commandsMetadata; // register the message callback funtion for receiving messages if (IoTHubClient_LL_SetMessageCallback(iotHubClientHandle, IoTHubMessage, myStream) != IOTHUB_CLIENT_OK) { LogInfo("unable to IoTHubClient_SetMessageCallback\r\n"); } else { // send the device info once so that the cloud app knows // what commands are available and the fact that the device is up if (!deviceInfoSent) { // define the device info data myStream->ObjectType = "DeviceInfo"; myStream->IsSimulatedDevice = false; myStream->Version = "1.0"; myStream->DeviceProperties.HubEnabledState = true; myStream->DeviceProperties.DeviceID = "lyons_creek_1"; myStream->DeviceProperties.DeviceState = "normal"; myStream->DeviceProperties.Manufacturer = "SparkFun"; myStream->DeviceProperties.ModelNumber = "Thing Dev"; myStream->DeviceProperties.FirmwareVersion = "2.1.1"; myStream->DeviceProperties.Latitude = 0; myStream->DeviceProperties.Longitude = 0; unsigned char* destination; size_t destinationSize; if (SERIALIZE(&destination, &destinationSize, myStream->ObjectType, myStream->Version, myStream->IsSimulatedDevice, myStream->DeviceProperties) != IOT_AGENT_OK) { LogInfo("Failed to serialize\r\n"); } else { // create the message IOTHUB_MESSAGE_HANDLE messageHandle = IoTHubMessage_CreateFromByteArray(destination, destinationSize); if (messageHandle == NULL) { LogInfo("unable to create a new IoTHubMessage\r\n"); } else { // send the message if (IoTHubClient_LL_SendEventAsync(iotHubClientHandle, messageHandle, sendCallback, (void*)1) != IOTHUB_CLIENT_OK) { LogInfo("failed to hand over the message to IoTHubClient\r\n"); } else { LogInfo("IoTHubClient accepted the message for delivery\r\n"); deviceInfoSent = true; } IoTHubMessage_Destroy(messageHandle); } free(destination); } } // define the event data of the message myStream->DeviceId = "lyons_creek_1"; myStream->AirTemp = air; myStream->WaterTemp = water; myStream->TimeStamp = sampleTime; { //serialize the data unsigned char* destination; size_t destinationSize; IOT_AGENT_RESULT serializeStatus; // check if device should send air temp if (sendAirTemp) { // include air temp in the message serializeStatus = SERIALIZE(&destination, &destinationSize, myStream->DeviceId, myStream->AirTemp, myStream->WaterTemp, myStream-> TimeStamp); } else { // do not include air temp in the message serializeStatus = SERIALIZE(&destination, &destinationSize, myStream->DeviceId, myStream->WaterTemp, myStream-> TimeStamp); } if (serializeStatus != IOT_AGENT_OK) { LogInfo("Failed to serialize\r\n"); } else { // create the message IOTHUB_MESSAGE_HANDLE messageHandle = IoTHubMessage_CreateFromByteArray(destination, destinationSize); if (messageHandle == NULL) { LogInfo("unable to create a new IoTHubMessage\r\n"); } else { // send the message if (IoTHubClient_LL_SendEventAsync(iotHubClientHandle, messageHandle, sendCallback, (void*)1) != IOTHUB_CLIENT_OK) { LogInfo("failed to hand over the message to IoTHubClient\r\n"); } else { LogInfo("IoTHubClient accepted the message for delivery\r\n"); } IoTHubMessage_Destroy(messageHandle); } free(destination); } } IOTHUB_CLIENT_STATUS status; // send all events in the buffer // and get incoming messages while ((IoTHubClient_LL_GetSendStatus(iotHubClientHandle, &status) == IOTHUB_CLIENT_OK) && (status == IOTHUB_CLIENT_SEND_STATUS_BUSY)) { IoTHubClient_LL_DoWork(iotHubClientHandle); ThreadAPI_Sleep(1000); } /* wait for commands while (1) { IoTHubClient_LL_DoWork(iotHubClientHandle); ThreadAPI_Sleep(100); }*/ } // clear the model DESTROY_MODEL_INSTANCE(myStream); } // uninitialize the IoT Hub client handle IoTHubClient_LL_Destroy(iotHubClientHandle); } // uninitialize the serializer serializer_deinit(); } }
danielgindi/FileDir
FileDirController.h
// // FileDirController.h // FileDir // // Created by <NAME> on 6/24/14. // Copyright (c) 2013 <NAME>. All rights reserved. // // https://github.com/danielgindi/FileDir // // The MIT License (MIT) // // Copyright (c) 2014 <NAME> (<EMAIL>) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // #pragma once #include "FileDir.h" #ifdef _WIN32 #define WIN32_LEAN_AND_MEAN #include <windows.h> #else #include <dirent.h> #endif #include <list> class FileDirController { public: FileDirController(void); virtual ~FileDirController(void); #ifdef _WIN32 /* Wide char */ bool EnumerateFilesAtPath(const wchar_t *path, bool recursive = false); #else /* UTF8 */ bool EnumerateFilesAtPath(const char *path, bool recursive = false); #endif FileDir * NextFile(); #ifdef _WIN32 /* Wide char */ static FileDir * GetFileInfo(const wchar_t *path); #else /* UTF8 */ static FileDir * GetFileInfo(const char *path); #endif void Close(); inline bool HasNext() { return !_searchTree.empty(); } private: bool _isRecursive; std::list<void *> _searchTree; };
danielgindi/FileDir
FileDir.h
<filename>FileDir.h // // FileDir.h // FileDir // // Created by <NAME> on 6/24/14. // Copyright (c) 2013 <NAME>. All rights reserved. // // https://github.com/danielgindi/FileDir // // The MIT License (MIT) // // Copyright (c) 2014 <NAME> (<EMAIL>) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // #pragma once #include <ctime> class FileDir { friend class FileDirController; public: FileDir(void); virtual ~FileDir(void); // Returns the full path including drive letter, base path, and file/folder name #ifdef _WIN32 /* Wide char */ inline const wchar_t * GetFullPath() { return _fullPath; } #else inline const char * GetFullPath() { return _fullPath; } #endif // Sets the full path including drive letter, base path, and file/folder name #ifdef _WIN32 /* Wide char */ void SetFullPath(const wchar_t *fullPath); #else void SetFullPath(const char *fullPath); #endif // Returns the file name including extension, without base path #ifdef _WIN32 /* Wide char */ inline const wchar_t * GetFileName() { return _fileName; } #else inline const char * GetFileName() { return _fileName; } #endif // Returns the extension without the period #ifdef _WIN32 /* Wide char */ const wchar_t * GetExtension(); #else const char * GetExtension(); #endif // Returns the file name without the extension #ifdef _WIN32 /* Wide char */ const wchar_t * GetFileNameWithoutExtension(); #else const char * GetFileNameWithoutExtension(); #endif // Returns the path without the filename #ifdef _WIN32 /* Wide char */ const wchar_t * GetBasePath(); #else const char * GetBasePath(); #endif // Is this a folder? inline bool IsFolder() { return _isFolder; } // Is this a file? inline bool IsFile() { return _isFile; } // Get the last modified time time_t GetLastModified(); // Get the creation time time_t GetCreationTime(); // Get the last access time time_t GetLastAccessTime(); // Get the last status change time time_t GetLastStatusChangeTime(); private: #ifdef _WIN32 /* Wide char */ wchar_t *_fullPath; wchar_t *_fileName; #else /* UTF8 */ char *_fullPath; char *_fileName; #endif bool _isFolder; bool _isFile; bool _hasTimes; time_t _creationTime; time_t _lastModificationTime; time_t _lastAccessTime; time_t _lastStatusChangeTime; #ifdef _WIN32 /* Wide char */ wchar_t *_cachedExtension; wchar_t *_cachedFileNameWithoutExtension; wchar_t *_cachedBasePath; #else /* UTF8 */ char *_cachedExtension; char *_cachedFileNameWithoutExtension; char *_cachedBasePath; #endif };
mark7/libsdl_extras_interposer
libsdl_extras.c
<gh_stars>1-10 // Released into the public domain by <NAME> <<EMAIL>> #ifndef _GNU_SOURCE #define _GNU_SOURCE #endif #include <SDL.h> #include <dlfcn.h> #include <stdbool.h> #include <stdlib.h> static bool g_enable_fullscreen_toggle; static bool g_enable_ungrab = true; static bool g_enable_hdb_colorkey_fix; static bool g_have_settings; static void __attribute__ ((constructor)) startup_constructor() { char *str; if (!g_have_settings) { str = getenv("SDL_FS_TOGGLE"); if (str && strcmp("0", str)) { g_enable_fullscreen_toggle = true; } str = getenv("SDL_FS_TOGGLE_NO_UNGRAB"); if (str && strcmp("1", str)) { g_enable_ungrab = false; } str = getenv("SDL_HDB_COLORKEY_FIX"); if (str && strcmp("0", str)) { g_enable_hdb_colorkey_fix = true; } g_have_settings = true; } } static void handle_key_event(SDL_Event *event) { SDL_Surface *surface; bool becoming_fullscreen; bool toggle_fullscreen; if (!event) return; toggle_fullscreen = (event->type == SDL_KEYDOWN) && (event->key.keysym.sym == SDLK_RETURN) && (event->key.keysym.mod & KMOD_ALT); if (toggle_fullscreen) { if (g_enable_fullscreen_toggle) { SDL_WM_ToggleFullScreen(SDL_GetVideoSurface()); if (g_enable_ungrab) { surface = SDL_GetVideoSurface(); becoming_fullscreen = !!(surface->flags & SDL_FULLSCREEN); if (becoming_fullscreen) { SDL_WM_GrabInput(SDL_GRAB_ON); } else { SDL_WM_GrabInput(SDL_GRAB_OFF); } } } } } int SDL_WaitEvent(SDL_Event *event) { int result; static int (*func)(SDL_Event *event); if (!func) func = dlsym(RTLD_NEXT, "SDL_WaitEvent"); result = func(event); if (result) { handle_key_event(event); } return (result); } int SDL_SetColorKey(SDL_Surface *surface, Uint32 flag, Uint32 key) { static int (*func)(SDL_Surface *, Uint32, Uint32); if (!func) func = dlsym(RTLD_NEXT, "SDL_SetColorKey"); if (g_enable_hdb_colorkey_fix) { if (key == 0xff00ff) key = 0xf800f8; } return func(surface, flag, key); } int SDL_PollEvent(SDL_Event *event) { int result; static int (*func)(SDL_Event *event); if (!func) func = dlsym(RTLD_NEXT, "SDL_PollEvent"); result = func(event); if (result) { handle_key_event(event); } return (result); }
Yukikamome316/MCSE
msscmp/test.c
<gh_stars>1-10 #include <stdio.h> #include <wchar.h> #include "msscmp.hpp" int main(int argc, char const *argv[]) { loadMsscmp(L"/home/syoch/work/wiiu/msscmp/vita.msscmp"); // extractLoadedMsscmp(); return 0; }
kingosticks/spotify-mitm-proxy
pyshn/shn.c
<gh_stars>10-100 /* $Id: shn.c 182 2009-03-12 08:21:53Z zagor $ */ /* Shannon: Shannon stream cipher and MAC -- reference implementation */ /* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE AND AGAINST INFRINGEMENT ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* interface */ #include <stdlib.h> #include <string.h> #include "shn.h" /* * FOLD is how many register cycles need to be performed after combining the * last byte of key and non-linear feedback, before every byte depends on every * byte of the key. This depends on the feedback and nonlinear functions, and * on where they are combined into the register. Making it same as the * register length is a safe and conservative choice. */ #define FOLD N /* how many iterations of folding to do */ #define INITKONST 0x6996c53a /* value of KONST to use during key loading */ #define KEYP 13 /* where to insert key/MAC/counter words */ /* some useful macros -- machine independent little-endian */ #define Byte(x,i) ((UCHAR)(((x) >> (8*(i))) & 0xFF)) #define BYTE2WORD(b) ( \ (((WORD)(b)[3] & 0xFF)<<24) | \ (((WORD)(b)[2] & 0xFF)<<16) | \ (((WORD)(b)[1] & 0xFF)<<8) | \ (((WORD)(b)[0] & 0xFF)) \ ) #define WORD2BYTE(w, b) { \ (b)[3] = Byte(w,3); \ (b)[2] = Byte(w,2); \ (b)[1] = Byte(w,1); \ (b)[0] = Byte(w,0); \ } #define XORWORD(w, b) { \ (b)[3] ^= Byte(w,3); \ (b)[2] ^= Byte(w,2); \ (b)[1] ^= Byte(w,1); \ (b)[0] ^= Byte(w,0); \ } /* Nonlinear transform (sbox) of a word. * There are two slightly different combinations. */ static WORD sbox1 (WORD w) { w ^= ROTL (w, 5) | ROTL (w, 7); w ^= ROTL (w, 19) | ROTL (w, 22); return w; } static WORD sbox2 (WORD w) { w ^= ROTL (w, 7) | ROTL (w, 22); w ^= ROTL (w, 5) | ROTL (w, 19); return w; } /* cycle the contents of the register and calculate output word in c->sbuf. */ static void cycle (shn_ctx * c) { WORD t; int i; /* nonlinear feedback function */ t = c->R[12] ^ c->R[13] ^ c->konst; t = sbox1 (t) ^ ROTL (c->R[0], 1); /* shift register */ for (i = 1; i < N; ++i) c->R[i - 1] = c->R[i]; c->R[N - 1] = t; t = sbox2 (c->R[2] ^ c->R[15]); c->R[0] ^= t; c->sbuf = t ^ c->R[8] ^ c->R[12]; } /* The Shannon MAC function is modelled after the concepts of Phelix and SHA. * Basically, words to be accumulated in the MAC are incorporated in two * different ways: * 1. They are incorporated into the stream cipher register at a place * where they will immediately have a nonlinear effect on the state * 2. They are incorporated into bit-parallel CRC-16 registers; the * contents of these registers will be used in MAC finalization. */ /* Accumulate a CRC of input words, later to be fed into MAC. * This is actually 32 parallel CRC-16s, using the IBM CRC-16 * polynomial x^16 + x^15 + x^2 + 1. */ static void crcfunc (shn_ctx * c, WORD i) { WORD t; int j; /* Accumulate CRC of input */ t = c->CRC[0] ^ c->CRC[2] ^ c->CRC[15] ^ i; for (j = 1; j < N; ++j) c->CRC[j - 1] = c->CRC[j]; c->CRC[N - 1] = t; } /* Normal MAC word processing: do both stream register and CRC. */ static void macfunc (shn_ctx * c, WORD i) { crcfunc (c, i); c->R[KEYP] ^= i; } /* initialise to known state */ static void shn_initstate (shn_ctx * c) { int i; /* Register initialised to Fibonacci numbers; Counter zeroed. */ c->R[0] = 1; c->R[1] = 1; for (i = 2; i < N; ++i) c->R[i] = c->R[i - 1] + c->R[i - 2]; c->konst = INITKONST; } /* Save the current register state */ static void shn_savestate (shn_ctx * c) { int i; for (i = 0; i < N; ++i) c->initR[i] = c->R[i]; } /* initialise to previously saved register state */ static void shn_reloadstate (shn_ctx * c) { int i; for (i = 0; i < N; ++i) c->R[i] = c->initR[i]; } /* Initialise "konst" */ static void shn_genkonst (shn_ctx * c) { c->konst = c->R[0]; } /* Load key material into the register */ #define ADDKEY(k) \ c->R[KEYP] ^= (k); /* extra nonlinear diffusion of register for key and MAC */ static void shn_diffuse (shn_ctx * c) { int i; for (i = 0; i < FOLD; ++i) cycle (c); } /* Common actions for loading key material * Allow non-word-multiple key and nonce material. * Note also initializes the CRC register as a side effect. */ static void shn_loadkey (shn_ctx * c, UCHAR key[], int keylen) { int i, j; WORD k; UCHAR xtra[4]; /* start folding in key */ for (i = 0; i < (keylen & ~0x3); i += 4) { k = BYTE2WORD (&key[i]); ADDKEY (k); cycle (c); } /* if there were any extra key bytes, zero pad to a word */ if (i < keylen) { for (j = 0 /* i unchanged */ ; i < keylen; ++i) xtra[j++] = key[i]; for ( /* j unchanged */ ; j < 4; ++j) xtra[j] = 0; k = BYTE2WORD (xtra); ADDKEY (k); cycle (c); } /* also fold in the length of the key */ ADDKEY (keylen); cycle (c); /* save a copy of the register */ for (i = 0; i < N; ++i) c->CRC[i] = c->R[i]; /* now diffuse */ shn_diffuse (c); /* now xor the copy back -- makes key loading irreversible */ for (i = 0; i < N; ++i) c->R[i] ^= c->CRC[i]; } /* Published "key" interface */ void shn_key (shn_ctx * c, UCHAR key[], int keylen) { shn_initstate (c); shn_loadkey (c, key, keylen); shn_genkonst (c); /* in case we proceed to stream generation */ shn_savestate (c); c->nbuf = 0; } /* Published "IV" interface */ void shn_nonce (shn_ctx * c, UCHAR nonce[], int noncelen) { shn_reloadstate (c); c->konst = INITKONST; shn_loadkey (c, nonce, noncelen); shn_genkonst (c); c->nbuf = 0; } /* XOR pseudo-random bytes into buffer * Note: doesn't play well with MAC functions. */ void shn_stream (shn_ctx * c, UCHAR * buf, int nbytes) { UCHAR *endbuf; /* handle any previously buffered bytes */ while (c->nbuf != 0 && nbytes != 0) { *buf++ ^= c->sbuf & 0xFF; c->sbuf >>= 8; c->nbuf -= 8; --nbytes; } /* handle whole words */ endbuf = &buf[nbytes & ~((WORD) 0x03)]; while (buf < endbuf) { cycle (c); XORWORD (c->sbuf, buf); buf += 4; } /* handle any trailing bytes */ nbytes &= 0x03; if (nbytes != 0) { cycle (c); c->nbuf = 32; while (c->nbuf != 0 && nbytes != 0) { *buf++ ^= c->sbuf & 0xFF; c->sbuf >>= 8; c->nbuf -= 8; --nbytes; } } } /* accumulate words into MAC without encryption * Note that plaintext is accumulated for MAC. */ void shn_maconly (shn_ctx * c, UCHAR * buf, int nbytes) { UCHAR *endbuf; /* handle any previously buffered bytes */ if (c->nbuf != 0) { while (c->nbuf != 0 && nbytes != 0) { c->mbuf ^= (*buf++) << (32 - c->nbuf); c->nbuf -= 8; --nbytes; } if (c->nbuf != 0) /* not a whole word yet */ return; /* LFSR already cycled */ macfunc (c, c->mbuf); } /* handle whole words */ endbuf = &buf[nbytes & ~((WORD) 0x03)]; while (buf < endbuf) { cycle (c); macfunc (c, BYTE2WORD (buf)); buf += 4; } /* handle any trailing bytes */ nbytes &= 0x03; if (nbytes != 0) { cycle (c); c->mbuf = 0; c->nbuf = 32; while (c->nbuf != 0 && nbytes != 0) { c->mbuf ^= (*buf++) << (32 - c->nbuf); c->nbuf -= 8; --nbytes; } } } /* Combined MAC and encryption. * Note that plaintext is accumulated for MAC. */ void shn_encrypt (shn_ctx * c, UCHAR * buf, int nbytes) { UCHAR *endbuf; WORD t = 0; /* handle any previously buffered bytes */ if (c->nbuf != 0) { while (c->nbuf != 0 && nbytes != 0) { c->mbuf ^= *buf << (32 - c->nbuf); *buf ^= (c->sbuf >> (32 - c->nbuf)) & 0xFF; ++buf; c->nbuf -= 8; --nbytes; } if (c->nbuf != 0) /* not a whole word yet */ return; /* LFSR already cycled */ macfunc (c, c->mbuf); } /* handle whole words */ endbuf = &buf[nbytes & ~((WORD) 0x03)]; while (buf < endbuf) { cycle (c); t = BYTE2WORD (buf); macfunc (c, t); t ^= c->sbuf; WORD2BYTE (t, buf); buf += 4; } /* handle any trailing bytes */ nbytes &= 0x03; if (nbytes != 0) { cycle (c); c->mbuf = 0; c->nbuf = 32; while (c->nbuf != 0 && nbytes != 0) { c->mbuf ^= *buf << (32 - c->nbuf); *buf ^= (c->sbuf >> (32 - c->nbuf)) & 0xFF; ++buf; c->nbuf -= 8; --nbytes; } } } /* Combined MAC and decryption. * Note that plaintext is accumulated for MAC. */ void shn_decrypt (shn_ctx * c, UCHAR * buf, int nbytes) { UCHAR *endbuf; WORD t = 0; /* handle any previously buffered bytes */ if (c->nbuf != 0) { while (c->nbuf != 0 && nbytes != 0) { *buf ^= (c->sbuf >> (32 - c->nbuf)) & 0xFF; c->mbuf ^= *buf << (32 - c->nbuf); ++buf; c->nbuf -= 8; --nbytes; } if (c->nbuf != 0) /* not a whole word yet */ return; /* LFSR already cycled */ macfunc (c, c->mbuf); } /* handle whole words */ endbuf = &buf[nbytes & ~((WORD) 0x03)]; while (buf < endbuf) { cycle (c); t = BYTE2WORD (buf) ^ c->sbuf; macfunc (c, t); WORD2BYTE (t, buf); buf += 4; } /* handle any trailing bytes */ nbytes &= 0x03; if (nbytes != 0) { cycle (c); c->mbuf = 0; c->nbuf = 32; while (c->nbuf != 0 && nbytes != 0) { *buf ^= (c->sbuf >> (32 - c->nbuf)) & 0xFF; c->mbuf ^= *buf << (32 - c->nbuf); ++buf; c->nbuf -= 8; --nbytes; } } } /* Having accumulated a MAC, finish processing and return it. * Note that any unprocessed bytes are treated as if * they were encrypted zero bytes, so plaintext (zero) is accumulated. */ void shn_finish (shn_ctx * c, UCHAR * buf, int nbytes) { int i; /* handle any previously buffered bytes */ if (c->nbuf != 0) { /* LFSR already cycled */ macfunc (c, c->mbuf); } /* perturb the MAC to mark end of input. * Note that only the stream register is updated, not the CRC. This is an * action that can't be duplicated by passing in plaintext, hence * defeating any kind of extension attack. */ cycle (c); ADDKEY (INITKONST ^ (c->nbuf << 3)); c->nbuf = 0; /* now add the CRC to the stream register and diffuse it */ for (i = 0; i < N; ++i) c->R[i] ^= c->CRC[i]; shn_diffuse (c); /* produce output from the stream buffer */ while (nbytes > 0) { cycle (c); if (nbytes >= 4) { WORD2BYTE (c->sbuf, buf); nbytes -= 4; buf += 4; } else { for (i = 0; i < nbytes; ++i) buf[i] = Byte (c->sbuf, i); break; } } }
KaiserLancelot/kpkg
include/command.h
#pragma once #include <string> #include <vector> namespace kpkg { void run_commands(const std::vector<std::string>& commands, const std::string& cwd); namespace detail { std::string calc_command(const std::vector<std::string>& commands, const std::string& cwd); } // namespace detail } // namespace kpkg
KaiserLancelot/kpkg
include/program.h
#pragma once #include <cstdint> #include <string> #include <vector> #include "library.h" namespace kpkg { class Program { public: Program(const std::vector<std::string>& libraries, const std::string& proxy); [[nodiscard]] bool build_pyftsubset() const { return build_pyftsubset_; } [[nodiscard]] std::string proxy() const { return proxy_; } [[nodiscard]] std::vector<Library>& dependencies() { return dependencies_; } [[nodiscard]] std::vector<Library>& libraries_to_be_built() { return libraries_to_be_built_; } void show_libraries(); private: static void unique(std::vector<Library>& libraries); static bool contains(const std::vector<Library>& libraries, const std::string& name); Library get_from_name(const std::string& name); std::string proxy_; std::vector<Library> libraries_; std::vector<Library> dependencies_; std::vector<Library> libraries_to_be_built_; bool build_pyftsubset_ = false; }; } // namespace kpkg
KaiserLancelot/kpkg
include/library.h
<filename>include/library.h<gh_stars>1-10 #pragma once #include <string> #include <vector> namespace kpkg { class Library { public: Library() = default; Library(const std::string& name, const std::string& releases_url, const std::string& tags_url, const std::vector<std::string>& dependency, const std::string& cwd, const std::vector<std::string>& cmd, const std::string& tag_name, const std::string& download_url); void init(const std::string& proxy); [[nodiscard]] const std::string& get_name() const { return name_; } [[nodiscard]] const std::vector<std::string>& get_dependency() const { return dependency_; } void download(const std::string& proxy) const; void build() const; void print() const; private: std::string name_; std::string releases_url_; std::string tags_url_; std::vector<std::string> dependency_; std::string cwd_; std::vector<std::string> cmd_; std::string tag_name_; std::string download_url_; std::string file_name_; std::string dir_name_; }; std::vector<Library> read_from_json(); void show_pyftsubset(const std::string& proxy); void build_pyftsubset(const std::string& proxy); } // namespace kpkg
KaiserLancelot/kpkg
include/downloader.h
#pragma once #include <string> #include <aria2/aria2.h> namespace kpkg { class HTTPDownloader { public: explicit HTTPDownloader(const std::string &proxy = ""); HTTPDownloader(const HTTPDownloader &) = delete; HTTPDownloader(HTTPDownloader &&) = delete; HTTPDownloader &operator=(const HTTPDownloader &) = delete; HTTPDownloader &operator=(HTTPDownloader &&) = delete; ~HTTPDownloader(); std::string download(const std::string &url, const std::string &file_name = ""); private: aria2::KeyVals options_; }; } // namespace kpkg
KaiserLancelot/kpkg
include/http.h
<reponame>KaiserLancelot/kpkg #pragma once #include <string> #include <klib/http.h> namespace kpkg { klib::Response http_get(const std::string &url, const std::string &proxy); } // namespace kpkg
KaiserLancelot/kpkg
include/upgrade.h
#pragma once #include <string> namespace kpkg { void upgrade(const std::string &proxy); } // namespace kpkg
KaiserLancelot/kpkg
include/github_info.h
<gh_stars>1-10 #pragma once #include <optional> #include <string> #include <string_view> #include <vector> namespace kpkg { struct Asset { Asset(std::string_view name, std::string_view url) : name_(name), url_(url) {} std::string name_; std::string url_; }; class ReleaseInfo { public: explicit ReleaseInfo(std::string json); [[nodiscard]] const std::string& get_tag_name() const { return tag_name_; } [[nodiscard]] const std::string& get_url() const { return url_; } [[nodiscard]] std::optional<Asset> get_deb_asset() const; private: std::string tag_name_; std::string url_; std::vector<Asset> assets_; }; class TagInfo { public: explicit TagInfo(std::string json); [[nodiscard]] const std::string& get_tag_name() const { return tag_name_; } [[nodiscard]] const std::string& get_url() const { return url_; } private: std::string tag_name_; std::string url_; }; } // namespace kpkg
KaiserLancelot/kpkg
test/extra_test/error.h
#pragma once #include <cstdint> #include <cstdlib> #include <iostream> #include <string_view> [[noreturn]] void error(std::string_view msg) { std::cerr << "error: " << msg << '\n'; std::exit(EXIT_FAILURE); } [[noreturn]] void require_fail(std::string_view expr, std::string_view file_name, std::uint_least32_t line, std::string_view function_name) { std::cerr << "error: " << expr << '\n'; std::cerr << "at file name: " << file_name << "\t function name :" << function_name << "\t line :" << line << '\n'; std::exit(EXIT_FAILURE); } #define EXPECT(expr) \ (static_cast<bool>(expr) \ ? void(0) \ : require_fail(#expr, __FILE__, __LINE__, __func__))
KaiserLancelot/kpkg
include/version.h
<reponame>KaiserLancelot/kpkg<gh_stars>1-10 #pragma once #include <string> #define KPKG_VER_MAJOR 0 #define KPKG_VER_MINOR 11 #define KPKG_VER_PATCH 2 #define KPKG_VERSION \ (KPKG_VER_MAJOR * 10000 + KPKG_VER_MINOR * 100 + KPKG_VER_PATCH) #define KPKG_STRINGIZE2(s) #s #define KPKG_STRINGIZE(s) KPKG_STRINGIZE2(s) #define KPKG_VERSION_STRING \ KPKG_STRINGIZE(KPKG_VER_MAJOR) \ "." KPKG_STRINGIZE(KPKG_VER_MINOR) "." KPKG_STRINGIZE(KPKG_VER_PATCH) namespace kpkg { std::string version_str(); } // namespace kpkg
alfin3/graph-algorithms
data-structures/queue/queue-test.c
/** queue-test.c Tests of a generic queue. The following command line arguments can be used to customize tests: queue-test [0, ulong width) : i s.t. # inserts = 2**i [0, ulong width) : i s.t. # inserts = 2**i in uchar queue test [0, 1] : on/off push pop first free uint test [0, 1] : on/off push pop first free uint_ptr (noncontiguous) test [0, 1] : on/off uchar queue test usage examples: ./queue-test ./queue-test 23 ./queue-test 24 31 ./queue-test 24 31 0 0 1 queue-test can be run with any subset of command line arguments in the above-defined order. If the (i + 1)th argument is specified then the ith argument must be specified for i >= 0. Default values are used for the unspecified arguments according to the C_ARGS_DEF array. The implementation of tests does not use stdint.h and is portable under C89/C90 and C99. The tests require that: - size_t and clock_t are convertible to double, - size_t can represent values upto 65535 for default values, and upto ULONG_MAX (>= 4294967295) otherwise, - the widths of the unsigned integral types are less than 2040 and even. TODO: add portable size_t printing */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <limits.h> #include <time.h> #include "queue.h" #include "utilities-mem.h" #include "utilities-mod.h" #include "utilities-lim.h" #define TOLU(i) ((unsigned long int)(i)) /* printing size_t under C89/C90 */ /* input handling */ const char *C_USAGE = "queue-test \n" "[0, ulong width) : i s.t. # inserts = 2**i\n" "[0, ulong width) : i s.t. # inserts = 2**i in uchar queue test\n" "[0, 1] : on/off push pop first free uint test\n" "[0, 1] : on/off push pop first free uint_ptr (noncontiguous) test\n" "[0, 1] : on/off uchar queue test\n"; const int C_ARGC_ULIMIT = 6; const size_t C_ARGS_DEF[5] = {14, 15, 1, 1, 1}; const size_t C_ULONG_BIT = PRECISION_FROM_ULIMIT((unsigned long)-1); /* tests */ const unsigned char C_UCHAR_ULIMIT = (unsigned char)-1; const size_t C_START_VAL = 0; /* <= # inserts */ void print_test_result(int res); /** Run tests of a queue of size_t elements. A pointer to an element is passed as elt in queue_push and the size_t element is copied onto the queue. NULL as free_elt is sufficient to free the queue. */ void uint_push_pop_helper(struct queue *q, size_t start_val, size_t num_ins); void run_uint_push_pop_test(size_t log_ins){ size_t num_ins; size_t start_val = C_START_VAL; struct queue q; num_ins = pow_two_perror(log_ins); queue_init(&q, sizeof(size_t), NULL); printf("Run a queue_{push, pop} test on %lu size_t elements\n", TOLU(num_ins)); printf("\teff initial count: %lu, eff max count: %lu\n", TOLU(q.init_count) >> 1, TOLU(q.max_count) >> 1); uint_push_pop_helper(&q, start_val, num_ins); queue_free(&q); queue_init(&q, sizeof(size_t), NULL); queue_bound(&q, 1, num_ins); printf("\teff initial count: %lu, eff max count: %lu\n", TOLU(q.init_count) >> 1, TOLU(q.max_count) >> 1); uint_push_pop_helper(&q, start_val, num_ins); queue_free(&q); queue_init(&q, sizeof(size_t), NULL); queue_bound(&q, num_ins, num_ins); printf("\teff initial count: %lu, eff max count: %lu\n", TOLU(q.init_count) >> 1, TOLU(q.max_count) >> 1); uint_push_pop_helper(&q, start_val, num_ins); queue_free(&q); } void uint_push_pop_helper(struct queue *q, size_t start_val, size_t num_ins){ int res = 1; size_t i; size_t *pushed = NULL, *popped = NULL; clock_t t_push, t_pop; pushed = malloc_perror(num_ins, sizeof(size_t)); popped = malloc_perror(num_ins, sizeof(size_t)); for (i = 0; i < num_ins; i++){ pushed[i] = start_val + i; } t_push = clock(); for (i = 0; i < num_ins; i++){ queue_push(q, &pushed[i]); } t_push = clock() - t_push; t_pop = clock(); for (i = 0; i < num_ins; i++){ queue_pop(q, &popped[i]); } t_pop = clock() - t_pop; res *= (q->num_elts == 0); res *= (q->count >= num_ins); for (i = 0; i < num_ins; i++){ res *= (popped[i] == start_val + i); } printf("\t\tpush time: %.4f seconds\n", (double)t_push / CLOCKS_PER_SEC); printf("\t\tpop time: %.4f seconds\n", (double)t_pop / CLOCKS_PER_SEC); printf("\t\tcorrectness: "); print_test_result(res); free(pushed); free(popped); pushed = NULL; popped = NULL; } void run_uint_first_test(size_t log_ins){ int res = 1; size_t i; size_t num_ins; size_t start_val = C_START_VAL; size_t pushed, popped; struct queue q; num_ins = pow_two_perror(log_ins); queue_init(&q, sizeof(size_t), NULL); printf("Run a queue_first test on %lu size_t elements\n", TOLU(num_ins)); for (i = 0; i < num_ins; i++){ if (q.num_elts == 0){ res *= (queue_first(&q) == NULL); } pushed = start_val + i; queue_push(&q, &pushed); res *= (*(size_t *)queue_first(&q) == start_val); } for (i = 0; i < num_ins; i++){ res *= (*(size_t *)queue_first(&q) == start_val + i); queue_pop(&q, &popped); if (q.num_elts == 0){ res *= (queue_first(&q) == NULL); } } res *= (q.num_elts == 0); res *= (q.count >= num_ins); printf("\t\tcorrectness: "); print_test_result(res); queue_free(&q); } void run_uint_free_test(size_t log_ins){ size_t i; size_t num_ins; struct queue q; clock_t t; num_ins = pow_two_perror(log_ins); queue_init(&q, sizeof(size_t), NULL); printf("Run a queue_free test on %lu size_t elements\n", TOLU(num_ins)); for (i = 0; i < num_ins; i++){ queue_push(&q, &i); } t = clock(); queue_free(&q); t = clock() - t; printf("\t\tfree time: %.4f seconds\n", (double)t / CLOCKS_PER_SEC); } /** Run tests of a queue of uint_ptr elements. A pointer to a pointer to an uint_ptr element is passed as elt in queue_push and the pointer to the uint_ptr element is copied onto the queue. A uint_ptr- specific free_elt, taking a pointer to a pointer to an element as its parameter, is necessary to free the queue. */ struct uint_ptr{ size_t *val; }; void free_uint_ptr(void *a){ struct uint_ptr **s = a; free((*s)->val); (*s)->val = NULL; free(*s); *s = NULL; } void uint_ptr_push_pop_helper(struct queue *q, size_t start_val, size_t num_ins); void run_uint_ptr_push_pop_test(size_t log_ins){ size_t num_ins; size_t start_val = C_START_VAL; struct queue q; num_ins = pow_two_perror(log_ins); queue_init(&q, sizeof(struct uint_ptr *), free_uint_ptr); printf("Run a queue_{push, pop} test on %lu noncontiguous uint_ptr " "elements\n", TOLU(num_ins)); printf("\teff initial count: %lu, eff max count: %lu\n", TOLU(q.init_count) >> 1, TOLU(q.max_count) >> 1); uint_ptr_push_pop_helper(&q, start_val, num_ins); queue_free(&q); queue_init(&q, sizeof(struct uint_ptr *), free_uint_ptr); queue_bound(&q, 1, num_ins); printf("\teff initial count: %lu, eff max count: %lu\n", TOLU(q.init_count) >> 1, TOLU(q.max_count) >> 1); uint_ptr_push_pop_helper(&q, start_val, num_ins); queue_free(&q); queue_init(&q, sizeof(struct uint_ptr *), free_uint_ptr); queue_bound(&q, num_ins, num_ins); printf("\teff initial count: %lu, eff max count: %lu\n", TOLU(q.init_count) >> 1, TOLU(q.max_count) >> 1); uint_ptr_push_pop_helper(&q, start_val, num_ins); queue_free(&q); } void uint_ptr_push_pop_helper(struct queue *q, size_t start_val, size_t num_ins){ int res = 1; size_t i; struct uint_ptr **pushed = NULL, **popped = NULL; clock_t t_push, t_pop; pushed = calloc_perror(num_ins, sizeof(struct uint_ptr *)); popped = calloc_perror(num_ins, sizeof(struct uint_ptr *)); for (i = 0; i < num_ins; i++){ pushed[i] = malloc_perror(1, sizeof(struct uint_ptr)); pushed[i]->val = malloc_perror(1, sizeof(size_t)); *(pushed[i]->val) = start_val + i; } t_push = clock(); for (i = 0; i < num_ins; i++){ queue_push(q, &pushed[i]); } t_push = clock() - t_push; for (i = 0; i < num_ins; i++){ pushed[i] = NULL; } t_pop = clock(); for (i = 0; i < num_ins; i++){ queue_pop(q, &popped[i]); } t_pop = clock() - t_pop; res *= (q->num_elts == 0); res *= (q->count >= num_ins); for (i = 0; i < num_ins; i++){ res *= (*(popped[i]->val) == start_val + i); free_uint_ptr(&popped[i]); } printf("\t\tpush time: %.4f seconds\n", (double)t_push / CLOCKS_PER_SEC); printf("\t\tpop time: %.4f seconds\n", (double)t_pop / CLOCKS_PER_SEC); printf("\t\tcorrectness: "); print_test_result(res); free(pushed); free(popped); pushed = NULL; popped = NULL; } void run_uint_ptr_first_test(size_t log_ins){ int res = 1; size_t i; size_t num_ins; size_t start_val = C_START_VAL; struct uint_ptr *pushed = NULL, *popped = NULL; struct queue q; num_ins = pow_two_perror(log_ins); queue_init(&q, sizeof(struct uint_ptr *), free_uint_ptr); printf("Run a queue_first test on %lu noncontiguous uint_ptr elements\n", TOLU(num_ins)); for (i = 0; i < num_ins; i++){ if (q.num_elts == 0){ res *= (queue_first(&q) == NULL); } pushed = malloc_perror(1, sizeof(struct uint_ptr)); pushed->val = malloc_perror(1, sizeof(size_t)); *(pushed->val) = start_val + i; queue_push(&q, &pushed); res *= (*(*(struct uint_ptr **)queue_first(&q))->val == start_val); pushed = NULL; } for (i = 0; i < num_ins; i++){ res *= (*(*(struct uint_ptr **)queue_first(&q))->val == start_val + i); queue_pop(&q, &popped); if (q.num_elts == 0){ res *= (queue_first(&q) == NULL); } free_uint_ptr(&popped); popped = NULL; } res *= (q.num_elts == 0); res *= (q.count >= num_ins); printf("\t\tcorrectness: "); print_test_result(res); queue_free(&q); } void run_uint_ptr_free_test(size_t log_ins){ size_t i; size_t num_ins; struct uint_ptr *pushed = NULL; struct queue q; clock_t t; num_ins = pow_two_perror(log_ins); queue_init(&q, sizeof(struct uint_ptr *), free_uint_ptr); printf("Run a queue_free test on %lu noncontiguous uint_ptr elements\n", TOLU(num_ins)); for (i = 0; i < num_ins; i++){ pushed = malloc_perror(1, sizeof(struct uint_ptr)); pushed->val = malloc_perror(1, sizeof(size_t)); *(pushed->val) = i; queue_push(&q, &pushed); pushed = NULL; } t = clock(); queue_free(&q); t = clock() - t; printf("\t\tfree time: %.4f seconds\n", (double)t / CLOCKS_PER_SEC); } /** Runs a test of a queue of unsigned char elements. */ void run_uchar_queue_test(size_t log_ins){ unsigned char c; size_t i; size_t num_ins; struct queue q; clock_t t_push, t_pop; num_ins = pow_two_perror(log_ins); queue_init(&q, sizeof(unsigned char), NULL); printf("Run a queue_{push, pop} test on %lu char elements\n", TOLU(num_ins)); t_push = clock(); for (i = 0; i < num_ins; i++){ queue_push(&q, &C_UCHAR_ULIMIT); } t_push = clock() - t_push; t_pop = clock(); for (i = 0; i < num_ins; i++){ queue_pop(&q, &c); } t_pop = clock() - t_pop; printf("\t\tpush time: %.4f seconds\n", (double)t_push / CLOCKS_PER_SEC); printf("\t\tpop time: %.4f seconds\n", (double)t_pop / CLOCKS_PER_SEC); queue_free(&q); } void print_test_result(int res){ if (res){ printf("SUCCESS\n"); }else{ printf("FAILURE\n"); } } int main(int argc, char *argv[]){ int i; size_t *args = NULL; if (argc > C_ARGC_ULIMIT){ fprintf(stderr, "USAGE:\n%s", C_USAGE); exit(EXIT_FAILURE); } args = malloc_perror(C_ARGC_ULIMIT - 1, sizeof(size_t)); memcpy(args, C_ARGS_DEF, (C_ARGC_ULIMIT - 1) * sizeof(size_t)); for (i = 1; i < argc; i++){ args[i - 1] = atoi(argv[i]); } if (args[0] > C_ULONG_BIT - 1 || args[1] > C_ULONG_BIT - 1 || args[2] > 1 || args[3] > 1 || args[4] > 1){ fprintf(stderr, "USAGE:\n%s", C_USAGE); exit(EXIT_FAILURE); } if (args[2]){ run_uint_push_pop_test(args[0]); run_uint_first_test(args[0]); run_uint_free_test(args[0]); } if (args[3]){ run_uint_ptr_push_pop_test(args[0]); run_uint_ptr_first_test(args[0]); run_uint_ptr_free_test(args[0]); } if (args[4]){ run_uchar_queue_test(args[1]); } free(args); args = NULL; return 0; }
alfin3/graph-algorithms
utilities-pthread/mergesort-pthread/mergesort-pthread.h
<reponame>alfin3/graph-algorithms<filename>utilities-pthread/mergesort-pthread/mergesort-pthread.h /** mergesort-pthread.h Declarations of accessible functions and macro definitions for optimizing and running a generic merge sort algorithm with parallel sorting and parallel merging. The algorithm provides \Theta(n/log^{2}n) theoretical parallelism within the dynamic multithreading model. The implementation provides i) a set of parameters for setting the constant base case upper bounds for switching from parallel sorting to serial sorting and from parallel merging to serial merging during recursion, and ii) a macro for setting the constant upper bound for the number of recursive calls placed on the stack of a thread across sorting and merging operations, thereby enabling the optimization of the parallelism and concurrency-associated overhead across input ranges and hardware settings. The provided parametrization of multithreading is based on the common parametrization of serial mergesort, where the recursion depth is limited by switching to a base case non-recursive sort algorithm. On a 4-core machine, the optimization of the base case upper bound parameters resulted in a speedup of approximately 2.6X in comparison to serial qsort (stdlib.h) on arrays of 10M random integer or double elements. */ #ifndef MERGESORT_PTHREAD_H #define MERGESORT_PTHREAD_H #include <stddef.h> /** Sorts a given array pointed to by elts in ascending order according to cmp. The array contains count elements of elt_size bytes. The first thread entry is placed on the thread stack of the caller. elts : pointer to the array to sort count : > 0, < 2^{CHAR_BIT * sizeof(size_t) - 1} count of elements in the array elt_size : size of each element in the array in bytes sbase_count : > 0 base case upper bound for parallel sorting; if the count of an unsorted subarray is less or equal to sbase_count, then the subarray is sorted with serial sort routine (qsort) mbase_count : > 1 base case upper bound for parallel merging; if the sum of the counts of two sorted subarrays is less or equal to mbase_count, then the two subarrays are merged with a serial merge routine cmp : comparison function which returns a negative integer value if the element pointed to by the first argument is less than the element pointed to by the second, a positive integer value if the element pointed to by the first argument is greater than the element pointed to by the second, and zero integer value if the two elements are equal */ void mergesort_pthread(void *elts, size_t count, size_t elt_size, size_t sbase_count, size_t mbase_count, int (*cmp)(const void *, const void *)); /** A constant upper bound for the number of recursive calls of thread entry functions placed on the stack of a thread. Reduces the total number of threads and provides an additional speedup if greater than 0. If equal to 0, then each recursive call results in the creation of a new thread. The macro is used as size_t. */ #define MERGESORT_PTHREAD_MAX_ONTHREAD_REC (20) #endif
alfin3/graph-algorithms
utilities/utilities-lim/utilities-lim.h
<gh_stars>0 /** utilities-lim.h Numerical limits in addition to limits.h requiring only C89/C99. */ #ifndef UTILITIES_LIM_H #define UTILITIES_LIM_H #include <limits.h> /** Provides the precision number of bits given the maximum value of an integer from 1 to 2**2040 - 1. The width of an unsigned integer is the same as precision. Adopted from: https://groups.google.com/g/comp.lang.c/c/1kiXXt5T0TQ/m/S_B_8D4VmOkJ */ #define PRECISION_FROM_ULIMIT(m) ((m) / ((m) % 255u + 1u) / 255u % 255u * 8u \ + 7u - \ 86u / ((m) % 255u + 12u)) #endif
alfin3/graph-algorithms
graph-algorithms/tsp/tsp-test.c
/** tsp-test.c Tests of an exact solution of TSP without vertex revisiting across i) default, division and multiplication-based hash tables, and ii) weight types. The following command line arguments can be used to customize tests: tsp-test: - [1, # bits in size_t) : a - [1, # bits in size_t) : b s.t. a <= |V| <= b for all hash tables test - [1, # bits in size_t) : c - [1, # bits in size_t) : d s.t. c <= |V| <= d for default hash table test - [1, 8 * # bits in size_t] : e - [1, 8 * # bits in size_t] : f s.t. e <= |V| <= f for sparse graph test - [0, 1] : on/off for small graph test - [0, 1] : on/off for all hash tables test - [0, 1] : on/off for default hash table test - [0, 1] : on/off for sparse graph test usage examples: ./tsp-test ./tsp-test 12 18 18 22 10 60 ./tsp-test 12 18 18 22 100 105 0 0 1 1 tsp-test can be run with any subset of command line arguments in the above-defined order. If the (i + 1)th argument is specified then the ith argument must be specified for i >= 0. Default values are used for the unspecified arguments according to the C_ARGS_DEF array. The implementation of tests does not use stdint.h and is portable under C89/C90 with the only requirement that CHAR_BIT * sizeof(size_t) is greater or equal to 16 and is even. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <limits.h> #include <time.h> #include "tsp.h" #include "ht-divchn.h" #include "ht-muloa.h" #include "graph.h" #include "stack.h" #include "utilities-mem.h" #include "utilities-mod.h" /** Generate random numbers in a portable way for test purposes only; rand() in the Linux C Library uses the same generator as random(), which may not be the case on older rand() implementations, and on current implementations on different systems. */ #define RGENS_SEED() do{srand(time(NULL));}while (0) #define RANDOM() (rand()) /* [0, RAND_MAX] */ #define DRAND() ((double)rand() / RAND_MAX) /* [0.0, 1.0] */ #define TOLU(i) ((unsigned long int)(i)) /* printing size_t under C89/C90 */ /* input handling */ const char *C_USAGE = "tsp-test \n" "[1, # bits in size_t) : a \n" "[1, # bits in size_t) : b s.t. a <= |V| <= b for all hash tables test \n" "[1, # bits in size_t) : c \n" "[1, # bits in size_t) : d s.t. c <= |V| <= d for default hash table test \n" "[1, 8 * # bits in size_t] : e \n" "[1, 8 * # bits in size_t] : f s.t. e <= |V| <= f for sparse graph test \n" "[0, 1] : on/off for small graph test \n" "[0, 1] : on/off for all hash tables test \n" "[0, 1] : on/off for default hash table test \n" "[0, 1] : on/off for sparse graph test \n"; const int C_ARGC_MAX = 11; const size_t C_ARGS_DEF[10] = {1, 20, 20, 21, 100, 104, 1, 1, 1, 1}; const size_t C_SPARSE_GRAPH_V_MAX = 8 * CHAR_BIT * sizeof(size_t); const size_t C_FULL_BIT = CHAR_BIT * sizeof(size_t); /* hash table load factor upper bounds */ const size_t C_ALPHA_N_DIVCHN = 1; const size_t C_LOG_ALPHA_D_DIVCHN = 0; const size_t C_ALPHA_N_MULOA = 13107; const size_t C_LOG_ALPHA_D_MULOA = 15; /* small graph test */ const size_t C_NUM_VTS = 4; const size_t C_NUM_ES = 12; const size_t C_U[12] = {0, 1, 2, 3, 1, 2, 3, 0, 0, 2, 1, 3}; const size_t C_V[12] = {1, 2, 3, 0, 0, 1, 2, 3, 2, 0, 3, 1}; const size_t C_WTS_UINT[12] = {1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2}; const double C_WTS_DOUBLE[12] = {1.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0}; /* random graph tests */ const int C_ITER = 3; const int C_PROBS_COUNT = 4; const int C_SPARSE_PROBS_COUNT = 2; const double C_PROBS[4] = {1.0000, 0.2500, 0.0625, 0.0000}; const double C_SPARSE_PROBS[2] = {0.0050, 0.0025}; const double C_PROB_ONE = 1.0; const double C_PROB_ZERO = 0.0; const size_t C_SIZE_MAX = (size_t)-1; const size_t C_WEIGHT_HIGH = ((size_t)-1 >> ((CHAR_BIT * sizeof(size_t) + 1) / 2)); void print_uint(const void *a); void print_double(const void *a); void print_adj_lst(const adj_lst_t *a, void (*print_wt)(const void *)); void print_uint_arr(const size_t *arr, size_t n); void print_double_arr(const double *arr, size_t n); void print_test_result(int res); void fprintf_stderr_exit(const char *s, int line); /** Initialize small graphs with size_t weights. */ void graph_uint_wts_init(graph_t *g){ size_t i; graph_base_init(g, C_NUM_VTS, sizeof(size_t)); g->num_es = C_NUM_ES; g->u = malloc_perror(g->num_es, sizeof(size_t)); g->v = malloc_perror(g->num_es, sizeof(size_t)); g->wts = malloc_perror(g->num_es, g->wt_size); for (i = 0; i < g->num_es; i++){ g->u[i] = C_U[i]; g->v[i] = C_V[i]; *((size_t *)g->wts + i) = C_WTS_UINT[i]; } } void graph_uint_single_vt_init(graph_t *g){ graph_base_init(g, 1, sizeof(size_t)); } /** Run a test on small graphs with size_t weights. */ void add_uint(void *sum, const void *a, const void *b){ *(size_t *)sum = *(size_t *)a + *(size_t *)b; } int cmp_uint(const void *a, const void *b){ if (*(size_t *)a > *(size_t *)b){ return 1; }else if (*(size_t *)a < *(size_t *)b){ return -1; }else{ return 0; } } typedef struct{ size_t alpha_n; size_t log_alpha_d; } context_divchn_t; typedef struct{ size_t alpha_n; size_t log_alpha_d; size_t (*rdc_key)(const void *, size_t); } context_muloa_t; void ht_divchn_init_helper(ht_divchn_t *ht, size_t key_size, size_t elt_size, void (*free_elt)(void *), void *context){ context_divchn_t *c = context; ht_divchn_init(ht, key_size, elt_size, 0, c->alpha_n, c->log_alpha_d, free_elt); } void ht_muloa_init_helper(ht_muloa_t *ht, size_t key_size, size_t elt_size, void (*free_elt)(void *), void *context){ context_muloa_t * c = context; ht_muloa_init(ht, key_size, elt_size, 0, c->alpha_n, c->log_alpha_d, c->rdc_key, free_elt); } void run_def_uint_tsp(const adj_lst_t *a){ int ret = -1; size_t dist; size_t i; for (i = 0; i < a->num_vts; i++){ ret = tsp(a, i, &dist, NULL, add_uint, cmp_uint); printf("tsp ret: %d, tour length with %lu as start: ", ret, TOLU(i)); print_uint_arr(&dist, 1); } printf("\n"); } void run_divchn_uint_tsp(const adj_lst_t *a){ int ret = -1; size_t dist; size_t i; ht_divchn_t ht_divchn; context_divchn_t context_divchn; tsp_ht_t tht; context_divchn.alpha_n = C_ALPHA_N_DIVCHN; context_divchn.log_alpha_d = C_LOG_ALPHA_D_DIVCHN; tht.ht = &ht_divchn; tht.context = &context_divchn; tht.init = (tsp_ht_init)ht_divchn_init_helper; tht.insert = (tsp_ht_insert)ht_divchn_insert; tht.search = (tsp_ht_search)ht_divchn_search; tht.remove = (tsp_ht_remove)ht_divchn_remove; tht.free = (tsp_ht_free)ht_divchn_free; for (i = 0; i < a->num_vts; i++){ ret = tsp(a, i, &dist, &tht, add_uint, cmp_uint); printf("tsp ret: %d, tour length with %lu as start: ", ret, TOLU(i)); print_uint_arr(&dist, 1); } printf("\n"); } void run_muloa_uint_tsp(const adj_lst_t *a){ int ret = -1; size_t dist; size_t i; ht_muloa_t ht_muloa; context_muloa_t context_muloa; tsp_ht_t tht; context_muloa.alpha_n = C_ALPHA_N_MULOA; context_muloa.log_alpha_d = C_LOG_ALPHA_D_MULOA; context_muloa.rdc_key = NULL; tht.ht = &ht_muloa; tht.context = &context_muloa; tht.init = (tsp_ht_init)ht_muloa_init_helper; tht.insert = (tsp_ht_insert)ht_muloa_insert; tht.search = (tsp_ht_search)ht_muloa_search; tht.remove = (tsp_ht_remove)ht_muloa_remove; tht.free = (tsp_ht_free)ht_muloa_free; for (i = 0; i < a->num_vts; i++){ ret = tsp(a, i, &dist, &tht, add_uint, cmp_uint); printf("tsp ret: %d, tour length with %lu as start: ", ret, TOLU(i)); print_uint_arr(&dist, 1); } printf("\n"); } void run_uint_graph_test(){ graph_t g; adj_lst_t a; graph_uint_wts_init(&g); printf("Running a test on a size_t graph with a \n" "i) default hash table \n" "ii) ht_divchn_t hash table \n" "iii) ht_muloa_t hash table \n\n"); adj_lst_init(&a, &g); adj_lst_dir_build(&a, &g); print_adj_lst(&a, print_uint); run_def_uint_tsp(&a); run_divchn_uint_tsp(&a); run_muloa_uint_tsp(&a); adj_lst_free(&a); graph_free(&g); graph_uint_single_vt_init(&g); printf("Running a test on a size_t graph with a single vertex, with a \n" "i) default hash table \n" "ii) ht_divchn_t hash table \n" "iii) ht_muloa_t hash table \n\n"); adj_lst_init(&a, &g); adj_lst_dir_build(&a, &g); print_adj_lst(&a, print_uint); run_def_uint_tsp(&a); run_divchn_uint_tsp(&a); run_muloa_uint_tsp(&a); adj_lst_free(&a); graph_free(&g); } /** Initialize small graphs with double weights. */ void graph_double_wts_init(graph_t *g){ size_t i; graph_base_init(g, C_NUM_VTS, sizeof(double)); g->num_es = C_NUM_ES; g->u = malloc_perror(g->num_es, sizeof(size_t)); g->v = malloc_perror(g->num_es, sizeof(size_t)); g->wts = malloc_perror(g->num_es, g->wt_size); for (i = 0; i < g->num_es; i++){ g->u[i] = C_U[i]; g->v[i] = C_V[i]; *((double *)g->wts + i) = C_WTS_DOUBLE[i]; } } void graph_double_single_vt_init(graph_t *g){ graph_base_init(g, 1, sizeof(double)); } /** Run a test on small graphs with double weights. */ void add_double(void *sum, const void *a, const void *b){ *(double *)sum = *(double *)a + *(double *)b; } int cmp_double(const void *a, const void *b){ if (*(double *)a > *(double *)b){ return 1; }else if (*(double *)a < *(double *)b){ return -1; }else{ return 0; } } void run_def_double_tsp(const adj_lst_t *a){ int ret = -1; size_t i; double dist; for (i = 0; i < a->num_vts; i++){ ret = tsp(a, i, &dist, NULL, add_double, cmp_double); printf("tsp ret: %d, tour length with %lu as start: ", ret, TOLU(i)); print_double_arr(&dist, 1); } printf("\n"); } void run_divchn_double_tsp(const adj_lst_t *a){ int ret = -1; size_t i; double dist; ht_divchn_t ht_divchn; context_divchn_t context_divchn; tsp_ht_t tht; context_divchn.alpha_n = C_ALPHA_N_DIVCHN; context_divchn.log_alpha_d = C_LOG_ALPHA_D_DIVCHN; tht.ht = &ht_divchn; tht.context = &context_divchn; tht.init = (tsp_ht_init)ht_divchn_init_helper; tht.insert = (tsp_ht_insert)ht_divchn_insert; tht.search = (tsp_ht_search)ht_divchn_search; tht.remove = (tsp_ht_remove)ht_divchn_remove; tht.free = (tsp_ht_free)ht_divchn_free; for (i = 0; i < a->num_vts; i++){ ret = tsp(a, i, &dist, &tht, add_double, cmp_double); printf("tsp ret: %d, tour length with %lu as start: ", ret, TOLU(i)); print_double_arr(&dist, 1); } printf("\n"); } void run_muloa_double_tsp(const adj_lst_t *a){ int ret = -1; size_t i; double dist; ht_muloa_t ht_muloa; context_muloa_t context_muloa; tsp_ht_t tht; context_muloa.alpha_n = C_ALPHA_N_MULOA; context_muloa.log_alpha_d = C_LOG_ALPHA_D_MULOA; context_muloa.rdc_key = NULL; tht.ht = &ht_muloa; tht.context = &context_muloa; tht.init = (tsp_ht_init)ht_muloa_init_helper; tht.insert = (tsp_ht_insert)ht_muloa_insert; tht.search = (tsp_ht_search)ht_muloa_search; tht.remove = (tsp_ht_remove)ht_muloa_remove; tht.free = (tsp_ht_free)ht_muloa_free; for (i = 0; i < a->num_vts; i++){ ret = tsp(a, i, &dist, &tht, add_double, cmp_double); printf("tsp ret: %d, tour length with %lu as start: ", ret, TOLU(i)); print_double_arr(&dist, 1); } printf("\n"); } void run_double_graph_test(){ graph_t g; adj_lst_t a; graph_double_wts_init(&g); printf("Running a test on a double graph with a \n" "i) default hash table \n" "ii) ht_divchn_t hash table \n" "iii) ht_muloa_t hash table \n\n"); adj_lst_init(&a, &g); adj_lst_dir_build(&a, &g); print_adj_lst(&a, print_double); run_def_double_tsp(&a); run_divchn_double_tsp(&a); run_muloa_double_tsp(&a); adj_lst_free(&a); graph_free(&g); graph_double_single_vt_init(&g); printf("Running a test on a double graph with a single vertex, with a \n" "i) default hash table \n" "ii) ht_divchn_t hash table \n" "iii) ht_muloa_t hash table \n\n"); adj_lst_init(&a, &g); adj_lst_dir_build(&a, &g); print_adj_lst(&a, print_double); run_def_double_tsp(&a); run_divchn_double_tsp(&a); run_muloa_double_tsp(&a); adj_lst_free(&a); graph_free(&g); } /** Construct adjacency lists of random directed graphs with random weights. */ typedef struct{ double p; } bern_arg_t; int bern(void *arg){ bern_arg_t *b = arg; if (b->p >= C_PROB_ONE) return 1; if (b->p <= C_PROB_ZERO) return 0; if (b->p > DRAND()) return 1; return 0; } void add_dir_uint_edge(adj_lst_t *a, size_t u, size_t v, size_t wt_l, size_t wt_h, int (*bern)(void *), void *arg){ size_t rand_val = wt_l + DRAND() * (wt_h - wt_l); adj_lst_add_dir_edge(a, u, v, &rand_val, bern, arg); } void add_dir_double_edge(adj_lst_t *a, size_t u, size_t v, size_t wt_l, size_t wt_h, int (*bern)(void *), void *arg){ double rand_val = wt_l + DRAND() * (wt_h - wt_l); adj_lst_add_dir_edge(a, u, v, &rand_val, bern, arg); } void adj_lst_rand_dir_wts(adj_lst_t *a, size_t n, size_t wt_size, size_t wt_l, size_t wt_h, int (*bern)(void *), void *arg, void (*add_dir_edge)(adj_lst_t *, size_t, size_t, size_t, size_t, int (*)(void *), void *)){ size_t i, j; graph_t g; bern_arg_t arg_true; graph_base_init(&g, n, wt_size); adj_lst_init(a, &g); arg_true.p = C_PROB_ONE; for (i = 0; i < n - 1; i++){ for (j = i + 1; j < n; j++){ if (n == 2){ add_dir_edge(a, i, j, 1, 1, bern, &arg_true); add_dir_edge(a, j, i, 1, 1, bern, &arg_true); }else if (j - i == 1){ add_dir_edge(a, i, j, 1, 1, bern, &arg_true); add_dir_edge(a, j, i, wt_l, wt_h, bern, arg); }else if (i == 0 && j == n - 1){ add_dir_edge(a, i, j, wt_l, wt_h, bern, arg); add_dir_edge(a, j, i, 1, 1, bern, &arg_true); }else{ add_dir_edge(a, i, j, wt_l, wt_h, bern, arg); add_dir_edge(a, j, i, wt_l, wt_h, bern, arg); } } } graph_free(&g); } /** Tests tsp across all hash tables on random directed graphs with random size_t non-tour weights and a known tour. */ void run_rand_uint_test(int num_vts_start, int num_vts_end){ int p, i, j; int res = 1; int ret_def = -1, ret_divchn = -1, ret_muloa = -1; size_t n; size_t wt_l = 0, wt_h = C_WEIGHT_HIGH; size_t dist_def, dist_divchn, dist_muloa; size_t *rand_start = NULL; adj_lst_t a; bern_arg_t b; ht_divchn_t ht_divchn; ht_muloa_t ht_muloa; context_divchn_t context_divchn; context_muloa_t context_muloa; tsp_ht_t tht_divchn, tht_muloa; clock_t t_def, t_divchn, t_muloa; rand_start = malloc_perror(C_ITER, sizeof(size_t)); context_divchn.alpha_n = C_ALPHA_N_DIVCHN; context_divchn.log_alpha_d = C_LOG_ALPHA_D_DIVCHN; tht_divchn.ht = &ht_divchn; tht_divchn.context = &context_divchn; tht_divchn.init = (tsp_ht_init)ht_divchn_init_helper; tht_divchn.insert = (tsp_ht_insert)ht_divchn_insert; tht_divchn.search = (tsp_ht_search)ht_divchn_search; tht_divchn.remove = (tsp_ht_remove)ht_divchn_remove; tht_divchn.free = (tsp_ht_free)ht_divchn_free; context_muloa.alpha_n = C_ALPHA_N_MULOA; context_muloa.log_alpha_d = C_LOG_ALPHA_D_MULOA; context_muloa.rdc_key = NULL; tht_muloa.ht = &ht_muloa; tht_muloa.context = &context_muloa; tht_muloa.init = (tsp_ht_init)ht_muloa_init_helper; tht_muloa.insert = (tsp_ht_insert)ht_muloa_insert; tht_muloa.search = (tsp_ht_search)ht_muloa_search; tht_muloa.remove = (tsp_ht_remove)ht_muloa_remove; tht_muloa.free = (tsp_ht_free)ht_muloa_free; printf("Run a tsp test across all hash tables on random directed graphs \n" "with random size_t non-tour weights in [%lu, %lu]\n", TOLU(wt_l), TOLU(wt_h)); fflush(stdout); for (p = 0; p < C_PROBS_COUNT; p++){ b.p = C_PROBS[p]; printf("\tP[an edge is in a graph] = %.4f\n", C_PROBS[p]); for (i = num_vts_start; i <= num_vts_end; i++){ n = i; adj_lst_rand_dir_wts(&a, n, sizeof(size_t), wt_l, wt_h, bern, &b, add_dir_uint_edge); for (j = 0; j < C_ITER; j++){ rand_start[j] = RANDOM() % n; } t_def = clock(); for (j = 0; j < C_ITER; j++){ ret_def = tsp(&a, rand_start[j], &dist_def, NULL, add_uint, cmp_uint); } t_def = clock() - t_def; t_divchn = clock(); for (j = 0; j < C_ITER; j++){ ret_divchn = tsp(&a, rand_start[j], &dist_divchn, &tht_divchn, add_uint, cmp_uint); } t_divchn = clock() - t_divchn; t_muloa = clock(); for (j = 0; j < C_ITER; j++){ ret_muloa = tsp(&a, rand_start[j], &dist_muloa, &tht_muloa, add_uint, cmp_uint); } t_muloa = clock() - t_muloa; if (n == 1){ res *= (dist_def == 0 && ret_def == 0); res *= (dist_divchn == 0 && ret_divchn == 0); res *= (dist_muloa == 0 && ret_muloa == 0); }else{ res *= (dist_def == n && ret_def == 0); res *= (dist_divchn == n && ret_divchn == 0); res *= (dist_muloa == n && ret_muloa == 0); } printf("\t\tvertices: %lu, # of directed edges: %lu\n", TOLU(a.num_vts), TOLU(a.num_es)); printf("\t\t\ttsp default ht ave runtime: %.8f seconds\n" "\t\t\ttsp ht_divchn ave runtime: %.8f seconds\n" "\t\t\ttsp ht_muloa ave runtime: %.8f seconds\n", (float)t_def / C_ITER / CLOCKS_PER_SEC, (float)t_divchn / C_ITER / CLOCKS_PER_SEC, (float)t_muloa / C_ITER / CLOCKS_PER_SEC); printf("\t\t\tcorrectness: "); print_test_result(res); res = 1; adj_lst_free(&a); } } free(rand_start); rand_start = NULL; } /** Tests tsp with a default hash table on directed graphs with random size_t non-tour weights and a known tour. */ void run_def_rand_uint_test(int num_vts_start, int num_vts_end){ int i, j; int res = 1; int ret_def = -1; size_t n; size_t wt_l = 0, wt_h = C_WEIGHT_HIGH; size_t dist_def; size_t *rand_start = NULL; adj_lst_t a; bern_arg_t b; clock_t t_def; rand_start = malloc_perror(C_ITER, sizeof(size_t)); printf("Run a tsp test with a default hash table on directed graphs \n" "with random size_t non-tour weights in [%lu, %lu]\n", TOLU(wt_l), TOLU(wt_h)); fflush(stdout); b.p = C_PROB_ONE; printf("\tP[an edge is in a graph] = %.4f\n", C_PROB_ONE); for (i = num_vts_start; i <= num_vts_end; i++){ n = i; adj_lst_rand_dir_wts(&a, n, sizeof(size_t), wt_l, wt_h, bern, &b, add_dir_uint_edge); for (j = 0; j < C_ITER; j++){ rand_start[j] = RANDOM() % n; } t_def = clock(); for (j = 0; j < C_ITER; j++){ ret_def = tsp(&a, rand_start[j], &dist_def, NULL, add_uint, cmp_uint); } t_def = clock() - t_def; if (n == 1){ res *= (dist_def == 0 && ret_def == 0); }else{ res *= (dist_def == n && ret_def == 0); } printf("\t\tvertices: %lu, # of directed edges: %lu\n", TOLU(a.num_vts), TOLU(a.num_es)); printf("\t\t\ttsp default ht ave runtime: %.8f seconds\n", (float)t_def / C_ITER / CLOCKS_PER_SEC); printf("\t\t\tcorrectness: "); print_test_result(res); res = 1; adj_lst_free(&a); } free(rand_start); rand_start = NULL; } /** Tests tsp on sparse random directed graphs with random size_t non-tour weights and a known tour. */ void run_sparse_rand_uint_test(int num_vts_start, int num_vts_end){ int p, i, j; int res = 1; int ret_divchn = -1, ret_muloa = -1; size_t n; size_t wt_l = 0, wt_h = C_WEIGHT_HIGH; size_t dist_divchn, dist_muloa; size_t *rand_start = NULL; adj_lst_t a; bern_arg_t b; ht_divchn_t ht_divchn; ht_muloa_t ht_muloa; context_divchn_t context_divchn; context_muloa_t context_muloa; tsp_ht_t tht_divchn, tht_muloa; clock_t t_divchn, t_muloa; rand_start = malloc_perror(C_ITER, sizeof(size_t)); context_divchn.alpha_n = C_ALPHA_N_DIVCHN; context_divchn.log_alpha_d = C_LOG_ALPHA_D_DIVCHN; tht_divchn.ht = &ht_divchn; tht_divchn.context = &context_divchn; tht_divchn.init = (tsp_ht_init)ht_divchn_init_helper; tht_divchn.insert = (tsp_ht_insert)ht_divchn_insert; tht_divchn.search = (tsp_ht_search)ht_divchn_search; tht_divchn.remove = (tsp_ht_remove)ht_divchn_remove; tht_divchn.free = (tsp_ht_free)ht_divchn_free; context_muloa.alpha_n = C_ALPHA_N_MULOA; context_muloa.log_alpha_d = C_LOG_ALPHA_D_MULOA; context_muloa.rdc_key = NULL; tht_muloa.ht = &ht_muloa; tht_muloa.context = &context_muloa; tht_muloa.init = (tsp_ht_init)ht_muloa_init_helper; tht_muloa.insert = (tsp_ht_insert)ht_muloa_insert; tht_muloa.search = (tsp_ht_search)ht_muloa_search; tht_muloa.remove = (tsp_ht_remove)ht_muloa_remove; tht_muloa.free = (tsp_ht_free)ht_muloa_free; printf("Run a tsp test on sparse random directed graphs with random " "size_t non-tour weights in [%lu, %lu]\n", TOLU(wt_l), TOLU(wt_h)); fflush(stdout); for (p = 0; p < C_SPARSE_PROBS_COUNT; p++){ b.p = C_SPARSE_PROBS[p]; printf("\tP[an edge is in a graph] = %.4f\n", C_SPARSE_PROBS[p]); for (i = num_vts_start; i <= num_vts_end; i++){ n = i; adj_lst_rand_dir_wts(&a, n, sizeof(size_t), wt_l, wt_h, bern, &b, add_dir_uint_edge); for (j = 0; j < C_ITER; j++){ rand_start[j] = RANDOM() % n; } t_divchn = clock(); for (j = 0; j < C_ITER; j++){ ret_divchn = tsp(&a, rand_start[j], &dist_divchn, &tht_divchn, add_uint, cmp_uint); } t_divchn = clock() - t_divchn; t_muloa = clock(); for (j = 0; j < C_ITER; j++){ ret_muloa = tsp(&a, rand_start[j], &dist_muloa, &tht_muloa, add_uint, cmp_uint); } t_muloa = clock() - t_muloa; if (n == 1){ res *= (dist_divchn == 0 && ret_divchn == 0); res *= (dist_muloa == 0 && ret_muloa == 0); }else{ res *= (dist_divchn == n && ret_divchn == 0); res *= (dist_muloa == n && ret_muloa == 0); } printf("\t\tvertices: %lu, # of directed edges: %lu\n", TOLU(a.num_vts), TOLU(a.num_es)); printf("\t\t\ttsp ht_divchn ave runtime: %.8f seconds\n" "\t\t\ttsp ht_muloa ave runtime: %.8f seconds\n", (float)t_divchn / C_ITER / CLOCKS_PER_SEC, (float)t_muloa / C_ITER / CLOCKS_PER_SEC); printf("\t\t\tcorrectness: "); print_test_result(res); res = 1; adj_lst_free(&a); } } free(rand_start); rand_start = NULL; } /** Printing functions. */ void print_uint(const void *a){ printf("%lu ", TOLU(*(size_t *)a)); } void print_double(const void *a){ printf("%.2f ", *(double *)a); } void print_adj_lst(const adj_lst_t *a, void (*print_wt)(const void *)){ const char *p = NULL, *p_start = NULL, *p_end = NULL; size_t i; printf("\tvertices: \n"); for (i = 0; i < a->num_vts; i++){ printf("\t%lu : ", TOLU(i)); p_start = a->vt_wts[i]->elts; p_end = p_start + a->vt_wts[i]->num_elts * a->pair_size; for (p = p_start; p != p_end; p += a->pair_size){ printf("%lu ", TOLU(*(const size_t *)p)); } printf("\n"); } if (a->wt_size > 0 && print_wt != NULL){ printf("\tweights: \n"); for (i = 0; i < a->num_vts; i++){ printf("\t%lu : ", TOLU(i)); p_start = a->vt_wts[i]->elts; p_end = p_start + a->vt_wts[i]->num_elts * a->pair_size; for (p = p_start; p != p_end; p += a->pair_size){ print_wt(p + a->offset); } printf("\n"); } } } void print_uint_arr(const size_t *arr, size_t n){ size_t i; for (i = 0; i < n; i++){ printf("%lu ", TOLU(arr[i])); } printf("\n"); } void print_double_arr(const double *arr, size_t n){ size_t i; for (i = 0; i < n; i++){ printf("%.2f ", arr[i]); } printf("\n"); } void print_test_result(int res){ if (res){ printf("SUCCESS\n"); }else{ printf("FAILURE\n"); } } void fprintf_stderr_exit(const char *s, int line){ fprintf(stderr, "%s in %s at line %d\n", s, __FILE__, line); exit(EXIT_FAILURE); } int main(int argc, char *argv[]){ int i; size_t *args = NULL; RGENS_SEED(); if (argc > C_ARGC_MAX){ fprintf(stderr, "USAGE:\n%s", C_USAGE); exit(EXIT_FAILURE); } args = malloc_perror(C_ARGC_MAX - 1, sizeof(size_t)); memcpy(args, C_ARGS_DEF, (C_ARGC_MAX - 1) * sizeof(size_t)); for (i = 1; i < argc; i++){ args[i - 1] = atoi(argv[i]); } if (args[0] < 1 || args[0] > C_FULL_BIT - 1 || args[1] < 1 || args[1] > C_FULL_BIT - 1 || args[2] < 1 || args[2] > C_FULL_BIT - 1 || args[3] < 1 || args[3] > C_FULL_BIT - 1 || args[4] < 1 || args[4] > C_SPARSE_GRAPH_V_MAX || args[5] < 1 || args[5] > C_SPARSE_GRAPH_V_MAX || args[0] > args[1] || args[2] > args[3] || args[4] > args[5] || args[6] > 1 || args[7] > 1 || args[8] > 1 || args[9] > 1){ fprintf(stderr, "USAGE:\n%s", C_USAGE); exit(EXIT_FAILURE); } if (args[6]){ run_uint_graph_test(); run_double_graph_test(); } if (args[7]) run_rand_uint_test(args[0], args[1]); if (args[8]) run_def_rand_uint_test(args[2], args[3]); if (args[9]) run_sparse_rand_uint_test(args[4], args[5]); free(args); args = NULL; return 0; }
alfin3/graph-algorithms
graph-algorithms/dijkstra/dijkstra.h
/** dijkstra.h Declarations of accessible functions for running Dijkstra's algorithm on graphs with generic integer vertices, generic non-negative weights and a hash table parameter. The hash table parameter specifies a hash table used for in-heap operations, and enables the optimization of space and time resources associated with heap operations in Dijkstra's algorithm by choice of a hash table and its load factor upper bound. If NULL is passed as a hash table parameter value, a default hash table is used, which contains an index array with a count that is equal to the number of vertices in the graph. If E >> V, a default hash table may provide speed advantages by avoiding the computation of hash values. If V is large and the graph is sparse, a non-default hash table may provide space advantages. The effective type of every element in the prev array is of the integer type used to represent vertices. The value of every element is set by the algorithm to the value of the previous vertex. If the block pointed to by prev has no declared type then the algorithm sets the effective type of every element to the integer type used to represent vertices by writing a value of the type, including a special value for unreached vertices. A distance value in the dist array is only set if the corresponding vertex was reached, as indicated by the prev array, in which case it is guaranteed that the distance object representation is not a trap representation. An element corresponding to a not reached vertex, as indicated by the prev array, may be a trap representation. However, if distances are of an integer type and the dist array is allocated with calloc, then for any integer type the representation with all zero bits is 0 integer value under C99 and C11 (6.2.6.2), and it is safe to read such a representation even if the value was not set by the algorithm. The implementation only uses integer and pointer operations. Given parameter values within the specified ranges, the implementation provides an error message and an exit is executed if an integer overflow is attempted or an allocation is not completed due to insufficient resources. The behavior outside the specified parameter ranges is undefined. The implementation does not use stdint.h and is portable under C89/C90 and C99. */ #ifndef DIJKSTRA_H #define DIJKSTRA_H #include <stddef.h> #include "graph.h" /** Dijkstra hash table parameter struct, pointing to the hash table op helpers, pre-defined in each hash table. */ struct dijkstra_ht{ void *ht; size_t alpha_n; size_t log_alpha_d; void (*init)(void *, size_t, size_t, size_t, size_t, size_t, int (*)(const void *, const void *), size_t (*)(const void *), void (*)(void *), void (*)(void *)); void (*align)(void *, size_t); void (*insert)(void *, const void *, const void *); void *(*search)(const void *, const void *); void (*remove)(void *, const void *, void *); void (*free)(void *); }; /** Computes and copies the shortest distances from start to the array pointed to by dist, and the previous vertices to the array pointed to by prev, with the number of vertices as the special value in the prev array for unreached vertices. a : pointer to an adjacency list with at least one vertex start : start vertex for running the algorithm dist : pointer to a preallocated array with the count of elements equal to the number of vertices in the adjacency list; each element is of size wt_size (wt_size block) that equals to the size of a weight in the adjacency list; if the block pointed to by dist has no declared type then dijkstra sets the effective type of each element corresponding to a reached vertex to the type of a weight in the adjacency list by writing a value of the type; if distances are of an integer type and the block was allocated with calloc then under C99 and C11 each element corresponding to an unreached vertex can be safely read as the integer type and will represent 0 value prev : pointer to a preallocated array with the count equal to the number of vertices in the adjacency list; each element is of size vt_size (vt_size block) that equals to the size of the integer type used to represent vertices in the adjacency list; if the block pointed to by prev has no declared type then it is guaranteed that dijkstra sets the effective type of every element to the integer type used to represent vertices by writing a value of the type zero_wt : pointer to a block of size wt_size with a zero value of the type used to represent distances daht : - NULL pointer, if a default hash table is used for in-heap operations; a default hash table contains an index array with a count that is equal to the number of vertices - a pointer to a set of parameters specifying a hash table used for in-heap operations read_vt : reads the integer value of the type used to represent vertices from the vt_size block pointed to by the argument and returns a size_t value write_vt : writes the integer value of the second argument to the vt_size block pointed to by the first argument as a value of the integer type used to represent vertices at_vt : returns a pointer to the element in the array pointed to by the first argument at the index pointed to by the second argument; the first argument points to the integer type used to represent vertices and is not dereferenced; the second argument points to a value of the integer type used to represent vertices and is dereferenced cmp_vt : returns 0 iff the element pointed to by the first argument is equal to the element pointed to by the second argument; each argument points to a value of the integer type used to represent vertices cmp_wt : comparison function which returns a negative integer value if the weight value pointed to by the first argument is less than the weight value pointed to by the second, a positive integer value if the weight value pointed to by the first argument is greater than the weight value pointed to by the second, and zero integer value if the two weight values are equal add_wt : addition function which copies the sum of the weight values pointed to by the second and third arguments to the preallocated wt_size block pointed to by the first argument; if the distribution of weights can result in an overflow, the user may include an overflow test in the function or use a provided _perror-suffixed function */ void dijkstra(const struct adj_lst *a, size_t start, void *dist, void *prev, const void *wt_zero, const struct dijkstra_ht *daht, size_t (*read_vt)(const void *), void (*write_vt)(void *, size_t), void *(*at_vt)(const void *, const void *), int (*cmp_vt)(const void *, const void *), int (*cmp_wt)(const void *, const void *), void (*add_wt)(void *, const void *, const void *)); #endif
alfin3/graph-algorithms
graph-algorithms/prim/prim-test.c
/** prim-test.c Tests of Prim's algorithm with a hash table parameter across i) default, division-based and multiplication-based hash tables, ii) vertex types, and iii) edge weight types. The following command line arguments can be used to customize tests: prim-test: - [0, ushort width) : n for 2**n vertices in the smallest graph - [0, ushort width) : n for 2**n vertices in the largest graph - [0, 1] : small graph test on/off - [0, 1] : test on random graphs with random weights on/off usage examples: ./prim-test ./prim-test 10 12 ./prim-test 13 13 0 1 prim-test can be run with any subset of command line arguments in the above-defined order. If the (i + 1)th argument is specified then the ith argument must be specified for i >= 0. Default values are used for the unspecified arguments according to the C_ARGS_DEF array. The implementation of tests does not use stdint.h and is portable under C89/C90 and C99. The tests require that: - size_t and clock_t are convertible to double - size_t can represent values upto 65535 for default values, and upto USHRT_MAX (>= 65535) otherwise, - the widths of the unsigned integral types are less than 2040 and even. TODO: add portable size_t printing */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <limits.h> #include <time.h> #include "prim.h" #include "heap.h" #include "ht-divchn.h" #include "ht-muloa.h" #include "graph.h" #include "stack.h" #include "utilities-mem.h" #include "utilities-mod.h" #include "utilities-lim.h" /** Generate random numbers in a portable way for test purposes only; rand() in the Linux C Library uses the same generator as random(), which may not be the case on older rand() implementations, and on current implementations on different systems. */ #define RGENS_SEED() do{srand(time(NULL));}while (0) #define RANDOM() (rand()) /* [0, RAND_MAX] */ #define DRAND() ((double)rand() / RAND_MAX) /* [0.0, 1.0] */ #define TOLU(i) ((unsigned long int)(i)) /* printing size_t under C89/C90 */ /* input handling */ const char *C_USAGE = "prim-test \n" "[0, ushort width) : n for 2**n vertices in smallest graph\n" "[0, ushort width) : n for 2**n vertices in largest graph\n" "[0, 1] : small graph test on/off\n" "[0, 1] : random graphs with random weights test on/off\n"; const int C_ARGC_ULIMIT = 5; const size_t C_ARGS_DEF[4] = {6u, 9u, 1u, 1u}; /* hash table load factor upper bounds */ const size_t C_ALPHA_N_DIVCHN = 1u; const size_t C_LOG_ALPHA_D_DIVCHN = 0u; const size_t C_ALPHA_N_MULOA = 13107u; const size_t C_LOG_ALPHA_D_MULOA = 15u; /* small graph tests */ const size_t C_NUM_VTS = 5u; const size_t C_NUM_ES = 4u; const unsigned short C_USHORT_U[4] = {0u, 0u, 0u, 1u}; const unsigned short C_USHORT_V[4] = {1u, 2u, 3u, 3u}; const unsigned short C_USHORT_WTS[4] = {4u, 3u, 2u, 1u}; const unsigned int C_UINT_U[4] = {0u, 0u, 0u, 1u}; const unsigned int C_UINT_V[4] = {1u, 2u, 3u, 3u}; const unsigned int C_UINT_WTS[4] = {4u, 3u, 2u, 1u}; const unsigned long C_ULONG_U[4] = {0u, 0u, 0u, 1u}; const unsigned long C_ULONG_V[4] = {1u, 2u, 3u, 3u}; const unsigned long C_ULONG_WTS[4] = {4u, 3u, 2u, 1u}; const size_t C_SZ_U[4] = {0u, 0u, 0u, 1u}; const size_t C_SZ_V[4] = {1u, 2u, 3u, 3u}; const size_t C_SZ_WTS[4] = {4u, 3u, 2u, 1u}; const double C_DOUBLE_WTS[4] = {4.0, 3.0, 2.0, 1.0}; /* small graph initialization ops */ void init_ushort_ushort(struct graph *g); void init_ushort_uint(struct graph *g); void init_ushort_ulong(struct graph *g); void init_ushort_sz(struct graph *g); void init_ushort_double(struct graph *g); void init_uint_ushort(struct graph *g); void init_uint_uint(struct graph *g); void init_uint_ulong(struct graph *g); void init_uint_sz(struct graph *g); void init_uint_double(struct graph *g); void init_ulong_ushort(struct graph *g); void init_ulong_uint(struct graph *g); void init_ulong_ulong(struct graph *g); void init_ulong_sz(struct graph *g); void init_ulong_double(struct graph *g); void init_sz_ushort(struct graph *g); void init_sz_uint(struct graph *g); void init_sz_ulong(struct graph *g); void init_sz_sz(struct graph *g); void init_sz_double(struct graph *g); const size_t C_FN_VT_COUNT = 4u; const size_t C_FN_WT_COUNT = 5u; const size_t C_FN_INTEGRAL_WT_COUNT = 4u; void (* const C_INIT_GRAPH[4][5])(struct graph *) ={ {init_ushort_ushort, init_ushort_uint, init_ushort_ulong, init_ushort_sz, init_ushort_double}, {init_uint_ushort, init_uint_uint, init_uint_ulong, init_uint_sz, init_uint_double}, {init_ulong_ushort, init_ulong_uint, init_ulong_ulong, init_ulong_sz, init_ulong_double}, {init_sz_ushort, init_sz_uint, init_sz_ulong, init_sz_sz, init_sz_double}}; /* vertex ops */ size_t (* const C_READ_VT[4])(const void *) ={ graph_read_ushort, graph_read_uint, graph_read_ulong, graph_read_sz}; void (* const C_WRITE_VT[4])(void *, size_t) ={ graph_write_ushort, graph_write_uint, graph_write_ulong, graph_write_sz}; void *(* const C_AT_VT[4])(const void *, const void *) ={ graph_at_ushort, graph_at_uint, graph_at_ulong, graph_at_sz}; int (* const C_CMP_VT[4])(const void *, const void *) ={ graph_cmpeq_ushort, graph_cmpeq_uint, graph_cmpeq_ulong, graph_cmpeq_sz}; const size_t C_VT_SIZES[4] = { sizeof(unsigned short), sizeof(unsigned int), sizeof(unsigned long), sizeof(size_t)}; const char *C_VT_TYPES[4] = {"ushort", "uint ", "ulong ", "sz "}; /* weight and print ops */ int cmp_double(const void *a, const void *b); int (* const C_CMP_WT[5])(const void *, const void *) ={ graph_cmp_ushort, graph_cmp_uint, graph_cmp_ulong, graph_cmp_sz, cmp_double}; const size_t C_WT_SIZES[5] = { sizeof(unsigned short), sizeof(unsigned int), sizeof(unsigned long), sizeof(size_t), sizeof(double)}; const char *C_WT_TYPES[5] = {"ushort", "uint ", "ulong ", "sz ", "double"}; /* random graph tests */ /* C89 (draft): USHRT_MAX >= 65535, UINT_MAX >= 65535, ULONG_MAX >= 4294967295, RAND_MAX >= 32767 */ const size_t C_RANDOM_BIT = 15u; const unsigned int C_RANDOM_MASK = 32767u; const size_t C_USHORT_BIT = PRECISION_FROM_ULIMIT(USHRT_MAX); const size_t C_USHORT_BIT_MOD = PRECISION_FROM_ULIMIT(USHRT_MAX) / 15u; const size_t C_USHORT_HALF_BIT = PRECISION_FROM_ULIMIT(USHRT_MAX) / 2u; const unsigned short C_USHORT_ULIMIT = USHRT_MAX; const unsigned short C_USHORT_LOW_MASK = ((unsigned short)-1 >> (PRECISION_FROM_ULIMIT(USHRT_MAX) / 2u)); const size_t C_UINT_BIT = PRECISION_FROM_ULIMIT(UINT_MAX); const size_t C_UINT_BIT_MOD = PRECISION_FROM_ULIMIT(UINT_MAX) / 15u; const size_t C_UINT_HALF_BIT = PRECISION_FROM_ULIMIT(UINT_MAX) / 2u; const unsigned int C_UINT_ULIMIT = UINT_MAX; const unsigned int C_UINT_LOW_MASK = ((unsigned int)-1 >> (PRECISION_FROM_ULIMIT(UINT_MAX) / 2u)); const size_t C_ULONG_BIT = PRECISION_FROM_ULIMIT(ULONG_MAX); const size_t C_ULONG_BIT_MOD = PRECISION_FROM_ULIMIT(ULONG_MAX) / 15u; const size_t C_ULONG_HALF_BIT = PRECISION_FROM_ULIMIT(ULONG_MAX) / 2u; const unsigned long C_ULONG_ULIMIT = ULONG_MAX; const unsigned long C_ULONG_LOW_MASK = ((unsigned long)-1 >> (PRECISION_FROM_ULIMIT(ULONG_MAX) / 2u)); const size_t C_SZ_BIT = PRECISION_FROM_ULIMIT((size_t)-1); const size_t C_SZ_BIT_MOD = PRECISION_FROM_ULIMIT((size_t)-1) / 15u; const size_t C_SZ_HALF_BIT = PRECISION_FROM_ULIMIT((size_t)-1) / 2u; const size_t C_SZ_ULIMIT = (size_t)-1; const size_t C_SZ_LOW_MASK = ((size_t)-1 >> (PRECISION_FROM_ULIMIT((size_t)-1) / 2u)); const size_t C_ITER = 10u; const size_t C_PROBS_COUNT = 7u; const double C_PROBS[7] = {1.000000, 0.250000, 0.062500, 0.015625, 0.003906, 0.000977, 0.000000}; /* random number generation and random graph construction */ unsigned short random_ushort(); unsigned int random_uint(); unsigned long random_ulong(); size_t random_sz(); unsigned short mul_high_ushort(unsigned short a, unsigned short b); unsigned int mul_high_uint(unsigned int a, unsigned int b); unsigned long mul_high_ulong(unsigned long a, unsigned long b); size_t mul_high_sz(size_t a, size_t b); void add_undir_ushort_edge(struct adj_lst *a, size_t u, size_t v, const void *wt_l, const void *wt_h, void (*write_vt)(void *, size_t), int (*bern)(void *), void *arg); void add_undir_uint_edge(struct adj_lst *a, size_t u, size_t v, const void *wt_l, const void *wt_h, void (*write_vt)(void *, size_t), int (*bern)(void *), void *arg); void add_undir_ulong_edge(struct adj_lst *a, size_t u, size_t v, const void *wt_l, const void *wt_h, void (*write_vt)(void *, size_t), int (*bern)(void *), void *arg); void add_undir_sz_edge(struct adj_lst *a, size_t u, size_t v, const void *wt_l, const void *wt_h, void (*write_vt)(void *, size_t), int (*bern)(void *), void *arg); void add_undir_double_edge(struct adj_lst *a, size_t u, size_t v, const void *wt_l, const void *wt_h, void (*write_vt)(void *, size_t), int (*bern)(void *), void *arg); void (* const C_ADD_UNDIR_EDGE[5])(struct adj_lst *, size_t, size_t, const void *, const void *, void (*)(void *, size_t), int (*)(void *), void *) ={ add_undir_ushort_edge, add_undir_uint_edge, add_undir_ulong_edge, add_undir_sz_edge, add_undir_double_edge}; /* value initiliazation and printing */ void set_zero_ushort(void *a); void set_zero_uint(void *a); void set_zero_ulong(void *a); void set_zero_sz(void *a); void set_zero_double(void *a); void set_test_ulimit_ushort(void *a, size_t num_vts); void set_test_ulimit_uint(void *a, size_t num_vts); void set_test_ulimit_ulong(void *a, size_t num_vts); void set_test_ulimit_sz(void *a, size_t num_vts); void set_test_ulimit_double(void *a, size_t num_vts); void sum_dist_ushort(void *dist_sum, size_t *num_dist_wraps, size_t *num_paths, size_t num_vts, size_t vt_size, const void *prev, const void *dist, size_t (*read_vt)(const void *)); void sum_dist_uint(void *dist_sum, size_t *num_dist_wraps, size_t *num_paths, size_t num_vts, size_t vt_size, const void *prev, const void *dist, size_t (*read_vt)(const void *)); void sum_dist_ulong(void *dist_sum, size_t *num_dist_wraps, size_t *num_paths, size_t num_vts, size_t vt_size, const void *prev, const void *dist, size_t (*read_vt)(const void *)); void sum_dist_sz(void *dist_sum, size_t *num_dist_wraps, size_t *num_paths, size_t num_vts, size_t vt_size, const void *prev, const void *dist, size_t (*read_vt)(const void *)); void sum_dist_double(void *dist_sum, size_t *num_dist_wraps, size_t *num_paths, size_t num_vts, size_t vt_size, const void *prev, const void *dist, size_t (*read_vt)(const void *)); void print_ushort(const void *a); void print_uint(const void *a); void print_ulong(const void *a); void print_sz(const void *a); void print_double(const void *a); void (* const C_SET_ZERO[5])(void *) ={ set_zero_ushort, set_zero_uint, set_zero_ulong, set_zero_sz, set_zero_double}; void (* const C_SET_TEST_ULIMIT[5])(void *, size_t) ={ set_test_ulimit_ushort, set_test_ulimit_uint, set_test_ulimit_ulong, set_test_ulimit_sz, set_test_ulimit_double}; void (* const C_SUM_DIST[5])(void *, size_t *, size_t *, size_t, size_t, const void *, const void *, size_t (*)(const void *)) ={ sum_dist_ushort, sum_dist_uint, sum_dist_ulong, sum_dist_sz, sum_dist_double}; void (* const C_PRINT[5])(const void *) ={ print_ushort, print_uint, print_ulong, print_sz, print_double}; /* additional operations */ void *ptr(const void *block, size_t i, size_t size); void print_arr(const void *arr, size_t size, size_t n, void (*print_elt)(const void *)); void print_prev(const struct adj_lst *a, const void *prev, void (*print_vt)(const void *)); void print_dist(const struct adj_lst *a, const void *dist, const void *prev, const void *wt_zero, size_t (*read_vt)(const void *), void (*print_wt)(const void *)); void print_adj_lst(const struct adj_lst *a, void (*print_vt)(const void *), void (*print_wt)(const void *)); void print_test_result(int res); /** Initialize small graphs across vertex and weight types. */ void init_ushort_ushort(struct graph *g){ graph_base_init(g, C_NUM_VTS, sizeof(unsigned short), sizeof(unsigned short)); g->num_es = C_NUM_ES; g->u = (unsigned short *)C_USHORT_U; g->v = (unsigned short *)C_USHORT_V; g->wts = (unsigned short *)C_USHORT_WTS; } void init_ushort_uint(struct graph *g){ graph_base_init(g, C_NUM_VTS, sizeof(unsigned short), sizeof(unsigned int)); g->num_es = C_NUM_ES; g->u = (unsigned short *)C_USHORT_U; g->v = (unsigned short *)C_USHORT_V; g->wts = (unsigned int *)C_UINT_WTS; } void init_ushort_ulong(struct graph *g){ graph_base_init(g, C_NUM_VTS, sizeof(unsigned short), sizeof(unsigned long)); g->num_es = C_NUM_ES; g->u = (unsigned short *)C_USHORT_U; g->v = (unsigned short *)C_USHORT_V; g->wts = (unsigned long *)C_ULONG_WTS; } void init_ushort_sz(struct graph *g){ graph_base_init(g, C_NUM_VTS, sizeof(unsigned short), sizeof(size_t)); g->num_es = C_NUM_ES; g->u = (unsigned short *)C_USHORT_U; g->v = (unsigned short *)C_USHORT_V; g->wts = (size_t *)C_SZ_WTS; } void init_ushort_double(struct graph *g){ graph_base_init(g, C_NUM_VTS, sizeof(unsigned short), sizeof(double)); g->num_es = C_NUM_ES; g->u = (unsigned short *)C_USHORT_U; g->v = (unsigned short *)C_USHORT_V; g->wts = (double *)C_DOUBLE_WTS; } void init_uint_ushort(struct graph *g){ graph_base_init(g, C_NUM_VTS, sizeof(unsigned int), sizeof(unsigned short)); g->num_es = C_NUM_ES; g->u = (unsigned int *)C_UINT_U; g->v = (unsigned int *)C_UINT_V; g->wts = (unsigned short *)C_USHORT_WTS; } void init_uint_uint(struct graph *g){ graph_base_init(g, C_NUM_VTS, sizeof(unsigned int), sizeof(unsigned int)); g->num_es = C_NUM_ES; g->u = (unsigned int *)C_UINT_U; g->v = (unsigned int *)C_UINT_V; g->wts = (unsigned int *)C_UINT_WTS; } void init_uint_ulong(struct graph *g){ graph_base_init(g, C_NUM_VTS, sizeof(unsigned int), sizeof(unsigned long)); g->num_es = C_NUM_ES; g->u = (unsigned int *)C_UINT_U; g->v = (unsigned int *)C_UINT_V; g->wts = (unsigned long *)C_ULONG_WTS; } void init_uint_sz(struct graph *g){ graph_base_init(g, C_NUM_VTS, sizeof(unsigned int), sizeof(size_t)); g->num_es = C_NUM_ES; g->u = (unsigned int *)C_UINT_U; g->v = (unsigned int *)C_UINT_V; g->wts = (size_t *)C_SZ_WTS; } void init_uint_double(struct graph *g){ graph_base_init(g, C_NUM_VTS, sizeof(unsigned int), sizeof(double)); g->num_es = C_NUM_ES; g->u = (unsigned int *)C_UINT_U; g->v = (unsigned int *)C_UINT_V; g->wts = (double *)C_DOUBLE_WTS; } void init_ulong_ushort(struct graph *g){ graph_base_init(g, C_NUM_VTS, sizeof(unsigned long), sizeof(unsigned short)); g->num_es = C_NUM_ES; g->u = (unsigned long *)C_ULONG_U; g->v = (unsigned long *)C_ULONG_V; g->wts = (unsigned short *)C_USHORT_WTS; } void init_ulong_uint(struct graph *g){ graph_base_init(g, C_NUM_VTS, sizeof(unsigned long), sizeof(unsigned int)); g->num_es = C_NUM_ES; g->u = (unsigned long *)C_ULONG_U; g->v = (unsigned long *)C_ULONG_V; g->wts = (unsigned int *)C_UINT_WTS; } void init_ulong_ulong(struct graph *g){ graph_base_init(g, C_NUM_VTS, sizeof(unsigned long), sizeof(unsigned long)); g->num_es = C_NUM_ES; g->u = (unsigned long *)C_ULONG_U; g->v = (unsigned long *)C_ULONG_V; g->wts = (unsigned long *)C_ULONG_WTS; } void init_ulong_sz(struct graph *g){ graph_base_init(g, C_NUM_VTS, sizeof(unsigned long), sizeof(size_t)); g->num_es = C_NUM_ES; g->u = (unsigned long *)C_ULONG_U; g->v = (unsigned long *)C_ULONG_V; g->wts = (size_t *)C_SZ_WTS; } void init_ulong_double(struct graph *g){ graph_base_init(g, C_NUM_VTS, sizeof(unsigned long), sizeof(double)); g->num_es = C_NUM_ES; g->u = (unsigned long *)C_ULONG_U; g->v = (unsigned long *)C_ULONG_V; g->wts = (double *)C_DOUBLE_WTS; } void init_sz_ushort(struct graph *g){ graph_base_init(g, C_NUM_VTS, sizeof(size_t), sizeof(unsigned short)); g->num_es = C_NUM_ES; g->u = (size_t *)C_SZ_U; g->v = (size_t *)C_SZ_V; g->wts = (unsigned short *)C_USHORT_WTS; } void init_sz_uint(struct graph *g){ graph_base_init(g, C_NUM_VTS, sizeof(size_t), sizeof(unsigned int)); g->num_es = C_NUM_ES; g->u = (size_t *)C_SZ_U; g->v = (size_t *)C_SZ_V; g->wts = (unsigned int *)C_UINT_WTS; } void init_sz_ulong(struct graph *g){ graph_base_init(g, C_NUM_VTS, sizeof(size_t), sizeof(unsigned long)); g->num_es = C_NUM_ES; g->u = (size_t *)C_SZ_U; g->v = (size_t *)C_SZ_V; g->wts = (unsigned long *)C_ULONG_WTS; } void init_sz_sz(struct graph *g){ graph_base_init(g, C_NUM_VTS, sizeof(size_t), sizeof(size_t)); g->num_es = C_NUM_ES; g->u = (size_t *)C_SZ_U; g->v = (size_t *)C_SZ_V; g->wts = (size_t *)C_SZ_WTS; } void init_sz_double(struct graph *g){ graph_base_init(g, C_NUM_VTS, sizeof(size_t), sizeof(double)); g->num_es = C_NUM_ES; g->u = (size_t *)C_SZ_U; g->v = (size_t *)C_SZ_V; g->wts = (double *)C_DOUBLE_WTS; } /** Run a test on small graphs across vertex and weight types. */ int cmp_double(const void *a, const void *b){ return ((*(const double *)a > *(const double *)b) - (*(const double *)a < *(const double *)b)); } void run_small_graph_test(){ size_t i, j, k, l; void *wt_zero = NULL; void *dist_def = NULL, *dist_divchn = NULL, *dist_muloa = NULL; void *prev_def = NULL, *prev_divchn = NULL, *prev_muloa = NULL; struct graph g; struct adj_lst a; struct ht_divchn ht_divchn; struct ht_muloa ht_muloa; struct prim_ht pmht_divchn, pmht_muloa; pmht_divchn.ht = &ht_divchn; pmht_divchn.alpha_n = C_ALPHA_N_DIVCHN; pmht_divchn.log_alpha_d = C_LOG_ALPHA_D_DIVCHN; pmht_divchn.init = ht_divchn_init_helper; pmht_divchn.align = ht_divchn_align_helper; pmht_divchn.insert = ht_divchn_insert_helper; pmht_divchn.search = ht_divchn_search_helper; pmht_divchn.remove = ht_divchn_remove_helper; pmht_divchn.free = ht_divchn_free_helper; pmht_muloa.ht = &ht_muloa; pmht_muloa.alpha_n = C_ALPHA_N_MULOA; pmht_muloa.log_alpha_d = C_LOG_ALPHA_D_MULOA; pmht_muloa.init = ht_muloa_init_helper; pmht_muloa.align = ht_muloa_align_helper; pmht_muloa.insert = ht_muloa_insert_helper; pmht_muloa.search = ht_muloa_search_helper; pmht_muloa.remove = ht_muloa_remove_helper; pmht_muloa.free = ht_muloa_free_helper; printf("Run a prim test on an undirected graph across vertex and" " weight types, with a\n" "i) default hash table (index array)\n" "ii) ht_divchn hash table\n" "iii) ht_muloa hash table\n\n"); for (i = 0; i < C_NUM_VTS; i++){ printf("\tstart vertex: %lu\n", TOLU(i)); for (j = 0; j < C_FN_VT_COUNT; j++){ printf("\t\tvertex type: %s\n", C_VT_TYPES[j]); for (k = 0; k < C_FN_WT_COUNT; k++){ printf("\t\t\tweight type: %s\n", C_WT_TYPES[k]); C_INIT_GRAPH[j][k](&g); adj_lst_base_init(&a, &g); adj_lst_undir_build(&a, &g, C_READ_VT[j]); /* no declared type after realloc; new eff. type to be acquired */ wt_zero = realloc_perror(wt_zero, 1, a.wt_size); prev_def = realloc_perror(prev_def, a.num_vts, a.vt_size); prev_divchn = realloc_perror(prev_divchn, a.num_vts, a.vt_size); prev_muloa = realloc_perror(prev_muloa, a.num_vts, a.vt_size); dist_def = realloc_perror(dist_def, a.num_vts, a.wt_size); dist_divchn = realloc_perror(dist_divchn, a.num_vts, a.wt_size); dist_muloa = realloc_perror(dist_muloa, a.num_vts, a.wt_size); C_SET_ZERO[k](wt_zero); for (l = 0; l < a.num_vts; l++){ /* avoid trap representations in tests */ C_SET_ZERO[k](ptr(dist_def, l, a.wt_size)); C_SET_ZERO[k](ptr(dist_divchn, l, a.wt_size)); C_SET_ZERO[k](ptr(dist_muloa, l, a.wt_size)); } prim(&a, i, dist_def, prev_def, wt_zero, NULL, C_READ_VT[j], C_WRITE_VT[j], C_AT_VT[j], C_CMP_VT[j], C_CMP_WT[k]); prim(&a, i, dist_divchn, prev_divchn, wt_zero, &pmht_divchn, C_READ_VT[j], C_WRITE_VT[j], C_AT_VT[j], C_CMP_VT[j], C_CMP_WT[k]); prim(&a, i, dist_muloa, prev_muloa, wt_zero, &pmht_muloa, C_READ_VT[j], C_WRITE_VT[j], C_AT_VT[j], C_CMP_VT[j], C_CMP_WT[k]); adj_lst_free(&a); printf("\t\t\t\tdefault dist: "); print_dist(&a, dist_def, prev_def, wt_zero, C_READ_VT[j], C_PRINT[k]); printf("\n"); printf("\t\t\t\tdivchn dist: "); print_dist(&a, dist_divchn, prev_divchn, wt_zero, C_READ_VT[j], C_PRINT[k]); printf("\n"); printf("\t\t\t\tmuloa dist: "); print_dist(&a, dist_muloa, prev_muloa, wt_zero, C_READ_VT[j], C_PRINT[k]); printf("\n"); printf("\t\t\t\tdefault prev: "); print_prev(&a, prev_def, C_PRINT[j]); printf("\n"); printf("\t\t\t\tdivchn prev: "); print_prev(&a, prev_divchn, C_PRINT[j]); printf("\n"); printf("\t\t\t\tmuloa prev: "); print_prev(&a, prev_muloa, C_PRINT[j]); printf("\n"); } } } printf("\n"); free(wt_zero); free(dist_def); free(dist_divchn); free(dist_muloa); free(prev_def); free(prev_divchn); free(prev_muloa); wt_zero = NULL; dist_def = NULL; dist_divchn = NULL; dist_muloa = NULL; prev_def = NULL; prev_divchn = NULL; prev_muloa = NULL; } /** Construct adjacency lists of random undirected graphs with random weights across vertex and weight types. A function with the add_undir_ prefix adds a (u, v) edge to an adjacency list of a weighted graph, preinitialized with at least adj_lst_base_init and with the number of vertices n greater or equal to 1. An edge (u, v), where u < n nad v < n, is added with the Bernoulli distribution according to the bern and arg parameter values. wt_l and wt_h point to wt_size blocks with values l and h of the type used to represent weights in the adjacency list, and l is less or equal to h. If (u, v) is added, a random weight in [l, h) is chosen for the edge. adj_lst_rand_undir_wts builds a random adjacency list with one of the above functions as a parameter value. g points to a graph preinitialized with graph_base_init with at least one vertex. a points to a preallocated block of size sizeof(struct adj_lst). */ struct bern_arg{ double p; }; int bern(void *arg){ struct bern_arg *b = arg; if (b->p >= 1.0) return 1; if (b->p <= 0.0) return 0; if (b->p > DRAND()) return 1; return 0; } void add_undir_ushort_edge(struct adj_lst *a, size_t u, size_t v, const void *wt_l, const void *wt_h, void (*write_vt)(void *, size_t), int (*bern)(void *), void *arg){ unsigned short rand_val = *(unsigned short *)wt_l + mul_high_ushort(random_ushort(), (*(unsigned short *)wt_h - *(unsigned short *)wt_l)); adj_lst_add_undir_edge(a, u, v, &rand_val, write_vt, bern, arg); } void add_undir_uint_edge(struct adj_lst *a, size_t u, size_t v, const void *wt_l, const void *wt_h, void (*write_vt)(void *, size_t), int (*bern)(void *), void *arg){ unsigned int rand_val = *(unsigned int *)wt_l + mul_high_uint(random_uint(), (*(unsigned int *)wt_h - *(unsigned int *)wt_l)); adj_lst_add_undir_edge(a, u, v, &rand_val, write_vt, bern, arg); } void add_undir_ulong_edge(struct adj_lst *a, size_t u, size_t v, const void *wt_l, const void *wt_h, void (*write_vt)(void *, size_t), int (*bern)(void *), void *arg){ unsigned long rand_val = *(unsigned long *)wt_l + mul_high_ulong(random_ulong(), (*(unsigned long *)wt_h - *(unsigned long *)wt_l)); adj_lst_add_undir_edge(a, u, v, &rand_val, write_vt, bern, arg); } void add_undir_sz_edge(struct adj_lst *a, size_t u, size_t v, const void *wt_l, const void *wt_h, void (*write_vt)(void *, size_t), int (*bern)(void *), void *arg){ size_t rand_val = *(size_t *)wt_l + mul_high_sz(random_sz(), (*(size_t *)wt_h - *(size_t *)wt_l)); adj_lst_add_undir_edge(a, u, v, &rand_val, write_vt, bern, arg); } void add_undir_double_edge(struct adj_lst *a, size_t u, size_t v, const void *wt_l, const void *wt_h, void (*write_vt)(void *, size_t), int (*bern)(void *), void *arg){ double rand_val = *(double *)wt_l + DRAND() * (*(double *)wt_h - *(double *)wt_l); adj_lst_add_undir_edge(a, u, v, &rand_val, write_vt, bern, arg); } void adj_lst_rand_undir_wts(const struct graph *g, struct adj_lst *a, const void *wt_l, const void *wt_h, void (*write_vt)(void *, size_t), int (*bern)(void *), void *arg, void (*add_undir_edge)(struct adj_lst *, size_t, size_t, const void *, const void *, void (*)(void *, size_t), int (*)(void *), void *)){ size_t i, j; adj_lst_base_init(a, g); for (i = 0; i < a->num_vts - 1; i++){ for (j = i + 1; j < a->num_vts; j++){ add_undir_edge(a, i, j, wt_l, wt_h, write_vt, bern, arg); } } } /** Run a test on random undirected graphs with random weights, across edge weight types, vertex types, as well as default, division-based and multiplication-based hash tables. */ void run_rand_test(size_t log_start, size_t log_end){ int res = 1; size_t p, i, j, k, l; size_t num_vts; size_t vt_size; size_t wt_size; size_t num_dwraps_def, num_dwraps_divchn, num_dwraps_muloa; size_t num_paths_def, num_paths_divchn, num_paths_muloa; size_t *rand_start = NULL; void *wt_l = NULL, *wt_h = NULL; void *wt_zero = NULL; void *dsum_def = NULL, *dsum_divchn = NULL, *dsum_muloa = NULL; void *dist_def = NULL, *dist_divchn = NULL, *dist_muloa = NULL; void *prev_def = NULL, *prev_divchn = NULL, *prev_muloa = NULL; struct graph g; struct adj_lst a; struct bern_arg b; struct ht_divchn ht_divchn; struct ht_muloa ht_muloa; struct prim_ht pmht_divchn, pmht_muloa; clock_t t_def, t_divchn, t_muloa; rand_start = malloc_perror(C_ITER, sizeof(size_t)); pmht_divchn.ht = &ht_divchn; pmht_divchn.alpha_n = C_ALPHA_N_DIVCHN; pmht_divchn.log_alpha_d = C_LOG_ALPHA_D_DIVCHN; pmht_divchn.init = ht_divchn_init_helper; pmht_divchn.align = ht_divchn_align_helper; pmht_divchn.insert = ht_divchn_insert_helper; pmht_divchn.search = ht_divchn_search_helper; pmht_divchn.remove = ht_divchn_remove_helper; pmht_divchn.free = ht_divchn_free_helper; pmht_muloa.ht = &ht_muloa; pmht_muloa.alpha_n = C_ALPHA_N_MULOA; pmht_muloa.log_alpha_d = C_LOG_ALPHA_D_MULOA; pmht_muloa.init = ht_muloa_init_helper; pmht_muloa.align = ht_muloa_align_helper; pmht_muloa.insert = ht_muloa_insert_helper; pmht_muloa.search = ht_muloa_search_helper; pmht_muloa.remove = ht_muloa_remove_helper; pmht_muloa.free = ht_muloa_free_helper; printf("Run a prim test on random undirected graphs with random weights" " across vertex and weight types;\nthe runtime is averaged" " over %lu runs from random start vertices\n", TOLU(C_ITER)); fflush(stdout); for (p = 0; p < C_PROBS_COUNT; p++){ b.p = C_PROBS[p]; printf("\tP[an edge is in a graph] = %.4f\n", C_PROBS[p]); for (k = 0; k < C_FN_WT_COUNT; k++){ wt_size = C_WT_SIZES[k]; wt_l = realloc_perror(wt_l, 2, wt_size); wt_h = ptr(wt_l, 1, wt_size); C_SET_ZERO[k](wt_l); C_SET_TEST_ULIMIT[k](wt_h, pow_two_perror(log_end)); printf("\t%s range: [", C_WT_TYPES[k]); C_PRINT[k](wt_l); printf(", "); C_PRINT[k](wt_h); printf(")\n"); } for (i = log_start; i <= log_end; i++){ num_vts = pow_two_perror(i); /* 0 < n */ printf("\t\t# vertices: %lu\n", TOLU(num_vts)); for (j = 0; j < C_FN_VT_COUNT; j++){ for (k = 0; k < C_FN_WT_COUNT; k++){ vt_size = C_VT_SIZES[j]; wt_size = C_WT_SIZES[k]; /* no declared type after realloc; new eff. type to be acquired */ wt_l = realloc_perror(wt_l, 3, wt_size); wt_h = ptr(wt_l, 1, wt_size); wt_zero = ptr(wt_l, 2, wt_size); dsum_def = realloc_perror(dsum_def, 1, wt_size); dsum_divchn = realloc_perror(dsum_divchn, 1, wt_size); dsum_muloa = realloc_perror(dsum_muloa, 1, wt_size); prev_def = realloc_perror(prev_def, num_vts, vt_size); prev_divchn = realloc_perror(prev_divchn, num_vts, vt_size); prev_muloa = realloc_perror(prev_muloa, num_vts, vt_size); dist_def = realloc_perror(dist_def, num_vts, wt_size); dist_divchn = realloc_perror(dist_divchn, num_vts, wt_size); dist_muloa = realloc_perror(dist_muloa, num_vts, wt_size); C_SET_ZERO[k](wt_l); C_SET_TEST_ULIMIT[k](wt_h, pow_two_perror(log_end)); C_SET_ZERO[k](wt_zero); for (l = 0; l < num_vts; l++){ /* avoid trap representations in tests */ C_SET_ZERO[k](ptr(dist_def, l, wt_size)); C_SET_ZERO[k](ptr(dist_divchn, l, wt_size)); C_SET_ZERO[k](ptr(dist_muloa, l, wt_size)); } graph_base_init(&g, num_vts, vt_size, wt_size); adj_lst_rand_undir_wts(&g, &a, wt_l, wt_h, C_WRITE_VT[j], bern, &b, C_ADD_UNDIR_EDGE[k]); for (l = 0; l < C_ITER; l++){ rand_start[l] = mul_high_sz(random_sz(), num_vts); } t_def = clock(); for (l = 0; l < C_ITER; l++){ prim(&a, rand_start[l], dist_def, prev_def, wt_zero, NULL, C_READ_VT[j], C_WRITE_VT[j], C_AT_VT[j], C_CMP_VT[j], C_CMP_WT[k]); } t_def = clock() - t_def; C_SUM_DIST[k](dsum_def, &num_dwraps_def, &num_paths_def, num_vts, vt_size, dist_def, prev_def, C_READ_VT[j]); t_divchn = clock(); for (l = 0; l < C_ITER; l++){ prim(&a, rand_start[l], dist_divchn, prev_divchn, wt_zero, &pmht_divchn, C_READ_VT[j], C_WRITE_VT[j], C_AT_VT[j], C_CMP_VT[j], C_CMP_WT[k]); } t_divchn = clock() - t_divchn; C_SUM_DIST[k](dsum_divchn, &num_dwraps_divchn, &num_paths_divchn, num_vts, vt_size, dist_def, prev_def, C_READ_VT[j]); t_muloa = clock(); for (l = 0; l < C_ITER; l++){ prim(&a, rand_start[l], dist_muloa, prev_muloa, wt_zero, &pmht_muloa, C_READ_VT[j], C_WRITE_VT[j], C_AT_VT[j], C_CMP_VT[j], C_CMP_WT[k]); } t_muloa = clock() - t_muloa; C_SUM_DIST[k](dsum_muloa, &num_dwraps_muloa, &num_paths_muloa, num_vts, vt_size, dist_def, prev_def, C_READ_VT[j]); if (k < C_FN_INTEGRAL_WT_COUNT){ res *= (C_CMP_WT[k](dsum_def, dsum_divchn) == 0 && C_CMP_WT[k](dsum_divchn, dsum_muloa) == 0); } res *= (num_dwraps_def == num_dwraps_divchn && num_dwraps_divchn == num_dwraps_muloa && num_paths_def == num_paths_divchn && num_paths_divchn == num_paths_muloa); printf("\t\t\t# edges: %lu\n", TOLU(a.num_es)); printf("\t\t\t\t%s %s prim default ht: %.8f seconds\n" "\t\t\t\t%s %s prim ht_divchn: %.8f seconds\n" "\t\t\t\t%s %s prim ht_muloa: %.8f seconds\n", C_VT_TYPES[j], C_WT_TYPES[k], (double)t_def / C_ITER / CLOCKS_PER_SEC, C_VT_TYPES[j], C_WT_TYPES[k], (double)t_divchn / C_ITER / CLOCKS_PER_SEC, C_VT_TYPES[j], C_WT_TYPES[k], (double)t_muloa / C_ITER / CLOCKS_PER_SEC); printf("\t\t\t\t%s %s correctness: ", C_VT_TYPES[j], C_WT_TYPES[k]); print_test_result(res); printf("\t\t\t\t%s %s last mst # edges: %lu\n", C_VT_TYPES[j], C_WT_TYPES[k], TOLU(num_paths_def - 1)); printf("\t\t\t\t%s %s last [# wraps, mst sum]: [%lu, ", C_VT_TYPES[j], C_WT_TYPES[k], TOLU(num_dwraps_def)); C_PRINT[k](dsum_def); printf("]\n"); res = 1; adj_lst_free(&a); } } } } free(rand_start); free(wt_l); free(dsum_def); free(dsum_divchn); free(dsum_muloa); free(dist_def); free(dist_divchn); free(dist_muloa); free(prev_def); free(prev_divchn); free(prev_muloa); rand_start = NULL; wt_l = NULL; dsum_def = NULL; dsum_divchn = NULL; dsum_muloa = NULL; dist_def = NULL; dist_divchn = NULL; dist_muloa = NULL; prev_def = NULL; prev_divchn = NULL; prev_muloa = NULL; } /** Portable random number generation. For better uniformity (according to rand) RAND_MAX should be 32767, a power to two minus one, or many times larger than 32768 on a given system if it is not a power of two minus one. Given a value n of one of the below unsigned integral types, the overflow bits after multipying n with a random number of the same type represent a random number of the type within the range [0, n). According to C89 (draft): "When a signed integer is converted to an unsigned integer with equal or greater size, if the value of the signed integer is nonnegative, its value is unchanged." "For each of the signed integer types, there is a corresponding (but different) unsigned integer type (designated with the keyword unsigned) that uses the same amount of storage (including sign information) and has the same alignment requirements" "When an integer is demoted to an unsigned integer with smaller size, the result is the nonnegative remainder on division by the number one greater than the largest unsigned number that can be represented in the type with smaller size. " It is guaranteed that: sizeof(short) <= sizeof(int) <= sizeof(long) */ unsigned short random_ushort(){ size_t i; unsigned short ret = 0; for (i = 0; i <= C_USHORT_BIT_MOD; i++){ ret |= ((unsigned short)((unsigned int)RANDOM() & C_RANDOM_MASK) << (i * C_RANDOM_BIT)); } return ret; } unsigned int random_uint(){ size_t i; unsigned int ret = 0; for (i = 0; i <= C_UINT_BIT_MOD; i++){ ret |= ((unsigned int)RANDOM() & C_RANDOM_MASK) << (i * C_RANDOM_BIT); } return ret; } unsigned long random_ulong(){ size_t i; unsigned long ret = 0; for (i = 0; i <= C_ULONG_BIT_MOD; i++){ ret |= ((unsigned long)((unsigned int)RANDOM() & C_RANDOM_MASK) << (i * C_RANDOM_BIT)); } return ret; } size_t random_sz(){ size_t i; size_t ret = 0; for (i = 0; i <= C_SZ_BIT_MOD; i++){ ret |= ((size_t)((unsigned int)RANDOM() & C_RANDOM_MASK) << (i * C_RANDOM_BIT)); } return ret; } unsigned short mul_high_ushort(unsigned short a, unsigned short b){ unsigned short al, bl, ah, bh, al_bh, ah_bl; unsigned short overlap; al = a & C_USHORT_LOW_MASK; bl = b & C_USHORT_LOW_MASK; ah = a >> C_USHORT_HALF_BIT; bh = b >> C_USHORT_HALF_BIT; al_bh = al * bh; ah_bl = ah * bl; overlap = ((ah_bl & C_USHORT_LOW_MASK) + (al_bh & C_USHORT_LOW_MASK) + (al * bl >> C_USHORT_HALF_BIT)); return ((overlap >> C_USHORT_HALF_BIT) + ah * bh + (ah_bl >> C_USHORT_HALF_BIT) + (al_bh >> C_USHORT_HALF_BIT)); } unsigned int mul_high_uint(unsigned int a, unsigned int b){ unsigned int al, bl, ah, bh, al_bh, ah_bl; unsigned int overlap; al = a & C_UINT_LOW_MASK; bl = b & C_UINT_LOW_MASK; ah = a >> C_UINT_HALF_BIT; bh = b >> C_UINT_HALF_BIT; al_bh = al * bh; ah_bl = ah * bl; overlap = ((ah_bl & C_UINT_LOW_MASK) + (al_bh & C_UINT_LOW_MASK) + (al * bl >> C_UINT_HALF_BIT)); return ((overlap >> C_UINT_HALF_BIT) + ah * bh + (ah_bl >> C_UINT_HALF_BIT) + (al_bh >> C_UINT_HALF_BIT)); } unsigned long mul_high_ulong(unsigned long a, unsigned long b){ unsigned long al, bl, ah, bh, al_bh, ah_bl; unsigned long overlap; al = a & C_ULONG_LOW_MASK; bl = b & C_ULONG_LOW_MASK; ah = a >> C_ULONG_HALF_BIT; bh = b >> C_ULONG_HALF_BIT; al_bh = al * bh; ah_bl = ah * bl; overlap = ((ah_bl & C_ULONG_LOW_MASK) + (al_bh & C_ULONG_LOW_MASK) + (al * bl >> C_ULONG_HALF_BIT)); return ((overlap >> C_ULONG_HALF_BIT) + ah * bh + (ah_bl >> C_ULONG_HALF_BIT) + (al_bh >> C_ULONG_HALF_BIT)); } size_t mul_high_sz(size_t a, size_t b){ size_t al, bl, ah, bh, al_bh, ah_bl; size_t overlap; al = a & C_SZ_LOW_MASK; bl = b & C_SZ_LOW_MASK; ah = a >> C_SZ_HALF_BIT; bh = b >> C_SZ_HALF_BIT; al_bh = al * bh; ah_bl = ah * bl; overlap = ((ah_bl & C_SZ_LOW_MASK) + (al_bh & C_SZ_LOW_MASK) + (al * bl >> C_SZ_HALF_BIT)); return ((overlap >> C_SZ_HALF_BIT) + ah * bh + (ah_bl >> C_SZ_HALF_BIT) + (al_bh >> C_SZ_HALF_BIT)); } /** Value initiliazation, arithmetic, and printing. The functions with the set_test_max prefix, set the maximum value of random weights (i.e. unreached upper bound). In contrast to Dijkstra, edge weights are not added in Prim, and the maximum value of random weights can be set to the maximum value of the type used to represent weights. The functions with the sum_dist prefix compute the sum of unsigned integer weights of an mst by counting the wrap-arounds.The computation is overflow safe, because each weight is at most the maximum value of the unsigned integer type used to represent weights, and there are at most n - 1 edges in an mst, where n is the number of vertices. The total sum is: # wrap-arounds * max value of weight type + # wraps-arounds + wrapped sum of weight type. For double weights, the maximum value in 1.0, and the number of wrap-arounds is 0. */ void set_zero_ushort(void *a){ *(unsigned short *)a = 0; } void set_zero_uint(void *a){ *(unsigned int *)a = 0; } void set_zero_ulong(void *a){ *(unsigned long *)a = 0; } void set_zero_sz(void *a){ *(size_t *)a = 0; } void set_zero_double(void *a){ *(double *)a = 0.0; } void set_test_ulimit_ushort(void *a, size_t num_vts){ if (num_vts == 0){ *(unsigned short *)a = C_USHORT_ULIMIT; }else{ /* usual arithmetic conversions */ *(unsigned short *)a = C_USHORT_ULIMIT / num_vts; } } void set_test_ulimit_uint(void *a, size_t num_vts){ if (num_vts == 0){ *(unsigned int *)a = C_UINT_ULIMIT; }else{ /* usual arithmetic conversions */ *(unsigned int *)a = C_UINT_ULIMIT / num_vts; } } void set_test_ulimit_ulong(void *a, size_t num_vts){ if (num_vts == 0){ *(unsigned long *)a = C_ULONG_ULIMIT; }else{ /* usual arithmetic conversions */ *(unsigned long *)a = C_ULONG_ULIMIT / num_vts; } } void set_test_ulimit_sz(void *a, size_t num_vts){ if (num_vts == 0){ *(size_t *)a = C_SZ_ULIMIT; }else{ *(size_t *)a = C_SZ_ULIMIT / num_vts; } } void set_test_ulimit_double(void *a, size_t num_vts){ if (num_vts == 0){ *(double *)a = 1.0; }else{ *(double *)a = 1.0 / num_vts; } } void sum_dist_ushort(void *dist_sum, size_t *num_dist_wraps, /* <= num_vts */ size_t *num_paths, /* <= num_vts */ size_t num_vts, size_t vt_size, const void *dist, const void *prev, size_t (*read_vt)(const void *)){ size_t i, p; unsigned short *dsum = dist_sum; const unsigned short *d = dist; *dsum = 0; *num_dist_wraps = 0; *num_paths = 0; for (i = 0; i < num_vts; i++){ p = read_vt(ptr(prev, i, vt_size)); if (p != num_vts){ (*num_dist_wraps) += (C_USHORT_ULIMIT - *dsum < d[i]); *dsum += d[i]; (*num_paths)++; } } } void sum_dist_uint(void *dist_sum, size_t *num_dist_wraps, /* <= num_vts */ size_t *num_paths, /* <= num_vts */ size_t num_vts, size_t vt_size, const void *dist, const void *prev, size_t (*read_vt)(const void *)){ size_t i, p; unsigned int *dsum = dist_sum; const unsigned int *d = dist; *dsum = 0; *num_dist_wraps = 0; *num_paths = 0; for (i = 0; i < num_vts; i++){ p = read_vt(ptr(prev, i, vt_size)); if (p != num_vts){ (*num_dist_wraps) += (C_UINT_ULIMIT - *dsum < d[i]); *dsum += d[i]; (*num_paths)++; } } } void sum_dist_ulong(void *dist_sum, size_t *num_dist_wraps, /* <= num_vts */ size_t *num_paths, /* <= num_vts */ size_t num_vts, size_t vt_size, const void *dist, const void *prev, size_t (*read_vt)(const void *)){ size_t i, p; unsigned long *dsum = dist_sum; const unsigned long *d = dist; *dsum = 0; *num_dist_wraps = 0; *num_paths = 0; for (i = 0; i < num_vts; i++){ p = read_vt(ptr(prev, i, vt_size)); if (p != num_vts){ (*num_dist_wraps) += (C_ULONG_ULIMIT - *dsum < d[i]); *dsum += d[i]; (*num_paths)++; } } } void sum_dist_sz(void *dist_sum, size_t *num_dist_wraps, /* <= num_vts */ size_t *num_paths, /* <= num_vts */ size_t num_vts, size_t vt_size, const void *dist, const void *prev, size_t (*read_vt)(const void *)){ size_t i, p; size_t *dsum = dist_sum; const size_t *d = dist; *dsum = 0; *num_dist_wraps = 0; *num_paths = 0; for (i = 0; i < num_vts; i++){ p = read_vt(ptr(prev, i, vt_size)); if (p != num_vts){ (*num_dist_wraps) += (C_SZ_ULIMIT - *dsum < d[i]); *dsum += d[i]; (*num_paths)++; } } } void sum_dist_double(void *dist_sum, size_t *num_dist_wraps, /* <= num_vts */ size_t *num_paths, /* <= num_vts */ size_t num_vts, size_t vt_size, const void *dist, const void *prev, size_t (*read_vt)(const void *)){ size_t i, p; double *dsum = dist_sum; const double *d = dist; *dsum = 0; *num_dist_wraps = 0; *num_paths = 0; for (i = 0; i < num_vts; i++){ p = read_vt(ptr(prev, i, vt_size)); if (p != num_vts){ *dsum += d[i]; (*num_paths)++; } } } void print_ushort(const void *a){ printf("%hu", *(const unsigned short *)a); } void print_uint(const void *a){ printf("%u", *(const unsigned int *)a); } void print_ulong(const void *a){ printf("%lu", *(const unsigned long *)a); } void print_sz(const void *a){ printf("%lu", TOLU(*(const size_t *)a)); } void print_double(const void *a){ printf("%.8f", *(const double *)a); } /** Computes a pointer to the ith element in the block of elements. */ void *ptr(const void *block, size_t i, size_t size){ return (void *)((char *)block + i * size); } /** Prints an array. */ void print_arr(const void *arr, size_t size, size_t n, void (*print_elt)(const void *)){ size_t i; for (i = 0; i < n; i++){ print_elt(ptr(arr, i, size)); printf(" "); } } /** Prints a prev array. */ void print_prev(const struct adj_lst *a, const void *prev, void (*print_vt)(const void *)){ print_arr(prev, a->vt_size, a->num_vts, print_vt); } /** Prints a dist array. */ void print_dist(const struct adj_lst *a, const void *dist, const void *prev, const void *wt_zero, size_t (*read_vt)(const void *), void (*print_wt)(const void *)){ size_t i; for (i = 0; i < a->num_vts; i++){ if (read_vt(ptr(prev, i, a->vt_size)) != a->num_vts){ print_wt(ptr(dist, i, a->wt_size)); printf(" "); }else{ print_wt(wt_zero); printf(" "); } } } /** Prints an adjacency list. If the graph is unweighted, then print_wt is NULL. */ void print_adj_lst(const struct adj_lst *a, void (*print_vt)(const void *), void (*print_wt)(const void *)){ size_t i; const void *p = NULL, *p_start = NULL, *p_end = NULL; printf("\tvertices: \n"); for (i = 0; i < a->num_vts; i++){ printf("\t%lu : ", TOLU(i)); p_start = a->vt_wts[i]->elts; p_end = (char *)p_start + a->vt_wts[i]->num_elts * a->pair_size; for (p = p_start; p != p_end; p = (char *)p + a->pair_size){ print_vt(p); printf(" "); } printf("\n"); } if (a->wt_size > 0 && print_wt != NULL){ printf("\tweights: \n"); for (i = 0; i < a->num_vts; i++){ printf("\t%lu : ", TOLU(i)); p_start = a->vt_wts[i]->elts; p_end = (char *)p_start + a->vt_wts[i]->num_elts * a->pair_size; for (p = p_start; p != p_end; p = (char *)p + a->pair_size){ print_wt((char *)p + a->wt_offset); printf(" "); } printf("\n"); } } } /** Prints a test result. */ void print_test_result(int res){ if (res){ printf("SUCCESS\n"); }else{ printf("FAILURE\n"); } } int main(int argc, char *argv[]){ int i; size_t *args = NULL; RGENS_SEED(); if (argc > C_ARGC_ULIMIT){ printf("USAGE:\n%s", C_USAGE); exit(EXIT_FAILURE); } args = malloc_perror(C_ARGC_ULIMIT - 1, sizeof(size_t)); memcpy(args, C_ARGS_DEF, (C_ARGC_ULIMIT - 1) * sizeof(size_t)); for (i = 1; i < argc; i++){ args[i - 1] = atoi(argv[i]); } if (args[0] > C_USHORT_BIT - 1 || args[1] > C_USHORT_BIT - 1 || args[1] < args[0] || args[2] > 1 || args[3] > 1){ printf("USAGE:\n%s", C_USAGE); exit(EXIT_FAILURE); } /*pow_two_perror later tests that # vertices is representable as size_t */ if (args[2]) run_small_graph_test(); if (args[3]) run_rand_test(args[0], args[1]); free(args); args = NULL; return 0; }
alfin3/graph-algorithms
utilities/utilities-alg/utilities-alg.c
<filename>utilities/utilities-alg/utilities-alg.c /** utilities-alg.c Implementations of general algorithms. */ #include <stdio.h> #include <stdlib.h> #include "utilities-mem.h" static void *elt_ptr(const void *elts, size_t i, size_t elt_size); /** Performs "greater or equal" binary search on an array with count elements, sorted in an ascending order according to cmp. The array is pointed to by elts and has at least one element. Given an array A, finds A[i] <= element pointed to by key <= A[i + 1] according to cmp, and returns i + 1. If at least two indices satisfy the search objective, it is unspecified which index in the set of indices satisfying the search objective is returned. Returns count, if A[count - 1] < element pointed to by key. */ size_t geq_bsearch(const void *key, const void *elts, size_t count, size_t elt_size, int (*cmp)(const void *, const void *)){ size_t cur = (count - 1) / 2; size_t prev_low = 0, prev_high = count - 1; if (cmp(key, elt_ptr(elts, prev_low, elt_size)) <= 0) return 0; if (cmp(key, elt_ptr(elts, prev_high, elt_size)) > 0) return count; while (1){ /* a. A[0] < key element <= A[count - 1], A's count > 1 */ if (cmp(key, elt_ptr(elts, cur, elt_size)) < 0){ prev_high = cur; /* b. must decrease each time, since cur is not prev_low */ cur = (cur + prev_low) / 2; }else if (cmp(key, elt_ptr(elts, cur + 1, elt_size)) > 0){ prev_low = cur; /* c. must increase each time, since cur + 1 is not prev_high */ cur = (cur + prev_high) / 2; /* < count - 1 */ }else{ /* must enter due to a, b, and c, at the latest after step size is 1 */ break; } } return cur + 1; } /** Performs "less or equal" binary search on an array with count elements, sorted in an ascending order according to cmp. The array is pointed to by elts and has at least one element. Given an array A, finds A[i] <= element pointed to by key <= A[i + 1] according to cmp, and returns i. If at least two indices satisfy the search objective, it is unspecified which index in the set of indices satisfying the search objective is returned. Returns count, if A[0] > element pointed to by key. */ size_t leq_bsearch(const void *key, const void *elts, size_t count, size_t elt_size, int (*cmp)(const void *, const void *)){ size_t cur; if (cmp(key, elt_ptr(elts, 0, elt_size)) < 0){ /* key element < A[0], thus no element in A <= key element */ return count; } cur = geq_bsearch(key, elts, count, elt_size, cmp); if (cur == 0){ /* key element == A[0] */ return 0; }else{ return cur - 1; } } /** Computes a pointer to the ith element in an array pointed to by elts. */ static void *elt_ptr(const void *elts, size_t i, size_t elt_size){ return (void *)((char *)elts + i * elt_size); }
alfin3/graph-algorithms
data-structures/queue/queue.h
/** queue.h Struct declarations and declarations of accessible functions of a generic dynamically allocated queue, providing a dynamic set of generic elements in the fifo queue form. A distinction is made between an element and an "elt_size block". During an insertion a contiguous block of size elt_size ("elt_size block") is copied into a queue. An element may be within a contiguous or non- contiguous memory block. Given an element, the user decides what is copied into the elt_size block of the queue. If the element is within a contiguous memory block, then it can be entirely copied as an elt_size block, or a pointer to it can be copied as an elt_size block. If the element is within a non-contiguous memory block, then a pointer to it is copied as an elt_size block. When a pointer to an element is copied into a queue as an elt_size block, the user can also decide if only the pointer or the entire element is deleted during the free operation. By setting free_elt to NULL, only the pointer is deleted. Otherwise, the deletion is performed according to a non-NULL free_elt. For example, when an in-memory set of images are used as elements and pointers are copied into a queue, then setting free_elt to NULL will not affect the original set of images throughout the lifetime of the queue. The implementation is cache-efficient and provides a constant overhead per elt_size block across push and pop operations by maintaining the invariant that an elt_size block is copied within a queue at most once throughout its lifetime in the queue. The implementation only uses integer and pointer operations. Given parameter values within the specified ranges, the implementation provides an error message and an exit is executed if an integer overflow is attempted or an allocation is not completed due to insufficient resources. The behavior outside the specified parameter ranges is undefined. The implementation does not use stdint.h and is portable under C89/C90 and C99. */ #ifndef QUEUE_H #define QUEUE_H #include <stddef.h> struct queue{ size_t count; size_t init_count; size_t max_count; size_t num_elts; size_t num_popped_elts; size_t elt_size; void *elts; void (*free_elt)(void *); }; /** Initializes a queue. By default the initialized queue can accomodate as many elt_size blocks as the system resources allow, starting from two elt_size blocks and growing by repetitive doubling. q : pointer to a preallocated block of size sizeof(struct queue) elt_size : non-zero size of an elt_size block; must account for internal and trailing padding according to sizeof free_elt : - NULL if only elt_size blocks should be deleted in the queue_free operation (e.g. because elements were entirely copied as elt_size blocks, or because pointers were copied as elt_size blocks and only pointers should be deleted) - otherwise takes a pointer to the elt_size block of an element as an argument, frees the memory of the element except the elt_size block pointed to by the argument */ void queue_init(struct queue *q, size_t elt_size, void (*free_elt)(void *)); /** Sets the count of the elt_size blocks that can be simultaneously present in an initial queue without reallocation. The growth of the queue is then achieved by repetitive doubling upto the count that can accomodate max_count simultaneously present elt_size blocks. The bounds are valid for any sequence of push and pop operations. If max_count is greater than init_count and is not equal to init_count * 2**n for n > 0, then the last growth step sets the count of the queue to a count that accomodates max_count simultaneously present elt_size blocks. The operation is optionally called after queue_init is completed and before any other operation is called. q : pointer to a queue struct initialized with queue_init init_count : > 0 count of the elt_size blocks that can be simultaneously present in an initial queue without reallocation for any sequence of push and pop operations max_count : - if >= init_count, sets the maximum count of the elt_size blocks that can be simultaneously present in a queue for any sequence of push and pop operations; an error message is provided and an exit is executed if an attempt is made to exceed the allocated memory of the queue in queue_push, which may accomodate upto 2 * max_count elt_size blocks depending on the sequence of push and pop operations - otherwise, the count of the elt_size blocks that can be simultaneously present in a queue is only limited by the available system resources */ void queue_bound(struct queue *q, size_t init_count, size_t max_count); /** Pushes an element onto a queue. q : pointer to an initialized queue struct elt : non-NULL pointer to the elt_size block of an element */ void queue_push(struct queue *q, const void *elt); /** Pops an element of a queue. q : pointer to an initialized queue struct elt : non-NULL pointer to a preallocated elt_size block; if the queue is empty, the memory block pointed to by elt remains unchanged */ void queue_pop(struct queue *q, void *elt); /** If a queue is not empty, returns a pointer to the first elt_size block, otherwise returns NULL. The returned pointer is guaranteed to point to the first element until a queue modifying operation is performed. If non-NULL, the returned pointer can be dereferenced as a pointer to the type of the elt_size block, or as a character pointer. s : pointer to an initialized queue struct */ void *queue_first(const struct queue *q); /** Frees the memory of all elements that are in a queue according to free_elt, frees the memory of the queue, and leaves the block of size sizeof(struct queue) pointed to by the q parameter. */ void queue_free(struct queue *q); #endif
alfin3/graph-algorithms
utilities-pthread/mergesort-pthread/mergesort-pthread.c
<reponame>alfin3/graph-algorithms /** mergesort-pthread.c Functions for optimizing and running a generic merge sort algorithm with parallel sorting and parallel merging. The algorithm provides \Theta(n/log^{2}n) theoretical parallelism within the dynamic multithreading model. The implementation provides i) a set of parameters for setting the constant base case upper bounds for switching from parallel sorting to serial sorting and from parallel merging to serial merging during recursion, and ii) a macro for setting the constant upper bound for the number of recursive calls placed on the stack of a thread across sorting and merging operations, thereby enabling the optimization of the parallelism and concurrency-associated overhead across input ranges and hardware settings. The provided parametrization of multithreading is based on the common parametrization of serial mergesort, where the recursion depth is limited by switching to a base case non-recursive sort algorithm. On a 4-core machine, the optimization of the base case upper bound parameters resulted in a speedup of approximately 2.6X in comparison to serial qsort (stdlib.h) on arrays of 10M random integer or double elements. */ #define _POSIX_C_SOURCE 200112L #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <pthread.h> #include "mergesort-pthread.h" #include "utilities-alg.h" #include "utilities-mem.h" #include "utilities-pthread.h" typedef struct{ size_t p, r; size_t sbase_count; /* >0, count of sort base case bound */ size_t mbase_count; /* >1, count of merge base case bound */ size_t elt_size; size_t num_onthread_rec; void *cat_elts; /* pointer to concatenation buffer for merging */ void *elts; /* pointer to an input array */ int (*cmp)(const void *, const void *); } mergesort_arg_t; typedef struct{ size_t ap, ar, bp, br, cs; size_t mbase_count; /* >1, count of merge base case bound */ size_t elt_size; size_t num_onthread_rec; void *cat_seg_elts; /* pointer to concatenation buffer segment */ void *elts; /* pointer to an input array */ int (*cmp)(const void *, const void *); } merge_arg_t; const size_t C_SIZE_MAX = (size_t)-1; /* cannot be reached as array index */ static void *mergesort_thread(void *arg); static void *merge_thread(void *arg); static void merge(merge_arg_t *ma); static void *elt_ptr(const void *elts, size_t i, size_t elt_size); /** Sorts a given array pointed to by elts in ascending order according to cmp. The array contains count elements of elt_size bytes. The first thread entry is placed on the thread stack of the caller. elts : pointer to the array to sort count : > 0, < 2^{CHAR_BIT * sizeof(size_t) - 1} count of elements in the array elt_size : size of each element in the array in bytes sbase_count : > 0 base case upper bound for parallel sorting; if the count of an unsorted subarray is less or equal to sbase_count, then the subarray is sorted with serial sort routine (qsort) mbase_count : > 1 base case upper bound for parallel merging; if the sum of the counts of two sorted subarrays is less or equal to mbase_count, then the two subarrays are merged with a serial merge routine cmp : comparison function which returns a negative integer value if the element pointed to by the first argument is less than the element pointed to by the second, a positive integer value if the element pointed to by the first argument is greater than the element pointed to by the second, and zero integer value if the two elements are equal */ void mergesort_pthread(void *elts, size_t count, size_t elt_size, size_t sbase_count, size_t mbase_count, int (*cmp)(const void *, const void *)){ mergesort_arg_t msa; if (count < 1) return; msa.p = 0; msa.r = count - 1; msa.sbase_count = sbase_count; msa.mbase_count = mbase_count; msa.elt_size = elt_size; msa.num_onthread_rec = 0; msa.elts = elts; msa.cat_elts = malloc_perror(count, elt_size); msa.cmp = cmp; mergesort_thread(&msa); free(msa.cat_elts); } /** Enters a mergesort thread that spawns mergesort threads recursively. The total number of threads is reduced and an additional speedup is provided by placing O(logn) recursive calls on a thread stack, with the tightness of the bound set by MERGESORT_PTHREAD_MAX_ONTHREAD_REC. */ static void *mergesort_thread(void *arg){ size_t q; mergesort_arg_t *msa = arg; mergesort_arg_t child_msas[2]; pthread_t child_ids[2]; merge_arg_t ma; if (msa->r - msa->p + 1 <= msa->sbase_count){ qsort(elt_ptr(msa->elts, msa->p, msa->elt_size), msa->r - msa->p + 1, msa->elt_size, msa->cmp); }else{ /* sort recursion */ q = (msa->p + msa->r) / 2; /* rounds down */ child_msas[0].p = msa->p; child_msas[0].r = q; child_msas[0].sbase_count = msa->sbase_count; child_msas[0].mbase_count = msa->mbase_count; child_msas[0].elt_size = msa->elt_size; child_msas[0].num_onthread_rec = 0; child_msas[0].cat_elts = msa->cat_elts; child_msas[0].elts = msa->elts; child_msas[0].cmp = msa->cmp; child_msas[1].p = q + 1; child_msas[1].r = msa->r; child_msas[1].sbase_count = msa->sbase_count; child_msas[1].mbase_count = msa->mbase_count; child_msas[1].elt_size = msa->elt_size; child_msas[1].cat_elts = msa->cat_elts; child_msas[1].elts = msa->elts; child_msas[1].cmp = msa->cmp; thread_create_perror(&child_ids[0], mergesort_thread, &child_msas[0]); if (msa->num_onthread_rec < MERGESORT_PTHREAD_MAX_ONTHREAD_REC){ /* keep putting mergesort_thread calls on the current thread stack */ child_msas[1].num_onthread_rec = msa->num_onthread_rec + 1; mergesort_thread(&child_msas[1]); }else{ child_msas[1].num_onthread_rec = 0; thread_create_perror(&child_ids[1], mergesort_thread, &child_msas[1]); thread_join_perror(child_ids[1], NULL); } thread_join_perror(child_ids[0], NULL); /* merge recursion */ ma.ap = msa->p; ma.ar = q; ma.bp = q + 1; ma.br = msa->r; ma.cs = 0; ma.mbase_count = msa->mbase_count; ma.elt_size = msa->elt_size; ma.num_onthread_rec = msa->num_onthread_rec; ma.cat_seg_elts = elt_ptr(msa->cat_elts, msa->p, msa->elt_size); ma.elts = msa->elts; ma.cmp = msa->cmp; merge_thread(&ma); /* copy the merged result into the input array */ memcpy(elt_ptr(msa->elts, msa->p, msa->elt_size), elt_ptr(ma.cat_seg_elts, 0, msa->elt_size), (msa->r - msa->p + 1) * msa->elt_size); } return NULL; } /** Merges two sorted subarrays in a parallel manner. */ static void *merge_thread(void *arg){ size_t aq, bq, ix; merge_arg_t *ma = arg; merge_arg_t child_mas[2]; pthread_t child_ids[2]; if ((ma->ap == C_SIZE_MAX && ma->ar == C_SIZE_MAX) || (ma->bp == C_SIZE_MAX && ma->br == C_SIZE_MAX) || (ma->ar - ma->ap) + (ma->br - ma->bp) + 2 <= ma->mbase_count){ merge(ma); return NULL; } /* rec. parameters with <= 3/4 problem size for the larger subproblem */ if (ma->ar - ma->ap > ma->br - ma->bp){ aq = (ma->ap + ma->ar) / 2; child_mas[0].ap = ma->ap; child_mas[0].ar = aq; child_mas[0].cs = ma->cs; child_mas[1].ap = aq + 1; child_mas[1].ar = ma->ar; ix = leq_bsearch(elt_ptr(ma->elts, aq, ma->elt_size), elt_ptr(ma->elts, ma->bp, ma->elt_size), ma->br - ma->bp + 1, /* at least 1 element */ ma->elt_size, ma->cmp); if (ix == ma->br - ma->bp + 1){ child_mas[0].bp = C_SIZE_MAX; child_mas[0].br = C_SIZE_MAX; child_mas[1].bp = ma->bp; child_mas[1].br = ma->br; child_mas[1].cs = ma->cs + (aq - ma->ap + 1); }else if (ix == ma->br - ma->bp){ child_mas[0].bp = ma->bp; child_mas[0].br = ma->br; child_mas[1].bp = C_SIZE_MAX; child_mas[1].br = C_SIZE_MAX; child_mas[1].cs = ma->cs + (aq - ma->ap) + (ma->br - ma->bp) + 2; }else{ child_mas[0].bp = ma->bp; child_mas[0].br = ma->bp + ix; child_mas[1].bp = ma->bp + ix + 1; child_mas[1].br = ma->br; child_mas[1].cs = ma->cs + (aq - ma->ap) + ix + 2; } }else{ bq = (ma->bp + ma->br) / 2; child_mas[0].bp = ma->bp; child_mas[0].br = bq; child_mas[0].cs = ma->cs; child_mas[1].bp = bq + 1; child_mas[1].br = ma->br; ix = leq_bsearch(elt_ptr(ma->elts, bq, ma->elt_size), elt_ptr(ma->elts, ma->ap, ma->elt_size), ma->ar - ma->ap + 1, /* at least 1 element */ ma->elt_size, ma->cmp); if (ix == ma->ar - ma->ap + 1){ child_mas[0].ap = C_SIZE_MAX; child_mas[0].ar = C_SIZE_MAX; child_mas[1].ap = ma->ap; child_mas[1].ar = ma->ar; child_mas[1].cs = ma->cs + (bq - ma->bp + 1); }else if (ix == ma->ar - ma->ap){ child_mas[0].ap = ma->ap; child_mas[0].ar = ma->ar; child_mas[1].ap = C_SIZE_MAX; child_mas[1].ar = C_SIZE_MAX; child_mas[1].cs = ma->cs + (ma->ar - ma->ap) + (bq - ma->bp) + 2; }else{ child_mas[0].ap = ma->ap; child_mas[0].ar = ma->ap + ix; child_mas[1].ap = ma->ap + ix + 1; child_mas[1].ar = ma->ar; child_mas[1].cs = ma->cs + ix + (bq - ma->bp) + 2; } } child_mas[0].mbase_count = ma->mbase_count; child_mas[0].elt_size = ma->elt_size; child_mas[0].num_onthread_rec = ma->num_onthread_rec; child_mas[0].cat_seg_elts = ma->cat_seg_elts; child_mas[0].elts = ma->elts; child_mas[0].cmp = ma->cmp; child_mas[1].mbase_count = ma->mbase_count; child_mas[1].elt_size = ma->elt_size; child_mas[1].num_onthread_rec = ma->num_onthread_rec; child_mas[1].cat_seg_elts = ma->cat_seg_elts; child_mas[1].elts = ma->elts; child_mas[1].cmp = ma->cmp; /* recursion */ thread_create_perror(&child_ids[0], merge_thread, &child_mas[0]); if (ma->num_onthread_rec < MERGESORT_PTHREAD_MAX_ONTHREAD_REC){ /* keep putting merge_thread calls on the current thread stack */ child_mas[1].num_onthread_rec = ma->num_onthread_rec + 1; merge_thread(&child_mas[1]); }else{ child_mas[1].num_onthread_rec = 0; thread_create_perror(&child_ids[1], merge_thread, &child_mas[1]); thread_join_perror(child_ids[1], NULL); } thread_join_perror(child_ids[0], NULL); return NULL; } /** Merges two sorted subarrays onto a concatenation array as the base case of parallel merge. */ static void merge(merge_arg_t *ma){ size_t first_ix, second_ix, cat_ix; size_t elt_size = ma->elt_size; if (ma->ap == C_SIZE_MAX && ma->ar == C_SIZE_MAX){ /* a is empty */ memcpy(elt_ptr(ma->cat_seg_elts, ma->cs, elt_size), elt_ptr(ma->elts, ma->bp, elt_size), (ma->br - ma->bp + 1) * elt_size); }else if (ma->bp == C_SIZE_MAX && ma->br == C_SIZE_MAX){ /* b is empty */ memcpy(elt_ptr(ma->cat_seg_elts, ma->cs, elt_size), elt_ptr(ma->elts, ma->ap, elt_size), (ma->ar - ma->ap + 1) * elt_size); }else{ /* a and b are each not empty */ first_ix = ma->ap; second_ix = ma->bp; cat_ix = ma->cs; while(first_ix <= ma->ar && second_ix <= ma->br){ if (ma->cmp(elt_ptr(ma->elts, first_ix, elt_size), elt_ptr(ma->elts, second_ix, elt_size)) < 0){ memcpy(elt_ptr(ma->cat_seg_elts, cat_ix, elt_size), elt_ptr(ma->elts, first_ix, elt_size), elt_size); cat_ix++; first_ix++; }else{ memcpy(elt_ptr(ma->cat_seg_elts, cat_ix, elt_size), elt_ptr(ma->elts, second_ix, elt_size), elt_size); cat_ix++; second_ix++; } } if (second_ix == ma->br + 1){ memcpy(elt_ptr(ma->cat_seg_elts, cat_ix, elt_size), elt_ptr(ma->elts, first_ix, elt_size), (ma->ar - first_ix + 1) * elt_size); }else{ memcpy(elt_ptr(ma->cat_seg_elts, cat_ix, elt_size), elt_ptr(ma->elts, second_ix, elt_size), (ma->br - second_ix + 1) * elt_size); } } } /** Computes a pointer to an element in an element array. */ static void *elt_ptr(const void *elts, size_t i, size_t elt_size){ return (void *)((char *)elts + i * elt_size); }
alfin3/graph-algorithms
data-structures/graph/graph-test.c
/** graph-test.c Tests of graphs with generic integer vertices and generic contiguous weights. The following command line arguments can be used to customize tests: graph-test [0, size_t width / 2] : n for 2**n vertices in smallest graph [0, size_t width / 2] : n for 2**n vertices in largest graph [0, 1] : small graph test on/off [0, 1] : non-random graph test on/off [0, 1] : random graph test on/off usage examples: ./graph-test ./graph-test 10 14 ./graph-test 0 10 0 1 0 ./graph-test 14 14 0 0 1 graph-test can be run with any subset of command line arguments in the above-defined order. If the (i + 1)th argument is specified then the ith argument must be specified for i >= 0. Default values are used for the unspecified arguments according to the C_ARGS_DEF array. The implementation of tests does not use stdint.h and is portable under C89/C90 and C99 with the only requirement that width of size_t is even and less than 2040. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <limits.h> #include <time.h> #include "graph.h" #include "stack.h" #include "utilities-mem.h" #include "utilities-mod.h" #include "utilities-lim.h" /** Generate random numbers in a portable way for test purposes only; rand() in the Linux C Library uses the same generator as random(), which may not be the case on older rand() implementations, and on current implementations on different systems. */ #define RGENS_SEED() do{srand(time(NULL));}while (0) #define RANDOM() (rand()) /* [0, RAND_MAX] */ #define DRAND() ((double)rand() / RAND_MAX) /* [0.0, 1.0] */ #define TOLU(i) ((unsigned long int)(i)) /* printing size_t under C89/C90 */ /* input handling */ const char *C_USAGE = "graph-test \n" "[0, size_t width / 2] : n for 2**n vertices in smallest graph \n" "[0, size_t width / 2] : n for 2**n vertices in largest graph \n" "[0, 1] : small graph test on/off \n" "[0, 1] : non-random graph test on/off \n" "[0, 1] : random graph test on/off \n"; const int C_ARGC_ULIMIT = 6; const size_t C_ARGS_DEF[5] = {0u, 10u, 1u, 1u, 1u}; const size_t C_FULL_BIT = PRECISION_FROM_ULIMIT((size_t)-1); /* small graph tests */ const size_t C_NUM_VTS = 5u; const size_t C_NUM_ES = 4u; const unsigned char C_UCHAR_U[4] = {0u, 0u, 0u, 1u}; const unsigned char C_UCHAR_V[4] = {1u, 2u, 3u, 3u}; const unsigned char C_UCHAR_WTS[4] = {4u, 3u, 2u, 1u}; const unsigned long C_ULONG_U[4] = {0u, 0u, 0u, 1u}; const unsigned long C_ULONG_V[4] = {1u, 2u, 3u, 3u}; const unsigned long C_ULONG_WTS[4] = {4u, 3u, 2u, 1u}; const double C_DOUBLE_WTS[4] = {4.0, 3.0, 2.0, 1.0}; const size_t C_FN_COUNT = 4u; size_t (* const C_READ[4])(const void *) ={ graph_read_ushort, graph_read_uint, graph_read_ulong, graph_read_sz}; void (* const C_WRITE[4])(void *, size_t) ={ graph_write_ushort, graph_write_uint, graph_write_ulong, graph_write_sz}; const size_t C_VT_SIZES[4] = { sizeof(unsigned short), sizeof(unsigned int), sizeof(unsigned long), sizeof(size_t)}; const char *C_VT_TYPES[4] = {"ushort", "uint ", "ulong ", "sz "}; const double C_PROB_ONE = 1.0; const double C_PROB_HALF = 0.5; const double C_PROB_ZERO = 0.0; void print_uchar(const void *a); void print_ulong(const void *a); void print_double(const void *a); void print_adj_lst(const struct adj_lst *a, void (*print_vt)(const void *), void (*print_wt)(const void *)); size_t sum_vts(const struct adj_lst *a, size_t i, size_t (*read_vt)(const void *)); void print_test_result(int res); /** Test on small graphs. */ /** Initialize small graphs with unsigned char vertices and unsigned char, unsigned long, and double weights. */ void uchar_uchar_graph_init(struct graph *g){ graph_base_init(g, C_NUM_VTS, sizeof(unsigned char), sizeof(unsigned char)); g->num_es = C_NUM_ES; g->u = (unsigned char *)C_UCHAR_U; g->v = (unsigned char *)C_UCHAR_V; g->wts = (unsigned char *)C_UCHAR_WTS; } void uchar_ulong_graph_init(struct graph *g){ graph_base_init(g, C_NUM_VTS, sizeof(unsigned char), sizeof(unsigned long)); g->num_es = C_NUM_ES; g->u = (unsigned char *)C_UCHAR_U; g->v = (unsigned char *)C_UCHAR_V; g->wts = (unsigned long *)C_ULONG_WTS; } void uchar_double_graph_init(struct graph *g){ graph_base_init(g, C_NUM_VTS, sizeof(unsigned char), sizeof(double)); g->num_es = C_NUM_ES; g->u = (unsigned char *)C_UCHAR_U; g->v = (unsigned char *)C_UCHAR_V; g->wts = (double *)C_DOUBLE_WTS; } /** Initialize small graphs with unsigned long vertices and unsigned char, unsigned long, and double weights. */ void ulong_uchar_graph_init(struct graph *g){ graph_base_init(g, C_NUM_VTS, sizeof(unsigned long), sizeof(unsigned char)); g->num_es = C_NUM_ES; g->u = (unsigned long *)C_ULONG_U; g->v = (unsigned long *)C_ULONG_V; g->wts = (unsigned char *)C_UCHAR_WTS; } void ulong_ulong_graph_init(struct graph *g){ graph_base_init(g, C_NUM_VTS, sizeof(unsigned long), sizeof(unsigned long)); g->num_es = C_NUM_ES; g->u = (unsigned long *)C_ULONG_U; g->v = (unsigned long *)C_ULONG_V; g->wts = (unsigned long *)C_ULONG_WTS; } void ulong_double_graph_init(struct graph *g){ graph_base_init(g, C_NUM_VTS, sizeof(unsigned long), sizeof(double)); g->num_es = C_NUM_ES; g->u = (unsigned long *)C_ULONG_U; g->v = (unsigned long *)C_ULONG_V; g->wts = (double *)C_DOUBLE_WTS; } /** Runs a test of adj_lst_{init, dir_build, undir_build, free} on small graphs. */ void run_small_graph_test(){ struct graph g; struct adj_lst a; /* unsigned char vertices, unsigned char weights */ uchar_uchar_graph_init(&g); printf("uchar vertices, uchar weights\n"); printf("\tdirected\n"); adj_lst_base_init(&a, &g); adj_lst_dir_build(&a, &g, graph_read_uchar); print_adj_lst(&a, print_uchar, print_uchar); adj_lst_free(&a); printf("\tundirected\n"); adj_lst_base_init(&a, &g); adj_lst_undir_build(&a, &g, graph_read_uchar); print_adj_lst(&a, print_uchar, print_uchar); adj_lst_free(&a); /* unsigned char vertices, unsigned long weights */ uchar_ulong_graph_init(&g); printf("uchar vertices, ulong weights\n"); printf("\tdirected\n"); adj_lst_base_init(&a, &g); adj_lst_dir_build(&a, &g, graph_read_uchar); print_adj_lst(&a, print_uchar, print_ulong); adj_lst_free(&a); printf("\tundirected\n"); adj_lst_base_init(&a, &g); adj_lst_undir_build(&a, &g, graph_read_uchar); print_adj_lst(&a, print_uchar, print_ulong); adj_lst_free(&a); /* unsigned char vertices, double weights */ uchar_double_graph_init(&g); printf("uchar vertices, double weights\n"); printf("\tdirected\n"); adj_lst_base_init(&a, &g); adj_lst_dir_build(&a, &g, graph_read_uchar); print_adj_lst(&a, print_uchar, print_double); adj_lst_free(&a); printf("\tundirected\n"); adj_lst_base_init(&a, &g); adj_lst_undir_build(&a, &g, graph_read_uchar); print_adj_lst(&a, print_uchar, print_double); adj_lst_free(&a); /* unsigned long vertices, unsigned char weights */ ulong_uchar_graph_init(&g); printf("ulong vertices, uchar weights\n"); printf("\tdirected\n"); adj_lst_base_init(&a, &g); adj_lst_dir_build(&a, &g, graph_read_ulong); print_adj_lst(&a, print_ulong, print_uchar); adj_lst_free(&a); printf("\tundirected\n"); adj_lst_base_init(&a, &g); adj_lst_undir_build(&a, &g, graph_read_ulong); print_adj_lst(&a, print_ulong, print_uchar); adj_lst_free(&a); /* unsigned long vertices, unsigned long weights */ ulong_ulong_graph_init(&g); printf("ulong vertices, ulong weights\n"); printf("\tdirected\n"); adj_lst_base_init(&a, &g); adj_lst_dir_build(&a, &g, graph_read_ulong); print_adj_lst(&a, print_ulong, print_ulong); adj_lst_free(&a); printf("\tundirected\n"); adj_lst_base_init(&a, &g); adj_lst_undir_build(&a, &g, graph_read_ulong); print_adj_lst(&a, print_ulong, print_ulong); adj_lst_free(&a); /* unsigned long vertices, double weights */ ulong_double_graph_init(&g); printf("ulong vertices, double weights\n"); printf("\tdirected\n"); adj_lst_base_init(&a, &g); adj_lst_dir_build(&a, &g, graph_read_ulong); print_adj_lst(&a, print_ulong, print_double); adj_lst_free(&a); printf("\tundirected\n"); adj_lst_base_init(&a, &g); adj_lst_undir_build(&a, &g, graph_read_ulong); print_adj_lst(&a, print_ulong, print_double); adj_lst_free(&a); } /** Test on non-random graphs. */ /** Initialize and free unweighted graphs. Each graph is i) a DAG with source 0 and num_vts(num_vts - 1) / 2 edges in the directed form, and ii) complete in the undirected form. num_vts is >= 1. */ void complete_graph_init(struct graph *g, size_t num_vts, size_t vt_size, void (*write_vt)(void *, size_t)){ size_t i, j; size_t num_es = mul_sz_perror(num_vts, num_vts - 1) >> 1; void *up = NULL; void *vp = NULL; graph_base_init(g, num_vts, vt_size, 0); g->num_es = num_es; g->u = malloc_perror(g->num_es, vt_size); g->v = malloc_perror(g->num_es, vt_size); up = g->u; vp = g->v; for (i = 0; i < num_vts - 1; i++){ for (j = i + 1; j < num_vts; j++){ write_vt(up, i); write_vt(vp, j); up = (char *)up + vt_size; vp = (char *)vp + vt_size; } } } void complete_graph_free(struct graph *g){ free(g->u); free(g->v); g->u = NULL; g->v = NULL; } /** Runs a adj_lst_undir_build test on complete unweighted graphs across integer types for vertices. */ void run_adj_lst_undir_build_test(size_t log_start, size_t log_end){ size_t i, j; size_t num_vts; struct graph g; struct adj_lst a; clock_t t; printf("Test adj_lst_undir_build on complete unweighted graphs across" " vertex types\n"); printf("\tn vertices, n(n - 1)/2 edges represented by n(n - 1) " "directed edges\n"); for (i = log_start; i <= log_end; i++){ num_vts = pow_two_perror(i); printf("\t\tvertices: %lu\n", TOLU(num_vts)); for (j = 0; j < C_FN_COUNT; j++){ complete_graph_init(&g, pow_two_perror(i), C_VT_SIZES[j], C_WRITE[j]); adj_lst_base_init(&a, &g); t = clock(); adj_lst_undir_build(&a, &g, C_READ[j]); t = clock() - t; adj_lst_free(&a); complete_graph_free(&g); printf("\t\t\t%s build time: %.6f seconds\n", C_VT_TYPES[j], (float)t / CLOCKS_PER_SEC); } } } /** Test on random graphs. */ struct bern_arg{ double p; }; int bern(void *arg){ struct bern_arg *b = arg; if (b->p >= C_PROB_ONE) return 1; if (b->p <= C_PROB_ZERO) return 0; if (b->p > DRAND()) return 1; return 0; } /** Test adj_lst_add_dir_edge and adj_lst_add_undir_edge. */ void add_edge_helper(size_t log_start, size_t log_end, void (*build)(struct adj_lst *, const struct graph *, size_t (*)(const void *)), void (*add_edge)(struct adj_lst *, size_t, size_t, const void *, void (*)(void *, size_t), int (*)(void *), void *)); void run_adj_lst_add_dir_edge_test(size_t log_start, size_t log_end){ printf("Test adj_lst_add_dir_edge on DAGs \n"); printf("\tn vertices, 0 as source, n(n - 1)/2 directed edges \n"); add_edge_helper(log_start, log_end, adj_lst_dir_build, adj_lst_add_dir_edge); } void run_adj_lst_add_undir_edge_test(size_t log_start, size_t log_end){ printf("Test adj_lst_add_undir_edge on complete graphs \n"); printf("\tn vertices, n(n - 1)/2 edges represented by n(n - 1) " "directed edges \n"); add_edge_helper(log_start, log_end, adj_lst_undir_build, adj_lst_add_undir_edge); } void add_edge_helper(size_t log_start, size_t log_end, void (*build)(struct adj_lst *, const struct graph *, size_t (*)(const void *)), void (*add_edge)(struct adj_lst *, size_t, size_t, const void *, void (*)(void *, size_t), int (*)(void *), void *)){ int res = 1; size_t i, j, k, l; size_t num_vts; struct bern_arg b; struct graph g_blt, g_bld; struct adj_lst a_blt, a_bld; clock_t t; b.p = C_PROB_ONE; for (i = log_start; i <= log_end; i++){ num_vts = pow_two_perror(i); printf("\t\tvertices: %lu\n", TOLU(num_vts)); for (j = 0; j < C_FN_COUNT; j++){ complete_graph_init(&g_blt, num_vts, C_VT_SIZES[j], C_WRITE[j]); graph_base_init(&g_bld, num_vts, C_VT_SIZES[j], 0); adj_lst_base_init(&a_blt, &g_blt); adj_lst_base_init(&a_bld, &g_bld); build(&a_blt, &g_blt, C_READ[j]); t = clock(); for (k = 0; k < num_vts - 1; k++){ for (l = k + 1; l < num_vts; l++){ add_edge(&a_bld, k, l, NULL, C_WRITE[j], bern, &b); } } t = clock() - t; for (k = 0; k < num_vts; k++){ res *= (a_blt.vt_wts[k]->num_elts == a_bld.vt_wts[k]->num_elts); res *= (sum_vts(&a_blt, k, C_READ[j]) == sum_vts(&a_bld, k, C_READ[j])); } res *= (a_blt.num_vts == a_bld.num_vts); res *= (a_blt.num_es == a_bld.num_es); complete_graph_free(&g_blt); adj_lst_free(&a_blt); adj_lst_free(&a_bld); printf("\t\t\t%s build time: %.6f seconds\n", C_VT_TYPES[j], (float)t / CLOCKS_PER_SEC); } } printf("\t\tcorrectness across all builds --> "); print_test_result(res); } /** Test adj_lst_rand_dir and adj_lst_rand_undir. */ void rand_build_helper(size_t log_start, size_t log_end, double prob, void (*rand_build)(struct adj_lst *, void (*)(void *, size_t), int (*)(void *), void *)); void run_adj_lst_rand_dir_test(size_t log_start, size_t log_end){ printf("Test adj_lst_rand_dir on the number of edges in expectation\n"); printf("\tn vertices, E[# of directed edges] = n(n - 1) * (%.1f * 1)\n", C_PROB_HALF); rand_build_helper(log_start, log_end, C_PROB_HALF, adj_lst_rand_dir); } void run_adj_lst_rand_undir_test(size_t log_start, size_t log_end){ printf("Test adj_lst_rand_undir on the number of edges in expectation\n"); printf("\tn vertices, E[# of directed edges] = n(n - 1)/2 * (%.1f * 2)\n", C_PROB_HALF); rand_build_helper(log_start, log_end, C_PROB_HALF, adj_lst_rand_undir); } void rand_build_helper(size_t log_start, size_t log_end, double prob, void (*rand_build)(struct adj_lst *, void (*)(void *, size_t), int (*)(void *), void *)){ size_t i, j; size_t num_vts; struct graph g; struct adj_lst a; struct bern_arg b; b.p = prob; for (i = log_start; i <= log_end; i++){ num_vts = pow_two_perror(i); printf("\t\tvertices: %lu, expected directed edges: %.1f\n", TOLU(num_vts), prob * num_vts * (num_vts - 1)); for (j = 0; j < C_FN_COUNT; j++){ graph_base_init(&g, num_vts, C_VT_SIZES[j], 0); adj_lst_base_init(&a, &g); rand_build(&a, C_WRITE[j], bern, &b); printf("\t\t\t%s directed edges: %lu\n", C_VT_TYPES[j], TOLU(a.num_es)); adj_lst_free(&a); } } } /** Auxiliary functions. */ /** Sums the vertices in the ith stack in an adjacency list. Wraps around and does not check for overflow. */ size_t sum_vts(const struct adj_lst *a, size_t i, size_t (*read_vt)(const void *)){ void *p = NULL, *p_start = NULL, *p_end = NULL; size_t ret = 0; p_start = a->vt_wts[i]->elts; p_end = (char *)p_start + a->vt_wts[i]->num_elts * a->pair_size; for (p = p_start; p != p_end; p = (char *)p + a->pair_size){ ret += read_vt(p); } return ret; } /** Printing functions. */ void print_uchar(const void *a){ printf("%u ", *(const unsigned char *)a); } void print_ulong(const void *a){ printf("%lu ", *(const unsigned long *)a); } void print_double(const void *a){ printf("%.2f ", *(const double *)a); } void print_adj_lst(const struct adj_lst *a, void (*print_vt)(const void *), void (*print_wt)(const void *)){ size_t i; void *p = NULL, *p_start = NULL, *p_end = NULL; printf("\t\tvertices: \n"); for (i = 0; i < a->num_vts; i++){ printf("\t\t%lu : ", TOLU(i)); p_start = a->vt_wts[i]->elts; p_end = (char *)p_start + a->vt_wts[i]->num_elts * a->pair_size; for (p = p_start; p != p_end; p = (char *)p + a->pair_size){ print_vt(p); } printf("\n"); } if (a->wt_size > 0 && print_wt != NULL){ printf("\t\tweights: \n"); for (i = 0; i < a->num_vts; i++){ printf("\t\t%lu : ", TOLU(i)); p_start = a->vt_wts[i]->elts; p_end = (char *)p_start + a->vt_wts[i]->num_elts * a->pair_size; for (p = p_start; p != p_end; p = (char *)p + a->pair_size){ print_wt((char *)p + a->wt_offset); } printf("\n"); } } } void print_test_result(int res){ if (res){ printf("SUCCESS\n"); }else{ printf("FAILURE\n"); } } int main(int argc, char *argv[]){ int i; size_t *args = NULL; RGENS_SEED(); if (argc > C_ARGC_ULIMIT){ printf("USAGE:\n%s", C_USAGE); exit(EXIT_FAILURE); } args = malloc_perror(C_ARGC_ULIMIT - 1, sizeof(size_t)); memcpy(args, C_ARGS_DEF, (C_ARGC_ULIMIT - 1) * sizeof(size_t)); for (i = 1; i < argc; i++){ args[i - 1] = atoi(argv[i]); } if (args[0] > C_FULL_BIT / 2 || args[1] > C_FULL_BIT / 2 || args[1] < args[0] || args[2] > 1 || args[3] > 1 || args[4] > 1){ printf("USAGE:\n%s", C_USAGE); exit(EXIT_FAILURE); } if (args[2]) run_small_graph_test(); if (args[3]) run_adj_lst_undir_build_test(args[0], args[1]); if (args[4]){ run_adj_lst_add_dir_edge_test(args[0], args[1]); run_adj_lst_add_undir_edge_test(args[0], args[1]); run_adj_lst_rand_dir_test(args[0], args[1]); run_adj_lst_rand_undir_test(args[0], args[1]); } free(args); args = NULL; return 0; }
alfin3/graph-algorithms
utilities/utilities-mod/utilities-mod.c
<reponame>alfin3/graph-algorithms /** utilities-mod.c Utility functions in modular arithmetic. The utility functions are integer overflow-safe. The provided implementations assume that the width of size_t is even. */ #include <stdio.h> #include <stdlib.h> #include <limits.h> #include "utilities-mod.h" #include "utilities-lim.h" static const size_t C_SIZE_HALF = (((size_t)1 << (PRECISION_FROM_ULIMIT((size_t)-1) / 2u)) - 1u); static const size_t C_FULL_BIT = PRECISION_FROM_ULIMIT((size_t)-1); static const size_t C_HALF_BIT = PRECISION_FROM_ULIMIT((size_t)-1) / 2u; static const size_t C_LOW_MASK = ((size_t)-1 >> (PRECISION_FROM_ULIMIT((size_t)-1) / 2u)); /** Computes overflow-safe mod n of the kth power in O(logk) time, based on the binary representation of k and inductively applying the following relations: if a1 ≡ b1 (mod n) and a2 ≡ b2 (mod n) then a1 a2 ≡ b1 b2 (mod n), and a1 + a2 ≡ b1 + b2 (mod n). */ size_t pow_mod(size_t a, size_t k, size_t n){ size_t k_shift = k; size_t ret; if (n == 1) return 0; ret = 1; while (k_shift){ if (k_shift & 1){ ret = mul_mod(ret, a, n); /* update for each set bit */ } a = mul_mod(a, a, n); /* repetitive squaring between updates */ k_shift >>= 1; } return ret; } /** Computes overflow-safe (a * b) mod n, by applying the following relation: if a1 ≡ b1 (mod n) and a2 ≡ b2 (mod n) then a1 + a2 ≡ b1 + b2 (mod n). */ size_t mul_mod(size_t a, size_t b, size_t n){ size_t al, bl, ah, bh, ah_bh; size_t ret; size_t i; /* comparisons for speed up */ if (n == 1 || a == 0 || b == 0) return 0; if (a <= C_SIZE_HALF && b <= C_SIZE_HALF){ return (a * b) % n; } al = a & C_LOW_MASK; bl = b & C_LOW_MASK; ah = a >> C_HALF_BIT; bh = b >> C_HALF_BIT; ah_bh = ah * bh; for (i = 0; i < C_HALF_BIT; i++){ ah_bh = sum_mod(ah_bh, ah_bh, n); } ret = sum_mod(ah_bh, ah * bl, n); ret = sum_mod(ret, al * bh, n); for (i = 0; i < C_HALF_BIT; i++){ ret = sum_mod(ret, ret, n); } ret = sum_mod(ret, al * bl, n); return ret; } /** Computes overflow-safe (a + b) mod n, by applying the following relation: if a1 ≡ b1 (mod n) and a2 ≡ b2 (mod n) then a1 + a2 ≡ b1 + b2 (mod n). Note: this version with last unpredictable branch is faster at -O3 than the below non-branching version tested with gcc on hash table performance: rem = n - a; mask = (size_t)-(rem > b); return (a & mask) + b - (rem & ~mask); */ size_t sum_mod(size_t a, size_t b, size_t n){ size_t rem; if (n == 1) return 0; if (a == 0) return b % n; if (b == 0) return a % n; if (a >= n) a = a % n; if (b >= n) b = b % n; /* a, b < n, can subtract at most one n from a + b */ rem = n - a; /* >= 1 */ if (rem <= b){ return b - rem; }else{ return a + b; } } /** Multiplies two numbers in an overflow-safe manner and copies the high and low bits of the product into the preallocated blocks pointed to by h and l. */ void mul_ext(size_t a, size_t b, size_t *h, size_t *l){ size_t al, bl, ah, bh, al_bl, al_bh; size_t overlap; al = a & C_LOW_MASK; bl = b & C_LOW_MASK; ah = a >> C_HALF_BIT; bh = b >> C_HALF_BIT; al_bl = al * bl; al_bh = al * bh; overlap = ((bl * ah & C_LOW_MASK) + (al_bh & C_LOW_MASK) + (al_bl >> C_HALF_BIT)); *h = ((overlap >> C_HALF_BIT) + ah * bh + (ah * bl >> C_HALF_BIT) + (al_bh >> C_HALF_BIT)); *l = (overlap << C_HALF_BIT) + (al_bl & C_LOW_MASK); } /** Represents n as u * 2**k, where u is odd. */ void represent_uint(size_t n, size_t *k, size_t *u){ size_t c = 0; size_t shift_n = n; while (shift_n){ c++; shift_n <<= 1; } *k = C_FULL_BIT - c; *u = n >> *k; } /** Returns the kth power of 2, if 0 <= k < size_t width. Exits with an error otherwise. */ size_t pow_two_perror(size_t k){ if (k >= C_FULL_BIT){ perror("pow_two size_t overflow"); exit(EXIT_FAILURE); } return (size_t)1 << k; }
alfin3/graph-algorithms
graph-algorithms/tsp/tsp.h
/** tsp.h Declarations of accessible functions for running an exact solution of TSP without vertex revisiting on graphs with generic weights, including negative weights, with a hash table parameter. Vertices are indexed from 0. Edge weights are of any basic type (e.g. char, int, long, float, double), or are custom weights within a contiguous block (e.g. pair of 64-bit segments to address the potential overflow due to addition). The algorithm provides O(2^n n^2) assymptotic runtime, where n is the number of vertices in a tour, as well as tour existence detection. A bit array representation provides time and space efficient set membership and union operations over O(2^n) sets. The hash table parameter specifies a hash table used for set hashing operations, and enables the optimization of the associated space and time resources by choice of a hash table and its load factor upper bound. If NULL is passed as a hash table parameter value, a default hash table is used, which contains an array with a count that is equal to n * 2^n, where n is the number of vertices in the graph. If E >> V and V < sizeof(size_t) * CHAR_BIT, a default hash table may provide speed advantages by avoiding the computation of hash values. If V is larger and the graph is sparse, a non-default hash table may provide space advantages. */ #ifndef TSP_H #define TSP_H #include <stddef.h> #include "graph.h" typedef void (*tsp_ht_init)(void *, size_t, size_t, void (*)(void *), /* free_elt */ void *); /* pointer to context */ typedef void (*tsp_ht_insert)(void *, const void *, const void *); typedef void *(*tsp_ht_search)(const void *, const void *); typedef void (*tsp_ht_remove)(void *, const void *, void *); typedef void (*tsp_ht_free)(void *); typedef struct{ void *ht; /* points to a block of hash table struct size */ void *context; /* points to initialization context */ tsp_ht_init init; tsp_ht_insert insert; tsp_ht_search search; tsp_ht_remove remove; tsp_ht_free free; } tsp_ht_t; /** Copies to the block pointed to by dist the shortest tour length from start to start across all vertices without revisiting, if a tour exists. Returns 0 if a tour exists, otherwise returns 1. a : pointer to an adjacency list with at least one vertex start : start vertex for running the algorithm dist : pointer to a preallocated block of the size of a weight in the adjacency list tht : - NULL pointer, if a default hash table is used for set hashing operations; a default hash table contains an array with a count that is equal to n * 2^n, where n is the number of vertices in the adjacency list; the maximal n in a default hash table is system-dependent and is less than sizeof(size_t) * CHAR_BIT; if the allocation of a default hash table fails, the program terminates with an error message - a pointer to a set of parameters specifying a hash table used for set hashing operations; the size of a hash key is k * (1 + lowest # k-sized blocks s.t. # bits >= # vertices), where k = sizeof(size_t) add_wt : addition function which copies the sum of the weight values pointed to by the second and third arguments to the preallocated weight block pointed to by the first argument cmp_wt : comparison function which returns a negative integer value if the weight value pointed to by the first argument is less than the weight value pointed to by the second, a positive integer value if the weight value pointed to by the first argument is greater than the weight value pointed to by the second, and zero integer value if the two weight values are equal */ int tsp(const adj_lst_t *a, size_t start, void *dist, const tsp_ht_t *tht, void (*add_wt)(void *, const void *, const void *), int (*cmp_wt)(const void *, const void *)); #endif
alfin3/graph-algorithms
graph-algorithms/dijkstra/dijkstra-test.c
/** dijkstra-test.c Tests of Dijkstra's algorithm with a hash table parameter across i) default, division-based and multiplication-based hash tables, ii) vertex types, and iii) edge weight types. The following command line arguments can be used to customize tests: dijkstra-test: - [0, ushort width) : n for 2**n vertices in the smallest graph - [0, ushort width) : n for 2**n vertices in the largest graph - [0, 1] : small graph test on/off - [0, 1] : bfs comparison test on/off - [0, 1] : test on random graphs with random weights on/off usage examples: ./dijkstra-test ./dijkstra-test 10 12 ./dijkstra-test 13 13 0 0 1 dijkstra-test can be run with any subset of command line arguments in the above-defined order. If the (i + 1)th argument is specified then the ith argument must be specified for i >= 0. Default values are used for the unspecified arguments according to the C_ARGS_DEF array. The implementation of tests does not use stdint.h and is portable under C89/C90 and C99. The tests require that: - size_t and clock_t are convertible to double, - size_t can represent values upto 65535 for default values, and upto USHRT_MAX (>= 65535) otherwise, - the widths of the unsigned integral types are less than 2040 and even. TODO: add portable size_t printing */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <limits.h> #include <time.h> #include "dijkstra.h" #include "bfs.h" #include "heap.h" #include "ht-divchn.h" #include "ht-muloa.h" #include "graph.h" #include "stack.h" #include "utilities-mem.h" #include "utilities-mod.h" #include "utilities-lim.h" /** Generate random numbers in a portable way for test purposes only; rand() in the Linux C Library uses the same generator as random(), which may not be the case on older rand() implementations, and on current implementations on different systems. */ #define RGENS_SEED() do{srand(time(NULL));}while (0) #define RANDOM() (rand()) /* [0, RAND_MAX] */ #define DRAND() ((double)rand() / RAND_MAX) /* [0.0, 1.0] */ #define TOLU(i) ((unsigned long int)(i)) /* printing size_t under C89/C90 */ /* input handling */ const char *C_USAGE = "dijkstra-test \n" "[0, ushort width) : n for 2**n vertices in smallest graph\n" "[0, ushort width) : n for 2**n vertices in largest graph\n" "[0, 1] : small graph test on/off\n" "[0, 1] : bfs comparison test on/off\n" "[0, 1] : random graphs with random weights test on/off\n"; const int C_ARGC_ULIMIT = 6; const size_t C_ARGS_DEF[5] = {6u, 9u, 1u, 1u, 1u}; /* hash table load factor upper bounds */ const size_t C_ALPHA_N_DIVCHN = 1u; const size_t C_LOG_ALPHA_D_DIVCHN = 0u; const size_t C_ALPHA_N_MULOA = 13107u; const size_t C_LOG_ALPHA_D_MULOA = 15u; /* small graph tests */ const size_t C_NUM_VTS = 5u; const size_t C_NUM_ES = 4u; const unsigned short C_USHORT_U[4] = {0u, 0u, 0u, 1u}; const unsigned short C_USHORT_V[4] = {1u, 2u, 3u, 3u}; const unsigned short C_USHORT_WTS[4] = {4u, 3u, 2u, 1u}; const unsigned int C_UINT_U[4] = {0u, 0u, 0u, 1u}; const unsigned int C_UINT_V[4] = {1u, 2u, 3u, 3u}; const unsigned int C_UINT_WTS[4] = {4u, 3u, 2u, 1u}; const unsigned long C_ULONG_U[4] = {0u, 0u, 0u, 1u}; const unsigned long C_ULONG_V[4] = {1u, 2u, 3u, 3u}; const unsigned long C_ULONG_WTS[4] = {4u, 3u, 2u, 1u}; const size_t C_SZ_U[4] = {0u, 0u, 0u, 1u}; const size_t C_SZ_V[4] = {1u, 2u, 3u, 3u}; const size_t C_SZ_WTS[4] = {4u, 3u, 2u, 1u}; const double C_DOUBLE_WTS[4] = {4.0, 3.0, 2.0, 1.0}; /* small graph initialization ops */ void init_ushort_ushort(struct graph *g); void init_ushort_uint(struct graph *g); void init_ushort_ulong(struct graph *g); void init_ushort_sz(struct graph *g); void init_ushort_double(struct graph *g); void init_uint_ushort(struct graph *g); void init_uint_uint(struct graph *g); void init_uint_ulong(struct graph *g); void init_uint_sz(struct graph *g); void init_uint_double(struct graph *g); void init_ulong_ushort(struct graph *g); void init_ulong_uint(struct graph *g); void init_ulong_ulong(struct graph *g); void init_ulong_sz(struct graph *g); void init_ulong_double(struct graph *g); void init_sz_ushort(struct graph *g); void init_sz_uint(struct graph *g); void init_sz_ulong(struct graph *g); void init_sz_sz(struct graph *g); void init_sz_double(struct graph *g); const size_t C_FN_VT_COUNT = 4u; const size_t C_FN_WT_COUNT = 5u; const size_t C_FN_INTEGRAL_WT_COUNT = 4u; void (* const C_INIT_GRAPH[4][5])(struct graph *) ={ {init_ushort_ushort, init_ushort_uint, init_ushort_ulong, init_ushort_sz, init_ushort_double}, {init_uint_ushort, init_uint_uint, init_uint_ulong, init_uint_sz, init_uint_double}, {init_ulong_ushort, init_ulong_uint, init_ulong_ulong, init_ulong_sz, init_ulong_double}, {init_sz_ushort, init_sz_uint, init_sz_ulong, init_sz_sz, init_sz_double}}; /* vertex ops */ size_t (* const C_READ_VT[4])(const void *) ={ graph_read_ushort, graph_read_uint, graph_read_ulong, graph_read_sz}; void (* const C_WRITE_VT[4])(void *, size_t) ={ graph_write_ushort, graph_write_uint, graph_write_ulong, graph_write_sz}; void *(* const C_AT_VT[4])(const void *, const void *) ={ graph_at_ushort, graph_at_uint, graph_at_ulong, graph_at_sz}; int (* const C_CMP_VT[4])(const void *, const void *) ={ graph_cmpeq_ushort, graph_cmpeq_uint, graph_cmpeq_ulong, graph_cmpeq_sz}; void (* const C_INCR_VT[4])(void *) ={ graph_incr_ushort, graph_incr_uint, graph_incr_ulong, graph_incr_sz}; const size_t C_VT_SIZES[4] = { sizeof(unsigned short), sizeof(unsigned int), sizeof(unsigned long), sizeof(size_t)}; const char *C_VT_TYPES[4] = {"ushort", "uint ", "ulong ", "sz "}; /* weight and print ops */ int cmp_double(const void *a, const void *b); void add_double(void *s, const void *a, const void *b); int (* const C_CMP_WT[5])(const void *, const void *) ={ graph_cmp_ushort, graph_cmp_uint, graph_cmp_ulong, graph_cmp_sz, cmp_double}; void (* const C_ADD_WT[5])(void *, const void *, const void *) ={ graph_add_ushort, graph_add_uint, graph_add_ulong, graph_add_sz, add_double}; const size_t C_WT_SIZES[5] = { sizeof(unsigned short), sizeof(unsigned int), sizeof(unsigned long), sizeof(size_t), sizeof(double)}; const char *C_WT_TYPES[5] = {"ushort", "uint ", "ulong ", "sz ", "double"}; /* random graph tests */ /* C89 (draft): USHRT_MAX >= 65535, UINT_MAX >= 65535, ULONG_MAX >= 4294967295, RAND_MAX >= 32767 */ const size_t C_RANDOM_BIT = 15u; const unsigned int C_RANDOM_MASK = 32767u; const size_t C_USHORT_BIT = PRECISION_FROM_ULIMIT(USHRT_MAX); const size_t C_USHORT_BIT_MOD = PRECISION_FROM_ULIMIT(USHRT_MAX) / 15u; const size_t C_USHORT_HALF_BIT = PRECISION_FROM_ULIMIT(USHRT_MAX) / 2u; const unsigned short C_USHORT_ULIMIT = USHRT_MAX; const unsigned short C_USHORT_LOW_MASK = ((unsigned short)-1 >> (PRECISION_FROM_ULIMIT(USHRT_MAX) / 2u)); const size_t C_UINT_BIT = PRECISION_FROM_ULIMIT(UINT_MAX); const size_t C_UINT_BIT_MOD = PRECISION_FROM_ULIMIT(UINT_MAX) / 15u; const size_t C_UINT_HALF_BIT = PRECISION_FROM_ULIMIT(UINT_MAX) / 2u; const unsigned int C_UINT_ULIMIT = UINT_MAX; const unsigned int C_UINT_LOW_MASK = ((unsigned int)-1 >> (PRECISION_FROM_ULIMIT(UINT_MAX) / 2u)); const size_t C_ULONG_BIT = PRECISION_FROM_ULIMIT(ULONG_MAX); const size_t C_ULONG_BIT_MOD = PRECISION_FROM_ULIMIT(ULONG_MAX) / 15u; const size_t C_ULONG_HALF_BIT = PRECISION_FROM_ULIMIT(ULONG_MAX) / 2u; const unsigned long C_ULONG_ULIMIT = ULONG_MAX; const unsigned long C_ULONG_LOW_MASK = ((unsigned long)-1 >> (PRECISION_FROM_ULIMIT(ULONG_MAX) / 2u)); const size_t C_SZ_BIT = PRECISION_FROM_ULIMIT((size_t)-1); const size_t C_SZ_BIT_MOD = PRECISION_FROM_ULIMIT((size_t)-1) / 15u; const size_t C_SZ_HALF_BIT = PRECISION_FROM_ULIMIT((size_t)-1) / 2u; const size_t C_SZ_ULIMIT = (size_t)-1; const size_t C_SZ_LOW_MASK = ((size_t)-1 >> (PRECISION_FROM_ULIMIT((size_t)-1) / 2u)); const size_t C_ITER = 10u; const size_t C_PROBS_COUNT = 7u; const double C_PROBS[7] = {1.000000, 0.250000, 0.062500, 0.015625, 0.003906, 0.000977, 0.000000}; /* random number generation and random graph construction */ unsigned short random_ushort(); unsigned int random_uint(); unsigned long random_ulong(); size_t random_sz(); unsigned short mul_high_ushort(unsigned short a, unsigned short b); unsigned int mul_high_uint(unsigned int a, unsigned int b); unsigned long mul_high_ulong(unsigned long a, unsigned long b); size_t mul_high_sz(size_t a, size_t b); void add_dir_ushort_edge(struct adj_lst *a, size_t u, size_t v, const void *wt_l, const void *wt_h, void (*write_vt)(void *, size_t), int (*bern)(void *), void *arg); void add_dir_uint_edge(struct adj_lst *a, size_t u, size_t v, const void *wt_l, const void *wt_h, void (*write_vt)(void *, size_t), int (*bern)(void *), void *arg); void add_dir_ulong_edge(struct adj_lst *a, size_t u, size_t v, const void *wt_l, const void *wt_h, void (*write_vt)(void *, size_t), int (*bern)(void *), void *arg); void add_dir_sz_edge(struct adj_lst *a, size_t u, size_t v, const void *wt_l, const void *wt_h, void (*write_vt)(void *, size_t), int (*bern)(void *), void *arg); void add_dir_double_edge(struct adj_lst *a, size_t u, size_t v, const void *wt_l, const void *wt_h, void (*write_vt)(void *, size_t), int (*bern)(void *), void *arg); void (* const C_ADD_DIR_EDGE[5])(struct adj_lst *, size_t, size_t, const void *, const void *, void (*)(void *, size_t), int (*)(void *), void *) ={ add_dir_ushort_edge, add_dir_uint_edge, add_dir_ulong_edge, add_dir_sz_edge, add_dir_double_edge}; /* value initiliazation and printing */ void set_zero_ushort(void *a); void set_zero_uint(void *a); void set_zero_ulong(void *a); void set_zero_sz(void *a); void set_zero_double(void *a); void set_one_ushort(void *a); void set_one_uint(void *a); void set_one_ulong(void *a); void set_one_sz(void *a); void set_one_double(void *a); void set_test_ulimit_ushort(void *a, size_t num_vts); void set_test_ulimit_uint(void *a, size_t num_vts); void set_test_ulimit_ulong(void *a, size_t num_vts); void set_test_ulimit_sz(void *a, size_t num_vts); void set_test_ulimit_double(void *a, size_t num_vts); void sum_dist_ushort(void *dist_sum, void *wt_sum, size_t *num_dist_wraps, size_t *num_wt_wraps, size_t *num_paths, size_t num_vts, size_t vt_size, const void *prev, const void *dist, size_t (*read_vt)(const void *)); void sum_dist_uint(void *dist_sum, void *wt_sum, size_t *num_dist_wraps, size_t *num_wt_wraps, size_t *num_paths, size_t num_vts, size_t vt_size, const void *prev, const void *dist, size_t (*read_vt)(const void *)); void sum_dist_ulong(void *dist_sum, void *wt_sum, size_t *num_dist_wraps, size_t *num_wt_wraps, size_t *num_paths, size_t num_vts, size_t vt_size, const void *prev, const void *dist, size_t (*read_vt)(const void *)); void sum_dist_sz(void *dist_sum, void *wt_sum, size_t *num_dist_wraps, size_t *num_wt_wraps, size_t *num_paths, size_t num_vts, size_t vt_size, const void *prev, const void *dist, size_t (*read_vt)(const void *)); void sum_dist_double(void *dist_sum, void *wt_sum, size_t *num_dist_wraps, size_t *num_wt_wraps, size_t *num_paths, size_t num_vts, size_t vt_size, const void *prev, const void *dist, size_t (*read_vt)(const void *)); void print_ushort(const void *a); void print_uint(const void *a); void print_ulong(const void *a); void print_sz(const void *a); void print_double(const void *a); void (* const C_SET_ZERO[5])(void *) ={ set_zero_ushort, set_zero_uint, set_zero_ulong, set_zero_sz, set_zero_double}; void (* const C_SET_ONE[5])(void *) ={ set_one_ushort, set_one_uint, set_one_ulong, set_one_sz, set_one_double}; void (* const C_SET_TEST_ULIMIT[5])(void *, size_t) ={ set_test_ulimit_ushort, set_test_ulimit_uint, set_test_ulimit_ulong, set_test_ulimit_sz, set_test_ulimit_double}; void (* const C_SUM_DIST[5])(void *, void *, size_t *, size_t *, size_t *, size_t, size_t, const void *, const void *, size_t (*)(const void *)) ={ sum_dist_ushort, sum_dist_uint, sum_dist_ulong, sum_dist_sz, sum_dist_double}; void (* const C_PRINT[5])(const void *) ={ print_ushort, print_uint, print_ulong, print_sz, print_double}; /* additional operations */ void *ptr(const void *block, size_t i, size_t size); void print_arr(const void *arr, size_t size, size_t n, void (*print_elt)(const void *)); void print_prev(const struct adj_lst *a, const void *prev, void (*print_vt)(const void *)); void print_dist(const struct adj_lst *a, const void *dist, const void *prev, const void *wt_zero, size_t (*read_vt)(const void *), void (*print_wt)(const void *)); void print_adj_lst(const struct adj_lst *a, void (*print_vt)(const void *), void (*print_wt)(const void *)); void print_test_result(int res); /** Initialize small graphs across vertex and weight types. */ void init_ushort_ushort(struct graph *g){ graph_base_init(g, C_NUM_VTS, sizeof(unsigned short), sizeof(unsigned short)); g->num_es = C_NUM_ES; g->u = (unsigned short *)C_USHORT_U; g->v = (unsigned short *)C_USHORT_V; g->wts = (unsigned short *)C_USHORT_WTS; } void init_ushort_uint(struct graph *g){ graph_base_init(g, C_NUM_VTS, sizeof(unsigned short), sizeof(unsigned int)); g->num_es = C_NUM_ES; g->u = (unsigned short *)C_USHORT_U; g->v = (unsigned short *)C_USHORT_V; g->wts = (unsigned int *)C_UINT_WTS; } void init_ushort_ulong(struct graph *g){ graph_base_init(g, C_NUM_VTS, sizeof(unsigned short), sizeof(unsigned long)); g->num_es = C_NUM_ES; g->u = (unsigned short *)C_USHORT_U; g->v = (unsigned short *)C_USHORT_V; g->wts = (unsigned long *)C_ULONG_WTS; } void init_ushort_sz(struct graph *g){ graph_base_init(g, C_NUM_VTS, sizeof(unsigned short), sizeof(size_t)); g->num_es = C_NUM_ES; g->u = (unsigned short *)C_USHORT_U; g->v = (unsigned short *)C_USHORT_V; g->wts = (size_t *)C_SZ_WTS; } void init_ushort_double(struct graph *g){ graph_base_init(g, C_NUM_VTS, sizeof(unsigned short), sizeof(double)); g->num_es = C_NUM_ES; g->u = (unsigned short *)C_USHORT_U; g->v = (unsigned short *)C_USHORT_V; g->wts = (double *)C_DOUBLE_WTS; } void init_uint_ushort(struct graph *g){ graph_base_init(g, C_NUM_VTS, sizeof(unsigned int), sizeof(unsigned short)); g->num_es = C_NUM_ES; g->u = (unsigned int *)C_UINT_U; g->v = (unsigned int *)C_UINT_V; g->wts = (unsigned short *)C_USHORT_WTS; } void init_uint_uint(struct graph *g){ graph_base_init(g, C_NUM_VTS, sizeof(unsigned int), sizeof(unsigned int)); g->num_es = C_NUM_ES; g->u = (unsigned int *)C_UINT_U; g->v = (unsigned int *)C_UINT_V; g->wts = (unsigned int *)C_UINT_WTS; } void init_uint_ulong(struct graph *g){ graph_base_init(g, C_NUM_VTS, sizeof(unsigned int), sizeof(unsigned long)); g->num_es = C_NUM_ES; g->u = (unsigned int *)C_UINT_U; g->v = (unsigned int *)C_UINT_V; g->wts = (unsigned long *)C_ULONG_WTS; } void init_uint_sz(struct graph *g){ graph_base_init(g, C_NUM_VTS, sizeof(unsigned int), sizeof(size_t)); g->num_es = C_NUM_ES; g->u = (unsigned int *)C_UINT_U; g->v = (unsigned int *)C_UINT_V; g->wts = (size_t *)C_SZ_WTS; } void init_uint_double(struct graph *g){ graph_base_init(g, C_NUM_VTS, sizeof(unsigned int), sizeof(double)); g->num_es = C_NUM_ES; g->u = (unsigned int *)C_UINT_U; g->v = (unsigned int *)C_UINT_V; g->wts = (double *)C_DOUBLE_WTS; } void init_ulong_ushort(struct graph *g){ graph_base_init(g, C_NUM_VTS, sizeof(unsigned long), sizeof(unsigned short)); g->num_es = C_NUM_ES; g->u = (unsigned long *)C_ULONG_U; g->v = (unsigned long *)C_ULONG_V; g->wts = (unsigned short *)C_USHORT_WTS; } void init_ulong_uint(struct graph *g){ graph_base_init(g, C_NUM_VTS, sizeof(unsigned long), sizeof(unsigned int)); g->num_es = C_NUM_ES; g->u = (unsigned long *)C_ULONG_U; g->v = (unsigned long *)C_ULONG_V; g->wts = (unsigned int *)C_UINT_WTS; } void init_ulong_ulong(struct graph *g){ graph_base_init(g, C_NUM_VTS, sizeof(unsigned long), sizeof(unsigned long)); g->num_es = C_NUM_ES; g->u = (unsigned long *)C_ULONG_U; g->v = (unsigned long *)C_ULONG_V; g->wts = (unsigned long *)C_ULONG_WTS; } void init_ulong_sz(struct graph *g){ graph_base_init(g, C_NUM_VTS, sizeof(unsigned long), sizeof(size_t)); g->num_es = C_NUM_ES; g->u = (unsigned long *)C_ULONG_U; g->v = (unsigned long *)C_ULONG_V; g->wts = (size_t *)C_SZ_WTS; } void init_ulong_double(struct graph *g){ graph_base_init(g, C_NUM_VTS, sizeof(unsigned long), sizeof(double)); g->num_es = C_NUM_ES; g->u = (unsigned long *)C_ULONG_U; g->v = (unsigned long *)C_ULONG_V; g->wts = (double *)C_DOUBLE_WTS; } void init_sz_ushort(struct graph *g){ graph_base_init(g, C_NUM_VTS, sizeof(size_t), sizeof(unsigned short)); g->num_es = C_NUM_ES; g->u = (size_t *)C_SZ_U; g->v = (size_t *)C_SZ_V; g->wts = (unsigned short *)C_USHORT_WTS; } void init_sz_uint(struct graph *g){ graph_base_init(g, C_NUM_VTS, sizeof(size_t), sizeof(unsigned int)); g->num_es = C_NUM_ES; g->u = (size_t *)C_SZ_U; g->v = (size_t *)C_SZ_V; g->wts = (unsigned int *)C_UINT_WTS; } void init_sz_ulong(struct graph *g){ graph_base_init(g, C_NUM_VTS, sizeof(size_t), sizeof(unsigned long)); g->num_es = C_NUM_ES; g->u = (size_t *)C_SZ_U; g->v = (size_t *)C_SZ_V; g->wts = (unsigned long *)C_ULONG_WTS; } void init_sz_sz(struct graph *g){ graph_base_init(g, C_NUM_VTS, sizeof(size_t), sizeof(size_t)); g->num_es = C_NUM_ES; g->u = (size_t *)C_SZ_U; g->v = (size_t *)C_SZ_V; g->wts = (size_t *)C_SZ_WTS; } void init_sz_double(struct graph *g){ graph_base_init(g, C_NUM_VTS, sizeof(size_t), sizeof(double)); g->num_es = C_NUM_ES; g->u = (size_t *)C_SZ_U; g->v = (size_t *)C_SZ_V; g->wts = (double *)C_DOUBLE_WTS; } /** Run a test on small graphs across vertex and weight types. */ int cmp_double(const void *a, const void *b){ return ((*(const double *)a > *(const double *)b) - (*(const double *)a < *(const double *)b)); } void add_double(void *s, const void *a, const void *b){ *(double *)s = *(const double *)a + *(const double *)b; } void small_graph_helper(void (*build)(struct adj_lst *, const struct graph *, size_t (*)(const void *))){ size_t i, j, k, l; void *wt_zero = NULL; void *dist_def = NULL, *dist_divchn = NULL, *dist_muloa = NULL; void *prev_def = NULL, *prev_divchn = NULL, *prev_muloa = NULL; struct graph g; struct adj_lst a; struct ht_divchn ht_divchn; struct ht_muloa ht_muloa; struct dijkstra_ht daht_divchn, daht_muloa; daht_divchn.ht = &ht_divchn; daht_divchn.alpha_n = C_ALPHA_N_DIVCHN; daht_divchn.log_alpha_d = C_LOG_ALPHA_D_DIVCHN; daht_divchn.init = ht_divchn_init_helper; daht_divchn.align = ht_divchn_align_helper; daht_divchn.insert = ht_divchn_insert_helper; daht_divchn.search = ht_divchn_search_helper; daht_divchn.remove = ht_divchn_remove_helper; daht_divchn.free = ht_divchn_free_helper; daht_muloa.ht = &ht_muloa; daht_muloa.alpha_n = C_ALPHA_N_MULOA; daht_muloa.log_alpha_d = C_LOG_ALPHA_D_MULOA; daht_muloa.init = ht_muloa_init_helper; daht_muloa.align = ht_muloa_align_helper; daht_muloa.insert = ht_muloa_insert_helper; daht_muloa.search = ht_muloa_search_helper; daht_muloa.remove = ht_muloa_remove_helper; daht_muloa.free = ht_muloa_free_helper; for (i = 0; i < C_NUM_VTS; i++){ printf("\tstart vertex: %lu\n", TOLU(i)); for (j = 0; j < C_FN_VT_COUNT; j++){ printf("\t\tvertex type: %s\n", C_VT_TYPES[j]); for (k = 0; k < C_FN_WT_COUNT; k++){ printf("\t\t\tweight type: %s\n", C_WT_TYPES[k]); C_INIT_GRAPH[j][k](&g); adj_lst_base_init(&a, &g); build(&a, &g, C_READ_VT[j]); /* no declared type after realloc; new eff. type to be acquired */ wt_zero = realloc_perror(wt_zero, 1, a.wt_size); prev_def = realloc_perror(prev_def, a.num_vts, a.vt_size); prev_divchn = realloc_perror(prev_divchn, a.num_vts, a.vt_size); prev_muloa = realloc_perror(prev_muloa, a.num_vts, a.vt_size); dist_def = realloc_perror(dist_def, a.num_vts, a.wt_size); dist_divchn = realloc_perror(dist_divchn, a.num_vts, a.wt_size); dist_muloa = realloc_perror(dist_muloa, a.num_vts, a.wt_size); C_SET_ZERO[k](wt_zero); for (l = 0; l < a.num_vts; l++){ /* avoid trap representations in tests */ C_SET_ZERO[k](ptr(dist_def, l, a.wt_size)); C_SET_ZERO[k](ptr(dist_divchn, l, a.wt_size)); C_SET_ZERO[k](ptr(dist_muloa, l, a.wt_size)); } dijkstra(&a, i, dist_def, prev_def, wt_zero, NULL, C_READ_VT[j], C_WRITE_VT[j], C_AT_VT[j], C_CMP_VT[j], C_CMP_WT[k], C_ADD_WT[k]); dijkstra(&a, i, dist_divchn, prev_divchn, wt_zero, &daht_divchn, C_READ_VT[j], C_WRITE_VT[j], C_AT_VT[j], C_CMP_VT[j], C_CMP_WT[k], C_ADD_WT[k]); dijkstra(&a, i, dist_muloa, prev_muloa, wt_zero, &daht_muloa, C_READ_VT[j], C_WRITE_VT[j], C_AT_VT[j], C_CMP_VT[j], C_CMP_WT[k], C_ADD_WT[k]); adj_lst_free(&a); printf("\t\t\t\tdefault dist: "); print_dist(&a, dist_def, prev_def, wt_zero, C_READ_VT[j], C_PRINT[k]); printf("\n"); printf("\t\t\t\tdivchn dist: "); print_dist(&a, dist_divchn, prev_divchn, wt_zero, C_READ_VT[j], C_PRINT[k]); printf("\n"); printf("\t\t\t\tmuloa dist: "); print_dist(&a, dist_muloa, prev_muloa, wt_zero, C_READ_VT[j], C_PRINT[k]); printf("\n"); printf("\t\t\t\tdefault prev: "); print_prev(&a, prev_def, C_PRINT[j]); printf("\n"); printf("\t\t\t\tdivchn prev: "); print_prev(&a, prev_divchn, C_PRINT[j]); printf("\n"); printf("\t\t\t\tmuloa prev: "); print_prev(&a, prev_muloa, C_PRINT[j]); printf("\n"); } } } printf("\n"); free(wt_zero); free(dist_def); free(dist_divchn); free(dist_muloa); free(prev_def); free(prev_divchn); free(prev_muloa); wt_zero = NULL; dist_def = NULL; dist_divchn = NULL; dist_muloa = NULL; prev_def = NULL; prev_divchn = NULL; prev_muloa = NULL; } void run_small_graph_test(){ printf("Run a dijkstra test on a directed graph across vertex and weight" " types, with a\n" "i) default hash table (index array)\n" "ii) ht_divchn hash table\n" "iii) ht_muloa hash table\n\n"); small_graph_helper(adj_lst_dir_build); printf("Run a dijkstra test on an undirected graph across vertex and" " weight types, with a\n" "i) default hash table (index array)\n" "ii) ht_divchn hash table\n" "iii) ht_muloa hash table\n\n"); small_graph_helper(adj_lst_undir_build); } /** Construct adjacency lists of random directed graphs with random weights across vertex and weight types. A function with the add_dir_ prefix adds a (u, v) edge to an adjacency list of a weighted graph, preinitialized with at least adj_lst_base_init and with the number of vertices n greater or equal to 1. An edge (u, v), where u < n nad v < n, is added with the Bernoulli distribution according to the bern and arg parameter values. wt_l and wt_h point to wt_size blocks with values l and h of the type used to represent weights in the adjacency list, and l must be non-negative and less or equal to h. If (u, v) is added, a random weight in [l, h) is chosen for the edge. adj_lst_rand_dir_wts builds a random adjacency list with one of the above functions as a parameter value. g points to a graph preinitialized with graph_base_init with at least one vertex. a points to a preallocated block of size sizeof(struct adj_lst). */ struct bern_arg{ double p; }; int bern(void *arg){ struct bern_arg *b = arg; if (b->p >= 1.0) return 1; if (b->p <= 0.0) return 0; if (b->p > DRAND()) return 1; return 0; } void add_dir_ushort_edge(struct adj_lst *a, size_t u, size_t v, const void *wt_l, const void *wt_h, void (*write_vt)(void *, size_t), int (*bern)(void *), void *arg){ unsigned short rand_val = *(unsigned short *)wt_l + mul_high_ushort(random_ushort(), (*(unsigned short *)wt_h - *(unsigned short *)wt_l)); adj_lst_add_dir_edge(a, u, v, &rand_val, write_vt, bern, arg); } void add_dir_uint_edge(struct adj_lst *a, size_t u, size_t v, const void *wt_l, const void *wt_h, void (*write_vt)(void *, size_t), int (*bern)(void *), void *arg){ unsigned int rand_val = *(unsigned int *)wt_l + mul_high_uint(random_uint(), (*(unsigned int *)wt_h - *(unsigned int *)wt_l)); adj_lst_add_dir_edge(a, u, v, &rand_val, write_vt, bern, arg); } void add_dir_ulong_edge(struct adj_lst *a, size_t u, size_t v, const void *wt_l, const void *wt_h, void (*write_vt)(void *, size_t), int (*bern)(void *), void *arg){ unsigned long rand_val = *(unsigned long *)wt_l + mul_high_ulong(random_ulong(), (*(unsigned long *)wt_h - *(unsigned long *)wt_l)); adj_lst_add_dir_edge(a, u, v, &rand_val, write_vt, bern, arg); } void add_dir_sz_edge(struct adj_lst *a, size_t u, size_t v, const void *wt_l, const void *wt_h, void (*write_vt)(void *, size_t), int (*bern)(void *), void *arg){ size_t rand_val = *(size_t *)wt_l + mul_high_sz(random_sz(), (*(size_t *)wt_h - *(size_t *)wt_l)); adj_lst_add_dir_edge(a, u, v, &rand_val, write_vt, bern, arg); } void add_dir_double_edge(struct adj_lst *a, size_t u, size_t v, const void *wt_l, const void *wt_h, void (*write_vt)(void *, size_t), int (*bern)(void *), void *arg){ double rand_val = *(double *)wt_l + DRAND() * (*(double *)wt_h - *(double *)wt_l); adj_lst_add_dir_edge(a, u, v, &rand_val, write_vt, bern, arg); } void adj_lst_rand_dir_wts(const struct graph *g, struct adj_lst *a, const void *wt_l, const void *wt_h, void (*write_vt)(void *, size_t), int (*bern)(void *), void *arg, void (*add_dir_edge)(struct adj_lst *, size_t, size_t, const void *, const void *, void (*)(void *, size_t), int (*)(void *), void *)){ size_t i, j; adj_lst_base_init(a, g); for (i = 0; i < a->num_vts - 1; i++){ for (j = i + 1; j < a->num_vts; j++){ add_dir_edge(a, i, j, wt_l, wt_h, write_vt, bern, arg); add_dir_edge(a, j, i, wt_l, wt_h, write_vt, bern, arg); } } } /** Run a test of distance equivalence of bfs and dijkstra on random directed graphs with the same weight for all edges, across integral type edge weights, vertex types, as well as default, division-based and multiplication-based hash tables. */ void run_bfs_comparison_test(size_t log_start, size_t log_end){ int res = 1; size_t p, i, j, k, l; size_t num_vts; size_t vt_size; size_t wt_size; size_t *rand_start = NULL; void *wt_l = NULL; void *wt_zero = NULL; void *dist_elt_bfs = NULL; void *dist_bfs = NULL; void *prev_bfs = NULL; void *dist_def = NULL, *dist_divchn = NULL, *dist_muloa = NULL; void *prev_def = NULL, *prev_divchn = NULL, *prev_muloa = NULL; struct graph g; struct adj_lst a; struct bern_arg b; struct ht_divchn ht_divchn; struct ht_muloa ht_muloa; struct dijkstra_ht daht_divchn, daht_muloa; clock_t t_bfs, t_def, t_divchn, t_muloa; rand_start = malloc_perror(C_ITER, sizeof(size_t)); daht_divchn.ht = &ht_divchn; daht_divchn.alpha_n = C_ALPHA_N_DIVCHN; daht_divchn.log_alpha_d = C_LOG_ALPHA_D_DIVCHN; daht_divchn.init = ht_divchn_init_helper; daht_divchn.align = ht_divchn_align_helper; daht_divchn.insert = ht_divchn_insert_helper; daht_divchn.search = ht_divchn_search_helper; daht_divchn.remove = ht_divchn_remove_helper; daht_divchn.free = ht_divchn_free_helper; daht_muloa.ht = &ht_muloa; daht_muloa.alpha_n = C_ALPHA_N_MULOA; daht_muloa.log_alpha_d = C_LOG_ALPHA_D_MULOA; daht_muloa.init = ht_muloa_init_helper; daht_muloa.align = ht_muloa_align_helper; daht_muloa.insert = ht_muloa_insert_helper; daht_muloa.search = ht_muloa_search_helper; daht_muloa.remove = ht_muloa_remove_helper; daht_muloa.free = ht_muloa_free_helper; printf("Run a bfs and dijkstra test on random directed graphs across " "vertex types and integer weight types;\nthe runtime is averaged" " over %lu runs from random start vertices\n", TOLU(C_ITER)); fflush(stdout); for (p = 0; p < C_PROBS_COUNT; p++){ b.p = C_PROBS[p]; printf("\tP[an edge is in a graph] = %.4f\n", C_PROBS[p]); for (i = log_start; i <= log_end; i++){ num_vts = pow_two_perror(i); /* 0 < n */ printf("\t\t# vertices: %lu\n", TOLU(num_vts)); for (j = 0; j < C_FN_VT_COUNT; j++){ for (k = 0; k < C_FN_INTEGRAL_WT_COUNT; k++){ vt_size = C_VT_SIZES[j]; wt_size = C_WT_SIZES[k]; /* no declared type after realloc; new eff. type to be acquired */ wt_l = realloc_perror(wt_l, 3, wt_size); wt_zero = ptr(wt_l, 1, wt_size); dist_elt_bfs = ptr(wt_l, 2, wt_size); prev_bfs = realloc_perror(prev_bfs, num_vts, vt_size); prev_def = realloc_perror(prev_def, num_vts, vt_size); prev_divchn = realloc_perror(prev_divchn, num_vts, vt_size); prev_muloa = realloc_perror(prev_muloa, num_vts, vt_size); dist_bfs = realloc_perror(dist_bfs, num_vts, vt_size);/* vt_size */ dist_def = realloc_perror(dist_def, num_vts, wt_size); dist_divchn = realloc_perror(dist_divchn, num_vts, wt_size); dist_muloa = realloc_perror(dist_muloa, num_vts, wt_size); C_SET_ONE[k](wt_l); C_SET_ZERO[k](wt_zero); for (l = 0; l < num_vts; l++){ /* avoid trap representations in tests */ C_SET_ZERO[j](ptr(dist_bfs, l, vt_size)); C_SET_ZERO[k](ptr(dist_def, l, wt_size)); C_SET_ZERO[k](ptr(dist_divchn, l, wt_size)); C_SET_ZERO[k](ptr(dist_muloa, l, wt_size)); } graph_base_init(&g, num_vts, vt_size, wt_size); adj_lst_rand_dir_wts(&g, &a, wt_l, wt_l, C_WRITE_VT[j], bern, &b, C_ADD_DIR_EDGE[k]); for (l = 0; l < C_ITER; l++){ rand_start[l] = mul_high_sz(random_sz(), num_vts); } t_bfs = clock(); for (l = 0; l < C_ITER; l++){ bfs(&a, rand_start[l], dist_bfs, prev_bfs, C_READ_VT[j], C_WRITE_VT[j], C_AT_VT[j], C_CMP_VT[j], C_INCR_VT[j]); } t_bfs = clock() - t_bfs; t_def = clock(); for (l = 0; l < C_ITER; l++){ dijkstra(&a, rand_start[l], dist_def, prev_def, wt_zero, NULL, C_READ_VT[j], C_WRITE_VT[j], C_AT_VT[j], C_CMP_VT[j], C_CMP_WT[k], C_ADD_WT[k]); } t_def = clock() - t_def; t_divchn = clock(); for (l = 0; l < C_ITER; l++){ dijkstra(&a, rand_start[l], dist_divchn, prev_divchn, wt_zero, &daht_divchn, C_READ_VT[j], C_WRITE_VT[j], C_AT_VT[j], C_CMP_VT[j], C_CMP_WT[k], C_ADD_WT[k]); } t_divchn = clock() - t_divchn; t_muloa = clock(); for (l = 0; l < C_ITER; l++){ dijkstra(&a, rand_start[l], dist_muloa, prev_muloa, wt_zero, &daht_muloa, C_READ_VT[j], C_WRITE_VT[j], C_AT_VT[j], C_CMP_VT[j], C_CMP_WT[k], C_ADD_WT[k]); } t_muloa = clock() - t_muloa; for (l = 0; l < num_vts; l++){ if (C_READ_VT[j](ptr(prev_bfs, l, vt_size)) == num_vts){ res *= (C_READ_VT[j](ptr(prev_def, l, vt_size)) == num_vts && C_READ_VT[j](ptr(prev_divchn, l, vt_size)) == num_vts && C_READ_VT[j](ptr(prev_muloa, l, vt_size)) == num_vts); }else{ /* prev may differ from bfs, but distances are equal */ res *= (C_READ_VT[j](ptr(prev_def, l, vt_size)) < num_vts && C_READ_VT[j](ptr(prev_def, l, vt_size)) == C_READ_VT[j](ptr(prev_divchn, l, vt_size)) && C_READ_VT[j](ptr(prev_divchn, l, vt_size)) == C_READ_VT[j](ptr(prev_muloa, l, vt_size))); C_WRITE_VT[k](dist_elt_bfs, C_READ_VT[j](ptr(dist_bfs, l, vt_size))); res *= (C_CMP_WT[k](ptr(dist_def, l, wt_size), ptr(dist_divchn, l, wt_size)) == 0 && C_CMP_WT[k](ptr(dist_divchn, l, wt_size), ptr(dist_muloa, l, wt_size)) == 0 && C_CMP_WT[k](ptr(dist_muloa, l, wt_size), dist_elt_bfs) == 0); } } printf("\t\t\t# edges: %lu\n", TOLU(a.num_es)); printf("\t\t\t\t%s %s bfs: %.8f seconds\n" "\t\t\t\t%s %s dijkstra default ht: %.8f seconds\n" "\t\t\t\t%s %s dijkstra ht_divchn: %.8f seconds\n" "\t\t\t\t%s %s dijkstra ht_muloa: %.8f seconds\n", C_VT_TYPES[j], C_WT_TYPES[k], (double)t_bfs / C_ITER / CLOCKS_PER_SEC, C_VT_TYPES[j], C_WT_TYPES[k], (double)t_def / C_ITER / CLOCKS_PER_SEC, C_VT_TYPES[j], C_WT_TYPES[k], (double)t_divchn / C_ITER / CLOCKS_PER_SEC, C_VT_TYPES[j], C_WT_TYPES[k], (double)t_muloa / C_ITER / CLOCKS_PER_SEC); printf("\t\t\t\t%s %s correctness: ", C_VT_TYPES[j], C_WT_TYPES[k]); print_test_result(res); printf("\n"); res = 1; adj_lst_free(&a); } } } } free(rand_start); free(wt_l); free(dist_bfs); free(prev_bfs); free(dist_def); free(dist_divchn); free(dist_muloa); free(prev_def); free(prev_divchn); free(prev_muloa); rand_start = NULL; wt_l = NULL; wt_zero = NULL; dist_elt_bfs = NULL; dist_bfs = NULL; prev_bfs = NULL; dist_def = NULL; dist_divchn = NULL; dist_muloa = NULL; prev_def = NULL; prev_divchn = NULL; prev_muloa = NULL; } /** Run a test on random directed graphs with random weights, across edge weight types, vertex types, as well as default, division-based and multiplication-based hash tables. */ void run_rand_test(size_t log_start, size_t log_end){ int res = 1; size_t p, i, j, k, l; size_t num_vts; size_t vt_size; size_t wt_size; size_t num_dwraps_def, num_dwraps_divchn, num_dwraps_muloa; size_t num_wwraps_def, num_wwraps_divchn, num_wwraps_muloa; size_t num_paths_def, num_paths_divchn, num_paths_muloa; size_t *rand_start = NULL; void *wt_l = NULL, *wt_h = NULL; void *wt_zero = NULL; void *wsum_def = NULL, *wsum_divchn = NULL, *wsum_muloa = NULL; void *dsum_def = NULL, *dsum_divchn = NULL, *dsum_muloa = NULL; void *dist_def = NULL, *dist_divchn = NULL, *dist_muloa = NULL; void *prev_def = NULL, *prev_divchn = NULL, *prev_muloa = NULL; struct graph g; struct adj_lst a; struct bern_arg b; struct ht_divchn ht_divchn; struct ht_muloa ht_muloa; struct dijkstra_ht daht_divchn, daht_muloa; clock_t t_def, t_divchn, t_muloa; rand_start = malloc_perror(C_ITER, sizeof(size_t)); daht_divchn.ht = &ht_divchn; daht_divchn.alpha_n = C_ALPHA_N_DIVCHN; daht_divchn.log_alpha_d = C_LOG_ALPHA_D_DIVCHN; daht_divchn.init = ht_divchn_init_helper; daht_divchn.align = ht_divchn_align_helper; daht_divchn.insert = ht_divchn_insert_helper; daht_divchn.search = ht_divchn_search_helper; daht_divchn.remove = ht_divchn_remove_helper; daht_divchn.free = ht_divchn_free_helper; daht_muloa.ht = &ht_muloa; daht_muloa.alpha_n = C_ALPHA_N_MULOA; daht_muloa.log_alpha_d = C_LOG_ALPHA_D_MULOA; daht_muloa.init = ht_muloa_init_helper; daht_muloa.align = ht_muloa_align_helper; daht_muloa.insert = ht_muloa_insert_helper; daht_muloa.search = ht_muloa_search_helper; daht_muloa.remove = ht_muloa_remove_helper; daht_muloa.free = ht_muloa_free_helper; printf("Run a dijkstra test on random directed graphs with random weights" " across vertex and weight types;\nthe runtime is averaged" " over %lu runs from random start vertices\n", TOLU(C_ITER)); fflush(stdout); for (p = 0; p < C_PROBS_COUNT; p++){ b.p = C_PROBS[p]; printf("\tP[an edge is in a graph] = %.4f\n", C_PROBS[p]); for (k = 0; k < C_FN_WT_COUNT; k++){ wt_size = C_WT_SIZES[k]; wt_l = realloc_perror(wt_l, 2, wt_size); wt_h = ptr(wt_l, 1, wt_size); C_SET_ZERO[k](wt_l); C_SET_TEST_ULIMIT[k](wt_h, pow_two_perror(log_end)); printf("\t%s range: [", C_WT_TYPES[k]); C_PRINT[k](wt_l); printf(", "); C_PRINT[k](wt_h); printf(")\n"); } for (i = log_start; i <= log_end; i++){ num_vts = pow_two_perror(i); /* 0 < n */ printf("\t\t# vertices: %lu\n", TOLU(num_vts)); for (j = 0; j < C_FN_VT_COUNT; j++){ for (k = 0; k < C_FN_WT_COUNT; k++){ vt_size = C_VT_SIZES[j]; wt_size = C_WT_SIZES[k]; /* no declared type after realloc; new eff. type to be acquired */ wt_l = realloc_perror(wt_l, 3, wt_size); wt_h = ptr(wt_l, 1, wt_size); wt_zero = ptr(wt_l, 2, wt_size); wsum_def =realloc_perror(wsum_def, 1, wt_size); wsum_divchn = realloc_perror(wsum_divchn, 1, wt_size); wsum_muloa = realloc_perror(wsum_muloa, 1, wt_size); dsum_def = realloc_perror(dsum_def, 1, wt_size); dsum_divchn = realloc_perror(dsum_divchn, 1, wt_size); dsum_muloa = realloc_perror(dsum_muloa, 1, wt_size); prev_def = realloc_perror(prev_def, num_vts, vt_size); prev_divchn = realloc_perror(prev_divchn, num_vts, vt_size); prev_muloa = realloc_perror(prev_muloa, num_vts, vt_size); dist_def = realloc_perror(dist_def, num_vts, wt_size); dist_divchn = realloc_perror(dist_divchn, num_vts, wt_size); dist_muloa = realloc_perror(dist_muloa, num_vts, wt_size); C_SET_ZERO[k](wt_l); C_SET_TEST_ULIMIT[k](wt_h, pow_two_perror(log_end)); C_SET_ZERO[k](wt_zero); for (l = 0; l < num_vts; l++){ /* avoid trap representations in tests */ C_SET_ZERO[k](ptr(dist_def, l, wt_size)); C_SET_ZERO[k](ptr(dist_divchn, l, wt_size)); C_SET_ZERO[k](ptr(dist_muloa, l, wt_size)); } graph_base_init(&g, num_vts, vt_size, wt_size); adj_lst_rand_dir_wts(&g, &a, wt_l, wt_h, C_WRITE_VT[j], bern, &b, C_ADD_DIR_EDGE[k]); for (l = 0; l < C_ITER; l++){ rand_start[l] = mul_high_sz(random_sz(), num_vts); } t_def = clock(); for (l = 0; l < C_ITER; l++){ dijkstra(&a, rand_start[l], dist_def, prev_def, wt_zero, NULL, C_READ_VT[j], C_WRITE_VT[j], C_AT_VT[j], C_CMP_VT[j], C_CMP_WT[k], C_ADD_WT[k]); } t_def = clock() - t_def; C_SUM_DIST[k](dsum_def, wsum_def, &num_dwraps_def, &num_wwraps_def, &num_paths_def, num_vts, vt_size, dist_def, prev_def, C_READ_VT[j]); t_divchn = clock(); for (l = 0; l < C_ITER; l++){ dijkstra(&a, rand_start[l], dist_divchn, prev_divchn, wt_zero, &daht_divchn, C_READ_VT[j], C_WRITE_VT[j], C_AT_VT[j], C_CMP_VT[j], C_CMP_WT[k], C_ADD_WT[k]); } t_divchn = clock() - t_divchn; C_SUM_DIST[k](dsum_divchn, wsum_divchn, &num_dwraps_divchn, &num_wwraps_divchn, &num_paths_divchn, num_vts, vt_size, dist_def, prev_def, C_READ_VT[j]); t_muloa = clock(); for (l = 0; l < C_ITER; l++){ dijkstra(&a, rand_start[l], dist_muloa, prev_muloa, wt_zero, &daht_muloa, C_READ_VT[j], C_WRITE_VT[j], C_AT_VT[j], C_CMP_VT[j], C_CMP_WT[k], C_ADD_WT[k]); } t_muloa = clock() - t_muloa; C_SUM_DIST[k](dsum_muloa, wsum_muloa, &num_dwraps_muloa, &num_wwraps_muloa, &num_paths_muloa, num_vts, vt_size, dist_def, prev_def, C_READ_VT[j]); if (k < C_FN_INTEGRAL_WT_COUNT){ res *= (C_CMP_WT[k](dsum_def, dsum_divchn) == 0 && C_CMP_WT[k](dsum_divchn, dsum_muloa) == 0 && C_CMP_WT[k](wsum_def, wsum_divchn) == 0 && C_CMP_WT[k](wsum_divchn, wsum_muloa) == 0); } res *= (num_dwraps_def == num_dwraps_divchn && num_dwraps_divchn == num_dwraps_muloa && num_wwraps_def == num_wwraps_divchn && num_wwraps_divchn == num_wwraps_muloa && num_paths_def == num_paths_divchn && num_paths_divchn == num_paths_muloa); printf("\t\t\t# edges: %lu\n", TOLU(a.num_es)); printf("\t\t\t\t%s %s dijkstra default ht: %.8f seconds\n" "\t\t\t\t%s %s dijkstra ht_divchn: %.8f seconds\n" "\t\t\t\t%s %s dijkstra ht_muloa: %.8f seconds\n", C_VT_TYPES[j], C_WT_TYPES[k], (double)t_def / C_ITER / CLOCKS_PER_SEC, C_VT_TYPES[j], C_WT_TYPES[k], (double)t_divchn / C_ITER / CLOCKS_PER_SEC, C_VT_TYPES[j], C_WT_TYPES[k], (double)t_muloa / C_ITER / CLOCKS_PER_SEC); printf("\t\t\t\t%s %s correctness: ", C_VT_TYPES[j], C_WT_TYPES[k]); print_test_result(res); printf("\t\t\t\t%s %s last # paths: %lu\n", C_VT_TYPES[j], C_WT_TYPES[k], TOLU(num_paths_def - 1)); printf("\t\t\t\t%s %s last [# wraps, d sum]: [%lu, ", C_VT_TYPES[j], C_WT_TYPES[k], TOLU(num_dwraps_def)); C_PRINT[k](dsum_def); printf("]\n"); printf("\t\t\t\t%s %s last [# wraps, wt sum]: [%lu, ", C_VT_TYPES[j], C_WT_TYPES[k], TOLU(num_wwraps_def)); C_PRINT[k](wsum_def); printf("]\n\n"); res = 1; adj_lst_free(&a); } } } } free(rand_start); free(wt_l); free(wsum_def); free(wsum_divchn); free(wsum_muloa); free(dsum_def); free(dsum_divchn); free(dsum_muloa); free(dist_def); free(dist_divchn); free(dist_muloa); free(prev_def); free(prev_divchn); free(prev_muloa); rand_start = NULL; wt_l = NULL; wt_h = NULL; wt_zero = NULL; wsum_def = NULL; wsum_divchn = NULL; wsum_muloa = NULL; dsum_def = NULL; dsum_divchn = NULL; dsum_muloa = NULL; dist_def = NULL; dist_divchn = NULL; dist_muloa = NULL; prev_def = NULL; prev_divchn = NULL; prev_muloa = NULL; } /** Portable random number generation. For better uniformity (according to rand) RAND_MAX should be 32767, a power to two minus one, or many times larger than 32768 on a given system if it is not a power of two minus one. Given a value n of one of the below unsigned integral types, the overflow bits after multipying n with a random number of the same type represent a random number of the type within the range [0, n). According to C89 (draft): "When a signed integer is converted to an unsigned integer with equal or greater size, if the value of the signed integer is nonnegative, its value is unchanged." "For each of the signed integer types, there is a corresponding (but different) unsigned integer type (designated with the keyword unsigned) that uses the same amount of storage (including sign information) and has the same alignment requirements" "When an integer is demoted to an unsigned integer with smaller size, the result is the nonnegative remainder on division by the number one greater than the largest unsigned number that can be represented in the type with smaller size. " It is guaranteed that: sizeof(short) <= sizeof(int) <= sizeof(long) */ unsigned short random_ushort(){ size_t i; unsigned short ret = 0; for (i = 0; i <= C_USHORT_BIT_MOD; i++){ ret |= ((unsigned short)((unsigned int)RANDOM() & C_RANDOM_MASK) << (i * C_RANDOM_BIT)); } return ret; } unsigned int random_uint(){ size_t i; unsigned int ret = 0; for (i = 0; i <= C_UINT_BIT_MOD; i++){ ret |= ((unsigned int)RANDOM() & C_RANDOM_MASK) << (i * C_RANDOM_BIT); } return ret; } unsigned long random_ulong(){ size_t i; unsigned long ret = 0; for (i = 0; i <= C_ULONG_BIT_MOD; i++){ ret |= ((unsigned long)((unsigned int)RANDOM() & C_RANDOM_MASK) << (i * C_RANDOM_BIT)); } return ret; } size_t random_sz(){ size_t i; size_t ret = 0; for (i = 0; i <= C_SZ_BIT_MOD; i++){ ret |= ((size_t)((unsigned int)RANDOM() & C_RANDOM_MASK) << (i * C_RANDOM_BIT)); } return ret; } unsigned short mul_high_ushort(unsigned short a, unsigned short b){ unsigned short al, bl, ah, bh, al_bh, ah_bl; unsigned short overlap; al = a & C_USHORT_LOW_MASK; bl = b & C_USHORT_LOW_MASK; ah = a >> C_USHORT_HALF_BIT; bh = b >> C_USHORT_HALF_BIT; al_bh = al * bh; ah_bl = ah * bl; overlap = ((ah_bl & C_USHORT_LOW_MASK) + (al_bh & C_USHORT_LOW_MASK) + (al * bl >> C_USHORT_HALF_BIT)); return ((overlap >> C_USHORT_HALF_BIT) + ah * bh + (ah_bl >> C_USHORT_HALF_BIT) + (al_bh >> C_USHORT_HALF_BIT)); } unsigned int mul_high_uint(unsigned int a, unsigned int b){ unsigned int al, bl, ah, bh, al_bh, ah_bl; unsigned int overlap; al = a & C_UINT_LOW_MASK; bl = b & C_UINT_LOW_MASK; ah = a >> C_UINT_HALF_BIT; bh = b >> C_UINT_HALF_BIT; al_bh = al * bh; ah_bl = ah * bl; overlap = ((ah_bl & C_UINT_LOW_MASK) + (al_bh & C_UINT_LOW_MASK) + (al * bl >> C_UINT_HALF_BIT)); return ((overlap >> C_UINT_HALF_BIT) + ah * bh + (ah_bl >> C_UINT_HALF_BIT) + (al_bh >> C_UINT_HALF_BIT)); } unsigned long mul_high_ulong(unsigned long a, unsigned long b){ unsigned long al, bl, ah, bh, al_bh, ah_bl; unsigned long overlap; al = a & C_ULONG_LOW_MASK; bl = b & C_ULONG_LOW_MASK; ah = a >> C_ULONG_HALF_BIT; bh = b >> C_ULONG_HALF_BIT; al_bh = al * bh; ah_bl = ah * bl; overlap = ((ah_bl & C_ULONG_LOW_MASK) + (al_bh & C_ULONG_LOW_MASK) + (al * bl >> C_ULONG_HALF_BIT)); return ((overlap >> C_ULONG_HALF_BIT) + ah * bh + (ah_bl >> C_ULONG_HALF_BIT) + (al_bh >> C_ULONG_HALF_BIT)); } size_t mul_high_sz(size_t a, size_t b){ size_t al, bl, ah, bh, al_bh, ah_bl; size_t overlap; al = a & C_SZ_LOW_MASK; bl = b & C_SZ_LOW_MASK; ah = a >> C_SZ_HALF_BIT; bh = b >> C_SZ_HALF_BIT; al_bh = al * bh; ah_bl = ah * bl; overlap = ((ah_bl & C_SZ_LOW_MASK) + (al_bh & C_SZ_LOW_MASK) + (al * bl >> C_SZ_HALF_BIT)); return ((overlap >> C_SZ_HALF_BIT) + ah * bh + (ah_bl >> C_SZ_HALF_BIT) + (al_bh >> C_SZ_HALF_BIT)); } /** Value initiliazation, arithmetic, and printing. The functions with the set_test_max prefix, set the maximum value of random weights (i.e. unreached upper bound) and reflect that at most n - 1 edges participate in a path because otherwise there is a cycle. The functions with the sum_dist prefix compute i) the sum of the unsigned integer path distances, and ii) the sum of the unsigned integer edge weights in all paths, by counting the wrap-arounds in each case. The computation is overflow safe, because i) each path distance is at most the maximum value of the unsigned integer type used to represent weights, and there are at most n - 1 paths with a non-zero distance, and ii) there are at most n - 1 edges in the set of edges across all paths, because when v is popped (u, v) is added to the set with u being a popped vertex. The wrap-around count for ii) should be zero in the tests because any set of n - 1 edges can be added without overflow. The total sum in each case is: # wrap-arounds * max value of weight type + # wraps-arounds + wrapped sum of weight type. For double weights, the maximum value in 1.0 / n, where n can be converted to double as required in tests, and the number of wrap-arounds is 0. */ void set_zero_ushort(void *a){ *(unsigned short *)a = 0; } void set_zero_uint(void *a){ *(unsigned int *)a = 0; } void set_zero_ulong(void *a){ *(unsigned long *)a = 0; } void set_zero_sz(void *a){ *(size_t *)a = 0; } void set_zero_double(void *a){ *(double *)a = 0.0; } void set_one_ushort(void *a){ *(unsigned short *)a = 1; } void set_one_uint(void *a){ *(unsigned int *)a = 1; } void set_one_ulong(void *a){ *(unsigned long *)a = 1; } void set_one_sz(void *a){ *(size_t *)a = 1; } void set_one_double(void *a){ *(double *)a = 1.0; } void set_test_ulimit_ushort(void *a, size_t num_vts){ if (num_vts == 0){ *(unsigned short *)a = C_USHORT_ULIMIT; }else{ /* usual arithmetic conversions */ *(unsigned short *)a = C_USHORT_ULIMIT / num_vts; } } void set_test_ulimit_uint(void *a, size_t num_vts){ if (num_vts == 0){ *(unsigned int *)a = C_UINT_ULIMIT; }else{ /* usual arithmetic conversions */ *(unsigned int *)a = C_UINT_ULIMIT / num_vts; } } void set_test_ulimit_ulong(void *a, size_t num_vts){ if (num_vts == 0){ *(unsigned long *)a = C_ULONG_ULIMIT; }else{ /* usual arithmetic conversions */ *(unsigned long *)a = C_ULONG_ULIMIT / num_vts; } } void set_test_ulimit_sz(void *a, size_t num_vts){ if (num_vts == 0){ *(size_t *)a = C_SZ_ULIMIT; }else{ *(size_t *)a = C_SZ_ULIMIT / num_vts; } } void set_test_ulimit_double(void *a, size_t num_vts){ *(double *)a = 1.0 / num_vts; } void sum_dist_ushort(void *dist_sum, void *wt_sum, size_t *num_dist_wraps, /* <= num_vts */ size_t *num_wt_wraps, /* <= num_vts */ size_t *num_paths, /* <= num_vts */ size_t num_vts, size_t vt_size, const void *dist, const void *prev, size_t (*read_vt)(const void *)){ size_t i, p; unsigned short *dsum = dist_sum; unsigned short *wsum = wt_sum; const unsigned short *d = dist; *dsum = 0; *wsum = 0; *num_dist_wraps = 0; *num_wt_wraps = 0; *num_paths = 0; for (i = 0; i < num_vts; i++){ p = read_vt(ptr(prev, i, vt_size)); if (p != num_vts){ (*num_dist_wraps) += (C_USHORT_ULIMIT - *dsum < d[i]); /* includes d[i] < d[p] */ (*num_wt_wraps) += (C_USHORT_ULIMIT - *wsum < d[i] - d[p]); *dsum += d[i]; *wsum += d[i] - d[p]; (*num_paths)++; } } } void sum_dist_uint(void *dist_sum, void *wt_sum, size_t *num_dist_wraps, /* <= num_vts */ size_t *num_wt_wraps, /* <= num_vts */ size_t *num_paths, /* <= num_vts */ size_t num_vts, size_t vt_size, const void *dist, const void *prev, size_t (*read_vt)(const void *)){ size_t i, p; unsigned int *dsum = dist_sum; unsigned int *wsum = wt_sum; const unsigned int *d = dist; *dsum = 0; *wsum = 0; *num_dist_wraps = 0; *num_wt_wraps = 0; *num_paths = 0; for (i = 0; i < num_vts; i++){ p = read_vt(ptr(prev, i, vt_size)); if (p != num_vts){ (*num_dist_wraps) += (C_UINT_ULIMIT - *dsum < d[i]); /* includes d[i] < d[p] */ (*num_wt_wraps) += (C_UINT_ULIMIT - *wsum < d[i] - d[p]); *dsum += d[i]; *wsum += d[i] - d[p]; (*num_paths)++; } } } void sum_dist_ulong(void *dist_sum, void *wt_sum, size_t *num_dist_wraps, /* <= num_vts */ size_t *num_wt_wraps, /* <= num_vts */ size_t *num_paths, /* <= num_vts */ size_t num_vts, size_t vt_size, const void *dist, const void *prev, size_t (*read_vt)(const void *)){ size_t i, p; unsigned long *dsum = dist_sum; unsigned long *wsum = wt_sum; const unsigned long *d = dist; *dsum = 0; *wsum = 0; *num_dist_wraps = 0; *num_wt_wraps = 0; *num_paths = 0; for (i = 0; i < num_vts; i++){ p = read_vt(ptr(prev, i, vt_size)); if (p != num_vts){ (*num_dist_wraps) += (C_ULONG_ULIMIT - *dsum < d[i]); /* includes d[i] < d[p] */ (*num_wt_wraps) += (C_ULONG_ULIMIT - *wsum < d[i] - d[p]); *dsum += d[i]; *wsum += d[i] - d[p]; (*num_paths)++; } } } void sum_dist_sz(void *dist_sum, void *wt_sum, size_t *num_dist_wraps, /* <= num_vts */ size_t *num_wt_wraps, /* <= num_vts */ size_t *num_paths, /* <= num_vts */ size_t num_vts, size_t vt_size, const void *dist, const void *prev, size_t (*read_vt)(const void *)){ size_t i, p; size_t *dsum = dist_sum; size_t *wsum = wt_sum; const size_t *d = dist; *dsum = 0; *wsum = 0; *num_dist_wraps = 0; *num_wt_wraps = 0; *num_paths = 0; for (i = 0; i < num_vts; i++){ p = read_vt(ptr(prev, i, vt_size)); if (p != num_vts){ (*num_dist_wraps) += (C_SZ_ULIMIT - *dsum < d[i]); /* includes d[i] < d[p] */ (*num_wt_wraps) += (C_SZ_ULIMIT - *wsum < d[i] - d[p]); *dsum += d[i]; *wsum += d[i] - d[p]; (*num_paths)++; } } } void sum_dist_double(void *dist_sum, void *wt_sum, size_t *num_dist_wraps, /* <= num_vts */ size_t *num_wt_wraps, /* <= num_vts */ size_t *num_paths, /* <= num_vts */ size_t num_vts, size_t vt_size, const void *dist, const void *prev, size_t (*read_vt)(const void *)){ size_t i, p; double *dsum = dist_sum; double *wsum = wt_sum; const double *d = dist; *dsum = 0; *wsum = 0; *num_dist_wraps = 0; *num_wt_wraps = 0; *num_paths = 0; for (i = 0; i < num_vts; i++){ p = read_vt(ptr(prev, i, vt_size)); if (p != num_vts){ *dsum += d[i]; *wsum += d[i] - d[p]; (*num_paths)++; } } } void print_ushort(const void *a){ printf("%hu", *(const unsigned short *)a); } void print_uint(const void *a){ printf("%u", *(const unsigned int *)a); } void print_ulong(const void *a){ printf("%lu", *(const unsigned long *)a); } void print_sz(const void *a){ printf("%lu", TOLU(*(const size_t *)a)); } void print_double(const void *a){ printf("%.8f", *(const double *)a); } /** Computes a pointer to the ith element in the block of elements. */ void *ptr(const void *block, size_t i, size_t size){ return (void *)((char *)block + i * size); } /** Prints an array. */ void print_arr(const void *arr, size_t size, size_t n, void (*print_elt)(const void *)){ size_t i; for (i = 0; i < n; i++){ print_elt(ptr(arr, i, size)); printf(" "); } } /** Prints a prev array. */ void print_prev(const struct adj_lst *a, const void *prev, void (*print_vt)(const void *)){ print_arr(prev, a->vt_size, a->num_vts, print_vt); } /** Prints a dist array. */ void print_dist(const struct adj_lst *a, const void *dist, const void *prev, const void *wt_zero, size_t (*read_vt)(const void *), void (*print_wt)(const void *)){ size_t i; for (i = 0; i < a->num_vts; i++){ if (read_vt(ptr(prev, i, a->vt_size)) != a->num_vts){ print_wt(ptr(dist, i, a->wt_size)); printf(" "); }else{ print_wt(wt_zero); printf(" "); } } } /** Prints an adjacency list. If the graph is unweighted, then print_wt is NULL. */ void print_adj_lst(const struct adj_lst *a, void (*print_vt)(const void *), void (*print_wt)(const void *)){ size_t i; const void *p = NULL, *p_start = NULL, *p_end = NULL; printf("\tvertices: \n"); for (i = 0; i < a->num_vts; i++){ printf("\t%lu : ", TOLU(i)); p_start = a->vt_wts[i]->elts; p_end = (char *)p_start + a->vt_wts[i]->num_elts * a->pair_size; for (p = p_start; p != p_end; p = (char *)p + a->pair_size){ print_vt(p); printf(" "); } printf("\n"); } if (a->wt_size > 0 && print_wt != NULL){ printf("\tweights: \n"); for (i = 0; i < a->num_vts; i++){ printf("\t%lu : ", TOLU(i)); p_start = a->vt_wts[i]->elts; p_end = (char *)p_start + a->vt_wts[i]->num_elts * a->pair_size; for (p = p_start; p != p_end; p = (char *)p + a->pair_size){ print_wt((char *)p + a->wt_offset); printf(" "); } printf("\n"); } } } /** Prints a test result. */ void print_test_result(int res){ if (res){ printf("SUCCESS\n"); }else{ printf("FAILURE\n"); } } int main(int argc, char *argv[]){ int i; size_t *args = NULL; RGENS_SEED(); if (argc > C_ARGC_ULIMIT){ printf("USAGE:\n%s", C_USAGE); exit(EXIT_FAILURE); } args = malloc_perror(C_ARGC_ULIMIT - 1, sizeof(size_t)); memcpy(args, C_ARGS_DEF, (C_ARGC_ULIMIT - 1) * sizeof(size_t)); for (i = 1; i < argc; i++){ args[i - 1] = atoi(argv[i]); } if (args[0] > C_USHORT_BIT - 1 || args[1] > C_USHORT_BIT - 1 || args[1] < args[0] || args[2] > 1 || args[3] > 1 || args[4] > 1){ printf("USAGE:\n%s", C_USAGE); exit(EXIT_FAILURE); } /*pow_two_perror later tests that # vertices is representable as size_t */ if (args[2]) run_small_graph_test(); if (args[3]) run_bfs_comparison_test(args[0], args[1]); if (args[4]) run_rand_test(args[0], args[1]); free(args); args = NULL; return 0; }
alfin3/graph-algorithms
utilities/utilities-mem/utilities-mem.c
/** utilities-mem.c Utility functions for memory management. */ #include <stdio.h> #include <stdlib.h> static const size_t C_SIZE_ULIMIT = (size_t)-1; /** size_t addition and multiplication with wrapped overflow checking. */ size_t add_sz_perror(size_t a, size_t b){ if (a > C_SIZE_ULIMIT - b){ perror("addition size_t overflow"); exit(EXIT_FAILURE); } return a + b; } size_t mul_sz_perror(size_t a, size_t b){ if (a > C_SIZE_ULIMIT / b){ perror("multiplication size_t overflow"); exit(EXIT_FAILURE); } return a * b; } /** size_t multiplication with wrapped overflow and zero checking. Useful for computing end pointers for pointer iteration. */ size_t mul_nzero_sz_perror(size_t a, size_t b){ if (a < 1 || b < 1){ perror("zero multiplication"); exit(EXIT_FAILURE); } return mul_sz_perror(a, b); } /** Malloc, realloc, and calloc with wrapped error checking, including integer overflow checking. The latter is also included in calloc_perror because there is no guarantee that a calloc implementation checks for integer overflow. */ void *malloc_perror(size_t num, size_t size){ void *ptr = NULL; if (num > C_SIZE_ULIMIT / size){ perror("malloc integer overflow"); exit(EXIT_FAILURE); } ptr = malloc(num * size); if (ptr == NULL){ perror("malloc failed"); exit(EXIT_FAILURE); } return ptr; } void *realloc_perror(void *ptr, size_t num, size_t size){ void *new_ptr = NULL; if (num > C_SIZE_ULIMIT / size){ perror("realloc integer overflow"); exit(EXIT_FAILURE); } new_ptr = realloc(ptr, num * size); if (new_ptr == NULL){ perror("realloc failed"); exit(EXIT_FAILURE); } return new_ptr; } void *calloc_perror(size_t num, size_t size){ void *ptr = NULL; if (num > C_SIZE_ULIMIT / size){ perror("calloc integer overflow"); exit(EXIT_FAILURE); } ptr = calloc(num, size); if (ptr == NULL){ perror("calloc failed"); exit(EXIT_FAILURE); } return ptr; }
alfin3/graph-algorithms
data-structures-pthread/ht-divchn-pthread/ht-divchn-pthread-test.c
<filename>data-structures-pthread/ht-divchn-pthread/ht-divchn-pthread-test.c /** ht-divchn-pthread-test.c Tests of a hash table with generic contiguous or non-contiguous keys and generic contiguous or non-contiguous elements that is concurrently accessible and modifiable. The implementation is based on a division method for hashing and a chaining method for resolving collisions. The implementation does not use stdint.h and is portable under C89/C90 and C99. The requirements are: i) the width of size_t is greater or equal to 16, less than 2040, and is even, and ii) pthreads API is available. TODO: add portable printing of size_t */ #define _XOPEN_SOURCE 600 #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <limits.h> #include <sys/time.h> #include "ht-divchn-pthread.h" #include "dll.h" #include "utilities-mem.h" #include "utilities-mod.h" #include "utilities-lim.h" #include "utilities-pthread.h" /** Generate random numbers in a portable way for test purposes only; rand() in the Linux C Library uses the same generator as random(), which may not be the case on older rand() implementations, and on current implementations on different systems. */ #define RGENS_SEED() do{srand(time(NULL));}while (0) #define RANDOM() (rand()) /* [0, RAND_MAX] */ #define DRAND() ((double)rand() / RAND_MAX) /* [0.0, 1.0] */ #define TOLU(i) ((unsigned long int)(i)) /* printing size_t under C89/C90 */ /* input handling */ const char *C_USAGE = "ht-divchn-pthread-test\n" "[0, size_t width - 1) : i s.t. # inserts = 2**i\n" "[0, size_t width) : a given k = sizeof(size_t)\n" "[0, size_t width) : b s.t. k * 2**a <= key size <= k * 2**b\n" "> 0 : c\n" "> 0 : d\n" "> 0 : e log base 2\n" "> 0 : f s.t. c / 2**e <= load factor bound <= d / 2**e, in f steps\n" "[0, 1] : on/off insert search uint test\n" "[0, 1] : on/off remove delete uint test\n" "[0, 1] : on/off insert search uint_ptr test\n" "[0, 1] : on/off remove delete uint_ptr test\n" "[0, 1] : on/off corner cases test\n"; const int C_ARGC_ULIMIT = 13; const size_t C_ARGS_DEF[12] = {14u, 0u, 2u, 1024u, 30720u, 11u, 10u, 1u, 1u, 1u, 1u, 1u}; const size_t C_SIZE_ULIMIT = (size_t)-1; const size_t C_FULL_BIT = PRECISION_FROM_ULIMIT((size_t)-1); /* corner cases test */ const size_t C_CORNER_LOG_KEY_START = 0u; const size_t C_CORNER_LOG_KEY_END = 8u; const size_t C_CORNER_HT_COUNT = 1543u; const size_t C_CORNER_ALPHA_N = 33u; const size_t C_CORNER_LOG_ALPHA_D = 15u; /* lf bound is 33/32768 */ const size_t C_CORNER_MIN_NUM = 0u; const size_t C_CORNER_NUM_LOCKS = 1u; const size_t C_CORNER_NUM_GROW_THREADS = 1u; void insert_search_free(size_t num_ins, size_t key_size, size_t elt_size, size_t elt_alignment, size_t alpha_n, size_t log_alpha_d, size_t num_threads, size_t log_num_locks, size_t num_grow_threads, size_t batch_count, void (*new_elt)(void *, size_t), size_t (*val_elt)(const void *), void (*free_elt)(void *)); void remove_delete(size_t num_ins, size_t key_size, size_t elt_size, size_t elt_alignment, size_t alpha_n, size_t log_alpha_d, size_t num_threads, size_t log_num_locks, size_t num_grow_threads, size_t batch_count, void (*new_elt)(void *, size_t), size_t (*val_elt)(const void *), void (*free_elt)(void *)); void *ptr(const void *block, size_t i, size_t size); void print_test_result(int res); double timer(); /** Test hash table operations on distinct contiguous keys and contiguous size_t elements across key sizes and load factor upper bounds. For test purposes a key is a random key_size block with the exception of a distinct non-random sizeof(size_t)-sized sub-block inside the key_size block. An element is an elt_size block of size sizeof(size_t) with a size_t value. Keys and elements are entirely copied into a hash table and free_key and free_elt are NULL. */ void new_uint(void *elt, size_t val){ size_t *s = elt; *s = val; } size_t val_uint(const void *elt){ return *(size_t *)elt; } /** Runs a ht_divchn_pthread_{insert, search, free} test on distinct keys and size_t elements across key sizes >= sizeof(size_t) and load factor upper bounds. */ void run_insert_search_free_uint_test(size_t log_ins, size_t log_key_start, size_t log_key_end, size_t alpha_n_start, size_t alpha_n_end, size_t log_alpha_d, size_t num_alpha_steps, size_t num_threads, size_t log_num_locks, size_t num_grow_threads, size_t batch_count){ size_t i, j; size_t num_ins; size_t key_size; size_t elt_size = sizeof(size_t); size_t elt_alignment = sizeof(size_t); size_t step, rem; size_t alpha_n; num_ins = pow_two_perror(log_ins); step = (alpha_n_end - alpha_n_start) / num_alpha_steps; for (i = log_key_start; i <= log_key_end; i++){ alpha_n = alpha_n_start; rem = alpha_n_end - alpha_n_start - step * num_alpha_steps; key_size = sizeof(size_t) * pow_two_perror(i); printf("Run a ht_divchn_pthread_{insert, search, free} test on distinct " "%lu-byte keys and size_t elements\n", TOLU(key_size)); printf("\t# threads (t): %lu\n" "\t# locks: %lu\n" "\t# grow threads: %lu\n" "\tbatch count: %lu\n", TOLU(num_threads), TOLU(pow_two_perror(log_num_locks)), TOLU(num_grow_threads), TOLU(batch_count)); for (j = 0; j <= num_alpha_steps; j++){ printf("\t# inserts: %lu, load factor upper bound: %.4f\n", TOLU(num_ins), (float)alpha_n / pow_two_perror(log_alpha_d)); insert_search_free(num_ins, key_size, elt_size, elt_alignment, alpha_n, log_alpha_d, num_threads, log_num_locks, num_grow_threads, batch_count, new_uint, val_uint, NULL); alpha_n += (j < num_alpha_steps) * step + (rem > 0 && rem--); } } } /** Runs a ht_divchn_pthread_{remove, delete} test on distinct keys and size_t elements across key sizes >= C_KEY_SIZE_FACTOR and load factor upper bounds. */ void run_remove_delete_uint_test(size_t log_ins, size_t log_key_start, size_t log_key_end, size_t alpha_n_start, size_t alpha_n_end, size_t log_alpha_d, size_t num_alpha_steps, size_t num_threads, size_t log_num_locks, size_t num_grow_threads, size_t batch_count){ size_t i, j; size_t num_ins; size_t key_size; size_t elt_size = sizeof(size_t); size_t elt_alignment = sizeof(size_t); size_t step, rem; size_t alpha_n; num_ins = pow_two_perror(log_ins); step = (alpha_n_end - alpha_n_start) / num_alpha_steps; for (i = log_key_start; i <= log_key_end; i++){ alpha_n = alpha_n_start; rem = alpha_n_end - alpha_n_start - step * num_alpha_steps; key_size = sizeof(size_t) * pow_two_perror(i); printf("Run a ht_divchn_pthread_{remove, delete} test on distinct " "%lu-byte keys and size_t elements\n", TOLU(key_size)); printf("\t# threads (t): %lu\n" "\t# locks: %lu\n" "\t# grow threads: %lu\n" "\tbatch count: %lu\n", TOLU(num_threads), TOLU(pow_two_perror(log_num_locks)), TOLU(num_grow_threads), TOLU(batch_count)); for (j = 0; j <= num_alpha_steps; j++){ printf("\tnumber of inserts: %lu, load factor upper bound: %.4f\n", TOLU(num_ins), (float)alpha_n / pow_two_perror(log_alpha_d)); remove_delete(num_ins, key_size, elt_size, elt_alignment, alpha_n, log_alpha_d, num_threads, log_num_locks, num_grow_threads, batch_count, new_uint, val_uint, NULL); alpha_n += (j < num_alpha_steps) * step + (rem > 0 && rem--); } } } /** Test hash table operations on distinct contiguous keys and noncontiguous uint_ptr elements across key sizes and load factor upper bounds. For test purposes a key is a random key_size block with the exception of a distinct non-random sizeof(size_t)-sized sub-block inside the key_size block. A key is fully copied into a hash table as a key_size block. Because an element is noncontiguous, a pointer to an element is copied as an elt_size block. free_key is NULL. An element-specific free_elt is necessary to delete an element. */ struct uint_ptr{ size_t *val; }; void new_uint_ptr(void *elt, size_t val){ struct uint_ptr **s = elt; *s = malloc_perror(1, sizeof(struct uint_ptr)); (*s)->val = malloc_perror(1, sizeof(size_t)); *((*s)->val) = val; } size_t val_uint_ptr(const void *elt){ struct uint_ptr **s = (struct uint_ptr **)elt; return *((*s)->val); } void free_uint_ptr(void *elt){ struct uint_ptr **s = elt; free((*s)->val); (*s)->val = NULL; free(*s); *s = NULL; } /** Runs a ht_divchn_pthread_{insert, search, free} test on distinct keys and noncontiguous uint_ptr elements across key sizes >= sizeof(size_t) and load factor upper bounds. */ void run_insert_search_free_uint_ptr_test(size_t log_ins, size_t log_key_start, size_t log_key_end, size_t alpha_n_start, size_t alpha_n_end, size_t log_alpha_d, size_t num_alpha_steps, size_t num_threads, size_t log_num_locks, size_t num_grow_threads, size_t batch_count){ size_t i, j; size_t num_ins; size_t key_size; size_t elt_size = sizeof(struct uint_ptr *); size_t elt_alignment = sizeof(struct uint_ptr *); size_t step, rem; size_t alpha_n; num_ins = pow_two_perror(log_ins); step = (alpha_n_end - alpha_n_start) / num_alpha_steps; for (i = log_key_start; i <= log_key_end; i++){ alpha_n = alpha_n_start; rem = alpha_n_end - alpha_n_start - step * num_alpha_steps; key_size = sizeof(size_t) * pow_two_perror(i); printf("Run a ht_divchn_pthread_{insert, search, free} test on distinct " "%lu-byte keys and noncontiguous uint_ptr elements\n", TOLU(key_size)); printf("\t# threads (t): %lu\n" "\t# locks: %lu\n" "\t# grow threads: %lu\n" "\tbatch count: %lu\n", TOLU(num_threads), TOLU(pow_two_perror(log_num_locks)), TOLU(num_grow_threads), TOLU(batch_count)); for (j = 0; j <= num_alpha_steps; j++){ printf("\tnumber of inserts: %lu, load factor upper bound: %.4f\n", TOLU(num_ins), (float)alpha_n / pow_two_perror(log_alpha_d)); insert_search_free(num_ins, key_size, elt_size, elt_alignment, alpha_n, log_alpha_d, num_threads, log_num_locks, num_grow_threads, batch_count, new_uint_ptr, val_uint_ptr, free_uint_ptr); alpha_n += (j < num_alpha_steps) * step + (rem > 0 && rem--); } } } /** Runs a ht_divchn_pthread_{remove, delete} test on distinct keys and noncontiguous uint_ptr elements across key sizes >= sizeof(size_t) and load factor upper bounds. */ void run_remove_delete_uint_ptr_test(size_t log_ins, size_t log_key_start, size_t log_key_end, size_t alpha_n_start, size_t alpha_n_end, size_t log_alpha_d, size_t num_alpha_steps, size_t num_threads, size_t log_num_locks, size_t num_grow_threads, size_t batch_count){ size_t i, j; size_t num_ins; size_t key_size; size_t elt_size = sizeof(struct uint_ptr *); size_t elt_alignment = sizeof(struct uint_ptr *); size_t step, rem; size_t alpha_n; num_ins = pow_two_perror(log_ins); step = (alpha_n_end - alpha_n_start) / num_alpha_steps; for (i = log_key_start; i <= log_key_end; i++){ alpha_n = alpha_n_start; rem = alpha_n_end - alpha_n_start - step * num_alpha_steps; key_size = sizeof(size_t) * pow_two_perror(i); printf("Run a ht_divchn_pthread_{remove, delete} test on distinct " "%lu-byte keys and noncontiguous uint_ptr elements\n", TOLU(key_size)); printf("\t# threads (t): %lu\n" "\t# locks: %lu\n" "\t# grow threads: %lu\n" "\tbatch count: %lu\n", TOLU(num_threads), TOLU(pow_two_perror(log_num_locks)), TOLU(num_grow_threads), TOLU(batch_count)); for (j = 0; j <= num_alpha_steps; j++){ printf("\tnumber of inserts: %lu, load factor upper bound: %.4f\n", TOLU(num_ins), (float)alpha_n / pow_two_perror(log_alpha_d)); remove_delete(num_ins, key_size, elt_size, elt_alignment, alpha_n, log_alpha_d, num_threads, log_num_locks, num_grow_threads, batch_count, new_uint_ptr, val_uint_ptr, free_uint_ptr); alpha_n += (j < num_alpha_steps) * step + (rem > 0 && rem--); } } } /** Helper functions for the ht_divchn_pthread_{insert, search, free} tests across key sizes and load factor upper bounds, on size_t and uint_ptr elements. */ /* Insert */ struct insert_arg{ size_t start; size_t count; size_t batch_count; const unsigned char *keys; /* key_size blocks of unsigned chars */ const void *elts; struct ht_divchn_pthread *ht; }; void *insert_thread(void *arg){ size_t i; const unsigned char *k = NULL; const void *e = NULL; const struct insert_arg *ia = arg; for (i = 0; i < ia->count; i += ia->batch_count){ k = ptr(ia->keys, ia->start + i, ia->ht->key_size); e = ptr(ia->elts, ia->start + i, ia->ht->elt_size); if (ia->count - i < ia->batch_count){ ht_divchn_pthread_insert(ia->ht, k, e, ia->count - i); }else{ ht_divchn_pthread_insert(ia->ht, k, e, ia->batch_count); } } return NULL; } void insert_keys_elts(struct ht_divchn_pthread *ht, const unsigned char *keys, const void *elts, size_t count, size_t num_threads, size_t batch_count, int *res){ size_t i; size_t n = ht->num_elts; size_t init_count = ht->count; size_t seg_count, rem_count; size_t start = 0; double t; pthread_t *iids = NULL; struct insert_arg *ias = NULL; iids = malloc_perror(num_threads, sizeof(pthread_t)); ias = malloc_perror(num_threads, sizeof(struct insert_arg)); seg_count = count / num_threads; rem_count = count % num_threads; /* distribute among threads */ for (i = 0; i < num_threads; i++){ ias[i].start = start; ias[i].count = seg_count; ias[i].count += (rem_count > 0 && rem_count--); ias[i].batch_count = batch_count; ias[i].keys = keys; ias[i].elts = elts; ias[i].ht = ht; start += ias[i].count; } t = timer(); for (i = 0; i < num_threads; i++){ thread_create_perror(&iids[i], insert_thread, &ias[i]); } for (i = 0; i < num_threads; i++){ thread_join_perror(iids[i], NULL); } t = timer() - t; if (init_count < ht->count){ printf("\t\tinsert w/ growth time " "%.4f seconds\n", t); }else{ printf("\t\tinsert w/o growth time " "%.4f seconds\n", t); } *res *= (ht->num_elts == n + count); free(iids); free(ias); iids = NULL; ias = NULL; } /* Search */ struct search_arg{ size_t start; size_t count; size_t *elt_count; /* for each thread */ const unsigned char *keys; const void *elts; const struct ht_divchn_pthread *ht; size_t (*val_elt)(const void *); }; void *search_thread(void *arg){ size_t i; const struct search_arg *sa = arg; for (i = sa->start; i < sa->start + sa->count; i++){ ht_divchn_pthread_search(sa->ht, ptr(sa->keys, i, sa->ht->key_size)); } return NULL; } void *search_res_thread(void *arg){ size_t i; const void *elt = NULL; const struct search_arg *sa = arg; *(sa->elt_count) = 0; for (i = sa->start; i < sa->start + sa->count; i++){ elt = ht_divchn_pthread_search(sa->ht, ptr(sa->keys, i, sa->ht->key_size)); if (elt != NULL){ *(sa->elt_count) += (sa->val_elt(ptr(sa->elts, i, sa->ht->elt_size)) == sa->val_elt(elt)); } } return NULL; } size_t search_ht_helper(const struct ht_divchn_pthread *ht, const unsigned char *keys, const void *elts, size_t count, size_t num_threads, size_t (*val_elt)(const void *), double *t){ size_t i; size_t ret = 0; size_t seg_count, rem_count; size_t start = 0; size_t *elt_counts = NULL; pthread_t *sids = NULL; struct search_arg *sas = NULL; elt_counts = calloc_perror(num_threads, sizeof(size_t)); sids = malloc_perror(num_threads, sizeof(pthread_t)); sas = malloc_perror(num_threads, sizeof(struct search_arg)); seg_count = count / num_threads; rem_count = count - seg_count * num_threads; /* distribute among threads */ for (i = 0; i < num_threads; i++){ sas[i].start = start; sas[i].count = seg_count; sas[i].count += (rem_count > 0 && rem_count--); sas[i].elt_count = &elt_counts[i]; sas[i].keys = keys; sas[i].elts = elts; sas[i].ht = ht; sas[i].val_elt = val_elt; start += sas[i].count; } /* timing */ *t = timer(); for (i = 0; i < num_threads; i++){ thread_create_perror(&sids[i], search_thread, &sas[i]); } for (i = 0; i < num_threads; i++){ thread_join_perror(sids[i], NULL); } *t = timer() - *t; /* correctness */ for (i = 0; i < num_threads; i++){ thread_create_perror(&sids[i], search_res_thread, &sas[i]); } for (i = 0; i < num_threads; i++){ thread_join_perror(sids[i], NULL); ret += elt_counts[i]; } free(elt_counts); free(sids); free(sas); elt_counts = NULL; sids = NULL; sas = NULL; return ret; } void search_in_ht(const struct ht_divchn_pthread *ht, const unsigned char *keys, const void *elts, size_t count, size_t num_threads, size_t (*val_elt)(const void *), int *res){ size_t n = ht->num_elts; double t; *res *= (search_ht_helper(ht, keys, elts, count, num_threads, val_elt, &t) == ht->num_elts); *res *= (n == ht->num_elts); if (num_threads == 1){ printf("\t\tin ht search time (t = 1): " "%.4f seconds\n", t); }else{ printf("\t\tin ht search time: " "%.4f seconds\n", t); } } void search_nin_ht(const struct ht_divchn_pthread *ht, const unsigned char *keys, const void *elts, size_t count, size_t num_threads, size_t (*val_elt)(const void *), int *res){ size_t n = ht->num_elts; double t; *res *= (search_ht_helper(ht, keys, elts, count, num_threads, val_elt, &t) == 0); *res *= (n == ht->num_elts); if (num_threads == 1){ printf("\t\tnot in ht search time (t = 1): " "%.4f seconds\n", t); }else{ printf("\t\tnot in ht search time: " "%.4f seconds\n", t); } } /* Free */ void free_ht(struct ht_divchn_pthread *ht, int verb){ double t; t = timer(); ht_divchn_pthread_free(ht); t = timer() - t; if (verb){ printf("\t\tfree time: " "%.4f seconds\n", t); } } /* Insert, search, free */ void insert_search_free(size_t num_ins, size_t key_size, size_t elt_size, size_t elt_alignment, size_t alpha_n, size_t log_alpha_d, size_t num_threads, size_t log_num_locks, size_t num_grow_threads, size_t batch_count, void (*new_elt)(void *, size_t), size_t (*val_elt)(const void *), void (*free_elt)(void *)){ int res = 1; size_t i, j; size_t val; unsigned char key_buf[sizeof(size_t)]; unsigned char *key = NULL; unsigned char *keys = NULL; unsigned char *nin_keys = NULL; void *elts = NULL; struct ht_divchn_pthread ht; keys = malloc_perror(num_ins, key_size); elts = malloc_perror(num_ins, elt_size); nin_keys = malloc_perror(num_ins, key_size); for (i = 0; i < num_ins; i++){ key = ptr(keys, i, key_size); for (j = 0; j < key_size - sizeof(size_t); j++){ /* set random bytes in a key, each to RANDOM mod 2**CHAR_BIT */ *(unsigned char *)ptr(key, j, 1) = RANDOM(); } /* set non-random bytes in a key, and create element */ memcpy(key_buf, &i, sizeof(size_t)); /* eff. type in key unchanged */ memcpy(ptr(key, key_size - sizeof(size_t), 1), key_buf, sizeof(size_t)); new_elt(ptr(elts, i, elt_size), i); } ht_divchn_pthread_init(&ht, key_size, elt_size, 0, alpha_n, log_alpha_d, log_num_locks, num_grow_threads, NULL, NULL, NULL, NULL, NULL); /* NULL to reinsert non-contig. elements */ insert_keys_elts(&ht, keys, elts, num_ins, num_threads, batch_count, &res); free_ht(&ht, 0); ht_divchn_pthread_init(&ht, key_size, elt_size, num_ins, alpha_n, log_alpha_d, log_num_locks, num_grow_threads, NULL, NULL, NULL, NULL, free_elt); ht_divchn_pthread_align(&ht, elt_alignment); insert_keys_elts(&ht, keys, elts, num_ins, num_threads, batch_count, &res); search_in_ht(&ht, keys, elts, num_ins, num_threads, val_elt, &res); search_in_ht(&ht, keys, elts, num_ins, 1, val_elt, &res); for (i = 0; i < num_ins; i++){ key = ptr(keys, i, key_size); val = i + num_ins; /* set non-random bytes in a key s.t. it is not in ht */ memcpy(key_buf, &val, sizeof(size_t)); /* eff. type in key unchanged */ memcpy(ptr(key, key_size - sizeof(size_t), 1), key_buf, sizeof(size_t)); } search_nin_ht(&ht, keys, elts, num_ins, num_threads, val_elt, &res); search_nin_ht(&ht, keys, elts, num_ins, 1, val_elt, &res); free_ht(&ht, 1); printf("\t\tsearch correctness: "); print_test_result(res); free(keys); free(elts); free(nin_keys); keys = NULL; elts = NULL; nin_keys = NULL; } /** Helper functions for the ht_divchn_pthread_{remove, delete} tests across key sizes and load factor upper bounds, on size_t and uint_ptr elements. */ /* Remove */ struct remove_arg{ size_t start; size_t count; size_t batch_count; const unsigned char *keys; void *elts; struct ht_divchn_pthread *ht; }; void *remove_thread(void *arg){ size_t i; const unsigned char *k = NULL; void *e = NULL; const struct remove_arg *ra = arg; for (i = 0; i < ra->count; i += ra->batch_count){ k = ptr(ra->keys, ra->start + i, ra->ht->key_size); e = ptr(ra->elts, ra->start + i, ra->ht->elt_size); if (ra->count - i < ra->batch_count){ ht_divchn_pthread_remove(ra->ht, k, e, ra->count - i); }else{ ht_divchn_pthread_remove(ra->ht, k, e, ra->batch_count); } } return NULL; } void remove_key_elts(struct ht_divchn_pthread *ht, const unsigned char *keys, void *elts, size_t count, size_t num_threads, size_t batch_count, int *res){ size_t i; size_t seg_count, rem_count; size_t start = 0; double t; pthread_t *rids = NULL; struct remove_arg *ras = NULL; rids = malloc_perror(num_threads, sizeof(pthread_t)); ras = malloc_perror(num_threads, sizeof(struct remove_arg)); seg_count = count / num_threads; rem_count = count - seg_count * num_threads; /* distribute among threads */ for (i = 0; i < num_threads; i++){ ras[i].start = start; ras[i].count = seg_count; ras[i].count += (rem_count > 0 && rem_count--); ras[i].batch_count = batch_count; ras[i].keys = keys; ras[i].elts = elts; ras[i].ht = ht; start += ras[i].count; } t = timer(); for (i = 0; i < num_threads; i++){ thread_create_perror(&rids[i], remove_thread, &ras[i]); } for (i = 0; i < num_threads; i++){ thread_join_perror(rids[i], NULL); } t = timer() - t; *res *= (ht->num_elts == 0); for (i = 0; i < count; i++){ *res *= (ht_divchn_pthread_search(ht, ptr(keys, i, ht->key_size)) == NULL); } for (i = 0; i < ht->count; i++){ *res *= (ht->key_elts[i] == NULL); } printf("\t\tremove time: " "%.4f seconds\n", t); free(rids); free(ras); rids = NULL; ras = NULL; } /* Delete */ struct delete_arg{ size_t start; size_t count; size_t batch_count; const unsigned char *keys; struct ht_divchn_pthread *ht; }; void *delete_thread(void *arg){ size_t i; const unsigned char *k = NULL; const struct delete_arg *da = arg; for (i = 0; i < da->count; i += da->batch_count){ k = ptr(da->keys, da->start + i, da->ht->key_size); if (da->count - i < da->batch_count){ ht_divchn_pthread_delete(da->ht, k, da->count - i); }else{ ht_divchn_pthread_delete(da->ht, k, da->batch_count); } } return NULL; } void delete_key_elts(struct ht_divchn_pthread *ht, const unsigned char *keys, size_t count, size_t num_threads, size_t batch_count, int *res){ size_t i; size_t seg_count, rem_count; size_t start = 0; double t; pthread_t *dids = NULL; struct delete_arg *das = NULL; dids = malloc_perror(num_threads, sizeof(pthread_t)); das = malloc_perror(num_threads, sizeof(struct delete_arg)); seg_count = count / num_threads; rem_count = count - seg_count * num_threads; /* distribute among threads */ for (i = 0; i < num_threads; i++){ das[i].start = start; das[i].count = seg_count; das[i].count += (rem_count > 0 && rem_count--); das[i].batch_count = batch_count; das[i].keys = keys; das[i].ht = ht; start += das[i].count; } t = timer(); for (i = 0; i < num_threads; i++){ thread_create_perror(&dids[i], delete_thread, &das[i]); } for (i = 0; i < num_threads; i++){ thread_join_perror(dids[i], NULL); } t = timer() - t; *res *= (ht->num_elts == 0); for (i = 0; i < count; i++){ *res *= (ht_divchn_pthread_search(ht, ptr(keys, i, ht->key_size)) == NULL); } for (i = 0; i < ht->count; i++){ *res *= (ht->key_elts[i] == NULL); } printf("\t\tdelete time: " "%.4f seconds\n", t); free(dids); free(das); dids = NULL; das = NULL; } /* Remove, delete */ void remove_delete(size_t num_ins, size_t key_size, size_t elt_size, size_t elt_alignment, size_t alpha_n, size_t log_alpha_d, size_t num_threads, size_t log_num_locks, size_t num_grow_threads, size_t batch_count, void (*new_elt)(void *, size_t), size_t (*val_elt)(const void *), void (*free_elt)(void *)){ int res = 1; size_t i, j; unsigned char key_buf[sizeof(size_t)]; unsigned char *key = NULL; unsigned char *keys = NULL; void *elts = NULL; struct ht_divchn_pthread ht; keys = malloc_perror(num_ins, key_size); elts = malloc_perror(num_ins, elt_size); for (i = 0; i < num_ins; i++){ key = ptr(keys, i, key_size); for (j = 0; j < key_size - sizeof(size_t); j++){ /* set random bytes in a key, each to RANDOM mod 2**CHAR_BIT */ *(unsigned char *)ptr(key, j, 1) = RANDOM(); } /* set non-random bytes in a key, and create element */ memcpy(key_buf, &i, sizeof(size_t)); /* eff. type in key unchanged */ memcpy(ptr(key, key_size - sizeof(size_t), 1), key_buf, sizeof(size_t)); new_elt(ptr(elts, i, elt_size), i); } ht_divchn_pthread_init(&ht, key_size, elt_size, 0, alpha_n, log_alpha_d, log_num_locks, num_grow_threads, NULL, NULL, NULL, NULL, free_elt); ht_divchn_pthread_align(&ht, elt_alignment); insert_keys_elts(&ht, keys, elts, num_ins, num_threads, batch_count, &res); for (i = 1; i < num_ins; i++){ memcpy(ptr(elts, i, elt_size), ptr(elts, 0, elt_size), elt_size); } remove_key_elts(&ht, keys, elts, num_ins, num_threads, batch_count, &res); search_nin_ht(&ht, keys, elts, num_ins, num_threads, val_elt, &res); insert_keys_elts(&ht, keys, elts, num_ins, num_threads, batch_count, &res); search_in_ht(&ht, keys, elts, num_ins, num_threads, val_elt, &res); delete_key_elts(&ht, keys, num_ins, num_threads, batch_count, &res); free_ht(&ht, 1); printf("\t\tremove and delete correctness: "); print_test_result(res); free(keys); free(elts); keys = NULL; elts = NULL; } /** Runs a corner cases test. */ void run_corner_cases_test(size_t log_ins){ int res = 1; size_t i, j; size_t elt; size_t elt_size = sizeof(size_t); size_t elt_alignment = sizeof(size_t); size_t key_size; size_t num_ins; unsigned char *key = NULL; struct ht_divchn_pthread ht; num_ins = pow_two_perror(log_ins); key = malloc_perror(1, pow_two_perror(C_CORNER_LOG_KEY_END)); for (i = 0; i < pow_two_perror(C_CORNER_LOG_KEY_END); i++){ key[i] = RANDOM(); } printf("Run corner cases test --> "); for (i = C_CORNER_LOG_KEY_START; i <= C_CORNER_LOG_KEY_END; i++){ key_size = pow_two_perror(i); ht_divchn_pthread_init(&ht, key_size, elt_size, C_CORNER_MIN_NUM, C_CORNER_ALPHA_N, C_CORNER_LOG_ALPHA_D, C_CORNER_NUM_LOCKS, C_CORNER_NUM_GROW_THREADS, NULL, NULL, NULL, NULL, NULL); ht_divchn_pthread_align(&ht, elt_alignment); for (j = 0; j < num_ins; j++){ elt = j; ht_divchn_pthread_insert(&ht, key, &elt, 1); } res *= (ht.count_ix == 0 && ht.count == C_CORNER_HT_COUNT && ht.num_elts == 1 && *(size_t *)ht_divchn_pthread_search(&ht, key) == elt); ht_divchn_pthread_delete(&ht, key, 1); res *= (ht.count == C_CORNER_HT_COUNT && ht.num_elts == 0 && ht_divchn_pthread_search(&ht, key) == NULL); ht_divchn_pthread_free(&ht); } print_test_result(res); free(key); key = NULL; } /** Helper functions. */ /** Computes a pointer to the ith element in the block of elements. */ void *ptr(const void *block, size_t i, size_t size){ return (void *)((char *)block + i * size); } /** Prints a test result. */ void print_test_result(int res){ if (res){ printf("SUCCESS\n"); }else{ printf("FAILURE\n"); } } /** Times execution. */ double timer(){ struct timeval tm; gettimeofday(&tm, NULL); return tm.tv_sec + tm.tv_usec / 1e6; } int main(int argc, char *argv[]){ int i; size_t *args = NULL; RGENS_SEED(); if (argc > C_ARGC_ULIMIT){ fprintf(stderr, "USAGE:\n%s", C_USAGE); exit(EXIT_FAILURE); } args = malloc_perror(C_ARGC_ULIMIT - 1, sizeof(size_t)); memcpy(args, C_ARGS_DEF, (C_ARGC_ULIMIT - 1) * sizeof(size_t)); for (i = 1; i < argc; i++){ args[i - 1] = atoi(argv[i]); } if (args[0] > C_FULL_BIT - 2 || args[1] > C_FULL_BIT - 1 || args[2] > C_FULL_BIT - 1 || args[1] > args[2] || args[3] < 1 || args[4] < 1 || args[5] > C_FULL_BIT - 1 || args[3] > args[4] || args[6] < 1 || args[7] > 1 || args[8] > 1 || args[9] > 1 || args[10] > 1 || args[11] > 1){ fprintf(stderr, "USAGE:\n%s", C_USAGE); exit(EXIT_FAILURE); } if (args[7]) run_insert_search_free_uint_test(args[0], args[1], args[2], args[3], args[4], args[5], args[6], 4, 15, 4, 1000); if (args[8]) run_remove_delete_uint_test(args[0], args[1], args[2], args[3], args[4], args[5], args[6], 4, 15, 4, 1000); if (args[9]) run_insert_search_free_uint_ptr_test(args[0], args[1], args[2], args[3], args[4], args[5], args[6], 4, 15, 4, 1000); if (args[10]) run_remove_delete_uint_ptr_test(args[0], args[1], args[2], args[3], args[4], args[5], args[6], 4, 15, 4, 1000); if (args[11]) run_corner_cases_test(args[0]); free(args); args = NULL; return 0; }
alfin3/graph-algorithms
data-structures/graph/graph.h
<reponame>alfin3/graph-algorithms<gh_stars>0 /** graph.h Struct declarations and declarations of accessible functions for representing a graph with generic integer vertices and generic contiguous weights. Each list in an adjacency list is represented by a dynamically growing stack. A vertex is of any integer type with values starting from 0 and is copied into an adjacency list as a "vt_size block". If a graph is weighted, an edge weight is an object within a contiguous memory block, such as an object of basic type (e.g. char, int, double) or a struct or an array, and is copied into the adjacency list as a "wt_size block". A single stack of vt_size and wt_size block pairs with adjustable alignment in memory is used to achieve cache efficiency in graph algorithms. Depending on the problem size and a given system, the choice of an integer type of a lower size for vertices may provide additional cache efficiency in addition to reducing the space requirements. The user-defined and predefined operations for reading and writing integer values into the vt_size blocks of vertices use size_t as the user interface. This design is portable because vertex values start from zero and are used as indices in the array of stacks in an adjacency list. As a consequence, a valid vertex value of any integer type cannot exceed the maximum value of size_t. The implementation only uses integer and pointer operations. Given parameter values within the specified ranges, the implementation provides an error message and an exit is executed if an integer overflow is attempted or an allocation is not completed due to insufficient resources. The behavior outside the specified parameter ranges is undefined. The implementation does not use stdint.h and is portable under C89/C90 and C99. TODO: add non-contiguous weights to store pointers to data such as images as graph weights */ #ifndef GRAPH_H #define GRAPH_H #include <stdlib.h> #include "stack.h" struct graph{ size_t num_vts; size_t num_es; size_t vt_size; size_t wt_size; /* 0 if a graph is not weighted */ void *u; /* u of (u, v) edges, NULL if no edges */ void *v; /* v of (u, v) edges, NULL if no edges */ void *wts; /* NULL if no edges or wt_size is 0 */ }; struct adj_lst{ size_t num_vts; size_t num_es; size_t vt_size; size_t wt_size; size_t pair_size; /* size of a vertex weight pair aligned in memory */ size_t wt_offset; /* number of bytes from beginning of pair to weight */ void *buf; /* buffer that is only used by adj_lst_ functions */ struct stack **vt_wts; /* stacks of vt wt pairs, NULL if no vertices */ }; /** Initializes a weighted or unweighted graph with num_vts vertices and no edges, providing a basis for graph construction. Makes no allocations. g : pointer to a preallocated block of size sizeof(struct graph) num_vts : number of vertices vt_size : non-zero size of the integer type used to represent a vertex according to sizeof; equals to the size of the vt_size block of a vertex wt_size : - 0 if a graph is not weighted - otherwise non-zero size of the wt_size block of a weight; must account for internal and trailing padding according to sizeof */ void graph_base_init(struct graph *g, size_t num_vts, size_t vt_size, size_t wt_size); /** Initializes an empty adjacency list according to a graph. The alignment of vt_size and wt_size blocks in the adjacency list is computed by default according to their sizes because size of a type T >= alignment requirement of T (due to the structure of arrays), which may result in overalignment. a : pointer to a preallocated block of size sizeof(struct adj_lst) g : pointer to the graph struct of a graph that was initialized with at least graph_base_init */ void adj_lst_base_init(struct adj_lst *a, const struct graph *g); /** Aligns the vt_size and wt_size blocks in an adjacency list according to the values of the alignment parameters. If the alignment requirement of only one type is known, then the size of the other type can be used as a value of the other alignment parameter because size of type >= alignment requirement of type (due to structure of arrays), which may result in overalignment. The call to this operation may result in the reduction of space requirements as compared to adj_lst_base_init alone. The operation is optionally called after adj_lst_base_init is completed and before any other adj_list_ operation is called. a : pointer to an adj_lst struct initialized with adj_lst_base_init vt_alignment : alignment requirement or size of the type of the vt_size block of a vertex, which is the representation of an integer type value; if size, must account for padding according to sizeof wt_alignment : alignment requirement or size of the type of the wt_size block of a weight; if size, must account for internal and trailing padding according to sizeof */ void adj_lst_align(struct adj_lst *a, size_t vt_alignment, size_t wt_alignment); /** Builds the adjacency list of a directed graph. The adjacency list keeps the effective type of the copied vt_size blocks (with integer values) from the graph. The adjacency list also keeps the effective type of the copied wt_size blocks if the graph is weighted and the wt_size blocks have an effective type in the graph. a : pointer to an adj_lst struct initialized with adj_lst_base_init and optionally with adj_lst_align g : pointer to the graph struct of a graph initialized with at least graph_base_init read_vt : reads the integer value in the vt_size block of a vertex pointed to by the argument and returns a size_t value */ void adj_lst_dir_build(struct adj_lst *a, const struct graph *g, size_t (*read_vt)(const void *)); /** Builds the adjacency list of an undirected graph. The adjacency list keeps the effective type of the copied vt_size blocks (with integer values) from the graph. The adjacency list also keeps the effective type of the copied wt_size blocks if the graph is weighted and the wt_size blocks have an effective type in the graph. a : pointer to an adj_lst struct initialized with adj_lst_base_init and optionally with adj_lst_align g : pointer to the graph struct of a graph initialized with at least graph_base_init read_vt : reads the integer value in the vt_size block of a vertex pointed to by the argument and returns a size_t value */ void adj_lst_undir_build(struct adj_lst *a, const struct graph *g, size_t (*read_vt)(const void *)); /** Adds a directed edge (u, v) to the adjacency list of a directed graph according to a Bernoulli distribution. a : pointer to an adj_lst struct initialized with adj_lst_base_init and optionally with adj_lst_align u : u of an (u, v) edge to be added; is less than the number of vertices in an adjacency list v : v of an (u, v) edge to be added; is less than the number of vertices in an adjacency list wt : - NULL if the graph is not weighted - otherwise points to the wt_size block of a weight write_vt : writes the integer value of the second argument to the vt_size block pointed to by the first argument as a value of the integer type used to represent vertices bern : takes arg as the value of its parameter and returns nonzero if the edge is added according to a Bernoulli distribution arg : pointer that is taken as the value of the parameter of bern */ void adj_lst_add_dir_edge(struct adj_lst *a, size_t u, size_t v, const void *wt, void (*write_vt)(void *, size_t), int (*bern)(void *), void *arg); /** Adds an undirected edge (u, v) to the adjacency list of an undirected graph according to a Bernoulli distribution. Please see the parameter specification in adj_lst_add_dir_edge. */ void adj_lst_add_undir_edge(struct adj_lst *a, size_t u, size_t v, const void *wt, void (*write_vt)(void *, size_t), int (*bern)(void *), void *arg); /** Builds the adjacency list of a directed graph with num_vts vertices, where each of the num_vts(num_vts - 1) possible edges is added according to a Bernoulli distribution. The added pairs of vt_size and wt_size blocks are aligned in memory according to the preceding calls to adj_lst_base_init and optionally adj_lst_align. If the graph is weighted, then the effective type of the wt_size block in each vt_size and wt_size block pair is not set and can be set by writing a weight value according to wt_offset after the call is completed. If the graph is not weighted, then there are no wt_size blocks. a : pointer to an adj_lst struct initialized with adj_lst_base_init and optionally with adj_lst_align write_vt : writes the integer value of the second argument to the vt_size block pointed to by the first argument as a value of the integer type used to represent vertices bern : takes arg as the value of its parameter and returns nonzero if the edge is added according to a Bernoulli distribution arg : pointer that is taken as the value of the parameter of bern */ void adj_lst_rand_dir(struct adj_lst *a, void (*write_vt)(void *, size_t), int (*bern)(void *), void *arg); /** Builds the adjacency list of an undirected graph with num_vts vertices, where each of the num_vts(num_vts - 1)/2 possible edges is added according to a Bernoulli distribution. The added pairs of vt_size and wt_size blocks are aligned in memory according to the preceding calls to adj_lst_base_init and optionally adj_lst_align. If the graph is weighted, then the effective type of the wt_size block in each vt_size and wt_size block pair is not set and can be set by writing the same weight value into the two pairs corresponding to (u, v) and (v, u) edges according to wt_offset after the call is completed. If the graph is not weighted, then there are no wt_size blocks. Please see the parameter specification in adj_lst_rand_dir. */ void adj_lst_rand_undir(struct adj_lst *a, void (*write_vt)(void *, size_t), int (*bern)(void *), void *arg); /** Frees the memory allocated by adj_lst_base_init and any subsequent calls to adj_lst_ operations, and leaves a block of size sizeof(struct adj_lst) pointed to by the a parameter. */ void adj_lst_free(struct adj_lst *a); /* A. Vertex operations */ /** Read values of different unsigned integer types of vertices. size_t can represent any vertex due to graph construction. */ size_t graph_read_uchar(const void *a); size_t graph_read_ushort(const void *a); size_t graph_read_uint(const void *a); size_t graph_read_ulong(const void *a); size_t graph_read_sz(const void *a); /** Write values of different unsigned integer types of vertices. */ void graph_write_uchar(void *a, size_t val); void graph_write_ushort(void *a, size_t val); void graph_write_uint(void *a, size_t val); void graph_write_ulong(void *a, size_t val); void graph_write_sz(void *a, size_t val); /** Get a pointer to the element in the array pointed to by the first argument at the index pointed to by the second argument; the first argument points to the unsigned integer type used to represent vertices and is not dereferenced; the second argument points to a value of the same unsigned integer type and is dereferenced. */ void *graph_at_uchar(const void *a, const void *i); void *graph_at_ushort(const void *a, const void *i); void *graph_at_uint(const void *a, const void *i); void *graph_at_ulong(const void *a, const void *i); void *graph_at_sz(const void *a, const void *i); /** Compare the element pointed to by the first argument to the element pointed to by the second argument, and return 0 iff the two elements are equal; each argument points to a value of the unsigned integer type used to represent vertices. */ int graph_cmpeq_uchar(const void *a, const void *b); int graph_cmpeq_ushort(const void *a, const void *b); int graph_cmpeq_uint(const void *a, const void *b); int graph_cmpeq_ulong(const void *a, const void *b); int graph_cmpeq_sz(const void *a, const void *b); /** Increment values of different unsigned integer types. The argument points to a value of the unsigned integer type used to represent vertices. */ void graph_incr_uchar(void *a); void graph_incr_ushort(void *a); void graph_incr_uint(void *a); void graph_incr_ulong(void *a); void graph_incr_sz(void *a); /* B. Weight operations */ /** Return a negative integer value if the value pointed to by the first argument is less than the value pointed to by the second, a positive integer value if the value pointed to by the first argument is greater than the value pointed to by the second, and zero integer value if the two values are equal; each argument points to a value of the integer type used to represent weights. Non-integer weight operations on suitable systems are defined by the user. */ int graph_cmp_uchar(const void *a, const void *b); int graph_cmp_ushort(const void *a, const void *b); int graph_cmp_uint(const void *a, const void *b); int graph_cmp_ulong(const void *a, const void *b); int graph_cmp_sz(const void *a, const void *b); int graph_cmp_schar(const void *a, const void *b); int graph_cmp_short(const void *a, const void *b); int graph_cmp_int(const void *a, const void *b); int graph_cmp_long(const void *a, const void *b); /** Copies the sum of the values pointed to by the second and third arguments to the preallocated block pointed to by the first argument; the second and third arguments point to values of the integer type used to represent weights; if the block pointed to by the first argument has no declared type, then the operation sets the effective type to the type used to represent weights; the operations with the _perror suffix provide an error message and an exit is executed if an integer overflow is attempted during addition. Non-integer weight operations on suitable systems are defined by the user. */ void graph_add_uchar(void *s, const void *a, const void *b); void graph_add_ushort(void *s, const void *a, const void *b); void graph_add_uint(void *s, const void *a, const void *b); void graph_add_ulong(void *s, const void *a, const void *b); void graph_add_sz(void *s, const void *a, const void *b); void graph_add_uchar_perror(void *s, const void *a, const void *b); void graph_add_ushort_perror(void *s, const void *a, const void *b); void graph_add_uint_perror(void *s, const void *a, const void *b); void graph_add_ulong_perror(void *s, const void *a, const void *b); void graph_add_sz_perror(void *s, const void *a, const void *b); void graph_add_schar(void *s, const void *a, const void *b); void graph_add_short(void *s, const void *a, const void *b); void graph_add_int(void *s, const void *a, const void *b); void graph_add_long(void *s, const void *a, const void *b); void graph_add_schar_perror(void *s, const void *a, const void *b); void graph_add_short_perror(void *s, const void *a, const void *b); void graph_add_int_perror(void *s, const void *a, const void *b); void graph_add_long_perror(void *s, const void *a, const void *b); #endif
alfin3/graph-algorithms
graph-algorithms/bfs/test-perf-uint/bfs-test-perf-uint.c
/** bfs-test-perf-uint.c Performance test of the BFS algorithm across graphs with only unsigned int vertices. The following command line arguments can be used to customize tests: bfs-test-perf-uint [0, uint width - 1] : a [0, uint width - 1] : b s.t. 2**a <= V <= 2**b for rand graph test usage examples: ./bfs-test-perf-uint ./bfs-test-perf-uint 10 14 bfs-test-perf-uint can be run with any subset of command line arguments in the above-defined order. If the (i + 1)th argument is specified then the ith argument must be specified for i >= 0. Default values are used for the unspecified arguments according to the C_ARGS_DEF array. The implementation of tests does not use stdint.h and is portable under C89/C90 and C99. The tests require that: - size_t and clock_t are convertible to double, - size_t can represent values upto 65535 for default values, and upto UINT_MAX (>= 65535) otherwise, - the widths of the unsigned integral types are less than 2040 and even. TODO: add portable size_t printing */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <limits.h> #include <time.h> #include "bfs.h" #include "graph.h" #include "stack.h" #include "utilities-mem.h" #include "utilities-mod.h" #include "utilities-lim.h" /** Generate random numbers in a portable way for test purposes only; rand() in the Linux C Library uses the same generator as random(), which may not be the case on older rand() implementations, and on current implementations on different systems. */ #define RGENS_SEED() do{srand(time(NULL));}while (0) #define RANDOM() (rand()) /* [0, RAND_MAX] */ #define DRAND() ((double)rand() / RAND_MAX) /* [0.0, 1.0] */ #define TOLU(i) ((unsigned long int)(i)) /* printing size_t under C89/C90 */ /* input handling */ const char *C_USAGE = "bfs-test-perf-uint\n" "[0, uint width - 1] : a\n" "[0, uint width - 1] : b s.t. 2**a <= V <= 2**b for rand graph test\n"; const int C_ARGC_ULIMIT = 3; const size_t C_ARGS_DEF[2] = {14u, 14u}; const size_t C_UINT_BIT = PRECISION_FROM_ULIMIT((unsigned int)-1); /* random graph tests */ const size_t C_FN_COUNT = 4; size_t (* const C_READ[4])(const void *) ={ graph_read_ushort, graph_read_uint, graph_read_ulong, graph_read_sz}; void (* const C_WRITE[4])(void *, size_t) ={ graph_write_ushort, graph_write_uint, graph_write_ulong, graph_write_sz}; void *(* const C_AT[4])(const void *, const void *) ={ graph_at_ushort, graph_at_uint, graph_at_ulong, graph_at_sz}; int (* const C_CMPEQ[4])(const void *, const void *) ={ graph_cmpeq_ushort, graph_cmpeq_uint, graph_cmpeq_ulong, graph_cmpeq_sz}; void (* const C_INCR[4])(void *) ={ graph_incr_ushort, graph_incr_uint, graph_incr_ulong, graph_incr_sz}; const size_t C_VT_SIZES[4] = { sizeof(unsigned short), sizeof(unsigned int), sizeof(unsigned long), sizeof(size_t)}; const char *C_VT_TYPES[4] = {"ushort", "uint ", "ulong ", "sz "}; const size_t C_ITER = 10u; const size_t C_PROBS_COUNT = 5u; const double C_PROBS[5] = {1.00, 0.75, 0.50, 0.25, 0.00}; const double C_PROB_ONE = 1.0; const double C_PROB_ZERO = 0.0; /* additional operations */ void *ptr(const void *block, size_t i, size_t size); /** Run a bfs test on random directed graphs. */ struct bern_arg{ double p; }; int bern(void *arg){ struct bern_arg *b = arg; if (b->p >= C_PROB_ONE) return 1; if (b->p <= C_PROB_ZERO) return 0; if (b->p > DRAND()) return 1; return 0; } void run_random_dir_graph_helper(size_t num_vts, size_t vt_size, const char *type_string, size_t (*read_vt)(const void *), void (*write_vt)(void *, size_t), void *(*at_vt)(const void *, const void *), int (*cmp_vt)(const void *, const void *), void (*incr_vt)(void *), int bern(void *), struct bern_arg *b); void run_random_dir_graph_test(size_t log_start, size_t log_end){ size_t i, j; size_t num_vts; struct bern_arg b; printf("Run a bfs test on random directed graphs from %lu random " "start vertices in each graph\n", TOLU(C_ITER)); for (i = 0; i < C_PROBS_COUNT; i++){ b.p = C_PROBS[i]; printf("\tP[an edge is in a graph] = %.2f\n", b.p); for (j = log_start; j <= log_end; j++){ num_vts = pow_two_perror(j); printf("\t\tvertices: %lu, E[# of directed edges]: %.1f\n", TOLU(num_vts), b.p * num_vts * (num_vts - 1)); run_random_dir_graph_helper(num_vts, C_VT_SIZES[1], C_VT_TYPES[1], C_READ[1], C_WRITE[1], C_AT[1], C_CMPEQ[1], C_INCR[1], bern, &b); } } } void run_random_dir_graph_helper(size_t num_vts, size_t vt_size, const char *type_string, size_t (*read_vt)(const void *), void (*write_vt)(void *, size_t), void *(*at_vt)(const void *, const void *), int (*cmp_vt)(const void *, const void *), void (*incr_vt)(void *), int bern(void *), struct bern_arg *b){ size_t i; size_t *start = NULL; void *dist = NULL, *prev = NULL; struct graph g; struct adj_lst a; clock_t t; /* no declared type after malloc; effective type is set by bfs */ start = malloc_perror(C_ITER, sizeof(size_t)); dist = malloc_perror(num_vts, vt_size); prev = malloc_perror(num_vts, vt_size); for (i = 0; i < num_vts; i++){ /* avoid trap representations in tests */ write_vt(ptr(dist, i, vt_size), 0); } graph_base_init(&g, num_vts, vt_size, 0); adj_lst_base_init(&a, &g); adj_lst_rand_dir(&a, write_vt, bern, b); for (i = 0; i < C_ITER; i++){ start[i] = RANDOM() % num_vts; } t = clock(); for (i = 0; i < C_ITER; i++){ bfs(&a, start[i], dist, prev, read_vt, write_vt, at_vt, cmp_vt, incr_vt); } t = clock() - t; printf("\t\t\t%s ave runtime: %.6f seconds\n", type_string, (double)t / C_ITER / CLOCKS_PER_SEC); adj_lst_free(&a); /* deallocates blocks with effective vertex type */ free(start); free(dist); free(prev); start = NULL; dist = NULL; prev = NULL; } /** Computes a pointer to the ith element in the block of elements. */ void *ptr(const void *block, size_t i, size_t size){ return (void *)((char *)block + i * size); } int main(int argc, char *argv[]){ int i; size_t *args = NULL; RGENS_SEED(); if (argc > C_ARGC_ULIMIT){ printf("USAGE:\n%s", C_USAGE); exit(EXIT_FAILURE); } args = malloc_perror(C_ARGC_ULIMIT - 1, sizeof(size_t)); memcpy(args, C_ARGS_DEF, (C_ARGC_ULIMIT - 1) * sizeof(size_t)); for (i = 1; i < argc; i++){ args[i - 1] = atoi(argv[i]); } if (args[0] > C_UINT_BIT - 1 || args[1] > C_UINT_BIT - 1 || args[1] < args[0]){ printf("USAGE:\n%s", C_USAGE); exit(EXIT_FAILURE); } run_random_dir_graph_test(args[0], args[1]); free(args); args = NULL; return 0; }
alfin3/graph-algorithms
graph-algorithms/dfs/dfs.h
<filename>graph-algorithms/dfs/dfs.h /** dfs.h Declarations of accessible functions for running the DFS algorithm on graphs with generic integer vertices indexed from 0. A graph may be unweighted or weighted. In the latter case the weights of the graph are ignored. The recursion in DFS is emulated on a dynamically allocated stack data structure to avoid an overflow of the memory stack. An option to optimally align the elements in the stack is provided and may increase the cache efficiency and reduce the space requirement*, depending on the system and the choice of the integer type for representing vertices. The effective type of every element in the previsit and postvisit arrays is of the integer type used to represent vertices. The value of every element is set by the algorithm. If the block pointed to by pre or post has no declared type then the algorithm sets the effective type of every element to the integer type used to represent vertices by writing a value of the type. The implementation only uses integer and pointer operations. Given parameter values within the specified ranges, the implementation provides an error message and an exit is executed if an integer overflow is attempted or an allocation is not completed due to insufficient resources. The behavior outside the specified parameter ranges is undefined. The implementation does not use stdint.h and is portable under C89/C90 and C99. * A bit array for cache-efficient set membership testing is not included due to an overhead that decreased the performance in tests. */ #ifndef DFS_H #define DFS_H #include <stddef.h> #include "graph.h" /** Computes and copies to the arrays pointed to by pre and post the previsit and postvisit values of a DFS search from a start vertex. Assumes start is valid and there is at least one vertex. a : pointer to an adjacency list with at least one and at most 2**(P - 1) - 1 vertices, where P is the precision of the integer type used to represent vertices start : a start vertex for running dfs pre : pointer to a preallocated array with the count equal to the number of vertices in the adjacency list; each element is of size vt_size (vt_size block) that equals to the size of the integer type used to represent vertices in the adjacency list; if the block pointed to by pre has no declared type then it is guaranteed that dfs sets the effective type of every element to the integer type used to represent vertices by writing a value of the type post : pointer to a preallocated array with the count equal to the number of vertices in the adjacency list; each element is of size vt_size (vt_size block) that equals to the size of the integer type used to represent vertices in the adjacency list; if the block pointed to by post has no declared type then it is guaranteed that dfs sets the effective type of every element to the integer type used to represent vertices by writing a value of the type read_vt : reads the integer value of the type used to represent vertices from the vt_size block pointed to by the argument and returns a size_t value write_vt : writes the integer value of the second argument to the vt_size block pointed to by the first argument as a value of the integer type used to represent vertices at_vt : returns a pointer to the element in the array pointed to by the first argument at the index pointed to by the second argument; the first argument points to the integer type used to represent vertices and is not dereferenced; the second argument points to a value of the integer type used to represent vertices and is dereferenced cmp_vt : returns 0 iff the element pointed to by the first argument is equal to the element pointed to by the second argument; each argument points to a value of the integer type used to represent vertices incr_vt : increments a value of the integer type used to represent vertices */ void dfs(const struct adj_lst *a, size_t start, void *pre, void *post, size_t (*read_vt)(const void *), void (*write_vt)(void *, size_t), void *(*at_vt)(const void *, const void *), int (*cmp_vt)(const void *, const void *), void (*incr_vt)(void *)); /** Computes and copies to the arrays pointed to by pre and post the previsit and postvisit values of a DFS search from a start vertex. Assumes start is valid and there is at least one vertex. Sets the alignment of void * vertex value pairs in the dynamically allocated stack used to emulate the dfs recursion. If the alignment requirement of only one type is known, then the size of the other type can be used as a value of the other alignment parameter because size of type >= alignment requirement of type (due to structure of arrays). The call to this operation may result in an increase in cache efficiency and a reduction of the space requirements as compared to dfs. Also see the parameter specification in dfs. vt_alignment : alignment requirement or size of the integer type used to represent vertices; the size is equal to vt_size, which accounts for padding according to sizeof vdp_alignment: alignment requirement of void * (i.e. alignof(void *)) or size of void * according to sizeof */ void dfs_align(const struct adj_lst *a, size_t start, size_t vt_alignment, size_t vdp_alignment, void *pre, void *post, size_t (*read_vt)(const void *), void (*write_vt)(void *, size_t), void *(*at_vt)(const void *, const void *), int (*cmp_vt)(const void *, const void *), void (*incr_vt)(void *)); #endif
alfin3/graph-algorithms
data-structures/ht-divchn/ht-divchn.h
/** ht-divchn.h Struct declarations and declarations of accessible functions of a hash table with generic contiguous or non-contiguous keys and generic contiguous or non-contiguous elements. The implementation is based on a division method for hashing into upto the number of slots determined by the largest prime number in the C_PRIME_PARTS array, representable as size_t on a given system, and a chaining method for resolving collisions. Due to chaining, the number of keys and elements that can be inserted is not limited by the hash table implementation. The load factor of a hash table is the expected number of keys in a slot under the simple uniform hashing assumption, and is upper-bounded by the alpha parameters. The alpha parameters do not provide an upper bound after the maximum count of slots in a hash table is reached. A distinction is made between a key and a "key_size block", and an element and an "elt_size block". During an insertion without update*, a contiguous block of size key_size ("key_size block") and a contiguous block of size elt_size ("elt_size block") are copied into a hash table. A key may be within a contiguous or non-contiguous memory block. Given a key, the user decides what is copied into the key_size block of the hash table. If the key is within a contiguous memory block, then it can be entirely copied as a key_size block, or a pointer to it can be copied as a key_size block. If the key is within a non-contiguous memory block, then a pointer to it is copied as a key_size block. The same applies to an element. When a pointer to a key is copied into a hash table as a key_size block, the user can also decide if only the pointer or the entire key is deleted during the delete and free operations. By setting free_key to NULL, only the pointer is deleted. Otherwise, the deletion is performed according to a non-NULL free_key. For example, when an in-memory set of images are used as keys (e.g. with a subset of bits in each image used for hashing) and pointers are copied into a hash table, then setting free_key to NULL will not affect the original set of images throughout the lifetime of the hash table. The same applies to elements and free_elt. The implementation only uses integer and pointer operations. Integer arithmetic is used in load factor operations, thereby eliminating the use of float. Given parameter values within the specified ranges, the implementation provides an error message and an exit is executed if an integer overflow is attempted** or an allocation is not completed due to insufficient resources. The behavior outside the specified parameter ranges is undefined. The implementation does not use stdint.h and is portable under C89/C90 and C99 with the only requirement that the width of size_t is greater or equal to 16, less than 2040, and is even. * if there is an update during an insertion, a key_size block is not copied and an elt_size block is copied ** except intended wrapping around of unsigned integers in modulo operations, which is defined, and overflow detection as a part of computing bounds, which is defined by the implementation. TODO: add division with magic number multiplication. */ #ifndef HT_DIVCHN_H #define HT_DIVCHN_H #include <stddef.h> #include "dll.h" struct ht_divchn{ size_t key_size; size_t elt_size; size_t elt_alignment; size_t group_ix; size_t count_ix; /* max size_t value if last representable prime reached */ size_t count; size_t alpha_n; size_t log_alpha_d; size_t max_num_elts; /* >= 0, <= C_SIZE_ULIMIT, alpha wrt a count */ size_t num_elts; struct dll *ll; struct dll_node **key_elts; /* array of pointers to nodes */ int (*cmp_key)(const void *, const void *); /* cmp_key and rdc_key must */ size_t (*rdc_key)(const void *); /* work on the same bits of a key */ void (*free_key)(void *); void (*free_elt)(void *); }; /** Initializes a hash table. An in-table elt_size block is guaranteed to be accessible only with a pointer to a character, unless additional alignment is performed by calling ht_divchn_align. ht : a pointer to a preallocated block of size sizeof(struct ht_divchn). key_size : non-zero size of a key_size block; must account for internal and trailing padding according to sizeof elt_size : non-zero size of an elt_size block; must account for internal and trailing padding according to sizeof min_num : minimum number of keys that are known to be or expected to be present simultaneously in a hash table; results in a speedup by avoiding unnecessary growth steps of a hash table; 0 if a positive value is not specified and all growth steps are to be completed alpha_n : > 0 numerator of a load factor upper bound log_alpha_d : < size_t width; log base 2 of the denominator of the load factor upper bound; the denominator is a power of two cmp_key : - if NULL then a default memcmp-based comparison of key_size blocks of keys is performed - otherwise comparison function is applied which returns a zero integer value iff the two keys accessed through the first and the second arguments are equal; each argument is a pointer to the key_size block of a key; cmp_key must use the same subset of bits in a key as rdc_key rdc_key : - if NULL then a default conversion of a bit pattern in the key_size block of a key is performed prior to hashing, which may introduce regularities - otherwise rdc_key is applied to a key to reduce the key to a size_t integer value prior to hashing; the argument points to the key_size block of a key; rdc_key must use the same subset of bits in a key as cmp_key free_key : - NULL if only key_size blocks should be deleted throughout the lifetime of the hash table (e.g. because keys were entirely copied as key_size blocks, or because pointers were copied as key_size blocks and only pointers should be deleted) - otherwise takes a pointer to the key_size block of a key as an argument, frees the memory of the key except the key_size block pointed to by the argument free_elt : - NULL if only elt_size blocks should be deleted throughout the lifetime of the hash table (e.g. because elements were entirely copied as elt_size blocks, or because pointers were copied as elt_size blocks and only pointers should be deleted) - otherwise takes a pointer to the elt_size block of an element as an argument, frees the memory of the element except the elt_size block pointed to by the argument */ void ht_divchn_init(struct ht_divchn *ht, size_t key_size, size_t elt_size, size_t min_num, size_t alpha_n, size_t log_alpha_d, int (*cmp_key)(const void *, const void *), size_t (*rdc_key)(const void *), void (*free_key)(void *), void (*free_elt)(void *)); /** Aligns each in-table elt_size block to be accessible with a pointer to a type T other than character through ht_divchn_search (in addition to a character pointer). If alignment requirement of T is unknown, the size of T can be used as a value of the alignment parameter because size of T >= alignment requirement of T (due to structure of arrays), which may result in overalignment. The hash table keeps the effective type of a copied elt_size block, if it had one at the time of insertion, and T must be compatible with the type to comply with the strict aliasing rules. T can be the same or a cvr-qualified/signed/unsigned version of the type. The operation is optionally called after ht_divchn_init is completed and before any other operation is called. ht : pointer to an initialized ht_divchn struct elt_alignment : alignment requirement or size of the type, a pointer to which is used to access the elt_size block of an element in a hash table; if size, must account for internal and trailing padding according to sizeof */ void ht_divchn_align(struct ht_divchn *ht, size_t elt_alignment); /** Inserts a key and an associated element into a hash table by copying the corresponding key_size and elt_size blocks. If the key pointed to by the key parameter is already in the hash table according to cmp_key, then deletes the previous element according to free_elt and copies the elt_size block pointed to by the elt parameter. ht : pointer to an initialized ht_divchn struct key : non-NULL pointer to the key_size block of a key elt : non-NULL pointer to the elt_size block of an element */ void ht_divchn_insert(struct ht_divchn *ht, const void *key, const void *elt); /** If a key is present in a hash table, according to cmp_key, then returns a pointer to the elt_size block of its associated element in the hash table. Otherwise returns NULL. The returned pointer can be dereferenced according to the preceding calls to ht_divchn_init and ht_divchn_align_elt. ht : pointer to an initialized ht_divchn struct key : non-NULL pointer to the key_size block of a key */ void *ht_divchn_search(const struct ht_divchn *ht, const void *key); /** Removes the element associated with a key in a hash table that equals to the key pointed to by the key parameter according to cmp_key, by a) copying the elt_size block of the element to the elt_size block pointed to by the elt parameter and b) deleting the corresponding key_size and elt_size blocks in the hash table. If there is no matching key in the hash table according to cmp_key, leaves the hash table and the block pointed to by elt unchanged. ht : pointer to an initialized ht_divchn struct key : non-NULL pointer to the key_size block of a key elt : non-NULL pointer to a preallocated elt_size block */ void ht_divchn_remove(struct ht_divchn *ht, const void *key, void *elt); /** If there is a key in a hash table that equals to the key pointed to by the key parameter according to cmp_key, then deletes the in-table key element pair according to free_key and free_elt. ht : pointer to an initialized ht_divchn struct key : non-NULL pointer to the key_size block of a key */ void ht_divchn_delete(struct ht_divchn *ht, const void *key); /** Frees the memory of all keys and elements that are in a hash table according to free_key and free_elt, frees the memory of the hash table, and leaves the block of size sizeof(struct ht_divchn) pointed to by the ht parameter. */ void ht_divchn_free(struct ht_divchn *ht); /** Help construct a hash table parameter value in algorithms and data structures with a hash table parameter, complying with the stict aliasing rules and compatibility rules for function types. In each case, a (qualified) struct ht_divchn *p0 is converted to (qualified) void * and back to a (qualified) struct ht_divchn *p1, thus guaranteeing that the value of p0 equals the value of p1. */ void ht_divchn_init_helper(void *ht, size_t key_size, size_t elt_size, size_t min_num, size_t alpha_n, size_t log_alpha_d, int (*cmp_key)(const void *, const void *), size_t (*rdc_key)(const void *), void (*free_key)(void *), void (*free_elt)(void *)); void ht_divchn_align_helper(void *ht, size_t elt_alignment); void ht_divchn_insert_helper(void *ht, const void *key, const void *elt); void *ht_divchn_search_helper(const void *ht, const void *key); void ht_divchn_remove_helper(void *ht, const void *key, void *elt); void ht_divchn_delete_helper(void *ht, const void *key); void ht_divchn_free_helper(void *ht); #endif
alfin3/graph-algorithms
graph-algorithms/bfs/bfs.c
<filename>graph-algorithms/bfs/bfs.c /** bfs.c Functions for running the BFS algorithm on graphs with generic integer vertices indexed from 0. A graph may be unweighted or weighted. In the latter case the weights of the graph are ignored. The effective type of every element in the prev array is of the integer type used to represent vertices. The value of every element is set by the algorithm to the value of the previous vertex. If the block pointed to by prev has no declared type then the algorithm sets the effective type of every element to the integer type used to represent vertices by writing a value of the type. A distance value in the dist array is only set if the corresponding vertex was reached, as indicated by the prev array, in which case it is guaranteed that the distance object representation is not a trap representation. An element corresponding to a not reached vertex, as indicated by the prev array, may be a trap representation. However, if the dist array is allocated with calloc, then for any integer type the representation with all zero bits is 0 integer value under C99 and C11 (6.2.6.2), and it is safe to read such a representation even if the value was not set by the algorithm. The implementation only uses integer and pointer operations. Given parameter values within the specified ranges, the implementation provides an error message and an exit is executed if an integer overflow is attempted or an allocation is not completed due to insufficient resources. The behavior outside the specified parameter ranges is undefined. The implementation does not use stdint.h and is portable under C89/C90 and C99. Note: A bit array for cache-efficient set membership testing is not included due to an overhead that decreased the performance in tests. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "bfs.h" #include "graph.h" #include "queue.h" #include "stack.h" #include "utilities-mem.h" static const size_t C_QUEUE_INIT_COUNT = 1; static void *ptr(const void *block, size_t i, size_t size); /** Computes and copies to an array pointed to by dist the lowest # of edges from start to each reached vertex, and provides the previous vertex in the array pointed to by prev, with the number of vertices in a graph as the special value in prev for unreached vertices. Assumes start is valid and there is at least one vertex. a : pointer to an adjacency list with at least one vertex start : a start vertex for running bfs dist : pointer to a preallocated array with the count of elements equal to the number of vertices in the adjacency list; each element is of size vt_size (vt_size block) that equals to the size of the integer type used to represent vertices in the adjacency list; if the block pointed to by dist has no declared type then bfs sets the effective type of each element corresponding to a reached vertex to the integer type of vertices by writing a value of the type; if the block was allocated with calloc then under C99 and C11 each element corresponding to an unreached vertex, can be safely read as an integer of the type used to represent vertices and will represent 0 value prev : pointer to a preallocated array with the count equal to the number of vertices in the adjacency list; each element is of size vt_size (vt_size block) that equals to the size of the integer type used to represent vertices in the adjacency list; if the block pointed to by prev has no declared type then it is guaranteed that bfs sets the effective type of every element to the integer type used to represent vertices by writing a value of the type read_vt : reads the integer value of the type used to represent vertices from the vt_size block pointed to by the argument and returns a size_t value write_vt : writes the integer value of the second argument to the vt_size block pointed to by the first argument as a value of the integer type used to represent vertices at_vt : returns a pointer to the element in the array pointed to by the first argument at the index pointed to by the second argument; the first argument points to the integer type used to represent vertices and is not dereferenced; the second argument points to a value of the integer type used to represent vertices and is dereferenced cmp_vt : returns 0 iff the element pointed to by the first argument is equal to the element pointed to by the second argument; each argument points to a value of the integer type used to represent vertices incr_vt : increments a value of the integer type used to represent vertices */ void bfs(const struct adj_lst *a, size_t start, void *dist, void *prev, size_t (*read_vt)(const void *), void (*write_vt)(void *, size_t), void *(*at_vt)(const void *, const void *), int (*cmp_vt)(const void *, const void *), void (*incr_vt)(void *)){ const void *p = NULL, *p_start = NULL, *p_end = NULL; struct queue q; /* variables in single block for cache-efficiency */ void * const vars = malloc_perror(5, a->vt_size); void * const u = vars; void * const nr = ptr(vars, 1, a->vt_size); void * const zero = ptr(vars, 2, a->vt_size); void * const ix = ptr(vars, 3, a->vt_size); void * const d = ptr(vars, 4, a->vt_size); write_vt(u, start); write_vt(nr, a->num_vts); write_vt(zero, 0); write_vt(ix, 0); write_vt(d, 0); write_vt(at_vt(dist, u), 0); while (cmp_vt(ix, nr) != 0){ memcpy(at_vt(prev, ix), nr, a->vt_size); incr_vt(ix); } memcpy(at_vt(prev, u), u, a->vt_size); queue_init(&q, a->vt_size, NULL); queue_bound(&q, C_QUEUE_INIT_COUNT, a->num_vts); queue_push(&q, u); while (q.num_elts > 0){ queue_pop(&q, u); memcpy(d, at_vt(dist, u), a->vt_size); incr_vt(d); p_start = a->vt_wts[read_vt(u)]->elts; p_end = (char *)p_start + a->vt_wts[read_vt(u)]->num_elts * a->pair_size; for (p = p_start; p != p_end; p = (char *)p + a->pair_size){ if (cmp_vt(at_vt(prev, p), nr) == 0){ memcpy(at_vt(dist, p), d, a->vt_size); memcpy(at_vt(prev, p), u, a->vt_size); queue_push(&q, p); } } } queue_free(&q); free(vars); /* after this line vars cannot be dereferenced */ } /** Computes a pointer to the ith element in the block of elements. According to C89 (draft): "It is guaranteed, however, that a pointer to an object of a given alignment may be converted to a pointer to an object of the same alignment or a less strict alignment and back again; the result shall compare equal to the original pointer. (An object that has character type has the least strict alignment.)" "A pointer to void may be converted to or from a pointer to any incomplete or object type. A pointer to any incomplete or object type may be converted to a pointer to void and back again; the result shall compare equal to the original pointer." "A pointer to void shall have the same representation and alignment requirements as a pointer to a character type." */ static void *ptr(const void *block, size_t i, size_t size){ return (void *)((char *)block + i * size); }
alfin3/graph-algorithms
data-structures/stack/stack.c
<gh_stars>0 /** stack.c Implementation of a generic dynamically allocated stack, providing a dynamic set of generic elements in the stack form. A distinction is made between an element and an "elt_size block". During an insertion a contiguous block of size elt_size ("elt_size block") is copied into a stack. An element may be within a contiguous or non- contiguous memory block. Given an element, the user decides what is copied into the elt_size block of the stack. If the element is within a contiguous memory block, then it can be entirely copied as an elt_size block, or a pointer to it can be copied as an elt_size block. If the element is within a non-contiguous memory block, then a pointer to it is copied as an elt_size block. When a pointer to an element is copied into a stack as an elt_size block, the user can also decide if only the pointer or the entire element is deleted during the free operation. By setting free_elt to NULL, only the pointer is deleted. Otherwise, the deletion is performed according to a non-NULL free_elt. For example, when an in-memory set of images are used as elements and pointers are copied into a stack, then setting free_elt to NULL will not affect the original set of images throughout the lifetime of the stack. The implementation only uses integer and pointer operations. Given parameter values within the specified ranges, the implementation provides an error message and an exit is executed if an integer overflow is attempted or an allocation is not completed due to insufficient resources. The behavior outside the specified parameter ranges is undefined. The implementation does not use stdint.h and is portable under C89/C90 and C99. Functions in stack.h and stack.c are similar to the implementation in https://see.stanford.edu/Course/CS107, with i) additional bound parameters to minimize the memory use in problems with the prior knowledge of the count of elements, ii) integer overflow safety, iii) generalization to size_t to represent indices and sizes, iv) C89/C90 and C99 compliance, and v) comments. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "stack.h" #include "utilities-mem.h" static void stack_grow(struct stack *s); static void *ptr(const void *block, size_t i, size_t size); static void fprintf_stderr_exit(const char *s, int line); /** Initializes a stack. By default the initialized stack can accomodate as many elt_size blocks as the system resources allow, starting from one elt_size block and growing by repetitive doubling. s : pointer to a preallocated block of size sizeof(struct stack) elt_size : non-zero size of an elt_size block; must account for internal and trailing padding according to sizeof free_elt : - NULL if only elt_size blocks should be deleted in the stack_free operation (e.g. because elements were entirely copied as elt_size blocks, or because pointers were copied as elt_size blocks and only pointers should be deleted) - otherwise takes a pointer to the elt_size block of an element as an argument, frees the memory of the element except the elt_size block pointed to by the argument */ void stack_init(struct stack *s, size_t elt_size, void (*free_elt)(void *)){ s->count = 1; s->init_count = 1; s->max_count = 0; s->num_elts = 0; s->elt_size = elt_size; s->elts = malloc_perror(s->init_count, elt_size); s->free_elt = free_elt; } /** Sets the count of an initially allocated stack to the count that can accomodate init_count elt_size blocks without reallocation. The growth of the stack is then achieved by repetitive doubling upto the count that equals to max_count. If max_count is greater than init_count and is not equal to init_count * 2**n for n > 0, then the last growth step sets the count of the stack to max_count. The operation is optionally called after stack_init is completed and before any other operation is called. s : pointer to a stack struct initialized with stack_init init_count : > 0 count of the elt_size blocks that can be simultaneously present in an initial stack without reallocation max_count : - if >= init_count, sets the maximum count of the elt_size blocks that can be simultaneously present in a stack; an error message is provided and an exit is executed if an attempt is made to exceed it - otherwise, the count of the elt_size blocks that can be simultaneously present in a stack is only limited by the available system resources */ void stack_bound(struct stack *s, size_t init_count, size_t max_count){ s->init_count = init_count; s->max_count = max_count; s->elts = realloc_perror(s->elts, s->init_count, s->elt_size); } /** Pushes an element onto a stack. s : pointer to an initialized stack struct elt : non-NULL pointer to the elt_size block of an element */ void stack_push(struct stack *s, const void *elt){ if (s->num_elts == s->count) stack_grow(s); memcpy(ptr(s->elts, s->num_elts, s->elt_size), elt, s->elt_size); s->num_elts++; } /** Pops an element of a stack. s : pointer to an initialized stack struct elt : non-NULL pointer to a preallocated elt_size block; if the stack is empty, the memory block pointed to by elt remains unchanged */ void stack_pop(struct stack *s, void *elt){ if (s->num_elts == 0) return; memcpy(elt, ptr(s->elts, s->num_elts - 1, s->elt_size), s->elt_size); s->num_elts--; } /** If a stack is not empty, returns a pointer to the first elt_size block, otherwise returns NULL. The returned pointer is guaranteed to point to the first element until a stack modifying operation is performed. If non-NULL, the returned pointed can be dereferenced as a pointer to the type of the elt_size block, or as a character pointer. s : pointer to an initialized stack struct */ void *stack_first(const struct stack *s){ if (s->num_elts == 0) return NULL; return ptr(s->elts, s->num_elts - 1, s->elt_size); } /** Frees the memory of all elements that are in a stack according to free_elt, frees the memory of the stack, and leaves the block of size sizeof(struct stack) pointed to by the s parameter. */ void stack_free(struct stack *s){ size_t i; if (s->free_elt != NULL){ for (i = 0; i < s->num_elts; i++){ s->free_elt(ptr(s->elts, i, s->elt_size)); } } free(s->elts); s->elts = NULL; } /** Helper functions */ /** Doubles the count of a stack, according to the bound parameter values and the available system resources. Amortized constant overhead for copying in the worst case of realloc calls. realloc's search is O(size of heap). */ static void stack_grow(struct stack *s){ if (s->count == s->max_count){ /* always enter if init_count == max_count */ fprintf_stderr_exit("tried to exceed the count maximum", __LINE__); }else if (s->max_count > s->init_count && s->max_count - s->count < s->count){ s->count = s->max_count; }else{ /* always enter if init_count > max_count */ s->count = mul_sz_perror(2, s->count); } s->elts = realloc_perror(s->elts, s->count, s->elt_size); } /** Computes a pointer to the ith element in the block of elements. */ void *ptr(const void *block, size_t i, size_t size){ return (void *)((char *)block + i * size); } /** Prints an error message and exits. */ static void fprintf_stderr_exit(const char *s, int line){ fprintf(stderr, "%s in %s at line %d\n", s, __FILE__, line); exit(EXIT_FAILURE); }
alfin3/graph-algorithms
graph-algorithms/bfs/bfs.h
/** bfs.h Declarations of accessible functions for running the BFS algorithm on graphs with generic integer vertices indexed from 0. A graph may be unweighted or weighted. In the latter case the weights of the graph are ignored. The effective type of every element in the prev array is of the integer type used to represent vertices. The value of every element is set by the algorithm to the value of the previous vertex. If the block pointed to by prev has no declared type then the algorithm sets the effective type of every element to the integer type used to represent vertices by writing a value of the type. A distance value in the dist array is only set if the corresponding vertex was reached, as indicated by the prev array, in which case it is guaranteed that the distance object representation is not a trap representation. An element corresponding to a not reached vertex, as indicated by the prev array, may be a trap representation. However, if the dist array is allocated with calloc, then for any integer type the representation with all zero bits is 0 integer value under C99 and C11 (6.2.6.2), and it is safe to read such a representation even if the value was not set by the algorithm. The implementation only uses integer and pointer operations. Given parameter values within the specified ranges, the implementation provides an error message and an exit is executed if an integer overflow is attempted or an allocation is not completed due to insufficient resources. The behavior outside the specified parameter ranges is undefined. The implementation does not use stdint.h and is portable under C89/C90 and C99. Note: A bit array for cache-efficient set membership testing is not included due to an overhead that decreased the performance in tests. */ #ifndef BFS_H #define BFS_H #include <stddef.h> #include "graph.h" /** Computes and copies to an array pointed to by dist the lowest # of edges from start to each reached vertex, and provides the previous vertex in the array pointed to by prev, with the number of vertices in a graph as the special value in prev for unreached vertices. Assumes start is valid and there is at least one vertex. a : pointer to an adjacency list with at least one vertex start : a start vertex for running bfs dist : pointer to a preallocated array with the count of elements equal to the number of vertices in the adjacency list; each element is of size vt_size (vt_size block) that equals to the size of the integer type used to represent vertices in the adjacency list; if the block pointed to by dist has no declared type then bfs sets the effective type of each element corresponding to a reached vertex to the integer type of vertices by writing a value of the type; if the block was allocated with calloc then under C99 and C11 each element corresponding to an unreached vertex, can be safely read as an integer of the type used to represent vertices and will represent 0 value prev : pointer to a preallocated array with the count equal to the number of vertices in the adjacency list; each element is of size vt_size (vt_size block) that equals to the size of the integer type used to represent vertices in the adjacency list; if the block pointed to by prev has no declared type then it is guaranteed that bfs sets the effective type of every element to the integer type used to represent vertices by writing a value of the type read_vt : reads the integer value of the type used to represent vertices from the vt_size block pointed to by the argument and returns a size_t value write_vt : writes the integer value of the second argument to the vt_size block pointed to by the first argument as a value of the integer type used to represent vertices at_vt : returns a pointer to the element in the array pointed to by the first argument at the index pointed to by the second argument; the first argument points to the integer type used to represent vertices and is not dereferenced; the second argument points to a value of the integer type used to represent vertices and is dereferenced cmp_vt : returns 0 iff the element pointed to by the first argument is equal to the element pointed to by the second argument; each argument points to a value of the integer type used to represent vertices incr_vt : increments a value of the integer type used to represent vertices */ void bfs(const struct adj_lst *a, size_t start, void *dist, void *prev, size_t (*read_vt)(const void *), void (*write_vt)(void *, size_t), void *(*at_vt)(const void *, const void *), int (*cmp_vt)(const void *, const void *), void (*incr_vt)(void *)); #endif
alfin3/graph-algorithms
graph-algorithms/prim/prim.c
/** prim.c Prim's algorithm on undirected graphs with generic integer vertices, generic weights (incl. negative) and a hash table parameter. The hash table parameter specifies a hash table used for in-heap operations, and enables the optimization of space and time resources associated with heap operations in Prim's algorithm by choice of a hash table and its load factor upper bound. If NULL is passed as a hash table parameter value, a default hash table is used, which contains an index array with a count that is equal to the number of vertices in the graph. If E >> V, a default hash table may provide speed advantages by avoiding the computation of hash values. If V is large and the graph is sparse, a non-default hash table may provide space advantages. The effective type of every element in the prev array is of the integer type used to represent vertices. The value of every element is set by the algorithm to the value of the previous vertex. If the block pointed to by prev has no declared type then the algorithm sets the effective type of every element to the integer type used to represent vertices by writing a value of the type, including a special value for unreached vertices. An edge weight value in the dist array is only set if the corresponding vertex was reached, as indicated by the prev array, in which case it is guaranteed that the edge weight object representation is not a trap representation. An element corresponding to a not reached vertex, as indicated by the prev array, may be a trap representation. However, if edge weights are of an integer type and the dist array is allocated with calloc, then for any integer type the representation with all zero bits is 0 integer value under C99 and C11 (6.2.6.2), and it is safe to read such a representation even if the value was not set by the algorithm. The implementation only uses integer and pointer operations. Given parameter values within the specified ranges, the implementation provides an error message and an exit is executed if an integer overflow is attempted or an allocation is not completed due to insufficient resources. The behavior outside the specified parameter ranges is undefined. The implementation does not use stdint.h and is portable under C89/C90 and C99. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "prim.h" #include "graph.h" #include "heap.h" #include "stack.h" #include "utilities-mem.h" static const size_t C_HEAP_INIT_COUNT = 1; struct ht_def{ size_t absent; size_t *elts; size_t (*read_vt)(const void *); }; static void ht_def_init(void *ht, size_t num_vts, size_t (*read_vt)(const void *)); static void ht_def_insert(void *ht, const void *vt, const void *ix); static void *ht_def_search(const void *ht, const void *vt); static void ht_def_remove(void *ht, const void *vt, void *ix); static void ht_def_free(void *ht); static size_t compute_wt_offset_perror(const struct adj_lst *a); static void *ptr(const void *block, size_t i, size_t size); /** Computes and copies the edge weights of an mst of the connected component of a start vertex to the array pointed to by dist, and the previous vertices to the array pointed to by prev, with the number of vertices as the special value in the prev array for unreached vertices. a : pointer to an adjacency list with at least one vertex start : start vertex for running the algorithm dist : pointer to a preallocated array with the count of elements equal to the number of vertices in the adjacency list; each element is of size wt_size (wt_size block) that equals to the size of a weight in the adjacency list; if the block pointed to by dist has no declared type then prim sets the effective type of each element corresponding to a reached vertex to the type of a weight in the adjacency list by writing a value of the type; if edge weights are of an integer type and the block was allocated with calloc then under C99 and C11 each element corresponding to an unreached vertex can be safely read as the integer type and will represent 0 value prev : pointer to a preallocated array with the count equal to the number of vertices in the adjacency list; each element is of size vt_size (vt_size block) that equals to the size of the integer type used to represent vertices in the adjacency list; if the block pointed to by prev has no declared type then it is guaranteed that prim sets the effective type of every element to the integer type used to represent vertices by writing a value of the type zero_wt : pointer to a block of size wt_size with a zero value of the type used to represent weights; this value is copied to the element in dist corresponding to the start vertex pmht : - NULL pointer, if a default hash table is used for in-heap operations; a default hash table contains an index array with a count that is equal to the number of vertices - a pointer to a set of parameters specifying a hash table used for in-heap operations read_vt : reads the integer value of the type used to represent vertices from the vt_size block pointed to by the argument and returns a size_t value write_vt : writes the integer value of the second argument to the vt_size block pointed to by the first argument as a value of the integer type used to represent vertices at_vt : returns a pointer to the element in the array pointed to by the first argument at the index pointed to by the second argument; the first argument points to the integer type used to represent vertices and is not dereferenced; the second argument points to a value of the integer type used to represent vertices and is dereferenced cmp_vt : returns 0 iff the element pointed to by the first argument is equal to the element pointed to by the second argument; each argument points to a value of the integer type used to represent vertices cmp_wt : comparison function which returns a negative integer value if the weight value pointed to by the first argument is less than the weight value pointed to by the second, a positive integer value if the weight value pointed to by the first argument is greater than the weight value pointed to by the second, and zero integer value if the two weight values are equal */ void prim(const struct adj_lst *a, size_t start, void *dist, void *prev, const void *wt_zero, const struct prim_ht *pmht, size_t (*read_vt)(const void *), void (*write_vt)(void *, size_t), void *(*at_vt)(const void *, const void *), int (*cmp_vt)(const void *, const void *), int (*cmp_wt)(const void *, const void *)){ struct ht_def ht_def; struct heap_ht hht; struct heap h; void *p = NULL, *p_start = NULL, *p_end = NULL; void *dp = NULL, *dp_new = NULL; /* variables in single block for cache-efficiency */ void * const vars = malloc_perror(1, add_sz_perror(compute_wt_offset_perror(a), a->wt_size)); void * const u = vars; void * const nr = (char *)u + a->vt_size; void * const du = (char *)u + compute_wt_offset_perror(a); write_vt(u, start); write_vt(nr, a->num_vts); memcpy(du, wt_zero, a->wt_size); memcpy(ptr(dist, read_vt(u), a->wt_size), wt_zero, a->wt_size); p_start = prev; p_end = ptr(prev, a->num_vts, a->vt_size); for (p = p_start; p != p_end; p = (char *)p + a->vt_size){ memcpy(p, nr, a->vt_size); } memcpy(at_vt(prev, u), u, a->vt_size); if (pmht == NULL){ ht_def_init(&ht_def, a->num_vts, read_vt); hht.ht = &ht_def; hht.alpha_n = 0; hht.log_alpha_d = 0; hht.init = NULL; hht.align = NULL; hht.insert = ht_def_insert; hht.search = ht_def_search; hht.remove = ht_def_remove; hht.free = ht_def_free; }else{ hht.ht = pmht->ht; hht.alpha_n = pmht->alpha_n; hht.log_alpha_d = pmht->log_alpha_d; hht.init = pmht->init; hht.align = pmht->align; hht.insert = pmht->insert; hht.search = pmht->search; hht.remove = pmht->remove; hht.free = pmht->free; } heap_init(&h, a->wt_size, a->vt_size, C_HEAP_INIT_COUNT, &hht, cmp_wt, cmp_vt, read_vt, NULL); heap_push(&h, du, u); while (h.num_elts > 0){ heap_pop(&h, du, u); p_start = a->vt_wts[read_vt(u)]->elts; p_end = ptr(p_start, a->vt_wts[read_vt(u)]->num_elts, a->pair_size); for (p = p_start; p != p_end; p = (char *)p + a->pair_size){ dp = ptr(dist, read_vt(p), a->wt_size); dp_new = (char *)p + a->wt_offset; if (cmp_vt(at_vt(prev, p), nr) == 0){ memcpy(dp, dp_new, a->wt_size); memcpy(at_vt(prev, p), u, a->vt_size); heap_push(&h, dp, p); }else if (cmp_wt(dp, dp_new) > 0 && /* hashing after && */ heap_search(&h, p) != NULL){ /* was not popped and a better edge found */ memcpy(dp, dp_new, a->wt_size); memcpy(at_vt(prev, p), u, a->vt_size); heap_update(&h, dp, p); } } } heap_free(&h); free(vars); /* vars cannot be dereferenced after this line */ } /** Default hash table operations, mapping values of the integer type used to represent vertices to size_t indices for in-heap operations. */ static void ht_def_init(void *ht, size_t num_vts, size_t (*read_vt)(const void *)){ size_t i; struct ht_def *ht_def = ht; ht_def->absent = num_vts; ht_def->elts = malloc_perror(num_vts, sizeof(size_t)); for (i = 0; i < num_vts; i++){ /* <= num_vts elements in the heap; indices are < num_vts */ ht_def->elts[i] = num_vts; } ht_def->read_vt = read_vt; } static void ht_def_insert(void *ht, const void *vt, const void *ix){ struct ht_def *ht_def = ht; ht_def->elts[ht_def->read_vt(vt)] = *(const size_t *)ix; } static void *ht_def_search(const void *ht, const void *vt){ const struct ht_def *ht_def = ht; const size_t *p = ht_def->elts + ht_def->read_vt(vt); if (*p != ht_def->absent){ return (void *)p; }else{ return NULL; } } static void ht_def_remove(void *ht, const void *vt, void *ix){ struct ht_def *ht_def = ht; size_t *p = ht_def->elts + ht_def->read_vt(vt); if (*p != ht_def->absent){ *(size_t *)ix = *p; *p = ht_def->absent; } } static void ht_def_free(void *ht){ struct ht_def *ht_def = ht; free(ht_def->elts); ht_def->elts = NULL; } /** Computes the wt_offset from malloc's pointer in the vars block consisting of two vt_size blocks followed by one wt_size block. */ static size_t compute_wt_offset_perror(const struct adj_lst *a){ size_t wt_rem; size_t vt_pair_size = mul_sz_perror(2, a->vt_size); if (vt_pair_size <= a->wt_size) return a->wt_size; wt_rem = vt_pair_size % a->wt_size; return add_sz_perror(vt_pair_size, (wt_rem > 0) * (a->wt_size - wt_rem)); } /** Computes a pointer to the ith element in the block of elements. According to C89 (draft): "It is guaranteed, however, that a pointer to an object of a given alignment may be converted to a pointer to an object of the same alignment or a less strict alignment and back again; the result shall compare equal to the original pointer. (An object that has character type has the least strict alignment.)" "A pointer to void may be converted to or from a pointer to any incomplete or object type. A pointer to any incomplete or object type may be converted to a pointer to void and back again; the result shall compare equal to the original pointer." "A pointer to void shall have the same representation and alignment requirements as a pointer to a character type." */ static void *ptr(const void *block, size_t i, size_t size){ return (void *)((char *)block + i * size); }
alfin3/graph-algorithms
data-structures/queue/queue.c
/** queue.c Implementation of a generic dynamically allocated queue, providing a dynamic set of generic elements in the fifo queue form. A distinction is made between an element and an "elt_size block". During an insertion a contiguous block of size elt_size ("elt_size block") is copied into a queue. An element may be within a contiguous or non- contiguous memory block. Given an element, the user decides what is copied into the elt_size block of the queue. If the element is within a contiguous memory block, then it can be entirely copied as an elt_size block, or a pointer to it can be copied as an elt_size block. If the element is within a non-contiguous memory block, then a pointer to it is copied as an elt_size block. When a pointer to an element is copied into a queue as an elt_size block, the user can also decide if only the pointer or the entire element is deleted during the free operation. By setting free_elt to NULL, only the pointer is deleted. Otherwise, the deletion is performed according to a non-NULL free_elt. For example, when an in-memory set of images are used as elements and pointers are copied into a queue, then setting free_elt to NULL will not affect the original set of images throughout the lifetime of the queue. The implementation is cache-efficient and provides a constant overhead per elt_size block across push and pop operations by maintaining the invariant that an elt_size block is copied within a queue at most once throughout its lifetime in the queue. The implementation only uses integer and pointer operations. Given parameter values within the specified ranges, the implementation provides an error message and an exit is executed if an integer overflow is attempted or an allocation is not completed due to insufficient resources. The behavior outside the specified parameter ranges is undefined. The implementation does not use stdint.h and is portable under C89/C90 and C99. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "queue.h" #include "utilities-mem.h" static void queue_grow(struct queue *q); static void queue_move(struct queue *q); static void *ptr(const void *block, size_t i, size_t size); static void fprintf_stderr_exit(const char *s, int line); /** Initializes a queue. By default the initialized queue can accomodate as many elt_size blocks as the system resources allow, starting from two elt_size blocks and growing by repetitive doubling. q : pointer to a preallocated block of size sizeof(struct queue) elt_size : non-zero size of an elt_size block; must account for internal and trailing padding according to sizeof free_elt : - NULL if only elt_size blocks should be deleted in the queue_free operation (e.g. because elements were entirely copied as elt_size blocks, or because pointers were copied as elt_size blocks and only pointers should be deleted) - otherwise takes a pointer to the elt_size block of an element as an argument, frees the memory of the element except the elt_size block pointed to by the argument */ void queue_init(struct queue *q, size_t elt_size, void (*free_elt)(void *)){ q->count = 2; q->init_count = 2; q->max_count = 0; q->num_elts = 0; q->num_popped_elts = 0; q->elt_size = elt_size; q->elts = malloc_perror(q->init_count, elt_size); q->free_elt = free_elt; } /** Sets the count of the elt_size blocks that can be simultaneously present in an initial queue without reallocation. The growth of the queue is then achieved by repetitive doubling upto the count that can accomodate max_count simultaneously present elt_size blocks. The bounds are valid for any sequence of push and pop operations. If max_count is greater than init_count and is not equal to init_count * 2**n for n > 0, then the last growth step sets the count of the queue to a count that accomodates max_count simultaneously present elt_size blocks. The operation is optionally called after queue_init is completed and before any other operation is called. q : pointer to a queue struct initialized with queue_init init_count : > 0 count of the elt_size blocks that can be simultaneously present in an initial queue without reallocation for any sequence of push and pop operations max_count : - if >= init_count, sets the maximum count of the elt_size blocks that can be simultaneously present in a queue for any sequence of push and pop operations; an error message is provided and an exit is executed if an attempt is made to exceed the allocated memory of the queue in queue_push, which may accomodate upto 2 * max_count elt_size blocks depending on the sequence of push and pop operations - otherwise, the count of the elt_size blocks that can be simultaneously present in a queue is only limited by the available system resources */ void queue_bound(struct queue *q, size_t init_count, size_t max_count){ /* doubling guarantees that max_count simultaneously present elt_size blocks can be accomodated for any sequence of pop and push ops */ q->init_count = mul_sz_perror(2, init_count); q->max_count = mul_sz_perror(2, max_count); q->elts = realloc_perror(q->elts, q->init_count, q->elt_size); } /** Pushes an element onto a queue. q : pointer to an initialized queue struct elt : non-NULL pointer to the elt_size block of an element */ void queue_push(struct queue *q, const void *elt){ if (q->count == q->num_popped_elts + q->num_elts) queue_grow(q); memcpy(ptr(q->elts, q->num_popped_elts + q->num_elts, q->elt_size), elt, q->elt_size); q->num_elts++; } /** Pops an element of a queue. q : pointer to an initialized queue struct elt : non-NULL pointer to a preallocated elt_size block; if the queue is empty, the memory block pointed to by elt remains unchanged */ void queue_pop(struct queue *q, void *elt){ if (q->num_elts == 0) return; memcpy(elt, ptr(q->elts, q->num_popped_elts, q->elt_size), q->elt_size); q->num_elts--; q->num_popped_elts++; if (q->count - q->num_popped_elts <= q->num_popped_elts){ queue_move(q); } } /** If a queue is not empty, returns a pointer to the first elt_size block, otherwise returns NULL. The returned pointer is guaranteed to point to the first element until a queue modifying operation is performed. If non-NULL, the returned pointer can be dereferenced as a pointer to the type of the elt_size block, or as a character pointer. s : pointer to an initialized queue struct */ void *queue_first(const struct queue *q){ if (q->num_elts == 0) return NULL; return ptr(q->elts, q->num_popped_elts, q->elt_size); } /** Frees the memory of all elements that are in a queue according to free_elt, frees the memory of the queue, and leaves the block of size sizeof(struct queue) pointed to by the q parameter. */ void queue_free(struct queue *q){ size_t i; if (q->free_elt != NULL){ for (i = 0; i < q->num_elts; i++){ q->free_elt(ptr(q->elts, q->num_popped_elts + i, q->elt_size)); } } free(q->elts); q->elts = NULL; } /** Helper functions */ /** Doubles the count of a queue, according to the bound parameter values and the available system resources. Amortized constant overhead for copying in the worst case of realloc calls. realloc's search is O(size of heap). */ static void queue_grow(struct queue *q){ if (q->count == q->max_count){ /* always enter if init_count == max_count */ fprintf_stderr_exit("tried to exceed the count maximum", __LINE__); }else if (q->max_count - q->count < q->count){ q->count = q->max_count; }else{ /* always enter if init_count > max_count */ q->count = mul_sz_perror(2, q->count); } q->elts = realloc_perror(q->elts, q->count, q->elt_size); } /** Moves elements to the beginning of the element array of a queue. Constant overhead per elt_size block because each elt_size is moved at most once. The destination and source regions do not overlap due to the implementation of the queue. */ static void queue_move(struct queue *q){ memcpy(q->elts, ptr(q->elts, q->num_popped_elts, q->elt_size), q->num_elts * q->elt_size); /* product cannot overflow */ q->num_popped_elts = 0; } /** Computes a pointer to the ith element in the block of elements. */ void *ptr(const void *block, size_t i, size_t size){ return (void *)((char *)block + i * size); } /** Prints an error message and exits. */ static void fprintf_stderr_exit(const char *s, int line){ fprintf(stderr, "%s in %s at line %d\n", s, __FILE__, line); exit(EXIT_FAILURE); }
alfin3/graph-algorithms
utilities/utilities-mem/utilities-mem.h
/** utilities-mem.h Declarations of accessible utility functions for memory management. */ #ifndef UTILITIES_MEM_H #define UTILITIES_MEM_H #include <stdlib.h> /** Addition and multiplication of size_t with wrapped overflow checking. */ size_t add_sz_perror(size_t a, size_t b); size_t mul_sz_perror(size_t a, size_t b); /** Multiplication of size_t with wrapped overflow and zero checking. Useful for computing end pointers for pointer iteration. */ size_t mul_nzero_sz_perror(size_t a, size_t b); /** Malloc, realloc, and calloc with wrapped error checking, including integer overflow checking. The latter is also included in calloc_perror because there is no guarantee that a calloc implementation checks for integer overflow. */ void *malloc_perror(size_t num, size_t size); void *realloc_perror(void *ptr, size_t num, size_t size); void *calloc_perror(size_t num, size_t size); #endif
alfin3/graph-algorithms
utilities/utilities-mod/utilities-mod-test.c
/** utilities-mod-test.c Tests of integer overflow-safe utility functions in modular arithmetic. The following command line arguments can be used to customize tests: utilities-mod-test [0, size_t width) : n for 2**n # trials in tests [0, 1] : pow_mod, mul_mod, and sum_mod tests on/off [0, 1] : mul_ext, represent_uint, and pow_two_perror tests on/off usage examples: ./utilities-mod-test 20 ./utilities-mod-test 20 0 1 utilities-mod-test can be run with any subset of command line arguments in the above-defined order. If the (i + 1)th argument is specified then the ith argument must be specified for i >= 0. Default values are used for the unspecified arguments according to the C_ARGS_DEF array. The implementation of tests does not use stdint.h and is portable under C89/C90 with the only requirement that the width of size_t is even. TODO: add portable size_t printing */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <limits.h> #include <time.h> #include "utilities-mem.h" #include "utilities-mod.h" #include "utilities-lim.h" /** Generate random numbers in a portable way for test purposes only; rand() in the Linux C Library uses the same generator as random(), which may not be the case on older rand() implementations, and on current implementations on different systems. */ #define RGENS_SEED() do{srand(time(NULL));}while (0) #define RANDOM() (rand()) /* [0, RAND_MAX] */ #define DRAND() ((double)rand() / RAND_MAX) /* [0.0, 1.0] */ #define TOLU(i) ((unsigned long int)(i)) /* printing size_t under C89/C90 */ /* input handling */ const char *C_USAGE = "utilities-mod-test \n" "[0, size_t width) : n for 2**n # trials in tests \n" "[0, 1] : pow_mod, mul_mod, and sum_mod tests on/off \n" "[0, 1] : mul_ext, represent_uint, and pow_two_perror tests on/off \n"; const int C_ARGC_ULIMIT = 4; const size_t C_ARGS_DEF[3] = {15u, 1u, 1u}; /* tests */ const unsigned char C_UCHAR_ULIMIT = (unsigned char)-1; const size_t C_SIZE_ULIMIT = (size_t)-1; /* >= 3 */ const size_t C_SIZE_HALF = (((size_t)1 << (PRECISION_FROM_ULIMIT((size_t)-1) / 2u)) - 1u); const size_t C_BYTE_BIT = CHAR_BIT; const size_t C_FULL_BIT = PRECISION_FROM_ULIMIT((size_t)-1); /* >= 2 */ const size_t C_HALF_BIT = PRECISION_FROM_ULIMIT((size_t)-1) / 2u; /* >= 1 */ const size_t C_BASE_ULIMIT = (((size_t)1 << (CHAR_BIT / 2u)) + 1u); /* >= 2, <= C_SIZE_ULIMIT */ void print_test_result(int res); /** Tests pow_mod. */ void run_pow_mod_test(int log_trials){ int res = 1; size_t i, trials; size_t k_max, n_max; size_t base_sq_max = C_SIZE_ULIMIT; size_t j, k; size_t a, n; size_t r, r_wo; trials = pow_two_perror(log_trials); k_max = 1; n_max = C_SIZE_HALF - 1; /* >= 0 */ while (base_sq_max / C_BASE_ULIMIT >= C_BASE_ULIMIT){ base_sq_max /= C_BASE_ULIMIT; k_max++; } printf("Run pow_mod random test\n "); for (i = 0; i < trials; i++){ r_wo = 1; a = DRAND() * C_BASE_ULIMIT; k = DRAND() * k_max; n = 1 + DRAND() * n_max; /* >= 1*/ r = pow_mod(a, k, n); for (j = 0; j < k; j++){ r_wo *= a; } r_wo = r_wo % n; res *= (r == r_wo); } printf("\t0 <= a <= %lu, 0 <= k <= %lu, 0 < n <= 2**%lu - 1 --> ", TOLU(C_BASE_ULIMIT), TOLU(k_max), TOLU(C_HALF_BIT)); print_test_result(res); res = 1; k_max = C_SIZE_ULIMIT - 1; n_max = C_SIZE_ULIMIT - 2; for (i = 0; i < trials; i++){ k = DRAND() * k_max; while (k & 1){ k = DRAND() * k_max; } n = 2 + DRAND() * n_max; a = n - 1; r = pow_mod(a, k, n); res *= (r == 1); } printf("\ta = n - 1, 0 <= k < 2**%lu - 1, 1 < n <= 2**%lu - 1, " "where 0 = k (mod 2) --> ", TOLU(C_FULL_BIT), TOLU(C_FULL_BIT)); print_test_result(res); res = 1; res *= (pow_mod(0, 0, 1) == 0); res *= (pow_mod(2, 0, 1) == 0); res *= (pow_mod(0, 0, 2) == 1); res *= (pow_mod(2, 0, 2) == 1); res *= (pow_mod(C_SIZE_ULIMIT, C_SIZE_ULIMIT, C_SIZE_ULIMIT) == 0); res *= (pow_mod(C_SIZE_ULIMIT - 1, C_SIZE_ULIMIT, C_SIZE_ULIMIT) == C_SIZE_ULIMIT - 1); res *= (pow_mod(C_SIZE_ULIMIT, C_SIZE_ULIMIT - 1, C_SIZE_ULIMIT) == 0); printf("\tcorner cases --> "); print_test_result(res); } /** Tests mul_mod. */ void run_mul_mod_test(int log_trials){ int res = 1; size_t i, trials; size_t a_max, b_max, n_max; size_t a, b, n; size_t r, r_wo; trials = pow_two_perror(log_trials); a_max = C_SIZE_HALF; b_max = C_SIZE_HALF; n_max = C_SIZE_ULIMIT - 1; printf("Run mul_mod random test\n"); for (i = 0; i < trials; i++){ a = DRAND() * a_max; b = DRAND() * b_max; n = 1 + DRAND() * n_max; r = mul_mod(a, b, n); r_wo = (a * b) % n; res *= (r == r_wo); } printf("\ta, b <= 2**%lu - 1, 0 < n <= 2**%lu - 1 --> ", TOLU(C_HALF_BIT), TOLU(C_FULL_BIT)); print_test_result(res); res = 1; for (i = 0; i < trials; i++){ n = 2 + DRAND() * (n_max - 1); r = mul_mod(n - 1, n - 1, n); res *= (r == 1); } printf("\ta, b = n - 1, 1 < n <= 2**%lu - 1 --> ", TOLU(C_FULL_BIT)); print_test_result(res); res = 1; res *= (mul_mod(0, 0, 1) == 0); res *= (mul_mod(1, 0, 2) == 0); res *= (mul_mod(0, 1, 2) == 0); res *= (mul_mod(0, 2, 2) == 0); res *= (mul_mod(1, 1, 2) == 1); res *= (mul_mod(0, C_SIZE_ULIMIT - 1, C_SIZE_ULIMIT) == 0); res *= (mul_mod(C_SIZE_ULIMIT - 1, 0, C_SIZE_ULIMIT) == 0); res *= (mul_mod(C_SIZE_ULIMIT - 1, 1, C_SIZE_ULIMIT) == C_SIZE_ULIMIT - 1); res *= (mul_mod(1, C_SIZE_ULIMIT - 1, C_SIZE_ULIMIT) == C_SIZE_ULIMIT - 1); res *= (mul_mod(C_SIZE_ULIMIT - 1, C_SIZE_ULIMIT - 1, C_SIZE_ULIMIT - 1) == 0); res *= (mul_mod(C_SIZE_ULIMIT - 1, C_SIZE_ULIMIT - 1, C_SIZE_ULIMIT) == 1); res *= (mul_mod(C_SIZE_ULIMIT, C_SIZE_ULIMIT, C_SIZE_ULIMIT) == 0); printf("\tcorner cases --> "); print_test_result(res); } /** Tests sum_mod. */ void run_sum_mod_test(int log_trials){ int res = 1; size_t i, trials; size_t a_max, b_max, n_max; size_t a, b, n; size_t r, r_wo; trials = pow_two_perror(log_trials); a_max = pow_two_perror(C_FULL_BIT - 1) - 1; b_max = pow_two_perror(C_FULL_BIT - 1) - 1; n_max = C_SIZE_ULIMIT - 1; printf("Run sum_mod random test\n"); for (i = 0; i < trials; i++){ a = DRAND() * a_max; b = DRAND() * b_max; n = 1 + DRAND() * n_max; r = sum_mod(a, b, n); r_wo = (a + b) % n; res *= (r == r_wo); } printf("\ta, b <= 2**%lu - 1, 0 < n <= 2**%lu - 1 --> ", TOLU(C_FULL_BIT - 1), TOLU(C_FULL_BIT)); print_test_result(res); res = 1; for (i = 0; i < trials; i++){ b = 1 + DRAND() * n_max; r = sum_mod(n_max, b, n_max + 1); res *= (r == b - 1); } printf("\ta = 2**%lu - 2, 0 < b <= 2**%lu - 1, n = 2**%lu - 1 --> ", TOLU(C_FULL_BIT), TOLU(C_FULL_BIT), TOLU(C_FULL_BIT)); print_test_result(res); res = 1; res *= (sum_mod(0, 0, 1) == 0); res *= (sum_mod(1, 0, 2) == 1); res *= (sum_mod(0, 1, 2) == 1); res *= (sum_mod(1, 1, 2) == 0); res *= (sum_mod(C_SIZE_ULIMIT - 1, C_SIZE_ULIMIT - 1, C_SIZE_ULIMIT) == C_SIZE_ULIMIT - 2); printf("\tcorner cases --> "); print_test_result(res); } /** Tests mul_ext. */ void run_mul_ext_test(int log_trials){ int res = 1; size_t i, trials; size_t a, b, n; size_t h, l; size_t *hl = NULL; trials = pow_two_perror(log_trials); hl = malloc_perror(2, sizeof(size_t)); printf("Run mul_ext random test\n"); for (i = 0; i < trials; i++){ a = DRAND() * C_SIZE_HALF; b = DRAND() * C_SIZE_HALF; mul_ext(a, b, &h, &l); res *= (h == 0); res *= (l == a * b); } printf("\t0 <= a, b <= 2**%lu - 1 --> ", TOLU(C_HALF_BIT)); print_test_result(res); res = 1; for (i = 0; i < trials; i++){ a = 1 + DRAND() * (C_SIZE_ULIMIT - 1); b = 1 + DRAND() * (C_SIZE_ULIMIT - 1); n = 1 + DRAND() * (C_SIZE_ULIMIT - 1); mul_ext(a, b, &h, &l); hl[0] = l; hl[1] = h; res *= (sum_mod(hl[0] % n, mul_mod(sum_mod(C_SIZE_ULIMIT, 1, n), hl[1] % n, n), n) == mul_mod(a, b, n)); } printf("\t0 < a, b <= 2**%lu - 1 --> ", TOLU(C_FULL_BIT)); print_test_result(res); res = 1; mul_ext(0, 0, &h, &l); res *= (h == 0 && l == 0); mul_ext(1, 0, &h, &l); res *= (h == 0 && l == 0); mul_ext(0, 1, &h, &l); res *= (h == 0 && l == 0); mul_ext(1, 1, &h, &l); res *= (h == 0 && l == 1); mul_ext(pow_two_perror(C_HALF_BIT), pow_two_perror(C_HALF_BIT), &h, &l); res *= (h == 1 && l == 0); mul_ext(pow_two_perror(C_FULL_BIT - 1), pow_two_perror(C_FULL_BIT - 1), &h, &l); res *= (h == pow_two_perror(C_FULL_BIT - 2) && l == 0); mul_ext(C_SIZE_ULIMIT, C_SIZE_ULIMIT, &h, &l); res *= (h == C_SIZE_ULIMIT - 1 && l == 1); printf("\tcorner cases --> "); print_test_result(res); free(hl); hl = NULL; } /** Tests represent_uint. */ void run_represent_uint_test(int log_trials){ int res = 1; int i, trials; size_t n, k, u; size_t j; trials = pow_two_perror(log_trials); printf("Run represent_uint odds test --> "); for (i = 0; i < trials; i++){ n = RANDOM(); while (!(n & 1)){ n = RANDOM(); } represent_uint(n, &k, &u); res *= (k == 0 && u == n); } print_test_result(res); res = 1; printf("Run represent_uint odds * 2**k test --> "); for (i = 0; i < trials; i++){ for (j = 0; j <= C_FULL_BIT - C_BYTE_BIT; j++){ n = RANDOM() % C_UCHAR_ULIMIT; if (!(n & 1)) n++; /* <= C_UCHAR_ULIMIT as size_t */ represent_uint(pow_two_perror(j) * n, &k, &u); res *= (k == j && u == n); } } print_test_result(res); res = 1; printf("Run represent_uint corner cases test --> "); represent_uint(0, &k, &u); res *= (k == C_FULL_BIT && u == 0); represent_uint(1, &k, &u); res *= (k == 0 && u == 1); print_test_result(res); } /** Tests pow_two. */ void run_pow_two_test(){ int res = 1; int i, trials = C_FULL_BIT; size_t prod = 1; for (i = 0; i < trials; i++){ res *= (prod == pow_two_perror(i)); prod *= 2; } printf("Run pow_two test --> "); print_test_result(res); } void print_test_result(int res){ if (res){ printf("SUCCESS\n"); }else{ printf("FAILURE\n"); } } int main(int argc, char *argv[]){ int i; size_t *args = NULL; RGENS_SEED(); if (argc > C_ARGC_ULIMIT){ printf("USAGE:\n%s", C_USAGE); exit(EXIT_FAILURE); } args = malloc_perror(C_ARGC_ULIMIT - 1, sizeof(size_t)); memcpy(args, C_ARGS_DEF, (C_ARGC_ULIMIT - 1) * sizeof(size_t)); for (i = 1; i < argc; i++){ args[i - 1] = atoi(argv[i]); } if (args[0] > C_FULL_BIT - 1 || args[1] > 1 || args[2] > 1){ printf("USAGE:\n%s", C_USAGE); exit(EXIT_FAILURE); } if (args[1]){ run_pow_mod_test(args[0]); run_mul_mod_test(args[0]); run_sum_mod_test(args[0]); } if (args[2]){ run_mul_ext_test(args[0]); run_represent_uint_test(args[0]); run_pow_two_test(); } free(args); args = NULL; return 0; }
alfin3/graph-algorithms
utilities/utilities-alg/utilities-alg-test.c
<gh_stars>0 /** utilities-alg-test.c Tests of general algorithm utilities. The following command line arguments can be used to customize tests: utilities-alg-test [0, # bits in size_t) : n for 2^n trials in geq_leq_bsearch tests [0, # bits in size_t) : a [0, # bits in size_t) : b s.t. 2^a <= count <= 2^b in geq_leq_bsearch tests [0, 1] : geq_leq_bsearch int test on/off [0, 1] : geq_leq_bsearch double test on/off usage examples: ./utilities-alg-test ./utilities-alg-test 0 0 10 ./utilities-alg-test 0 25 25 ./utilities-alg-test 10 20 25 0 1 utilities-alg-test can be run with any subset of command line arguments in the above-defined order. If the (i + 1)th argument is specified then the ith argument must be specified for i >= 0. Default values are used for the unspecified arguments according to the C_ARGS_DEF array. The implementation of tests does not use stdint.h and is portable under C89/C90 with the only requirement that CHAR_BIT * sizeof(size_t) is even. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <limits.h> #include <time.h> #include "utilities-alg.h" #include "utilities-mem.h" #include "utilities-mod.h" /** Generate random numbers in a portable way for test purposes only; rand() in the Linux C Library uses the same generator as random(), which may not be the case on older rand() implementations, and on current implementations on different systems. */ #define RGENS_SEED() do{srand(time(NULL));}while (0) #define RANDOM() (rand()) /* [0, RAND_MAX] */ #define DRAND() ((double)rand() / RAND_MAX) /* [0.0, 1.0] */ #define TOLU(i) ((unsigned long int)(i)) /* printing size_t under C89/C90 */ /* input handling */ const char *C_USAGE = "utilities-alg-test \n" "[0, # bits in size_t) : n for 2^n trials in geq_leq_bsearch tests \n" "[0, # bits in size_t) : a \n" "[0, # bits in size_t) : b s.t. 2^a <= count <= 2^b in " "geq_leq_bsearch tests \n" "[0, 1] : geq_leq_bsearch int test on/off \n" "[0, 1] : geq_leq_bsearch double test on/off \n"; const int C_ARGC_MAX = 6; const size_t C_ARGS_DEF[5] = {10, 10, 15, 1, 1}; const size_t C_FULL_BIT = CHAR_BIT * sizeof(size_t); /* tests */ const size_t C_NRAND_COUNT_MAX = 100; const double C_HALF_PROB = 0.5; void *elt_ptr(const void *elts, size_t i, size_t elt_size); void print_test_result(int result); /** Test geq_bsearch and leq_bsearch. */ int cmp_int(const void *a, const void *b){ if (*(int *)a > *(int *)b){ return 1; }else if (*(int *)a < *(int *)b){ return -1; }else{ return 0; } } int cmp_double(const void *a, const void *b){ if (*(double *)a > *(double *)b){ return 1; }else if (*(double *)a < *(double *)b){ return -1; }else{ return 0; } } int is_geq_leq_correct(const void *key, const void *elts, size_t count, size_t elt_size, size_t geq_ix, size_t leq_ix, int (*cmp)(const void *, const void *)); void run_geq_leq_bsearch_int_test(int pow_trials, int pow_count_start, int pow_count_end){ int res = 1; int i; int key; int *elts = NULL, *nrand_elts = NULL; size_t j, count; size_t k, trials; size_t elt_size = sizeof(int); size_t geq_ix, leq_ix; double tot_geq, tot_leq, tot; clock_t t_geq, t_leq, t; trials = pow_two(pow_trials); elts = malloc_perror(pow_two(pow_count_end), elt_size); nrand_elts = malloc_perror(C_NRAND_COUNT_MAX, elt_size); printf("Test geq_bsearch and leq_bsearch on random int arrays\n"); for (i = pow_count_start; i <= pow_count_end; i++){ count = pow_two(i); for (j = 0; j < count; j++){ elts[j] = (DRAND() < C_HALF_PROB ? -1 : 1) * RANDOM(); } qsort(elts, count, elt_size, cmp_int); tot_geq = 0.0; tot_leq = 0.0; tot = 0.0; for(k = 0; k < trials; k++){ key = (DRAND() < C_HALF_PROB ? -1 : 1) * RANDOM(); t_geq = clock(); geq_ix = geq_bsearch(&key, elts, count, elt_size, cmp_int); t_geq = clock() - t_geq; tot_geq += (double)t_geq / CLOCKS_PER_SEC; t_leq = clock(); leq_ix = leq_bsearch(&key, elts, count, elt_size, cmp_int); t_leq = clock() - t_leq; tot_leq += (double)t_leq / CLOCKS_PER_SEC; t = clock(); bsearch(&key, elts, count, elt_size, cmp_int); t = clock() - t; tot += (double)t / CLOCKS_PER_SEC; res *= is_geq_leq_correct(&key, elts, count, elt_size, geq_ix, leq_ix, cmp_int); } printf("\tarray count: %lu, # trials: %lu\n", TOLU(count), TOLU(trials)); printf("\t\t\tgeq_bsearch: %.6f seconds\n", tot_geq); printf("\t\t\tleq_bsearch: %.6f seconds\n", tot_geq); printf("\t\t\tbsearch: %.6f seconds\n", tot); printf("\t\t\tcorrectness: "); print_test_result(res); } printf("\tnon-random array and corner cases\n"); res = 1; for (j = 0; j < C_NRAND_COUNT_MAX; j++){ if (j == 0){ nrand_elts[j] = 1; }else{ nrand_elts[j] = nrand_elts[j - 1] + 2; /* odd elements */ } } for (count = 1; count <= C_NRAND_COUNT_MAX; count++){ for (j = 0; j <= count; j++){ key = 2 * j; /* even keys */ geq_ix = geq_bsearch(&key, nrand_elts, count, elt_size, cmp_int); leq_ix = leq_bsearch(&key, nrand_elts, count, elt_size, cmp_int); if (j == 0){ res *= (geq_ix == 0 && leq_ix == count); }else if (j == count){ res *= (geq_ix == count && leq_ix == count - 1); }else{ res *= (geq_ix == j && leq_ix == j - 1); } } } printf("\t\t\tcorrectness: "); print_test_result(res); free(elts); free(nrand_elts); elts = NULL; nrand_elts = NULL; } void run_geq_leq_bsearch_double_test(int pow_trials, int pow_count_start, int pow_count_end){ int res = 1; int i; size_t j, count; size_t k, trials; size_t elt_size = sizeof(double); size_t geq_ix, leq_ix; double key; double *elts = NULL, *nrand_elts = NULL; double tot_geq, tot_leq, tot; clock_t t_geq, t_leq, t; trials = pow_two(pow_trials); elts = malloc_perror(pow_two(pow_count_end), elt_size); nrand_elts = malloc_perror(C_NRAND_COUNT_MAX, elt_size); printf("Test geq_bsearch and leq_bsearch on random double arrays\n"); for (i = pow_count_start; i <= pow_count_end; i++){ count = pow_two(i); for (j = 0; j < count; j++){ elts[j] = (DRAND() < C_HALF_PROB ? -1 : 1) * DRAND(); } qsort(elts, count, elt_size, cmp_double); tot_geq = 0.0; tot_leq = 0.0; tot = 0.0; for(k = 0; k < trials; k++){ key = (DRAND() < C_HALF_PROB ? -1 : 1) * DRAND(); t_geq = clock(); geq_ix = geq_bsearch(&key, elts, count, elt_size, cmp_double); t_geq = clock() - t_geq; tot_geq += (double)t_geq / CLOCKS_PER_SEC; t_leq = clock(); leq_ix = leq_bsearch(&key, elts, count, elt_size, cmp_double); t_leq = clock() - t_leq; tot_leq += (double)t_leq / CLOCKS_PER_SEC; t = clock(); bsearch(&key, elts, count, elt_size, cmp_double); t = clock() - t; tot += (double)t / CLOCKS_PER_SEC; res *= is_geq_leq_correct(&key, elts, count, elt_size, geq_ix, leq_ix, cmp_double); } printf("\tarray count: %lu, # trials: %lu\n", TOLU(count), TOLU(trials)); printf("\t\t\tgeq_bsearch: %.6f seconds\n", tot_geq); printf("\t\t\tleq_bsearch: %.6f seconds\n", tot_geq); printf("\t\t\tbsearch: %.6f seconds\n", tot); printf("\t\t\tcorrectness: "); print_test_result(res); } printf("\tnon-random array and corner cases\n"); res = 1; for (j = 0; j < C_NRAND_COUNT_MAX; j++){ if (j == 0){ nrand_elts[j] = 1; }else{ nrand_elts[j] = nrand_elts[j - 1] + 2; } } for (count = 1; count <= C_NRAND_COUNT_MAX; count++){ for (j = 0; j <= count; j++){ key = 2 * j; geq_ix = geq_bsearch(&key, nrand_elts, count, elt_size, cmp_double); leq_ix = leq_bsearch(&key, nrand_elts, count, elt_size, cmp_double); if (j == 0){ res *= (geq_ix == 0 && leq_ix == count); }else if (j == count){ res *= (geq_ix == count && leq_ix == count - 1); }else{ res *= (geq_ix == j && leq_ix == j - 1); } } } printf("\t\t\tcorrectness: "); print_test_result(res); free(elts); free(nrand_elts); elts = NULL; nrand_elts = NULL; } int is_geq_leq_correct(const void *key, const void *elts, size_t count, size_t elt_size, size_t geq_ix, size_t leq_ix, int (*cmp)(const void *, const void *)){ int res = 1; if (geq_ix == count){ res *= (cmp(key, elt_ptr(elts, count - 1, elt_size)) > 0); }else if (geq_ix == 0){ res *= (cmp(key, elt_ptr(elts, geq_ix, elt_size)) <= 0); }else{ res *= (cmp(key, elt_ptr(elts, geq_ix, elt_size)) <= 0); res *= (cmp(key, elt_ptr(elts, geq_ix - 1, elt_size)) >= 0); } if (leq_ix == count){ res *= (cmp(key, elt_ptr(elts, 0, elt_size)) < 0); }else if (leq_ix == count - 1){ res *= (cmp(key, elt_ptr(elts, leq_ix, elt_size)) >= 0); }else{ res *= (cmp(key, elt_ptr(elts, leq_ix, elt_size)) >= 0); res *= (cmp(key, elt_ptr(elts, leq_ix + 1, elt_size)) <= 0); } return res; } /** Computes a pointer to the ith element in an array pointed to by elts. */ void *elt_ptr(const void *elts, size_t i, size_t elt_size){ return (void *)((char *)elts + i * elt_size); } /** Prints test result. */ void print_test_result(int result){ if (result){ printf("SUCCESS\n"); }else{ printf("FAILURE\n"); } } int main(int argc, char *argv[]){ int i; size_t *args = NULL; RGENS_SEED(); if (argc > C_ARGC_MAX){ printf("USAGE:\n%s", C_USAGE); exit(EXIT_FAILURE); } args = malloc_perror(C_ARGC_MAX - 1, sizeof(size_t)); memcpy(args, C_ARGS_DEF, (C_ARGC_MAX - 1) * sizeof(size_t)); for (i = 1; i < argc; i++){ args[i - 1] = atoi(argv[i]); } if (args[0] > C_FULL_BIT - 1 || args[1] > C_FULL_BIT - 1 || args[2] > C_FULL_BIT - 1 || args[1] > args[2] || args[3] > 1 || args[4] > 1){ printf("USAGE:\n%s", C_USAGE); exit(EXIT_FAILURE); } if (args[3]) run_geq_leq_bsearch_int_test(args[0], args[1], args[2]); if (args[4]) run_geq_leq_bsearch_double_test(args[0], args[1], args[2]); free(args); args = NULL; return 0; }
alfin3/graph-algorithms
utilities-pthread/utilities-pthread/utilities-pthread.c
<gh_stars>0 /** utilities-pthread.c Utility functions for concurrency, including 1) pthread functions with wrapped error checking, and 2) an implementation of semaphore operations based on 1), adopted from The Little Book of Semaphores by <NAME> (Version 2.2.1) with modifications. */ #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <pthread.h> #include "utilities-pthread.h" /** Create a thread with default attributes and error checking. Join a thread with error checking. */ void thread_create_perror(pthread_t *thread, void *(*start_routine)(void *), void *arg){ int err = pthread_create(thread, NULL , start_routine, arg); if (err != 0){ perror("pthread_create failed"); exit(EXIT_FAILURE); } } void thread_join_perror(pthread_t thread, void **retval){ int err = pthread_join(thread, retval); if (err != 0){ perror("pthread_join failed"); exit(EXIT_FAILURE); } } /** Initialize with default attributes, lock, and unlock a mutex with error checking. */ void mutex_init_perror(pthread_mutex_t *mutex){ int err = pthread_mutex_init(mutex, NULL); if (err != 0){ perror("pthread_mutex_init failed"); exit(EXIT_FAILURE); } } void mutex_lock_perror(pthread_mutex_t *mutex){ int err = pthread_mutex_lock(mutex); if (err != 0){ perror("pthread_mutex_lock failed"); exit(EXIT_FAILURE); } } void mutex_unlock_perror(pthread_mutex_t *mutex){ int err = pthread_mutex_unlock(mutex); if (err != 0){ perror("pthread_mutex_unlock failed"); exit(EXIT_FAILURE); } } /** Initialize a condition variable with default attributes and error checking. Wait on and signal a condition with error checking. */ void cond_init_perror(pthread_cond_t *cond){ int err = pthread_cond_init(cond, NULL); if (err != 0){ perror("pthread_cond_init failed"); exit(EXIT_FAILURE); } } void cond_wait_perror(pthread_cond_t *cond, pthread_mutex_t *mutex){ int err = pthread_cond_wait(cond, mutex); if (err != 0){ perror("pthread_cond_wait failed"); exit(EXIT_FAILURE); } } void cond_signal_perror(pthread_cond_t *cond){ int err = pthread_cond_signal(cond); if (err != 0){ perror("pthread_cond_signal failed"); exit(EXIT_FAILURE); } } void cond_broadcast_perror(pthread_cond_t *cond){ int err = pthread_cond_broadcast(cond); if (err != 0){ perror("pthread_cond_broadcast failed"); exit(EXIT_FAILURE); } } /** Initialize, wait on, and signal a semaphore with error checking provided by mutex and condition variable operations. */ void sema_init_perror(struct sema *sema, int value){ sema->value = value; sema->num_wakeups = 0; mutex_init_perror(&sema->mutex); cond_init_perror(&sema->cond); } void sema_wait_perror(struct sema *sema){ mutex_lock_perror(&sema->mutex); sema->value--; if (sema->value < 0){ do{ /* guaranteed queuing of a thread to avoid thread starvation */ cond_wait_perror(&sema->cond, &sema->mutex); }while (sema->num_wakeups < 1); /* accounting due to spurious wakeups */ sema->num_wakeups--; } mutex_unlock_perror(&sema->mutex); } void sema_signal_perror(struct sema *sema){ mutex_lock_perror(&sema->mutex); sema->value++; if (sema->value <= 0){ sema->num_wakeups++; cond_signal_perror(&sema->cond); } mutex_unlock_perror(&sema->mutex); }
alfin3/graph-algorithms
data-structures/ht-divchn/ht-divchn.c
/** ht-divchn.c A hash table with generic contiguous or non-contiguous keys and generic contiguous or non-contiguous elements. The implementation is based on a division method for hashing into upto the number of slots determined by the largest prime number in the C_PRIME_PARTS array, representable as size_t on a given system, and a chaining method for resolving collisions. Due to chaining, the number of keys and elements that can be inserted is not limited by the hash table implementation. The load factor of a hash table is the expected number of keys in a slot under the simple uniform hashing assumption, and is upper-bounded by the alpha parameters. The alpha parameters do not provide an upper bound after the maximum count of slots in a hash table is reached. A distinction is made between a key and a "key_size block", and an element and an "elt_size block". During an insertion without update*, a contiguous block of size key_size ("key_size block") and a contiguous block of size elt_size ("elt_size block") are copied into a hash table. A key may be within a contiguous or non-contiguous memory block. Given a key, the user decides what is copied into the key_size block of the hash table. If the key is within a contiguous memory block, then it can be entirely copied as a key_size block, or a pointer to it can be copied as a key_size block. If the key is within a non-contiguous memory block, then a pointer to it is copied as a key_size block. The same applies to an element. When a pointer to a key is copied into a hash table as a key_size block, the user can also decide if only the pointer or the entire key is deleted during the delete and free operations. By setting free_key to NULL, only the pointer is deleted. Otherwise, the deletion is performed according to a non-NULL free_key. For example, when an in-memory set of images are used as keys (e.g. with a subset of bits in each image used for hashing) and pointers are copied into a hash table, then setting free_key to NULL will not affect the original set of images throughout the lifetime of the hash table. The same applies to elements and free_elt. The implementation only uses integer and pointer operations. Integer arithmetic is used in load factor operations, thereby eliminating the use of float. Given parameter values within the specified ranges, the implementation provides an error message and an exit is executed if an integer overflow is attempted** or an allocation is not completed due to insufficient resources. The behavior outside the specified parameter ranges is undefined. The implementation does not use stdint.h and is portable under C89/C90 and C99 with the only requirement that the width of size_t is greater or equal to 16, less than 2040, and is even. * if there is an update during an insertion, a key_size block is not copied and an elt_size block is copied ** except intended wrapping around of unsigned integers in modulo operations, which is defined, and overflow detection as a part of computing bounds, which is defined by the implementation. TODO: add division with magic number multiplication. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <limits.h> #include "ht-divchn.h" #include "dll.h" #include "utilities-mem.h" #include "utilities-mod.h" #include "utilities-lim.h" /** An array of primes in the increasing order, approximately doubling in magnitude, that are not too close to the powers of 2 and 10 to avoid hashing regularities due to the structure of data. */ static const size_t C_PRIME_PARTS[6 * 1 + 16 * (2 + 3 + 4)] = {0x0607u, /* 1543 */ 0x0c2fu, /* 3119 */ 0x1843u, /* 6211 */ 0x3037u, /* 12343 */ 0x5dadu, /* 23981 */ 0xbe21u, /* 48673 */ 0x5b0bu, 0x0001u, /* 88843 */ 0xd8d5u, 0x0002u, /* 186581 */ 0xc219u, 0x0005u, /* 377369 */ 0x0077u, 0x000cu, /* 786551 */ 0xa243u, 0x0016u, /* 1483331 */ 0x2029u, 0x0031u, /* 3219497 */ 0xcc21u, 0x005fu, /* 6278177 */ 0x5427u, 0x00bfu, /* 12538919 */ 0x037fu, 0x0180u, /* 25166719 */ 0x42bbu, 0x030fu, /* 51331771 */ 0x1c75u, 0x06b7u, /* 112663669 */ 0x96adu, 0x0c98u, /* 211326637 */ 0x96b7u, 0x1898u, /* 412653239 */ 0xc10fu, 0x2ecfu, /* 785367311 */ 0x425bu, 0x600fu, /* 1611612763 */ 0x0007u, 0xc000u, /* 3221225479 */ 0x016fu, 0x8000u, 0x0001u, /* 6442451311 */ 0x9345u, 0xffc8u, 0x0002u, /* 12881269573 */ 0x5523u, 0xf272u, 0x0005u, /* 25542415651 */ 0x1575u, 0x0a63u, 0x000cu, /* 51713873269 */ 0x22fbu, 0xca07u, 0x001bu, /* 119353582331 */ 0xc513u, 0x4d6bu, 0x0031u, /* 211752305939 */ 0xa6cdu, 0x50f3u, 0x0061u, /* 417969972941 */ 0xa021u, 0x5460u, 0x00beu, /* 817459404833 */ 0xea29u, 0x7882u, 0x0179u, /* 1621224516137 */ 0xeaafu, 0x7c3du, 0x02f5u, /* 3253374675631 */ 0xab5fu, 0x5a69u, 0x05ffu, /* 6594291673951 */ 0x6b1fu, 0x29efu, 0x0c24u, /* 13349461912351 */ 0xc81bu, 0x35a7u, 0x17feu, /* 26380589320219 */ 0x57b7u, 0xccbeu, 0x2ffbu, /* 52758518323127 */ 0xc8fbu, 0x1da8u, 0x6bf3u, /* 118691918825723 */ 0x82c3u, 0x2c9fu, 0xc2ccu, /* 214182177768131 */ 0x3233u, 0x1c54u, 0x7d40u, 0x0001u, /* 419189283369523 */ 0x60adu, 0x46a1u, 0xf55eu, 0x0002u, /* 832735214133421 */ 0x6babu, 0x40c4u, 0xf12au, 0x0005u, /* 1672538661088171 */ 0xb24du, 0x6765u, 0x38b5u, 0x000bu, /* 3158576518771277 */ 0x789fu, 0xfd94u, 0xc6b2u, 0x0017u, /* 6692396525189279 */ 0x0d35u, 0x5443u, 0xff54u, 0x0030u, /* 13791536538127669 */ 0x2465u, 0x74f9u, 0x42d1u, 0x005eu, /* 26532115188884581 */ 0xd017u, 0x90c7u, 0x37b3u, 0x00c6u, /* 55793289756397591 */ 0x5055u, 0x5a82u, 0x64dfu, 0x0193u, /* 113545326073368661 */ 0x6f8fu, 0x423bu, 0x8949u, 0x0304u, /* 217449629757435791 */ 0xd627u, 0x08e0u, 0x0b2fu, 0x05feu, /* 431794910914467367 */ 0xbbc1u, 0x662cu, 0x4d90u, 0x0badu, /* 841413987972987841 */ 0xf7d3u, 0x45a1u, 0x8ccbu, 0x185du, /* 1755714234418853843 */ 0xc647u, 0x3c91u, 0x46b2u, 0x2e9bu, /* 3358355678469146183 */ 0x58a1u, 0xbd96u, 0x2836u, 0x5f8cu, /* 6884922145916737697 */ 0x8969u, 0x4c70u, 0x6dbeu, 0xdad8u}; /* 15769474759331449193 */ static const size_t C_PRIME_PARTS_COUNT = 6u + 16u * (2u + 3u + 4u); static const size_t C_PARTS_PER_PRIME[4] = {1u, 2u, 3u, 4u}; static const size_t C_PARTS_ACC_COUNTS[4] = {6u, 6u + 16u * 2u, 6u + 16u * (2u + 3u), 6u + 16u * (2u + 3u + 4u)}; static const size_t C_BUILD_SHIFT = 16u; static const size_t C_BYTE_BIT = CHAR_BIT; static const size_t C_FULL_BIT = PRECISION_FROM_ULIMIT((size_t)-1); static const size_t C_SIZE_ULIMIT = (size_t)-1; static size_t hash(const struct ht_divchn *ht, const void *key); static size_t mul_alpha_sz_max(size_t n, size_t alpha_n, size_t log_alpha_d); static void ht_grow(struct ht_divchn *ht); static int incr_count(struct ht_divchn *ht); static int is_overflow(size_t start, size_t count); static size_t build_prime(size_t start, size_t count); /** Initializes a hash table. An in-table elt_size block is guaranteed to be accessible only with a pointer to a character, unless additional alignment is performed by calling ht_divchn_align. ht : a pointer to a preallocated block of size sizeof(struct ht_divchn). key_size : non-zero size of a key_size block; must account for internal and trailing padding according to sizeof elt_size : non-zero size of an elt_size block; must account for internal and trailing padding according to sizeof min_num : minimum number of keys that are known to be or expected to be present simultaneously in a hash table; results in a speedup by avoiding unnecessary growth steps of a hash table; 0 if a positive value is not specified and all growth steps are to be completed alpha_n : > 0 numerator of a load factor upper bound log_alpha_d : < size_t width; log base 2 of the denominator of the load factor upper bound; the denominator is a power of two cmp_key : - if NULL then a default memcmp-based comparison of key_size blocks of keys is performed - otherwise comparison function is applied which returns a zero integer value iff the two keys accessed through the first and the second arguments are equal; each argument is a pointer to the key_size block of a key; cmp_key must use the same subset of bits in a key as rdc_key rdc_key : - if NULL then a default conversion of a bit pattern in the key_size block of a key is performed prior to hashing, which may introduce regularities - otherwise rdc_key is applied to a key to reduce the key to a size_t integer value prior to hashing; the argument points to the key_size block of a key; rdc_key must use the same subset of bits in a key as cmp_key free_key : - NULL if only key_size blocks should be deleted throughout the lifetime of the hash table (e.g. because keys were entirely copied as key_size blocks, or because pointers were copied as key_size blocks and only pointers should be deleted) - otherwise takes a pointer to the key_size block of a key as an argument, frees the memory of the key except the key_size block pointed to by the argument free_elt : - NULL if only elt_size blocks should be deleted throughout the lifetime of the hash table (e.g. because elements were entirely copied as elt_size blocks, or because pointers were copied as elt_size blocks and only pointers should be deleted) - otherwise takes a pointer to the elt_size block of an element as an argument, frees the memory of the element except the elt_size block pointed to by the argument */ void ht_divchn_init(struct ht_divchn *ht, size_t key_size, size_t elt_size, size_t min_num, size_t alpha_n, size_t log_alpha_d, int (*cmp_key)(const void *, const void *), size_t (*rdc_key)(const void *), void (*free_key)(void *), void (*free_elt)(void *)){ size_t i; ht->key_size = key_size; ht->elt_size = elt_size; ht->elt_alignment = 1; ht->group_ix = 0; ht->count_ix = 0; ht->count = build_prime(ht->count_ix, C_PARTS_PER_PRIME[ht->group_ix]); ht->alpha_n = alpha_n; ht->log_alpha_d = log_alpha_d; /* 0 <= max_num_elts */ ht->max_num_elts = mul_alpha_sz_max(ht->count, alpha_n, log_alpha_d); while (min_num > ht->max_num_elts && incr_count(ht)); ht->num_elts = 0; ht->ll = malloc_perror(1, sizeof(struct dll)); ht->key_elts = malloc_perror(ht->count, sizeof(struct dll_node *)); for (i = 0; i < ht->count; i++){ dll_init(ht->ll, &ht->key_elts[i], ht->key_size); } ht->cmp_key = cmp_key; ht->rdc_key = rdc_key; ht->free_key = free_key; ht->free_elt = free_elt; } /** Aligns each in-table elt_size block to be accessible with a pointer to a type T other than character through ht_divchn_search (in addition to a character pointer). If alignment requirement of T is unknown, the size of T can be used as a value of the alignment parameter because size of T >= alignment requirement of T (due to structure of arrays), which may result in overalignment. The hash table keeps the effective type of a copied elt_size block, if it had one at the time of insertion, and T must be compatible with the type to comply with the strict aliasing rules. T can be the same or a cvr-qualified/signed/unsigned version of the type. The operation is optionally called after ht_divchn_init is completed and before any other operation is called. ht : pointer to an initialized ht_divchn struct elt_alignment : alignment requirement or size of the type, a pointer to which is used to access the elt_size block of an element in a hash table; if size, must account for internal and trailing padding according to sizeof */ void ht_divchn_align(struct ht_divchn *ht, size_t elt_alignment){ ht->elt_alignment = elt_alignment; dll_align_elt(ht->ll, elt_alignment); } /** Inserts a key and an associated element into a hash table by copying the corresponding key_size and elt_size blocks. If the key pointed to by the key parameter is already in the hash table according to cmp_key, then deletes the previous element according to free_elt and copies the elt_size block pointed to by the elt parameter. ht : pointer to an initialized ht_divchn struct key : non-NULL pointer to the key_size block of a key elt : non-NULL pointer to the elt_size block of an element */ void ht_divchn_insert(struct ht_divchn *ht, const void *key, const void *elt){ size_t ix; struct dll_node **head = NULL, *node = NULL; ix = hash(ht, key); head = &ht->key_elts[ix]; node = dll_search_key(ht->ll, head, key, ht->key_size, ht->cmp_key); if (node == NULL){ dll_prepend_new(ht->ll, head, key, elt, ht->key_size, ht->elt_size); ht->num_elts++; }else{ /* updates the elt_size block */ if (ht->free_elt != NULL) ht->free_elt(dll_elt_ptr(ht->ll, node)); memcpy(dll_elt_ptr(ht->ll, node), elt, ht->elt_size); } /* grow ht after ensuring it was insertion, not update */ if (ht->num_elts > ht->max_num_elts && ht->count_ix != C_SIZE_ULIMIT && ht->count_ix != C_PRIME_PARTS_COUNT){ ht_grow(ht); } } /** If a key is present in a hash table, according to cmp_key, then returns a pointer to the elt_size block of its associated element in the hash table. Otherwise returns NULL. The returned pointer can be dereferenced according to the preceding calls to ht_divchn_init and ht_divchn_align_elt. ht : pointer to an initialized ht_divchn struct key : non-NULL pointer to the key_size block of a key */ void *ht_divchn_search(const struct ht_divchn *ht, const void *key){ const struct dll_node *node = dll_search_key(ht->ll, &ht->key_elts[hash(ht, key)], key, ht->key_size, ht->cmp_key); if (node == NULL){ return NULL; }else{ return dll_elt_ptr(ht->ll, node); } } /** Removes the element associated with a key in a hash table that equals to the key pointed to by the key parameter according to cmp_key, by a) copying the elt_size block of the element to the elt_size block pointed to by the elt parameter and b) deleting the corresponding key_size and elt_size blocks in the hash table. If there is no matching key in the hash table according to cmp_key, leaves the hash table and the block pointed to by elt unchanged. ht : pointer to an initialized ht_divchn struct key : non-NULL pointer to the key_size block of a key elt : non-NULL pointer to a preallocated elt_size block */ void ht_divchn_remove(struct ht_divchn *ht, const void *key, void *elt){ struct dll_node **head = &ht->key_elts[hash(ht, key)]; struct dll_node *node = dll_search_key(ht->ll, head, key, ht->key_size, ht->cmp_key); if (node != NULL){ memcpy(elt, dll_elt_ptr(ht->ll, node), ht->elt_size); /* NULL: only the key_size and elt_size blocks are deleted in ht */ dll_delete(ht->ll, head, node, NULL, NULL); ht->num_elts--; } } /** If there is a key in a hash table that equals to the key pointed to by the key parameter according to cmp_key, then deletes the in-table key element pair according to free_key and free_elt. ht : pointer to an initialized ht_divchn struct key : non-NULL pointer to the key_size block of a key */ void ht_divchn_delete(struct ht_divchn *ht, const void *key){ struct dll_node **head = &ht->key_elts[hash(ht, key)]; struct dll_node *node = dll_search_key(ht->ll, head, key, ht->key_size, ht->cmp_key); if (node != NULL){ dll_delete(ht->ll, head, node, ht->free_key, ht->free_elt); ht->num_elts--; } } /** Frees the memory of all keys and elements that are in a hash table according to free_key and free_elt, frees the memory of the hash table, and leaves the block of size sizeof(struct ht_divchn) pointed to by the ht parameter. */ void ht_divchn_free(struct ht_divchn *ht){ size_t i; for (i = 0; i < ht->count; i++){ dll_free(ht->ll, &ht->key_elts[i], ht->free_key, ht->free_elt); } free(ht->ll); free(ht->key_elts); ht->ll = NULL; ht->key_elts = NULL; } /** Help construct a hash table parameter value in algorithms and data structures with a hash table parameter, complying with the stict aliasing rules and compatibility rules for function types. In each case, a (qualified) struct ht_divchn *p0 is converted to (qualified) void * and back to a (qualified) struct ht_divchn *p1, thus guaranteeing that the value of p0 equals the value of p1. */ void ht_divchn_init_helper(void *ht, size_t key_size, size_t elt_size, size_t min_num, size_t alpha_n, size_t log_alpha_d, int (*cmp_key)(const void *, const void *), size_t (*rdc_key)(const void *), void (*free_key)(void *), void (*free_elt)(void *)){ ht_divchn_init(ht, key_size, elt_size, min_num, alpha_n, log_alpha_d, cmp_key, rdc_key, free_key, free_elt); } void ht_divchn_align_helper(void *ht, size_t elt_alignment){ ht_divchn_align(ht, elt_alignment); } void ht_divchn_insert_helper(void *ht, const void *key, const void *elt){ ht_divchn_insert(ht, key, elt); } void *ht_divchn_search_helper(const void *ht, const void *key){ return ht_divchn_search(ht, key); } void ht_divchn_remove_helper(void *ht, const void *key, void *elt){ ht_divchn_remove(ht, key, elt); } void ht_divchn_delete_helper(void *ht, const void *key){ ht_divchn_delete(ht, key); } void ht_divchn_free_helper(void *ht){ ht_divchn_free(ht); } /** Auxiliary functions */ /** Converts a key to a size_t value (standard key). If rdc_key is NULL, applies a safe conversion of any bit pattern in the key_size block of a key to reduce it to size_t. Otherwise, returns the value after applying rdc_key to the key. */ static size_t convert_std_key(const struct ht_divchn *ht, const void *key){ size_t i; size_t sz_count, rem_size; size_t std_key = 0; size_t buf_size = sizeof(size_t); unsigned char buf[sizeof(size_t)]; const void *k = NULL, *k_start = NULL, *k_end = NULL; if (ht->rdc_key != NULL) return ht->rdc_key(key); sz_count = ht->key_size / buf_size; /* division by sizeof(size_t) */ rem_size = ht->key_size - sz_count * buf_size; k = key; memset(buf, 0, buf_size); memcpy(buf, k, rem_size); for (i = 0; i < rem_size; i++){ std_key += (size_t)buf[i] << (i * C_BYTE_BIT); } k_start = (char *)k + rem_size; k_end = (char *)k_start + sz_count * buf_size; for (k = k_start; k != k_end; k = (char *)k + buf_size){ memcpy(buf, k, buf_size); for (i = 0; i < buf_size; i++){ std_key += (size_t)buf[i] << (i * C_BYTE_BIT); } } return std_key; } /** Maps a hash key to a slot index in a hash table with a division method. */ static size_t hash(const struct ht_divchn *ht, const void *key){ return convert_std_key(ht, key) % ht->count; } /** Multiplies an unsigned integer n by a load factor upper bound, represented by a numerator and log base 2 of a denominator. The denominator is a power of two. Returns the product if it is representable as size_t. Otherwise returns the maximal value of size_t. */ static size_t mul_alpha_sz_max(size_t n, size_t alpha_n, size_t log_alpha_d){ size_t h, l; mul_ext(n, alpha_n, &h, &l); if (h >> log_alpha_d) return C_SIZE_ULIMIT; /* overflow after division */ l >>= log_alpha_d; h <<= (C_FULL_BIT - log_alpha_d); return l + h; } /** Increases the count of a hash table to the next prime number in the C_PRIME_PARTS array that accomodates a load factor upper bound. The operation is called if the load factor upper bound was exceeded (i.e. num_elts > max_num_elts) and count_ix is not equal to C_SIZE_ULIMIT or C_PRIME_PARTS_COUNT. A single call: i) lowers the load factor s.t. num_elts <= max_num_elts if a sufficiently large prime in the C_PRIME_PARTS array is available and is representable as size_t, or ii) lowers the load factor as low as possible. If the largest representable prime is reached, count_ix may not yet be set to C_SIZE_ULIMIT or C_PRIME_PARTS_COUNT, which requires one additional call. Otherwise, each call increases the count. */ static void ht_grow(struct ht_divchn *ht){ size_t i, prev_count = ht->count; struct dll_node **prev_key_elts = ht->key_elts; struct dll_node **head = NULL, *node = NULL; while (ht->num_elts > ht->max_num_elts && incr_count(ht)); if (prev_count == ht->count) return; /* load factor not lowered */ ht->key_elts = malloc_perror(ht->count, sizeof(struct dll_node *)); for (i = 0; i < ht->count; i++){ dll_init(ht->ll, &ht->key_elts[i], ht->key_size); } if (ht->elt_alignment > 1) dll_align_elt(ht->ll, ht->elt_alignment); for (i = 0; i < prev_count; i++){ head = &prev_key_elts[i]; while (*head != NULL){ node = *head; dll_remove(head, node); dll_prepend(&ht->key_elts[hash(ht, dll_key_ptr(ht->ll, node))], node); } } free(prev_key_elts); prev_key_elts = NULL; } /** Attempts to increase the count of a hash table. Returns 1 if the count was increased. Otherwise returns 0. Updates count_ix, group_ix, count, and max_num_elts accordingly. If the largest representable prime was reached, count_ix may not yet be set to C_SIZE_ULIMIT or C_PRIME_PARTS_COUNT, which requires one additional call. Otherwise, each call increases the count. */ static int incr_count(struct ht_divchn *ht){ ht->count_ix += C_PARTS_PER_PRIME[ht->group_ix]; if (ht->count_ix == C_PARTS_ACC_COUNTS[ht->group_ix]) ht->group_ix++; if (ht->count_ix == C_PRIME_PARTS_COUNT){ return 0; }else if (is_overflow(ht->count_ix, C_PARTS_PER_PRIME[ht->group_ix])){ ht->count_ix = C_SIZE_ULIMIT; return 0; }else{ ht->count = build_prime(ht->count_ix, C_PARTS_PER_PRIME[ht->group_ix]); /* 0 <= max_num_elts <= C_SIZE_ULIMIT */ ht->max_num_elts = mul_alpha_sz_max(ht->count, ht->alpha_n, ht->log_alpha_d); } return 1; } /** Tests if the next prime number results in the overflow of size_t on a given system. Returns 0 if no overflow, otherwise returns 1. */ static int is_overflow(size_t start, size_t count){ size_t c = 0; size_t n_shift; n_shift = C_PRIME_PARTS[start + (count - 1)]; while (n_shift){ n_shift >>= 1; c++; } return (c + (count - 1) * C_BUILD_SHIFT > C_FULL_BIT); } /** Builds a prime number from parts in the C_PRIME_PARTS array. */ static size_t build_prime(size_t start, size_t count){ size_t p = 0; size_t n_shift; size_t i; for (i = 0; i < count; i++){ n_shift = C_PRIME_PARTS[start + i]; n_shift <<= (i * C_BUILD_SHIFT); p |= n_shift; } return p; }
alfin3/graph-algorithms
graph-algorithms/dfs/dfs.c
<reponame>alfin3/graph-algorithms /** dfs.c Functions for running the DFS algorithm on graphs with generic integer vertices indexed from 0. A graph may be unweighted or weighted. In the latter case the weights of the graph are ignored. The recursion in DFS is emulated on a dynamically allocated stack data structure to avoid an overflow of the memory stack. An option to optimally align the elements in the stack is provided and may increase the cache efficiency and reduce the space requirement*, depending on the system and the choice of the integer type for representing vertices. The effective type of every element in the previsit and postvisit arrays is of the integer type used to represent vertices. The value of every element is set by the algorithm. If the block pointed to by pre or post has no declared type then the algorithm sets the effective type of every element to the integer type used to represent vertices by writing a value of the type. The implementation only uses integer and pointer operations. Given parameter values within the specified ranges, the implementation provides an error message and an exit is executed if an integer overflow is attempted or an allocation is not completed due to insufficient resources. The behavior outside the specified parameter ranges is undefined. The implementation does not use stdint.h and is portable under C89/C90 and C99. * A bit array for cache-efficient set membership testing is not included due to an overhead that decreased the performance in tests. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "dfs.h" #include "graph.h" #include "stack.h" #include "utilities-mem.h" static const size_t C_STACK_INIT_COUNT = 1; static void dfs_helper(const struct adj_lst *a, size_t start, size_t vt_alignment, size_t vdptr_alignment, void *pre, void *post, size_t (*read_vt)(const void *), void (*write_vt)(void *, size_t), void *(*at_vt)(const void *, const void *), int (*cmp_vt)(const void *, const void *), void (*incr_vt)(void *)); static void search(const struct adj_lst *a, struct stack *s, size_t offset, void *c, const void *nr, const void *ix, void *pre, void *post, size_t (*read_vt)(const void *), void *(*at_vt)(const void *, const void *), int (*cmp_vt)(const void *, const void *), void (*incr_vt)(void *)); static void *ptr(const void *block, size_t i, size_t size); /** Computes and copies to the arrays pointed to by pre and post the previsit and postvisit values of a DFS search from a start vertex. Assumes start is valid and there is at least one vertex. a : pointer to an adjacency list with at least one and at most 2**(P - 1) - 1 vertices, where P is the precision of the integer type used to represent vertices start : a start vertex for running dfs pre : pointer to a preallocated array with the count equal to the number of vertices in the adjacency list; each element is of size vt_size (vt_size block) that equals to the size of the integer type used to represent vertices in the adjacency list; if the block pointed to by pre has no declared type then it is guaranteed that dfs sets the effective type of every element to the integer type used to represent vertices by writing a value of the type post : pointer to a preallocated array with the count equal to the number of vertices in the adjacency list; each element is of size vt_size (vt_size block) that equals to the size of the integer type used to represent vertices in the adjacency list; if the block pointed to by post has no declared type then it is guaranteed that dfs sets the effective type of every element to the integer type used to represent vertices by writing a value of the type read_vt : reads the integer value of the type used to represent vertices from the vt_size block pointed to by the argument and returns a size_t value write_vt : writes the integer value of the second argument to the vt_size block pointed to by the first argument as a value of the integer type used to represent vertices at_vt : returns a pointer to the element in the array pointed to by the first argument at the index pointed to by the second argument; the first argument points to the integer type used to represent vertices and is not dereferenced; the second argument points to a value of the integer type used to represent vertices and is dereferenced cmp_vt : returns 0 iff the element pointed to by the first argument is equal to the element pointed to by the second argument; each argument points to a value of the integer type used to represent vertices incr_vt : increments a value of the integer type used to represent vertices */ void dfs(const struct adj_lst *a, size_t start, void *pre, void *post, size_t (*read_vt)(const void *), void (*write_vt)(void *, size_t), void *(*at_vt)(const void *, const void *), int (*cmp_vt)(const void *, const void *), void (*incr_vt)(void *)){ dfs_helper(a, start, a->vt_size, sizeof(void *), pre, post, read_vt, write_vt, at_vt, cmp_vt, incr_vt); } /** Computes and copies to the arrays pointed to by pre and post the previsit and postvisit values of a DFS search from a start vertex. Assumes start is valid and there is at least one vertex. Sets the alignment of void * vertex value pairs in the dynamically allocated stack used to emulate the dfs recursion. If the alignment requirement of only one type is known, then the size of the other type can be used as a value of the other alignment parameter because size of type >= alignment requirement of type (due to structure of arrays). The call to this operation may result in an increase in cache efficiency and a reduction of the space requirements as compared to dfs. Also see the parameter specification in dfs. vt_alignment : alignment requirement or size of the integer type used to represent vertices; the size is equal to vt_size, which accounts for padding according to sizeof vdp_alignment: alignment requirement of void * (i.e. alignof(void *)) or size of void * according to sizeof */ void dfs_align(const struct adj_lst *a, size_t start, size_t vt_alignment, size_t vdp_alignment, void *pre, void *post, size_t (*read_vt)(const void *), void (*write_vt)(void *, size_t), void *(*at_vt)(const void *, const void *), int (*cmp_vt)(const void *, const void *), void (*incr_vt)(void *)){ dfs_helper(a, start, vt_alignment, vdp_alignment, pre, post, read_vt, write_vt, at_vt, cmp_vt, incr_vt); } static void dfs_helper(const struct adj_lst *a, size_t start, size_t vt_alignment, size_t vdp_alignment, void *pre, void *post, size_t (*read_vt)(const void *), void (*write_vt)(void *, size_t), void *(*at_vt)(const void *, const void *), int (*cmp_vt)(const void *, const void *), void (*incr_vt)(void *)){ size_t vt_rem, vdp_rem; size_t vt_offset, pair_size; struct stack s; /* variables in single block for cache-efficiency */ void * const vars = malloc_perror(6, a->vt_size); void * const su = vars; void * const c = ptr(vars, 1, a->vt_size); void * const nr = ptr(vars, 2, a->vt_size); void * const zero = ptr(vars, 3, a->vt_size); void * const ix = ptr(vars, 4, a->vt_size); void * const end = ptr(vars, 5, a->vt_size); write_vt(su, start); write_vt(c, 0); write_vt(nr, mul_sz_perror(2, a->num_vts)); write_vt(zero, 0); write_vt(ix, 0); write_vt(end, a->num_vts); while (cmp_vt(ix, end) != 0){ memcpy(at_vt(pre, ix), nr, a->vt_size); incr_vt(ix); } /* align v_uval block relative to a malloc's pointer in stack */ if (sizeof(void *) <= vt_alignment){ vt_offset = vt_alignment; }else{ vt_rem = sizeof(void *) % vt_alignment; vt_offset = add_sz_perror(sizeof(void *), (vt_rem > 0) * (vt_alignment - vt_rem)); } vdp_rem = add_sz_perror(vt_offset, a->vt_size) % vdp_alignment; pair_size = add_sz_perror(vt_offset + a->vt_size, (vdp_rem > 0) * (vdp_alignment - vdp_rem)); /* run search with recursion emulation on a stack ds */ stack_init(&s, pair_size, NULL); stack_bound(&s, C_STACK_INIT_COUNT, a->num_vts); memcpy(ix, su, a->vt_size); while (cmp_vt(ix, end) != 0){ if (cmp_vt(at_vt(pre, ix), nr) == 0){ search(a, &s, vt_offset, c, nr, ix, pre, post, read_vt, at_vt, cmp_vt, incr_vt); } incr_vt(ix); } memcpy(end, su, a->vt_size); memcpy(ix, zero, a->vt_size); while (cmp_vt(ix, end) != 0){ if (cmp_vt(at_vt(pre, ix), nr) == 0){ search(a, &s, vt_offset, c, nr, ix, pre, post, read_vt, at_vt, cmp_vt, incr_vt); } incr_vt(ix); } stack_free(&s); free(vars); /* after this line vars cannot be dereferenced */ } /** Performs a DFS search of a graph component reachable from an unexplored vertex pointed to by the ix parameter by emulating the recursion in DFS on a dynamically allocated stack data structure. */ static void search(const struct adj_lst *a, struct stack *s, size_t vt_offset, void *c, const void *nr, const void *ix, void *pre, void *post, size_t (*read_vt)(const void *), void *(*at_vt)(const void *, const void *), int (*cmp_vt)(const void *, const void *), void (*incr_vt)(void *)){ const void *v = NULL, *v_end = NULL; void * const v_uval = malloc_perror(1, s->elt_size); const void ** const vp = v_uval; void * const u = ptr(v_uval, 1, vt_offset); memcpy(u, ix, a->vt_size); *vp = a->vt_wts[read_vt(u)]->elts; memcpy(at_vt(pre, u), c, a->vt_size); incr_vt(c); stack_push(s, v_uval); while (s->num_elts > 0){ stack_pop(s, v_uval); v = *vp; /* for performance */ v_end = ptr(a->vt_wts[read_vt(u)]->elts, a->vt_wts[read_vt(u)]->num_elts, a->pair_size); /* iterate v across the u's stack */ while (v != v_end && cmp_vt(at_vt(pre, v), nr) != 0){ v = (char *)v + a->pair_size; } if (v == v_end){ memcpy(at_vt(post, u), c, a->vt_size); incr_vt(c); }else{ *vp = v; stack_push(s, v_uval); /* push the unfinished vertex */ memcpy(u, *vp, a->vt_size); *vp = a->vt_wts[read_vt(u)]->elts; memcpy(at_vt(pre, u), c, a->vt_size); incr_vt(c); stack_push(s, v_uval); /* then push an unexplored vertex */ } } free(v_uval); /* after this line v_uval cannot be dereferenced */ } /** Computes a pointer to the ith element in the block of elements. According to C89 (draft): "It is guaranteed, however, that a pointer to an object of a given alignment may be converted to a pointer to an object of the same alignment or a less strict alignment and back again; the result shall compare equal to the original pointer. (An object that has character type has the least strict alignment.)" "A pointer to void may be converted to or from a pointer to any incomplete or object type. A pointer to any incomplete or object type may be converted to a pointer to void and back again; the result shall compare equal to the original pointer." "A pointer to void shall have the same representation and alignment requirements as a pointer to a character type." */ static void *ptr(const void *block, size_t i, size_t size){ return (void *)((char *)block + i * size); }
alfin3/graph-algorithms
data-structures/dll/dll.h
<filename>data-structures/dll/dll.h /** dll.h Struct declarations and declarations of accessible functions of a doubly linked list with cache-efficient allocation of nodes with two type- generic data blocks. The list is in a circular representation. Given the circular representation of the list, the head pointer in the provided list operations is not limited to a fixed position in the list. The head pointer determines the "beginning" and "end" of a list each time with respect to a call to an operation and can be used as a positional pointer for searching and modifying the list from and at any position, including a fixed position if desired. A list node contains i) a malloc-aligned generic block of size key_size (referred to as "key_size block"), ii) a dll_node struct for pointer operations, and iii) an optionally aligned generic block of size elt_size (referred to as "elt_size block"), all within a single allocated block for cache-efficiency and to reduce administrative bytes. A distinction is made between a key and a key_size block, and an element and an elt_size block. Given a key, which may be within a contiguous or a non-contiguous block of memory, the user decides what is copied into the key_size block of a new node. If the key is within a contiguous memory block, then it can be entirely copied as a key_size block, or a pointer to it can be copied as a key_size block. If the key is within a non- contiguous memory block, then a pointer to it is copied as a key_size block. The same applies to an element. When a pointer to a key is copied into a node as a key_size block, the user can also decide if only the pointer or the entire key is deleted during the delete and free operations. By using NULL as free_key, only the pointer is deleted. Otherwise, the deletion is performed according to a non-NULL free_key. For example, when an in-memory set of images are used as keys and pointers are copied into the nodes of a list, then using NULL as free_key will not affect the original set of images. The same applies to elements and free_elt. The implementation provides a guarantee that a key_size block, a dll_node struct, and an elt_size block belonging to the same node keep their addresses in memory throughout the lifetime of the node in a list. The implementation may not be slower (as tested) than a singly linked list due to instruction-level parallelism. The implementation only uses integer and pointer operations. Given parameter values within the specified ranges, the implementation provides an error message and an exit is executed if an integer overflow is attempted or an allocation is not completed due to insufficient resources. The behavior outside the specified parameter ranges is undefined. The node implementation facilitates type-generic hashing applications, such as mapping a key to a node pointer for fast in-list access and using a list for chaining hash keys and their elements in a hash table. In combination with the circular representation, the implementation also facilitates the parallelization of search. The implementation does not use stdint.h, and is portable under C89/C90 and C99. */ #ifndef DLL_H #define DLL_H struct dll{ size_t key_offset; /* subtracted */ size_t elt_offset; /* added */ }; /* given char *p pointer to a dll_node, p - key_offset points to key_size block and p + elt_offset points to elt_size block; see dll_key_ptr and dll_elt_ptr functions */ struct dll_node{ struct dll_node *next; struct dll_node *prev; }; /** Initializes an empty doubly linked list by setting a head pointer to NULL and key_offset and elt_offset in a dll struct to values according to the memory alignment requirements for the key_size and elt_size blocks of a node. An in-list key_size block can be accessed with a pointer to any type with which a malloc'ed block can be accessed. An in-list elt_size block is guaranteed to be accessible only with a pointer to a character (e.g. for memcpy), unless additional alignment is performed by calling dll_align_elt. ll : pointer to a preallocated block of size of a dll struct head : pointer to a preallocated block of size of a dll_node pointer (head pointer) key_size : non-zero size of a key_size block; must account for internal and trailing padding according to sizeof */ void dll_init(struct dll *ll, struct dll_node **head, size_t key_size); /** Aligns each in-list elt_size block to be accessible with a pointer to a type T other than character (in addition to a character pointer). If alignment requirement of T is unknown, the size of T can be used as a value of the alignment parameter because size of T >= alignment requirement of T (due to structure of arrays), which may result in overalignment. The list keeps the effective type of a copied elt_size block, if it had one at the time of insertion, and T must be compatible with the type to comply with the strict aliasing rules. T can be the same or a cvr-qualified/signed/unsigned version of the type. The operation is optionally called after dll_init is completed and before any other operation is called. ll : pointer to an initialized dll struct alignment : alignment requirement or size of the type, a pointer to which is used to access the elt_size block of a node; if size, must account for internal and trailing padding according to sizeof */ void dll_align_elt(struct dll *ll, size_t alignment); /** Creates and prepends a node relative to a head pointer. A head pointer is NULL if the list is empty, or points to any node in the list to determine the position for the prepend operation. ll : pointer to an initialized dll struct head : pointer to a head pointer to an initialized list key : non-NULL pointer to the key_size block of a key elt : non-NULL pointer to the elt_size block of an element key_size : non-zero size of a key_size block; must account for internal and trailing padding according to sizeof elt_size : non-zero size of an elt_size block; must account for internal and trailing padding according to sizeof */ void dll_prepend_new(const struct dll *ll, struct dll_node **head, const void *key, const void *elt, size_t key_size, size_t elt_size); /** Creates and appends a node relative to a head pointer. Please see the parameter specification in dll_prepend_new. */ void dll_append_new(const struct dll *ll, struct dll_node **head, const void *key, const void *elt, size_t key_size, size_t elt_size); /** Prepends a node relative to a head pointer. A head pointer is NULL if the list is empty, or points to any node in the list to determine the position for the prepend operation. head : pointer to a head pointer to an initialized list node : non-NULL pointer to a node to be prepended */ void dll_prepend(struct dll_node **head, struct dll_node *node); /** Appends a node relative to a head pointer. Please see the parameter specification in dll_prepend. */ void dll_append(struct dll_node **head, struct dll_node *node); /** Returns a pointer to the key_size block of a node. */ void *dll_key_ptr(const struct dll *ll, const struct dll_node *node); /** Returns a pointer to the elt_size block of a node. */ void *dll_elt_ptr(const struct dll *ll, const struct dll_node *node); /** Relative to a head pointer, returns a pointer to the clockwise (next) first node with a key that equals the key pointed to by the key parameter according to cmp_key, or NULL if such a node in not found. Temporarily modifies a node in the list to mark the end of the list during search. ll : pointer to an initialized dll struct head : pointer to a head pointer to an initialized list key : non-NULL pointer to the key_size block of a key key_size : non-zero size of a key_size block; must account for internal and trailing padding according to sizeof cmp_key : - if NULL then a default memcmp-based comparison of key_size blocks is performed - otherwise comparison function is applied which returns a zero integer value iff the two keys accessed through the first and the second arguments are equal; each argument is a pointer to the key_size block of a key */ struct dll_node *dll_search_key(const struct dll *ll, struct dll_node * const *head, const void *key, size_t key_size, int (*cmp_key)(const void *, const void *)); /** Relative to a head pointer, returns a pointer to the clockwise (next) first node with a key that equals the key pointed to by the key parameter according to cmp_key, or NULL if such a node in not found. Assumes that every key in a list is unique according to cmp_key. The list is not modified during the operation which enables parallel queries without thread synchronization overhead. Please see the parameter specification in dll_search_key. */ struct dll_node *dll_search_uq_key(const struct dll *ll, struct dll_node * const *head, const void *key, size_t key_size, int (*cmp_key)(const void *, const void *)); /** Removes a node in a doubly linked list. head : pointer to a head pointer to an initialized list node : pointer to a node in an initialized list; if the pointer points to the node pointed to by the head pointer, then the head pointer is set to point to the next node from the removed node, or to NULL if the last node is removed */ void dll_remove(struct dll_node **head, const struct dll_node *node); /** Deletes a node in a doubly linked list. ll : pointer to an initialized dll struct head : pointer to a head pointer to an initialized list node : pointer to a node in an initialized list; if the pointer points to the node pointed to by the head pointer, then the head pointer is set to point to the next node from the deleted node, or to NULL if the last node is deleted free_key : - NULL if only a key_size block should be deleted (e.g. because a key was entirely copied as a key_size block, or because a pointer was copied as a key_size block and only the pointer should be deleted) - otherwise takes a pointer to the key_size block of a key as an argument, frees the memory of the key except the key_size block pointed to by the argument free_elt : - NULL if only an elt_size block should be deleted (e.g. because an element was entirely copied as an elt_size block, or because a pointer was copied as an elt_size block and only the pointer should be deleted) - otherwise takes a pointer to the elt_size block of an element as an argument, frees the memory of the element except the elt_size block pointed to by the argument */ void dll_delete(const struct dll *ll, struct dll_node **head, struct dll_node *node, void (*free_key)(void *), void (*free_elt)(void *)); /** Frees the memory of all keys and elements that are in a list according to free_key and free_elt, frees the memory of the list, and leaves the block of size sizeof(struct dll) pointed to by the ll parameter. Please see the parameter specification in dll_delete. */ void dll_free(const struct dll *ll, struct dll_node **head, void (*free_key)(void *), void (*free_elt)(void *)); #endif
alfin3/graph-algorithms
graph-algorithms/bfs/bfs-test.c
<gh_stars>0 /** bfs-test.c Tests of the BFS algorithm across graphs with different integer types of vertices within the same translation unit. The following command line arguments can be used to customize tests: bfs-test [0, ushort width - 1] : a [0, ushort width - 1] : b s.t. 2**a <= V <= 2**b for max edges test [0, ushort width - 1] : c [0, ushort width - 1] : d s.t. 2**c <= V <= 2**d for no edges test [0, ushort width - 1] : e [0, ushort width - 1] : f s.t. 2**e <= V <= 2**f for rand graph test [0, 1] : on/off for small graph tests [0, 1] : on/off for max edges test [0, 1] : on/off for no edges test [0, 1] : on/off for rand graph test usage examples: ./bfs-test ./bfs-test 10 14 10 14 10 14 ./bfs-test 10 14 10 14 10 14 0 1 1 1 bfs-test can be run with any subset of command line arguments in the above-defined order. If the (i + 1)th argument is specified then the ith argument must be specified for i >= 0. Default values are used for the unspecified arguments according to the C_ARGS_DEF array. The implementation of tests does not use stdint.h and is portable under C89/C90 and C99. The tests require that: - size_t and clock_t are convertible to double, - size_t can represent values upto 65535 for default values, and upto USHRT_MAX (>= 65535) otherwise, - the widths of the unsigned integral types are less than 2040 and even. TODO: add portable size_t printing */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <limits.h> #include <time.h> #include "bfs.h" #include "graph.h" #include "stack.h" #include "utilities-mem.h" #include "utilities-mod.h" #include "utilities-lim.h" /** Generate random numbers in a portable way for test purposes only; rand() in the Linux C Library uses the same generator as random(), which may not be the case on older rand() implementations, and on current implementations on different systems. */ #define RGENS_SEED() do{srand(time(NULL));}while (0) #define RANDOM() (rand()) /* [0, RAND_MAX] */ #define DRAND() ((double)rand() / RAND_MAX) /* [0.0, 1.0] */ #define TOLU(i) ((unsigned long int)(i)) /* printing size_t under C89/C90 */ /* input handling */ const char *C_USAGE = "bfs-test\n" "[0, ushort width - 1] : a\n" "[0, ushort width - 1] : b s.t. 2**a <= V <= 2**b for max edges test\n" "[0, ushort width - 1] : c\n" "[0, ushort width - 1] : d s.t. 2**c <= V <= 2**d for no edges test\n" "[0, ushort width - 1] : e\n" "[0, ushort width - 1] : f s.t. 2**e <= V <= 2**f for rand graph test\n" "[0, 1] : on/off for small graph tests\n" "[0, 1] : on/off for max edges test\n" "[0, 1] : on/off for no edges test\n" "[0, 1] : on/off for rand graph test\n"; const int C_ARGC_ULIMIT = 11; const size_t C_ARGS_DEF[10] = {0u, 6u, 0u, 6u, 0u, 14u, 1u, 1u, 1u, 1u}; const size_t C_USHORT_BIT = PRECISION_FROM_ULIMIT((unsigned short)-1); /* first small graph test */ const size_t C_NUM_VTS_A = 5u; const size_t C_NUM_ES_A = 4u; const unsigned short C_USHORT_U_A[4] = {0u, 0u, 0u, 1u}; const unsigned short C_USHORT_V_A[4] = {1u, 2u, 3u, 3u}; const unsigned short C_USHORT_WTS_A[4] = {(unsigned short)-1, 1u, (unsigned short)-1, 2u}; const unsigned short C_USHORT_DIR_DIST_A[25] = {0u, 1u, 1u, 1u, 0u, 0u, 0u, 0u, 1u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u}; const unsigned short C_USHORT_DIR_PREV_A[25] = {0u, 0u, 0u, 0u, 5u, 5u, 1u, 5u, 1u, 5u, 5u, 5u, 2u, 5u, 5u, 5u, 5u, 5u, 3u, 5u, 5u, 5u, 5u, 5u, 4u}; const unsigned short C_USHORT_UNDIR_DIST_A[25] = {0u, 1u, 1u, 1u, 0u, 1u, 0u, 2u, 1u, 0u, 1u, 2u, 0u, 2u, 0u, 1u, 1u, 2u, 0u, 0u, 0u, 0u, 0u, 0u, 0u}; const unsigned short C_USHORT_UNDIR_PREV_A[25] = {0u, 0u, 0u, 0u, 5u, 1u, 1u, 0u, 1u, 5u, 2u, 0u, 2u, 0u, 5u, 3u, 3u, 0u, 3u, 5u, 5u, 5u, 5u, 5u, 4u}; const unsigned long C_ULONG_U_A[4] = {0u, 0u, 0u, 1u}; const unsigned long C_ULONG_V_A[4] = {1u, 2u, 3u, 3u}; const unsigned long C_ULONG_WTS_A[4] = {(unsigned long)-1, 1u, (unsigned long)-1, 2u}; const unsigned long C_ULONG_DIR_DIST_A[25] = {0u, 1u, 1u, 1u, 0u, 0u, 0u, 0u, 1u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u}; const unsigned long C_ULONG_DIR_PREV_A[25] = {0u, 0u, 0u, 0u, 5u, 5u, 1u, 5u, 1u, 5u, 5u, 5u, 2u, 5u, 5u, 5u, 5u, 5u, 3u, 5u, 5u, 5u, 5u, 5u, 4u}; const unsigned long C_ULONG_UNDIR_DIST_A[25] = {0u, 1u, 1u, 1u, 0u, 1u, 0u, 2u, 1u, 0u, 1u, 2u, 0u, 2u, 0u, 1u, 1u, 2u, 0u, 0u, 0u, 0u, 0u, 0u, 0u}; const unsigned long C_ULONG_UNDIR_PREV_A[25] = {0u, 0u, 0u, 0u, 5u, 1u, 1u, 0u, 1u, 5u, 2u, 0u, 2u, 0u, 5u, 3u, 3u, 0u, 3u, 5u, 5u, 5u, 5u, 5u, 4u}; /* second small graph test */ const size_t C_NUM_VTS_B = 5u; const size_t C_NUM_ES_B = 4u; const unsigned short C_USHORT_U_B[4] = {0u, 1u, 2u, 3u}; const unsigned short C_USHORT_V_B[4] = {1u, 2u, 3u, 4u}; const unsigned short C_USHORT_WTS_B[4] = {(unsigned short)-1, 1u, (unsigned short)-1, 2u}; const unsigned short C_USHORT_DIR_DIST_B[25] = {0u, 1u, 2u, 3u, 4u, 0u, 0u, 1u, 2u, 3u, 0u, 0u, 0u, 1u, 2u, 0u, 0u, 0u, 0u, 1u, 0u, 0u, 0u, 0u, 0u}; const unsigned short C_USHORT_DIR_PREV_B[25] = {0u, 0u, 1u, 2u, 3u, 5u, 1u, 1u, 2u, 3u, 5u, 5u, 2u, 2u, 3u, 5u, 5u, 5u, 3u, 3u, 5u, 5u, 5u, 5u, 4u}; const unsigned short C_USHORT_UNDIR_DIST_B[25] = {0u, 1u, 2u, 3u, 4u, 1u, 0u, 1u, 2u, 3u, 2u, 1u, 0u, 1u, 2u, 3u, 2u, 1u, 0u, 1u, 4u, 3u, 2u, 1u, 0u}; const unsigned short C_USHORT_UNDIR_PREV_B[25] = {0u, 0u, 1u, 2u, 3u, 1u, 1u, 1u, 2u, 3u, 1u, 2u, 2u, 2u, 3u, 1u, 2u, 3u, 3u, 3u, 1u, 2u, 3u, 4u, 4u}; const unsigned long C_ULONG_U_B[4] = {0u, 1u, 2u, 3u}; const unsigned long C_ULONG_V_B[4] = {1u, 2u, 3u, 4u}; const unsigned long C_ULONG_WTS_B[4] = {(unsigned long)-1, 1u, (unsigned long)-1, 2u}; const unsigned long C_ULONG_DIR_DIST_B[25] = {0u, 1u, 2u, 3u, 4u, 0u, 0u, 1u, 2u, 3u, 0u, 0u, 0u, 1u, 2u, 0u, 0u, 0u, 0u, 1u, 0u, 0u, 0u, 0u, 0u}; const unsigned long C_ULONG_DIR_PREV_B[25] = {0u, 0u, 1u, 2u, 3u, 5u, 1u, 1u, 2u, 3u, 5u, 5u, 2u, 2u, 3u, 5u, 5u, 5u, 3u, 3u, 5u, 5u, 5u, 5u, 4u}; const unsigned long C_ULONG_UNDIR_DIST_B[25] = {0u, 1u, 2u, 3u, 4u, 1u, 0u, 1u, 2u, 3u, 2u, 1u, 0u, 1u, 2u, 3u, 2u, 1u, 0u, 1u, 4u, 3u, 2u, 1u, 0u}; const unsigned long C_ULONG_UNDIR_PREV_B[25] = {0u, 0u, 1u, 2u, 3u, 1u, 1u, 1u, 2u, 3u, 1u, 2u, 2u, 2u, 3u, 1u, 2u, 3u, 3u, 3u, 1u, 2u, 3u, 4u, 4u}; /* random graph tests */ const size_t C_FN_COUNT = 4; size_t (* const C_READ[4])(const void *) ={ graph_read_ushort, graph_read_uint, graph_read_ulong, graph_read_sz}; void (* const C_WRITE[4])(void *, size_t) ={ graph_write_ushort, graph_write_uint, graph_write_ulong, graph_write_sz}; void *(* const C_AT[4])(const void *, const void *) ={ graph_at_ushort, graph_at_uint, graph_at_ulong, graph_at_sz}; int (* const C_CMPEQ[4])(const void *, const void *) ={ graph_cmpeq_ushort, graph_cmpeq_uint, graph_cmpeq_ulong, graph_cmpeq_sz}; void (* const C_INCR[4])(void *) ={ graph_incr_ushort, graph_incr_uint, graph_incr_ulong, graph_incr_sz}; const size_t C_VT_SIZES[4] = { sizeof(unsigned short), sizeof(unsigned int), sizeof(unsigned long), sizeof(size_t)}; const char *C_VT_TYPES[4] = {"ushort", "uint ", "ulong ", "sz "}; const size_t C_ITER = 10u; const size_t C_PROBS_COUNT = 5u; const double C_PROBS[5] = {1.00, 0.75, 0.50, 0.25, 0.00}; const double C_PROB_ONE = 1.0; const double C_PROB_ZERO = 0.0; /* additional operations */ void *ptr(const void *block, size_t i, size_t size); void print_test_result(int res); /** Initialize small graphs. */ void ushort_none_graph_a_init(struct graph *g){ graph_base_init(g, C_NUM_VTS_A, sizeof(unsigned short), 0); g->num_es = C_NUM_ES_A; g->u = (unsigned short *)C_USHORT_U_A; g->v = (unsigned short *)C_USHORT_V_A; } void ulong_none_graph_a_init(struct graph *g){ graph_base_init(g, C_NUM_VTS_A, sizeof(unsigned long), 0); g->num_es = C_NUM_ES_A; g->u = (unsigned long *)C_ULONG_U_A; g->v = (unsigned long *)C_ULONG_V_A; } void ushort_ulong_graph_a_init(struct graph *g){ graph_base_init(g, C_NUM_VTS_A, sizeof(unsigned short), sizeof(unsigned long)); g->num_es = C_NUM_ES_A; g->u = (unsigned short *)C_USHORT_U_A; g->v = (unsigned short *)C_USHORT_V_A; g->wts = (unsigned long *)C_ULONG_WTS_A; } void ulong_ushort_graph_a_init(struct graph *g){ graph_base_init(g, C_NUM_VTS_A, sizeof(unsigned long), sizeof(unsigned short)); g->num_es = C_NUM_ES_A; g->u = (unsigned long *)C_ULONG_U_A; g->v = (unsigned long *)C_ULONG_V_A; g->wts = (unsigned short *)C_USHORT_WTS_A; } void ushort_none_graph_b_init(struct graph *g){ graph_base_init(g, C_NUM_VTS_B, sizeof(unsigned short), 0); g->num_es = C_NUM_ES_B; g->u = (unsigned short *)C_USHORT_U_B; g->v = (unsigned short *)C_USHORT_V_B; } void ulong_none_graph_b_init(struct graph *g){ graph_base_init(g, C_NUM_VTS_B, sizeof(unsigned long), 0); g->num_es = C_NUM_ES_B; g->u = (unsigned long *)C_ULONG_U_B; g->v = (unsigned long *)C_ULONG_V_B; } void ushort_ulong_graph_b_init(struct graph *g){ graph_base_init(g, C_NUM_VTS_B, sizeof(unsigned short), sizeof(unsigned long)); g->num_es = C_NUM_ES_B; g->u = (unsigned short *)C_USHORT_U_B; g->v = (unsigned short *)C_USHORT_V_B; g->wts = (unsigned long *)C_ULONG_WTS_B; } void ulong_ushort_graph_b_init(struct graph *g){ graph_base_init(g, C_NUM_VTS_B, sizeof(unsigned long), sizeof(unsigned short)); g->num_es = C_NUM_ES_B; g->u = (unsigned long *)C_ULONG_U_B; g->v = (unsigned long *)C_ULONG_V_B; g->wts = (unsigned short *)C_USHORT_WTS_B; } /** Run bfs tests on small graphs. */ void small_graph_helper(const struct graph *g, const void *ret_dist, const void *ret_prev, void (*build)(struct adj_lst *, const struct graph *, size_t (*)(const void *)), size_t (*read_vt)(const void *), void (*write_vt)(void *, size_t), void *(*at_vt)(const void *, const void *), int (*cmp_vt)(const void *, const void *), void (*incr_vt)(void *), int *res); void run_graph_a_test(){ int res = 1; struct graph g; printf("Run a bfs test on the first small graph with ushort " "vertices --> "); ushort_none_graph_a_init(&g); small_graph_helper(&g, C_USHORT_DIR_DIST_A, C_USHORT_DIR_PREV_A, adj_lst_dir_build, graph_read_ushort, graph_write_ushort, graph_at_ushort, graph_cmpeq_ushort, graph_incr_ushort, &res); small_graph_helper(&g, C_USHORT_UNDIR_DIST_A, C_USHORT_UNDIR_PREV_A, adj_lst_undir_build, graph_read_ushort, graph_write_ushort, graph_at_ushort, graph_cmpeq_ushort, graph_incr_ushort, &res); ushort_ulong_graph_a_init(&g); small_graph_helper(&g, C_USHORT_DIR_DIST_A, C_USHORT_DIR_PREV_A, adj_lst_dir_build, graph_read_ushort, graph_write_ushort, graph_at_ushort, graph_cmpeq_ushort, graph_incr_ushort, &res); small_graph_helper(&g, C_USHORT_UNDIR_DIST_A, C_USHORT_UNDIR_PREV_A, adj_lst_undir_build, graph_read_ushort, graph_write_ushort, graph_at_ushort, graph_cmpeq_ushort, graph_incr_ushort, &res); print_test_result(res); res = 1; printf("Run a bfs test on the first small graph with ulong " "vertices --> "); ulong_none_graph_a_init(&g); small_graph_helper(&g, C_ULONG_DIR_DIST_A, C_ULONG_DIR_PREV_A, adj_lst_dir_build, graph_read_ulong, graph_write_ulong, graph_at_ulong, graph_cmpeq_ulong, graph_incr_ulong, &res); small_graph_helper(&g, C_ULONG_UNDIR_DIST_A, C_ULONG_UNDIR_PREV_A, adj_lst_undir_build, graph_read_ulong, graph_write_ulong, graph_at_ulong, graph_cmpeq_ulong, graph_incr_ulong, &res); ulong_ushort_graph_a_init(&g); small_graph_helper(&g, C_ULONG_DIR_DIST_A, C_ULONG_DIR_PREV_A, adj_lst_dir_build, graph_read_ulong, graph_write_ulong, graph_at_ulong, graph_cmpeq_ulong, graph_incr_ulong, &res); small_graph_helper(&g, C_ULONG_UNDIR_DIST_A, C_ULONG_UNDIR_PREV_A, adj_lst_undir_build, graph_read_ulong, graph_write_ulong, graph_at_ulong, graph_cmpeq_ulong, graph_incr_ulong, &res); print_test_result(res); } void run_graph_b_test(){ int res = 1; struct graph g; printf("Run a bfs test on the second small graph with ushort " "vertices --> "); ushort_none_graph_b_init(&g); small_graph_helper(&g, C_USHORT_DIR_DIST_B, C_USHORT_DIR_PREV_B, adj_lst_dir_build, graph_read_ushort, graph_write_ushort, graph_at_ushort, graph_cmpeq_ushort, graph_incr_ushort, &res); small_graph_helper(&g, C_USHORT_UNDIR_DIST_B, C_USHORT_UNDIR_PREV_B, adj_lst_undir_build, graph_read_ushort, graph_write_ushort, graph_at_ushort, graph_cmpeq_ushort, graph_incr_ushort, &res); ushort_ulong_graph_b_init(&g); small_graph_helper(&g, C_USHORT_DIR_DIST_B, C_USHORT_DIR_PREV_B, adj_lst_dir_build, graph_read_ushort, graph_write_ushort, graph_at_ushort, graph_cmpeq_ushort, graph_incr_ushort, &res); small_graph_helper(&g, C_USHORT_UNDIR_DIST_B, C_USHORT_UNDIR_PREV_B, adj_lst_undir_build, graph_read_ushort, graph_write_ushort, graph_at_ushort, graph_cmpeq_ushort, graph_incr_ushort, &res); print_test_result(res); res = 1; printf("Run a bfs test on the second small graph with ulong " "vertices --> "); ulong_none_graph_b_init(&g); small_graph_helper(&g, C_ULONG_DIR_DIST_B, C_ULONG_DIR_PREV_B, adj_lst_dir_build, graph_read_ulong, graph_write_ulong, graph_at_ulong, graph_cmpeq_ulong, graph_incr_ulong, &res); small_graph_helper(&g, C_ULONG_UNDIR_DIST_B, C_ULONG_UNDIR_PREV_B, adj_lst_undir_build, graph_read_ulong, graph_write_ulong, graph_at_ulong, graph_cmpeq_ulong, graph_incr_ulong, &res); ulong_ushort_graph_b_init(&g); small_graph_helper(&g, C_ULONG_DIR_DIST_B, C_ULONG_DIR_PREV_B, adj_lst_dir_build, graph_read_ulong, graph_write_ulong, graph_at_ulong, graph_cmpeq_ulong, graph_incr_ulong, &res); small_graph_helper(&g, C_ULONG_UNDIR_DIST_B, C_ULONG_UNDIR_PREV_B, adj_lst_undir_build, graph_read_ulong, graph_write_ulong, graph_at_ulong, graph_cmpeq_ulong, graph_incr_ulong, &res); print_test_result(res); } void small_graph_helper(const struct graph *g, const void *ret_dist, const void *ret_prev, void (*build)(struct adj_lst *, const struct graph *, size_t (*)(const void *)), size_t (*read_vt)(const void *), void (*write_vt)(void *, size_t), void *(*at_vt)(const void *, const void *), int (*cmp_vt)(const void *, const void *), void (*incr_vt)(void *), int *res){ size_t i, j; size_t vt_offset = 0; void *dist = NULL, *prev = NULL; struct adj_lst a; adj_lst_base_init(&a, g); build(&a, g, read_vt); dist = malloc_perror(a.num_vts, a.vt_size); prev = malloc_perror(a.num_vts, a.vt_size); for (i = 0; i < a.num_vts; i++){ /* avoid trap representations in tests */ write_vt(ptr(dist, i, a.vt_size), 0); } for (i = 0; i < a.num_vts; i++){ bfs(&a, i, dist, prev, read_vt, write_vt, at_vt, cmp_vt, incr_vt); for (j = 0; j < a.num_vts; j++){ *res *= (cmp_vt(ptr(prev, j, a.vt_size), ptr(ret_prev, j + vt_offset, a.vt_size)) == 0); if (read_vt(ptr(prev, j, a.vt_size)) != a.num_vts){ *res *= (cmp_vt(ptr(dist, j, a.vt_size), ptr(ret_dist, j + vt_offset, a.vt_size)) == 0); } } vt_offset += a.num_vts; } adj_lst_free(&a); free(dist); free(prev); dist = NULL; prev = NULL; } /** Test bfs on large graphs. */ struct bern_arg{ double p; }; int bern(void *arg){ struct bern_arg *b = arg; if (b->p >= C_PROB_ONE) return 1; if (b->p <= C_PROB_ZERO) return 0; if (b->p > DRAND()) return 1; return 0; } /** Runs a bfs test on directed graphs with n(n - 1) edges. */ void run_max_edges_graph_test(size_t log_start, size_t log_end){ int res = 1; size_t i, j, k; size_t num_vts; size_t start; void *dist = NULL, *prev = NULL; struct graph g; struct adj_lst a; struct bern_arg b; b.p = C_PROB_ONE; printf("Run a bfs test on graphs with n vertices, where " "2**%lu <= n <= 2**%lu, and n(n - 1) edges\n", TOLU(log_start), TOLU(log_end)); for (i = log_start; i <= log_end; i++){ num_vts = pow_two_perror(i); printf("\t\tvertices: %lu\n", TOLU(num_vts)); for (j = 0; j < C_FN_COUNT; j++){ /* no declared type after realloc; effective type is set by bfs */ dist = realloc_perror(dist, num_vts, C_VT_SIZES[j]); prev = realloc_perror(prev, num_vts, C_VT_SIZES[j]); for (k = 0; k < num_vts; k++){ /* avoid trap representations in tests */ C_WRITE[j](ptr(dist, k, C_VT_SIZES[j]), 0); } graph_base_init(&g, num_vts, C_VT_SIZES[j], 0); adj_lst_base_init(&a, &g); adj_lst_rand_dir(&a, C_WRITE[j], bern, &b); start = RANDOM() % num_vts; bfs(&a, start, dist, prev, C_READ[j], C_WRITE[j], C_AT[j], C_CMPEQ[j], C_INCR[j]); for (k = 0; k < num_vts; k++){ if (k == start){ res *= (C_READ[j](ptr(dist, k, C_VT_SIZES[j])) == 0); }else{ res *= (C_READ[j](ptr(dist, k, C_VT_SIZES[j])) == 1); } res *= (C_READ[j](ptr(prev, k, C_VT_SIZES[j])) == start); } printf("\t\t\t%s correctness: ", C_VT_TYPES[j]); print_test_result(res); res = 1; adj_lst_free(&a); /* deallocates blocks with effective vertex type */ } } free(dist); free(prev); dist = NULL; prev = NULL; } /** Runs a bfs test on directed graphs with no edges. */ void run_no_edges_graph_test(size_t log_start, size_t log_end){ int res = 1; size_t i, j, k; size_t num_vts; size_t start; void *dist = NULL, *prev = NULL; struct graph g; struct adj_lst a; struct bern_arg b; b.p = C_PROB_ZERO; printf("Run a bfs test on graphs with no edges\n");; for (i = log_start; i <= log_end; i++){ num_vts = pow_two_perror(i); printf("\t\tvertices: %lu\n", TOLU(num_vts)); for (j = 0; j < C_FN_COUNT; j++){ /* no declared type after realloc; effective type is set by bfs */ dist = realloc_perror(dist, num_vts, C_VT_SIZES[j]); prev = realloc_perror(prev, num_vts, C_VT_SIZES[j]); for (k = 0; k < num_vts; k++){ /* avoid trap representations in tests */ C_WRITE[j](ptr(dist, k, C_VT_SIZES[j]), 0); } graph_base_init(&g, num_vts, C_VT_SIZES[j], 0); adj_lst_base_init(&a, &g); adj_lst_rand_dir(&a, C_WRITE[j], bern, &b); start = RANDOM() % num_vts; bfs(&a, start, dist, prev, C_READ[j], C_WRITE[j], C_AT[j], C_CMPEQ[j], C_INCR[j]); for (k = 0; k < num_vts; k++){ if (k == start){ res *= (C_READ[j](ptr(prev, k, C_VT_SIZES[j])) == start && C_READ[j](ptr(dist, k, C_VT_SIZES[j])) == 0); }else{ res *= (C_READ[j](ptr(prev, k, C_VT_SIZES[j])) == num_vts); } } printf("\t\t\t%s correctness: ", C_VT_TYPES[j]); print_test_result(res); res = 1; adj_lst_free(&a); /* deallocates blocks with effective vertex type */ } } free(dist); free(prev); dist = NULL; prev = NULL; } /** Run a bfs test on random directed graphs. */ void run_random_dir_graph_helper(size_t num_vts, size_t vt_size, const char *type_string, size_t (*read_vt)(const void *), void (*write_vt)(void *, size_t), void *(*at_vt)(const void *, const void *), int (*cmp_vt)(const void *, const void *), void (*incr_vt)(void *), int bern(void *), struct bern_arg *b); void run_random_dir_graph_test(size_t log_start, size_t log_end){ size_t i, j; size_t num_vts; struct bern_arg b; printf("Run a bfs test on random directed graphs from %lu random " "start vertices in each graph\n", TOLU(C_ITER)); for (i = 0; i < C_PROBS_COUNT; i++){ b.p = C_PROBS[i]; printf("\tP[an edge is in a graph] = %.2f\n", b.p); for (j = log_start; j <= log_end; j++){ num_vts = pow_two_perror(j); printf("\t\tvertices: %lu, E[# of directed edges]: %.1f\n", TOLU(num_vts), b.p * num_vts * (num_vts - 1)); run_random_dir_graph_helper(num_vts, C_VT_SIZES[0], C_VT_TYPES[0], C_READ[0], C_WRITE[0], C_AT[0], C_CMPEQ[0], C_INCR[0], bern, &b); run_random_dir_graph_helper(num_vts, C_VT_SIZES[1], C_VT_TYPES[1], C_READ[1], C_WRITE[1], C_AT[1], C_CMPEQ[1], C_INCR[1], bern, &b); run_random_dir_graph_helper(num_vts, C_VT_SIZES[2], C_VT_TYPES[2], C_READ[2], C_WRITE[2], C_AT[2], C_CMPEQ[2], C_INCR[2], bern, &b); run_random_dir_graph_helper(num_vts, C_VT_SIZES[3], C_VT_TYPES[3], C_READ[3], C_WRITE[3], C_AT[3], C_CMPEQ[3], C_INCR[3], bern, &b); } } } void run_random_dir_graph_helper(size_t num_vts, size_t vt_size, const char *type_string, size_t (*read_vt)(const void *), void (*write_vt)(void *, size_t), void *(*at_vt)(const void *, const void *), int (*cmp_vt)(const void *, const void *), void (*incr_vt)(void *), int bern(void *), struct bern_arg *b){ size_t i; size_t *start = NULL; void *dist = NULL, *prev = NULL; struct graph g; struct adj_lst a; clock_t t; /* no declared type after malloc; effective type is set by bfs */ start = malloc_perror(C_ITER, sizeof(size_t)); dist = malloc_perror(num_vts, vt_size); prev = malloc_perror(num_vts, vt_size); for (i = 0; i < num_vts; i++){ /* avoid trap representations in tests */ write_vt(ptr(dist, i, vt_size), 0); } graph_base_init(&g, num_vts, vt_size, 0); adj_lst_base_init(&a, &g); adj_lst_rand_dir(&a, write_vt, bern, b); for (i = 0; i < C_ITER; i++){ start[i] = RANDOM() % num_vts; } t = clock(); for (i = 0; i < C_ITER; i++){ bfs(&a, start[i], dist, prev, read_vt, write_vt, at_vt, cmp_vt, incr_vt); } t = clock() - t; printf("\t\t\t%s ave runtime: %.6f seconds\n", type_string, (double)t / C_ITER / CLOCKS_PER_SEC); adj_lst_free(&a); /* deallocates blocks with effective vertex type */ free(start); free(dist); free(prev); start = NULL; dist = NULL; prev = NULL; } /** Computes a pointer to the ith element in the block of elements. */ void *ptr(const void *block, size_t i, size_t size){ return (void *)((char *)block + i * size); } void print_test_result(int res){ if (res){ printf("SUCCESS\n"); }else{ printf("FAILURE\n"); } } int main(int argc, char *argv[]){ int i; size_t *args = NULL; RGENS_SEED(); if (argc > C_ARGC_ULIMIT){ printf("USAGE:\n%s", C_USAGE); exit(EXIT_FAILURE); } args = malloc_perror(C_ARGC_ULIMIT - 1, sizeof(size_t)); memcpy(args, C_ARGS_DEF, (C_ARGC_ULIMIT - 1) * sizeof(size_t)); for (i = 1; i < argc; i++){ args[i - 1] = atoi(argv[i]); } if (args[0] > C_USHORT_BIT - 1 || args[1] > C_USHORT_BIT - 1 || args[2] > C_USHORT_BIT - 1 || args[3] > C_USHORT_BIT - 1 || args[4] > C_USHORT_BIT - 1 || args[5] > C_USHORT_BIT - 1 || args[1] < args[0] || args[3] < args[2] || args[5] < args[4] || args[6] > 1 || args[7] > 1 || args[8] > 1 || args[9] > 1){ printf("USAGE:\n%s", C_USAGE); exit(EXIT_FAILURE); } if (args[6]){ run_graph_a_test(); run_graph_b_test(); } if (args[7]) run_max_edges_graph_test(args[0], args[1]); if (args[8]) run_no_edges_graph_test(args[2], args[3]); if (args[9]) run_random_dir_graph_test(args[4], args[5]); free(args); args = NULL; return 0; }
alfin3/graph-algorithms
utilities-pthread/mergesort-pthread/mergesort-pthread-test.c
<filename>utilities-pthread/mergesort-pthread/mergesort-pthread-test.c /** mergesort-pthread-test.c Optimization and correctness tests of a generic merge sort algorithm with parallel sorting and parallel merging. The following command line arguments can be used to customize tests: mergesort-pthread-test [0, # bits in size_t - 1) : a [0, # bits in size_t - 1) : b s.t. 2^a <= count <= 2^b [0, # bits in size_t) : c [0, # bits in size_t) : d s.t. 2^c <= sort base case bound <= 2^d [1, # bits in size_t) : e [1, # bits in size_t) : f s.t. 2^e <= merge base case bound <= 2^f [0, 1] : int corner test on/off [0, 1] : int performance test on/off [0, 1] : double corner test on/off [0, 1] : double performance test on/off usage examples: ./mergesort-pthread-test ./mergesort-pthread-test 17 17 ./mergesort-pthread-test 20 20 15 20 15 20 ./mergesort-pthread-test 20 20 15 20 15 20 0 1 0 1 mergesort-pthread-test can be run with any subset of command line arguments in the above-defined order. If the (i + 1)th argument is specified then the ith argument must be specified for i >= 0. Default values are used for the unspecified arguments according to the C_ARGS_DEF array. The implementation of tests does not use stdint.h and is portable under C89/C90 with the requirements that CHAR_BIT * sizeof(size_t) is even and pthreads API is available. */ #define _POSIX_C_SOURCE 200112L #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <limits.h> #include <time.h> #include <sys/time.h> #include "mergesort-pthread.h" #include "utilities-mem.h" #include "utilities-mod.h" /** Generate random numbers in a portable way for test purposes only; rand() in the Linux C Library uses the same generator as random(), which may not be the case on older rand() implementations, and on current implementations on different systems. */ #define RGENS_SEED() do{srand(time(NULL));}while (0) #define RANDOM() (rand()) /* [0, RAND_MAX] */ #define DRAND() ((double)rand() / RAND_MAX) /* [0.0, 1.0] */ #define TOLU(i) ((unsigned long int)(i)) /* printing size_t under C89/C90 */ /* input handling */ const char *C_USAGE = "mergesort-pthread-test \n" "[0, # bits in size_t - 1) : a \n" "[0, # bits in size_t - 1) : b s.t. 2^a <= count <= 2^b \n" "[0, # bits in size_t) : c \n" "[0, # bits in size_t) : d s.t. 2^c <= sort base case bound <= 2^d \n" "[1, # bits in size_t) : e \n" "[1, # bits in size_t) : f s.t. 2^e <= merge base case bound <= 2^f \n" "[0, 1] : int corner test on/off \n" "[0, 1] : int performance test on/off \n" "[0, 1] : double corner test on/off \n" "[0, 1] : double performance test on/off \n"; const int C_ARGC_MAX = 11; const size_t C_ARGS_DEF[10] = {15, 15, 10, 15, 10, 15, 1, 1, 1, 1}; const size_t C_FULL_BIT = CHAR_BIT * sizeof(size_t); /* corner cases */ const size_t C_CORNER_TRIALS = 10; const size_t C_CORNER_COUNT_MAX = 17; const size_t C_CORNER_SBASE_START = 1; const size_t C_CORNER_SBASE_END = 17; const size_t C_CORNER_MBASE_START = 2; const size_t C_CORNER_MBASE_END = 20; const double C_HALF_PROB = 0.5; /* performance tests */ const size_t C_TRIALS = 5; double timer(); void print_uint_elts(const size_t *a, size_t count); void print_test_result(int res); int cmp_int(const void *a, const void *b){ if (*(int *)a > *(int *)b){ return 1; }else if (*(int *)a < *(int *)b){ return -1; }else{ return 0; } } int cmp_double(const void *a, const void *b){ if (*(double *)a > *(double *)b){ return 1; }else if (*(double *)a < *(double *)b){ return -1; }else{ return 0; } } /** Runs a mergesort_pthread corner cases test on random integer arrays. */ void run_int_corner_test(){ int res = 1; int *arr_a = NULL, *arr_b = NULL; size_t count, sb, mb; size_t i, j; size_t elt_size = sizeof(int); arr_a = malloc_perror(C_CORNER_COUNT_MAX, elt_size); arr_b = malloc_perror(C_CORNER_COUNT_MAX, elt_size); printf("Test mergesort_pthread on corner cases on random " "integer arrays\n"); for (count = 1; count <= C_CORNER_COUNT_MAX; count++){ for (sb = C_CORNER_SBASE_START; sb <= C_CORNER_SBASE_END; sb++){ for (mb = C_CORNER_MBASE_START; mb <= C_CORNER_MBASE_END; mb++){ for(i = 0; i < C_CORNER_TRIALS; i++){ for (j = 0; j < count; j++){ arr_a[j] = (DRAND() < C_HALF_PROB ? -1 : 1) * RANDOM(); } memcpy(arr_b, arr_a, count * elt_size); mergesort_pthread(arr_a, count, elt_size, sb, mb, cmp_int); qsort(arr_b, count, elt_size, cmp_int); for (j = 0; j < count; j++){ res *= (arr_a[j] == arr_b[j]); } } } } } printf("\tcorrectness: "); print_test_result(res); free(arr_a); free(arr_b); arr_a = NULL; arr_b = NULL; } /** Runs a test comparing mergesort_pthread vs. qsort performance on random integer arrays across sort and merge base count bounds. */ void run_int_opt_test(int pow_count_start, int pow_count_end, int pow_sbase_start, int pow_sbase_end, int pow_mbase_start, int pow_mbase_end){ int res = 1; int *arr_a = NULL, *arr_b = NULL; int ci, si, mi; size_t count, sbase, mbase; size_t i, j; size_t elt_size = sizeof(int); double tot_m, tot_q, t_m, t_q; arr_a = malloc_perror(pow_two(pow_count_end), elt_size); arr_b = malloc_perror(pow_two(pow_count_end), elt_size); printf("Test mergesort_pthread performance on random integer arrays\n"); for (ci = pow_count_start; ci <= pow_count_end; ci++){ count = pow_two(ci); /* > 0 */ printf("\t# trials: %lu, array count: %lu\n", TOLU(C_TRIALS), TOLU(count)); for (si = pow_sbase_start; si <= pow_sbase_end; si++){ sbase = pow_two(si); printf("\t\tsort base count: %lu\n", TOLU(sbase)); for (mi = pow_mbase_start; mi <= pow_mbase_end; mi++){ mbase = pow_two(mi); printf("\t\t\tmerge base count: %lu\n", TOLU(mbase)); tot_m = 0.0; tot_q = 0.0; for(i = 0; i < C_TRIALS; i++){ for (j = 0; j < count; j++){ arr_a[j] = (DRAND() < C_HALF_PROB ? -1 : 1) * RANDOM(); } memcpy(arr_b, arr_a, count * elt_size); t_m = timer(); mergesort_pthread(arr_a, count, elt_size, sbase, mbase, cmp_int); t_m = timer() - t_m; t_q = timer(); qsort(arr_b, count, elt_size, cmp_int); t_q = timer() - t_q; tot_m += t_m; tot_q += t_q; for (j = 0; j < count; j++){ res *= (arr_a[j] == arr_b[j]); } } printf("\t\t\tave pthread mergesort: %.6f seconds\n", tot_m / C_TRIALS); printf("\t\t\tave qsort: %.6f seconds\n", tot_q / C_TRIALS); printf("\t\t\tcorrectness: "); print_test_result(res); } } } free(arr_a); free(arr_b); arr_a = NULL; arr_b = NULL; } /** Runs a mergesort_pthread corner cases test on random double arrays. */ void run_double_corner_test(){ int res = 1; size_t count, sb, mb; size_t i, j; size_t elt_size = sizeof(double); double *arr_a = NULL, *arr_b = NULL; arr_a = malloc_perror(C_CORNER_COUNT_MAX, elt_size); arr_b = malloc_perror(C_CORNER_COUNT_MAX, elt_size); printf("Test mergesort_pthread on corner cases on random " "double arrays\n"); for (count = 1; count <= C_CORNER_COUNT_MAX; count++){ for (sb = C_CORNER_SBASE_START; sb <= C_CORNER_SBASE_END; sb++){ for (mb = C_CORNER_MBASE_START; mb <= C_CORNER_MBASE_END; mb++){ for(i = 0; i < C_CORNER_TRIALS; i++){ for (j = 0; j < count; j++){ arr_a[j] = (DRAND() < C_HALF_PROB ? -1 : 1) * DRAND(); } memcpy(arr_b, arr_a, count * elt_size); mergesort_pthread(arr_a, count, elt_size, sb, mb, cmp_double); qsort(arr_b, count, elt_size, cmp_double); for (j = 0; j < count; j++){ res *= (arr_a[j] == arr_b[j]); } } } } } printf("\tcorrectness: "); print_test_result(res); free(arr_a); free(arr_b); arr_a = NULL; arr_b = NULL; } /** Runs a test comparing mergesort_pthread vs. qsort performance on random double arrays across sort and merge base count bounds. */ void run_double_opt_test(int pow_count_start, int pow_count_end, int pow_sbase_start, int pow_sbase_end, int pow_mbase_start, int pow_mbase_end){ int res = 1; int ci, si, mi; size_t count, sbase, mbase; size_t i, j; size_t elt_size = sizeof(double); double *arr_a = NULL, *arr_b = NULL; double tot_m, tot_q, t_m, t_q; arr_a = malloc_perror(pow_two(pow_count_end), elt_size); arr_b = malloc_perror(pow_two(pow_count_end), elt_size); printf("Test mergesort_pthread performance on random double arrays\n"); for (ci = pow_count_start; ci <= pow_count_end; ci++){ count = pow_two(ci); /* > 0 */ printf("\t# trials: %lu, array count: %lu\n", TOLU(C_TRIALS), TOLU(count)); for (si = pow_sbase_start; si <= pow_sbase_end; si++){ sbase = pow_two(si); printf("\t\tsort base count: %lu\n", TOLU(sbase)); for (mi = pow_mbase_start; mi <= pow_mbase_end; mi++){ mbase = pow_two(mi); printf("\t\t\tmerge base count: %lu\n", TOLU(mbase)); tot_m = 0.0; tot_q = 0.0; for(i = 0; i < C_TRIALS; i++){ for (j = 0; j < count; j++){ arr_a[j] = (DRAND() < C_HALF_PROB ? -1 : 1) * DRAND(); } memcpy(arr_b, arr_a, count * elt_size); t_m = timer(); mergesort_pthread(arr_a, count, elt_size, sbase, mbase, cmp_double); t_m = timer() - t_m; t_q = timer(); qsort(arr_b, count, elt_size, cmp_double); t_q = timer() - t_q; tot_m += t_m; tot_q += t_q; for (j = 0; j < count; j++){ res *= (arr_a[j] == arr_b[j]); } } printf("\t\t\tave pthread mergesort: %.6f seconds\n", tot_m / C_TRIALS); printf("\t\t\tave qsort: %.6f seconds\n", tot_q / C_TRIALS); printf("\t\t\tcorrectness: "); print_test_result(res); } } } free(arr_a); free(arr_b); arr_a = NULL; arr_b = NULL; } /** Times execution. */ double timer(){ struct timeval tm; gettimeofday(&tm, NULL); return tm.tv_sec + tm.tv_usec / (double)1000000; } /** Print helper functions. */ void print_uint_elts(const size_t *a, size_t count){ size_t i; for (i = 0; i < count; i++){ printf("%lu ", TOLU(a[i])); } printf("\n"); } void print_test_result(int res){ if (res){ printf("SUCCESS\n"); }else{ printf("FAILURE\n"); } } int main(int argc, char *argv[]){ int i; size_t *args = NULL; RGENS_SEED(); if (argc > C_ARGC_MAX){ printf("USAGE:\n%s", C_USAGE); exit(EXIT_FAILURE); } args = malloc_perror(C_ARGC_MAX - 1, sizeof(size_t)); memcpy(args, C_ARGS_DEF, (C_ARGC_MAX - 1) * sizeof(size_t)); for (i = 1; i < argc; i++){ args[i - 1] = atoi(argv[i]); } if (args[0] > C_FULL_BIT - 2 || args[1] > C_FULL_BIT - 2 || args[2] > C_FULL_BIT - 1 || args[3] > C_FULL_BIT - 1 || args[4] > C_FULL_BIT - 1 || args[5] > C_FULL_BIT - 1 || args[4] < 1 || args[5] < 1 || args[0] > args[1] || args[2] > args[3] || args[4] > args[5] || args[6] > 1 || args[7] > 1 || args[8] > 1 || args[9] > 1){ printf("USAGE:\n%s", C_USAGE); exit(EXIT_FAILURE); } if (args[6]) run_int_corner_test(); if (args[7]) run_int_opt_test(args[0], args[1], args[2], args[3], args[4], args[5]); if (args[8]) run_double_corner_test(); if (args[9]) run_double_opt_test(args[0], args[1], args[2], args[3], args[4], args[5]); free(args); args = NULL; return 0; }
alfin3/graph-algorithms
data-structures/heap/heap-test.c
/** heap-test.c Tests of a (min) heap across i) division- and mutliplication-based hash tables, ii) contiguous and noncontiguous elements, and iii) basic priority types. The following command line arguments can be used to customize tests: heap-test [0, size_t width - 1) : i s.t. # inserts = 2^i > 0 : a < size_t width : b s.t. 0.0 < a / 2**b > 0 : c < size_t width : d s.t. 0.0 < c / 2**d <= 1.0 [0, 1] : on/off push pop free division hash table test [0, 1] : on/off update search division hash table test [0, 1] : on/off push pop free multiplication hash table test [0, 1] : on/off update search multiplication hash table test usage examples: ./heap-test ./heap-test 21 ./heap-test 20 10 10 ./heap-test 20 1 0 ./heap-test 20 100 0 ./heap-test 20 1 0 10 10 0 0 ./heap-test 20 1 0 1 0 0 0 ./heap-test 20 1 0 100 0 0 0 heap-test can be run with any subset of command line arguments in the above-defined order. If the (i + 1)th argument is specified then the ith argument must be specified for i >= 0. Default values are used for the unspecified arguments according to the C_ARGS_DEF array. The implementation does not use stdint.h and is portable under C89/C90 and C99 with the only requirement that the width of size_t is greater or equal to 16, less than 2040, and is even. TODO: add portable size_t printing */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <limits.h> #include <time.h> #include "heap.h" #include "ht-divchn.h" #include "ht-muloa.h" #include "utilities-mem.h" #include "utilities-mod.h" #include "utilities-lim.h" #define TOLU(i) ((unsigned long int)(i)) /* printing size_t under C89/C90 */ /* input handling */ const char *C_USAGE = "heap-test\n" "[0, size_t width - 1) : i s.t. # inserts = 2^i\n" "> 0 : a\n" "< size_t width : b s.t. 0.0 < a / 2**b\n" "> 0 : c\n" "< size_t width : d s.t. 0.0 < c / 2**d <= 1.0\n" "[0, 1] : on/off push pop free division hash table test\n" "[0, 1] : on/off update search division hash table test\n" "[0, 1] : on/off push pop free multiplication hash table test\n" "[0, 1] : on/off update search multiplication hash table test\n"; const int C_ARGC_ULIMIT = 10; const size_t C_ARGS_DEF[9] = {14u, 1u, 0u, 341u, 10u, 1u, 1u, 1u, 1u}; const size_t C_FULL_BIT = PRECISION_FROM_ULIMIT((size_t)-1); /* tests */ const int C_PTY_TYPES_COUNT = 3; const char *C_PTY_TYPES[3] = {"size_t", "double", "long double"}; const size_t C_PTY_SIZES[3] = {sizeof(size_t), sizeof(double), sizeof(long double)}; int cmp_uint(const void *a, const void *b); int cmp_double(const void *a, const void *b); int cmp_long_double(const void *a, const void *b); void new_uint(void *a, size_t val); void new_double(void *a, size_t val); void new_long_double(void *a, size_t val); int (*const C_CMP_PTY_ARR[3])(const void *, const void *) ={cmp_uint, cmp_double, cmp_long_double}; void (*const C_NEW_PTY_ARR[3])(void *, size_t) = {new_uint, new_double, new_long_double}; const size_t C_H_MIN_NUM = 1u; void push_pop_free(size_t num_ins, size_t pty_size, size_t elt_size, const struct heap_ht *hht, void (*new_pty)(void *, size_t), void (*new_elt)(void *, size_t), int (*cmp_pty)(const void *, const void *), int (*cmp_elt)(const void *, const void *), size_t (*rdc_elt)(const void *), void (*free_elt)(void *)); void update_search(size_t num_ins, size_t pty_size, size_t elt_size, const struct heap_ht *hht, void (*new_pty)(void *, size_t), void (*new_elt)(void *, size_t), int (*cmp_pty)(const void *, const void *), int (*cmp_elt)(const void *, const void *), size_t (*rdc_elt)(const void *), void (*free_elt)(void *)); void *ptr(const void *block, size_t i, size_t size); void print_test_result(int res); /** Run heap_{push, pop, free} and heap_{update, search} tests with division- and mutliplication-based hash tables on size_t elements across priority types. An element is an elt_size block of size sizeof(size_t) with a size_t value. Elements are entirely copied into the heap and free_elt is NULL. */ void new_uint(void *a, size_t val){ size_t *s = a; *s = val; } void new_double(void *a, size_t val){ double *s = a; *s = val; } void new_long_double(void *a, size_t val){ long double *s = a; *s = val; } int cmp_uint(const void *a, const void *b){ return ((*(size_t *)a > *(size_t *)b) - (*(size_t *)a < *(size_t *)b)); } int cmp_double(const void *a, const void *b){ return ((*(double *)a > *(double *)b) - (*(double *)a < *(double *)b)); } int cmp_long_double(const void *a, const void *b){ return ((*(long double *)a > *(long double *)b) - (*(long double *)a < *(long double *)b)); } size_t rdc_uint(const void *a){ return *(size_t *)a; } /** Runs a heap_{push, pop, free} test with a ht_divchn_t hash table on size_t elements across priority types. */ void run_push_pop_free_divchn_uint_test(size_t log_ins, size_t alpha_n, size_t log_alpha_d){ int i; size_t n; struct ht_divchn ht_divchn; struct heap_ht hht; n = pow_two_perror(log_ins); hht.ht = &ht_divchn; hht.alpha_n = alpha_n; hht.log_alpha_d = log_alpha_d; hht.init = ht_divchn_init_helper; hht.align = ht_divchn_align_helper; hht.insert = ht_divchn_insert_helper; hht.search = ht_divchn_search_helper; hht.remove = ht_divchn_remove_helper; hht.free = ht_divchn_free_helper; printf("Run a heap_{push, pop, free} test with a ht_divchn " "hash table on size_t elements\n"); for (i = 0; i < C_PTY_TYPES_COUNT; i++){ printf("\tnumber of elements: %lu\n" "\tload factor upper bound: %.4f\n" "\tpriority type: %s\n", TOLU(n), (float)alpha_n / pow_two_perror(log_alpha_d), C_PTY_TYPES[i]); push_pop_free(n, C_PTY_SIZES[i], sizeof(size_t), &hht, C_NEW_PTY_ARR[i], new_uint, C_CMP_PTY_ARR[i], cmp_uint, rdc_uint, NULL); } } /** Runs a heap_{update, search} test with a ht_divchn hash table on size_t elements across priority types. */ void run_update_search_divchn_uint_test(size_t log_ins, size_t alpha_n, size_t log_alpha_d){ int i; size_t n; struct ht_divchn ht_divchn; struct heap_ht hht; n = pow_two_perror(log_ins); hht.ht = &ht_divchn; hht.alpha_n = alpha_n; hht.log_alpha_d = log_alpha_d; hht.init = ht_divchn_init_helper; hht.align = ht_divchn_align_helper; hht.insert = ht_divchn_insert_helper; hht.search = ht_divchn_search_helper; hht.remove = ht_divchn_remove_helper; hht.free = ht_divchn_free_helper; printf("Run a heap_{update, search} test with a ht_divchn " "hash table on size_t elements\n"); for (i = 0; i < C_PTY_TYPES_COUNT; i++){ printf("\tnumber of elements: %lu\n" "\tload factor upper bound: %.4f\n" "\tpriority type: %s\n", TOLU(n), (float)alpha_n / pow_two_perror(log_alpha_d), C_PTY_TYPES[i]); update_search(n, C_PTY_SIZES[i], sizeof(size_t), &hht, C_NEW_PTY_ARR[i], new_uint, C_CMP_PTY_ARR[i], cmp_uint, rdc_uint, NULL); } } /** Runs a heap_{push, pop, free} test with a ht_muloa hash table on size_t elements across priority types. */ void run_push_pop_free_muloa_uint_test(size_t log_ins, size_t alpha_n, size_t log_alpha_d){ int i; size_t n; struct ht_muloa ht_muloa; struct heap_ht hht; n = pow_two_perror(log_ins); hht.ht = &ht_muloa; hht.alpha_n = alpha_n; hht.log_alpha_d = log_alpha_d; hht.init = ht_muloa_init_helper; hht.align = ht_muloa_align_helper; hht.insert = ht_muloa_insert_helper; hht.search = ht_muloa_search_helper; hht.remove = ht_muloa_remove_helper; hht.free = ht_muloa_free_helper; printf("Run a heap_{push, pop, free} test with a ht_muloa " "hash table on size_t elements\n"); for (i = 0; i < C_PTY_TYPES_COUNT; i++){ printf("\tnumber of elements: %lu\n" "\tload factor upper bound: %.4f\n" "\tpriority type: %s\n", TOLU(n), (float)alpha_n / pow_two_perror(log_alpha_d), C_PTY_TYPES[i]); push_pop_free(n, C_PTY_SIZES[i], sizeof(size_t), &hht, C_NEW_PTY_ARR[i], new_uint, C_CMP_PTY_ARR[i], cmp_uint, rdc_uint, NULL); } } /** Runs a heap_{update, search} test with a ht_muloa hash table on size_t elements across priority types. */ void run_update_search_muloa_uint_test(size_t log_ins, size_t alpha_n, size_t log_alpha_d){ int i; size_t n; struct ht_muloa ht_muloa; struct heap_ht hht; n = pow_two_perror(log_ins); hht.ht = &ht_muloa; hht.alpha_n = alpha_n; hht.log_alpha_d = log_alpha_d; hht.init = ht_muloa_init_helper; hht.align = ht_muloa_align_helper; hht.insert = ht_muloa_insert_helper; hht.search = ht_muloa_search_helper; hht.remove = ht_muloa_remove_helper; hht.free = ht_muloa_free_helper; printf("Run a heap_{update, search} test with a ht_muloa " "hash table on size_t elements\n"); for (i = 0; i < C_PTY_TYPES_COUNT; i++){ printf("\tnumber of elements: %lu\n" "\tload factor upper bound: %.4f\n" "\tpriority type: %s\n", TOLU(n), (float)alpha_n / pow_two_perror(log_alpha_d), C_PTY_TYPES[i]); update_search(n, C_PTY_SIZES[i], sizeof(size_t), &hht, C_NEW_PTY_ARR[i], new_uint, C_CMP_PTY_ARR[i], cmp_uint, rdc_uint, NULL); } } /** Run heap_{push, pop, free} and heap_{update, search} tests with division- and mutliplication-based hash tables on noncontiguous uint_ptr elements across priority types. Because an element is noncontiguous, a pointer to an element is copied as an elt_size block. An element-specific free_elt is necessary to delete an element. */ struct uint_ptr{ size_t *val; }; void new_uint_ptr(void *a, size_t val){ struct uint_ptr **s = a; *s = malloc_perror(1, sizeof(struct uint_ptr)); (*s)->val = malloc_perror(1, sizeof(size_t)); *((*s)->val) = val; } int cmp_uint_ptr(const void *a, const void *b){ return ((*((*(struct uint_ptr **)a)->val) > *((*(struct uint_ptr **)b)->val)) - (*((*(struct uint_ptr **)a)->val) < *((*(struct uint_ptr **)b)->val))); } size_t rdc_uint_ptr(const void *a){ return *((*(struct uint_ptr **)a)->val); } void free_uint_ptr(void *a){ struct uint_ptr **s = a; free((*s)->val); (*s)->val = NULL; free(*s); *s = NULL; } /** Runs a heap_{push, pop, free} test with a ht_divchn hash table on noncontiguous uint_ptr elements across priority types. */ void run_push_pop_free_divchn_uint_ptr_test(size_t log_ins, size_t alpha_n, size_t log_alpha_d){ int i; size_t n; struct ht_divchn ht_divchn; struct heap_ht hht; n = pow_two_perror(log_ins); hht.ht = &ht_divchn; hht.alpha_n = alpha_n; hht.log_alpha_d = log_alpha_d; hht.init = ht_divchn_init_helper; hht.align = ht_divchn_align_helper; hht.insert = ht_divchn_insert_helper; hht.search = ht_divchn_search_helper; hht.remove = ht_divchn_remove_helper; hht.free = ht_divchn_free_helper; printf("Run a heap_{push, pop, free} test with a ht_divchn " "hash table on noncontiguous uint_ptr elements\n"); for (i = 0; i < C_PTY_TYPES_COUNT; i++){ printf("\tnumber of elements: %lu\n" "\tload factor upper bound: %.4f\n" "\tpriority type: %s\n", TOLU(n), (float)alpha_n / pow_two_perror(log_alpha_d), C_PTY_TYPES[i]); push_pop_free(n, C_PTY_SIZES[i], sizeof(struct uint_ptr *), &hht, C_NEW_PTY_ARR[i], new_uint_ptr, C_CMP_PTY_ARR[i], cmp_uint_ptr, rdc_uint_ptr, free_uint_ptr); } } /** Runs a heap_{update, search} test with a ht_divchn hash table on noncontiguous uint_ptr elements across priority types. */ void run_update_search_divchn_uint_ptr_test(size_t log_ins, size_t alpha_n, size_t log_alpha_d){ int i; size_t n; struct ht_divchn ht_divchn; struct heap_ht hht; n = pow_two_perror(log_ins); hht.ht = &ht_divchn; hht.alpha_n = alpha_n; hht.log_alpha_d = log_alpha_d; hht.init = ht_divchn_init_helper; hht.align = ht_divchn_align_helper; hht.insert = ht_divchn_insert_helper; hht.search = ht_divchn_search_helper; hht.remove = ht_divchn_remove_helper; hht.free = ht_divchn_free_helper; printf("Run a heap_{update, search} test with a ht_divchn " "hash table on noncontiguous uint_ptr elements\n"); for (i = 0; i < C_PTY_TYPES_COUNT; i++){ printf("\tnumber of elements: %lu\n" "\tload factor upper bound: %.4f\n" "\tpriority type: %s\n", TOLU(n), (float)alpha_n / pow_two_perror(log_alpha_d), C_PTY_TYPES[i]); update_search(n, C_PTY_SIZES[i], sizeof(struct uint_ptr *), &hht, C_NEW_PTY_ARR[i], new_uint_ptr, C_CMP_PTY_ARR[i], cmp_uint_ptr, rdc_uint_ptr, free_uint_ptr); } } /** Runs a heap_{push, pop, free} test with a ht_muloa hash table on noncontiguous uint_ptr elements across priority types. */ void run_push_pop_free_muloa_uint_ptr_test(size_t log_ins, size_t alpha_n, size_t log_alpha_d){ int i; size_t n; struct ht_muloa ht_muloa; struct heap_ht hht; n = pow_two_perror(log_ins); hht.ht = &ht_muloa; hht.alpha_n = alpha_n; hht.log_alpha_d = log_alpha_d; hht.init = ht_muloa_init_helper; hht.align = ht_muloa_align_helper; hht.insert = ht_muloa_insert_helper; hht.search = ht_muloa_search_helper; hht.remove = ht_muloa_remove_helper; hht.free = ht_muloa_free_helper; printf("Run a heap_{push, pop, free} test with a ht_muloa " "hash table on noncontiguous uint_ptr elements\n"); for (i = 0; i < C_PTY_TYPES_COUNT; i++){ printf("\tnumber of elements: %lu\n" "\tload factor upper bound: %.4f\n" "\tpriority type: %s\n", TOLU(n), (float)alpha_n / pow_two_perror(log_alpha_d), C_PTY_TYPES[i]); push_pop_free(n, C_PTY_SIZES[i], sizeof(struct uint_ptr *), &hht, C_NEW_PTY_ARR[i], new_uint_ptr, C_CMP_PTY_ARR[i], cmp_uint_ptr, rdc_uint_ptr, free_uint_ptr); } } /** Runs a heap_{update, search} test with a ht_muloa hash table on noncontiguous uint_ptr elements across priority types. */ void run_update_search_muloa_uint_ptr_test(size_t log_ins, size_t alpha_n, size_t log_alpha_d){ int i; size_t n; struct ht_muloa ht_muloa; struct heap_ht hht; n = pow_two_perror(log_ins); hht.ht = &ht_muloa; hht.alpha_n = alpha_n; hht.log_alpha_d = log_alpha_d; hht.init = ht_muloa_init_helper; hht.align = ht_muloa_align_helper; hht.insert = ht_muloa_insert_helper; hht.search = ht_muloa_search_helper; hht.remove = ht_muloa_remove_helper; hht.free = ht_muloa_free_helper; printf("Run a heap_{update, search} test with a ht_muloa " "hash table on noncontiguous uint_ptr elements\n"); for (i = 0; i < C_PTY_TYPES_COUNT; i++){ printf("\tnumber of elements: %lu\n" "\tload factor upper bound: %.4f\n" "\tpriority type: %s\n", TOLU(n), (float)alpha_n / pow_two_perror(log_alpha_d), C_PTY_TYPES[i]); update_search(n, C_PTY_SIZES[i], sizeof(struct uint_ptr *), &hht, C_NEW_PTY_ARR[i], new_uint_ptr, C_CMP_PTY_ARR[i], cmp_uint_ptr, rdc_uint_ptr, free_uint_ptr); } } /** Helper functions for heap_{push, pop, free} tests. */ void push_ptys_elts(struct heap *h, const void *pty_elts, size_t count, int *res){ size_t half_count; size_t n = h->num_elts; const void *p = NULL, *p_start = NULL, *p_end = NULL; clock_t t_first, t_second; half_count = count >> 1; /* count > 0 */ p_start = pty_elts; p_end = ptr(pty_elts, half_count, h->pair_size); t_first = clock(); for (p = p_start; p != p_end; p = (char *)p + h->pair_size){ heap_push(h, p, (char *)p + h->elt_offset); } t_first = clock() - t_first; p_start = ptr(pty_elts, half_count, h->pair_size); p_end = ptr(pty_elts, count, h->pair_size); t_second = clock(); for (p = p_start; p != p_end; p = (char *)p + h->pair_size){ heap_push(h, p, (char *)p + h->elt_offset); } t_second = clock() - t_second; printf("\t\tpush 1/2 elements: " "%.4f seconds\n", (float)t_first / CLOCKS_PER_SEC); printf("\t\tpush residual elements: " "%.4f seconds\n", (float)t_second / CLOCKS_PER_SEC); *res *= (h->num_elts == n + count); } void push_rev_ptys_elts(struct heap *h, const void *pty_elts, size_t count, int *res){ const void *p = NULL, *p_start = NULL, *p_end = NULL; size_t half_count; size_t n = h->num_elts; clock_t t_first, t_second; half_count = count >> 1; /* backwards pointer iteration; count > 0 */ p_start = ptr(pty_elts, count - 1, h->pair_size); p_end = ptr(pty_elts, half_count, h->pair_size); t_first = clock(); for (p = p_start; p != p_end; p = (char *)p - h->pair_size){ heap_push(h, p, (char *)p + h->elt_offset); } t_first = clock() - t_first; p_start = ptr(pty_elts, half_count, h->pair_size); p_end = pty_elts; t_second = clock(); for (p = p_start; p >= p_end; p = (char *)p - h->pair_size){ heap_push(h, p, (char *)p + h->elt_offset); } t_second = clock() - t_second; printf("\t\tpush 1/2 elements, rev. pty order: " "%.4f seconds\n", (float)t_first / CLOCKS_PER_SEC); printf("\t\tpush residual elements, rev. pty order: " "%.4f seconds\n", (float)t_second / CLOCKS_PER_SEC); *res *= (h->num_elts == n + count); } void pop_ptys_elts(struct heap *h, const void *pty_elts, size_t count, int (*cmp_pty)(const void *, const void *), int (*cmp_elt)(const void *, const void *), int *res){ size_t i, half_count; size_t n = h->num_elts; void *p = NULL, *p_start = NULL, *p_end = NULL; void *pop_pty_elts = NULL; clock_t t_first, t_second; half_count = count >> 1; /* count > 0 */ pop_pty_elts = malloc_perror(count, h->pair_size); p_start = pop_pty_elts; p_end = ptr(pop_pty_elts, half_count, h->pair_size); t_first = clock(); for (p = p_start; p != p_end; p = (char *)p + h->pair_size){ heap_pop(h, p, (char *)p + h->elt_offset); } t_first = clock() - t_first; p_start = ptr(pop_pty_elts, half_count, h->pair_size); p_end = ptr(pop_pty_elts, count, h->pair_size); t_second = clock(); for (p = p_start; p != p_end; p = (char *)p + h->pair_size){ heap_pop(h, p, (char *)p + h->elt_offset); } t_second = clock() - t_second; *res *= (h->num_elts == n - count); for (i = 0; i < count; i++){ if (i == 0){ *res *= (cmp_elt((char *)ptr(pop_pty_elts, i, h->pair_size) + h->elt_offset, (char *)ptr(pty_elts, i, h->pair_size) + h->elt_offset) == 0); }else{ *res *= (cmp_pty(ptr(pop_pty_elts, i, h->pair_size), ptr(pop_pty_elts, i - 1, h->pair_size)) >= 0); *res *= (cmp_elt((char *)ptr(pop_pty_elts, i, h->pair_size) + h->elt_offset, (char *)ptr(pty_elts, i, h->pair_size) + h->elt_offset) == 0); } } printf("\t\tpop 1/2 elements: " "%.4f seconds\n", (float)t_first / CLOCKS_PER_SEC); printf("\t\tpop residual elements: " "%.4f seconds\n", (float)t_second / CLOCKS_PER_SEC); free(pop_pty_elts); pop_pty_elts = NULL; } void free_heap(struct heap *h){ clock_t t; t = clock(); heap_free(h); t = clock() - t; printf("\t\tfree time: " "%.4f seconds\n", (float)t / CLOCKS_PER_SEC); } /** Helper functions for heap_{update, search} tests. */ void update_ptys_elts(struct heap *h, const void *pty_elts, size_t count, int *res){ size_t half_count = count >> 1; size_t n = h->num_elts; const void *p = NULL, *p_start = NULL, *p_end = NULL; clock_t t_first, t_second; p_start = pty_elts; p_end = ptr(pty_elts, half_count, h->pair_size); t_first = clock(); for (p = p_start; p != p_end; p = (char *)p + h->pair_size){ heap_update(h, p, (char *)p + h->elt_offset); } t_first = clock() - t_first; *res *= (h->num_elts == n); p_start = ptr(pty_elts, half_count, h->pair_size); p_end = ptr(pty_elts, count, h->pair_size); t_second = clock(); for (p = p_start; p != p_end; p = (char *)p + h->pair_size){ heap_update(h, p, (char *)p + h->elt_offset); } t_second = clock() - t_second; printf("\t\tupdate 1/2 elements: " "%.4f seconds\n", (float)t_first / CLOCKS_PER_SEC); printf("\t\tupdate residual elements: " "%.4f seconds\n", (float)t_second / CLOCKS_PER_SEC); *res *= (h->num_elts == n); } void search_ptys_elts(const struct heap *h, const void *pty_elts, const void *not_heap_elts, size_t count, int *res){ size_t n = h->num_elts; void *rp = NULL; const void *p = NULL, *p_start = NULL, *p_end = NULL; clock_t t_heap, t_not_heap; p_start = pty_elts; p_end = ptr(pty_elts, count, h->pair_size); t_heap = clock(); for (p = p_start; p != p_end; p = (char *)p + h->pair_size){ rp = heap_search(h, (char *)p + h->elt_offset); } t_heap = clock() - t_heap; for (p = p_start; p != p_end; p = (char *)p + h->pair_size){ rp = heap_search(h, (char *)p + h->elt_offset); *res *= (rp != NULL); } *res *= (h->num_elts == n); p_start = not_heap_elts; p_end = ptr(not_heap_elts, count, h->elt_size); t_not_heap = clock(); for (p = p_start; p != p_end; p = (char *)p + h->elt_size){ rp = heap_search(h, p); } t_not_heap = clock() - t_not_heap; for (p = p_start; p != p_end; p = (char *)p + h->elt_size){ rp = heap_search(h, p); *res *= (rp == NULL); } printf("\t\tin heap search: " "%.4f seconds\n", (float)t_heap / CLOCKS_PER_SEC); printf("\t\tnot in heap search: " "%.4f seconds\n", (float)t_not_heap / CLOCKS_PER_SEC); } /** Helper functions for heap_{push, pop, free} and heap_{update, search} tests that are used in the upper-level test routines. */ void push_pop_free(size_t num_ins, size_t pty_size, size_t elt_size, const struct heap_ht *hht, void (*new_pty)(void *, size_t), void (*new_elt)(void *, size_t), int (*cmp_pty)(const void *, const void *), int (*cmp_elt)(const void *, const void *), size_t (*rdc_elt)(const void *), void (*free_elt)(void *)){ int res = 1; size_t i; void *pty_elts = NULL; struct heap h; heap_init(&h, pty_size, elt_size, C_H_MIN_NUM, hht, cmp_pty, cmp_elt, rdc_elt, free_elt); /* num_ins > 0 */ pty_elts = malloc_perror(num_ins, h.pair_size); for (i = 0; i < num_ins; i++){ new_pty(ptr(pty_elts, i, h.pair_size), i); /* no decrease with i */ new_elt((char *)ptr(pty_elts, i, h.pair_size) + h.elt_offset, i); } push_ptys_elts(&h, pty_elts, num_ins, &res); pop_ptys_elts(&h, pty_elts, num_ins, cmp_pty, cmp_elt, &res); push_rev_ptys_elts(&h, pty_elts, num_ins, &res); pop_ptys_elts(&h, pty_elts, num_ins, cmp_pty, cmp_elt, &res); push_ptys_elts(&h, pty_elts, num_ins, &res); free_heap(&h); printf("\t\torder correctness: "); print_test_result(res); free(pty_elts); pty_elts = NULL; } void update_search(size_t num_ins, size_t pty_size, size_t elt_size, const struct heap_ht *hht, void (*new_pty)(void *, size_t), void (*new_elt)(void *, size_t), int (*cmp_pty)(const void *, const void *), int (*cmp_elt)(const void *, const void *), size_t (*rdc_elt)(const void *), void (*free_elt)(void *)){ int res = 1; size_t i; void *pty_elts = NULL, *pty_rev_elts = NULL, *not_heap_elts = NULL; struct heap h; heap_init(&h, pty_size, elt_size, C_H_MIN_NUM, hht, cmp_pty, cmp_elt, rdc_elt, free_elt); /* num_ins > 0 */ pty_elts = malloc_perror(num_ins, h.pair_size); pty_rev_elts = malloc_perror(num_ins, h.pair_size); not_heap_elts = malloc_perror(num_ins, elt_size); for (i = 0; i < num_ins; i++){ new_pty(ptr(pty_elts, i, h.pair_size), i); /* no decrease with i */ new_elt((char *)ptr(pty_elts, i, h.pair_size) + h.elt_offset, i); new_elt(ptr(not_heap_elts, i, elt_size), num_ins + i); } for (i = 0; i < num_ins; i++){ new_pty(ptr(pty_rev_elts, i, h.pair_size), i); /* no decrease with i */ memcpy((char *)ptr(pty_rev_elts, i, h.pair_size) + h.elt_offset, (char *)ptr(pty_elts, num_ins - 1 - i, h.pair_size) + h.elt_offset, elt_size); } push_ptys_elts(&h, pty_rev_elts, num_ins, &res); update_ptys_elts(&h, pty_elts, num_ins, &res); search_ptys_elts(&h, pty_elts, not_heap_elts, num_ins, &res); pop_ptys_elts(&h, pty_elts, num_ins, cmp_pty, cmp_elt, &res); free_heap(&h); printf("\t\torder correctness: "); print_test_result(res); if (free_elt != NULL){ for (i = 0; i < num_ins; i++){ free_elt((char *)ptr(pty_elts, i, h.pair_size) + h.elt_offset); free_elt(ptr(not_heap_elts, i, elt_size)); } } free(pty_elts); free(pty_rev_elts); free(not_heap_elts); pty_elts = NULL; pty_rev_elts = NULL; not_heap_elts = NULL; } /** Computes a pointer to the ith element in the block of elements. */ void *ptr(const void *block, size_t i, size_t size){ return (void *)((char *)block + i * size); } /** Prints a test result. */ void print_test_result(int res){ if (res){ printf("SUCCESS\n"); }else{ printf("FAILURE\n"); } } int main(int argc, char *argv[]){ int i; size_t *args = NULL; if (argc > C_ARGC_ULIMIT){ fprintf(stderr, "USAGE:\n%s", C_USAGE); exit(EXIT_FAILURE); } args = malloc_perror(C_ARGC_ULIMIT - 1, sizeof(size_t)); memcpy(args, C_ARGS_DEF, (C_ARGC_ULIMIT - 1) * sizeof(size_t)); for (i = 1; i < argc; i++){ args[i - 1] = atoi(argv[i]); } if (args[0] > C_FULL_BIT - 2 || args[1] < 1 || args[2] > C_FULL_BIT - 1 || args[3] < 1 || args[4] > C_FULL_BIT - 1 || args[3] > pow_two_perror(args[4]) || args[5] > 1 || args[6] > 1 || args[7] > 1 || args[8] > 1){ fprintf(stderr, "USAGE:\n%s", C_USAGE); exit(EXIT_FAILURE); } if (args[5]){ run_push_pop_free_divchn_uint_test(args[0], args[1], args[2]); run_push_pop_free_divchn_uint_ptr_test(args[0], args[1], args[2]); } if (args[6]){ run_update_search_divchn_uint_test(args[0], args[1], args[2]); run_update_search_divchn_uint_ptr_test(args[0], args[1], args[2]); } if (args[7]){ run_push_pop_free_muloa_uint_test(args[0], args[3], args[4]); run_push_pop_free_muloa_uint_ptr_test(args[0], args[3], args[4]); } if (args[8]){ run_update_search_muloa_uint_test(args[0], args[3], args[4]); run_update_search_muloa_uint_ptr_test(args[0], args[3], args[4]); } free(args); args = NULL; return 0; }
alfin3/graph-algorithms
data-structures/ht-muloa/ht-muloa-test.c
/** ht-muloa-test.c Tests of a hash table with generic contiguous keys and generic contiguous and non-contiguous elements.The implementation is based on a multiplication method for hashing and an open addressing method for resolving collisions. The following command line arguments can be used to customize tests: ht-muloa-test [0, size_t width - 1) : i s.t. # inserts = 2**i [0, size_t width) : a given k = sizeof(size_t) [0, size_t width) : b s.t. k * 2**a <= key size <= k * 2**b > 0 : c > 0 : d > 0 : e log base 2 s.t. c <= d <= 2**e > 0 : f s.t. c / 2**e <= load factor bound <= d / 2**e, in f steps [0, 1] : on/off insert search uint test [0, 1] : on/off remove delete uint test [0, 1] : on/off insert search uint_ptr test [0, 1] : on/off remove delete uint_ptr test [0, 1] : on/off corner cases test usage examples: ./ht-muloa-test ./ht-muloa-test 18 ./ht-muloa-test 17 5 6 ./ht-muloa-test 19 0 2 3000 4000 15 10 ./ht-muloa-test 19 0 2 3000 4000 15 10 1 1 0 0 0 ht-muloa-test can be run with any subset of command line arguments in the above-defined order. If the (i + 1)th argument is specified then the ith argument must be specified for i >= 0. Default values are used for the unspecified arguments according to the C_ARGS_DEF array. The implementation does not use stdint.h and is portable under C89/C90 and C99 with the only requirement that the width of size_t is greater or equal to 16, less than 2040, and is even. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <limits.h> #include <time.h> #include "ht-muloa.h" #include "utilities-mem.h" #include "utilities-mod.h" #include "utilities-lim.h" /** Generate random numbers in a portable way for test purposes only; rand() in the Linux C Library uses the same generator as random(), which may not be the case on older rand() implementations, and on current implementations on different systems. */ #define RGENS_SEED() do{srand(time(NULL));}while (0) #define RANDOM() (rand()) /* [0, RAND_MAX] */ #define DRAND() ((double)rand() / RAND_MAX) /* [0.0, 1.0] */ #define TOLU(i) ((unsigned long int)(i)) /* printing size_t under C89/C90 */ /* input handling */ const char *C_USAGE = "ht-muloa-test\n" "[0, size_t width - 1) : i s.t. # inserts = 2**i\n" "[0, size_t width) : a given k = sizeof(size_t)\n" "[0, size_t width) : b s.t. k * 2**a <= key size <= k * 2**b\n" "> 0 : c\n" "> 0 : d\n" "> 0 : e log base 2 s.t. c <= d <= 2**e\n" "> 0 : f s.t. c / 2**e <= load factor bound <= d / 2**e, in f steps\n" "[0, 1] : on/off insert search uint test\n" "[0, 1] : on/off remove delete uint test\n" "[0, 1] : on/off insert search uint_ptr test\n" "[0, 1] : on/off remove delete uint_ptr test\n" "[0, 1] : on/off corner cases test\n"; const int C_ARGC_ULIMIT = 13; const size_t C_ARGS_DEF[12] = {14u, 0u, 2u, 3277u, 32768u, 15u, 8u, 1u, 1u, 1u, 1u, 1u}; const size_t C_SIZE_ULIMIT = (size_t)-1; const size_t C_FULL_BIT = PRECISION_FROM_ULIMIT((size_t)-1); /* corner cases test */ const unsigned char C_CORNER_KEY_A = 2u; const unsigned char C_CORNER_KEY_B = 1u; const size_t C_CORNER_KEY_SIZE = sizeof(unsigned char); const size_t C_CORNER_HT_COUNT = 2048u; const size_t C_CORNER_ALPHA_N = 33u; const size_t C_CORNER_LOG_ALPHA_D = 15u; /* lf bound is 33/32768 */ void insert_search_free(size_t num_ins, size_t key_size, size_t elt_size, size_t elt_alignment, size_t alpha_n, size_t log_alpha_d, void (*new_elt)(void *, size_t), size_t (*val_elt)(const void *), void (*free_elt)(void *)); void remove_delete(size_t num_ins, size_t key_size, size_t elt_size, size_t elt_alignment, size_t alpha, size_t log_alpha_d, void (*new_elt)(void *, size_t), size_t (*val_elt)(const void *), void (*free_elt)(void *)); void *ptr(const void *block, size_t i, size_t size); void print_test_result(int res); /** Test hash table operations on distinct contiguous keys and contiguous size_t elements across key sizes and load factor upper bounds. For test purposes a key is a random key_size block with the exception of a distinct non-random sizeof(size_t)-sized sub-block inside the key_size block. An element is an elt_size block of size sizeof(size_t) with a size_t value. Keys and elements are entirely copied into a hash table and free_key and free_elt are NULL. */ void new_uint(void *elt, size_t val){ size_t *s = elt; *s = val; } size_t val_uint(const void *elt){ return *(size_t *)elt; } /** Runs a ht_muloa_{insert, search, free} test on distinct keys and size_t elements across key sizes >= sizeof(size_t) and load factor upper bounds. */ void run_insert_search_free_uint_test(size_t log_ins, size_t log_key_start, size_t log_key_end, size_t alpha_n_start, size_t alpha_n_end, size_t log_alpha_d, size_t num_alpha_steps){ size_t i, j; size_t num_ins; size_t key_size; size_t elt_size = sizeof(size_t); size_t elt_alignment = sizeof(size_t); size_t step, rem; size_t alpha_n; num_ins = pow_two_perror(log_ins); step = (alpha_n_end - alpha_n_start) / num_alpha_steps; for (i = log_key_start; i <= log_key_end; i++){ alpha_n = alpha_n_start; rem = alpha_n_end - alpha_n_start - step * num_alpha_steps; key_size = sizeof(size_t) * pow_two_perror(i); printf("Run a ht_muloa_{insert, search, free} test on distinct " "%lu-byte keys and size_t elements\n", TOLU(key_size)); for (j = 0; j <= num_alpha_steps; j++){ printf("\tnumber of inserts: %lu, load factor upper bound: %.4f\n", TOLU(num_ins), (float)alpha_n / pow_two_perror(log_alpha_d)); insert_search_free(num_ins, key_size, elt_size, elt_alignment, alpha_n, log_alpha_d, new_uint, val_uint, NULL); alpha_n += (j < num_alpha_steps) * step + (rem > 0 && rem--); } } } /** Runs a ht_muloa_{remove, delete} test on distinct keys and size_t elements across key sizes >= sizeof(size_t) and load factor upper bounds. */ void run_remove_delete_uint_test(size_t log_ins, size_t log_key_start, size_t log_key_end, size_t alpha_n_start, size_t alpha_n_end, size_t log_alpha_d, size_t num_alpha_steps){ size_t i, j; size_t num_ins; size_t key_size; size_t elt_size = sizeof(size_t); size_t elt_alignment = sizeof(size_t); size_t step, rem; size_t alpha_n; num_ins = pow_two_perror(log_ins); step = (alpha_n_end - alpha_n_start) / num_alpha_steps; for (i = log_key_start; i <= log_key_end; i++){ alpha_n = alpha_n_start; rem = alpha_n_end - alpha_n_start - step * num_alpha_steps; key_size = sizeof(size_t) * pow_two_perror(i); printf("Run a ht_muloa_{remove, delete} test on distinct " "%lu-byte keys and size_t elements\n", TOLU(key_size)); for (j = 0; j <= num_alpha_steps; j++){ printf("\tnumber of inserts: %lu, load factor upper bound: %.4f\n", TOLU(num_ins), (float)alpha_n / pow_two_perror(log_alpha_d)); remove_delete(num_ins, key_size, elt_size, elt_alignment, alpha_n, log_alpha_d, new_uint, val_uint, NULL); alpha_n += (j < num_alpha_steps) * step + (rem > 0 && rem--); } } } /** Test hash table operations on distinct contiguous keys and noncontiguous uint_ptr elements across key sizes and load factor upper bounds. For test purposes a key is a random key_size block with the exception of a distinct non-random sizeof(size_t)-sized sub-block inside the key_size block. A key is fully copied into a hash table as a key_size block. Because an element is noncontiguous, a pointer to an element is copied as an elt_size block. free_key is NULL. An element-specific free_elt is necessary to delete an element. */ struct uint_ptr{ size_t *val; }; void new_uint_ptr(void *elt, size_t val){ struct uint_ptr **s = elt; *s = malloc_perror(1, sizeof(struct uint_ptr)); (*s)->val = malloc_perror(1, sizeof(size_t)); *((*s)->val) = val; } size_t val_uint_ptr(const void *elt){ struct uint_ptr **s = (struct uint_ptr **)elt; return *((*s)->val); } void free_uint_ptr(void *elt){ struct uint_ptr **s = elt; free((*s)->val); (*s)->val = NULL; free(*s); *s = NULL; } /** Runs a ht_muloa_{insert, search, free} test on distinct keys and noncontiguous uint_ptr elements across key sizes >= sizeof(size_t) and load factor upper bounds. */ void run_insert_search_free_uint_ptr_test(size_t log_ins, size_t log_key_start, size_t log_key_end, size_t alpha_n_start, size_t alpha_n_end, size_t log_alpha_d, size_t num_alpha_steps){ size_t i, j; size_t num_ins; size_t key_size; size_t elt_size = sizeof(struct uint_ptr *); size_t elt_alignment = sizeof(struct uint_ptr *); size_t step, rem; size_t alpha_n; num_ins = pow_two_perror(log_ins); step = (alpha_n_end - alpha_n_start) / num_alpha_steps; for (i = log_key_start; i <= log_key_end; i++){ alpha_n = alpha_n_start; rem = alpha_n_end - alpha_n_start - step * num_alpha_steps; key_size = sizeof(size_t) * pow_two_perror(i); printf("Run a ht_muloa_{insert, search, free} test on distinct " "%lu-byte keys and noncontiguous uint_ptr elements\n", TOLU(key_size)); for (j = 0; j <= num_alpha_steps; j++){ printf("\tnumber of inserts: %lu, load factor upper bound: %.4f\n", TOLU(num_ins), (float)alpha_n / pow_two_perror(log_alpha_d)); insert_search_free(num_ins, key_size, elt_size, elt_alignment, alpha_n, log_alpha_d, new_uint_ptr, val_uint_ptr, free_uint_ptr); alpha_n += (j < num_alpha_steps) * step + (rem > 0 && rem--); } } } /** Runs a ht_muloa_{remove, delete} test on distinct keys and noncontiguous uint_ptr elements across key sizes >= sizeof(size_t) and load factor upper bounds. */ void run_remove_delete_uint_ptr_test(size_t log_ins, size_t log_key_start, size_t log_key_end, size_t alpha_n_start, size_t alpha_n_end, size_t log_alpha_d, size_t num_alpha_steps){ size_t i, j; size_t num_ins; size_t key_size; size_t elt_size = sizeof(struct uint_ptr *); size_t elt_alignment = sizeof(struct uint_ptr *); size_t step, rem; size_t alpha_n; num_ins = pow_two_perror(log_ins); step = (alpha_n_end - alpha_n_start) / num_alpha_steps; for (i = log_key_start; i <= log_key_end; i++){ alpha_n = alpha_n_start; rem = alpha_n_end - alpha_n_start - step * num_alpha_steps; key_size = sizeof(size_t) * pow_two_perror(i); printf("Run a ht_muloa_{remove, delete} test on distinct " "%lu-byte keys and noncontiguous uint_ptr elements\n", TOLU(key_size)); for (j = 0; j <= num_alpha_steps; j++){ printf("\tnumber of inserts: %lu, load factor upper bound: %.4f\n", TOLU(num_ins), (float)alpha_n / pow_two_perror(log_alpha_d)); remove_delete(num_ins, key_size, elt_size, elt_alignment, alpha_n, log_alpha_d, new_uint_ptr, val_uint_ptr, free_uint_ptr); alpha_n += (j < num_alpha_steps) * step + (rem > 0 && rem--); } } } /** Helper functions for the ht_muloa_{insert, search, free} tests across key sizes and load factor upper bounds, on size_t and uint_ptr elements. */ void insert_keys_elts(struct ht_muloa *ht, const unsigned char *keys, const void *elts, size_t count, int *res){ size_t i; size_t n = ht->num_elts; size_t init_count = ht->count; const unsigned char *k = NULL; const void *e = NULL; clock_t t; k = keys; e = elts; t = clock(); for (i = 0; i < count; i++){ ht_muloa_insert(ht, k, e); k += ht->key_size; e = (char *)e + ht->elt_size; } t = clock() - t; if (init_count < ht->count){ printf("\t\tinsert w/ growth time " "%.4f seconds\n", (float)t / CLOCKS_PER_SEC); }else{ printf("\t\tinsert w/o growth time " "%.4f seconds\n", (float)t / CLOCKS_PER_SEC); } *res *= (ht->num_elts == n + count); } void search_in_ht(const struct ht_muloa *ht, const unsigned char *keys, const void *elts, size_t count, size_t (*val_elt)(const void *), int *res){ size_t i; size_t n = ht->num_elts; const unsigned char *k = NULL; const void *e = NULL; const void *elt = NULL; clock_t t; k = keys; t = clock(); for (i = 0; i < count; i++){ elt = ht_muloa_search(ht, k); k += ht->key_size; } k = keys; e = elts; t = clock() - t; for (i = 0; i < count; i++){ elt = ht_muloa_search(ht, k); *res *= (val_elt(e) == val_elt(elt)); k += ht->key_size; e = (char *)e + ht->elt_size; } printf("\t\tin ht search time: " "%.4f seconds\n", (float)t / CLOCKS_PER_SEC); *res *= (ht->num_elts == n); } void search_nin_ht(const struct ht_muloa *ht, const unsigned char *nin_keys, size_t count, int *res){ size_t i; size_t n = ht->num_elts; const unsigned char *k = NULL; const void *elt = NULL; clock_t t; k = nin_keys; t = clock(); for (i = 0; i < count; i++){ elt = ht_muloa_search(ht, k); k += ht->key_size; } k = nin_keys; t = clock() - t; for (i = 0; i < count; i++){ elt = ht_muloa_search(ht, k); *res *= (elt == NULL); k += ht->key_size; } printf("\t\tnot in ht search time: " "%.4f seconds\n", (float)t / CLOCKS_PER_SEC); *res *= (ht->num_elts == n); } void free_ht(struct ht_muloa *ht){ clock_t t; t = clock(); ht_muloa_free(ht); t = clock() - t; printf("\t\tfree time: " "%.4f seconds\n", (float)t / CLOCKS_PER_SEC); } void insert_search_free(size_t num_ins, size_t key_size, size_t elt_size, size_t elt_alignment, size_t alpha_n, size_t log_alpha_d, void (*new_elt)(void *, size_t), size_t (*val_elt)(const void *), void (*free_elt)(void *)){ int res = 1; size_t i, j; size_t val; unsigned char key_buf[sizeof(size_t)]; unsigned char *key = NULL; unsigned char *keys = NULL; unsigned char *nin_keys = NULL; void *elts = NULL; struct ht_muloa ht; keys = malloc_perror(num_ins, key_size); elts = malloc_perror(num_ins, elt_size); nin_keys = malloc_perror(num_ins, key_size); for (i = 0; i < num_ins; i++){ key = ptr(keys, i, key_size); for (j = 0; j < key_size - sizeof(size_t); j++){ *(unsigned char *)ptr(key, j, 1) = RANDOM(); /* mod 2**CHAR_BIT */ } memcpy(key_buf, &i, sizeof(size_t)); /* eff. type in key unchanged */ memcpy(ptr(key, key_size - sizeof(size_t), 1), key_buf, sizeof(size_t)); new_elt(ptr(elts, i, elt_size), i); } ht_muloa_init(&ht, key_size, elt_size, 0, alpha_n, log_alpha_d, NULL, NULL, NULL, NULL); insert_keys_elts(&ht, keys, elts, num_ins, &res); /* no dereferencing */ free_ht(&ht); ht_muloa_init(&ht, key_size, elt_size, num_ins, alpha_n, log_alpha_d, NULL, NULL, NULL, free_elt); ht_muloa_align(&ht, elt_alignment); insert_keys_elts(&ht, keys, elts, num_ins, &res); search_in_ht(&ht, keys, elts, num_ins, val_elt, &res); for (i = 0; i < num_ins; i++){ key = ptr(nin_keys, i, key_size); val = i + num_ins; for (j = 0; j < key_size - sizeof(size_t); j++){ *(unsigned char *)ptr(key, j, 1) = RANDOM(); /* mod 2**CHAR_BIT */ } memcpy(key_buf, &val, sizeof(size_t)); /* eff. type in key unchanged */ memcpy(ptr(key, key_size - sizeof(size_t), 1), key_buf, sizeof(size_t)); } search_nin_ht(&ht, nin_keys, num_ins, &res); free_ht(&ht); printf("\t\tsearch correctness: "); print_test_result(res); free(keys); free(elts); free(nin_keys); keys = NULL; elts = NULL; nin_keys = NULL; } /** Helper functions for the ht_muloa_{remove, delete} tests across key sizes and load factor upper bounds, on size_t and uint_ptr elements. */ void remove_key_elts(struct ht_muloa *ht, const unsigned char *keys, const void *elts, size_t count, size_t (*val_elt)(const void *), int *res){ size_t i; size_t n = ht->num_elts; size_t key_step_size = mul_sz_perror(2, ht->key_size); const unsigned char *k = NULL; const void *e = NULL; void *elt = NULL; clock_t t_first_half, t_second_half; elt = malloc_perror(1, ht->elt_size); k = keys; t_first_half = clock(); for (i = 0; i < count; i += 2){ /* count < SIZE_MAX */ k += (i > 0) * key_step_size; /* avoid UB in pointer increment */ ht_muloa_remove(ht, k, elt); /* noncontiguous element is still accessible from elts */ } t_first_half = clock() - t_first_half; *res *= (ht->num_elts == ((count & 1) ? (n - count / 2 - 1) : (n - count / 2))); k = keys; e = elts; for (i = 0; i < count; i++){ if (i & 1){ *res *= (val_elt(e) == val_elt(ht_muloa_search(ht, k))); }else{ *res *= (ht_muloa_search(ht, k) == NULL); } k += ht->key_size; e = (char *)e + ht->elt_size; } k = ptr(keys, 1, ht->key_size); /* 1 <= count */ t_second_half = clock(); for (i = 1; i < count; i += 2){ /* count < SIZE_MAX */ k += (i > 1) * key_step_size; /* avoid UB in pointer increment */ ht_muloa_remove(ht, k, elt); /* noncontiguous element is still accessible from elts */ } t_second_half = clock() - t_second_half; *res *= (ht->num_elts == 0); k = keys; for (i = 0; i < count; i++){ *res *= (ht_muloa_search(ht, k) == NULL); k += ht->key_size; } for (i = 0; i < ht->count; i++){ if (ht->key_elts[i] != NULL) *res *= (ht->key_elts[i]->fval == 1); } printf("\t\tremove 1/2 elements time: " "%.4f seconds\n", (float)t_first_half / CLOCKS_PER_SEC); printf("\t\tremove residual elements time: " "%.4f seconds\n", (float)t_second_half / CLOCKS_PER_SEC); free(elt); elt = NULL; } void delete_key_elts(struct ht_muloa *ht, const unsigned char *keys, const void *elts, size_t count, size_t (*val_elt)(const void *), int *res){ size_t i; size_t n = ht->num_elts; size_t key_step_size = mul_sz_perror(2, ht->key_size); const unsigned char *k = NULL; const void *e = NULL; clock_t t_first_half, t_second_half; k = keys; t_first_half = clock(); for (i = 0; i < count; i += 2){ /* count < SIZE_MAX */ k += (i > 0) * key_step_size; /* avoid UB in pointer increment */ ht_muloa_delete(ht, k); } t_first_half = clock() - t_first_half; *res *= (ht->num_elts == ((count & 1) ? (n - count / 2 - 1) : (n - count / 2))); k = keys; e = elts; for (i = 0; i < count; i++){ if (i & 1){ *res *= (val_elt(e) == val_elt(ht_muloa_search(ht, k))); }else{ *res *= (ht_muloa_search(ht, k) == NULL); } k += ht->key_size; e = (char *)e + ht->elt_size; } k = ptr(keys, 1, ht->key_size); /* 1 <= count */ t_second_half = clock(); for (i = 1; i < count; i += 2){ /* count < SIZE_MAX */ k += (i > 1) * key_step_size; /* avoid UB in pointer increment */ ht_muloa_delete(ht, k); } t_second_half = clock() - t_second_half; *res *= (ht->num_elts == 0); k = keys; for (i = 0; i < count; i++){ *res *= (ht_muloa_search(ht, k) == NULL); k += ht->key_size; } for (i = 0; i < ht->count; i++){ if (ht->key_elts[i] != NULL) *res *= (ht->key_elts[i]->fval == 1); } printf("\t\tdelete 1/2 elements time: " "%.4f seconds\n", (float)t_first_half / CLOCKS_PER_SEC); printf("\t\tdelete residual elements time: " "%.4f seconds\n", (float)t_second_half / CLOCKS_PER_SEC); } void remove_delete(size_t num_ins, size_t key_size, size_t elt_size, size_t elt_alignment, size_t alpha_n, size_t log_alpha_d, void (*new_elt)(void *, size_t), size_t (*val_elt)(const void *), void (*free_elt)(void *)){ int res = 1; size_t i, j; unsigned char key_buf[sizeof(size_t)]; unsigned char *key = NULL; unsigned char *keys = NULL; void *elts = NULL; struct ht_muloa ht; keys = malloc_perror(num_ins, key_size); elts = malloc_perror(num_ins, elt_size); for (i = 0; i < num_ins; i++){ key = ptr(keys, i, key_size); for (j = 0; j < key_size - sizeof(size_t); j++){ *(unsigned char *)ptr(key, j, 1) = RANDOM(); /* mod 2**CHAR_BIT */ } memcpy(key_buf, &i, sizeof(size_t)); /* eff. type in key unchanged */ memcpy(ptr(key, key_size - sizeof(size_t), 1), key_buf, sizeof(size_t)); new_elt(ptr(elts, i, elt_size), i); } ht_muloa_init(&ht, key_size, elt_size, 0, alpha_n, log_alpha_d, NULL, NULL, NULL, free_elt); ht_muloa_align(&ht, elt_alignment); insert_keys_elts(&ht, keys, elts, num_ins, &res); remove_key_elts(&ht, keys, elts, num_ins, val_elt, &res); insert_keys_elts(&ht, keys, elts, num_ins, &res); delete_key_elts(&ht, keys, elts, num_ins, val_elt, &res); free_ht(&ht); printf("\t\tremove and delete correctness: "); print_test_result(res); free(keys); free(elts); keys = NULL; elts = NULL; } /** Runs a corner cases test. */ void run_corner_cases_test(int log_ins){ int res = 1; size_t elt; size_t elt_size = sizeof(size_t); size_t elt_alignment = sizeof(size_t); size_t i, num_ins; struct ht_muloa ht; ht_muloa_init(&ht, C_CORNER_KEY_SIZE, elt_size, 0, C_CORNER_ALPHA_N, C_CORNER_LOG_ALPHA_D, NULL, NULL, NULL, NULL); ht_muloa_align(&ht, elt_alignment); num_ins = pow_two_perror(log_ins); printf("Run corner cases test --> "); for (i = 0; i < num_ins; i++){ elt = i; ht_muloa_insert(&ht, &C_CORNER_KEY_A, &elt); } res *= (ht.num_elts == 1 && *(size_t *)ht_muloa_search(&ht, &C_CORNER_KEY_A) == elt && ht_muloa_search(&ht, &C_CORNER_KEY_B) == NULL); ht_muloa_insert(&ht, &C_CORNER_KEY_B, &elt); res *= (ht.count == C_CORNER_HT_COUNT && ht.num_elts == 2 && *(size_t *)ht_muloa_search(&ht, &C_CORNER_KEY_A) == elt && *(size_t *)ht_muloa_search(&ht, &C_CORNER_KEY_B) == elt); ht_muloa_delete(&ht, &C_CORNER_KEY_A); res *= (ht.count == C_CORNER_HT_COUNT && ht.num_elts == 1 && ht_muloa_search(&ht, &C_CORNER_KEY_A) == NULL && *(size_t *)ht_muloa_search(&ht, &C_CORNER_KEY_B) == elt); ht_muloa_delete(&ht, &C_CORNER_KEY_B); res *= (ht.count == C_CORNER_HT_COUNT && ht.num_elts == 0 && ht_muloa_search(&ht, &C_CORNER_KEY_A) == NULL && ht_muloa_search(&ht, &C_CORNER_KEY_B) == NULL); print_test_result(res); free_ht(&ht); } /** Helper functions. */ /** Computes a pointer to the ith element in the block of elements. */ void *ptr(const void *block, size_t i, size_t size){ return (void *)((char *)block + i * size); } /** Prints a test result. */ void print_test_result(int res){ if (res){ printf("SUCCESS\n"); }else{ printf("FAILURE\n"); } } int main(int argc, char *argv[]){ int i; size_t *args = NULL; RGENS_SEED(); if (argc > C_ARGC_ULIMIT){ fprintf(stderr, "USAGE:\n%s", C_USAGE); exit(EXIT_FAILURE); } args = malloc_perror(C_ARGC_ULIMIT - 1, sizeof(size_t)); memcpy(args, C_ARGS_DEF, (C_ARGC_ULIMIT - 1) * sizeof(size_t)); for (i = 1; i < argc; i++){ args[i - 1] = atoi(argv[i]); } if (args[0] > C_FULL_BIT - 2 || args[1] > C_FULL_BIT - 1 || args[2] > C_FULL_BIT - 1 || args[1] > args[2] || args[3] < 1 || args[4] < 1 || args[5] > C_FULL_BIT - 1 || args[3] > args[4] || args[3] > pow_two_perror(args[5]) || args[4] > pow_two_perror(args[5]) || args[6] < 1 || args[7] < 1 || args[8] > 1 || args[9] > 1 || args[10] > 1 || args[11] > 1){ fprintf(stderr, "USAGE:\n%s", C_USAGE); exit(EXIT_FAILURE); }; if (args[7]) run_insert_search_free_uint_test(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); if (args[8]) run_remove_delete_uint_test(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); if (args[9]) run_insert_search_free_uint_ptr_test(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); if (args[10]) run_remove_delete_uint_ptr_test(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); if (args[11]) run_corner_cases_test(args[0]); free(args); args = NULL; return 0; }
alfin3/graph-algorithms
graph-algorithms/tsp/tsp.c
<filename>graph-algorithms/tsp/tsp.c /** tsp.c An exact solution of TSP without vertex revisiting on graphs with generic weights, including negative weights, with a hash table parameter. Vertices are indexed from 0. Edge weights are of any basic type (e.g. char, int, long, float, double), or are custom weights within a contiguous block (e.g. pair of 64-bit segments to address the potential overflow due to addition). The algorithm provides O(2^n n^2) assymptotic runtime, where n is the number of vertices in a tour, as well as tour existence detection. A bit array representation provides time and space efficient set membership and union operations over O(2^n) sets. The hash table parameter specifies a hash table used for set hashing operations, and enables the optimization of the associated space and time resources by choice of a hash table and its load factor upper bound. If NULL is passed as a hash table parameter value, a default hash table is used, which contains an array with a count that is equal to n * 2^n, where n is the number of vertices in the graph. If E >> V and V < sizeof(size_t) * CHAR_BIT, a default hash table may provide speed advantages by avoiding the computation of hash values. If V is larger and the graph is sparse, a non-default hash table may provide space advantages. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <limits.h> #include "tsp.h" #include "graph.h" #include "stack.h" #include "utilities-mem.h" typedef enum{FALSE, TRUE} boolean_t; typedef struct{ size_t num_vts; } context_t; typedef struct{ size_t key_size; size_t elt_size; size_t num_vts; boolean_t *key_present; void *elts; void (*free_elt)(void *); } ht_def_t; typedef struct{ size_t ix; /* index of the set element with a single set bit */ size_t bit; /* set element with a single set bit */ } ibit_t; static const size_t C_SET_ELT_SIZE = sizeof(size_t); static const size_t C_SET_ELT_BIT = CHAR_BIT * sizeof(size_t); /* set operations based on a bit array representation */ static void set_init(ibit_t *ibit, size_t n); static size_t *set_member(const ibit_t *ibit, const size_t *set); static void set_union(const ibit_t *ibit, size_t *set); /* default hash table operations */ static void ht_def_init(ht_def_t *ht, size_t key_size, size_t elt_size, void (*free_elt)(void *), void *context); static void ht_def_insert(ht_def_t *ht, const size_t *key, const void *elt); static void *ht_def_search(const ht_def_t *ht, const size_t *key); static void ht_def_remove(ht_def_t *ht, const size_t *key, void *elt); static void ht_def_free(ht_def_t *ht); /* auxiliary functions */ static void build_next(const adj_lst_t *a, stack_t *prev_s, stack_t *next_s, const tsp_ht_t *tht, void (*add_wt)(void *, const void *, const void *), int (*cmp_wt)(const void *, const void *)); static size_t pow_two(size_t k); static void fprintf_stderr_exit(const char *s, int line); /* functions for computing pointers */ static void *elt_ptr(const void *elts, size_t i, size_t elt_size); /** Copies to the block pointed to by dist the shortest tour length from start to start across all vertices without revisiting, if a tour exists. Returns 0 if a tour exists, otherwise returns 1. a : pointer to an adjacency list with at least one vertex start : start vertex for running the algorithm dist : pointer to a preallocated block of the size of a weight in the adjacency list tht : - NULL pointer, if a default hash table is used for set hashing operations; a default hash table contains an array with a count that is equal to n * 2^n, where n is the number of vertices in the adjacency list; the maximal n in a default hash table is system-dependent and is less than sizeof(size_t) * CHAR_BIT; if the allocation of a default hash table fails, the program terminates with an error message - a pointer to a set of parameters specifying a hash table used for set hashing operations; the size of a hash key is k * (1 + lowest # k-sized blocks s.t. # bits >= # vertices), where k = sizeof(size_t) add_wt : addition function which copies the sum of the weight values pointed to by the second and third arguments to the preallocated weight block pointed to by the first argument cmp_wt : comparison function which returns a negative integer value if the weight value pointed to by the first argument is less than the weight value pointed to by the second, a positive integer value if the weight value pointed to by the first argument is greater than the weight value pointed to by the second, and zero integer value if the two weight values are equal */ int tsp(const adj_lst_t *a, size_t start, void *dist, const tsp_ht_t *tht, void (*add_wt)(void *, const void *, const void *), int (*cmp_wt)(const void *, const void *)){ const char *p = NULL, *p_start = NULL, *p_end = NULL; size_t wt_size = a->wt_size; size_t set_count, set_size; size_t u, v; size_t i; size_t *prev_set = NULL; void *sum_wt = NULL; boolean_t final_dist_updated = FALSE; stack_t prev_s, next_s; ht_def_t ht_def; context_t context; tsp_ht_t tht_def; const tsp_ht_t *thtp = tht; set_count = a->num_vts / C_SET_ELT_BIT; if (a->num_vts % C_SET_ELT_BIT){ set_count++; } set_count++; /* + last reached vertex representation */ set_size = set_count * C_SET_ELT_SIZE; prev_set = calloc_perror(1, set_size); sum_wt = malloc_perror(1, wt_size); prev_set[0] = start; memset(dist, 0, wt_size); stack_init(&prev_s, 1, set_size, NULL); stack_push(&prev_s, prev_set); if (thtp == NULL){ context.num_vts = a->num_vts; tht_def.ht = &ht_def; tht_def.context = &context; tht_def.init = (tsp_ht_init)ht_def_init; tht_def.insert = (tsp_ht_insert)ht_def_insert; tht_def.search = (tsp_ht_search)ht_def_search; tht_def.remove = (tsp_ht_remove)ht_def_remove; tht_def.free = (tsp_ht_free)ht_def_free; thtp = &tht_def; } thtp->init(thtp->ht, set_size, wt_size, NULL, thtp->context); thtp->insert(thtp->ht, prev_set, dist); for (i = 0; i < a->num_vts - 1; i++){ stack_init(&next_s, 1, set_size, NULL); build_next(a, &prev_s, &next_s, thtp, add_wt, cmp_wt); stack_free(&prev_s); prev_s = next_s; if (prev_s.num_elts == 0){ /* no progress made */ stack_free(&prev_s); thtp->free(thtp->ht); free(prev_set); free(sum_wt); thtp = NULL; prev_set = NULL; sum_wt = NULL; return 1; } } /* compute the return to start */ while (prev_s.num_elts > 0){ stack_pop(&prev_s, prev_set); u = prev_set[0]; p_start = a->vt_wts[u]->elts; p_end = p_start + a->vt_wts[u]->num_elts * a->pair_size; for (p = p_start; p != p_end; p += a->pair_size){ v = *(const size_t *)p; if (v == start){ add_wt(sum_wt, thtp->search(thtp->ht, prev_set), p + a->offset); if (!final_dist_updated){ memcpy(dist, sum_wt, wt_size); final_dist_updated = TRUE; }else if (cmp_wt(dist, sum_wt) > 0){ memcpy(dist, sum_wt, wt_size); } } } } stack_free(&prev_s); thtp->free(thtp->ht); free(prev_set); free(sum_wt); thtp = NULL; prev_set = NULL; sum_wt = NULL; if (!final_dist_updated && a->num_vts > 1) return 1; return 0; } /** Builds reachable sets from previous sets and updates a hash table mapping a set to a distance. */ static void build_next(const adj_lst_t *a, stack_t *prev_s, stack_t *next_s, const tsp_ht_t *tht, void (*add_wt)(void *, const void *, const void *), int (*cmp_wt)(const void *, const void *)){ const char *p = NULL, *p_start = NULL, *p_end = NULL; size_t wt_size = a->wt_size; size_t set_size = prev_s->elt_size; size_t u, v; size_t *prev_set = NULL, *next_set = NULL; void *prev_wt = NULL, *next_wt = NULL, *sum_wt = NULL; ibit_t ibit; prev_set = malloc_perror(1, set_size); next_set = malloc_perror(1, set_size); prev_wt = malloc_perror(1, wt_size); sum_wt = malloc_perror(1, wt_size); while (prev_s->num_elts > 0){ stack_pop(prev_s, prev_set); tht->remove(tht->ht, prev_set, prev_wt); u = prev_set[0]; p_start = a->vt_wts[u]->elts; p_end = p_start + a->vt_wts[u]->num_elts * a->pair_size; for (p = p_start; p != p_end; p += a->pair_size){ v = *(const size_t *)p; set_init(&ibit, v); if (set_member(&ibit, &prev_set[1]) == NULL){ memcpy(next_set, prev_set, set_size); next_set[0] = v; set_init(&ibit, u); set_union(&ibit, &next_set[1]); add_wt(sum_wt, prev_wt, p + a->offset); next_wt = tht->search(tht->ht, next_set); if (next_wt == NULL){ tht->insert(tht->ht, next_set, sum_wt); stack_push(next_s, next_set); }else if (cmp_wt(next_wt, sum_wt) > 0){ tht->insert(tht->ht, next_set, sum_wt); } } } } free(prev_set); free(next_set); free(prev_wt); free(sum_wt); prev_set = NULL; next_set = NULL; prev_wt = NULL; sum_wt = NULL; } /** Set operations based on a bit array representation. */ static void set_init(ibit_t *ibit, size_t n){ ibit->ix = n / C_SET_ELT_BIT; ibit->bit = 1; ibit->bit <<= n % C_SET_ELT_BIT; } static size_t *set_member(const ibit_t *ibit, const size_t *set){ if (set[ibit->ix] & ibit->bit){ return (size_t *)(&set[ibit->ix]); }else{ return NULL; } } static void set_union(const ibit_t *ibit, size_t *set){ set[ibit->ix] |= ibit->bit; } /** Default hash table operations. */ static void ht_def_init(ht_def_t *ht, size_t key_size, size_t elt_size, void (*free_elt)(void *), void *context){ context_t *c = context; if (c->num_vts >= C_SET_ELT_BIT){ fprintf_stderr_exit("default hash table allocation failed", __LINE__); } ht->key_size = key_size; ht->elt_size = elt_size; ht->num_vts = c->num_vts; ht->key_present = calloc_perror(mul_sz_perror(c->num_vts, pow_two(c->num_vts)), sizeof(boolean_t)); ht->elts = malloc_perror(mul_sz_perror(c->num_vts, pow_two(c->num_vts)), elt_size); ht->free_elt = free_elt; } static void ht_def_insert(ht_def_t *ht, const size_t *key, const void *elt){ size_t ix = key[0] + ht->num_vts * key[1]; ht->key_present[ix] = TRUE; memcpy(elt_ptr(ht->elts, ix, ht->elt_size), elt, ht->elt_size); } static void *ht_def_search(const ht_def_t *ht, const size_t *key){ size_t ix = key[0] + ht->num_vts * key[1]; if (ht->key_present[ix]){ return elt_ptr(ht->elts, ix, ht->elt_size); }else{ return NULL; } } static void ht_def_remove(ht_def_t *ht, const size_t *key, void *elt){ size_t ix = key[0] + ht->num_vts * key[1]; ht->key_present[ix] = FALSE; memcpy(elt, elt_ptr(ht->elts, ix, ht->elt_size), ht->elt_size); } static void ht_def_free(ht_def_t *ht){ size_t i; if (ht->free_elt != NULL){ for (i = 0; i < ht->num_vts * pow_two(ht->num_vts); i++){ if (ht->key_present[i]){ ht->free_elt(elt_ptr(ht->elts, i, ht->elt_size)); } } } free(ht->key_present); free(ht->elts); ht->key_present = NULL; ht->elts = NULL; } /** Returns the kth power of 2, where 0 <= k < C_SET_ELT_BIT. */ static size_t pow_two(size_t k){ size_t ret = 1; return ret << k; } /** Prints an error message and exits. */ static void fprintf_stderr_exit(const char *s, int line){ fprintf(stderr, "%s in %s at line %d\n", s, __FILE__, line); exit(EXIT_FAILURE); } /** Computes a pointer to an entry in the array of elements in a default hash table. */ static void *elt_ptr(const void *elts, size_t i, size_t elt_size){ return (void *)((char *)elts + i * elt_size); }
alfin3/graph-algorithms
data-structures/stack/stack-test.c
<filename>data-structures/stack/stack-test.c<gh_stars>0 /** stack-test.c Tests of a generic stack. The following command line arguments can be used to customize tests: stack-test [0, ulong width) : i s.t. # inserts = 2**i [0, ulong width) : i s.t. # inserts = 2**i in uchar stack test [0, 1] : on/off push pop first free uint test [0, 1] : on/off push pop first free uint_ptr (noncontiguous) test [0, 1] : on/off uchar stack test usage examples: ./stack-test ./stack-test 23 ./stack-test 24 31 ./stack-test 24 31 0 0 1 stack-test can be run with any subset of command line arguments in the above-defined order. If the (i + 1)th argument is specified then the ith argument must be specified for i >= 0. Default values are used for the unspecified arguments according to the C_ARGS_DEF array. The implementation of tests does not use stdint.h and is portable under C89/C90 and C99. The tests require that: - size_t and clock_t are convertible to double, - size_t can represent values upto 65535 for default values, and upto ULONG_MAX (>= 4294967295) otherwise, - the widths of the unsigned integral types are less than 2040 and even. TODO: add portable size_t printing */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <limits.h> #include <time.h> #include "stack.h" #include "utilities-mem.h" #include "utilities-mod.h" #include "utilities-lim.h" #define TOLU(i) ((unsigned long int)(i)) /* printing size_t under C89/C90 */ /* input handling */ const char *C_USAGE = "stack-test \n" "[0, ulong width) : i s.t. # inserts = 2**i\n" "[0, ulong width) : i s.t. # inserts = 2**i in uchar stack test\n" "[0, 1] : on/off push pop first free uint test\n" "[0, 1] : on/off push pop first free uint_ptr (noncontiguous) test\n" "[0, 1] : on/off uchar stack test\n"; const int C_ARGC_ULIMIT = 6; const size_t C_ARGS_DEF[5] = {14, 15, 1, 1, 1}; const size_t C_ULONG_BIT = PRECISION_FROM_ULIMIT((unsigned long)-1); /* tests */ const unsigned char C_UCHAR_ULIMIT = (unsigned char)-1; const size_t C_START_VAL = 0; /* <= # inserts */ void print_test_result(int res); /** Run tests of a stack of size_t elements. A pointer to an element is passed as elt in stack_push and the size_t element is copied onto the stack. NULL as free_elt is sufficient to free the stack. */ void uint_push_pop_helper(struct stack *s, size_t start_val, size_t num_ins); void run_uint_push_pop_test(size_t log_ins){ size_t num_ins; size_t start_val = C_START_VAL; struct stack s; num_ins = pow_two_perror(log_ins); stack_init(&s, sizeof(size_t), NULL); printf("Run a stack_{push, pop} test on %lu size_t elements\n", TOLU(num_ins)); printf("\tinitial count: %lu, max count: %lu\n", TOLU(s.init_count), TOLU(s.max_count)); uint_push_pop_helper(&s, start_val, num_ins); stack_free(&s); stack_init(&s, sizeof(size_t), NULL); stack_bound(&s, 1, num_ins); printf("\tinitial count: %lu, max count: %lu\n", TOLU(s.init_count), TOLU(s.max_count)); uint_push_pop_helper(&s, start_val, num_ins); stack_free(&s); stack_init(&s, sizeof(size_t), NULL); stack_bound(&s, num_ins, num_ins); printf("\tinitial count: %lu, max count: %lu\n", TOLU(s.init_count), TOLU(s.max_count)); uint_push_pop_helper(&s, start_val, num_ins); stack_free(&s); } void uint_push_pop_helper(struct stack *s, size_t start_val, size_t num_ins){ int res = 1; size_t i; size_t *pushed = NULL, *popped = NULL; clock_t t_push, t_pop; pushed = malloc_perror(num_ins, sizeof(size_t)); popped = malloc_perror(num_ins, sizeof(size_t)); for (i = 0; i < num_ins; i++){ pushed[i] = start_val + i; } t_push = clock(); for (i = 0; i < num_ins; i++){ stack_push(s, &pushed[i]); } t_push = clock() - t_push; t_pop = clock(); for (i = 0; i < num_ins; i++){ stack_pop(s, &popped[i]); } t_pop = clock() - t_pop; res *= (s->num_elts == 0); res *= (s->count >= num_ins); for (i = 0; i < num_ins; i++){ res *= (popped[i] == num_ins - 1 - i + start_val); } printf("\t\tpush time: %.4f seconds\n", (double)t_push / CLOCKS_PER_SEC); printf("\t\tpop time: %.4f seconds\n", (double)t_pop / CLOCKS_PER_SEC); printf("\t\tcorrectness: "); print_test_result(res); free(pushed); free(popped); pushed = NULL; popped = NULL; } void run_uint_first_test(size_t log_ins){ int res = 1; size_t i; size_t num_ins; size_t start_val = C_START_VAL; size_t pushed, popped; struct stack s; num_ins = pow_two_perror(log_ins); stack_init(&s, sizeof(size_t), NULL); printf("Run a stack_first test on %lu size_t elements\n", TOLU(num_ins)); for (i = 0; i < num_ins; i++){ if (s.num_elts == 0){ res *= (stack_first(&s) == NULL); } pushed = start_val + i; stack_push(&s, &pushed); res *= (*(size_t *)stack_first(&s) == pushed); } for (i = 0; i < num_ins; i++){ res *= (*(size_t *)stack_first(&s) == num_ins - 1 - i + start_val); stack_pop(&s, &popped); if (s.num_elts == 0){ res *= (stack_first(&s) == NULL); } } res *= (s.num_elts == 0); res *= (s.count >= num_ins); printf("\t\tcorrectness: "); print_test_result(res); stack_free(&s); } void run_uint_free_test(size_t log_ins){ size_t i; size_t num_ins; struct stack s; clock_t t; num_ins = pow_two_perror(log_ins); stack_init(&s, sizeof(size_t), NULL); printf("Run a stack_free test on %lu size_t elements\n", TOLU(num_ins)); for (i = 0; i < num_ins; i++){ stack_push(&s, &i); } t = clock(); stack_free(&s); t = clock() - t; printf("\t\tfree time: %.4f seconds\n", (double)t / CLOCKS_PER_SEC); } /** Run tests of a stack of uint_ptr elements. A pointer to a pointer to an uint_ptr element is passed as elt in stack_push and the pointer to the uint_ptr element is copied onto the stack. A uint_ptr- specific free_elt, taking a pointer to a pointer to an element as its parameter, is necessary to free the stack. */ struct uint_ptr{ size_t *val; }; void free_uint_ptr(void *a){ struct uint_ptr **s = a; free((*s)->val); (*s)->val = NULL; free(*s); *s = NULL; } void uint_ptr_push_pop_helper(struct stack *s, size_t start_val, size_t num_ins); void run_uint_ptr_push_pop_test(size_t log_ins){ size_t num_ins; size_t start_val = C_START_VAL; struct stack s; num_ins = pow_two_perror(log_ins); stack_init(&s, sizeof(struct uint_ptr *), free_uint_ptr); printf("Run a stack_{push, pop} test on %lu noncontiguous uint_ptr " "elements\n", TOLU(num_ins)); printf("\tinitial count: %lu, max count: %lu\n", TOLU(s.init_count), TOLU(s.max_count)); uint_ptr_push_pop_helper(&s, start_val, num_ins); stack_free(&s); stack_init(&s, sizeof(struct uint_ptr *), free_uint_ptr); stack_bound(&s, 1, num_ins); printf("\tinitial count: %lu, max count: %lu\n", TOLU(s.init_count), TOLU(s.max_count)); uint_ptr_push_pop_helper(&s, start_val, num_ins); stack_free(&s); stack_init(&s, sizeof(struct uint_ptr *), free_uint_ptr); stack_bound(&s, num_ins, num_ins); printf("\tinitial count: %lu, max count: %lu\n", TOLU(s.init_count), TOLU(s.max_count)); uint_ptr_push_pop_helper(&s, start_val, num_ins); stack_free(&s); } void uint_ptr_push_pop_helper(struct stack *s, size_t start_val, size_t num_ins){ int res = 1; size_t i; struct uint_ptr **pushed = NULL, **popped = NULL; clock_t t_push, t_pop; pushed = calloc_perror(num_ins, sizeof(struct uint_ptr *)); popped = calloc_perror(num_ins, sizeof(struct uint_ptr *)); for (i = 0; i < num_ins; i++){ pushed[i] = malloc_perror(1, sizeof(struct uint_ptr)); pushed[i]->val = malloc_perror(1, sizeof(size_t)); *(pushed[i]->val) = start_val + i; } t_push = clock(); for (i = 0; i < num_ins; i++){ stack_push(s, &pushed[i]); } t_push = clock() - t_push; for (i = 0; i < num_ins; i++){ pushed[i] = NULL; } t_pop = clock(); for (i = 0; i < num_ins; i++){ stack_pop(s, &popped[i]); } t_pop = clock() - t_pop; res *= (s->num_elts == 0); res *= (s->count >= num_ins); for (i = 0; i < num_ins; i++){ res *= (*(popped[i]->val) == num_ins - 1 - i + start_val); free_uint_ptr(&popped[i]); } printf("\t\tpush time: %.4f seconds\n", (double)t_push / CLOCKS_PER_SEC); printf("\t\tpop time: %.4f seconds\n", (double)t_pop / CLOCKS_PER_SEC); printf("\t\tcorrectness: "); print_test_result(res); free(pushed); free(popped); pushed = NULL; popped = NULL; } void run_uint_ptr_first_test(size_t log_ins){ int res = 1; size_t i; size_t num_ins; size_t start_val = C_START_VAL; struct uint_ptr *pushed = NULL, *popped = NULL; struct stack s; num_ins = pow_two_perror(log_ins); stack_init(&s, sizeof(struct uint_ptr *), free_uint_ptr); printf("Run a stack_first test on %lu noncontiguous uint_ptr elements\n", TOLU(num_ins)); for (i = 0; i < num_ins; i++){ if (s.num_elts == 0){ res *= (stack_first(&s) == NULL); } pushed = malloc_perror(1, sizeof(struct uint_ptr)); pushed->val = malloc_perror(1, sizeof(size_t)); *(pushed->val) = start_val + i; stack_push(&s, &pushed); res *= (*(*(struct uint_ptr **)stack_first(&s))->val == start_val + i); pushed = NULL; } for (i = 0; i < num_ins; i++){ res *= (*(*(struct uint_ptr **)stack_first(&s))->val == num_ins - 1 - i + start_val); stack_pop(&s, &popped); if (s.num_elts == 0){ res *= (stack_first(&s) == NULL); } free_uint_ptr(&popped); popped = NULL; } res *= (s.num_elts == 0); res *= (s.count >= num_ins); printf("\t\tcorrectness: "); print_test_result(res); stack_free(&s); } void run_uint_ptr_free_test(size_t log_ins){ size_t i; size_t num_ins; struct uint_ptr *pushed = NULL; struct stack s; clock_t t; num_ins = pow_two_perror(log_ins); stack_init(&s, sizeof(struct uint_ptr *), free_uint_ptr); printf("Run a stack_free test on %lu noncontiguous uint_ptr elements\n", TOLU(num_ins)); for (i = 0; i < num_ins; i++){ pushed = malloc_perror(1, sizeof(struct uint_ptr)); pushed->val = malloc_perror(1, sizeof(size_t)); *(pushed->val) = i; stack_push(&s, &pushed); pushed = NULL; } t = clock(); stack_free(&s); t = clock() - t; printf("\t\tfree time: %.4f seconds\n", (double)t / CLOCKS_PER_SEC); } /** Runs a test of a stack of unsigned char elements. */ void run_uchar_stack_test(size_t log_ins){ unsigned char c; size_t i; size_t num_ins; struct stack s; clock_t t_push, t_pop; num_ins = pow_two_perror(log_ins); stack_init(&s, sizeof(unsigned char), NULL); printf("Run a stack_{push, pop} test on %lu char elements\n", TOLU(num_ins)); t_push = clock(); for (i = 0; i < num_ins; i++){ stack_push(&s, &C_UCHAR_ULIMIT); } t_push = clock() - t_push; t_pop = clock(); for (i = 0; i < num_ins; i++){ stack_pop(&s, &c); } t_pop = clock() - t_pop; printf("\t\tpush time: %.4f seconds\n", (double)t_push / CLOCKS_PER_SEC); printf("\t\tpop time: %.4f seconds\n", (double)t_pop / CLOCKS_PER_SEC); stack_free(&s); } void print_test_result(int res){ if (res){ printf("SUCCESS\n"); }else{ printf("FAILURE\n"); } } int main(int argc, char *argv[]){ int i; size_t *args = NULL; if (argc > C_ARGC_ULIMIT){ fprintf(stderr, "USAGE:\n%s", C_USAGE); exit(EXIT_FAILURE); } args = malloc_perror(C_ARGC_ULIMIT - 1, sizeof(size_t)); memcpy(args, C_ARGS_DEF, (C_ARGC_ULIMIT - 1) * sizeof(size_t)); for (i = 1; i < argc; i++){ args[i - 1] = atoi(argv[i]); } if (args[0] > C_ULONG_BIT - 1 || args[1] > C_ULONG_BIT - 1 || args[2] > 1 || args[3] > 1 || args[4] > 1){ fprintf(stderr, "USAGE:\n%s", C_USAGE); exit(EXIT_FAILURE); } if (args[2]){ run_uint_push_pop_test(args[0]); run_uint_first_test(args[0]); run_uint_free_test(args[0]); } if (args[3]){ run_uint_ptr_push_pop_test(args[0]); run_uint_ptr_first_test(args[0]); run_uint_ptr_free_test(args[0]); } if (args[4]){ run_uchar_stack_test(args[1]); } free(args); args = NULL; return 0; }
be9/mlmvn
lib/learning.h
#pragma once #include <algorithm> #include <vector> #include <cassert> #include "mvn.h" namespace klogic { namespace learning { template<typename Desired> struct sample { typedef Desired desired_type; cvector input; Desired desired; sample(const cvector &i, const Desired &d) : input(i), desired(d) {} }; // ------------------ template<typename Desired> class learn_error {}; template<> class learn_error<cmplx> { public: cmplx operator()(const cmplx &output, const cmplx &sample) const { return sample - output; } }; template<> class learn_error<cvector> { public: cvector operator()(const cvector &output, const cvector &sample) const { assert(output.size() == sample.size()); cvector errors(output.size()); for (int i = 0; i < output.size(); ++i) errors[i] = sample[i] - output[i]; return errors; } }; // ------------------ template <typename Sample, typename Desired = typename Sample::desired_type> class learn_always { public: bool operator()(Sample const &, Desired const &) const { return true; } }; // ------------------ template<typename Learner, // mvn or mlmvn typename Sample = sample<typename Learner::desired_type>, typename LearnError = learn_error <typename Sample::desired_type> > class teacher { public: teacher(Learner &_learner, const std::vector<Sample> &samples = std::vector<Sample>()) : learner(_learner), _samples(samples) {} // Add sample to the set void add_sample(const Sample &sample) { _samples.push_back(sample); } void set_samples(const std::vector<Sample> &samples) { _samples = samples; } // Learning set const std::vector<Sample> samples() const { return _samples; } // Learning set size int samples_count() const { return samples().size(); } // How well learner matches the learning set template <class Match> int hits(Match const &match = Match()) const { int count = 0; for (typename std::vector<Sample>::const_iterator i = _samples.begin(); i != _samples.end(); ++i) { if (match(learner.output(i->input), i->desired)) ++count; } return count; } // Make a run against set. picker instance is used to skip some set items template <typename SamplePicker> void learn_run(SamplePicker const &picker = SamplePicker()) { for (typename std::vector<Sample>::const_iterator i = _samples.begin(); i != _samples.end(); ++i) { typename Sample::desired_type actual = learner.output(i->input); if (picker(*i, actual)) learner.learn(i->input, learn_error(actual, i->desired)); } } // Run against whole set void learn_run() { learn_run<learn_always<Sample> >(); } // Calculate MSE for all samples template <typename SquareError> double mse(SquareError const &sq_err = SquareError()) { double acc_error = 0.0; for (typename std::vector<Sample>::const_iterator i = _samples.begin(); i != _samples.end(); ++i) { typename Sample::desired_type actual = learner.output(i->input); acc_error += sq_err(*i, actual); } return acc_error / samples_count(); } private: std::vector<Sample> _samples; Learner &learner; LearnError learn_error; }; // ------------------ template<typename Stream, typename Desired> Stream &operator<<(Stream& os, const sample<Desired> &sample) { return os << "Input: " << sample.input << " Desired: " << sample.desired << std::endl; } // ------------------ template <int K> class single_discrete_match { public: bool operator()(const cmplx &output, const cmplx &sample) const { return sector_number(K, output) == sector_number(K, sample); } }; } }
be9/mlmvn
lib/klogic.h
#pragma once #include <complex> #define _USE_MATH_DEFINES #include <cmath> #include <cassert> #include <vector> namespace klogic { typedef std::complex<double> cmplx; typedef std::vector<cmplx> cvector; const double TWOPI = 2 * M_PI; // nth power of kth complex root of unity inline cmplx epsilon(unsigned n, int k) { assert(k > 0 && n >= 0 && n < k); double phase = (TWOPI * n) / k; return std::polar(1.0, phase); } // phase in [0..2pi) range inline double phase(const cmplx &z) { double phi = std::arg(z); return phi < 0 ? phi + TWOPI : phi; } // sector number in k-valued logic inline int sector_number(int k, const cmplx &z) { return int(std::floor((phase(z) / TWOPI) * k) + 0.5); } // complex activation function in k-valued logic. // if k=0 uses continuous activation function. inline cmplx activation(int k, const cmplx &z) { if (k == 0) return z / std::abs(z); else { return epsilon(sector_number(k, z), k); } } // ------------------ template<typename Stream, typename T> Stream &operator<<(Stream& os, const std::vector<T> &v) { os << '['; for (typename std::vector<T>::const_iterator i = v.begin(); i != v.end(); ++i) { os << *i; } return os << ']'; } }
be9/mlmvn
lib/transforms.h
<filename>lib/transforms.h #pragma once #include <algorithm> #include "klogic.h" namespace klogic { namespace learning { template<typename Desired> struct sample; // Forward declaration } //////////////////////////// namespace transform { // Discrete (one value) template<int K> cmplx discrete(int n) { assert(n >= 0 && n < K); return epsilon(n, K); } // Discrete (vector) template<int K> cvector discrete(const std::vector<int> &values) { cvector result(values.size()); std::transform(values.begin(), values.end(), result.begin(), static_cast<cmplx (*)(int)>(&discrete<K>)); return result; } // Sample template<int K, typename Desired, typename Input> learning::sample<Desired> discrete(const std::vector<int> &values, const Input &desired) { return learning::sample<Desired>(discrete<K>(values), discrete<K>(desired)); } ////// // Continuous (0..2pi) inline cmplx continuous(double x) { assert(x >= 0 && x < TWOPI); return std::polar(1.0, x); } // Continuous. Vector (0..2pi) inline cvector continuous(std::vector<double> xs) { cvector result(xs.size()); std::transform(xs.begin(), xs.end(), result.begin(), static_cast<cmplx (*)(double)>(&continuous)); return result; } template<typename Desired, typename Input> learning::sample<Desired> continuous(const std::vector<double> &values, const Input &desired) { return learning::sample<Desired>(continuous(values), continuous(desired)); } } }
be9/mlmvn
lib/mvn.h
<reponame>be9/mlmvn<gh_stars>1-10 // Single MVN implementation #pragma once #include "klogic.h" namespace klogic { class mvn { public: typedef cmplx desired_type; // Create mvn in k-valued logic with N inputs. // This counts for N+1 weights, including bias. mvn(int k, int N); mvn() : k(-1) {} // Applies activation function to weighted sum cmplx output(const cvector &X) const { return activation(k, weighted_sum(X.begin(), X.end())); } cmplx output(cvector::const_iterator xbeg, cvector::const_iterator xend) const { return activation(k, weighted_sum(xbeg, xend)); } // Returns true if this neuron is discrete bool is_discrete() const { return k > 0; } // Returns k int k_value() const { return k; } // Uses Error-Correction Learning Rule (3.92) to // change weights. If variable_rate is true, // additional division by |z| is done per (3.94) void learn(cvector::const_iterator Xbeg, cvector::const_iterator Xend, const cmplx &error, double learning_rate = 1.0, bool variable_rate = false); void learn(const cvector &X, const cmplx &error, double learning_rate = 1.0, bool variable_rate = false) { learn(X.begin(), X.end(), error, learning_rate, variable_rate); } // Returns weights const cvector &weights_vector() const { return weights; } cvector &weights_vector() { return weights; } // Returns weight which corresponds to i-th input of this neuron cmplx weight_for_input(int i) const { assert(i >= 0 && i < weights.size() - 1); // 0th weight is bias return weights[i+1]; } protected: cvector weights; int k; /**************/ // Calculates w_0+w_1*i_1+....+w_N*i_N cmplx weighted_sum(cvector::const_iterator xbeg, cvector::const_iterator xend) const; }; }
be9/mlmvn
lib/mlmvn.h
// MLMVN implementation #pragma once #include "mvn.h" namespace klogic { class mlmvn; // Separate class for calculating mlmvn output allows to parallelize, but // is stingy about memory allocation. It uses max. two vectors to support // computations for networks containing arbitrary number of layers class mlmvn_forward_base { public: mlmvn_forward_base(const mlmvn &_net); // Layer-by-layer calculation interface // Start calculation X -> out void start(const klogic::cvector &X, cvector::iterator out); // Start calculation for X not meaning to get result void start(const klogic::cvector &X); // Get current layer, i.e. neurons which process incoming data and // output results to the next layer int current_layer() const { return layer; } // Make calculations for current layer and step to the next one. // Returns true if result is already available. bool step(); // Input for current layer cvector::const_iterator input_begin() const { return from->begin(); } cvector::const_iterator input_end() const { return from->begin() + from_size; } protected: // original values passed to start are saved here cvector::iterator out; const mlmvn &net; bool use_out; // Two internal vectors storing intermediate results cvector layer1, layer2; // `from` always points to a vector which contains input for current // layer. At start, it points to X but then its value cycles between // &layer1 and &layer2 const cvector *from; // `to` points to a vector which receives output from current layer. It // also cycles between &layer1 and &layer2 but it always "opposite" to // `from`. If `to` points to layer1, `from` points to layer2 and vice versa. cvector *to; // This value corresponds to input size available in `*from` size_t from_size; // Current layer number. Input layer is not counted, so layer == 0 // means first hidden layer or output layer if network has no hidden // layers int layer; }; //-------------------------------------------------------------- class mlmvn { friend class mlmvn_forward; friend class mlmvn_forward_base; public: typedef cvector desired_type; // Construct an MLMVN. sizes is the following: // Number of inputs, hidden layer 1 size, ..., // hidden layer M size, output layer size mlmvn(const std::vector<int> &sizes, const std::vector<int> &k_values); // Total layer count in network (hidden + one output) size_t layers_count() const { return neurons.size(); } // Input layer size size_t input_layer_size() const { return input_size; } // Specific layer size size_t layer_size(size_t layer) const { return neurons[layer].size(); } // Output (last) layer size size_t output_layer_size() const { return output_size; } // Correct weights void learn(const cvector &X, const cvector &error, double learning_rate = 1.0); // i-th neuron in j-th layer mvn &neuron(int i, int j) { return neurons[j][i]; } const mvn &neuron(int i, int j) const { return neurons[j][i]; } // Net output. Use with care since it allocates memory on each run cvector output(const cvector &X) const; void dump() const; void dump_errors() const; void export_neurons(cvector &all_weights, std::vector<int> &k_values) const; void load_neurons(const cvector &all_weights, const std::vector<int> &k_values); protected: // Calculate errors for all neurons given // output layer errors void calculate_errors(const cvector &errs); // Get overall weights and neurons counts void get_stats(size_t &n_weights, size_t &n_neurons) const; std::vector<std::vector<mvn> > neurons; std::vector<std::vector<cmplx> > errors; int s_j(int j) { return (j <= 0) ? 1 : 1 + neurons[j-1].size(); } int max_layer_size; size_t input_size, output_size; mlmvn_forward_base calculator; }; //-------------------------------------------------------------- // Higher level version of mlmvn_forward_base class mlmvn_forward : protected mlmvn_forward_base { public: mlmvn_forward(const mlmvn &net) : mlmvn_forward_base(net) {} // Calculate network output for input vector X and return it as a vector cvector output(const cvector &X) { cvector result(net.output_size); output(X, result.begin()); return result; } // Calculate network output for input vector X and put it to out void output(const cvector &X, cvector::iterator out) { start(X, out); while (!step()) ; } }; //-------------------------------------------------------------- inline cvector mlmvn::output(const cvector &X) const { return mlmvn_forward(*this).output(X); } };
jwadia/CPP-MachineLearning
src/regression/Regression.h
<reponame>jwadia/CPP-MachineLearning<gh_stars>0 #ifndef __Regression_H_INCLUDED__ #define __Regression_H_INCLUDED__ #include <vector> #include <iostream> class Regression { private: std::vector<double> x; std::vector<double> y; public: Regression(std::vector<double> xList, std::vector<double> yList); std::vector<double> PolynomialRegression(int order); }; #endif
jwadia/CPP-MachineLearning
src/util/Functions.h
#ifndef __Functions_H_INCLUDED__ #define __Functions_H_INCLUDED__ #include <vector> #include <iostream> #include <math.h> class Functions { private: public: Functions(); double sigmoid(double input); }; #endif
jwadia/CPP-MachineLearning
src/nural-network/NuralNetwork.h
#ifndef __NuralNetwork_H_INCLUDED__ #define __NuralNetwork_H_INCLUDED__ #include <vector> #include <iostream> #include <ctime> #include "../util/Node.h" #include "../util/Functions.h" class NuralNetwork { private: std::vector<std::vector<Node>> network; public: NuralNetwork(std::vector<int> layers); std::vector<double> predict(std::vector<double> inputs); }; #endif
jwadia/CPP-MachineLearning
src/util/Node.h
#ifndef __Node_H_INCLUDED__ #define __Node_H_INCLUDED__ #include <vector> #include <iostream> class Node { private: std::vector<double> weights; double value = 0; public: Node(std::vector<double> w); std::vector<double> getWeights(); void setValue(double nodeValue); double getValue(); }; #endif
jwadia/CPP-MachineLearning
src/util/Matrix.h
<reponame>jwadia/CPP-MachineLearning #ifndef __Matrix_H_INCLUDED__ #define __Matrix_H_INCLUDED__ #include <vector> class Matrix { private: std::vector<std::vector<double>> matrix; std::vector<std::vector<double>> matrix_aug; double determinant(std::vector<std::vector<double>> matrix); public: Matrix(std::vector<std::vector<double>> insert); Matrix(std::vector<std::vector<double>> insert, std::vector<std::vector<double>> ans); double determinant(); std::vector<double> solve(); }; #endif
jwadia/CPP-MachineLearning
src/knn/Knn.h
<reponame>jwadia/CPP-MachineLearning<filename>src/knn/Knn.h #ifndef __KNN_INCLUDED__ #define __KNN_H_INCLUDED__ #include <vector> #include <math.h> class KNN { private: std::vector<double> x; std::vector<double> y; std::vector<double> label; int k; public: KNN(std::vector<double> xList, std::vector<double> yList, std::vector<double> lList, int num); double predict(double px, double py); }; #endif
Teddy-van-Jerry/LCDF_Expr
Expr5/D_74LS138_SCH/isim/D_74LS138_D_74LS138_sch_tb_isim_beh.exe.sim/work/m_00000000001292768382_1880772334.c
/**********************************************************************/ /* ____ ____ */ /* / /\/ / */ /* /___/ \ / */ /* \ \ \/ */ /* \ \ Copyright (c) 2003-2009 Xilinx, Inc. */ /* / / All Right Reserved. */ /* /---/ /\ */ /* \ \ / \ */ /* \___\/\___\ */ /***********************************************************************/ /* This file is designed for use with ISim build 0x7708f090 */ #define XSI_HIDE_SYMBOL_SPEC true #include "xsi.h" #include <memory.h> #ifdef __GNUC__ #include <stdlib.h> #else #include <malloc.h> #define alloca _alloca #endif static const char *ng0 = "E:/Tmp/D_74LS138_SCH/D_74LS138_sim.v"; static int ng1[] = {0, 0}; static int ng2[] = {1, 0}; static int ng3[] = {7, 0}; static void NetReassign_47_1(char *); static void NetReassign_48_2(char *); static void NetReassign_49_3(char *); static void NetReassign_52_4(char *); static void NetReassign_53_5(char *); static void NetReassign_54_6(char *); static void NetReassign_57_7(char *); static void NetReassign_58_8(char *); static void NetReassign_59_9(char *); static void Initial_33_0(char *t0) { char t6[8]; char *t1; char *t2; char *t3; char *t4; char *t5; char *t7; unsigned int t8; unsigned int t9; unsigned int t10; unsigned int t11; unsigned int t12; char *t13; char *t14; char *t15; char *t16; char *t17; char *t18; LAB0: t1 = (t0 + 3328U); t2 = *((char **)t1); if (t2 == 0) goto LAB2; LAB3: goto *t2; LAB2: xsi_set_current_line(33, ng0); LAB4: xsi_set_current_line(34, ng0); t2 = ((char*)((ng1))); t3 = (t0 + 1768); xsi_vlogvar_assign_value(t3, t2, 0, 0, 1); xsi_set_current_line(35, ng0); t2 = ((char*)((ng1))); t3 = (t0 + 1448); xsi_vlogvar_assign_value(t3, t2, 0, 0, 1); xsi_set_current_line(36, ng0); t2 = ((char*)((ng1))); t3 = (t0 + 1608); xsi_vlogvar_assign_value(t3, t2, 0, 0, 1); xsi_set_current_line(38, ng0); t2 = ((char*)((ng2))); t3 = (t0 + 1928); xsi_vlogvar_assign_value(t3, t2, 0, 0, 1); xsi_set_current_line(39, ng0); t2 = ((char*)((ng1))); t3 = (t0 + 2088); xsi_vlogvar_assign_value(t3, t2, 0, 0, 1); xsi_set_current_line(40, ng0); t2 = ((char*)((ng1))); t3 = (t0 + 2248); xsi_vlogvar_assign_value(t3, t2, 0, 0, 1); xsi_set_current_line(41, ng0); t2 = (t0 + 3136); xsi_process_wait(t2, 50000LL); *((char **)t1) = &&LAB5; LAB1: return; LAB5: xsi_set_current_line(42, ng0); xsi_set_current_line(42, ng0); t2 = ((char*)((ng1))); t3 = (t0 + 2408); xsi_vlogvar_assign_value(t3, t2, 0, 0, 32); LAB6: t2 = (t0 + 2408); t3 = (t2 + 56U); t4 = *((char **)t3); t5 = ((char*)((ng3))); memset(t6, 0, 8); xsi_vlog_signed_leq(t6, 32, t4, 32, t5, 32); t7 = (t6 + 4); t8 = *((unsigned int *)t7); t9 = (~(t8)); t10 = *((unsigned int *)t6); t11 = (t10 & t9); t12 = (t11 != 0); if (t12 > 0) goto LAB7; LAB8: xsi_set_current_line(47, ng0); t2 = (t0 + 1928); xsi_set_assignedflag(t2); t3 = (t0 + 7600); *((int *)t3) = 1; NetReassign_47_1(t0); xsi_set_current_line(48, ng0); t2 = (t0 + 2088); xsi_set_assignedflag(t2); t3 = (t0 + 7604); *((int *)t3) = 1; NetReassign_48_2(t0); xsi_set_current_line(49, ng0); t2 = (t0 + 2248); xsi_set_assignedflag(t2); t3 = (t0 + 7608); *((int *)t3) = 1; NetReassign_49_3(t0); xsi_set_current_line(50, ng0); t2 = (t0 + 3136); xsi_process_wait(t2, 50000LL); *((char **)t1) = &&LAB11; goto LAB1; LAB7: xsi_set_current_line(42, ng0); LAB9: xsi_set_current_line(43, ng0); t13 = (t0 + 2408); t14 = (t13 + 56U); t15 = *((char **)t14); t16 = (t0 + 1608); xsi_vlogvar_assign_value(t16, t15, 0, 0, 1); t17 = (t0 + 1448); xsi_vlogvar_assign_value(t17, t15, 1, 0, 1); t18 = (t0 + 1768); xsi_vlogvar_assign_value(t18, t15, 2, 0, 1); xsi_set_current_line(44, ng0); t2 = (t0 + 3136); xsi_process_wait(t2, 50000LL); *((char **)t1) = &&LAB10; goto LAB1; LAB10: xsi_set_current_line(42, ng0); t2 = (t0 + 2408); t3 = (t2 + 56U); t4 = *((char **)t3); t5 = ((char*)((ng2))); memset(t6, 0, 8); xsi_vlog_signed_add(t6, 32, t4, 32, t5, 32); t7 = (t0 + 2408); xsi_vlogvar_assign_value(t7, t6, 0, 0, 32); goto LAB6; LAB11: xsi_set_current_line(52, ng0); t2 = (t0 + 1928); xsi_set_assignedflag(t2); t3 = (t0 + 7612); *((int *)t3) = 1; NetReassign_52_4(t0); xsi_set_current_line(53, ng0); t2 = (t0 + 2088); xsi_set_assignedflag(t2); t3 = (t0 + 7616); *((int *)t3) = 1; NetReassign_53_5(t0); xsi_set_current_line(54, ng0); t2 = (t0 + 2248); xsi_set_assignedflag(t2); t3 = (t0 + 7620); *((int *)t3) = 1; NetReassign_54_6(t0); xsi_set_current_line(55, ng0); t2 = (t0 + 3136); xsi_process_wait(t2, 50000LL); *((char **)t1) = &&LAB12; goto LAB1; LAB12: xsi_set_current_line(57, ng0); t2 = (t0 + 1928); xsi_set_assignedflag(t2); t3 = (t0 + 7624); *((int *)t3) = 1; NetReassign_57_7(t0); xsi_set_current_line(58, ng0); t2 = (t0 + 2088); xsi_set_assignedflag(t2); t3 = (t0 + 7628); *((int *)t3) = 1; NetReassign_58_8(t0); xsi_set_current_line(59, ng0); t2 = (t0 + 2248); xsi_set_assignedflag(t2); t3 = (t0 + 7632); *((int *)t3) = 1; NetReassign_59_9(t0); xsi_set_current_line(60, ng0); t2 = (t0 + 3136); xsi_process_wait(t2, 50000LL); *((char **)t1) = &&LAB13; goto LAB1; LAB13: goto LAB1; } static void NetReassign_47_1(char *t0) { char *t1; char *t2; unsigned int t3; char *t4; char *t5; LAB0: t1 = (t0 + 3576U); t2 = *((char **)t1); if (t2 == 0) goto LAB2; LAB3: goto *t2; LAB2: xsi_set_current_line(47, ng0); t3 = 0; t2 = ((char*)((ng1))); t4 = (t0 + 7600); if (*((int *)t4) > 0) goto LAB4; LAB5: LAB1: return; LAB4: t5 = (t0 + 1928); xsi_vlogvar_assignassignvalue(t5, t2, 0, 0, 0, 1, ((int*)(t4))); t3 = 1; goto LAB5; } static void NetReassign_48_2(char *t0) { char *t1; char *t2; unsigned int t3; char *t4; char *t5; LAB0: t1 = (t0 + 3824U); t2 = *((char **)t1); if (t2 == 0) goto LAB2; LAB3: goto *t2; LAB2: xsi_set_current_line(48, ng0); t3 = 0; t2 = ((char*)((ng1))); t4 = (t0 + 7604); if (*((int *)t4) > 0) goto LAB4; LAB5: LAB1: return; LAB4: t5 = (t0 + 2088); xsi_vlogvar_assignassignvalue(t5, t2, 0, 0, 0, 1, ((int*)(t4))); t3 = 1; goto LAB5; } static void NetReassign_49_3(char *t0) { char *t1; char *t2; unsigned int t3; char *t4; char *t5; LAB0: t1 = (t0 + 4072U); t2 = *((char **)t1); if (t2 == 0) goto LAB2; LAB3: goto *t2; LAB2: xsi_set_current_line(49, ng0); t3 = 0; t2 = ((char*)((ng1))); t4 = (t0 + 7608); if (*((int *)t4) > 0) goto LAB4; LAB5: LAB1: return; LAB4: t5 = (t0 + 2248); xsi_vlogvar_assignassignvalue(t5, t2, 0, 0, 0, 1, ((int*)(t4))); t3 = 1; goto LAB5; } static void NetReassign_52_4(char *t0) { char *t1; char *t2; unsigned int t3; char *t4; char *t5; LAB0: t1 = (t0 + 4320U); t2 = *((char **)t1); if (t2 == 0) goto LAB2; LAB3: goto *t2; LAB2: xsi_set_current_line(52, ng0); t3 = 0; t2 = ((char*)((ng2))); t4 = (t0 + 7612); if (*((int *)t4) > 0) goto LAB4; LAB5: LAB1: return; LAB4: t5 = (t0 + 1928); xsi_vlogvar_assignassignvalue(t5, t2, 0, 0, 0, 1, ((int*)(t4))); t3 = 1; goto LAB5; } static void NetReassign_53_5(char *t0) { char *t1; char *t2; unsigned int t3; char *t4; char *t5; LAB0: t1 = (t0 + 4568U); t2 = *((char **)t1); if (t2 == 0) goto LAB2; LAB3: goto *t2; LAB2: xsi_set_current_line(53, ng0); t3 = 0; t2 = ((char*)((ng2))); t4 = (t0 + 7616); if (*((int *)t4) > 0) goto LAB4; LAB5: LAB1: return; LAB4: t5 = (t0 + 2088); xsi_vlogvar_assignassignvalue(t5, t2, 0, 0, 0, 1, ((int*)(t4))); t3 = 1; goto LAB5; } static void NetReassign_54_6(char *t0) { char *t1; char *t2; unsigned int t3; char *t4; char *t5; LAB0: t1 = (t0 + 4816U); t2 = *((char **)t1); if (t2 == 0) goto LAB2; LAB3: goto *t2; LAB2: xsi_set_current_line(54, ng0); t3 = 0; t2 = ((char*)((ng1))); t4 = (t0 + 7620); if (*((int *)t4) > 0) goto LAB4; LAB5: LAB1: return; LAB4: t5 = (t0 + 2248); xsi_vlogvar_assignassignvalue(t5, t2, 0, 0, 0, 1, ((int*)(t4))); t3 = 1; goto LAB5; } static void NetReassign_57_7(char *t0) { char *t1; char *t2; unsigned int t3; char *t4; char *t5; LAB0: t1 = (t0 + 5064U); t2 = *((char **)t1); if (t2 == 0) goto LAB2; LAB3: goto *t2; LAB2: xsi_set_current_line(57, ng0); t3 = 0; t2 = ((char*)((ng2))); t4 = (t0 + 7624); if (*((int *)t4) > 0) goto LAB4; LAB5: LAB1: return; LAB4: t5 = (t0 + 1928); xsi_vlogvar_assignassignvalue(t5, t2, 0, 0, 0, 1, ((int*)(t4))); t3 = 1; goto LAB5; } static void NetReassign_58_8(char *t0) { char *t1; char *t2; unsigned int t3; char *t4; char *t5; LAB0: t1 = (t0 + 5312U); t2 = *((char **)t1); if (t2 == 0) goto LAB2; LAB3: goto *t2; LAB2: xsi_set_current_line(58, ng0); t3 = 0; t2 = ((char*)((ng1))); t4 = (t0 + 7628); if (*((int *)t4) > 0) goto LAB4; LAB5: LAB1: return; LAB4: t5 = (t0 + 2088); xsi_vlogvar_assignassignvalue(t5, t2, 0, 0, 0, 1, ((int*)(t4))); t3 = 1; goto LAB5; } static void NetReassign_59_9(char *t0) { char *t1; char *t2; unsigned int t3; char *t4; char *t5; LAB0: t1 = (t0 + 5560U); t2 = *((char **)t1); if (t2 == 0) goto LAB2; LAB3: goto *t2; LAB2: xsi_set_current_line(59, ng0); t3 = 0; t2 = ((char*)((ng2))); t4 = (t0 + 7632); if (*((int *)t4) > 0) goto LAB4; LAB5: LAB1: return; LAB4: t5 = (t0 + 2248); xsi_vlogvar_assignassignvalue(t5, t2, 0, 0, 0, 1, ((int*)(t4))); t3 = 1; goto LAB5; } extern void work_m_00000000001292768382_1880772334_init() { static char *pe[] = {(void *)Initial_33_0,(void *)NetReassign_47_1,(void *)NetReassign_48_2,(void *)NetReassign_49_3,(void *)NetReassign_52_4,(void *)NetReassign_53_5,(void *)NetReassign_54_6,(void *)NetReassign_57_7,(void *)NetReassign_58_8,(void *)NetReassign_59_9}; xsi_register_didat("work_m_00000000001292768382_1880772334", "isim/D_74LS138_D_74LS138_sch_tb_isim_beh.exe.sim/work/m_00000000001292768382_1880772334.didat"); xsi_register_executes(pe); }
Teddy-van-Jerry/LCDF_Expr
Expr9/MyALU/isim/AddSub4b_AddSub4b_sch_tb_isim_beh.exe.sim/work/m_00000000002934133259_2589900479.c
<reponame>Teddy-van-Jerry/LCDF_Expr /**********************************************************************/ /* ____ ____ */ /* / /\/ / */ /* /___/ \ / */ /* \ \ \/ */ /* \ \ Copyright (c) 2003-2009 Xilinx, Inc. */ /* / / All Right Reserved. */ /* /---/ /\ */ /* \ \ / \ */ /* \___\/\___\ */ /***********************************************************************/ /* This file is designed for use with ISim build 0x7708f090 */ #define XSI_HIDE_SYMBOL_SPEC true #include "xsi.h" #include <memory.h> #ifdef __GNUC__ #include <stdlib.h> #else #include <malloc.h> #define alloca _alloca #endif static const char *ng0 = "D:/Asudy/WorkSpace/LCDF_Expr/Expr8/MyALU/AddSub4b_sim.v"; static int ng1[] = {0, 0}; static int ng2[] = {2, 0}; static int ng3[] = {4, 0}; static int ng4[] = {9, 0}; static int ng5[] = {14, 0}; static int ng6[] = {1, 0}; static int ng7[] = {12, 0}; static void Initial_27_0(char *t0) { char *t1; char *t2; char *t3; LAB0: t1 = (t0 + 2848U); t2 = *((char **)t1); if (t2 == 0) goto LAB2; LAB3: goto *t2; LAB2: xsi_set_current_line(27, ng0); LAB4: xsi_set_current_line(28, ng0); t2 = ((char*)((ng1))); t3 = (t0 + 1608); xsi_vlogvar_assign_value(t3, t2, 0, 0, 1); xsi_set_current_line(29, ng0); t2 = ((char*)((ng1))); t3 = (t0 + 1768); xsi_vlogvar_assign_value(t3, t2, 0, 0, 4); xsi_set_current_line(30, ng0); t2 = ((char*)((ng1))); t3 = (t0 + 1928); xsi_vlogvar_assign_value(t3, t2, 0, 0, 4); xsi_set_current_line(33, ng0); t2 = ((char*)((ng2))); t3 = (t0 + 1768); xsi_vlogvar_assign_value(t3, t2, 0, 0, 4); xsi_set_current_line(34, ng0); t2 = ((char*)((ng3))); t3 = (t0 + 1928); xsi_vlogvar_assign_value(t3, t2, 0, 0, 4); xsi_set_current_line(35, ng0); t2 = (t0 + 2656); xsi_process_wait(t2, 100000LL); *((char **)t1) = &&LAB5; LAB1: return; LAB5: xsi_set_current_line(37, ng0); t2 = ((char*)((ng4))); t3 = (t0 + 1768); xsi_vlogvar_assign_value(t3, t2, 0, 0, 4); xsi_set_current_line(38, ng0); t2 = ((char*)((ng5))); t3 = (t0 + 1928); xsi_vlogvar_assign_value(t3, t2, 0, 0, 4); xsi_set_current_line(39, ng0); t2 = (t0 + 2656); xsi_process_wait(t2, 100000LL); *((char **)t1) = &&LAB6; goto LAB1; LAB6: xsi_set_current_line(41, ng0); t2 = ((char*)((ng6))); t3 = (t0 + 1608); xsi_vlogvar_assign_value(t3, t2, 0, 0, 1); xsi_set_current_line(42, ng0); t2 = ((char*)((ng7))); t3 = (t0 + 1768); xsi_vlogvar_assign_value(t3, t2, 0, 0, 4); xsi_set_current_line(43, ng0); t2 = ((char*)((ng4))); t3 = (t0 + 1928); xsi_vlogvar_assign_value(t3, t2, 0, 0, 4); xsi_set_current_line(44, ng0); t2 = (t0 + 2656); xsi_process_wait(t2, 100000LL); *((char **)t1) = &&LAB7; goto LAB1; LAB7: xsi_set_current_line(46, ng0); t2 = ((char*)((ng4))); t3 = (t0 + 1768); xsi_vlogvar_assign_value(t3, t2, 0, 0, 4); xsi_set_current_line(47, ng0); t2 = ((char*)((ng7))); t3 = (t0 + 1928); xsi_vlogvar_assign_value(t3, t2, 0, 0, 4); xsi_set_current_line(48, ng0); t2 = (t0 + 2656); xsi_process_wait(t2, 100000LL); *((char **)t1) = &&LAB8; goto LAB1; LAB8: goto LAB1; } extern void work_m_00000000002934133259_2589900479_init() { static char *pe[] = {(void *)Initial_27_0}; xsi_register_didat("work_m_00000000002934133259_2589900479", "isim/AddSub4b_AddSub4b_sch_tb_isim_beh.exe.sim/work/m_00000000002934133259_2589900479.didat"); xsi_register_executes(pe); }
Teddy-van-Jerry/LCDF_Expr
Expr10/MyLATCHS/isim/MS_FlipFlop_MS_FlipFlop_sch_tb_isim_beh.exe.sim/work/m_00000000000935785449_1666990586.c
<reponame>Teddy-van-Jerry/LCDF_Expr /**********************************************************************/ /* ____ ____ */ /* / /\/ / */ /* /___/ \ / */ /* \ \ \/ */ /* \ \ Copyright (c) 2003-2009 Xilinx, Inc. */ /* / / All Right Reserved. */ /* /---/ /\ */ /* \ \ / \ */ /* \___\/\___\ */ /***********************************************************************/ /* This file is designed for use with ISim build 0x7708f090 */ #define XSI_HIDE_SYMBOL_SPEC true #include "xsi.h" #include <memory.h> #ifdef __GNUC__ #include <stdlib.h> #else #include <malloc.h> #define alloca _alloca #endif static const char *ng0 = "E:/wjz/Expr10/MyLATCHS/MS_FlipFlop_sim.v"; static int ng1[] = {0, 0}; static int ng2[] = {1, 0}; static void Always_30_0(char *t0) { char t3[8]; char *t1; char *t2; char *t4; char *t5; char *t6; char *t7; unsigned int t8; unsigned int t9; unsigned int t10; unsigned int t11; unsigned int t12; char *t13; char *t14; char *t15; unsigned int t16; unsigned int t17; unsigned int t18; unsigned int t19; unsigned int t20; unsigned int t21; unsigned int t22; unsigned int t23; char *t24; LAB0: t1 = (t0 + 3008U); t2 = *((char **)t1); if (t2 == 0) goto LAB2; LAB3: goto *t2; LAB2: xsi_set_current_line(30, ng0); LAB4: xsi_set_current_line(31, ng0); t2 = (t0 + 2816); xsi_process_wait(t2, 50000LL); *((char **)t1) = &&LAB5; LAB1: return; LAB5: xsi_set_current_line(31, ng0); t4 = (t0 + 1928); t5 = (t4 + 56U); t6 = *((char **)t5); memset(t3, 0, 8); t7 = (t6 + 4); t8 = *((unsigned int *)t7); t9 = (~(t8)); t10 = *((unsigned int *)t6); t11 = (t10 & t9); t12 = (t11 & 1U); if (t12 != 0) goto LAB9; LAB7: if (*((unsigned int *)t7) == 0) goto LAB6; LAB8: t13 = (t3 + 4); *((unsigned int *)t3) = 1; *((unsigned int *)t13) = 1; LAB9: t14 = (t3 + 4); t15 = (t6 + 4); t16 = *((unsigned int *)t6); t17 = (~(t16)); *((unsigned int *)t3) = t17; *((unsigned int *)t14) = 0; if (*((unsigned int *)t15) != 0) goto LAB11; LAB10: t22 = *((unsigned int *)t3); *((unsigned int *)t3) = (t22 & 1U); t23 = *((unsigned int *)t14); *((unsigned int *)t14) = (t23 & 1U); t24 = (t0 + 1928); xsi_vlogvar_assign_value(t24, t3, 0, 0, 1); goto LAB2; LAB6: *((unsigned int *)t3) = 1; goto LAB9; LAB11: t18 = *((unsigned int *)t3); t19 = *((unsigned int *)t15); *((unsigned int *)t3) = (t18 | t19); t20 = *((unsigned int *)t14); t21 = *((unsigned int *)t15); *((unsigned int *)t14) = (t20 | t21); goto LAB10; } static void Initial_34_1(char *t0) { char *t1; char *t2; char *t3; char *t4; LAB0: t1 = (t0 + 3256U); t2 = *((char **)t1); if (t2 == 0) goto LAB2; LAB3: goto *t2; LAB2: xsi_set_current_line(34, ng0); LAB4: xsi_set_current_line(35, ng0); t2 = ((char*)((ng1))); t3 = (t0 + 1928); xsi_vlogvar_assign_value(t3, t2, 0, 0, 1); xsi_set_current_line(36, ng0); t2 = (t0 + 3064); xsi_process_wait(t2, 40000LL); *((char **)t1) = &&LAB5; LAB1: return; LAB5: xsi_set_current_line(36, ng0); t3 = ((char*)((ng1))); t4 = (t0 + 1768); xsi_vlogvar_assign_value(t4, t3, 0, 0, 1); xsi_set_current_line(37, ng0); t2 = ((char*)((ng1))); t3 = (t0 + 2088); xsi_vlogvar_assign_value(t3, t2, 0, 0, 1); xsi_set_current_line(38, ng0); t2 = (t0 + 3064); xsi_process_wait(t2, 100000LL); *((char **)t1) = &&LAB6; goto LAB1; LAB6: xsi_set_current_line(38, ng0); t3 = ((char*)((ng2))); t4 = (t0 + 1768); xsi_vlogvar_assign_value(t4, t3, 0, 0, 1); xsi_set_current_line(39, ng0); t2 = (t0 + 3064); xsi_process_wait(t2, 100000LL); *((char **)t1) = &&LAB7; goto LAB1; LAB7: xsi_set_current_line(39, ng0); t3 = ((char*)((ng1))); t4 = (t0 + 1768); xsi_vlogvar_assign_value(t4, t3, 0, 0, 1); xsi_set_current_line(40, ng0); t2 = (t0 + 3064); xsi_process_wait(t2, 100000LL); *((char **)t1) = &&LAB8; goto LAB1; LAB8: xsi_set_current_line(40, ng0); t3 = ((char*)((ng2))); t4 = (t0 + 2088); xsi_vlogvar_assign_value(t4, t3, 0, 0, 1); xsi_set_current_line(41, ng0); t2 = (t0 + 3064); xsi_process_wait(t2, 100000LL); *((char **)t1) = &&LAB9; goto LAB1; LAB9: xsi_set_current_line(41, ng0); t3 = ((char*)((ng1))); t4 = (t0 + 2088); xsi_vlogvar_assign_value(t4, t3, 0, 0, 1); xsi_set_current_line(42, ng0); t2 = (t0 + 3064); xsi_process_wait(t2, 100000LL); *((char **)t1) = &&LAB10; goto LAB1; LAB10: xsi_set_current_line(42, ng0); t3 = ((char*)((ng2))); t4 = (t0 + 1768); xsi_vlogvar_assign_value(t4, t3, 0, 0, 1); xsi_set_current_line(42, ng0); t2 = (t0 + 3064); xsi_process_wait(t2, 20000LL); *((char **)t1) = &&LAB11; goto LAB1; LAB11: xsi_set_current_line(42, ng0); t3 = ((char*)((ng1))); t4 = (t0 + 1768); xsi_vlogvar_assign_value(t4, t3, 0, 0, 1); xsi_set_current_line(43, ng0); t2 = (t0 + 3064); xsi_process_wait(t2, 5000LL); *((char **)t1) = &&LAB12; goto LAB1; LAB12: xsi_set_current_line(43, ng0); t3 = ((char*)((ng2))); t4 = (t0 + 2088); xsi_vlogvar_assign_value(t4, t3, 0, 0, 1); xsi_set_current_line(43, ng0); t2 = (t0 + 3064); xsi_process_wait(t2, 15000LL); *((char **)t1) = &&LAB13; goto LAB1; LAB13: xsi_set_current_line(43, ng0); t3 = ((char*)((ng1))); t4 = (t0 + 2088); xsi_vlogvar_assign_value(t4, t3, 0, 0, 1); xsi_set_current_line(44, ng0); t2 = (t0 + 3064); xsi_process_wait(t2, 60000LL); *((char **)t1) = &&LAB14; goto LAB1; LAB14: xsi_set_current_line(44, ng0); t3 = ((char*)((ng2))); t4 = (t0 + 1768); xsi_vlogvar_assign_value(t4, t3, 0, 0, 1); xsi_set_current_line(44, ng0); t2 = (t0 + 3064); xsi_process_wait(t2, 20000LL); *((char **)t1) = &&LAB15; goto LAB1; LAB15: xsi_set_current_line(44, ng0); t3 = ((char*)((ng1))); t4 = (t0 + 1768); xsi_vlogvar_assign_value(t4, t3, 0, 0, 1); xsi_set_current_line(45, ng0); t2 = (t0 + 3064); xsi_process_wait(t2, 140000LL); *((char **)t1) = &&LAB16; goto LAB1; LAB16: xsi_set_current_line(45, ng0); t3 = ((char*)((ng2))); t4 = (t0 + 1768); xsi_vlogvar_assign_value(t4, t3, 0, 0, 1); xsi_set_current_line(45, ng0); t2 = ((char*)((ng2))); t3 = (t0 + 2088); xsi_vlogvar_assign_value(t3, t2, 0, 0, 1); xsi_set_current_line(46, ng0); t2 = (t0 + 3064); xsi_process_wait(t2, 100000LL); *((char **)t1) = &&LAB17; goto LAB1; LAB17: xsi_set_current_line(46, ng0); t3 = ((char*)((ng1))); t4 = (t0 + 1768); xsi_vlogvar_assign_value(t4, t3, 0, 0, 1); xsi_set_current_line(46, ng0); t2 = ((char*)((ng1))); t3 = (t0 + 2088); xsi_vlogvar_assign_value(t3, t2, 0, 0, 1); goto LAB1; } extern void work_m_00000000000935785449_1666990586_init() { static char *pe[] = {(void *)Always_30_0,(void *)Initial_34_1}; xsi_register_didat("work_m_00000000000935785449_1666990586", "isim/MS_FlipFlop_MS_FlipFlop_sch_tb_isim_beh.exe.sim/work/m_00000000000935785449_1666990586.didat"); xsi_register_executes(pe); }
Teddy-van-Jerry/LCDF_Expr
Expr11/MyRevCounter/isim/Conter4bRev_sim_isim_beh.exe.sim/work/m_00000000004261765678_3107888780.c
<reponame>Teddy-van-Jerry/LCDF_Expr<filename>Expr11/MyRevCounter/isim/Conter4bRev_sim_isim_beh.exe.sim/work/m_00000000004261765678_3107888780.c /**********************************************************************/ /* ____ ____ */ /* / /\/ / */ /* /___/ \ / */ /* \ \ \/ */ /* \ \ Copyright (c) 2003-2009 Xilinx, Inc. */ /* / / All Right Reserved. */ /* /---/ /\ */ /* \ \ / \ */ /* \___\/\___\ */ /***********************************************************************/ /* This file is designed for use with ISim build 0x7708f090 */ #define XSI_HIDE_SYMBOL_SPEC true #include "xsi.h" #include <memory.h> #ifdef __GNUC__ #include <stdlib.h> #else #include <malloc.h> #define alloca _alloca #endif static const char *ng0 = "E:/wjz/Expr11/MyRevCounter/Counter4bRev.v"; static int ng1[] = {0, 0}; static unsigned int ng2[] = {0U, 0U}; static void Initial_31_0(char *t0) { char *t1; char *t2; char *t3; char *t4; char *t5; LAB0: xsi_set_current_line(31, ng0); t1 = ((char*)((ng1))); t2 = (t0 + 3848); xsi_vlogvar_assign_value(t2, t1, 0, 0, 1); t3 = (t0 + 3688); xsi_vlogvar_assign_value(t3, t1, 1, 0, 1); t4 = (t0 + 3528); xsi_vlogvar_assign_value(t4, t1, 2, 0, 1); t5 = (t0 + 3368); xsi_vlogvar_assign_value(t5, t1, 3, 0, 1); LAB1: return; } static void Cont_33_1(char *t0) { char t3[8]; char *t1; char *t2; char *t4; char *t5; char *t6; unsigned int t7; unsigned int t8; unsigned int t9; unsigned int t10; unsigned int t11; char *t12; char *t13; char *t14; unsigned int t15; unsigned int t16; unsigned int t17; unsigned int t18; unsigned int t19; unsigned int t20; unsigned int t21; unsigned int t22; char *t23; char *t24; char *t25; char *t26; char *t27; unsigned int t28; unsigned int t29; char *t30; unsigned int t31; unsigned int t32; char *t33; unsigned int t34; unsigned int t35; char *t36; LAB0: t1 = (t0 + 5016U); t2 = *((char **)t1); if (t2 == 0) goto LAB2; LAB3: goto *t2; LAB2: xsi_set_current_line(33, ng0); t2 = (t0 + 3848); t4 = (t2 + 56U); t5 = *((char **)t4); memset(t3, 0, 8); t6 = (t5 + 4); t7 = *((unsigned int *)t6); t8 = (~(t7)); t9 = *((unsigned int *)t5); t10 = (t9 & t8); t11 = (t10 & 1U); if (t11 != 0) goto LAB7; LAB5: if (*((unsigned int *)t6) == 0) goto LAB4; LAB6: t12 = (t3 + 4); *((unsigned int *)t3) = 1; *((unsigned int *)t12) = 1; LAB7: t13 = (t3 + 4); t14 = (t5 + 4); t15 = *((unsigned int *)t5); t16 = (~(t15)); *((unsigned int *)t3) = t16; *((unsigned int *)t13) = 0; if (*((unsigned int *)t14) != 0) goto LAB9; LAB8: t21 = *((unsigned int *)t3); *((unsigned int *)t3) = (t21 & 1U); t22 = *((unsigned int *)t13); *((unsigned int *)t13) = (t22 & 1U); t23 = (t0 + 8056); t24 = (t23 + 56U); t25 = *((char **)t24); t26 = (t25 + 56U); t27 = *((char **)t26); memset(t27, 0, 8); t28 = 1U; t29 = t28; t30 = (t3 + 4); t31 = *((unsigned int *)t3); t28 = (t28 & t31); t32 = *((unsigned int *)t30); t29 = (t29 & t32); t33 = (t27 + 4); t34 = *((unsigned int *)t27); *((unsigned int *)t27) = (t34 | t28); t35 = *((unsigned int *)t33); *((unsigned int *)t33) = (t35 | t29); xsi_driver_vfirst_trans(t23, 0, 0); t36 = (t0 + 7816); *((int *)t36) = 1; LAB1: return; LAB4: *((unsigned int *)t3) = 1; goto LAB7; LAB9: t17 = *((unsigned int *)t3); t18 = *((unsigned int *)t14); *((unsigned int *)t3) = (t17 | t18); t19 = *((unsigned int *)t13); t20 = *((unsigned int *)t14); *((unsigned int *)t13) = (t19 | t20); goto LAB8; } static void Cont_34_2(char *t0) { char t3[8]; char *t1; char *t2; char *t4; char *t5; char *t6; unsigned int t7; unsigned int t8; unsigned int t9; unsigned int t10; unsigned int t11; char *t12; char *t13; char *t14; unsigned int t15; unsigned int t16; unsigned int t17; unsigned int t18; unsigned int t19; unsigned int t20; unsigned int t21; unsigned int t22; char *t23; char *t24; char *t25; char *t26; char *t27; unsigned int t28; unsigned int t29; char *t30; unsigned int t31; unsigned int t32; char *t33; unsigned int t34; unsigned int t35; char *t36; LAB0: t1 = (t0 + 5264U); t2 = *((char **)t1); if (t2 == 0) goto LAB2; LAB3: goto *t2; LAB2: xsi_set_current_line(34, ng0); t2 = (t0 + 3688); t4 = (t2 + 56U); t5 = *((char **)t4); memset(t3, 0, 8); t6 = (t5 + 4); t7 = *((unsigned int *)t6); t8 = (~(t7)); t9 = *((unsigned int *)t5); t10 = (t9 & t8); t11 = (t10 & 1U); if (t11 != 0) goto LAB7; LAB5: if (*((unsigned int *)t6) == 0) goto LAB4; LAB6: t12 = (t3 + 4); *((unsigned int *)t3) = 1; *((unsigned int *)t12) = 1; LAB7: t13 = (t3 + 4); t14 = (t5 + 4); t15 = *((unsigned int *)t5); t16 = (~(t15)); *((unsigned int *)t3) = t16; *((unsigned int *)t13) = 0; if (*((unsigned int *)t14) != 0) goto LAB9; LAB8: t21 = *((unsigned int *)t3); *((unsigned int *)t3) = (t21 & 1U); t22 = *((unsigned int *)t13); *((unsigned int *)t13) = (t22 & 1U); t23 = (t0 + 8120); t24 = (t23 + 56U); t25 = *((char **)t24); t26 = (t25 + 56U); t27 = *((char **)t26); memset(t27, 0, 8); t28 = 1U; t29 = t28; t30 = (t3 + 4); t31 = *((unsigned int *)t3); t28 = (t28 & t31); t32 = *((unsigned int *)t30); t29 = (t29 & t32); t33 = (t27 + 4); t34 = *((unsigned int *)t27); *((unsigned int *)t27) = (t34 | t28); t35 = *((unsigned int *)t33); *((unsigned int *)t33) = (t35 | t29); xsi_driver_vfirst_trans(t23, 0, 0); t36 = (t0 + 7832); *((int *)t36) = 1; LAB1: return; LAB4: *((unsigned int *)t3) = 1; goto LAB7; LAB9: t17 = *((unsigned int *)t3); t18 = *((unsigned int *)t14); *((unsigned int *)t3) = (t17 | t18); t19 = *((unsigned int *)t13); t20 = *((unsigned int *)t14); *((unsigned int *)t13) = (t19 | t20); goto LAB8; } static void Cont_35_3(char *t0) { char t3[8]; char *t1; char *t2; char *t4; char *t5; char *t6; unsigned int t7; unsigned int t8; unsigned int t9; unsigned int t10; unsigned int t11; char *t12; char *t13; char *t14; unsigned int t15; unsigned int t16; unsigned int t17; unsigned int t18; unsigned int t19; unsigned int t20; unsigned int t21; unsigned int t22; char *t23; char *t24; char *t25; char *t26; char *t27; unsigned int t28; unsigned int t29; char *t30; unsigned int t31; unsigned int t32; char *t33; unsigned int t34; unsigned int t35; char *t36; LAB0: t1 = (t0 + 5512U); t2 = *((char **)t1); if (t2 == 0) goto LAB2; LAB3: goto *t2; LAB2: xsi_set_current_line(35, ng0); t2 = (t0 + 3528); t4 = (t2 + 56U); t5 = *((char **)t4); memset(t3, 0, 8); t6 = (t5 + 4); t7 = *((unsigned int *)t6); t8 = (~(t7)); t9 = *((unsigned int *)t5); t10 = (t9 & t8); t11 = (t10 & 1U); if (t11 != 0) goto LAB7; LAB5: if (*((unsigned int *)t6) == 0) goto LAB4; LAB6: t12 = (t3 + 4); *((unsigned int *)t3) = 1; *((unsigned int *)t12) = 1; LAB7: t13 = (t3 + 4); t14 = (t5 + 4); t15 = *((unsigned int *)t5); t16 = (~(t15)); *((unsigned int *)t3) = t16; *((unsigned int *)t13) = 0; if (*((unsigned int *)t14) != 0) goto LAB9; LAB8: t21 = *((unsigned int *)t3); *((unsigned int *)t3) = (t21 & 1U); t22 = *((unsigned int *)t13); *((unsigned int *)t13) = (t22 & 1U); t23 = (t0 + 8184); t24 = (t23 + 56U); t25 = *((char **)t24); t26 = (t25 + 56U); t27 = *((char **)t26); memset(t27, 0, 8); t28 = 1U; t29 = t28; t30 = (t3 + 4); t31 = *((unsigned int *)t3); t28 = (t28 & t31); t32 = *((unsigned int *)t30); t29 = (t29 & t32); t33 = (t27 + 4); t34 = *((unsigned int *)t27); *((unsigned int *)t27) = (t34 | t28); t35 = *((unsigned int *)t33); *((unsigned int *)t33) = (t35 | t29); xsi_driver_vfirst_trans(t23, 0, 0); t36 = (t0 + 7848); *((int *)t36) = 1; LAB1: return; LAB4: *((unsigned int *)t3) = 1; goto LAB7; LAB9: t17 = *((unsigned int *)t3); t18 = *((unsigned int *)t14); *((unsigned int *)t3) = (t17 | t18); t19 = *((unsigned int *)t13); t20 = *((unsigned int *)t14); *((unsigned int *)t13) = (t19 | t20); goto LAB8; } static void Cont_36_4(char *t0) { char t3[8]; char *t1; char *t2; char *t4; char *t5; char *t6; unsigned int t7; unsigned int t8; unsigned int t9; unsigned int t10; unsigned int t11; char *t12; char *t13; char *t14; unsigned int t15; unsigned int t16; unsigned int t17; unsigned int t18; unsigned int t19; unsigned int t20; unsigned int t21; unsigned int t22; char *t23; char *t24; char *t25; char *t26; char *t27; unsigned int t28; unsigned int t29; char *t30; unsigned int t31; unsigned int t32; char *t33; unsigned int t34; unsigned int t35; char *t36; LAB0: t1 = (t0 + 5760U); t2 = *((char **)t1); if (t2 == 0) goto LAB2; LAB3: goto *t2; LAB2: xsi_set_current_line(36, ng0); t2 = (t0 + 3368); t4 = (t2 + 56U); t5 = *((char **)t4); memset(t3, 0, 8); t6 = (t5 + 4); t7 = *((unsigned int *)t6); t8 = (~(t7)); t9 = *((unsigned int *)t5); t10 = (t9 & t8); t11 = (t10 & 1U); if (t11 != 0) goto LAB7; LAB5: if (*((unsigned int *)t6) == 0) goto LAB4; LAB6: t12 = (t3 + 4); *((unsigned int *)t3) = 1; *((unsigned int *)t12) = 1; LAB7: t13 = (t3 + 4); t14 = (t5 + 4); t15 = *((unsigned int *)t5); t16 = (~(t15)); *((unsigned int *)t3) = t16; *((unsigned int *)t13) = 0; if (*((unsigned int *)t14) != 0) goto LAB9; LAB8: t21 = *((unsigned int *)t3); *((unsigned int *)t3) = (t21 & 1U); t22 = *((unsigned int *)t13); *((unsigned int *)t13) = (t22 & 1U); t23 = (t0 + 8248); t24 = (t23 + 56U); t25 = *((char **)t24); t26 = (t25 + 56U); t27 = *((char **)t26); memset(t27, 0, 8); t28 = 1U; t29 = t28; t30 = (t3 + 4); t31 = *((unsigned int *)t3); t28 = (t28 & t31); t32 = *((unsigned int *)t30); t29 = (t29 & t32); t33 = (t27 + 4); t34 = *((unsigned int *)t27); *((unsigned int *)t27) = (t34 | t28); t35 = *((unsigned int *)t33); *((unsigned int *)t33) = (t35 | t29); xsi_driver_vfirst_trans(t23, 0, 0); t36 = (t0 + 7864); *((int *)t36) = 1; LAB1: return; LAB4: *((unsigned int *)t3) = 1; goto LAB7; LAB9: t17 = *((unsigned int *)t3); t18 = *((unsigned int *)t14); *((unsigned int *)t3) = (t17 | t18); t19 = *((unsigned int *)t13); t20 = *((unsigned int *)t14); *((unsigned int *)t13) = (t19 | t20); goto LAB8; } static void Cont_38_5(char *t0) { char *t1; char *t2; char *t3; char *t4; char *t5; char *t6; char *t7; unsigned int t8; unsigned int t9; char *t10; unsigned int t11; unsigned int t12; char *t13; unsigned int t14; unsigned int t15; char *t16; LAB0: t1 = (t0 + 6008U); t2 = *((char **)t1); if (t2 == 0) goto LAB2; LAB3: goto *t2; LAB2: xsi_set_current_line(38, ng0); t2 = (t0 + 2488U); t3 = *((char **)t2); t2 = (t0 + 8312); t4 = (t2 + 56U); t5 = *((char **)t4); t6 = (t5 + 56U); t7 = *((char **)t6); memset(t7, 0, 8); t8 = 1U; t9 = t8; t10 = (t3 + 4); t11 = *((unsigned int *)t3); t8 = (t8 & t11); t12 = *((unsigned int *)t10); t9 = (t9 & t12); t13 = (t7 + 4); t14 = *((unsigned int *)t7); *((unsigned int *)t7) = (t14 | t8); t15 = *((unsigned int *)t13); *((unsigned int *)t13) = (t15 | t9); xsi_driver_vfirst_trans(t2, 0, 0); t16 = (t0 + 7880); *((int *)t16) = 1; LAB1: return; } static void Cont_39_6(char *t0) { char t3[8]; char t6[8]; char t21[8]; char *t1; char *t2; char *t4; char *t5; unsigned int t7; unsigned int t8; unsigned int t9; char *t10; char *t11; unsigned int t12; unsigned int t13; unsigned int t14; unsigned int t15; unsigned int t16; unsigned int t17; unsigned int t18; char *t19; char *t20; unsigned int t22; unsigned int t23; unsigned int t24; char *t25; char *t26; unsigned int t27; unsigned int t28; unsigned int t29; unsigned int t30; unsigned int t31; unsigned int t32; unsigned int t33; char *t34; unsigned int t35; unsigned int t36; unsigned int t37; unsigned int t38; unsigned int t39; char *t40; char *t41; char *t42; unsigned int t43; unsigned int t44; unsigned int t45; unsigned int t46; unsigned int t47; unsigned int t48; unsigned int t49; unsigned int t50; char *t51; char *t52; char *t53; char *t54; char *t55; unsigned int t56; unsigned int t57; char *t58; unsigned int t59; unsigned int t60; char *t61; unsigned int t62; unsigned int t63; char *t64; LAB0: t1 = (t0 + 6256U); t2 = *((char **)t1); if (t2 == 0) goto LAB2; LAB3: goto *t2; LAB2: xsi_set_current_line(39, ng0); t2 = (t0 + 1368U); t4 = *((char **)t2); t2 = (t0 + 2488U); t5 = *((char **)t2); t7 = *((unsigned int *)t4); t8 = *((unsigned int *)t5); t9 = (t7 ^ t8); *((unsigned int *)t6) = t9; t2 = (t4 + 4); t10 = (t5 + 4); t11 = (t6 + 4); t12 = *((unsigned int *)t2); t13 = *((unsigned int *)t10); t14 = (t12 | t13); *((unsigned int *)t11) = t14; t15 = *((unsigned int *)t11); t16 = (t15 != 0); if (t16 == 1) goto LAB4; LAB5: LAB6: t19 = (t0 + 2648U); t20 = *((char **)t19); t22 = *((unsigned int *)t6); t23 = *((unsigned int *)t20); t24 = (t22 ^ t23); *((unsigned int *)t21) = t24; t19 = (t6 + 4); t25 = (t20 + 4); t26 = (t21 + 4); t27 = *((unsigned int *)t19); t28 = *((unsigned int *)t25); t29 = (t27 | t28); *((unsigned int *)t26) = t29; t30 = *((unsigned int *)t26); t31 = (t30 != 0); if (t31 == 1) goto LAB7; LAB8: LAB9: memset(t3, 0, 8); t34 = (t21 + 4); t35 = *((unsigned int *)t34); t36 = (~(t35)); t37 = *((unsigned int *)t21); t38 = (t37 & t36); t39 = (t38 & 1U); if (t39 != 0) goto LAB13; LAB11: if (*((unsigned int *)t34) == 0) goto LAB10; LAB12: t40 = (t3 + 4); *((unsigned int *)t3) = 1; *((unsigned int *)t40) = 1; LAB13: t41 = (t3 + 4); t42 = (t21 + 4); t43 = *((unsigned int *)t21); t44 = (~(t43)); *((unsigned int *)t3) = t44; *((unsigned int *)t41) = 0; if (*((unsigned int *)t42) != 0) goto LAB15; LAB14: t49 = *((unsigned int *)t3); *((unsigned int *)t3) = (t49 & 1U); t50 = *((unsigned int *)t41); *((unsigned int *)t41) = (t50 & 1U); t51 = (t0 + 8376); t52 = (t51 + 56U); t53 = *((char **)t52); t54 = (t53 + 56U); t55 = *((char **)t54); memset(t55, 0, 8); t56 = 1U; t57 = t56; t58 = (t3 + 4); t59 = *((unsigned int *)t3); t56 = (t56 & t59); t60 = *((unsigned int *)t58); t57 = (t57 & t60); t61 = (t55 + 4); t62 = *((unsigned int *)t55); *((unsigned int *)t55) = (t62 | t56); t63 = *((unsigned int *)t61); *((unsigned int *)t61) = (t63 | t57); xsi_driver_vfirst_trans(t51, 0, 0); t64 = (t0 + 7896); *((int *)t64) = 1; LAB1: return; LAB4: t17 = *((unsigned int *)t6); t18 = *((unsigned int *)t11); *((unsigned int *)t6) = (t17 | t18); goto LAB6; LAB7: t32 = *((unsigned int *)t21); t33 = *((unsigned int *)t26); *((unsigned int *)t21) = (t32 | t33); goto LAB9; LAB10: *((unsigned int *)t3) = 1; goto LAB13; LAB15: t45 = *((unsigned int *)t3); t46 = *((unsigned int *)t42); *((unsigned int *)t3) = (t45 | t46); t47 = *((unsigned int *)t41); t48 = *((unsigned int *)t42); *((unsigned int *)t41) = (t47 | t48); goto LAB14; } static void Cont_40_7(char *t0) { char t3[8]; char t4[8]; char t5[8]; char t29[8]; char t57[8]; char t93[8]; char t120[8]; char t152[8]; char t199[8]; char *t1; char *t2; char *t6; unsigned int t7; unsigned int t8; unsigned int t9; unsigned int t10; unsigned int t11; char *t12; char *t13; char *t14; unsigned int t15; unsigned int t16; unsigned int t17; unsigned int t18; unsigned int t19; unsigned int t20; unsigned int t21; unsigned int t22; char *t23; char *t24; char *t25; char *t26; char *t27; char *t28; unsigned int t30; unsigned int t31; unsigned int t32; char *t33; char *t34; char *t35; unsigned int t36; unsigned int t37; unsigned int t38; unsigned int t39; unsigned int t40; unsigned int t41; unsigned int t42; char *t43; char *t44; unsigned int t45; unsigned int t46; unsigned int t47; int t48; unsigned int t49; unsigned int t50; unsigned int t51; int t52; unsigned int t53; unsigned int t54; unsigned int t55; unsigned int t56; unsigned int t58; unsigned int t59; unsigned int t60; char *t61; char *t62; char *t63; unsigned int t64; unsigned int t65; unsigned int t66; unsigned int t67; unsigned int t68; unsigned int t69; unsigned int t70; char *t71; char *t72; unsigned int t73; unsigned int t74; unsigned int t75; unsigned int t76; unsigned int t77; unsigned int t78; unsigned int t79; unsigned int t80; int t81; int t82; unsigned int t83; unsigned int t84; unsigned int t85; unsigned int t86; unsigned int t87; unsigned int t88; char *t89; char *t90; char *t91; char *t92; unsigned int t94; unsigned int t95; unsigned int t96; char *t97; char *t98; unsigned int t99; unsigned int t100; unsigned int t101; unsigned int t102; unsigned int t103; unsigned int t104; unsigned int t105; char *t106; char *t107; unsigned int t108; unsigned int t109; unsigned int t110; int t111; unsigned int t112; unsigned int t113; unsigned int t114; int t115; unsigned int t116; unsigned int t117; unsigned int t118; unsigned int t119; unsigned int t121; unsigned int t122; unsigned int t123; char *t124; char *t125; char *t126; unsigned int t127; unsigned int t128; unsigned int t129; unsigned int t130; unsigned int t131; unsigned int t132; unsigned int t133; char *t134; char *t135; unsigned int t136; unsigned int t137; unsigned int t138; unsigned int t139; unsigned int t140; unsigned int t141; unsigned int t142; unsigned int t143; int t144; int t145; unsigned int t146; unsigned int t147; unsigned int t148; unsigned int t149; unsigned int t150; unsigned int t151; unsigned int t153; unsigned int t154; unsigned int t155; char *t156; char *t157; char *t158; unsigned int t159; unsigned int t160; unsigned int t161; unsigned int t162; unsigned int t163; unsigned int t164; unsigned int t165; char *t166; char *t167; unsigned int t168; unsigned int t169; unsigned int t170; int t171; unsigned int t172; unsigned int t173; unsigned int t174; int t175; unsigned int t176; unsigned int t177; unsigned int t178; unsigned int t179; char *t180; unsigned int t181; unsigned int t182; unsigned int t183; unsigned int t184; unsigned int t185; char *t186; char *t187; char *t188; unsigned int t189; unsigned int t190; unsigned int t191; unsigned int t192; unsigned int t193; unsigned int t194; unsigned int t195; unsigned int t196; char *t197; char *t198; unsigned int t200; unsigned int t201; unsigned int t202; char *t203; char *t204; unsigned int t205; unsigned int t206; unsigned int t207; unsigned int t208; unsigned int t209; unsigned int t210; unsigned int t211; char *t212; unsigned int t213; unsigned int t214; unsigned int t215; unsigned int t216; unsigned int t217; char *t218; char *t219; char *t220; unsigned int t221; unsigned int t222; unsigned int t223; unsigned int t224; unsigned int t225; unsigned int t226; unsigned int t227; unsigned int t228; char *t229; char *t230; char *t231; char *t232; char *t233; unsigned int t234; unsigned int t235; char *t236; unsigned int t237; unsigned int t238; char *t239; unsigned int t240; unsigned int t241; char *t242; LAB0: t1 = (t0 + 6504U); t2 = *((char **)t1); if (t2 == 0) goto LAB2; LAB3: goto *t2; LAB2: xsi_set_current_line(40, ng0); t2 = (t0 + 1368U); t6 = *((char **)t2); memset(t5, 0, 8); t2 = (t6 + 4); t7 = *((unsigned int *)t2); t8 = (~(t7)); t9 = *((unsigned int *)t6); t10 = (t9 & t8); t11 = (t10 & 1U); if (t11 != 0) goto LAB7; LAB5: if (*((unsigned int *)t2) == 0) goto LAB4; LAB6: t12 = (t5 + 4); *((unsigned int *)t5) = 1; *((unsigned int *)t12) = 1; LAB7: t13 = (t5 + 4); t14 = (t6 + 4); t15 = *((unsigned int *)t6); t16 = (~(t15)); *((unsigned int *)t5) = t16; *((unsigned int *)t13) = 0; if (*((unsigned int *)t14) != 0) goto LAB9; LAB8: t21 = *((unsigned int *)t5); *((unsigned int *)t5) = (t21 & 1U); t22 = *((unsigned int *)t13); *((unsigned int *)t13) = (t22 & 1U); t23 = (t0 + 3848); t24 = (t23 + 56U); t25 = *((char **)t24); t26 = (t0 + 3688); t27 = (t26 + 56U); t28 = *((char **)t27); t30 = *((unsigned int *)t25); t31 = *((unsigned int *)t28); t32 = (t30 | t31); *((unsigned int *)t29) = t32; t33 = (t25 + 4); t34 = (t28 + 4); t35 = (t29 + 4); t36 = *((unsigned int *)t33); t37 = *((unsigned int *)t34); t38 = (t36 | t37); *((unsigned int *)t35) = t38; t39 = *((unsigned int *)t35); t40 = (t39 != 0); if (t40 == 1) goto LAB10; LAB11: LAB12: t58 = *((unsigned int *)t5); t59 = *((unsigned int *)t29); t60 = (t58 & t59); *((unsigned int *)t57) = t60; t61 = (t5 + 4); t62 = (t29 + 4); t63 = (t57 + 4); t64 = *((unsigned int *)t61); t65 = *((unsigned int *)t62); t66 = (t64 | t65); *((unsigned int *)t63) = t66; t67 = *((unsigned int *)t63); t68 = (t67 != 0); if (t68 == 1) goto LAB13; LAB14: LAB15: t89 = (t0 + 1368U); t90 = *((char **)t89); t89 = (t0 + 2488U); t91 = *((char **)t89); t89 = (t0 + 2648U); t92 = *((char **)t89); t94 = *((unsigned int *)t91); t95 = *((unsigned int *)t92); t96 = (t94 | t95); *((unsigned int *)t93) = t96; t89 = (t91 + 4); t97 = (t92 + 4); t98 = (t93 + 4); t99 = *((unsigned int *)t89); t100 = *((unsigned int *)t97); t101 = (t99 | t100); *((unsigned int *)t98) = t101; t102 = *((unsigned int *)t98); t103 = (t102 != 0); if (t103 == 1) goto LAB16; LAB17: LAB18: t121 = *((unsigned int *)t90); t122 = *((unsigned int *)t93); t123 = (t121 & t122); *((unsigned int *)t120) = t123; t124 = (t90 + 4); t125 = (t93 + 4); t126 = (t120 + 4); t127 = *((unsigned int *)t124); t128 = *((unsigned int *)t125); t129 = (t127 | t128); *((unsigned int *)t126) = t129; t130 = *((unsigned int *)t126); t131 = (t130 != 0); if (t131 == 1) goto LAB19; LAB20: LAB21: t153 = *((unsigned int *)t57); t154 = *((unsigned int *)t120); t155 = (t153 | t154); *((unsigned int *)t152) = t155; t156 = (t57 + 4); t157 = (t120 + 4); t158 = (t152 + 4); t159 = *((unsigned int *)t156); t160 = *((unsigned int *)t157); t161 = (t159 | t160); *((unsigned int *)t158) = t161; t162 = *((unsigned int *)t158); t163 = (t162 != 0); if (t163 == 1) goto LAB22; LAB23: LAB24: memset(t4, 0, 8); t180 = (t152 + 4); t181 = *((unsigned int *)t180); t182 = (~(t181)); t183 = *((unsigned int *)t152); t184 = (t183 & t182); t185 = (t184 & 1U); if (t185 != 0) goto LAB28; LAB26: if (*((unsigned int *)t180) == 0) goto LAB25; LAB27: t186 = (t4 + 4); *((unsigned int *)t4) = 1; *((unsigned int *)t186) = 1; LAB28: t187 = (t4 + 4); t188 = (t152 + 4); t189 = *((unsigned int *)t152); t190 = (~(t189)); *((unsigned int *)t4) = t190; *((unsigned int *)t187) = 0; if (*((unsigned int *)t188) != 0) goto LAB30; LAB29: t195 = *((unsigned int *)t4); *((unsigned int *)t4) = (t195 & 1U); t196 = *((unsigned int *)t187); *((unsigned int *)t187) = (t196 & 1U); t197 = (t0 + 2808U); t198 = *((char **)t197); t200 = *((unsigned int *)t4); t201 = *((unsigned int *)t198); t202 = (t200 ^ t201); *((unsigned int *)t199) = t202; t197 = (t4 + 4); t203 = (t198 + 4); t204 = (t199 + 4); t205 = *((unsigned int *)t197); t206 = *((unsigned int *)t203); t207 = (t205 | t206); *((unsigned int *)t204) = t207; t208 = *((unsigned int *)t204); t209 = (t208 != 0); if (t209 == 1) goto LAB31; LAB32: LAB33: memset(t3, 0, 8); t212 = (t199 + 4); t213 = *((unsigned int *)t212); t214 = (~(t213)); t215 = *((unsigned int *)t199); t216 = (t215 & t214); t217 = (t216 & 1U); if (t217 != 0) goto LAB37; LAB35: if (*((unsigned int *)t212) == 0) goto LAB34; LAB36: t218 = (t3 + 4); *((unsigned int *)t3) = 1; *((unsigned int *)t218) = 1; LAB37: t219 = (t3 + 4); t220 = (t199 + 4); t221 = *((unsigned int *)t199); t222 = (~(t221)); *((unsigned int *)t3) = t222; *((unsigned int *)t219) = 0; if (*((unsigned int *)t220) != 0) goto LAB39; LAB38: t227 = *((unsigned int *)t3); *((unsigned int *)t3) = (t227 & 1U); t228 = *((unsigned int *)t219); *((unsigned int *)t219) = (t228 & 1U); t229 = (t0 + 8440); t230 = (t229 + 56U); t231 = *((char **)t230); t232 = (t231 + 56U); t233 = *((char **)t232); memset(t233, 0, 8); t234 = 1U; t235 = t234; t236 = (t3 + 4); t237 = *((unsigned int *)t3); t234 = (t234 & t237); t238 = *((unsigned int *)t236); t235 = (t235 & t238); t239 = (t233 + 4); t240 = *((unsigned int *)t233); *((unsigned int *)t233) = (t240 | t234); t241 = *((unsigned int *)t239); *((unsigned int *)t239) = (t241 | t235); xsi_driver_vfirst_trans(t229, 0, 0); t242 = (t0 + 7912); *((int *)t242) = 1; LAB1: return; LAB4: *((unsigned int *)t5) = 1; goto LAB7; LAB9: t17 = *((unsigned int *)t5); t18 = *((unsigned int *)t14); *((unsigned int *)t5) = (t17 | t18); t19 = *((unsigned int *)t13); t20 = *((unsigned int *)t14); *((unsigned int *)t13) = (t19 | t20); goto LAB8; LAB10: t41 = *((unsigned int *)t29); t42 = *((unsigned int *)t35); *((unsigned int *)t29) = (t41 | t42); t43 = (t25 + 4); t44 = (t28 + 4); t45 = *((unsigned int *)t43); t46 = (~(t45)); t47 = *((unsigned int *)t25); t48 = (t47 & t46); t49 = *((unsigned int *)t44); t50 = (~(t49)); t51 = *((unsigned int *)t28); t52 = (t51 & t50); t53 = (~(t48)); t54 = (~(t52)); t55 = *((unsigned int *)t35); *((unsigned int *)t35) = (t55 & t53); t56 = *((unsigned int *)t35); *((unsigned int *)t35) = (t56 & t54); goto LAB12; LAB13: t69 = *((unsigned int *)t57); t70 = *((unsigned int *)t63); *((unsigned int *)t57) = (t69 | t70); t71 = (t5 + 4); t72 = (t29 + 4); t73 = *((unsigned int *)t5); t74 = (~(t73)); t75 = *((unsigned int *)t71); t76 = (~(t75)); t77 = *((unsigned int *)t29); t78 = (~(t77)); t79 = *((unsigned int *)t72); t80 = (~(t79)); t81 = (t74 & t76); t82 = (t78 & t80); t83 = (~(t81)); t84 = (~(t82)); t85 = *((unsigned int *)t63); *((unsigned int *)t63) = (t85 & t83); t86 = *((unsigned int *)t63); *((unsigned int *)t63) = (t86 & t84); t87 = *((unsigned int *)t57); *((unsigned int *)t57) = (t87 & t83); t88 = *((unsigned int *)t57); *((unsigned int *)t57) = (t88 & t84); goto LAB15; LAB16: t104 = *((unsigned int *)t93); t105 = *((unsigned int *)t98); *((unsigned int *)t93) = (t104 | t105); t106 = (t91 + 4); t107 = (t92 + 4); t108 = *((unsigned int *)t106); t109 = (~(t108)); t110 = *((unsigned int *)t91); t111 = (t110 & t109); t112 = *((unsigned int *)t107); t113 = (~(t112)); t114 = *((unsigned int *)t92); t115 = (t114 & t113); t116 = (~(t111)); t117 = (~(t115)); t118 = *((unsigned int *)t98); *((unsigned int *)t98) = (t118 & t116); t119 = *((unsigned int *)t98); *((unsigned int *)t98) = (t119 & t117); goto LAB18; LAB19: t132 = *((unsigned int *)t120); t133 = *((unsigned int *)t126); *((unsigned int *)t120) = (t132 | t133); t134 = (t90 + 4); t135 = (t93 + 4); t136 = *((unsigned int *)t90); t137 = (~(t136)); t138 = *((unsigned int *)t134); t139 = (~(t138)); t140 = *((unsigned int *)t93); t141 = (~(t140)); t142 = *((unsigned int *)t135); t143 = (~(t142)); t144 = (t137 & t139); t145 = (t141 & t143); t146 = (~(t144)); t147 = (~(t145)); t148 = *((unsigned int *)t126); *((unsigned int *)t126) = (t148 & t146); t149 = *((unsigned int *)t126); *((unsigned int *)t126) = (t149 & t147); t150 = *((unsigned int *)t120); *((unsigned int *)t120) = (t150 & t146); t151 = *((unsigned int *)t120); *((unsigned int *)t120) = (t151 & t147); goto LAB21; LAB22: t164 = *((unsigned int *)t152); t165 = *((unsigned int *)t158); *((unsigned int *)t152) = (t164 | t165); t166 = (t57 + 4); t167 = (t120 + 4); t168 = *((unsigned int *)t166); t169 = (~(t168)); t170 = *((unsigned int *)t57); t171 = (t170 & t169); t172 = *((unsigned int *)t167); t173 = (~(t172)); t174 = *((unsigned int *)t120); t175 = (t174 & t173); t176 = (~(t171)); t177 = (~(t175)); t178 = *((unsigned int *)t158); *((unsigned int *)t158) = (t178 & t176); t179 = *((unsigned int *)t158); *((unsigned int *)t158) = (t179 & t177); goto LAB24; LAB25: *((unsigned int *)t4) = 1; goto LAB28; LAB30: t191 = *((unsigned int *)t4); t192 = *((unsigned int *)t188); *((unsigned int *)t4) = (t191 | t192); t193 = *((unsigned int *)t187); t194 = *((unsigned int *)t188); *((unsigned int *)t187) = (t193 | t194); goto LAB29; LAB31: t210 = *((unsigned int *)t199); t211 = *((unsigned int *)t204); *((unsigned int *)t199) = (t210 | t211); goto LAB33; LAB34: *((unsigned int *)t3) = 1; goto LAB37; LAB39: t223 = *((unsigned int *)t3); t224 = *((unsigned int *)t220); *((unsigned int *)t3) = (t223 | t224); t225 = *((unsigned int *)t219); t226 = *((unsigned int *)t220); *((unsigned int *)t219) = (t225 | t226); goto LAB38; } static void Cont_41_8(char *t0) { char t3[8]; char t4[8]; char t5[8]; char t29[8]; char t60[8]; char t88[8]; char t124[8]; char t153[8]; char t180[8]; char t212[8]; char t259[8]; char *t1; char *t2; char *t6; unsigned int t7; unsigned int t8; unsigned int t9; unsigned int t10; unsigned int t11; char *t12; char *t13; char *t14; unsigned int t15; unsigned int t16; unsigned int t17; unsigned int t18; unsigned int t19; unsigned int t20; unsigned int t21; unsigned int t22; char *t23; char *t24; char *t25; char *t26; char *t27; char *t28; unsigned int t30; unsigned int t31; unsigned int t32; char *t33; char *t34; char *t35; unsigned int t36; unsigned int t37; unsigned int t38; unsigned int t39; unsigned int t40; unsigned int t41; unsigned int t42; char *t43; char *t44; unsigned int t45; unsigned int t46; unsigned int t47; int t48; unsigned int t49; unsigned int t50; unsigned int t51; int t52; unsigned int t53; unsigned int t54; unsigned int t55; unsigned int t56; char *t57; char *t58; char *t59; unsigned int t61; unsigned int t62; unsigned int t63; char *t64; char *t65; char *t66; unsigned int t67; unsigned int t68; unsigned int t69; unsigned int t70; unsigned int t71; unsigned int t72; unsigned int t73; char *t74; char *t75; unsigned int t76; unsigned int t77; unsigned int t78; int t79; unsigned int t80; unsigned int t81; unsigned int t82; int t83; unsigned int t84; unsigned int t85; unsigned int t86; unsigned int t87; unsigned int t89; unsigned int t90; unsigned int t91; char *t92; char *t93; char *t94; unsigned int t95; unsigned int t96; unsigned int t97; unsigned int t98; unsigned int t99; unsigned int t100; unsigned int t101; char *t102; char *t103; unsigned int t104; unsigned int t105; unsigned int t106; unsigned int t107; unsigned int t108; unsigned int t109; unsigned int t110; unsigned int t111; int t112; int t113; unsigned int t114; unsigned int t115; unsigned int t116; unsigned int t117; unsigned int t118; unsigned int t119; char *t120; char *t121; char *t122; char *t123; unsigned int t125; unsigned int t126; unsigned int t127; char *t128; char *t129; unsigned int t130; unsigned int t131; unsigned int t132; unsigned int t133; unsigned int t134; unsigned int t135; unsigned int t136; char *t137; char *t138; unsigned int t139; unsigned int t140; unsigned int t141; int t142; unsigned int t143; unsigned int t144; unsigned int t145; int t146; unsigned int t147; unsigned int t148; unsigned int t149; unsigned int t150; char *t151; char *t152; unsigned int t154; unsigned int t155; unsigned int t156; char *t157; char *t158; unsigned int t159; unsigned int t160; unsigned int t161; unsigned int t162; unsigned int t163; unsigned int t164; unsigned int t165; char *t166; char *t167; unsigned int t168; unsigned int t169; unsigned int t170; int t171; unsigned int t172; unsigned int t173; unsigned int t174; int t175; unsigned int t176; unsigned int t177; unsigned int t178; unsigned int t179; unsigned int t181; unsigned int t182; unsigned int t183; char *t184; char *t185; char *t186; unsigned int t187; unsigned int t188; unsigned int t189; unsigned int t190; unsigned int t191; unsigned int t192; unsigned int t193; char *t194; char *t195; unsigned int t196; unsigned int t197; unsigned int t198; unsigned int t199; unsigned int t200; unsigned int t201; unsigned int t202; unsigned int t203; int t204; int t205; unsigned int t206; unsigned int t207; unsigned int t208; unsigned int t209; unsigned int t210; unsigned int t211; unsigned int t213; unsigned int t214; unsigned int t215; char *t216; char *t217; char *t218; unsigned int t219; unsigned int t220; unsigned int t221; unsigned int t222; unsigned int t223; unsigned int t224; unsigned int t225; char *t226; char *t227; unsigned int t228; unsigned int t229; unsigned int t230; int t231; unsigned int t232; unsigned int t233; unsigned int t234; int t235; unsigned int t236; unsigned int t237; unsigned int t238; unsigned int t239; char *t240; unsigned int t241; unsigned int t242; unsigned int t243; unsigned int t244; unsigned int t245; char *t246; char *t247; char *t248; unsigned int t249; unsigned int t250; unsigned int t251; unsigned int t252; unsigned int t253; unsigned int t254; unsigned int t255; unsigned int t256; char *t257; char *t258; unsigned int t260; unsigned int t261; unsigned int t262; char *t263; char *t264; unsigned int t265; unsigned int t266; unsigned int t267; unsigned int t268; unsigned int t269; unsigned int t270; unsigned int t271; char *t272; unsigned int t273; unsigned int t274; unsigned int t275; unsigned int t276; unsigned int t277; char *t278; char *t279; char *t280; unsigned int t281; unsigned int t282; unsigned int t283; unsigned int t284; unsigned int t285; unsigned int t286; unsigned int t287; unsigned int t288; char *t289; char *t290; char *t291; char *t292; char *t293; unsigned int t294; unsigned int t295; char *t296; unsigned int t297; unsigned int t298; char *t299; unsigned int t300; unsigned int t301; char *t302; LAB0: t1 = (t0 + 6752U); t2 = *((char **)t1); if (t2 == 0) goto LAB2; LAB3: goto *t2; LAB2: xsi_set_current_line(41, ng0); t2 = (t0 + 1368U); t6 = *((char **)t2); memset(t5, 0, 8); t2 = (t6 + 4); t7 = *((unsigned int *)t2); t8 = (~(t7)); t9 = *((unsigned int *)t6); t10 = (t9 & t8); t11 = (t10 & 1U); if (t11 != 0) goto LAB7; LAB5: if (*((unsigned int *)t2) == 0) goto LAB4; LAB6: t12 = (t5 + 4); *((unsigned int *)t5) = 1; *((unsigned int *)t12) = 1; LAB7: t13 = (t5 + 4); t14 = (t6 + 4); t15 = *((unsigned int *)t6); t16 = (~(t15)); *((unsigned int *)t5) = t16; *((unsigned int *)t13) = 0; if (*((unsigned int *)t14) != 0) goto LAB9; LAB8: t21 = *((unsigned int *)t5); *((unsigned int *)t5) = (t21 & 1U); t22 = *((unsigned int *)t13); *((unsigned int *)t13) = (t22 & 1U); t23 = (t0 + 3848); t24 = (t23 + 56U); t25 = *((char **)t24); t26 = (t0 + 3688); t27 = (t26 + 56U); t28 = *((char **)t27); t30 = *((unsigned int *)t25); t31 = *((unsigned int *)t28); t32 = (t30 | t31); *((unsigned int *)t29) = t32; t33 = (t25 + 4); t34 = (t28 + 4); t35 = (t29 + 4); t36 = *((unsigned int *)t33); t37 = *((unsigned int *)t34); t38 = (t36 | t37); *((unsigned int *)t35) = t38; t39 = *((unsigned int *)t35); t40 = (t39 != 0); if (t40 == 1) goto LAB10; LAB11: LAB12: t57 = (t0 + 3528); t58 = (t57 + 56U); t59 = *((char **)t58); t61 = *((unsigned int *)t29); t62 = *((unsigned int *)t59); t63 = (t61 | t62); *((unsigned int *)t60) = t63; t64 = (t29 + 4); t65 = (t59 + 4); t66 = (t60 + 4); t67 = *((unsigned int *)t64); t68 = *((unsigned int *)t65); t69 = (t67 | t68); *((unsigned int *)t66) = t69; t70 = *((unsigned int *)t66); t71 = (t70 != 0); if (t71 == 1) goto LAB13; LAB14: LAB15: t89 = *((unsigned int *)t5); t90 = *((unsigned int *)t60); t91 = (t89 & t90); *((unsigned int *)t88) = t91; t92 = (t5 + 4); t93 = (t60 + 4); t94 = (t88 + 4); t95 = *((unsigned int *)t92); t96 = *((unsigned int *)t93); t97 = (t95 | t96); *((unsigned int *)t94) = t97; t98 = *((unsigned int *)t94); t99 = (t98 != 0); if (t99 == 1) goto LAB16; LAB17: LAB18: t120 = (t0 + 1368U); t121 = *((char **)t120); t120 = (t0 + 2488U); t122 = *((char **)t120); t120 = (t0 + 2648U); t123 = *((char **)t120); t125 = *((unsigned int *)t122); t126 = *((unsigned int *)t123); t127 = (t125 | t126); *((unsigned int *)t124) = t127; t120 = (t122 + 4); t128 = (t123 + 4); t129 = (t124 + 4); t130 = *((unsigned int *)t120); t131 = *((unsigned int *)t128); t132 = (t130 | t131); *((unsigned int *)t129) = t132; t133 = *((unsigned int *)t129); t134 = (t133 != 0); if (t134 == 1) goto LAB19; LAB20: LAB21: t151 = (t0 + 2808U); t152 = *((char **)t151); t154 = *((unsigned int *)t124); t155 = *((unsigned int *)t152); t156 = (t154 | t155); *((unsigned int *)t153) = t156; t151 = (t124 + 4); t157 = (t152 + 4); t158 = (t153 + 4); t159 = *((unsigned int *)t151); t160 = *((unsigned int *)t157); t161 = (t159 | t160); *((unsigned int *)t158) = t161; t162 = *((unsigned int *)t158); t163 = (t162 != 0); if (t163 == 1) goto LAB22; LAB23: LAB24: t181 = *((unsigned int *)t121); t182 = *((unsigned int *)t153); t183 = (t181 & t182); *((unsigned int *)t180) = t183; t184 = (t121 + 4); t185 = (t153 + 4); t186 = (t180 + 4); t187 = *((unsigned int *)t184); t188 = *((unsigned int *)t185); t189 = (t187 | t188); *((unsigned int *)t186) = t189; t190 = *((unsigned int *)t186); t191 = (t190 != 0); if (t191 == 1) goto LAB25; LAB26: LAB27: t213 = *((unsigned int *)t88); t214 = *((unsigned int *)t180); t215 = (t213 | t214); *((unsigned int *)t212) = t215; t216 = (t88 + 4); t217 = (t180 + 4); t218 = (t212 + 4); t219 = *((unsigned int *)t216); t220 = *((unsigned int *)t217); t221 = (t219 | t220); *((unsigned int *)t218) = t221; t222 = *((unsigned int *)t218); t223 = (t222 != 0); if (t223 == 1) goto LAB28; LAB29: LAB30: memset(t4, 0, 8); t240 = (t212 + 4); t241 = *((unsigned int *)t240); t242 = (~(t241)); t243 = *((unsigned int *)t212); t244 = (t243 & t242); t245 = (t244 & 1U); if (t245 != 0) goto LAB34; LAB32: if (*((unsigned int *)t240) == 0) goto LAB31; LAB33: t246 = (t4 + 4); *((unsigned int *)t4) = 1; *((unsigned int *)t246) = 1; LAB34: t247 = (t4 + 4); t248 = (t212 + 4); t249 = *((unsigned int *)t212); t250 = (~(t249)); *((unsigned int *)t4) = t250; *((unsigned int *)t247) = 0; if (*((unsigned int *)t248) != 0) goto LAB36; LAB35: t255 = *((unsigned int *)t4); *((unsigned int *)t4) = (t255 & 1U); t256 = *((unsigned int *)t247); *((unsigned int *)t247) = (t256 & 1U); t257 = (t0 + 2968U); t258 = *((char **)t257); t260 = *((unsigned int *)t4); t261 = *((unsigned int *)t258); t262 = (t260 ^ t261); *((unsigned int *)t259) = t262; t257 = (t4 + 4); t263 = (t258 + 4); t264 = (t259 + 4); t265 = *((unsigned int *)t257); t266 = *((unsigned int *)t263); t267 = (t265 | t266); *((unsigned int *)t264) = t267; t268 = *((unsigned int *)t264); t269 = (t268 != 0); if (t269 == 1) goto LAB37; LAB38: LAB39: memset(t3, 0, 8); t272 = (t259 + 4); t273 = *((unsigned int *)t272); t274 = (~(t273)); t275 = *((unsigned int *)t259); t276 = (t275 & t274); t277 = (t276 & 1U); if (t277 != 0) goto LAB43; LAB41: if (*((unsigned int *)t272) == 0) goto LAB40; LAB42: t278 = (t3 + 4); *((unsigned int *)t3) = 1; *((unsigned int *)t278) = 1; LAB43: t279 = (t3 + 4); t280 = (t259 + 4); t281 = *((unsigned int *)t259); t282 = (~(t281)); *((unsigned int *)t3) = t282; *((unsigned int *)t279) = 0; if (*((unsigned int *)t280) != 0) goto LAB45; LAB44: t287 = *((unsigned int *)t3); *((unsigned int *)t3) = (t287 & 1U); t288 = *((unsigned int *)t279); *((unsigned int *)t279) = (t288 & 1U); t289 = (t0 + 8504); t290 = (t289 + 56U); t291 = *((char **)t290); t292 = (t291 + 56U); t293 = *((char **)t292); memset(t293, 0, 8); t294 = 1U; t295 = t294; t296 = (t3 + 4); t297 = *((unsigned int *)t3); t294 = (t294 & t297); t298 = *((unsigned int *)t296); t295 = (t295 & t298); t299 = (t293 + 4); t300 = *((unsigned int *)t293); *((unsigned int *)t293) = (t300 | t294); t301 = *((unsigned int *)t299); *((unsigned int *)t299) = (t301 | t295); xsi_driver_vfirst_trans(t289, 0, 0); t302 = (t0 + 7928); *((int *)t302) = 1; LAB1: return; LAB4: *((unsigned int *)t5) = 1; goto LAB7; LAB9: t17 = *((unsigned int *)t5); t18 = *((unsigned int *)t14); *((unsigned int *)t5) = (t17 | t18); t19 = *((unsigned int *)t13); t20 = *((unsigned int *)t14); *((unsigned int *)t13) = (t19 | t20); goto LAB8; LAB10: t41 = *((unsigned int *)t29); t42 = *((unsigned int *)t35); *((unsigned int *)t29) = (t41 | t42); t43 = (t25 + 4); t44 = (t28 + 4); t45 = *((unsigned int *)t43); t46 = (~(t45)); t47 = *((unsigned int *)t25); t48 = (t47 & t46); t49 = *((unsigned int *)t44); t50 = (~(t49)); t51 = *((unsigned int *)t28); t52 = (t51 & t50); t53 = (~(t48)); t54 = (~(t52)); t55 = *((unsigned int *)t35); *((unsigned int *)t35) = (t55 & t53); t56 = *((unsigned int *)t35); *((unsigned int *)t35) = (t56 & t54); goto LAB12; LAB13: t72 = *((unsigned int *)t60); t73 = *((unsigned int *)t66); *((unsigned int *)t60) = (t72 | t73); t74 = (t29 + 4); t75 = (t59 + 4); t76 = *((unsigned int *)t74); t77 = (~(t76)); t78 = *((unsigned int *)t29); t79 = (t78 & t77); t80 = *((unsigned int *)t75); t81 = (~(t80)); t82 = *((unsigned int *)t59); t83 = (t82 & t81); t84 = (~(t79)); t85 = (~(t83)); t86 = *((unsigned int *)t66); *((unsigned int *)t66) = (t86 & t84); t87 = *((unsigned int *)t66); *((unsigned int *)t66) = (t87 & t85); goto LAB15; LAB16: t100 = *((unsigned int *)t88); t101 = *((unsigned int *)t94); *((unsigned int *)t88) = (t100 | t101); t102 = (t5 + 4); t103 = (t60 + 4); t104 = *((unsigned int *)t5); t105 = (~(t104)); t106 = *((unsigned int *)t102); t107 = (~(t106)); t108 = *((unsigned int *)t60); t109 = (~(t108)); t110 = *((unsigned int *)t103); t111 = (~(t110)); t112 = (t105 & t107); t113 = (t109 & t111); t114 = (~(t112)); t115 = (~(t113)); t116 = *((unsigned int *)t94); *((unsigned int *)t94) = (t116 & t114); t117 = *((unsigned int *)t94); *((unsigned int *)t94) = (t117 & t115); t118 = *((unsigned int *)t88); *((unsigned int *)t88) = (t118 & t114); t119 = *((unsigned int *)t88); *((unsigned int *)t88) = (t119 & t115); goto LAB18; LAB19: t135 = *((unsigned int *)t124); t136 = *((unsigned int *)t129); *((unsigned int *)t124) = (t135 | t136); t137 = (t122 + 4); t138 = (t123 + 4); t139 = *((unsigned int *)t137); t140 = (~(t139)); t141 = *((unsigned int *)t122); t142 = (t141 & t140); t143 = *((unsigned int *)t138); t144 = (~(t143)); t145 = *((unsigned int *)t123); t146 = (t145 & t144); t147 = (~(t142)); t148 = (~(t146)); t149 = *((unsigned int *)t129); *((unsigned int *)t129) = (t149 & t147); t150 = *((unsigned int *)t129); *((unsigned int *)t129) = (t150 & t148); goto LAB21; LAB22: t164 = *((unsigned int *)t153); t165 = *((unsigned int *)t158); *((unsigned int *)t153) = (t164 | t165); t166 = (t124 + 4); t167 = (t152 + 4); t168 = *((unsigned int *)t166); t169 = (~(t168)); t170 = *((unsigned int *)t124); t171 = (t170 & t169); t172 = *((unsigned int *)t167); t173 = (~(t172)); t174 = *((unsigned int *)t152); t175 = (t174 & t173); t176 = (~(t171)); t177 = (~(t175)); t178 = *((unsigned int *)t158); *((unsigned int *)t158) = (t178 & t176); t179 = *((unsigned int *)t158); *((unsigned int *)t158) = (t179 & t177); goto LAB24; LAB25: t192 = *((unsigned int *)t180); t193 = *((unsigned int *)t186); *((unsigned int *)t180) = (t192 | t193); t194 = (t121 + 4); t195 = (t153 + 4); t196 = *((unsigned int *)t121); t197 = (~(t196)); t198 = *((unsigned int *)t194); t199 = (~(t198)); t200 = *((unsigned int *)t153); t201 = (~(t200)); t202 = *((unsigned int *)t195); t203 = (~(t202)); t204 = (t197 & t199); t205 = (t201 & t203); t206 = (~(t204)); t207 = (~(t205)); t208 = *((unsigned int *)t186); *((unsigned int *)t186) = (t208 & t206); t209 = *((unsigned int *)t186); *((unsigned int *)t186) = (t209 & t207); t210 = *((unsigned int *)t180); *((unsigned int *)t180) = (t210 & t206); t211 = *((unsigned int *)t180); *((unsigned int *)t180) = (t211 & t207); goto LAB27; LAB28: t224 = *((unsigned int *)t212); t225 = *((unsigned int *)t218); *((unsigned int *)t212) = (t224 | t225); t226 = (t88 + 4); t227 = (t180 + 4); t228 = *((unsigned int *)t226); t229 = (~(t228)); t230 = *((unsigned int *)t88); t231 = (t230 & t229); t232 = *((unsigned int *)t227); t233 = (~(t232)); t234 = *((unsigned int *)t180); t235 = (t234 & t233); t236 = (~(t231)); t237 = (~(t235)); t238 = *((unsigned int *)t218); *((unsigned int *)t218) = (t238 & t236); t239 = *((unsigned int *)t218); *((unsigned int *)t218) = (t239 & t237); goto LAB30; LAB31: *((unsigned int *)t4) = 1; goto LAB34; LAB36: t251 = *((unsigned int *)t4); t252 = *((unsigned int *)t248); *((unsigned int *)t4) = (t251 | t252); t253 = *((unsigned int *)t247); t254 = *((unsigned int *)t248); *((unsigned int *)t247) = (t253 | t254); goto LAB35; LAB37: t270 = *((unsigned int *)t259); t271 = *((unsigned int *)t264); *((unsigned int *)t259) = (t270 | t271); goto LAB39; LAB40: *((unsigned int *)t3) = 1; goto LAB43; LAB45: t283 = *((unsigned int *)t3); t284 = *((unsigned int *)t280); *((unsigned int *)t3) = (t283 | t284); t285 = *((unsigned int *)t279); t286 = *((unsigned int *)t280); *((unsigned int *)t279) = (t285 | t286); goto LAB44; } static void Cont_42_9(char *t0) { char t3[8]; char t23[8]; char t56[8]; char t89[8]; char t122[8]; char t157[8]; char t192[8]; char t227[8]; char t262[8]; char t294[8]; char *t1; char *t2; char *t4; unsigned int t5; unsigned int t6; unsigned int t7; unsigned int t8; unsigned int t9; char *t10; char *t11; char *t12; unsigned int t13; unsigned int t14; unsigned int t15; unsigned int t16; unsigned int t17; unsigned int t18; unsigned int t19; unsigned int t20; char *t21; char *t22; unsigned int t24; unsigned int t25; unsigned int t26; char *t27; char *t28; unsigned int t29; unsigned int t30; unsigned int t31; unsigned int t32; unsigned int t33; unsigned int t34; unsigned int t35; char *t36; char *t37; unsigned int t38; unsigned int t39; unsigned int t40; unsigned int t41; unsigned int t42; unsigned int t43; unsigned int t44; unsigned int t45; int t46; int t47; unsigned int t48; unsigned int t49; unsigned int t50; unsigned int t51; unsigned int t52; unsigned int t53; char *t54; char *t55; unsigned int t57; unsigned int t58; unsigned int t59; char *t60; char *t61; unsigned int t62; unsigned int t63; unsigned int t64; unsigned int t65; unsigned int t66; unsigned int t67; unsigned int t68; char *t69; char *t70; unsigned int t71; unsigned int t72; unsigned int t73; unsigned int t74; unsigned int t75; unsigned int t76; unsigned int t77; unsigned int t78; int t79; int t80; unsigned int t81; unsigned int t82; unsigned int t83; unsigned int t84; unsigned int t85; unsigned int t86; char *t87; char *t88; unsigned int t90; unsigned int t91; unsigned int t92; char *t93; char *t94; unsigned int t95; unsigned int t96; unsigned int t97; unsigned int t98; unsigned int t99; unsigned int t100; unsigned int t101; char *t102; char *t103; unsigned int t104; unsigned int t105; unsigned int t106; unsigned int t107; unsigned int t108; unsigned int t109; unsigned int t110; unsigned int t111; int t112; int t113; unsigned int t114; unsigned int t115; unsigned int t116; unsigned int t117; unsigned int t118; unsigned int t119; char *t120; char *t121; unsigned int t123; unsigned int t124; unsigned int t125; char *t126; char *t127; unsigned int t128; unsigned int t129; unsigned int t130; unsigned int t131; unsigned int t132; unsigned int t133; unsigned int t134; char *t135; char *t136; unsigned int t137; unsigned int t138; unsigned int t139; unsigned int t140; unsigned int t141; unsigned int t142; unsigned int t143; unsigned int t144; int t145; int t146; unsigned int t147; unsigned int t148; unsigned int t149; unsigned int t150; unsigned int t151; unsigned int t152; char *t153; char *t154; char *t155; char *t156; unsigned int t158; unsigned int t159; unsigned int t160; char *t161; char *t162; char *t163; unsigned int t164; unsigned int t165; unsigned int t166; unsigned int t167; unsigned int t168; unsigned int t169; unsigned int t170; char *t171; char *t172; unsigned int t173; unsigned int t174; unsigned int t175; unsigned int t176; unsigned int t177; unsigned int t178; unsigned int t179; unsigned int t180; int t181; int t182; unsigned int t183; unsigned int t184; unsigned int t185; unsigned int t186; unsigned int t187; unsigned int t188; char *t189; char *t190; char *t191; unsigned int t193; unsigned int t194; unsigned int t195; char *t196; char *t197; char *t198; unsigned int t199; unsigned int t200; unsigned int t201; unsigned int t202; unsigned int t203; unsigned int t204; unsigned int t205; char *t206; char *t207; unsigned int t208; unsigned int t209; unsigned int t210; unsigned int t211; unsigned int t212; unsigned int t213; unsigned int t214; unsigned int t215; int t216; int t217; unsigned int t218; unsigned int t219; unsigned int t220; unsigned int t221; unsigned int t222; unsigned int t223; char *t224; char *t225; char *t226; unsigned int t228; unsigned int t229; unsigned int t230; char *t231; char *t232; char *t233; unsigned int t234; unsigned int t235; unsigned int t236; unsigned int t237; unsigned int t238; unsigned int t239; unsigned int t240; char *t241; char *t242; unsigned int t243; unsigned int t244; unsigned int t245; unsigned int t246; unsigned int t247; unsigned int t248; unsigned int t249; unsigned int t250; int t251; int t252; unsigned int t253; unsigned int t254; unsigned int t255; unsigned int t256; unsigned int t257; unsigned int t258; char *t259; char *t260; char *t261; unsigned int t263; unsigned int t264; unsigned int t265; char *t266; char *t267; char *t268; unsigned int t269; unsigned int t270; unsigned int t271; unsigned int t272; unsigned int t273; unsigned int t274; unsigned int t275; char *t276; char *t277; unsigned int t278; unsigned int t279; unsigned int t280; unsigned int t281; unsigned int t282; unsigned int t283; unsigned int t284; unsigned int t285; int t286; int t287; unsigned int t288; unsigned int t289; unsigned int t290; unsigned int t291; unsigned int t292; unsigned int t293; unsigned int t295; unsigned int t296; unsigned int t297; char *t298; char *t299; char *t300; unsigned int t301; unsigned int t302; unsigned int t303; unsigned int t304; unsigned int t305; unsigned int t306; unsigned int t307; char *t308; char *t309; unsigned int t310; unsigned int t311; unsigned int t312; int t313; unsigned int t314; unsigned int t315; unsigned int t316; int t317; unsigned int t318; unsigned int t319; unsigned int t320; unsigned int t321; char *t322; char *t323; char *t324; char *t325; char *t326; unsigned int t327; unsigned int t328; char *t329; unsigned int t330; unsigned int t331; char *t332; unsigned int t333; unsigned int t334; char *t335; LAB0: t1 = (t0 + 7000U); t2 = *((char **)t1); if (t2 == 0) goto LAB2; LAB3: goto *t2; LAB2: xsi_set_current_line(42, ng0); t2 = (t0 + 1368U); t4 = *((char **)t2); memset(t3, 0, 8); t2 = (t4 + 4); t5 = *((unsigned int *)t2); t6 = (~(t5)); t7 = *((unsigned int *)t4); t8 = (t7 & t6); t9 = (t8 & 1U); if (t9 != 0) goto LAB7; LAB5: if (*((unsigned int *)t2) == 0) goto LAB4; LAB6: t10 = (t3 + 4); *((unsigned int *)t3) = 1; *((unsigned int *)t10) = 1; LAB7: t11 = (t3 + 4); t12 = (t4 + 4); t13 = *((unsigned int *)t4); t14 = (~(t13)); *((unsigned int *)t3) = t14; *((unsigned int *)t11) = 0; if (*((unsigned int *)t12) != 0) goto LAB9; LAB8: t19 = *((unsigned int *)t3); *((unsigned int *)t3) = (t19 & 1U); t20 = *((unsigned int *)t11); *((unsigned int *)t11) = (t20 & 1U); t21 = (t0 + 2488U); t22 = *((char **)t21); t24 = *((unsigned int *)t3); t25 = *((unsigned int *)t22); t26 = (t24 & t25); *((unsigned int *)t23) = t26; t21 = (t3 + 4); t27 = (t22 + 4); t28 = (t23 + 4); t29 = *((unsigned int *)t21); t30 = *((unsigned int *)t27); t31 = (t29 | t30); *((unsigned int *)t28) = t31; t32 = *((unsigned int *)t28); t33 = (t32 != 0); if (t33 == 1) goto LAB10; LAB11: LAB12: t54 = (t0 + 2648U); t55 = *((char **)t54); t57 = *((unsigned int *)t23); t58 = *((unsigned int *)t55); t59 = (t57 & t58); *((unsigned int *)t56) = t59; t54 = (t23 + 4); t60 = (t55 + 4); t61 = (t56 + 4); t62 = *((unsigned int *)t54); t63 = *((unsigned int *)t60); t64 = (t62 | t63); *((unsigned int *)t61) = t64; t65 = *((unsigned int *)t61); t66 = (t65 != 0); if (t66 == 1) goto LAB13; LAB14: LAB15: t87 = (t0 + 2808U); t88 = *((char **)t87); t90 = *((unsigned int *)t56); t91 = *((unsigned int *)t88); t92 = (t90 & t91); *((unsigned int *)t89) = t92; t87 = (t56 + 4); t93 = (t88 + 4); t94 = (t89 + 4); t95 = *((unsigned int *)t87); t96 = *((unsigned int *)t93); t97 = (t95 | t96); *((unsigned int *)t94) = t97; t98 = *((unsigned int *)t94); t99 = (t98 != 0); if (t99 == 1) goto LAB16; LAB17: LAB18: t120 = (t0 + 2968U); t121 = *((char **)t120); t123 = *((unsigned int *)t89); t124 = *((unsigned int *)t121); t125 = (t123 & t124); *((unsigned int *)t122) = t125; t120 = (t89 + 4); t126 = (t121 + 4); t127 = (t122 + 4); t128 = *((unsigned int *)t120); t129 = *((unsigned int *)t126); t130 = (t128 | t129); *((unsigned int *)t127) = t130; t131 = *((unsigned int *)t127); t132 = (t131 != 0); if (t132 == 1) goto LAB19; LAB20: LAB21: t153 = (t0 + 1368U); t154 = *((char **)t153); t153 = (t0 + 3848); t155 = (t153 + 56U); t156 = *((char **)t155); t158 = *((unsigned int *)t154); t159 = *((unsigned int *)t156); t160 = (t158 & t159); *((unsigned int *)t157) = t160; t161 = (t154 + 4); t162 = (t156 + 4); t163 = (t157 + 4); t164 = *((unsigned int *)t161); t165 = *((unsigned int *)t162); t166 = (t164 | t165); *((unsigned int *)t163) = t166; t167 = *((unsigned int *)t163); t168 = (t167 != 0); if (t168 == 1) goto LAB22; LAB23: LAB24: t189 = (t0 + 3688); t190 = (t189 + 56U); t191 = *((char **)t190); t193 = *((unsigned int *)t157); t194 = *((unsigned int *)t191); t195 = (t193 & t194); *((unsigned int *)t192) = t195; t196 = (t157 + 4); t197 = (t191 + 4); t198 = (t192 + 4); t199 = *((unsigned int *)t196); t200 = *((unsigned int *)t197); t201 = (t199 | t200); *((unsigned int *)t198) = t201; t202 = *((unsigned int *)t198); t203 = (t202 != 0); if (t203 == 1) goto LAB25; LAB26: LAB27: t224 = (t0 + 3528); t225 = (t224 + 56U); t226 = *((char **)t225); t228 = *((unsigned int *)t192); t229 = *((unsigned int *)t226); t230 = (t228 & t229); *((unsigned int *)t227) = t230; t231 = (t192 + 4); t232 = (t226 + 4); t233 = (t227 + 4); t234 = *((unsigned int *)t231); t235 = *((unsigned int *)t232); t236 = (t234 | t235); *((unsigned int *)t233) = t236; t237 = *((unsigned int *)t233); t238 = (t237 != 0); if (t238 == 1) goto LAB28; LAB29: LAB30: t259 = (t0 + 3368); t260 = (t259 + 56U); t261 = *((char **)t260); t263 = *((unsigned int *)t227); t264 = *((unsigned int *)t261); t265 = (t263 & t264); *((unsigned int *)t262) = t265; t266 = (t227 + 4); t267 = (t261 + 4); t268 = (t262 + 4); t269 = *((unsigned int *)t266); t270 = *((unsigned int *)t267); t271 = (t269 | t270); *((unsigned int *)t268) = t271; t272 = *((unsigned int *)t268); t273 = (t272 != 0); if (t273 == 1) goto LAB31; LAB32: LAB33: t295 = *((unsigned int *)t122); t296 = *((unsigned int *)t262); t297 = (t295 | t296); *((unsigned int *)t294) = t297; t298 = (t122 + 4); t299 = (t262 + 4); t300 = (t294 + 4); t301 = *((unsigned int *)t298); t302 = *((unsigned int *)t299); t303 = (t301 | t302); *((unsigned int *)t300) = t303; t304 = *((unsigned int *)t300); t305 = (t304 != 0); if (t305 == 1) goto LAB34; LAB35: LAB36: t322 = (t0 + 8568); t323 = (t322 + 56U); t324 = *((char **)t323); t325 = (t324 + 56U); t326 = *((char **)t325); memset(t326, 0, 8); t327 = 1U; t328 = t327; t329 = (t294 + 4); t330 = *((unsigned int *)t294); t327 = (t327 & t330); t331 = *((unsigned int *)t329); t328 = (t328 & t331); t332 = (t326 + 4); t333 = *((unsigned int *)t326); *((unsigned int *)t326) = (t333 | t327); t334 = *((unsigned int *)t332); *((unsigned int *)t332) = (t334 | t328); xsi_driver_vfirst_trans(t322, 0, 0); t335 = (t0 + 7944); *((int *)t335) = 1; LAB1: return; LAB4: *((unsigned int *)t3) = 1; goto LAB7; LAB9: t15 = *((unsigned int *)t3); t16 = *((unsigned int *)t12); *((unsigned int *)t3) = (t15 | t16); t17 = *((unsigned int *)t11); t18 = *((unsigned int *)t12); *((unsigned int *)t11) = (t17 | t18); goto LAB8; LAB10: t34 = *((unsigned int *)t23); t35 = *((unsigned int *)t28); *((unsigned int *)t23) = (t34 | t35); t36 = (t3 + 4); t37 = (t22 + 4); t38 = *((unsigned int *)t3); t39 = (~(t38)); t40 = *((unsigned int *)t36); t41 = (~(t40)); t42 = *((unsigned int *)t22); t43 = (~(t42)); t44 = *((unsigned int *)t37); t45 = (~(t44)); t46 = (t39 & t41); t47 = (t43 & t45); t48 = (~(t46)); t49 = (~(t47)); t50 = *((unsigned int *)t28); *((unsigned int *)t28) = (t50 & t48); t51 = *((unsigned int *)t28); *((unsigned int *)t28) = (t51 & t49); t52 = *((unsigned int *)t23); *((unsigned int *)t23) = (t52 & t48); t53 = *((unsigned int *)t23); *((unsigned int *)t23) = (t53 & t49); goto LAB12; LAB13: t67 = *((unsigned int *)t56); t68 = *((unsigned int *)t61); *((unsigned int *)t56) = (t67 | t68); t69 = (t23 + 4); t70 = (t55 + 4); t71 = *((unsigned int *)t23); t72 = (~(t71)); t73 = *((unsigned int *)t69); t74 = (~(t73)); t75 = *((unsigned int *)t55); t76 = (~(t75)); t77 = *((unsigned int *)t70); t78 = (~(t77)); t79 = (t72 & t74); t80 = (t76 & t78); t81 = (~(t79)); t82 = (~(t80)); t83 = *((unsigned int *)t61); *((unsigned int *)t61) = (t83 & t81); t84 = *((unsigned int *)t61); *((unsigned int *)t61) = (t84 & t82); t85 = *((unsigned int *)t56); *((unsigned int *)t56) = (t85 & t81); t86 = *((unsigned int *)t56); *((unsigned int *)t56) = (t86 & t82); goto LAB15; LAB16: t100 = *((unsigned int *)t89); t101 = *((unsigned int *)t94); *((unsigned int *)t89) = (t100 | t101); t102 = (t56 + 4); t103 = (t88 + 4); t104 = *((unsigned int *)t56); t105 = (~(t104)); t106 = *((unsigned int *)t102); t107 = (~(t106)); t108 = *((unsigned int *)t88); t109 = (~(t108)); t110 = *((unsigned int *)t103); t111 = (~(t110)); t112 = (t105 & t107); t113 = (t109 & t111); t114 = (~(t112)); t115 = (~(t113)); t116 = *((unsigned int *)t94); *((unsigned int *)t94) = (t116 & t114); t117 = *((unsigned int *)t94); *((unsigned int *)t94) = (t117 & t115); t118 = *((unsigned int *)t89); *((unsigned int *)t89) = (t118 & t114); t119 = *((unsigned int *)t89); *((unsigned int *)t89) = (t119 & t115); goto LAB18; LAB19: t133 = *((unsigned int *)t122); t134 = *((unsigned int *)t127); *((unsigned int *)t122) = (t133 | t134); t135 = (t89 + 4); t136 = (t121 + 4); t137 = *((unsigned int *)t89); t138 = (~(t137)); t139 = *((unsigned int *)t135); t140 = (~(t139)); t141 = *((unsigned int *)t121); t142 = (~(t141)); t143 = *((unsigned int *)t136); t144 = (~(t143)); t145 = (t138 & t140); t146 = (t142 & t144); t147 = (~(t145)); t148 = (~(t146)); t149 = *((unsigned int *)t127); *((unsigned int *)t127) = (t149 & t147); t150 = *((unsigned int *)t127); *((unsigned int *)t127) = (t150 & t148); t151 = *((unsigned int *)t122); *((unsigned int *)t122) = (t151 & t147); t152 = *((unsigned int *)t122); *((unsigned int *)t122) = (t152 & t148); goto LAB21; LAB22: t169 = *((unsigned int *)t157); t170 = *((unsigned int *)t163); *((unsigned int *)t157) = (t169 | t170); t171 = (t154 + 4); t172 = (t156 + 4); t173 = *((unsigned int *)t154); t174 = (~(t173)); t175 = *((unsigned int *)t171); t176 = (~(t175)); t177 = *((unsigned int *)t156); t178 = (~(t177)); t179 = *((unsigned int *)t172); t180 = (~(t179)); t181 = (t174 & t176); t182 = (t178 & t180); t183 = (~(t181)); t184 = (~(t182)); t185 = *((unsigned int *)t163); *((unsigned int *)t163) = (t185 & t183); t186 = *((unsigned int *)t163); *((unsigned int *)t163) = (t186 & t184); t187 = *((unsigned int *)t157); *((unsigned int *)t157) = (t187 & t183); t188 = *((unsigned int *)t157); *((unsigned int *)t157) = (t188 & t184); goto LAB24; LAB25: t204 = *((unsigned int *)t192); t205 = *((unsigned int *)t198); *((unsigned int *)t192) = (t204 | t205); t206 = (t157 + 4); t207 = (t191 + 4); t208 = *((unsigned int *)t157); t209 = (~(t208)); t210 = *((unsigned int *)t206); t211 = (~(t210)); t212 = *((unsigned int *)t191); t213 = (~(t212)); t214 = *((unsigned int *)t207); t215 = (~(t214)); t216 = (t209 & t211); t217 = (t213 & t215); t218 = (~(t216)); t219 = (~(t217)); t220 = *((unsigned int *)t198); *((unsigned int *)t198) = (t220 & t218); t221 = *((unsigned int *)t198); *((unsigned int *)t198) = (t221 & t219); t222 = *((unsigned int *)t192); *((unsigned int *)t192) = (t222 & t218); t223 = *((unsigned int *)t192); *((unsigned int *)t192) = (t223 & t219); goto LAB27; LAB28: t239 = *((unsigned int *)t227); t240 = *((unsigned int *)t233); *((unsigned int *)t227) = (t239 | t240); t241 = (t192 + 4); t242 = (t226 + 4); t243 = *((unsigned int *)t192); t244 = (~(t243)); t245 = *((unsigned int *)t241); t246 = (~(t245)); t247 = *((unsigned int *)t226); t248 = (~(t247)); t249 = *((unsigned int *)t242); t250 = (~(t249)); t251 = (t244 & t246); t252 = (t248 & t250); t253 = (~(t251)); t254 = (~(t252)); t255 = *((unsigned int *)t233); *((unsigned int *)t233) = (t255 & t253); t256 = *((unsigned int *)t233); *((unsigned int *)t233) = (t256 & t254); t257 = *((unsigned int *)t227); *((unsigned int *)t227) = (t257 & t253); t258 = *((unsigned int *)t227); *((unsigned int *)t227) = (t258 & t254); goto LAB30; LAB31: t274 = *((unsigned int *)t262); t275 = *((unsigned int *)t268); *((unsigned int *)t262) = (t274 | t275); t276 = (t227 + 4); t277 = (t261 + 4); t278 = *((unsigned int *)t227); t279 = (~(t278)); t280 = *((unsigned int *)t276); t281 = (~(t280)); t282 = *((unsigned int *)t261); t283 = (~(t282)); t284 = *((unsigned int *)t277); t285 = (~(t284)); t286 = (t279 & t281); t287 = (t283 & t285); t288 = (~(t286)); t289 = (~(t287)); t290 = *((unsigned int *)t268); *((unsigned int *)t268) = (t290 & t288); t291 = *((unsigned int *)t268); *((unsigned int *)t268) = (t291 & t289); t292 = *((unsigned int *)t262); *((unsigned int *)t262) = (t292 & t288); t293 = *((unsigned int *)t262); *((unsigned int *)t262) = (t293 & t289); goto LAB33; LAB34: t306 = *((unsigned int *)t294); t307 = *((unsigned int *)t300); *((unsigned int *)t294) = (t306 | t307); t308 = (t122 + 4); t309 = (t262 + 4); t310 = *((unsigned int *)t308); t311 = (~(t310)); t312 = *((unsigned int *)t122); t313 = (t312 & t311); t314 = *((unsigned int *)t309); t315 = (~(t314)); t316 = *((unsigned int *)t262); t317 = (t316 & t315); t318 = (~(t313)); t319 = (~(t317)); t320 = *((unsigned int *)t300); *((unsigned int *)t300) = (t320 & t318); t321 = *((unsigned int *)t300); *((unsigned int *)t300) = (t321 & t319); goto LAB36; } static void Cont_44_10(char *t0) { char t3[8]; char *t1; char *t2; char *t4; char *t5; char *t6; char *t7; char *t8; char *t9; char *t10; char *t11; char *t12; char *t13; char *t14; char *t15; char *t16; char *t17; char *t18; char *t19; unsigned int t20; unsigned int t21; char *t22; unsigned int t23; unsigned int t24; char *t25; unsigned int t26; unsigned int t27; char *t28; LAB0: t1 = (t0 + 7248U); t2 = *((char **)t1); if (t2 == 0) goto LAB2; LAB3: goto *t2; LAB2: xsi_set_current_line(44, ng0); t2 = (t0 + 3848); t4 = (t2 + 56U); t5 = *((char **)t4); t6 = (t0 + 3688); t7 = (t6 + 56U); t8 = *((char **)t7); t9 = (t0 + 3528); t10 = (t9 + 56U); t11 = *((char **)t10); t12 = (t0 + 3368); t13 = (t12 + 56U); t14 = *((char **)t13); xsi_vlogtype_concat(t3, 4, 4, 4U, t14, 1, t11, 1, t8, 1, t5, 1); t15 = (t0 + 8632); t16 = (t15 + 56U); t17 = *((char **)t16); t18 = (t17 + 56U); t19 = *((char **)t18); memset(t19, 0, 8); t20 = 15U; t21 = t20; t22 = (t3 + 4); t23 = *((unsigned int *)t3); t20 = (t20 & t23); t24 = *((unsigned int *)t22); t21 = (t21 & t24); t25 = (t19 + 4); t26 = *((unsigned int *)t19); *((unsigned int *)t19) = (t26 | t20); t27 = *((unsigned int *)t25); *((unsigned int *)t25) = (t27 | t21); xsi_driver_vfirst_trans(t15, 0, 3); t28 = (t0 + 7960); *((int *)t28) = 1; LAB1: return; } static void Always_46_11(char *t0) { char t16[8]; char *t1; char *t2; char *t3; char *t4; char *t5; unsigned int t6; unsigned int t7; unsigned int t8; unsigned int t9; unsigned int t10; char *t11; char *t12; char *t13; char *t14; char *t15; LAB0: t1 = (t0 + 7496U); t2 = *((char **)t1); if (t2 == 0) goto LAB2; LAB3: goto *t2; LAB2: xsi_set_current_line(46, ng0); t2 = (t0 + 7976); *((int *)t2) = 1; t3 = (t0 + 7528); *((char **)t3) = t2; *((char **)t1) = &&LAB4; LAB1: return; LAB4: xsi_set_current_line(47, ng0); t4 = (t0 + 1208U); t5 = *((char **)t4); t4 = (t5 + 4); t6 = *((unsigned int *)t4); t7 = (~(t6)); t8 = *((unsigned int *)t5); t9 = (t8 & t7); t10 = (t9 != 0); if (t10 > 0) goto LAB5; LAB6: xsi_set_current_line(48, ng0); t2 = (t0 + 1848U); t3 = *((char **)t2); t2 = (t0 + 2008U); t4 = *((char **)t2); t2 = (t0 + 2168U); t5 = *((char **)t2); t2 = (t0 + 2328U); t11 = *((char **)t2); xsi_vlogtype_concat(t16, 4, 4, 4U, t11, 1, t5, 1, t4, 1, t3, 1); t2 = (t0 + 3848); xsi_vlogvar_wait_assign_value(t2, t16, 0, 0, 1, 0LL); t12 = (t0 + 3688); xsi_vlogvar_wait_assign_value(t12, t16, 1, 0, 1, 0LL); t13 = (t0 + 3528); xsi_vlogvar_wait_assign_value(t13, t16, 2, 0, 1, 0LL); t14 = (t0 + 3368); xsi_vlogvar_wait_assign_value(t14, t16, 3, 0, 1, 0LL); LAB7: goto LAB2; LAB5: xsi_set_current_line(47, ng0); t11 = ((char*)((ng2))); t12 = (t0 + 3848); xsi_vlogvar_wait_assign_value(t12, t11, 0, 0, 1, 0LL); t13 = (t0 + 3688); xsi_vlogvar_wait_assign_value(t13, t11, 1, 0, 1, 0LL); t14 = (t0 + 3528); xsi_vlogvar_wait_assign_value(t14, t11, 2, 0, 1, 0LL); t15 = (t0 + 3368); xsi_vlogvar_wait_assign_value(t15, t11, 3, 0, 1, 0LL); goto LAB7; } extern void work_m_00000000004261765678_3107888780_init() { static char *pe[] = {(void *)Initial_31_0,(void *)Cont_33_1,(void *)Cont_34_2,(void *)Cont_35_3,(void *)Cont_36_4,(void *)Cont_38_5,(void *)Cont_39_6,(void *)Cont_40_7,(void *)Cont_41_8,(void *)Cont_42_9,(void *)Cont_44_10,(void *)Always_46_11}; xsi_register_didat("work_m_00000000004261765678_3107888780", "isim/Conter4bRev_sim_isim_beh.exe.sim/work/m_00000000004261765678_3107888780.didat"); xsi_register_executes(pe); }
jonssa/AirPolutionSensor_ATMega328_GP2Y1010AU0F
src/GP2Y1010AU0F/GP2Y1010AU0F.c
/* * * Created on: 2018-01-02 * Autor: <NAME> * GP2Y1010AU0F.c */ #include <avr/io.h> #include <avr/interrupt.h> #include <util/delay.h> #include "GP2Y1010AU0F.h" #include "../LCD/lcd44780.h" uint16_t D_min = 1000; /*! * init_adc - funkcja inicjalizująca przetwornik ADC */ void init_adc() { ADCSRA |= (1<<ADEN); ///< włącz ADC ADCSRA |= (1<<ADPS2) | (1<<ADPS1); ///< preskaler = 64 ADMUX |= (1<<REFS1) | (1<<REFS0); ///< ustaw napięcie odniesienia na 1.1V SENSOR_LED_DDR |= SENSOR_LED; ///< Ustaw pin do którego jest podłączona dioda czujnika jako wyjście } /*! * count_dust_min - funkcja która co 5 minut do tablicy wpisuje wartośc zapylenia powietrza */ void count_dust_min(void) { static uint8_t iter_5min = 0; ///< zmienna statyczna do odwoływania się do odpowiednich elementów tablicy if((min % 5) == 0 ) ///< jeśli modulo 5 z liczby minut wynosi 0 (jest wielokrotnośc 5 minut) { dust_5min[iter_5min] = avg_dust; if (iter_5min < 12) iter_5min ++; ///< jeśli wartośc zmiennej jest mniejsza niż 11 zwiększ ją o 1 else iter_5min = 0; ///< w przeciwnym wypadku wyzeruj } min_flag = 0; ///< ustaw flagę minut na 0 } /*! * count_dust_h - ta funkcja ma za zadanie wpisywac do wektora średnią godzinną zapylenia powietrza */ void count_dust_h(void) { uint8_t i,j; ///< zmienne lokalne for(j=23; j>0; j--) dust_h[j] = dust_h[j-1]; ///< przesuwanie wektora o jedną pozycję for(i=0; i<12; i++) dust_h[0] = (dust_h[0] + dust_5min[i]); ///< dodawanie wartosci z pomiaru 5 minutowego do 1 elementu tablicy dust_h[0] /= 12; ///< policz średnią dla ostatniej godziny D_max = 0; D_min = 1000; h_flag = 0; ///< flaga godzin na 0 } /*! * count_avg - funkcja wyświetlająca wartośc średnią godzinną na wyświetlacz */ void count_avg(void) { lcd_locate(0,0); lcd_str("Avg -"); lcd_int(tryb+1); lcd_str("h "); lcd_int(dust_h[tryb]); ///< wyświetl wartośc zapylenia godzinnego w zależności od wybranej godziny lcd_str(" mg/m"); lcd_str("\x83"); lcd_str(" "); } /*! * show_caqi - przeliczanie godzinnej wartości zapylenia na współczynnik CAQI */ void show_caqi(void) { uint8_t tmp; ///< zmienna lokalna tmp = dust_h[tryb]; ///< przypisanie wartości do zmiennej lcd_locate(1,0); if (tmp<15) lcd_str(" Bardzo dobra! "); else if (tmp >= 15 && tmp < 30) lcd_str(" Dobra "); else if (tmp >= 30 && tmp < 55) lcd_str(" Umiarkowana "); else if (tmp >= 55 && tmp < 110) lcd_str(" Zla "); else lcd_str(" Bardzo zla! "); } /*! * pomiar - funkcja dokonująca pomiaru na wybranym kanale ADC_CHANNEL */ inline uint16_t pomiar() { ADMUX = (ADMUX & 0b11111000) | ADC_CHANNEL; ///< maskowanie 3 młodszych bitów aby załączyc pomiar na wybranym kanale ADCSRA |= (1<<ADSC); ///< rozpocznij pomiar while(ADCSRA & (1<<ADSC)); ///< gdy zakończy się pomiar bit ADSC w rejestrze ADCSRA jest zerowany ///< jeśli jest 1 kontynuuj pomiar return ADCW; ///< zwróc zawartośc rejestru ADCW (połączone rejestry ADCL oraz ADCH) }
jonssa/AirPolutionSensor_ATMega328_GP2Y1010AU0F
src/1Wire/crc8.h
/************************************************************************/ /* */ /* Access Dallas 1-Wire Device with ATMEL AVRs */ /* */ /* Author: <NAME> */ /* <EMAIL> */ /* */ /* modified by <NAME> <<EMAIL>> 9/2004 */ /************************************************************************/ /* * crc8.h * */ #ifndef CRC8_H_ #define CRC8_H_ #include <inttypes.h> uint8_t crc8 (uint8_t* data_in, uint16_t number_of_bytes_to_read); #endif
jonssa/AirPolutionSensor_ATMega328_GP2Y1010AU0F
src/1Wire/crc8.c
<reponame>jonssa/AirPolutionSensor_ATMega328_GP2Y1010AU0F /************************************************************************/ /* */ /* Access Dallas 1-Wire Device with ATMEL AVRs */ /* */ /* Author: <NAME> */ /* <EMAIL> */ /* */ /* modified by <NAME> <<EMAIL>> 9/2004 */ /************************************************************************/ /* * crc8.c * */ /* please read copyright-notice at EOF */ #include <inttypes.h> #define CRC8INIT 0x00 #define CRC8POLY 0x18 //0X18 = X^8+X^5+X^4+X^0 uint8_t crc8 ( uint8_t *data_in, uint16_t number_of_bytes_to_read ) { uint8_t crc; uint16_t loop_count; uint8_t bit_counter; uint8_t data; uint8_t feedback_bit; crc = CRC8INIT; for (loop_count = 0; loop_count != number_of_bytes_to_read; loop_count++) { data = data_in[loop_count]; bit_counter = 8; do { feedback_bit = (crc ^ data) & 0x01; if ( feedback_bit == 0x01 ) { crc = crc ^ CRC8POLY; } crc = (crc >> 1) & 0x7F; if ( feedback_bit == 0x01 ) { crc = crc | 0x80; } data = data >> 1; bit_counter--; } while (bit_counter > 0); } return crc; }
jonssa/AirPolutionSensor_ATMega328_GP2Y1010AU0F
src/LCD/lcd44780.c
//----------------------------------------------------------------------------------------------------------- // *** Obsługa wyświetlaczy alfanumerycznych zgodnych z HD44780 *** // // - Sterowanie: tryb 4-bitowy // - Dowolne przypisanie każdego sygnału sterującego do dowolnego pinu mikrokontroleralcd_wir // - Praca z pinem RW podłączonym do GND lub do mikrokontrolera (sprawdzanie BusyFLAG - szybkie operacje LCD) // // Pliki : lcd44780.c , lcd44780.h // Mikrokontrolery : Atmel AVR // Kompilator : avr-gcc // Źródło : http://www.atnel.pl // Data : marzec 2010 // Autor : <NAME> //---------------------------------------------------------------------------------------------------------- #include <avr/io.h> #include <avr/interrupt.h> #include <avr/eeprom.h> #include <avr/pgmspace.h> #include <stdlib.h> #include <util/delay.h> #include "lcd44780.h" // makrodefinicje operacji na sygnałach sterujących RS,RW oraz E #define SET_RS PORT(LCD_RSPORT) |= (1<<LCD_RS) // stan wysoki na linii RS #define CLR_RS PORT(LCD_RSPORT) &= ~(1<<LCD_RS) // stan niski na linii RS #define SET_RW PORT(LCD_RWPORT) |= (1<<LCD_RW) // stan wysoki na RW - odczyt z LCD #define CLR_RW PORT(LCD_RWPORT) &= ~(1<<LCD_RW) // stan niski na RW - zapis do LCD #define SET_E PORT(LCD_EPORT) |= (1<<LCD_E) // stan wysoki na linii E #define CLR_E PORT(LCD_EPORT) &= ~(1<<LCD_E) // stan niski na linii E uint8_t check_BF(void); // deklaracja funkcji wewnętrznej /*! * tablice znaków do wyświetlenia na wyświetlaczu LCD */ uint8_t znak_happy[] = {0,27,27,0,0,17,14,0}; ///< wzór miny uśmiechniętej uint8_t znak_neutral[] = {0,27,27,0,0,0,31,0}; ///< wzór miny neutralnej uint8_t znak_sad[] = {0,27,27,0,0,0,14,17}; ///< wzór miny smutnej uint8_t znak_3[] = {24,4,24,4,24,0,0,0}; ///< wzór znaku 3 w indeksie górnym uint8_t znak_termo[] = {4,10,10,10,17,31,31,14}; ///< wzór znaku termometru //********************* FUNKCJE WEWNĘTRZNE ********************* //---------------------------------------------------------------------------------------- // // Ustawienie wszystkich 4 linii danych jako WYjścia // //---------------------------------------------------------------------------------------- static inline void data_dir_out(void) { DDR(LCD_D7PORT) |= (1<<LCD_D7); DDR(LCD_D6PORT) |= (1<<LCD_D6); DDR(LCD_D5PORT) |= (1<<LCD_D5); DDR(LCD_D4PORT) |= (1<<LCD_D4); } //---------------------------------------------------------------------------------------- // // Ustawienie wszystkich 4 linii danych jako WEjścia // //---------------------------------------------------------------------------------------- static inline void data_dir_in(void) { DDR(LCD_D7PORT) &= ~(1<<LCD_D7); DDR(LCD_D6PORT) &= ~(1<<LCD_D6); DDR(LCD_D5PORT) &= ~(1<<LCD_D5); DDR(LCD_D4PORT) &= ~(1<<LCD_D4); } //---------------------------------------------------------------------------------------- // // Wysłanie połówki bajtu do LCD (D4..D7) // //---------------------------------------------------------------------------------------- static inline void lcd_sendHalf(uint8_t data) { if (data&(1<<0)) PORT(LCD_D4PORT) |= (1<<LCD_D4); else PORT(LCD_D4PORT) &= ~(1<<LCD_D4); if (data&(1<<1)) PORT(LCD_D5PORT) |= (1<<LCD_D5); else PORT(LCD_D5PORT) &= ~(1<<LCD_D5); if (data&(1<<2)) PORT(LCD_D6PORT) |= (1<<LCD_D6); else PORT(LCD_D6PORT) &= ~(1<<LCD_D6); if (data&(1<<3)) PORT(LCD_D7PORT) |= (1<<LCD_D7); else PORT(LCD_D7PORT) &= ~(1<<LCD_D7); } #if USE_RW == 1 //---------------------------------------------------------------------------------------- // // Odczyt połówki bajtu z LCD (D4..D7) // //---------------------------------------------------------------------------------------- static inline uint8_t lcd_readHalf(void) { uint8_t result=0; if(PIN(LCD_D4PORT)&(1<<LCD_D4)) result |= (1<<0); if(PIN(LCD_D5PORT)&(1<<LCD_D5)) result |= (1<<1); if(PIN(LCD_D6PORT)&(1<<LCD_D6)) result |= (1<<2); if(PIN(LCD_D7PORT)&(1<<LCD_D7)) result |= (1<<3); return result; } #endif //---------------------------------------------------------------------------------------- // // Zapis bajtu do wyświetlacza LCD // //---------------------------------------------------------------------------------------- void _lcd_write_byte(unsigned char _data) { // Ustawienie pinów portu LCD D4..D7 jako wyjścia data_dir_out(); #if USE_RW == 1 CLR_RW; #endif SET_E; lcd_sendHalf(_data >> 4); // wysłanie starszej części bajtu danych D7..D4 CLR_E; SET_E; lcd_sendHalf(_data); // wysłanie młodszej części bajtu danych D3..D0 CLR_E; #if USE_RW == 1 while( (check_BF() & (1<<7)) ); #else _delay_us(120); #endif } #if USE_RW == 1 //---------------------------------------------------------------------------------------- // // Odczyt bajtu z wyświetlacza LCD // //---------------------------------------------------------------------------------------- uint8_t _lcd_read_byte(void) { uint8_t result=0; data_dir_in(); SET_RW; SET_E; result = (lcd_readHalf() << 4); // odczyt starszej części bajtu z LCD D7..D4 CLR_E; SET_E; result |= lcd_readHalf(); // odczyt młodszej części bajtu z LCD D3..D0 CLR_E; return result; } #endif #if USE_RW == 1 //---------------------------------------------------------------------------------------- // // Sprawdzenie stanu Busy Flag (Zajętości wyświetlacza) // //---------------------------------------------------------------------------------------- uint8_t check_BF(void) { CLR_RS; return _lcd_read_byte(); } #endif //---------------------------------------------------------------------------------------- // // Zapis komendy do wyświetlacza LCD // //---------------------------------------------------------------------------------------- void lcd_write_cmd(uint8_t cmd) { CLR_RS; _lcd_write_byte(cmd); } //---------------------------------------------------------------------------------------- // // Zapis danych do wyświetlacza LCD // //---------------------------------------------------------------------------------------- void lcd_write_data(uint8_t data) { SET_RS; _lcd_write_byte(data); } //************************** FUNKCJE PRZEZNACZONE TAKŻE DLA INNYCH MODUŁÓW ****************** #if USE_LCD_CHAR == 1 //---------------------------------------------------------------------------------------- // // Wysłanie pojedynczego znaku do wyświetlacza LCD w postaci argumentu // // 8 własnych znaków zdefiniowanych w CGRAM // wysyłamy za pomocą kodów 0x80 do 0x87 zamiast 0x00 do 0x07 // //---------------------------------------------------------------------------------------- void lcd_char(char c) { lcd_write_data( ( c>=0x80 && c<=0x87 ) ? (c & 0x07) : c); } #endif //---------------------------------------------------------------------------------------- // // Wysłanie stringa do wyświetlacza LCD z pamięci RAM // // //---------------------------------------------------------------------------------------- void lcd_str(char * str) { register char znak; while ( (znak=*(str++)) ) lcd_char( znak ); } #if USE_LCD_STR_P == 1 //---------------------------------------------------------------------------------------- // // Wysłanie stringa do wyświetlacza LCD z pamięci FLASH // //---------------------------------------------------------------------------------------- void lcd_str_P(const char * str) { register char znak; while ( (znak=pgm_read_byte(str++)) ) lcd_char( znak ); } #endif #if USE_LCD_STR_E == 1 //---------------------------------------------------------------------------------------- // // Wysłanie stringa do wyświetlacza LCD z pamięci EEPROM // // 8 własnych znaków zdefiniowanych w CGRAM // wysyłamy za pomocą kodów 0x80 do 0x87 zamiast 0x00 do 0x07 // //---------------------------------------------------------------------------------------- void lcd_str_E(char * str) { register char znak; while(1) { znak=eeprom_read_byte( (uint8_t *)(str++) ); if(!znak || znak==0xFF) break; else lcd_char( znak ); } } #endif #if USE_LCD_INT == 1 //---------------------------------------------------------------------------------------- // // Wyświetla liczbę dziesiętną na wyświetlaczu LCD // //---------------------------------------------------------------------------------------- void lcd_int(int val) { char bufor[17]; lcd_str( itoa(val, bufor, 10) ); } #endif //---------------------------------------------------------------------------------------- // // Wyświetla liczbę typu double na wyświetlaczu LCD // //---------------------------------------------------------------------------------------- void lcd_double(int val) { char bufor[17]; lcd_str( ltoa(val, bufor, 10) ); } #if USE_LCD_HEX == 1 //---------------------------------------------------------------------------------------- // // Wyświetla liczbę szestnastkową HEX na wyświetlaczu LCD // //---------------------------------------------------------------------------------------- void lcd_hex(uint32_t val) { char bufor[17]; lcd_str( ltoa(val, bufor, 16) ); } #endif #if USE_LCD_DEFCHAR == 1 //---------------------------------------------------------------------------------------- // // Definicja własnego znaku na LCD z pamięci RAM // // argumenty: // nr: - kod znaku w pamięci CGRAM od 0x80 do 0x87 // *def_znak: - wskaźnik do tablicy 7 bajtów definiujących znak // //---------------------------------------------------------------------------------------- void lcd_defchar(uint8_t nr, uint8_t *def_znak) { register uint8_t i,c; lcd_write_cmd( 64+((nr&0x07)*8) ); for(i=0;i<8;i++) { c = *(def_znak++); lcd_write_data(c); } } #endif #if USE_LCD_DEFCHAR_P == 1 //---------------------------------------------------------------------------------------- // // Definicja własnego znaku na LCD z pamięci FLASH // // argumenty: // nr: - kod znaku w pamięci CGRAM od 0x80 do 0x87 // *def_znak: - wskaźnik do tablicy 7 bajtów definiujących znak // //---------------------------------------------------------------------------------------- void lcd_defchar_P(uint8_t nr, const uint8_t *def_znak) { register uint8_t i,c; lcd_write_cmd( 64+((nr&0x07)*8) ); for(i=0;i<8;i++) { c = pgm_read_byte(def_znak++); lcd_write_data(c); } } #endif #if USE_LCD_DEFCHAR_E == 1 //---------------------------------------------------------------------------------------- // // Definicja własnego znaku na LCD z pamięci EEPROM // // argumenty: // nr: - kod znaku w pamięci CGRAM od 0x80 do 0x87 // *def_znak: - wskaźnik do tablicy 7 bajtów definiujących znak // //---------------------------------------------------------------------------------------- void lcd_defchar_E(uint8_t nr, uint8_t *def_znak) { register uint8_t i,c; lcd_write_cmd( 64+((nr&0x07)*8) ); for(i=0;i<8;i++) { c = eeprom_read_byte(def_znak++); lcd_write_data(c); } } #endif #if USE_LCD_LOCATE == 1 //---------------------------------------------------------------------------------------- // // Ustawienie kursora w pozycji Y-wiersz, X-kolumna // // Y = od 0 do 3 // X = od 0 do n // // funkcja dostosowuje automatycznie adresy DDRAM // w zależności od rodzaju wyświetlacza (ile posiada wierszy) // //---------------------------------------------------------------------------------------- void lcd_locate(uint8_t y, uint8_t x) { switch(y) { case 0: y = LCD_LINE1; break; #if (LCD_ROWS>1) case 1: y = LCD_LINE2; break; // adres 1 znaku 2 wiersza #endif #if (LCD_ROWS>2) case 2: y = LCD_LINE3; break; // adres 1 znaku 3 wiersza #endif #if (LCD_ROWS>3) case 3: y = LCD_LINE4; break; // adres 1 znaku 4 wiersza #endif } lcd_write_cmd( (0x80 + y + x) ); } #endif //---------------------------------------------------------------------------------------- // // Kasowanie ekranu wyświetlacza // //---------------------------------------------------------------------------------------- void lcd_cls(void) { lcd_write_cmd( LCDC_CLS ); #if USE_RW == 0 _delay_ms(4.9); #endif } #if USE_LCD_CURSOR_HOME == 1 //---------------------------------------------------------------------------------------- // // Powrót kursora na początek // //---------------------------------------------------------------------------------------- void lcd_home(void) { lcd_write_cmd( LCDC_CLS|LCDC_HOME ); #if USE_RW == 0 _delay_ms(4.9); #endif } #endif #if USE_LCD_CURSOR_ON == 1 //---------------------------------------------------------------------------------------- // // Włączenie kursora na LCD // //---------------------------------------------------------------------------------------- void lcd_cursor_on(void) { lcd_write_cmd( LCDC_ONOFF|LCDC_DISPLAYON|LCDC_CURSORON); } //---------------------------------------------------------------------------------------- // // Wyłączenie kursora na LCD // //---------------------------------------------------------------------------------------- void lcd_cursor_off(void) { lcd_write_cmd( LCDC_ONOFF|LCDC_DISPLAYON); } #endif #if USE_LCD_CURSOR_BLINK == 1 //---------------------------------------------------------------------------------------- // // WŁącza miganie kursora na LCD // //---------------------------------------------------------------------------------------- void lcd_blink_on(void) { lcd_write_cmd( LCDC_ONOFF|LCDC_DISPLAYON|LCDC_CURSORON|LCDC_BLINKON); } //---------------------------------------------------------------------------------------- // // WYłącza miganie kursora na LCD // //---------------------------------------------------------------------------------------- void lcd_blink_off(void) { lcd_write_cmd( LCDC_ONOFF|LCDC_DISPLAYON); } #endif //---------------------------------------------------------------------------------------- // // ******* INICJALIZACJA WYŚWIETLACZA LCD ******** // //---------------------------------------------------------------------------------------- void lcd_init(void) { // inicjowanie pinów portów ustalonych do podłączenia z wyświetlaczem LCD // ustawienie wszystkich jako wyjścia data_dir_out(); DDR(LCD_RSPORT) |= (1<<LCD_RS); DDR(LCD_EPORT) |= (1<<LCD_E); #if USE_RW == 1 DDR(LCD_RWPORT) |= (1<<LCD_RW); #endif PORT(LCD_RSPORT) |= (1<<LCD_RS); PORT(LCD_EPORT) |= (1<<LCD_E); #if USE_RW == 1 PORT(LCD_RWPORT) |= (1<<LCD_RW); #endif _delay_ms(15); PORT(LCD_EPORT) &= ~(1<<LCD_E); PORT(LCD_RSPORT) &= ~(1<<LCD_RS); #if USE_RW == 1 PORT(LCD_RWPORT) &= ~(1<<LCD_RW); #endif // jeszcze nie można używać Busy Flag SET_E; lcd_sendHalf(0x03); // tryb 8-bitowy CLR_E; _delay_ms(4.1); SET_E; lcd_sendHalf(0x03); // tryb 8-bitowy CLR_E; _delay_us(100); SET_E; lcd_sendHalf(0x03); // tryb 8-bitowy CLR_E; _delay_us(100); SET_E; lcd_sendHalf(0x02);// tryb 4-bitowy CLR_E; _delay_us(100); // już można używać Busy Flag // tryb 4-bitowy, 2 wiersze, znak 5x7 lcd_write_cmd( LCDC_FUNC|LCDC_FUNC4B|LCDC_FUNC2L|LCDC_FUNC5x7 ); // wyłączenie kursora lcd_write_cmd( LCDC_ONOFF|LCDC_CURSOROFF ); // włączenie wyświetlacza lcd_write_cmd( LCDC_ONOFF|LCDC_DISPLAYON ); // przesuwanie kursora w prawo bez przesuwania zawartości ekranu lcd_write_cmd( LCDC_ENTRY|LCDC_ENTRYR ); // kasowanie ekranu lcd_cls(); }
baita00/Lissajous
TestLissajous/resource.h
<reponame>baita00/Lissajous //{{NO_DEPENDENCIES}} // Microsoft Developer Studio generated include file. // Used by TestLissajous.rc // #define IDD_ABOUTBOX 100 #define IDR_MAINFRAME 128 #define IDR_TESTLITYPE 129 #define IDD_CMDFORM 130 #define IDC_HAND 130 #define IDB_DEFINITION 131 #define IDB_PHI 133 #define IDB_PI 134 #define IDR_COMMANDTYPE 142 #define IDC_PICTURE 1000 #define IDC_EDIT_A 1001 #define IDC_EDIT_B 1002 #define IDC_EDIT_P 1003 #define IDC_EDIT_Q 1004 #define IDC_EDIT_PHI 1005 #define IDC_BUTTON_DRAW 1006 #define IDC_BUTTON_CLEAR 1007 #define IDC_BUTTON_CURVECOLOR 1008 #define IDC_EDIT_LINESIZE 1009 #define IDC_COMBO_LINESTYLE 1011 #define IDC_EDIT_NUM 1012 #define IDC_BUTTON_ANIMATE 1013 #define IDC_EDIT_TIMERINTERVAL 1014 #define IDC_WEB 1015 #define IDC_GITHUB 1016 #define IDC_CCHART 1017 #define IDC_VISIT 1018 // Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_3D_CONTROLS 1 #define _APS_NEXT_RESOURCE_VALUE 135 #define _APS_NEXT_COMMAND_VALUE 32771 #define _APS_NEXT_CONTROL_VALUE 1019 #define _APS_NEXT_SYMED_VALUE 101 #endif #endif
baita00/Lissajous
TestLissajous/Label.h
<gh_stars>0 #if !defined(AFX_LABEL_H__A4EABEC5_2E8C_11D1_B79F_00805F9ECE10__INCLUDED_) #define AFX_LABEL_H__A4EABEC5_2E8C_11D1_B79F_00805F9ECE10__INCLUDED_ #if _MSC_VER >= 1000 #pragma once #endif // _MSC_VER >= 1000 // Label.h : header file // ///////////////////////////////////////////////////////////////////////////// // CLabel window enum FlashType {None, Text, Background }; class CLabel : public CStatic { // Construction public: CLabel(); CLabel& SetBkColor(COLORREF crBkgnd); CLabel& SetTextColor(COLORREF crText); CLabel& SetText(const CString& strText); CLabel& SetFontBold(BOOL bBold); CLabel& SetFontName(const CString& strFont); CLabel& SetFontUnderline(BOOL bSet); CLabel& SetFontItalic(BOOL bSet); CLabel& SetFontSize(int nSize); CLabel& SetSunken(BOOL bSet); CLabel& SetBorder(BOOL bSet); CLabel& FlashText(BOOL bActivate); CLabel& FlashBackground(BOOL bActivate); CLabel& SetLink(BOOL bLink); CLabel& SetLinkCursor(HCURSOR hCursor); // Attributes public: protected: void ReconstructFont(); COLORREF m_crText; HBRUSH m_hBrush; HBRUSH m_hwndBrush; LOGFONT m_lf; CFont m_font; CString m_strText; BOOL m_bState; BOOL m_bTimer; BOOL m_bLink; FlashType m_Type; HCURSOR m_hCursor; // Operations public: // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CLabel) //}}AFX_VIRTUAL // Implementation public: virtual ~CLabel(); // Generated message map functions protected: //{{AFX_MSG(CLabel) afx_msg HBRUSH CtlColor(CDC* pDC, UINT nCtlColor); afx_msg void OnTimer(UINT nIDEvent); afx_msg void OnLButtonDown(UINT nFlags, CPoint point); afx_msg BOOL OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Developer Studio will insert additional declarations immediately before the previous line. #endif // !defined(AFX_LABEL_H__A4EABEC5_2E8C_11D1_B79F_00805F9ECE10__INCLUDED_)
baita00/Lissajous
TestLissajous/TestLissajousView.h
<filename>TestLissajous/TestLissajousView.h // TestLissajousView.h : interface of the CTestLissajousView class // ///////////////////////////////////////////////////////////////////////////// #if !defined(AFX_TESTLISSAJOUSVIEW_H__9D27DFAE_F2FB_4266_83E9_AFD3E89804B1__INCLUDED_) #define AFX_TESTLISSAJOUSVIEW_H__9D27DFAE_F2FB_4266_83E9_AFD3E89804B1__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "CChart/Chart.h" # if defined(_UNICODE) || defined(UNICODE) # pragma comment(lib,"CChart\\CChartu.lib") # else # pragma comment(lib,"CChart\\CChart.lib") # endif using namespace NsCChart; class CTestLissajousDoc; const double myPi = 3.14159265358979324; class CTestLissajousView : public CView { protected: // create from serialization only CTestLissajousView(); DECLARE_DYNCREATE(CTestLissajousView) // Attributes public: CTestLissajousDoc* GetDocument(); double a, b, p, q, phi; size_t num; COLORREF cr; int width, style; UINT timerID; bool running; int cur; int timerInterval; CChartWnd m_chartWnd; // Operations public: void CreateLissajous(); void CreateEmpty(); void CreateAnimation(); void SwitchTimer(); // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CTestLissajousView) public: virtual void OnDraw(CDC* pDC); // overridden to draw this view virtual BOOL PreCreateWindow(CREATESTRUCT& cs); protected: virtual BOOL OnPreparePrinting(CPrintInfo* pInfo); virtual void OnBeginPrinting(CDC* pDC, CPrintInfo* pInfo); virtual void OnEndPrinting(CDC* pDC, CPrintInfo* pInfo); //}}AFX_VIRTUAL // Implementation public: virtual ~CTestLissajousView(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif protected: // Generated message map functions protected: //{{AFX_MSG(CTestLissajousView) afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); afx_msg void OnTimer(UINT nIDEvent); afx_msg void OnLButtonDown(UINT nFlags, CPoint point); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; #ifndef _DEBUG // debug version in TestLissajousView.cpp inline CTestLissajousDoc* CTestLissajousView::GetDocument() { return (CTestLissajousDoc*)m_pDocument; } #endif ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_TESTLISSAJOUSVIEW_H__9D27DFAE_F2FB_4266_83E9_AFD3E89804B1__INCLUDED_)
baita00/Lissajous
TestLissajous/CmdFormView.h
#if !defined(AFX_CMDFORMVIEW_H__6FC95772_CF45_468E_AEBA_CA43D836E359__INCLUDED_) #define AFX_CMDFORMVIEW_H__6FC95772_CF45_468E_AEBA_CA43D836E359__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 // CmdFormView.h : header file // ///////////////////////////////////////////////////////////////////////////// // CCmdFormView form view #ifndef __AFXEXT_H__ #include <afxext.h> #endif #include <vector> using namespace std; #include "Label.h" class CTestLissajousDoc; class CCmdFormView : public CFormView { protected: CCmdFormView(); // protected constructor used by dynamic creation DECLARE_DYNCREATE(CCmdFormView) // Form Data public: //{{AFX_DATA(CCmdFormView) enum { IDD = IDD_CMDFORM }; CLabel m_ctrlVisit; CLabel m_ctrlCChart; CComboBox m_ctrlComboLinestyle; double m_fA; double m_fB; double m_fP; double m_fQ; double m_fPhi; int m_nWidth; int m_nNum; int m_nInterval; //}}AFX_DATA // Attributes public: CTestLissajousDoc* GetDocument(); // Operations public: bool PutParams(); // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CCmdFormView) public: virtual void OnInitialUpdate(); protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: virtual ~CCmdFormView(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif // Generated message map functions //{{AFX_MSG(CCmdFormView) afx_msg void OnButtonDraw(); afx_msg void OnButtonClear(); afx_msg void OnButtonCurvecolor(); afx_msg void OnButtonAnimate(); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; #ifndef _DEBUG // debug version in BetatronView.cpp inline CTestLissajousDoc* CCmdFormView::GetDocument() { return (CTestLissajousDoc*)m_pDocument; } #endif ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_CMDFORMVIEW_H__6FC95772_CF45_468E_AEBA_CA43D836E359__INCLUDED_)
baita00/Lissajous
TestLissajous/TestLissajousDoc.h
// TestLissajousDoc.h : interface of the CTestLissajousDoc class // ///////////////////////////////////////////////////////////////////////////// #if !defined(AFX_TESTLISSAJOUSDOC_H__C6FEC400_6A47_47DF_86C7_A54861A1ED9F__INCLUDED_) #define AFX_TESTLISSAJOUSDOC_H__C6FEC400_6A47_47DF_86C7_A54861A1ED9F__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 class CTestLissajousView; class CCmdFormView; class CTestLissajousDoc : public CDocument { protected: // create from serialization only CTestLissajousDoc(); DECLARE_DYNCREATE(CTestLissajousDoc) // Attributes public: // Operations public: CTestLissajousView *GetTestLissajousView(); CCmdFormView *GetCmdFormView(); // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CTestLissajousDoc) public: virtual BOOL OnNewDocument(); virtual void Serialize(CArchive& ar); //}}AFX_VIRTUAL // Implementation public: virtual ~CTestLissajousDoc(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif protected: // Generated message map functions protected: //{{AFX_MSG(CTestLissajousDoc) // NOTE - the ClassWizard will add and remove member functions here. // DO NOT EDIT what you see in these blocks of generated code ! //}}AFX_MSG DECLARE_MESSAGE_MAP() }; ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_TESTLISSAJOUSDOC_H__C6FEC400_6A47_47DF_86C7_A54861A1ED9F__INCLUDED_)
cran/edesign
src/entrp.c
<filename>src/entrp.c #include "heap.h" #include "entrp.h" #include <stdlib.h> /* #define VERBOSE 1 */ void entrp(double *A, int *lda, int *na, int *nf, int *ne, int *ns, int *S, double *opt, int *S_Work, int *F, int *E, int *ind, int *ind1, double *As, int *ldas, double *Bs, int *ldbs, double *Cs, int *ldcs, double *Inv, int *ldinv, double *W, double* WORK, int *LWORK, int *IWORK, double *tol, int *maxcount, int *iter, int *verbose ) { double diff; double LB,UB,det,RCOND,UB_Work; heap_type *subproblems; heap_element_type *act_subproblem, *act_subproblem_Work; int i,j,k,ni,cardf,carde,ierr,lerr; *iter=0;lerr=0; LB=*opt; #ifdef VERBOSE if(*verbose!=0) { printf("Init: \n"); printf("LB:%e\n",LB); } #endif for(i=0;i<=(*nf)-1;i++) ind[i]=i+1; for(i=0;i<=(*ne)-1;i++) { E[i]=1; F[i]=0; } cardf=*nf; carde=*ne; if (cardf!=0) { UB_Work=F77_CALL(upbnd)(A, lda, na, F, E, ne, ns, As, ldas, Bs, ldbs, Cs, ldcs, Inv, ldinv, ind1, &ierr, W, WORK, LWORK, IWORK); UB=UB_Work; } if (cardf==0) UB=2*LB; #ifdef VERBOSE if(*verbose!=0) { printf("\nbound\n"); printf("UB:%e\n",UB); } #endif if(! (subproblems=heap_init())){ /* error("memory exhausted"); exit(1); */ lerr=1; } if(! (act_subproblem=heap_element_init(F,E,*ne,UB,0))){ /* error("memory exhausted"); exit(1); */ lerr=1; } /* heap_element_print(act_subproblem); */ heap_insert(subproblems, act_subproblem); /* heap_traverse(subproblems); */ diff=UB-LB; #ifdef VERBOSE if(*verbose!=0) { printf("\nbegin of the loop!! tolerance: %e\n",*tol); } #endif while(diff>*tol && subproblems->count>0) { (*iter)++; #ifdef VERBOSE if(*verbose!=0) { printf("iter: %i, heap: %i\n",*iter,subproblems->count); } #endif /* heap_traverse(subproblems); */ act_subproblem=heap_drop(subproblems); if(act_subproblem!=NULL) { /* printf("dropped element:\n"); */ /* heap_element_print(act_subproblem); */ carde=0; cardf=*nf; for(j=0;j<=(*ne)-1;j++) { carde=carde+act_subproblem->E[j]*act_subproblem->E[j]; cardf=cardf+act_subproblem->F[j]*act_subproblem->F[j]; } /* if(*verbose!=0)*/ /* {*/ /* F77_CALL(ivecpr)(act_subproblem->E,ne); */ /* F77_CALL(ivecpr)(act_subproblem->F,ne); */ /* }*/ for(j=0;j<=(*ne)-1;j++) S_Work[j]=0; i=act_subproblem->ibranch; /***** loop *****/ /* while(i<(*ne)-1 && diff>*tol) { */ do i++; while(act_subproblem->E[i]==0 && i<(*ne)-1); if(act_subproblem->E[i]>0) { if(! (act_subproblem_Work=heap_element_init(NULL,NULL,*ne,0,0))){ /* error("memory exhausted"); exit(1);*/ lerr=1; } heap_element_copy(act_subproblem_Work,act_subproblem); act_subproblem_Work->E[i]=0; act_subproblem_Work->ibranch=i; if(cardf+carde-1>(*ns)+(*nf)) { UB_Work=F77_CALL(upbnd)(A, lda, na, act_subproblem_Work->F, act_subproblem_Work->E, ne, ns, As, ldas, Bs, ldbs, Cs, ldcs, Inv, ldinv, ind1, &ierr, W, WORK, LWORK, IWORK); act_subproblem_Work->b=UB_Work; /* fathoming by lower bounds */ if(UB_Work>=LB) heap_insert(subproblems, act_subproblem_Work); /* printf("LB: %e UB: %e\n",LB, UB_Work); */ } if(cardf+carde-1==(*ns)+(*nf)) { for(j=0;j<=(*ne)-1;j++) S_Work[j]=(act_subproblem_Work->F[j]==1 || act_subproblem_Work->E[j]!=0 ? j+(*nf)+1 : 0); ni=*nf; for(j=0;j<=(*ne)-1;j++) { if(S_Work[j]!=0) { ind[ni]=S_Work[j]; ni=ni+1; } } /* calculation of the determinant */ F77_CALL(psubm)(A,lda,na,As,ldas,ind,&ni); F77_CALL(chol1)(As,ldas,&ni,Bs,ldbs,&ierr); det=F77_CALL(chdet)(Bs,ldbs,&ni); if (det>LB) { LB=det; for(j=0;j<=(*ne)-1;j++) S[j]=S_Work[j]; } } if(! (act_subproblem_Work=heap_element_init(NULL,NULL,*ne,0,0))){ /* error("memory exhausted"); exit(1);*/ lerr=1; } heap_element_copy(act_subproblem_Work,act_subproblem); act_subproblem_Work->E[i]=0; act_subproblem_Work->F[i]=1; act_subproblem_Work->ibranch=i; if(cardf+1<(*ns)+(*nf)) { UB_Work=F77_CALL(upbnd)(A, lda, na, act_subproblem_Work->F, act_subproblem_Work->E, ne, ns, As, ldas, Bs, ldbs, Cs, ldcs, Inv, ldinv, ind1, &ierr, W, WORK, LWORK, IWORK); act_subproblem_Work->b=UB_Work; /* fathoming by lower bounds */ /* printf("LB: %e UB: %e\n",LB, UB_Work); */ if(UB_Work>=LB) heap_insert(subproblems, act_subproblem_Work); } if(cardf+1==(*ns)+(*nf)) { for(j=0;j<=(*ne)-1;j++) S_Work[j]=(act_subproblem_Work->F[j]==1 ? j+(*nf)+1 : 0); ni=*nf; for(j=0;j<=(*ne)-1;j++) { if(S_Work[j]!=0) { ind[ni]=S_Work[j]; ni=ni+1; } } /* calculation of the determinant */ F77_CALL(psubm)(A,lda,na,As,ldas,ind,&ni); F77_CALL(chol1)(As,ldas,&ni,Bs,ldbs,&ierr); det=F77_CALL(chdet)(Bs,ldbs,&ni); if (det>LB) { LB=det; for(j=0;j<=(*ne)-1;j++) S[j]=S_Work[j]; } } UB=subproblems->top->down->b; diff=UB-LB; #ifdef VERBOSE if (subproblems->count!=0 && *verbose!=0) printf("diff:%e LB: %e UB: %e\n",diff, LB, UB); #endif } /* }*/ /***** End While *****/ } } #ifdef VERBOSE if(*verbose!=0) { printf("\nEnd\n"); /* printf("diff:%e LB: %e UB: %e\n",diff, LB, UB); */ } #endif /* LB is numerically better than UB !! */ *opt=LB; *maxcount=subproblems->maxcount; }
cran/edesign
src/init.c
/* * This file contains declarations to interface to the edisgn C and Fortran * functions. * */ #include <R.h> #include <Rinternals.h> #include "edesign.h" #include <R_ext/Rdynload.h> /* Fortran interface descriptions: */ static R_NativePrimitiveArgType grd_t[18] = { REALSXP, /* A */ INTSXP, /* LDA */ INTSXP, /* NA */ INTSXP, /* NF */ INTSXP, /* NE */ INTSXP, /* NS */ INTSXP, /* S */ REALSXP, /* OPT */ INTSXP, /* IND */ REALSXP, /* AS */ INTSXP, /* LDAS */ REALSXP, /* BS */ INTSXP, /* LDBS */ REALSXP, /* INV */ INTSXP, /* LDINV */ REALSXP, /* V */ REALSXP, /* W */ INTSXP /* IERR */ }; static R_NativePrimitiveArgType grddl_t[14] = { REALSXP, /* A */ INTSXP, /* LDA */ INTSXP, /* NA */ INTSXP, /* NF */ INTSXP, /* NE */ INTSXP, /* NS */ INTSXP, /* S */ REALSXP, /* OPT */ INTSXP, /* IND */ REALSXP, /* AS */ INTSXP, /* LDAS */ REALSXP, /* BS */ INTSXP, /* LDBS */ INTSXP /* IERR */ }; static R_NativePrimitiveArgType change_t[18] = { REALSXP, /* A */ INTSXP, /* LDA */ INTSXP, /* NA */ INTSXP, /* NF */ INTSXP, /* NE */ INTSXP, /* NS */ INTSXP, /* S */ REALSXP, /* OPT */ INTSXP, /* IND */ REALSXP, /* AS */ INTSXP, /* LDAS */ REALSXP, /* BS */ INTSXP, /* LDBS */ REALSXP, /* INV */ INTSXP, /* LDINV */ REALSXP, /* V */ REALSXP, /* W */ INTSXP /* IERR */ }; static R_NativePrimitiveArgType subde1_t[11] = { REALSXP, /* DET */ REALSXP, /* A */ INTSXP, /* LDA */ INTSXP, /* NA */ REALSXP, /* AS */ INTSXP, /* LDAS */ INTSXP, /* IND */ INTSXP, /* NI */ REALSXP, /* BS */ INTSXP, /* LDBS */ INTSXP /* IERR */ }; static R_FortranMethodDef fortranMethods[] = { {"grd", (DL_FUNC) &F77_SUB(grd), 18, grd_t}, /* greedy */ {"grddl", (DL_FUNC) &F77_SUB(grddl), 14, grddl_t}, /* dual.greedy */ {"change", (DL_FUNC) &F77_SUB(change), 18, change_t}, /* interchange */ {"subde1", (DL_FUNC) &F77_SUB(subde1), 11, subde1_t}, /* maxentropy */ {NULL, NULL, 0} }; /* C interface descriptions: */ static R_NativePrimitiveArgType entrp_t[29] = { REALSXP, /* A */ INTSXP, /* lda */ INTSXP, /* na */ INTSXP, /* nf */ INTSXP, /* ne */ INTSXP, /* ns */ INTSXP, /* S */ REALSXP, /* opt */ INTSXP, /* S_Work */ INTSXP, /* F */ INTSXP, /* E */ INTSXP, /* ind */ INTSXP, /* ind1 */ REALSXP, /* As */ INTSXP, /* ldas */ REALSXP, /* Bs */ INTSXP, /* ldbs */ REALSXP, /* Cs */ INTSXP, /* ldcs */ REALSXP, /* Inv */ INTSXP, /* ldinv */ REALSXP, /* W */ REALSXP, /* WORK */ INTSXP, /* LWORK */ INTSXP, /* IWORK */ REALSXP, /* tol */ INTSXP, /* maxcount */ INTSXP, /* iter */ INTSXP /* verbose */ }; static R_CMethodDef cMethods[] = { {"entrp", (DL_FUNC) entrp, 29, entrp_t}, /* maxentropy */ {NULL, NULL, 0} }; void R_init_edesign(DllInfo *info) { R_registerRoutines(info, cMethods, NULL /*callMethods*/, fortranMethods, NULL/*externalMethods*/); }
cran/edesign
src/heap.c
<gh_stars>1-10 /* #include "stdlib.h" */ /* #include "math.h" */ #include "heap.h" /* * #define N 10 * #define M 20 */ void int_copy(int *dest, int *src, int n) { int i; for(i=0;i<=n-1;i++) dest[i]=src[i]; } /* * element functions: * init * copy * destroy * print */ heap_element_type *heap_element_init(int *F, int *E, int n, double b, int ib) { heap_element_type *heap_element; /* allocate memory, initialize values */ heap_element = Calloc((size_t)1,heap_element_type); if(heap_element == NULL ) { warning("Calloc failed for heap element"); return(NULL); }; heap_element->n = n; heap_element->F = Calloc((size_t)n,int); if(heap_element->F == NULL) { warning("Calloc failed for F"); return(NULL); }; heap_element->E = Calloc((size_t)n,int); if(heap_element->E == NULL ) { warning("Calloc failed for E"); return(NULL); }; if(F!=NULL) int_copy(heap_element->F,F,n); if(E!=NULL) int_copy(heap_element->E,E,n); heap_element->b = b; heap_element->bound = 0; heap_element->ibranch=ib; heap_element->serial = -1; /* -1 indicates a initialised only element */ heap_element->up = NULL; heap_element->down = NULL; return(heap_element); } void heap_element_copy(heap_element_type *dest, heap_element_type *orig) { int_copy(dest->F, orig->F, orig->n); int_copy(dest->E, orig->E, orig->n); dest->n = orig->n; dest->b = orig->b; dest->bound = orig->bound; dest->ibranch = orig->ibranch; dest->up = orig->up; dest->down = orig->down; dest->serial = -2; /* -2 indicates a copied element */ } void heap_element_destroy(heap_element_type *el) { Free(el->F); Free(el->E); Free(el); } void heap_element_print(heap_element_type *el) { #ifdef HEAP_DEBUG int i,up=-1,down=-1; printf("element %i, n=%i, bound=%f\nF: ",el->serial, el->n, el->b); for(i=0;i<=(el->n)-1;i++) printf("%2i ",el->F[i]); printf("\nE: "); for(i=0;i<=(el->n)-1;i++) printf("%2i ",el->E[i]); printf("\n"); if(el->up) up=el->up->serial; if(el->down) down=el->down->serial; printf("pointers: up->%i, down->%i\n",up,down); #endif } /* * heap funcions: * init * insert * traverse * drop * length */ heap_type *heap_init() { heap_type *heap; int *i,*j,*k,*l; /* dummy arrays */ i=Calloc((size_t)1,int); j=Calloc((size_t)1,int); k=Calloc((size_t)1,int); l=Calloc((size_t)1,int); i[0]=0; j[0]=0; k[0]=0; l[0]=0; /* * allocate memory, initialize values */ heap = Calloc((size_t)1,heap_type); if(heap == NULL) { warning("Calloc failed for heap"); return(NULL); } /* * lower and upper entry to the heap: */ heap->bottom = heap_element_init(i,j,1,0,0); heap->top = heap_element_init(k,l,1,0,0); /* * initialize links between elements */ heap->bottom->up = heap->top; heap->top->down = heap->bottom; /* * indicate top and bottom by bound=+/-1 */ heap->top->bound = 1; heap->bottom->bound = -1; heap->count = 0; heap->maxcount = 0; heap->top->serial = 0; /* 0 for boundary elements */ heap->bottom->serial = 0; /* */ heap->next_serial = 1; return(heap); } void heap_insert(heap_type *heap, heap_element_type *el) { heap_element_type *ptr; ptr=heap->bottom->up; /* search from bottom to top where el fits in the heap */ if (ptr->bound == +1) /* insert first element between top and bottom */ { #ifdef HEAP_DEBUG /* printf("inserting first element with bound %f\n",el->b); */ #endif /* update new links from/to el */ el->up = ptr; el->down = ptr->down; ptr->down->up = el; ptr->down = el; } else { #ifdef HEAP_DEBUG /* printf("inserting element with bound %f\n",el->b); */ #endif if (el->b <= ptr->b) /* insert below lowermost element */ { /* update new links from/to el */ el->up = ptr; el->down = ptr->down; ptr->down->up = el; ptr->down = el; } else { /* go up until top or bound el->b */ while(ptr->bound != +1 && ptr->b <= el->b) ptr=ptr->up; /* insert below found element */ /* update new links from/to el */ el->up = ptr; el->down = ptr->down; ptr->down->up = el; ptr->down = el; } } el->serial = heap->next_serial; heap->next_serial = heap->next_serial+1;; heap->count = heap->count+1; if( heap->count > heap->maxcount) heap->maxcount = heap->count; } void heap_traverse(heap_type *heap) { heap_element_type *ptr; int i=1; ptr=heap->bottom->up; #ifdef HEAP_DEBUG printf("-------- heap contents: --------\n",i); #endif while(ptr->bound != +1 && i < 20) { #ifdef HEAP_DEBUG printf("%i th heap element:\n",i); #endif heap_element_print(ptr); ptr=ptr->up; i++; } #ifdef HEAP_DEBUG printf("--------------------------------\n",i); #endif } heap_element_type *heap_drop(heap_type *heap) { heap_element_type *ptr,*destroy; int lerr; if(! (ptr=heap_element_init(NULL,NULL,heap->top->down->n,0,0))){ /* error("memory exhausted"); exit(1); */ lerr=1; } if(heap->top->down->bound!=-1) { heap_element_copy(ptr,heap->top->down); destroy = heap->top->down; heap->top->down->down->up = heap->top; heap->top->down = heap->top->down->down; heap_element_destroy(destroy); heap->count = heap->count-1; return(ptr); } else return(NULL); } int heap_length(heap_type *heap) { return(heap->count); } /* cc -I/usr/lib/R/include/ heap.c -lm -g -DHEAP_DEBUG=1 \ * -L/usr/lib/R/bin -lR * LD_LIBRARY_PATH=/usr/lib/R/bin ./a.out */ /* int M=200; int N=40; int main(int argc, void *argv) { heap_type *heap; heap_element_type *el; int i; int f[M]; int e[M]; heap = heap_init(); for(i=1;i<=M;i++) { f[i]=-1; e[i]=i; } for(i=1;i<=N;i++) { el = heap_element_init(f,e,M,rand()*(double)sin((double)i),i); heap_insert(heap, el); } heap_traverse(heap); for(i=N;i>=-111;i--) { #ifdef HEAP_DEBUG printf("removing number %i:\n",i); #endif el=heap_drop(heap); if(el!=NULL) heap_element_print(el); else #ifdef HEAP_DEBUG printf("element is NIL!\n"); #endif heap_traverse(heap); } exit(0); } */
cran/edesign
src/heap.h
#include <R.h> #include <Rinternals.h> typedef struct heap_element{ int n; /* dimension of E and F */ int *F; /* set E */ int *E; /* set F */ double b; /* upper bound */ int ibranch; /* branching index */ int bound; /* indicates "real" heap elements, */ /* dummy elements have bound!=0 */ int serial; /* unique identifier for this element */ struct heap_element *up; /* ptr to upper neigbour */ struct heap_element *down; /* ptr to lower neigbour */ } heap_element_type; typedef struct heap{ struct heap_element *bottom; /* dummy element, lower entry point */ struct heap_element *top; /* dummy element, upper entry point */ int count; /* # of elements */ int maxcount; /* max. # of elements */ int next_serial; /* used to generate el->serial */ } heap_type; void int_copy(int *dest, int *src, int n); heap_element_type *heap_element_init(int *F, int *E, int n, double b, int ib); void heap_element_copy(heap_element_type *dest, heap_element_type *orig); void heap_element_destroy(heap_element_type *el); void heap_element_print(heap_element_type *el); heap_type *heap_init(); void heap_insert(heap_type *heap, heap_element_type *el); void heap_traverse(heap_type *heap); heap_element_type *heap_drop(heap_type *heap); int heap_length(heap_type *heap);