repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
---|---|---|
FPGA-Research-Manchester/nextpnr-fabulous
|
xc7/arch.h
|
/*
* nextpnr -- Next Generation Place and Route
*
* Copyright (C) 2018 <NAME> <<EMAIL>>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
#ifndef NEXTPNR_H
#error Include "arch.h" via "nextpnr.h" only.
#endif
#include "torc/Architecture.hpp"
#include "torc/Common.hpp"
using namespace torc::architecture;
using namespace torc::architecture::xilinx;
namespace std {
template <> struct hash<Segments::SegmentReference>
{
size_t operator()(const Segments::SegmentReference &s) const
{
size_t seed = 0;
boost::hash_combine(seed, hash<unsigned>()(s.getCompactSegmentIndex()));
boost::hash_combine(seed, hash<unsigned>()(s.getAnchorTileIndex()));
return seed;
}
};
template <> struct equal_to<Segments::SegmentReference>
{
bool operator()(const Segments::SegmentReference &lhs, const Segments::SegmentReference &rhs) const
{
return lhs.getAnchorTileIndex() == rhs.getAnchorTileIndex() &&
lhs.getCompactSegmentIndex() == rhs.getCompactSegmentIndex();
}
};
template <> struct hash<Tilewire>
{
size_t operator()(const Tilewire &t) const { return hash_value(t); }
};
template <> struct hash<Arc>
{
size_t operator()(const Arc &a) const
{
size_t seed = 0;
boost::hash_combine(seed, hash_value(a.getSourceTilewire()));
boost::hash_combine(seed, hash_value(a.getSinkTilewire()));
return seed;
}
};
} // namespace std
NEXTPNR_NAMESPACE_BEGIN
struct TorcInfo
{
TorcInfo(BaseCtx *ctx, const std::string &inDeviceName, const std::string &inPackageName);
TorcInfo() = delete;
std::unique_ptr<const DDB> ddb;
const Sites &sites;
const Tiles &tiles;
const Segments &segments;
const TileInfo &bel_to_tile_info(int32_t index) const
{
auto si = bel_to_site_index[index];
const auto &site = sites.getSite(si);
return tiles.getTileInfo(site.getTileIndex());
}
const std::string &bel_to_name(int32_t index) const
{
auto si = bel_to_site_index[index];
return sites.getSite(si).getName();
}
std::string wire_to_name(int32_t index) const
{
const auto &tw = wire_to_tilewire[index];
ExtendedWireInfo ewi(*ddb, tw);
std::stringstream ss;
ss << ewi.mTileName << "/" << ewi.mWireName;
ss << "(" << tw.getWireIndex() << "@" << tw.getTileIndex() << ")";
return ss.str();
}
Loc wire_to_loc(int32_t index) const
{
const auto &tw = wire_to_tilewire[index];
ExtendedWireInfo ewi(*ddb, tw);
Loc l;
l.x = (int)ewi.mTileCol;
l.y = (int)ewi.mTileRow;
return l;
}
WireId tilewire_to_wire(const Tilewire &tw) const
{
const auto &segment = segments.getTilewireSegment(tw);
if (!segment.isTrivial())
return segment_to_wire.at(segment);
return trivial_to_wire.at(tw);
}
std::vector<SiteIndex> bel_to_site_index;
int num_bels;
std::vector<BelId> site_index_to_bel;
std::vector<IdString> site_index_to_type;
std::vector<Loc> bel_to_loc;
std::unordered_map<Segments::SegmentReference, WireId> segment_to_wire;
std::unordered_map<Tilewire, WireId> trivial_to_wire;
std::vector<Tilewire> wire_to_tilewire;
int num_wires;
std::vector<DelayInfo> wire_to_delay;
// std::vector<std::vector<int>> wire_to_pips_uphill;
std::vector<std::vector<PipId>> wire_to_pips_downhill;
std::vector<Arc> pip_to_arc;
int num_pips;
int width;
int height;
std::vector<bool> wire_is_global;
std::vector<std::pair<int, int>> tile_to_xy;
TorcInfo(const std::string &inDeviceName, const std::string &inPackageName);
};
extern std::unique_ptr<const TorcInfo> torc_info;
struct BelIterator
{
int cursor;
BelIterator operator++()
{
cursor++;
return *this;
}
BelIterator operator++(int)
{
BelIterator prior(*this);
cursor++;
return prior;
}
bool operator!=(const BelIterator &other) const { return cursor != other.cursor; }
bool operator==(const BelIterator &other) const { return cursor == other.cursor; }
BelId operator*() const
{
BelId ret;
ret.index = cursor;
return ret;
}
};
struct BelRange
{
BelIterator b, e;
BelIterator begin() const { return b; }
BelIterator end() const { return e; }
};
// -----------------------------------------------------------------------
struct BelPinIterator
{
const BelId bel;
Array<const WireIndex>::iterator it;
void operator++() { it++; }
bool operator!=(const BelPinIterator &other) const { return it != other.it && bel != other.bel; }
BelPin operator*() const
{
BelPin ret;
ret.bel = bel;
ret.pin = IdString();
return ret;
}
};
struct BelPinRange
{
BelPinIterator b, e;
BelPinIterator begin() const { return b; }
BelPinIterator end() const { return e; }
};
// -----------------------------------------------------------------------
struct WireIterator
{
int cursor = -1;
void operator++() { cursor++; }
bool operator!=(const WireIterator &other) const { return cursor != other.cursor; }
WireId operator*() const
{
WireId ret;
ret.index = cursor;
return ret;
}
};
struct WireRange
{
WireIterator b, e;
WireIterator begin() const { return b; }
WireIterator end() const { return e; }
};
// -----------------------------------------------------------------------
struct AllPipIterator
{
int cursor = -1;
void operator++() { cursor++; }
bool operator!=(const AllPipIterator &other) const { return cursor != other.cursor; }
PipId operator*() const
{
PipId ret;
ret.index = cursor;
return ret;
}
};
struct AllPipRange
{
AllPipIterator b, e;
AllPipIterator begin() const { return b; }
AllPipIterator end() const { return e; }
};
// -----------------------------------------------------------------------
struct PipIterator
{
const PipId *cursor = nullptr;
void operator++() { cursor++; }
bool operator!=(const PipIterator &other) const { return cursor != other.cursor; }
PipId operator*() const { return *cursor; }
};
struct PipRange
{
PipIterator b, e;
PipIterator begin() const { return b; }
PipIterator end() const { return e; }
};
struct ArchArgs
{
enum ArchArgsTypes
{
NONE,
Z020,
VX980
} type = NONE;
std::string package;
};
struct Arch : BaseCtx
{
int width;
int height;
mutable std::unordered_map<IdString, int> wire_by_name;
mutable std::unordered_map<IdString, int> pip_by_name;
mutable std::unordered_map<Loc, BelId> bel_by_loc;
// std::vector<bool> bel_carry;
std::vector<CellInfo *> bel_to_cell;
std::vector<NetInfo *> wire_to_net;
std::vector<NetInfo *> pip_to_net;
// std::vector<NetInfo *> switches_locked;
ArchArgs args;
Arch(ArchArgs args);
std::string getChipName() const;
IdString archId() const { return id("xc7"); }
ArchArgs archArgs() const { return args; }
IdString archArgsToId(ArchArgs args) const;
// -------------------------------------------------
int getGridDimX() const { return width; }
int getGridDimY() const { return height; }
int getTileBelDimZ(int, int) const { return 8; }
int getTilePipDimZ(int, int) const { return 1; }
// -------------------------------------------------
BelId getBelByName(IdString name) const;
IdString getBelName(BelId bel) const
{
NPNR_ASSERT(bel != BelId());
auto name = torc_info->bel_to_name(bel.index);
if (getBelType(bel) == id_SLICE_LUT6) {
// Append LUT name to name
name.reserve(name.size() + 2);
name += "_";
switch (torc_info->bel_to_loc[bel.index].z) {
case 0:
case 4:
name += 'A';
break;
case 1:
case 5:
name += 'B';
break;
case 2:
case 6:
name += 'C';
break;
case 3:
case 7:
name += 'D';
break;
default:
throw;
}
}
return id(name);
}
uint32_t getBelChecksum(BelId bel) const { return bel.index; }
void bindBel(BelId bel, CellInfo *cell, PlaceStrength strength)
{
NPNR_ASSERT(bel != BelId());
NPNR_ASSERT(bel_to_cell[bel.index] == nullptr);
bel_to_cell[bel.index] = cell;
// bel_carry[bel.index] = (cell->type == id_ICESTORM_LC && cell->lcInfo.carryEnable);
cell->bel = bel;
cell->belStrength = strength;
refreshUiBel(bel);
}
void unbindBel(BelId bel)
{
NPNR_ASSERT(bel != BelId());
NPNR_ASSERT(bel_to_cell[bel.index] != nullptr);
bel_to_cell[bel.index]->bel = BelId();
bel_to_cell[bel.index]->belStrength = STRENGTH_NONE;
bel_to_cell[bel.index] = nullptr;
// bel_carry[bel.index] = false;
refreshUiBel(bel);
}
bool checkBelAvail(BelId bel) const
{
NPNR_ASSERT(bel != BelId());
return bel_to_cell[bel.index] == nullptr;
}
CellInfo *getBoundBelCell(BelId bel) const
{
NPNR_ASSERT(bel != BelId());
return bel_to_cell[bel.index];
}
CellInfo *getConflictingBelCell(BelId bel) const
{
NPNR_ASSERT(bel != BelId());
return bel_to_cell[bel.index];
}
BelRange getBels() const
{
BelRange range;
range.b.cursor = 0;
range.e.cursor = torc_info->num_bels;
return range;
}
Loc getBelLocation(BelId bel) const { return torc_info->bel_to_loc[bel.index]; }
BelId getBelByLocation(Loc loc) const;
BelRange getBelsByTile(int x, int y) const;
bool getBelGlobalBuf(BelId bel) const { return getBelType(bel) == id_BUFGCTRL; }
IdString getBelType(BelId bel) const
{
NPNR_ASSERT(bel != BelId());
auto site_index = torc_info->bel_to_site_index[bel.index];
return torc_info->site_index_to_type[site_index];
}
std::vector<std::pair<IdString, std::string>> getBelAttrs(BelId bel) const;
WireId getBelPinWire(BelId bel, IdString pin) const;
PortType getBelPinType(BelId bel, IdString pin) const;
std::vector<IdString> getBelPins(BelId bel) const;
// -------------------------------------------------
WireId getWireByName(IdString name) const;
IdString getWireName(WireId wire) const
{
NPNR_ASSERT(wire != WireId());
return id(torc_info->wire_to_name(wire.index));
}
IdString getWireType(WireId wire) const;
std::vector<std::pair<IdString, std::string>> getWireAttrs(WireId wire) const;
uint32_t getWireChecksum(WireId wire) const { return wire.index; }
void bindWire(WireId wire, NetInfo *net, PlaceStrength strength)
{
NPNR_ASSERT(wire != WireId());
NPNR_ASSERT(wire_to_net[wire.index] == nullptr);
wire_to_net[wire.index] = net;
net->wires[wire].pip = PipId();
net->wires[wire].strength = strength;
refreshUiWire(wire);
}
void unbindWire(WireId wire)
{
NPNR_ASSERT(wire != WireId());
NPNR_ASSERT(wire_to_net[wire.index] != nullptr);
auto &net_wires = wire_to_net[wire.index]->wires;
auto it = net_wires.find(wire);
NPNR_ASSERT(it != net_wires.end());
auto pip = it->second.pip;
if (pip != PipId()) {
pip_to_net[pip.index] = nullptr;
}
net_wires.erase(it);
wire_to_net[wire.index] = nullptr;
refreshUiWire(wire);
}
bool checkWireAvail(WireId wire) const
{
NPNR_ASSERT(wire != WireId());
return wire_to_net[wire.index] == nullptr;
}
NetInfo *getBoundWireNet(WireId wire) const
{
NPNR_ASSERT(wire != WireId());
return wire_to_net[wire.index];
}
WireId getConflictingWireWire(WireId wire) const { return wire; }
NetInfo *getConflictingWireNet(WireId wire) const
{
NPNR_ASSERT(wire != WireId());
return wire_to_net[wire.index];
}
DelayInfo getWireDelay(WireId wire) const { return {}; }
BelPinRange getWireBelPins(WireId wire) const
{
BelPinRange range;
// TODO
return range;
}
WireRange getWires() const
{
WireRange range;
range.b.cursor = 0;
range.e.cursor = torc_info->num_wires;
return range;
}
// -------------------------------------------------
PipId getPipByName(IdString name) const;
void bindPip(PipId pip, NetInfo *net, PlaceStrength strength)
{
NPNR_ASSERT(pip != PipId());
NPNR_ASSERT(pip_to_net[pip.index] == nullptr);
pip_to_net[pip.index] = net;
WireId dst = getPipDstWire(pip);
NPNR_ASSERT(wire_to_net[dst.index] == nullptr);
wire_to_net[dst.index] = net;
net->wires[dst].pip = pip;
net->wires[dst].strength = strength;
refreshUiPip(pip);
refreshUiWire(dst);
}
void unbindPip(PipId pip)
{
NPNR_ASSERT(pip != PipId());
NPNR_ASSERT(pip_to_net[pip.index] != nullptr);
WireId dst = getPipDstWire(pip);
NPNR_ASSERT(wire_to_net[dst.index] != nullptr);
wire_to_net[dst.index] = nullptr;
pip_to_net[pip.index]->wires.erase(dst);
pip_to_net[pip.index] = nullptr;
refreshUiPip(pip);
refreshUiWire(dst);
}
bool checkPipAvail(PipId pip) const
{
NPNR_ASSERT(pip != PipId());
return pip_to_net[pip.index] == nullptr;
}
NetInfo *getBoundPipNet(PipId pip) const
{
NPNR_ASSERT(pip != PipId());
return pip_to_net[pip.index];
}
WireId getConflictingPipWire(PipId pip) const { return WireId(); }
NetInfo *getConflictingPipNet(PipId pip) const
{
NPNR_ASSERT(pip != PipId());
return pip_to_net[pip.index];
}
AllPipRange getPips() const
{
AllPipRange range;
range.b.cursor = 0;
range.e.cursor = torc_info->num_pips;
return range;
}
Loc getPipLocation(PipId pip) const
{
Loc loc;
NPNR_ASSERT("TODO");
return loc;
}
IdString getPipName(PipId pip) const;
IdString getPipType(PipId pip) const { return IdString(); }
std::vector<std::pair<IdString, std::string>> getPipAttrs(PipId pip) const;
uint32_t getPipChecksum(PipId pip) const { return pip.index; }
WireId getPipSrcWire(PipId pip) const
{
NPNR_ASSERT(pip != PipId());
const auto &arc = torc_info->pip_to_arc[pip.index];
const auto &tw = arc.getSourceTilewire();
return torc_info->tilewire_to_wire(tw);
}
WireId getPipDstWire(PipId pip) const
{
NPNR_ASSERT(pip != PipId());
const auto &arc = torc_info->pip_to_arc[pip.index];
const auto &tw = arc.getSinkTilewire();
return torc_info->tilewire_to_wire(tw);
}
DelayInfo getPipDelay(PipId pip) const
{
NPNR_ASSERT(pip != PipId());
auto wire = getPipDstWire(pip);
return torc_info->wire_to_delay[wire.index];
}
PipRange getPipsDownhill(WireId wire) const
{
PipRange range;
NPNR_ASSERT(wire != WireId());
const auto &pips = torc_info->wire_to_pips_downhill[wire.index];
range.b.cursor = pips.data();
range.e.cursor = range.b.cursor + pips.size();
return range;
}
PipRange getPipsUphill(WireId wire) const
{
PipRange range;
// NPNR_ASSERT(wire != WireId());
// const auto &pips = torc_info->wire_to_pips_uphill[wire.index];
// range.b.cursor = pips.data();
// range.e.cursor = range.b.cursor + pips.size();
return range;
}
PipRange getWireAliases(WireId wire) const
{
PipRange range;
NPNR_ASSERT(wire != WireId());
range.b.cursor = nullptr;
range.e.cursor = nullptr;
return range;
}
BelId getPackagePinBel(const std::string &pin) const;
std::string getBelPackagePin(BelId bel) const;
// -------------------------------------------------
GroupId getGroupByName(IdString name) const;
IdString getGroupName(GroupId group) const;
std::vector<GroupId> getGroups() const;
std::vector<BelId> getGroupBels(GroupId group) const;
std::vector<WireId> getGroupWires(GroupId group) const;
std::vector<PipId> getGroupPips(GroupId group) const;
std::vector<GroupId> getGroupGroups(GroupId group) const;
// -------------------------------------------------
delay_t estimateDelay(WireId src, WireId dst) const;
delay_t predictDelay(const NetInfo *net_info, const PortRef &sink) const;
delay_t getDelayEpsilon() const { return 20; }
delay_t getRipupDelayPenalty() const { return 200; }
float getDelayNS(delay_t v) const { return v * 0.001; }
DelayInfo getDelayFromNS(float ns) const
{
DelayInfo del;
del.delay = delay_t(ns * 1000);
return del;
}
uint32_t getDelayChecksum(delay_t v) const { return v; }
bool getBudgetOverride(const NetInfo *net_info, const PortRef &sink, delay_t &budget) const;
// -------------------------------------------------
bool pack();
bool place();
bool route();
// -------------------------------------------------
std::vector<GraphicElement> getDecalGraphics(DecalId decal) const;
DecalXY getBelDecal(BelId bel) const;
DecalXY getWireDecal(WireId wire) const;
DecalXY getPipDecal(PipId pip) const;
DecalXY getGroupDecal(GroupId group) const;
// -------------------------------------------------
// Get the delay through a cell from one port to another, returning false
// if no path exists
bool getCellDelay(const CellInfo *cell, IdString fromPort, IdString toPort, DelayInfo &delay) const;
// Get the port class, also setting clockDomain if applicable
TimingPortClass getPortTimingClass(const CellInfo *cell, IdString port, int &clockInfoCount) const;
// Get the TimingClockingInfo of a port
TimingClockingInfo getPortClockingInfo(const CellInfo *cell, IdString port, int index) const;
// Return true if a port is a net
bool isGlobalNet(const NetInfo *net) const;
// -------------------------------------------------
// Perform placement validity checks, returning false on failure (all
// implemented in arch_place.cc)
// Whether or not a given cell can be placed at a given Bel
// This is not intended for Bel type checks, but finer-grained constraints
// such as conflicting set/reset signals, etc
bool isValidBelForCell(CellInfo *cell, BelId bel) const;
// Return true whether all Bels at a given location are valid
bool isBelLocationValid(BelId bel) const;
// Helper function for above
bool logicCellsCompatible(const CellInfo **it, const size_t size) const;
// -------------------------------------------------
// Assign architecure-specific arguments to nets and cells, which must be
// called between packing or further
// netlist modifications, and validity checks
void assignArchInfo();
void assignCellInfo(CellInfo *cell);
// -------------------------------------------------
BelPin getIOBSharingPLLPin(BelId pll, IdString pll_pin) const
{
auto wire = getBelPinWire(pll, pll_pin);
for (auto src_bel : getWireBelPins(wire)) {
if (getBelType(src_bel.bel) == id_SB_IO && src_bel.pin == id_D_IN_0) {
return src_bel;
}
}
NPNR_ASSERT_FALSE("Expected PLL pin to share an output with an SB_IO D_IN_{0,1}");
}
float placer_constraintWeight = 10;
};
NEXTPNR_NAMESPACE_END
|
clean-code-craft-tcq-3/spring-in-cpp-PANINDRA-REDDY-BANDIATMAKUR
|
stats.h
|
#include <vector>
struct EmailAlert
{
char emailSent;
char emailNotSent;
};
struct LEDAlert
{
char ledGlows;
char ledOff;
};
namespace Statistics {
float ComputeStatistics(const std::vector<float *>& alerters );
}
|
jboillot/OctagonAI
|
test2.c
|
<filename>test2.c
int main() {
int x,y;
x = 10;
y = 0;
while (x > y) {
x = x - 1;
y = y + 1;
}
}
|
jboillot/OctagonAI
|
test1.c
|
<reponame>jboillot/OctagonAI
int main() {
int x, y, z;
if (x >= y) z = x - y;
else z = y - x;
}
|
jboillot/OctagonAI
|
test.c
|
<gh_stars>0
int main() {
int a = 1;
int b = 3;
a = a + b;
}
|
naisila/libhash
|
src/hash.c
|
<filename>src/hash.c
/*
PROJECT MADE BY:
<NAME> 21600336 SECTION 2
KUNDUZ EFRONOVA 21600469 SECTION 2
30 MARCH 2019
*/
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <string.h>
#include "hash.h"
HashTable *hash_init (int N, int K)
{
HashTable *ht;
if (N < MIN_N || N > MAX_N) {
printf("Error! Value of N should be between 100 and 1000.\n");
return NULL;
}
if(K > N)
{
printf("Error! Value of K should not be greater than N.\n");
return NULL;
}
if(N % K != 0) {
printf("Error! N should be a multiple of K.\n");
return NULL;
}
ht = malloc(sizeof(HashTable));
if (ht == NULL) {
printf("HASHTABLE ALLOCATION FAILED!!!\n");
return (NULL);
}
ht->M = N/K;
if(ht->M < MIN_M || ht->M > MAX_M) {
printf("Error! Value of K should be between 1 and 100.\n");
return NULL;
}
ht->table = (struct node**)malloc(N * sizeof(struct node));
if (ht->table == NULL) {
printf("HASHTABLE BUCKETS ALLOCATION FAILED!!!\n");
return (NULL);
}
//initialize K locks
ht->locks = malloc(K * sizeof(pthread_mutex_t));
for(int j = 0; j < K; j++)
pthread_mutex_init(&((ht->locks)[j]),NULL);
//initialize each bucket to null
for (int i = 0; i < N; i++)
{
ht->table[i] = NULL;
}
ht->N = N;
ht->K = K;
ht->currentSize = 0;
printf ("Hash Table successfully created!\n");
return ht;
}
int hash_insert (HashTable *hp, int k, void *v)
{
if(k < 1)
{
printf("ERROR! Key should be a positive integer!\n");
return -1;
}
if (hp == NULL) {
printf("ERROR! Hash Table is NULL!\n");
return -1;
}
struct node *node;
node = malloc(sizeof(struct node));
if (node == NULL) {
printf("ERROR! New item couldn't be allocated!\n");
return (-1);
}
node->key = k;
node->value = v;
//calculate the bucket to which the key belongs to
int bucket = k % (hp->N);
int region = bucket / (hp->M);
pthread_mutex_lock(&((hp->locks)[region]));
if (hp->table[bucket] != NULL) {
struct node *tmp = hp->table[bucket];
while (tmp != NULL) {
if (tmp->key == node->key) {
break;
}
tmp = tmp->next;
}
if (tmp == NULL) {
//add new node at the end of LL
node->next = hp->table[bucket];
hp->table[bucket] = node;
} else {
pthread_mutex_unlock(&((hp->locks)[region]));
// If key already present, does nothing and returns -1.
return(-1);
}
} else {
//head node
node->next = NULL;
hp->table[bucket] = node;
}
hp->currentSize = hp->currentSize + 1;
pthread_mutex_unlock(&((hp->locks)[region]));
return (0);
}
int hash_delete (HashTable *hp, int k) {
if (hp == NULL) {
printf("ERROR! Hash Table is NULL!\n");
return -1;
}
if(k < 1){
printf("ERROR! Key should be a positive integer!\n");
return -1;
}
//find to which bucket this key belongs to
int bucket = k % hp->N;
int region = bucket / hp->M;
pthread_mutex_lock(&((hp->locks)[region]));
struct node * tmp = hp->table[bucket];
struct node * tmp2 = hp->table[bucket];
while (tmp != NULL) {
if (tmp->key == k) {
break;
}
tmp2 = tmp;
tmp = tmp->next;
}
if(tmp == NULL)
{
pthread_mutex_unlock(&((hp->locks)[region]));
printf("Key doesn't exist!\n");
return (-1);
}
//delete key
if(tmp == tmp2){
hp->table[bucket] = NULL;
free(tmp);
}
else
{
tmp2->next = tmp->next;
free(tmp);
}
//decrease the number of elements in the list
hp->currentSize = hp->currentSize - 1;
pthread_mutex_unlock(&((hp->locks)[region]));
return (0);
}
int hash_update (HashTable *hp, int k, void *v)
{
if (hp == NULL) {
printf("ERROR! Hash Table is NULL!\n");
return -1;
}
if(k < 1){
printf("ERROR! Key should be a positive integer!\n");
return -1;
}
//find the bucket to which the key belongs to
int bucket = k % hp->N;
int region = bucket / (hp->M);
pthread_mutex_lock(&((hp->locks)[region]));
struct node *tmp = hp->table[bucket];
while (tmp != NULL) {
if (tmp->key == k) {
break;
}
tmp = tmp->next;
}
if (tmp == NULL) {
pthread_mutex_unlock(&((hp->locks)[region]));
printf("Key doesn't exist!\n");
return (-1);
} else {
//change the value of that particular key
tmp->value = v;
}
pthread_mutex_unlock(&((hp->locks)[region]));
return (0);
}
int hash_get (HashTable *hp, int k, void **vp)
{
if (hp == NULL) {
printf("ERROR! Hash Table is NULL!\n");
return -1;
}
if(k < 1){
printf("ERROR! Key should be a positive integer!\n");
return -1;
}
//find the bucket to which the key belongs to
int bucket = k % hp->N;
int region = bucket / hp->M;
pthread_mutex_lock(&((hp->locks)[region]));
struct node * tmp = hp->table[bucket];
while (tmp != NULL) {
if (tmp->key == k) {
break;
}
tmp = tmp->next;
}
if (tmp == NULL) {
pthread_mutex_unlock(&((hp->locks)[region]));
printf("Key doesn't exist!\n");
return -1;
}
else
{
//get the value of the node to the argument
(*vp) = tmp->value;
}
pthread_mutex_unlock(&((hp->locks)[region]));
return (0);
}
int hash_destroy (HashTable *hp)
{
struct node *tmp;
if (hp == NULL) {
printf ("Destroy Job done!\n");
return (0);
}
for(int j = 0; j < hp->K; j++)
{
pthread_mutex_lock(&((hp->locks)[j]));
}
for (int i = 0; i < hp->N; i++) {
if (hp->table[i] != NULL) {
//Traverse all the list and free the nodes
while(hp->table[i] != NULL) {
tmp = hp->table[i]->next;
hp->table[i]->value=NULL;
free(hp->table[i]);
hp->table[i] = tmp;
}
}
}
free(hp->table);
//destroy all locks
for(int j = 0; j < hp->K; j++)
{
pthread_mutex_destroy(&((hp->locks)[j]));
}
//free the table
free(hp->locks);
free(hp);
return (0);
}
|
naisila/libhash
|
src/test.c
|
/*
PROJECT MADE BY:
<NAME> 21600336 SECTION 2
KUNDUZ EFRONOVA 21600469 SECTION 2
30 MARCH 2019
*/
#include <pthread.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <fcntl.h>
#include <sys/stat.h>
#include "pthread.h"
#include "hash.h"
HashTable *ht1; // space allocated inside library
int W; //number of operations per thread
void *runner(void *param);
int main(int argc, char **argv)
{
int N, K, T;
pthread_t * thread_id;
pthread_attr_t attr;
pthread_attr_init(&attr);
//get arguments
N = atoi(argv[1]);
K = atoi(argv[2]);
T = atoi(argv[3]);
W = atoi(argv[4]);
//initialize table
ht1 = hash_init (N, K);
//allocate threads
thread_id = malloc(T * sizeof(pthread_t));
//start time
struct timeval tv0;
gettimeofday(&tv0, NULL);
//create threads
for(int i = 0; i < T; i++)
{
pthread_create(&(thread_id[i]), &attr, runner, (void*)(i));
}
//wait for threads to finish
for(int i = 0; i < T; i++)
{
pthread_join(thread_id[i], NULL);
}
//end time
struct timeval tv1;
gettimeofday(&tv1, NULL);
//get start and end in microseconds
long long start = tv0.tv_sec*10000000 + tv0.tv_usec;
long long end = tv1.tv_sec*10000000 + tv1.tv_usec;
//get elapsed time of write
printf("----------------------------------------------\n");
printf("Doing insert operations ... \n");
printf("For N = %d, K = %d, W = %d, T = %d:\nRequired time is %lld milliseconds.\n", N, K, W, T, (end-start));
printf("----------------------------------------------\n");
hash_destroy (ht1);
}
/* The thread will begin control in this function */
void *runner(void *param)
{
//insert inside ht1
for (int i = W * ((int)param) + 1 ; i < W * ((int)param) + W; i++) {
hash_insert (ht1, i, (void *) i);
}
pthread_exit(0);
}
|
naisila/libhash
|
src/hash.h
|
/*
PROJECT MADE BY:
<NAME> 21600336 SECTION 2
KUNDUZ EFRONOVA 21600469 SECTION 2
30 MARCH 2019
*/
#ifndef HASH_H
#define HASH_H
#include <pthread.h>
#define MIN_N 100
#define MAX_N 1000
#define MIN_M 10
#define MAX_M 1000
struct hash_table
{
//structure to keep linked-list elements
struct node
{
int key;
void * value;
struct node * next;
};
//each bucket is a linked list
struct node ** table;
//table size
int N;
//number of locks/regions
int K;
//size of a region
int M;
//number of elements currently found in the table
int currentSize;
//locks
pthread_mutex_t* locks;
};
typedef struct hash_table HashTable;
HashTable *hash_init (int N, int K);
int hash_insert (HashTable *hp, int k, void* v);
int hash_delete (HashTable *hp, int k);
int hash_update (HashTable *hp, int, void *v);
int hash_get (HashTable *hp, int k, void **vp);
int hash_destroy (HashTable *hp);
#endif /* HASH_H */
|
naisila/libhash
|
src/integer-count.c
|
<filename>src/integer-count.c
/*
PROJECT MADE BY:
<NAME> 21600336 SECTION 2
KUNDUZ EFRONOVA 21600469 SECTION 2
30 MARCH 2019
*/
#include <pthread.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include "pthread.h"
#include "hash.h"
#define MAXCHAR 50000
HashTable *ht1; // space allocated inside library
pthread_mutex_t motherOfLocks; //MAIN LOCK
void *runner(void *param);
int main(int argc, char **argv)
{
if(argc < 2)
{
printf("Error! Not enough arguments!\n");
return 0;
}
pthread_t * thread_id;
pthread_attr_t attr;
pthread_attr_init(&attr);
struct node ** list;
pthread_mutex_init(&motherOfLocks, NULL);
//get number of text files
int c = atoi(argv[1]);
if(argc < (c + 2))
{
printf("Error! Not enough arguments!\n");
return 0;
}
//initialize hash table
ht1 = hash_init (1000, 1);
//allocate threads
thread_id = malloc(c * sizeof(pthread_t));
//create a thread for each text file
for(int i = 0; i < c; i++)
{
pthread_create(&(thread_id[i]),&attr,runner,argv[i + 2]);
}
//wait for all threads to finish
for(int i = 0; i < c; i++)
{
pthread_join(thread_id[i],NULL);
}
list = (struct node**)malloc(ht1->currentSize * sizeof(struct node));
int index = 0;
struct node * tmp;
//put all nodes in a Node array
for(int i = 0; i < 1000; i++)
{
tmp = ht1->table[i];
while(tmp != NULL)
{
list[index] = ht1->table[i];
index += 1;
tmp = tmp->next;
}
}
struct node * a;
//sort the list of Nodes based on key
for (int i = 0; i < ht1->currentSize; ++i)
{
for (int j = i + 1; j < ht1->currentSize; ++j)
{
if (list[i]->key > list[j]->key)
{
a = list[i];
list[i] = list[j];
list[j] = a;
}
}
}
//write each key and the number of its occurrences in the specified text file
FILE * fp;
int i;
/* open the file for writing*/
fp = fopen (argv[c+2],"w");
/* write 10 lines of text into the file stream*/
for(i = 0; i < ht1->currentSize;i++){
fprintf (fp, "%d: ", list[i]->key);
fprintf (fp, "%d\n", (int *)(list[i]->value));
}
/* close the file*/
fclose (fp);
return 0;
}
/* The thread will begin control in this function */
void *runner(void *param)
{
FILE *fp;
int current;
void* value;
int casted;
//open specified text file
fp = fopen((char*)param, "r");
if (fp == NULL) {
printf("Couldn't read file %s\n", (char*)param);
pthread_exit(0);
}
char input[MAXCHAR];
//read integers from file and update hash table accordingly
while (fgets(input, MAXCHAR, fp) != NULL)
{
input[strcspn(input, "\n")] = 0;
current = atoi(input);
if(hash_insert(ht1, current, (void *)1) == -1)
{
pthread_mutex_lock(&motherOfLocks);
if(hash_get(ht1, current, &value) == 0)
{
casted = (int)(value);
casted += 1;
hash_update(ht1, current, (void *)casted);
}
pthread_mutex_unlock(&motherOfLocks);
}
}
pthread_exit(0);
}
|
VaibhaviOSGeek/VLViewController
|
Example/VLViewController/VLAppDelegate.h
|
<reponame>VaibhaviOSGeek/VLViewController
//
// VLAppDelegate.h
// VLViewController
//
// Created by <EMAIL> on 02/15/2017.
// Copyright (c) 2017 <EMAIL>. All rights reserved.
//
@import UIKit;
@interface VLAppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end
|
VaibhaviOSGeek/VLViewController
|
Example/VLViewController/VLViewController.h
|
<reponame>VaibhaviOSGeek/VLViewController
//
// VLViewController.h
// VLViewController
//
// Created by <EMAIL> on 02/15/2017.
// Copyright (c) 2017 <EMAIL>. All rights reserved.
//
@import UIKit;
@interface VLViewController : UIViewController
@end
|
huwb/jitternator
|
src/TimeAlgebra/TimeAlgebra/GameSimulation.h
|
<reponame>huwb/jitternator<gh_stars>10-100
// This file is subject to the MIT License as seen in the root of this folder structure (LICENSE)
//
#pragma once
#include "FloatTime.h"
/**
* Mock game simulation
*/
class GameSimulation
{
public:
void Update( const FloatTime& frameDt )
{
InputsUpdate( frameDt );
AnimationUpdate( frameDt );
//CameraUpdateWithRestOfGame( frameDt );
PhysicsUpdate( frameDt );
MainUpdate( frameDt );
//CameraUpdateNoSim( frameDt );
CameraUpdateEndFrame( frameDt );
}
void InputsUpdate( const FloatTime& frameDt )
{
_inputValLast = _inputVal;
// get keyboard input - here just use dt as an arbitrary mock input.
// assume our input value comes from the frame start time. may not always be the case!
_inputVal = FloatTime( 30.0f, frameDt );
}
FloatTime SampleAnimation( const FloatTime& frameDt )
{
// evaluate animation at end frame time - I've seen this on previous projects
// animated value is just a linear curve
FloatTime val = FloatTime( 5.0f * frameDt.Time(), frameDt );
// now move val forward to end frame time
val.FinishedUpdate( frameDt );
return val;
}
void AnimationUpdate( const FloatTime& frameDt )
{
// assume that the sampled animation gives the end-frame (rendered) values
// in this case, the start frame values are the end frame values from the previous frame
_carAnimTargetPos = _carAnimTargetPosEndFrame;
// compute a new end frame value
_carAnimTargetPosEndFrame = SampleAnimation( frameDt );
}
void PhysicsUpdate( const FloatTime& frameDt )
{
// _physTimeBalance is the cumulative delta between game update time and physics update time. this could be changed
// to be just a float instead of a FloatTime, but putting this delta on the physics time gives a little bit of
// additional validation that the simulation is consistent.
_physTimeBalance += FloatTime( frameDt.Value(), _physicsDt );
if( _physTimeBalance.Value() <= 0.0f )
{
// nothing to be done - physics is already up to date
return;
}
// this will be used to interpolate physics -> camera time
CarState lastState;
// loop while we still have outstanding time to simulate - while physics is behind camera shutter time
do
{
lastState = _carStateLatest;
PhysicsUpdateStep( frameDt, _physicsDt );
// update balance and move value forward in time in one fell swoop, by using the integrate function
// with a velocity of -1, which will make the value decrease by the amount of time moved forward.
_physTimeBalance.Integrate( FloatTime( -1.0f, _physicsDt ), _physicsDt );
AdvanceDt( _physicsDt );
} while( _physTimeBalance.Value() > 0.0f );
// now interpolate the physics state at the camera shutter time
// cam shutter time is current time + delta time
FloatTime camShutterTime = FloatTime( frameDt.Time(), frameDt ) + frameDt;
_carStateCurrent._pos = FloatTime::LerpToTime( lastState._pos, _carStateLatest._pos, camShutterTime );
_carStateCurrent._vel = FloatTime::LerpToTime( lastState._vel, _carStateLatest._vel, camShutterTime );
// optional assert to ensure two separate values are in sync
CheckConsistency( _carStateCurrent._pos, _carStateCurrent._vel );
}
void PhysicsUpdateStep( const FloatTime& frameDt, const FloatTime& physicsDt )
{
// we do multiple physics updates in a frame. here the update takes values from 2 sources:
// - animation data - we could potentially subsample the animation to give fresh data for each physics step. instead we
// knowingly and explicitly use the state start frame value by resampling at the current physics time:
CheckConsistency( _carAnimTargetPos, frameDt );
FloatTime carAnimTargetPos_const = FloatTime( _carAnimTargetPos.Value(), physicsDt );
// - input values - again we explicitly reuse stale data, but in some scnarios (VR) we may sample up to date fresh values here
// and would not need to hack this:
CheckConsistency( _inputVal, frameDt );
FloatTime inputVal_const = FloatTime( _inputVal.Value(), physicsDt );
FloatTime accel = inputVal_const + (carAnimTargetPos_const - _carStateLatest._pos);
_carStateLatest._pos.Integrate( _carStateLatest._vel, physicsDt );
_carStateLatest._vel.Integrate( accel, physicsDt );
}
void MainUpdate( const FloatTime& frameDt )
{
// systems update - ai, logic, etc
}
// this can be run after the other bits in the game are updated. it doesn't use the dt value in the time update.
void CameraUpdateNoSim( const FloatTime& frameDt )
{
// use the frame time giver, advanced to the end of the frame
FloatTime cameraDt = frameDt;
AdvanceDt( cameraDt );
// place camera two units behind car (locked - no dynamics!)
_cameraPos = _carStateCurrent._pos - FloatTime( 2.0f, cameraDt );
// add a bit of user input. we decide here to take the start frame input values, and therefore set the time manually
_cameraPos += FloatTime( 0.1f * _inputVal.Value(), cameraDt );
}
// this one should be run with start frame data (i.e. before car updates)
void CameraUpdateWithRestOfGame( const FloatTime& frameDt )
{
// lerp camera towards car
_cameraPos = FloatTime::Lerp( _cameraPos, _carStateCurrent._pos, FloatTime( 6.0f, frameDt ) * frameDt );
// add influence from changing input
if( _inputVal.Time() > _inputValLast.Time() )
{
_cameraPos += FloatTime( 0.2f, frameDt ) * Vel( _inputValLast, _inputVal );
}
// add influence from speed
_cameraPos -= _carStateCurrent._vel * FloatTime( 0.1f, frameDt );
_cameraPos.FinishedUpdate( frameDt );
}
// a scheme i often see is cameras are updated at the end of the frame, using end frame values. this function tries to implement this,
// but is not consistent, see the comments below.
void CameraUpdateEndFrame( const FloatTime& frameDt )
{
// SCHEME: sample car position etc at the end frame values, and then simulate forwards from end this frame state. so the from-time is
// the end frame time, and to to-time must then be 1 frame ahead. unfortunately this does not work in this strict framework because
// we don't know how far forward to advance the camera sim, because we don't know the next frame dt (this is typically measured from
// real time at the end of the frame).
// so instead we take the end frme state but set the times to be the start frame state, and then update from there. this feels similar to
// operator splitting for solving differential equations. there is some error from this but i dont have a clear understanding
// of if or when this error would manifest as jitter.
// sample at start frame time
FloatTime camCarPos = FloatTime( _carStateCurrent._pos.Value(), frameDt );
FloatTime camCarVel = FloatTime( _carStateCurrent._vel.Value(), frameDt );
// lerp camera towards car
_cameraPos = FloatTime::Lerp( _cameraPos, camCarPos, FloatTime( 6.0f, frameDt ) * frameDt );
// add influence from changing input
if( _inputVal.Time() > _inputValLast.Time() )
{
_cameraPos += FloatTime( 0.2f, frameDt ) * Vel( _inputValLast, _inputVal );
}
// add influence from speed
_cameraPos -= camCarVel * FloatTime( 0.1f, frameDt );
_cameraPos.FinishedUpdate( frameDt );
}
// sample end frame state and render
void Render( const FloatTime& frameDt )
{
// sample simulation state
const FloatTime renderCarPos = _carStateCurrent._pos;
const FloatTime renderCarVel = _carStateCurrent._vel;
const FloatTime renderCamPos = _cameraPos;
// strong check - everything should be at end frame time
FloatTime endFrameTime = frameDt;
AdvanceDt( endFrameTime );
CheckConsistency( renderCarPos, endFrameTime );
CheckConsistency( renderCarVel, endFrameTime );
CheckConsistency( renderCamPos, endFrameTime );
// the 'render'
printf( "Car pos: %f\n", _carStateCurrent._pos.Value() );
}
struct CarState
{
FloatTime _pos = FloatTime::SimStartValue( 0.0f );
FloatTime _vel = FloatTime::SimStartValue( 0.0f );
};
CarState _carStateLatest;
CarState _carStateCurrent;
FloatTime _inputVal = FloatTime::SimStartValue( 0.0f );
FloatTime _inputValLast = FloatTime::SimStartValue( 0.0f );
FloatTime _carAnimTargetPos = FloatTime::SimStartValue( 0.0f );
FloatTime _carAnimTargetPosEndFrame = FloatTime::SimStartValue( 0.0f );
FloatTime _physTimeBalance = FloatTime::SimStartValue( 0.0f );
FloatTime _physicsDt = FloatTime::SimStartValue( 1.0f / 64.0f );
FloatTime _cameraPos = FloatTime::SimStartValue( 0.0f );
};
|
huwb/jitternator
|
src/TimeAlgebra/TimeAlgebra/FloatTime.h
|
// This file is subject to the MIT License as seen in the root of this folder structure (LICENSE)
//
#pragma once
class FloatTime;
// could this be automatic through a conversion constructor?
void CheckConsistency( const FloatTime& a, const FloatTime& b );
/**
* A float value with a timestamp attached
*/
class FloatTime
{
private:
FloatTime()
{
}
public:
// creates a float with timestamp, using the timestamp from an existing value. using the
// frame dt is a common pattern here
explicit FloatTime( float value, const FloatTime& timeGiver )
{
_value = value;
_time = timeGiver.Time();
}
FloatTime operator+( const FloatTime& other ) const
{
CheckConsistency( *this, other );
FloatTime result;
result._value = _value + other._value;
result._time = _time;
return result;
}
FloatTime operator-( const FloatTime& other ) const
{
CheckConsistency( *this, other );
FloatTime result;
result._value = _value - other._value;
result._time = _time;
return result;
}
FloatTime operator*( const FloatTime& other ) const
{
CheckConsistency( *this, other );
FloatTime result;
result._value = _value * other._value;
result._time = _time;
return result;
}
FloatTime operator/( const FloatTime& other ) const
{
CheckConsistency( *this, other );
FloatTime result;
result._value = _value / other._value;
result._time = _time;
return result;
}
FloatTime& operator+=( const FloatTime& other )
{
CheckConsistency( *this, other );
_value += other.Value();
return *this;
}
FloatTime& operator-=( const FloatTime& other )
{
CheckConsistency( *this, other );
_value -= other.Value();
return *this;
}
FloatTime& operator*=( const FloatTime& other )
{
CheckConsistency( *this, other );
_value *= other._value;
return *this;
}
void Integrate( const FloatTime& rateOfChange, const FloatTime& dt )
{
CheckConsistency( *this, rateOfChange );
CheckConsistency( *this, dt );
*this += rateOfChange * dt;
_time = Time() + dt.Value();
}
void FinishedUpdate( const FloatTime& dt )
{
CheckConsistency( *this, dt );
_time = Time() + dt.Value();
}
float Value() const
{
return _value;
}
float Time() const
{
return _time;
}
// straightforward lerp of two values, given a lerp parameter
static FloatTime Lerp( const FloatTime& a, const FloatTime& b, const FloatTime& lerpParam )
{
return (FloatTime( 1.0f, lerpParam ) - lerpParam) * a + lerpParam * b;
}
// lerps between two values at different simulation times, to give an interpolated value
// at the provided target time. this would probably only be used in special cases, such as
// in code that runs simulations.
static FloatTime LerpToTime( const FloatTime& a, const FloatTime& b, const FloatTime& lerpTargetTime )
{
FloatTime result;
// strip time as we are interpolating across multiple times
float s = (lerpTargetTime.Value() - a.Time()) / (b.Time() - a.Time());
// lerp manually (unprotected)
result._value = (1.0f - s) * a.Value() + s * b.Value();
result._time = (1.0f - s) * a.Time() + s * b.Time();
return result;
}
static FloatTime SimStartValue( float value )
{
FloatTime result;
result._value = value;
result._time = 0.0f;
return result;
}
private:
float _value = 0.0f;
float _time = 0.0f;
};
bool ApproxEqual( float a, float b, float eps = 0.0001f )
{
return abs( a - b ) < eps;
}
void CheckConsistency( const FloatTime& a, const FloatTime& b )
{
bool consistent = ApproxEqual( a.Time(), b.Time() );
if( !consistent )
__debugbreak();
}
void AdvanceDt( FloatTime& io_dt, const FloatTime& newDt )
{
CheckConsistency( io_dt, newDt );
// save current dt
FloatTime curDt = io_dt;
// apply new dt value for next frame
io_dt = newDt;
// advance time by the current dt
io_dt.FinishedUpdate( curDt );
}
void AdvanceDt( FloatTime& io_dt )
{
AdvanceDt( io_dt, io_dt );
}
// Vel is interesting as we have timestamps for the values. This eliminates an issue i've seen where a vel is
// computed through finite differences but with an incorrect dt.
FloatTime Vel( const FloatTime& val_t0, const FloatTime& val_t1 )
{
if( val_t1.Time() < val_t0.Time() )
__debugbreak(); // expected arg order violated. this could be gracefully handled but erring on strictness for now..
//// returning 0 is not ideal, so do nothing for now
//if( ApproxEqual( val_t0.Time(), val_t1.Time() ) )
// return 0.0f;
float vel = (val_t1.Value() - val_t0.Value()) / (val_t1.Time() - val_t0.Time());
return FloatTime( vel, val_t1 );
}
|
kiyoMatsui/kiyoswebgame
|
server/app/assets/emscripten/kgePointLine.h
|
<gh_stars>0
/*-------------------------------*\
Copyright 2021 <NAME>
KiyosGameEngine v1.1
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
\*-------------------------------*/
#ifndef KGE_POINTLINE_H
#define KGE_POINTLINE_H
#include <cmath>
#ifdef USED_FOR_KGE_TESTS
#define kgeTestPrint(x) std::cout << x << std::endl
#else
#define kgeTestPrint(x)
#endif
namespace kge {
template <typename T>
class point {
static_assert(std::is_arithmetic<T>::value, "must be arithmetic type / useful fundamental type");
public:
point<T>() { kgeTestPrint("called no-args constructor"); }
point<T>(T ax, T ay) : x(ax), y(ay) { kgeTestPrint("called constructor with arguments"); }
point<T>(const point<T>& arg1) = default;
point<T>& operator=(const point<T>& arg1) = default;
point<T>(point<T>&& other) noexcept = default;
point<T>& operator=(point<T>&& other) noexcept = default;
~point<T>() = default;
T x{0};
T y{0};
point<T>& operator+=(const point<T>& arg1) {
kgeTestPrint("called operator +=");
this->x += arg1.x;
this->y += arg1.y;
return *this;
}
point<T>& operator+=(const T& arg1) {
kgeTestPrint("called operator += for type");
this->x += arg1;
this->y += arg1;
return *this;
}
point<T>& operator-=(const point<T>& arg1) {
kgeTestPrint("called operator -=");
this->x -= arg1.x;
this->y -= arg1.y;
return *this;
}
point<T>& operator-=(const T& arg1) {
kgeTestPrint("called operator -= for type");
this->x -= arg1;
this->y -= arg1;
return *this;
}
point<T>& operator*=(const point<T>& arg1) {
kgeTestPrint("called operator *=");
this->x *= arg1.x;
this->y *= arg1.y;
return *this;
}
point<T>& operator*=(const T& arg1) {
kgeTestPrint("called operator *= for type");
this->x *= arg1;
this->y *= arg1;
return *this;
}
point<T>& operator/=(const point<T>& arg1) {
kgeTestPrint("called operator /=");
this->x /= arg1.x;
this->y /= arg1.y;
return *this;
}
point<T>& operator/=(const T& arg1) {
kgeTestPrint("called operator /= for type");
this->x /= arg1;
this->y /= arg1;
return *this;
}
T length(const point<T>& arg1) const {
kgeTestPrint("called length");
point<T> a = *this - arg1;
return (std::hypot(a.x, a.y));
}
};
template <typename T>
point<T> operator+(const point<T>& arg1, const point<T>& arg2) {
kgeTestPrint("called operator +");
return point<T>((arg1.x + arg2.x), (arg1.y + arg2.y));
}
template <typename T>
point<T> operator+(const point<T>& arg1, const T& arg2) {
kgeTestPrint("called operator + with type");
return point<T>((arg1.x + arg2), (arg1.y + arg2));
}
template <typename T>
point<T> operator-(const point<T>& arg1, const point<T>& arg2) {
kgeTestPrint("called operator -");
return point<T>((arg1.x - arg2.x), (arg1.y - arg2.y));
}
template <typename T>
point<T> operator-(const point<T>& arg1, const T& arg2) {
kgeTestPrint("called operator - with type");
return point<T>((arg1.x - arg2), (arg1.y - arg2));
}
template <typename T>
point<T> operator*(const point<T>& arg1, const point<T>& arg2) {
kgeTestPrint("called operator *");
return point<T>((arg1.x * arg2.x), (arg1.y * arg2.y));
}
template <typename T>
point<T> operator*(const point<T>& arg1, const T& arg2) {
kgeTestPrint("called operator + with type");
return point<T>((arg1.x * arg2), (arg1.y * arg2));
}
template <typename T>
point<T> operator/(const point<T>& arg1, const point<T>& arg2) {
kgeTestPrint("called operator /");
return point<T>((arg1.x / arg2.x), (arg1.y / arg2.y));
}
template <typename T>
point<T> operator/(const point<T>& arg1, const T& arg2) {
kgeTestPrint("called operator / with type");
return point<T>((arg1.x / arg2), (arg1.y / arg2));
}
template <typename T>
bool operator==(const point<T>& arg1, const point<T>& arg2) {
kgeTestPrint("called operator ==");
if constexpr (std::is_floating_point_v<T>) {
T a = arg1.x - arg2.x;
T b = arg1.y - arg2.y;
return ((std::abs(a) < 0.001) && (std::abs(b) < 0.001));
}
return (arg1.x == arg2.x && arg1.y == arg2.y);
}
template <typename T>
bool operator!=(const point<T>& arg1, const point<T>& arg2) {
kgeTestPrint("called operator !=");
if constexpr (std::is_floating_point_v<T>) {
T a = arg1.x - arg2.x;
T b = arg1.y - arg2.y;
return ((std::abs(a) > 0.001) || (std::abs(b) > 0.001));
}
return (arg1.x != arg2.x || arg1.y != arg2.y);
}
template <typename T>
bool operator>(const point<T>& arg1, const point<T>& arg2) {
kgeTestPrint("called operator >");
return (arg1.x > arg2.x && arg1.y > arg2.y);
}
template <typename T>
bool operator<(const point<T>& arg1, const point<T>& arg2) {
kgeTestPrint("called operator <");
return (arg1.x < arg2.x && arg1.y < arg2.y);
}
template <typename T>
bool operator>=(const point<T>& arg1, const point<T>& arg2) {
kgeTestPrint("called operator >=");
return (arg1.x >= arg2.x && arg1.y >= arg2.y);
}
template <typename T>
bool operator<=(const point<T>& arg1, const point<T>& arg2) {
kgeTestPrint("called operator <=");
return (arg1.x <= arg2.x && arg1.y <= arg2.y);
}
template <typename T>
class line {
static_assert(std::is_floating_point<T>::value, "must be floating point type");
public:
line<T>() { kgeTestPrint("called line constructor no arguments"); }
line<T>(point<T> aA, point<T> aB) : A(aA), B(aB) { kgeTestPrint("called line constructor with arguments"); }
line<T>(const line<T>& arg1) = default;
line<T>& operator=(const line<T>& arg1) = default;
line<T>(line&& other) noexcept = default;
line<T>& operator=(line<T>&& other) noexcept = default;
~line<T>() = default;
T length() const {
kgeTestPrint("called line length");
point<T> a = A - B;
return (std::hypot(a.x, a.y));
}
bool intersect(const line<T>& arg1) {
kgeTestPrint("called line intersect");
point<T> w = this->A - arg1.A;
point<T> r = arg1.B - arg1.A;
point<T> s = this->B - this->A;
T wxr = ((w.x * r.y) - (w.y * r.x));
T wxs = ((w.x * s.y) - (w.y * s.x));
T rxs = ((r.x * s.y) - (r.y * s.x));
if (rxs < 0.0001 && rxs > -0.0001) {
return false;
}
T u = wxr / rxs;
T t = wxs / rxs;
if (t <= 1.0 && t >= 0.0 && u <= 1.0 && u >= 0.0) {
point<T> temp = s * u;
recentIntersection = this->A + temp;
return true;
}
return false;
}
point<T> A{0, 0};
point<T> B{0, 0};
point<T> recentIntersection{0, 0};
};
template <typename T>
line<T> operator+(const line<T>& arg1, const line<T>& arg2) {
kgeTestPrint("called line operator +");
point<T> temp = arg1.B + arg2.A;
temp = temp - arg2.B;
return line<T>(arg1.A, temp);
}
} // namespace kge
#endif
|
kiyoMatsui/kiyoswebgame
|
server/app/assets/emscripten/kgeMainLoop.h
|
/*-------------------------------*\
Copyright 2021 <NAME>
KiyosGameEngine v1.1
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
\*-------------------------------*/
#ifndef KGE_MAINLOOP_H
#define KGE_MAINLOOP_H
#ifdef __EMSCRIPTEN__
#include <emscripten.h>
#endif
#include <chrono>
#include <functional>
#include <memory>
#include <vector>
namespace kge {
void emscriptenTick(void* arg);
class abstractState {
public:
virtual ~abstractState() = default;
virtual void render(double dt) = 0;
virtual void update(double dt) = 0;
virtual void processEvents() = 0;
};
class mainLoop {
public:
explicit mainLoop(const std::size_t stackSizeReserve = 5) { stateStack.reserve(stackSizeReserve); }
mainLoop(const mainLoop& other) = delete;
mainLoop& operator=(const mainLoop& other) = delete;
mainLoop(mainLoop&& other) noexcept = delete;
mainLoop& operator=(mainLoop&& other) noexcept = delete;
~mainLoop() = default;
friend void emscriptenTick(void* argVoid);
template <typename pushedState, typename... Elements>
void pushState(Elements... args);
void popState() {
changeStatePtr = std::make_unique<std::function<void()>>([=] { mainLoop::popStack(); });
}
void popPopState() {
changeStatePtr = std::make_unique<std::function<void()>>([=] { mainLoop::popPopStack(); });
}
template <typename pushedState, typename... Elements>
void switchState(Elements... args);
abstractState* peekState() const { return stateStack.back().get(); }
abstractState* peekUnderState() const { return stateStack.rbegin()[1].get(); }
void run() {
start = std::chrono::steady_clock::now();
if (changeStatePtr) {
(*changeStatePtr)();
changeStatePtr = nullptr;
}
#ifdef __EMSCRIPTEN__
emscripten_set_main_loop_arg(emscriptenTick, this, -1, 1);
#else
while (!stateStack.empty()) {
tick();
}
#endif
}
void tick() {
auto elapsedTime = std::chrono::steady_clock::now() - start;
start = std::chrono::steady_clock::now();
double dt_double = std::chrono::duration<double>(elapsedTime).count();
stateStack.back()->processEvents();
stateStack.back()->update(dt_double);
stateStack.back()->render(dt_double);
if (changeStatePtr) {
(*changeStatePtr)();
changeStatePtr = nullptr;
}
}
private:
template <typename pushedState, typename... Elements>
void pushToStack(Elements... args);
void popStack() { stateStack.pop_back(); }
void popPopStack() {
stateStack.pop_back();
stateStack.pop_back();
}
template <typename pushedState, typename... Elements>
void popAndPushStack(Elements... args);
std::vector<std::unique_ptr<abstractState>> stateStack;
std::unique_ptr<std::function<void()>> changeStatePtr{nullptr};
std::chrono::time_point<std::chrono::steady_clock> start;
};
#ifdef __EMSCRIPTEN__
void emscriptenTick(void* argVoid) {
mainLoop* arg = static_cast<mainLoop* const>(argVoid);
auto elapsedTime = std::chrono::steady_clock::now() - arg->start;
arg->start = std::chrono::steady_clock::now();
double dt_double = std::chrono::duration<double>(elapsedTime).count();
arg->stateStack.back()->processEvents();
arg->stateStack.back()->update(dt_double);
arg->stateStack.back()->render(dt_double);
if (arg->changeStatePtr) {
(*(arg->changeStatePtr))();
arg->changeStatePtr = nullptr;
}
if (arg->stateStack.empty()) emscripten_cancel_main_loop();
}
#endif
template <typename pushedState, typename... Elements>
void mainLoop::pushState(Elements... args) {
static_assert(std::is_base_of<abstractState, pushedState>::value, "pushedState must be derived from abstractState");
changeStatePtr =
std::make_unique<std::function<void()>>([=] { mainLoop::pushToStack<pushedState, Elements...>(args...); });
}
template <typename pushedState, typename... Elements>
void mainLoop::pushToStack(Elements... args) {
static_assert(std::is_base_of<abstractState, pushedState>::value, "pushedState must be derived from abstractState");
stateStack.push_back(std::make_unique<pushedState>(args...));
}
template <typename pushedState, typename... Elements>
void mainLoop::switchState(Elements... args) {
static_assert(std::is_base_of<abstractState, pushedState>::value, "pushedState must be derived from abstractState");
changeStatePtr =
std::make_unique<std::function<void()>>([=] { mainLoop::popAndPushStack<pushedState, Elements...>(args...); });
}
template <typename pushedState, typename... Elements>
void mainLoop::popAndPushStack(Elements... args) {
static_assert(std::is_base_of<abstractState, pushedState>::value, "pushedState must be derived from abstractState");
mainLoop::popStack();
mainLoop::pushToStack<pushedState, Elements...>(args...);
}
} // namespace kge
#endif
|
MyHomeLibrary/FB2ePub
|
FFPlugin/js-ctype_connector/Fb2ePubConverter.h
|
<filename>FFPlugin/js-ctype_connector/Fb2ePubConverter.h
#pragma once
class CFb2ePubConverter
{
public:
CFb2ePubConverter(void);
virtual ~CFb2ePubConverter(void);
bool Convert(LPCWSTR inputPath,LPCWSTR outputPath);
};
|
MyHomeLibrary/FB2ePub
|
FFPlugin/js-ctype_connector/Fb2EpubConverterPaths.h
|
#pragma once
class CFb2EpubConverterPaths
{
public:
CFb2EpubConverterPaths(void);
virtual ~CFb2EpubConverterPaths(void);
bool GetPathsCount(UINT32& uiPathsCount);
bool GetPath(UINT32 uiPath,LPWSTR strPath, UINT32& uiPathLength);
bool GetPathName(UINT32 uiPath,LPWSTR strPathName, UINT32& uiPathLength);
protected:
/* additional members */
void Init();
LPTSTR DetectINILocation();
void ReadTargets(LPTSTR strINILocation);
void ReleaseTargets();
typedef struct
{
LPTSTR path;
LPTSTR name;
}target;
target* m_pTargetsArray;
UINT32 m_uiTargetsCount;
};
|
MyHomeLibrary/FB2ePub
|
FFPlugin/js-ctype_connector/js-ctype_connector.h
|
// The following ifdef block is the standard way of creating macros which make exporting
// from a DLL simpler. All files within this DLL are compiled with the JSCTYPE_CONNECTOR_EXPORTS
// symbol defined on the command line. This symbol should not be defined on any project
// that uses this DLL. This way any other project whose source files include this file see
// JSCTYPE_CONNECTOR_API functions as being imported from a DLL, whereas this DLL sees symbols
// defined with this macro as being exported.
#ifdef JSCTYPE_CONNECTOR_EXPORTS
#define JSCTYPE_CONNECTOR_API __declspec(dllexport)
#else
#define JSCTYPE_CONNECTOR_API __declspec(dllimport)
#endif
EXTERN_C
{
// Path related functions
bool JSCTYPE_CONNECTOR_API CNTR_GetPathsCount(UINT32& uiPathCount);
bool JSCTYPE_CONNECTOR_API CNTR_GetPath(UINT32 uiPath,LPWSTR strPath, UINT32& uiPathLength);
bool JSCTYPE_CONNECTOR_API CNTR_GetPathName(UINT32 uiPath,LPWSTR strPathName, UINT32& uiPathLength);
// Converter unctions
bool JSCTYPE_CONNECTOR_API CNTR_Convert(LPCWSTR inputPath,LPCWSTR outputPath);
}
|
Medigram/DBSignupViewController
|
DBSignup/RootViewController.h
|
//
// RootViewController.h
// DBSignup
//
// Created by <NAME> on 7/4/11.
// Copyright 2011 03081340121. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface RootViewController : UITableViewController {
}
@end
|
Medigram/DBSignupViewController
|
DBSignup/DBSignupViewController.h
|
//
// DBSignupViewController.h
// DBSignup
//
// Created by <NAME> on 7/4/11.
// Copyright 2011 03081340121. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface DBSignupViewController : UIViewController <UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate, UIActionSheetDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate> {
UITextField *nameTextField_;
UITextField *lastNameTextField_;
UITextField *emailTextField_;
UITextField *passwordTextField_;
UITextField *birthdayTextField_;
UITextField *genderTextField_;
UITextField *phoneTextField_;
UIButton *photoButton_;
UITextView *termsTextView_;
UILabel *emailLabel_;
UILabel *passwordLabel_;
UILabel *birthdayLabel_;
UILabel *genderLabel_;
UILabel *phoneLabel_;
UIToolbar *keyboardToolbar_;
UIPickerView *genderPickerView_;
UIDatePicker *birthdayDatePicker_;
NSDate *birthday_;
NSString *gender_;
UIImage *photo_;
}
@property(nonatomic, retain) IBOutlet UITextField *nameTextField;
@property(nonatomic, retain) IBOutlet UITextField *lastNameTextField;
@property(nonatomic, retain) IBOutlet UITextField *emailTextField;
@property(nonatomic, retain) IBOutlet UITextField *passwordTextField;
@property(nonatomic, retain) IBOutlet UITextField *birthdayTextField;
@property(nonatomic, retain) IBOutlet UITextField *genderTextField;
@property(nonatomic, retain) IBOutlet UITextField *phoneTextField;
@property(nonatomic, retain) IBOutlet UIButton *photoButton;
@property(nonatomic, retain) IBOutlet UITextView *termsTextView;
@property(nonatomic, retain) IBOutlet UILabel *emailLabel;
@property(nonatomic, retain) IBOutlet UILabel *passwordLabel;
@property(nonatomic, retain) IBOutlet UILabel *birthdayLabel;
@property(nonatomic, retain) IBOutlet UILabel *genderLabel;
@property(nonatomic, retain) IBOutlet UILabel *phoneLabel;
@property(nonatomic, retain) UIToolbar *keyboardToolbar;
@property(nonatomic, retain) UIPickerView *genderPickerView;
@property(nonatomic, retain) UIDatePicker *birthdayDatePicker;
@property(nonatomic, retain) NSDate *birthday;
@property(nonatomic, retain) NSString *gender;
@property(nonatomic, retain) UIImage *photo;
- (IBAction)choosePhoto:(id)sender;
- (void)resignKeyboard:(id)sender;
- (void)previousField:(id)sender;
- (void)nextField:(id)sender;
- (id)getFirstResponder;
- (void)animateView:(NSUInteger)tag;
- (void)checkBarButton:(NSUInteger)tag;
- (void)checkSpecialFields:(NSUInteger)tag;
- (void)setBirthdayData;
- (void)setGenderData;
- (void)birthdayDatePickerChanged:(id)sender;
- (void)signup:(id)sender;
- (void)resetLabelsColors;
+ (UIColor *)labelNormalColor;
+ (UIColor *)labelSelectedColor;
@end
|
Medigram/DBSignupViewController
|
DBSignup/DBSignupAppDelegate.h
|
<filename>DBSignup/DBSignupAppDelegate.h
//
// DBSignupAppDelegate.h
// DBSignup
//
// Created by <NAME> on 7/4/11.
// Copyright 2011 03081340121. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface DBSignupAppDelegate : NSObject <UIApplicationDelegate> {
}
@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet UINavigationController *navigationController;
@end
|
Harlem-Launch-Alliance/Catalyst-2
|
main/settings.h
|
<filename>main/settings.h
/*****************************************************************************
* This file is for any settings or constants that may be manually adjusted
*
****************************************************************************/
#ifndef SETTINGS_H
#define SETTINGS_H
//tick times (microseconds)
const unsigned int TICK_TIME_ONPAD = 10000;
const unsigned int TICK_TIME_ASCENDING = 10000;
const unsigned int TICK_TIME_DESCENDING = 50000;
const unsigned int TICK_TIME_POST_FLIGHT = 1000000;
const unsigned int RING_QUEUE_LENGTH = 3000;//each 100 elements is 1 seconds of data at 100hz
#endif
|
Harlem-Launch-Alliance/Catalyst-2
|
main/attitude.h
|
/*****************************************************************************
* This file is for all math used to determine attitude
*
****************************************************************************/
//angles are in radians
//rates are magnitudes of rad/s
//assuming roll == 0, pitchRate will be equivalent to y, and yawRate will be equivalent to x
#include <Ewma.h> //https://github.com/jonnieZG/EWMA
//returns calculated pitchRate or yawRate
double getRate(double roll, double parallel, double perpendicular){//if getting rateX, parallel should be x
return parallel * cos(roll) + perpendicular * sin(roll);
}
Directional calibrateGyro(Directional gyro, bool hasLaunched){//returns gyro offsets
static Ewma xFilter(.002);
static Ewma yFilter(.002);
static Ewma zFilter(.002);
static Directional lastSave;//0-5 second old data
static Directional oldSave;//5-10 second old data
static int counter = 0;
if(hasLaunched){//once launch occurs we lock in the offsets (and return early to skip the math)
//in order to offset the delay between launch and launch detection, we use the data from 5-10 seconds prior
return oldSave;
}
Directional current;
current.x = xFilter.filter(gyro.x);
current.y = yFilter.filter(gyro.y);
current.z = zFilter.filter(gyro.z);
counter = (counter + 1) % 500;
//every 500 ticks (5 seconds), we save the last state and transfer the previous state to the go queue
if(counter == 0){
oldSave = lastSave;
lastSave = current;
}
return oldSave;
}
Directional getRealGyro(Directional gyro, Directional offsets){
Directional realGyro;
realGyro.x = gyro.x - offsets.x;
realGyro.y = gyro.y - offsets.y;
realGyro.z = gyro.z - offsets.z;
return realGyro;
}
/**************************************************************************************
In order to minimize error, we should assume that attitude is 0,0,0 at launch. However,
we don't actually know exactly when launch occurs. We can assume with almost 100%
certianty that launch is detected less than 5 seconds after it has actually occured, so
as a substitute, we can start recording attitude changes 5 seconds before detected
launch. In order to achieve this, we can record changes in 5 second increments (chunks)
prior to launch. Once launch is detected we will 'lock in' those chunks and continue
recording changes forever.
**************************************************************************************/
Directional getAttitude(Directional gyro, bool hasLaunched){//only calibrated gyro data should go in here
const int hz = 100; //number of readings per second
static Directional oldChanges; //5-10 seconds ago
static Directional lastChanges; //0-5 seconds ago
static int counter = 0;
Directional currentAttitude;
counter = (counter + 1) % 500;
lastChanges.z += gyro.z/hz;
currentAttitude.z = oldChanges.z + lastChanges.z; //z must be set first so we can calculate x and y
lastChanges.x += getRate(currentAttitude.z/* -gyro.z/2 */, gyro.x, gyro.y)/hz; //TODO: test whether or not -gyro.z/2 makes a difference
lastChanges.y += getRate(currentAttitude.z/* -gyro.z/2 */, gyro.y, gyro.x)/hz;
currentAttitude.x = oldChanges.x + lastChanges.x;
currentAttitude.y = oldChanges.y + lastChanges.y;
if(counter == 0 && !hasLaunched){//every 5 seconds we dump all data that's more than 5 seconds old (prior to launch)
oldChanges = lastChanges;
lastChanges.x = 0;
lastChanges.y = 0;
lastChanges.z = 0;
}
return currentAttitude;
}
|
Harlem-Launch-Alliance/Catalyst-2
|
main/ringQueue.h
|
<filename>main/ringQueue.h
/*****************************************************************************
* This file is for the RingQueue class and definitions
*
****************************************************************************/
#include "settings.h"
#ifndef RINGQUEUE_H
#define RINGQUEUE_H
template<typename T>
class RingQueue{
public:
RingQueue();
void enqueue(T data);
T peek();
void dequeue();
bool isEmpty();
private:
unsigned int head;
unsigned int length;
T dataArray[RING_QUEUE_LENGTH];
};
template<typename T>
RingQueue<T>::RingQueue(){//each new queue is initialized with 0 data
head = 0;
length = 0;
}
template<typename T>
bool RingQueue<T>::isEmpty(){
return length == 0;//if length is 0 it's empty otherwise it isn't
}
template<typename T>
void RingQueue<T>::enqueue(T data){
if(length >= RING_QUEUE_LENGTH) //if the array is full just ignore
return;
int nextLocation = (head + length) % RING_QUEUE_LENGTH;
/*we use modulus to wrap around EX: [6, 7, 8, 9, NULL, NULL, NULL, 0, 1, 2, 3, 4, 5]
in this case the "head" is 7, and the length is 10. (7 + 10) mod 13 == 4,
so 4 is the next available location for data*/
dataArray[nextLocation] = data;
length++;
}
template<typename T>
T RingQueue<T>::peek(){//unintended behaviour if called when queue is empty
return dataArray[head];
}
template<typename T>
void RingQueue<T>::dequeue(){
if(length == 0)
return;
length--;
head++;
}
#endif
|
Harlem-Launch-Alliance/Catalyst-2
|
main/bmp_altimeter.h
|
<reponame>Harlem-Launch-Alliance/Catalyst-2
/*****************************************************************************
* This file is for all barometric altimeter queries
*
****************************************************************************/
#define BMP_CS 10
#define SEALEVELPRESSURE_HPA (1013.25)//To be replaced
Adafruit_BMP3XX bmp; //initialize sensor
bmpReading getBMP()
{
bmpReading sample;
if (!bmp.performReading()) {
Serial1.println("Failed to perform BMP388 reading.");
return sample;
}
//sample.temp = bmp.temperature; // Temperature in Celcius
//sample.pressure = bmp.pressure / 100.0; // Pressure in hPa
sample.altitude = bmp.readAltitude(SEALEVELPRESSURE_HPA)/* - altOffset*/; // Approximate altitude in meters
sample.time = micros();
return sample;
}
void setupBMP()
{
Serial1.print("Setting up altimeter... ");
delay(3000);
if (!bmp.begin_SPI(BMP_CS)) { // hardware I2C mode, can pass in address & alt Wire
Serial1.println("could not find a valid BMP388 sensor, check wiring!");
return;
}
// Set up oversampling and filter initialization
bmp.setTemperatureOversampling(BMP3_NO_OVERSAMPLING);
bmp.setPressureOversampling(BMP3_OVERSAMPLING_2X);
bmp.setIIRFilterCoeff(BMP3_IIR_FILTER_COEFF_3);
bmp.setOutputDataRate(BMP3_ODR_100_HZ);
for(int i = 0; i < 100; i++) // runs BMP 100 times to flush out data
getBMP();
bmpReading sample = getBMP();
if(sample.altitude != 0)
Serial1.println("successful");
else
Serial1.println("failed, check wiring or pin settings");
}
|
Harlem-Launch-Alliance/Catalyst-2
|
main/data.h
|
<reponame>Harlem-Launch-Alliance/Catalyst-2
/*****************************************************************************
* This file is for saving and transmitting data
* currently using an SD card and Xbee respectively
****************************************************************************/
#include "ringQueue.h"
const int chipSelect = BUILTIN_SDCARD;
char filename[50];
RingQueue<imuReading> imuQueue;
RingQueue<bmpReading> bmpQueue;
RingQueue<gpsReading> gpsQueue;
void transmitData(double altitude, gpsReading gps, char phase)
{
Serial1.print(phase); //0: ONPAD, 1: ASCENDING, 2: DESCENDING, 3: POST_FLIGHT
Serial1.print(" ");
Serial1.print(gps.latitude, 4);
Serial1.print(" ");
Serial1.print(gps.longitude, 4);
Serial1.print(" ");
Serial1.println(altitude,1);
}
void setupSD(String date){
if (!SD.begin(chipSelect)){
Serial1.println("MicroSD card: failed or not present");
return;
}
else
Serial1.println("MicroSD card: successful");
String filestart = "Catalyst2-";
filestart.concat(date).concat(".csv");
filestart.toCharArray(filename, 50);
File dataFile = SD.open(filename, FILE_WRITE);
if (dataFile) {
dataFile.println("Time(ms),Altitude(m),Latitude,Longitude,GyroX,GyroY,GyroZ,AccelX,AccelY,AccelZ,AttitudeX,AttitudeY,AttitudeZ,state");
dataFile.close();
}
else {
Serial1.println("MicroSD card: error opening file");
}
}
void recordData(imuReading sample, bool prelaunch){
imuQueue.enqueue(sample);
if(prelaunch){
while(!imuQueue.isEmpty() && imuQueue.peek().time < millis() - 2000){
imuQueue.dequeue();
}
}
}
void recordData(bmpReading sample, bool prelaunch){
bmpQueue.enqueue(sample);
if(prelaunch){
while(!bmpQueue.isEmpty() && bmpQueue.peek().time < millis() - 2000){
bmpQueue.dequeue();
}
}
}
void recordData(gpsReading sample, bool prelaunch){
gpsQueue.enqueue(sample);
if(prelaunch){
while(!gpsQueue.isEmpty() && gpsQueue.peek().time < millis() - 2000){
gpsQueue.dequeue();
}
}
}
void backupToSD(){
File dataFile = SD.open(filename, FILE_WRITE);
if(!dataFile){
Serial1.println("error opening datalog");
return;
}
while(!imuQueue.isEmpty()){
double altitude = 0;
double latitude = 0;
double longitude = 0;
imuReading imuSample = imuQueue.peek();
imuQueue.dequeue();
if(!bmpQueue.isEmpty()){
bmpReading bmpSample = bmpQueue.peek();
if(bmpSample.time < imuSample.time){
altitude = bmpSample.altitude;
bmpQueue.dequeue();
}
}
if(!gpsQueue.isEmpty()){
gpsReading gpsSample = gpsQueue.peek();
if(gpsSample.time < imuSample.time){
longitude = gpsSample.longitude;
latitude = gpsSample.latitude;
gpsQueue.dequeue();
}
}
dataFile.print(imuSample.time); dataFile.print(',');
if(altitude != 0)
dataFile.print(altitude, 1);
dataFile.print(',');
if(latitude != 0)
dataFile.print(latitude, 4);
dataFile.print(',');
if(longitude != 0)
dataFile.print(longitude, 4);
dataFile.print(',');
dataFile.print(imuSample.gyro.x); dataFile.print(',');
dataFile.print(imuSample.gyro.y); dataFile.print(',');
dataFile.print(imuSample.gyro.z); dataFile.print(',');
dataFile.print(imuSample.accel.x); dataFile.print(',');
dataFile.print(imuSample.accel.y); dataFile.print(',');
dataFile.print(imuSample.accel.z); dataFile.print(',');
dataFile.print(imuSample.attitude.x); dataFile.print(',');
dataFile.print(imuSample.attitude.y); dataFile.print(',');
dataFile.print(imuSample.attitude.z); dataFile.println(',');
//TODO add state
}
while(!bmpQueue.isEmpty()){
double latitude = 0;
double longitude = 0;
bmpReading bmpSample = bmpQueue.peek();
bmpQueue.dequeue();
if(!gpsQueue.isEmpty()){
gpsReading gpsSample = gpsQueue.peek();
if(gpsSample.time < bmpSample.time){
longitude = gpsSample.longitude;
latitude = gpsSample.latitude;
gpsQueue.dequeue();
}
}
dataFile.print(bmpSample.time); dataFile.print(',');
dataFile.print(bmpSample.altitude, 1); dataFile.print(',');
if(latitude != 0)
dataFile.print(latitude, 4);
dataFile.print(',');
if(longitude != 0)
dataFile.print(longitude, 4);
dataFile.print(',');
dataFile.print(',');
dataFile.print(',');
dataFile.print(',');
dataFile.print(',');
dataFile.print(',');
dataFile.print(',');
dataFile.print(',');
dataFile.print(',');
dataFile.println(',');
}
dataFile.close();
}
|
Harlem-Launch-Alliance/Catalyst-2
|
main/utils.h
|
/*****************************************************************************
* This file is for declaring utilities to be used in multiple other places
*
****************************************************************************/
#include <math.h>
#include "settings.h"
class Directional //any data that has an x,y and z attribute
{
public:
double x,y,z;
Directional(double a, double b, double c){
x = a;
y = b;
z = c;
}
Directional(){
x = 0;
y = 0;
z = 0;
}
};
struct bmpReading //all data from an altimeter reading
{
double altitude;
unsigned long time;
};
struct imuReading //all data from an IMU reading (accelerometer and gyroscope)
{
Directional accel;
Directional gyro;
Directional attitude;
unsigned long time;
};
struct gpsReading //only the data we need for now
{
double latitude, longitude;
unsigned long time;
};
double toDeg(double angle){
return ((angle) *(180/PI));
}
double toRad(double angle){
return ((angle) * (PI/180));
}
enum flightPhase {ONPAD, ASCENDING, DESCENDING, POST_FLIGHT};
int getTickTime(flightPhase phase){//map flight phases to tick times
switch(phase){
case ONPAD:
return TICK_TIME_ONPAD;
case ASCENDING:
return TICK_TIME_ASCENDING;
case DESCENDING:
return TICK_TIME_DESCENDING;
case POST_FLIGHT:
return TICK_TIME_POST_FLIGHT;
}
return TICK_TIME_POST_FLIGHT;
}
|
Harlem-Launch-Alliance/Catalyst-2
|
main/apogee.h
|
<filename>main/apogee.h
/*****************************************************************************
* apogee detection and helper functions
*
****************************************************************************/
#include <Ewma.h> //https://github.com/jonnieZG/EWMA
//this function should only be called once per loop iteration
bool detectLaunch(Directional accel){//accel in Gs
const double gForceToLaunch = 3; //if acceleration exceeds this number the rocket will assume it has been launched
static bool hasLaunched = false;
static Ewma accelFilter(.05);
if(hasLaunched) //no need to do any math once launch has been detected the first time
return true;
//group all accels into one
//accel may need calibration. If that is the case, it should happen externally and only calibrated data should enter this function
double totalAccel = sqrt(pow(accel.x, 2) + pow(accel.y, 2) + pow(accel.z, 2)); //this should be 1G when stationary
double filteredAccel = accelFilter.filter(totalAccel);
if(filteredAccel > gForceToLaunch)
hasLaunched = true;
return hasLaunched;
}
bool isAccelerating(Directional accel){
return sqrt(pow(accel.x, 2) + pow(accel.y, 2) + pow(accel.z, 2)) < 2;
}
bool detectApogee(Directional accel, double altitude, bool hasLaunched){ //accel in Gs
static bool apogeeReached = false; //this is initialized as false, but once it flips to true it should remain true until the arduino is reset
static Ewma altFilter(.05); //this will contain a filtered altitude (less prone to noise)
static int counter = 0;
static double lastAlt = altitude;
counter = (counter + 1) % 5; //this will count from 0 to 4, overflowing back to 0
double currentAlt = altFilter.filter(altitude);
if(apogeeReached)//if apogee was already detected earlier we don't need to do any more math
return true;
if(counter == 0){
//everytime counter overflows we check for apogee (4hz at the moment, this should be a constant or tied to a constant)
if(hasLaunched && currentAlt < lastAlt && !isAccelerating(accel))
apogeeReached = true;
lastAlt = currentAlt;
}
return apogeeReached;
}
|
Harlem-Launch-Alliance/Catalyst-2
|
main/gy521_imu.h
|
/*****************************************************************************
* This file is for all imu queries
* Calculations such as attitude determination should go in a separate file
****************************************************************************/
#include <Wire.h> //library allows communication with I2C / TWI devices
#include <math.h> //library includes mathematical functions
const int MPU=0b1101000; //I2C address of the MPU-6050
const double tcal = -1600; //Temperature correction
imuReading getIMU()
{
imuReading imuSample;
imuSample.time = micros(); //current timestamp
int16_t AcX, AcY, AcZ, GyX, GyY, GyZ, Tmp;
Wire.beginTransmission(MPU);
Wire.write(0x3B);
Wire.endTransmission(false);
Wire.requestFrom(MPU,14,1);
//read accelerometer data
AcX=Wire.read()<<8|Wire.read();
AcY=Wire.read()<<8|Wire.read();
AcZ=Wire.read()<<8|Wire.read();
//read temp
Tmp=Wire.read()<<8|Wire.read();
//read gyroscope data
GyX=Wire.read()<<8|Wire.read();
GyY=Wire.read()<<8|Wire.read();
GyZ=Wire.read()<<8|Wire.read();
imuSample.accel.x = AcX/16384.0;
imuSample.accel.y = AcY/16384.0;
imuSample.accel.z = AcZ/16384.0;
imuSample.gyro.x = toRad(GyX/131.0);
imuSample.gyro.y = toRad(GyY/131.0);
imuSample.gyro.z = toRad(GyZ/131.0);
//imuSample.temp = Tmp/340 + 36.53;
return imuSample; //return gyro and accel data
}
void setupIMU(){
Serial1.print("Setting up IMU... ");
delay(3000);
Wire.beginTransmission(0b1101000); //This is the I2C address of the MPU (b1101000/b1101001 for AC0 low/high datasheet sec. 9.2)
Wire.write(0x6B); //Accessing the register 6B - Power Management (Sec. 4.28)
Wire.write(0b00000000); //Setting SLEEP register to 0. (Required; see Note on p. 9)
Wire.endTransmission();
Wire.beginTransmission(0b1101000); //I2C address of the MPU
Wire.write(0x1B); //Accessing the register 1B - Gyroscope Configuration (Sec. 4.4)
Wire.write(0b00010000); //Setting the gyro to full scale +/- 1000deg./s
Wire.endTransmission();
Wire.beginTransmission(0b1101000); //I2C address of the MPU
Wire.write(0x1C); //Accessing the register 1C - Acccelerometer Configuration (Sec. 4.5)
Wire.write(0b00010000); //Setting the accel to +/- 8g
Wire.endTransmission();
imuReading sample = getIMU();
if(sample.accel.x != 0)
Serial1.println("successful");
else
Serial1.println("failed, check wiring or pin settings");
}
|
Harlem-Launch-Alliance/Catalyst-2
|
main/gps.h
|
<reponame>Harlem-Launch-Alliance/Catalyst-2
// Test code for Ultimate GPS Using Hardware Serial.
// Need to remove the GPS.lastNMEA() and see if it still works, still get compilation error
#include <Adafruit_GPS.h>
// what's the name of the hardware serial port?
#define GPSSerial Serial2
// Connect to the GPS on the hardware port
Adafruit_GPS GPS(&GPSSerial);
String setupGPS()
{
Serial1.println("Setting up GPS...");
// 9600 NMEA is the default baud rate for Adafruit MTK GPS's- some use 4800
GPS.begin(9600);
// uncomment this line to turn on RMC (recommended minimum) and GGA (fix data) including altitude
GPS.sendCommand(PMTK_SET_NMEA_OUTPUT_RMCGGA);
GPS.sendCommand(PMTK_SET_NMEA_UPDATE_1HZ); // 1 Hz update rate
delay(1000);
// Ask for firmware version
GPSSerial.println(PMTK_Q_RELEASE);
unsigned int timer = 0;
while(!GPS.fix){
char c = GPS.read();
// if you want to debug, this is a good time to do it!
if (GPS.newNMEAreceived()) {
// a tricky thing here is if we print the NMEA sentence, or data
// we end up not listening and catching other sentences!
// so be very wary if using OUTPUT_ALLDATA and trying to print out data
c = GPS.lastNMEA(); //this gives an error but doesn't seem to be an issue
if (!GPS.parse(GPS.lastNMEA())){} // this also sets the newNMEAreceived() flag to false
}
if(timer < millis()){
timer = millis() + 10000;
Serial1.println("Acquiring GPS signal...");
}
}
Serial1.println("GPS signal acquired");
uint8_t hour = GPS.hour;
uint8_t minute = GPS.minute;
uint8_t year = GPS.year;
uint8_t month = GPS.month;
uint8_t day = GPS.day;
uint8_t yearPrefix = 20;
String date = String(yearPrefix).concat(year).concat('-').concat(month).concat('-').concat(day).concat("--").concat(hour).concat('-').concat(minute);
Serial1.print("Date: ");
Serial1.println(date);
return date;
}
gpsReading getGPS()
{
int t1 = micros();
while(micros() - t1 < 5000){
char c = GPS.read();
// if you want to debug, this is a good time to do it!
if (GPS.newNMEAreceived()) {
// a tricky thing here is if we print the NMEA sentence, or data
// we end up not listening and catching other sentences!
// so be very wary if using OUTPUT_ALLDATA and trying to print out data
c = GPS.lastNMEA(); //this gives an error but doesn't seem to be an issue
if (!GPS.parse(GPS.lastNMEA())){} // this also sets the newNMEAreceived() flag to false
}
}
gpsReading sample;
if(GPS.fix){
sample.latitude = GPS.latitudeDegrees;
sample.longitude = GPS.longitudeDegrees;
}
sample.time = millis();
return sample;
}
|
Funto/OpenGL-Timestamp-Profiler
|
tgaloader.h
|
<reponame>Funto/OpenGL-Timestamp-Profiler
// tgaloader.h
// Version 2.1
#ifndef TGA_LOADER_H
#define TGA_LOADER_H
// Configuration:
#define TGA_LOADER_INCLUDE_GLEW // Define this if the project uses GLEW,
// for including GL/glew.h before GL/gl.h
//#define TGA_OPENGL_SUPPORT
//#define TGA_USE_LOG_H // Define this to use log/Log.h for logging (logError(), etc)
#define TGA_USE_LOG_IOSTREAM // Define this to use std::cout/std::cerr for logging
// ---------------------------------------------------------------------
#ifdef TGA_LOADER_INCLUDE_GLEW
#include <GL/glew.h>
#endif
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <string>
#ifdef TGA_OPENGL_SUPPORT
#ifdef WIN32
#include <windows.h>
#endif
#include <GL/gl.h>
#include <GL/glu.h>
#endif // defined TGA_OPENGL_SUPPORT
enum TGAErrorCode
{
TGA_OK,
TGA_FILE_NOT_FOUND,
TGA_UNSUPPORTED_TYPE,
TGA_NOT_ENOUGH_MEMORY
};
#ifdef TGA_OPENGL_SUPPORT
enum TGAFiltering
{
TGA_NO_FILTER,
TGA_LINEAR,
TGA_BILINEAR,
TGA_TRILINEAR
#ifdef GL_TEXTURE_MAX_ANISOTROPY_EXT
,TGA_ANISOTROPIC
#endif
};
#endif
class TGALoader
{
private:
unsigned char* data;
bool loaded;
unsigned int width, height;
unsigned int bpp; // Bytes Per Pixel : 0, 3 or 4
public:
TGALoader();
TGALoader(const TGALoader& ref);
TGALoader(const char* path, TGAErrorCode* error=NULL);
virtual ~TGALoader();
TGAErrorCode loadFile(const char* path);
TGAErrorCode loadFromData(unsigned char *data);
TGALoader& operator=(const TGALoader& ref);
// Convert an error to an explicit string
static std::string errorToString(TGAErrorCode error);
#ifdef TGA_OPENGL_SUPPORT
GLuint sendToOpenGL(TGAFiltering filtering=TGA_NO_FILTER);
void sendToOpenGLWithID(GLuint ID, TGAFiltering filtering=TGA_NO_FILTER);
TGAErrorCode loadOpenGLTexture(const char* path, GLuint* pID=NULL,
TGAFiltering filtering=TGA_NO_FILTER);
TGAErrorCode loadOpenGLTextureWithID(const char* path, GLuint ID,
TGAFiltering filtering=TGA_NO_FILTER);
TGAErrorCode loadOpenGLTextureFromData(unsigned char *data, GLuint* pID=NULL,
TGAFiltering filtering=TGA_NO_FILTER);
TGAErrorCode loadOpenGLTextureFromDataWithID(unsigned char *data, GLuint ID,
TGAFiltering filtering=TGA_NO_FILTER);
#endif
void free();
inline unsigned char* getData() {return data;}
inline bool isLoaded() {return loaded;}
inline unsigned int getHeight() {return height;}
inline unsigned int getWidth() {return width;}
inline unsigned int getBpp() {return bpp;}
};
// Overloading << for printing error codes using iostream
inline std::ostream& operator<<(std::ostream& os, const TGAErrorCode& error)
{
return os << TGALoader::errorToString(error);
}
#endif // !defined TGA_LOADER_H
|
Funto/OpenGL-Timestamp-Profiler
|
thread.h
|
// thread.h
// Thin interface over the Windows Threads API and pthread.
#ifndef __THREAD_H__
#define __THREAD_H__
// Basic types: ThreadHandle, ThreadId, Mutex, Event
#ifdef WIN32
#include <windows.h>
typedef HANDLE ThreadHandle;
typedef DWORD ThreadId;
typedef CRITICAL_SECTION Mutex;
typedef HANDLE Event;
#else
#include <pthread.h>
typedef pthread_t ThreadHandle;
typedef pthread_t ThreadId;
typedef pthread_mutex_t Mutex;
struct Event
{
pthread_mutex_t mutex;
pthread_cond_t cond;
bool triggered;
};
#endif
typedef void* (*ThreadProc)(void* arg);
ThreadHandle threadCreate(ThreadProc proc, void* arg);
ThreadId threadGetCurrentId();
void threadJoin(ThreadHandle id);
void mutexCreate(Mutex* mutex);
void mutexDestroy(Mutex* mutex);
void mutexLock(Mutex* mutex);
void mutexUnlock(Mutex* mutex);
void eventCreate(Event* event);
void eventDestroy(Event* event);
void eventTrigger(Event* event);
void eventReset(Event* event);
void eventWait(Event* event);
#endif // __THREAD_H__
|
Funto/OpenGL-Timestamp-Profiler
|
utils.h
|
<gh_stars>1-10
// utils.h
#ifndef UTILS_H
#define UTILS_H
#include <GL/glew.h>
void msleep(int ms);
const char* loadText(const char* filename);
bool loadShaders(const char* vert_filename, const char* frag_filename,
GLuint& id_vert, GLuint& id_frag, GLuint& id_prog);
bool checkGLError();
template <class T>
T clamp(T val, T min_val, T max_val)
{
if(val < min_val)
val = min_val;
if(val > max_val)
val = max_val;
return val;
}
inline void incrementCycle(int* pval, size_t array_size)
{
int val = *pval;
val++;
if(val >= (int)(array_size))
val = 0;
*pval = val;
}
inline void decrementCycle(int* pval, size_t array_size)
{
int val = *pval;
val--;
if(val < 0)
val = (int)(array_size-1);
*pval = val;
}
struct Rect
{
float x, y;
float w, h;
Rect() : x(0.0f), y(0.0f), w(0.0f), h(0.0f) {}
Rect(float x, float y, float w, float h) : x(x), y(y), w(w), h(h) {}
void set(float _x, float _y, float _w, float _h)
{
x = _x; y = _y; w = _w; h = _h;
}
bool isPointInside(float _x, float _y) const
{
return (_x >= x && _x < x+w &&
_y >= y && _y < y+h );
}
};
struct Color
{
unsigned char r;
unsigned char g;
unsigned char b;
Color() : r(0xFF), g(0xFF), b(0xFF) {}
Color(unsigned char r, unsigned char g, unsigned char b) : r(r), g(g), b(b) {}
void set(unsigned char _r, unsigned char _g, unsigned char _b)
{
r = _r; g = _g; b = _b;
}
void set(const Color& color)
{
r = color.r;
g = color.g;
b = color.b;
}
};
extern const Color COLOR_WHITE;
extern const Color COLOR_BLACK;
extern const Color COLOR_GRAY;
extern const Color COLOR_LIGHT_GRAY;
extern const Color COLOR_RED;
extern const Color COLOR_GREEN;
extern const Color COLOR_BLUE;
extern const Color COLOR_DARK_RED;
extern const Color COLOR_DARK_GREEN;
extern const Color COLOR_DARK_BLUE;
extern const Color COLOR_LIGHT_RED;
extern const Color COLOR_LIGHT_GREEN;
extern const Color COLOR_LIGHT_BLUE;
extern const Color COLOR_CYAN;
extern const Color COLOR_MAGENTA;
extern const Color COLOR_YELLOW;
#endif // UTILS_H
|
Funto/OpenGL-Timestamp-Profiler
|
hp_timer.h
|
// hp_timer.h
#ifndef __HP_TIMER_H__
#define __HP_TIMER_H__
#include <stdint.h>
void initTimer();
void shutTimer();
#ifdef _WIN32 // Windows 32 bits and 64 bits: use QueryPerformanceCounter()
#include <windows.h>
extern int64_t __freq;
extern int64_t __time_at_init;
inline uint64_t getTimeNs()
{
LARGE_INTEGER now;
QueryPerformanceCounter(&now);
static const uint64_t factor = 1000000000;
return (uint64_t)( factor*(now.QuadPart-__time_at_init) / __freq );
}
#elif defined(__MACH__) // OSX: use clock_get_time
#include <sys/time.h>
#include <mach/mach.h>
#include <mach/clock.h>
extern clock_serv_t __clock_rt;
extern unsigned int __tv_sec_at_init;
inline uint64_t getTimeNs()
{
// http://pastebin.com/89qJQsCw
// http://www.opensource.apple.com/source/xnu/xnu-344/osfmk/i386/rtclock.c
// http://opensource.apple.com/source/xnu/xnu-1456.1.26/osfmk/man/host_get_clock_service.html -> HIGHRES_CLOCK
mach_timespec_t mts;
clock_get_time(__clock_rt, &mts);
uint64_t time_sec = (uint64_t)(mts.tv_sec - __tv_sec_at_init);
uint64_t time_ns = time_sec * (uint64_t)(1000000000);
time_ns += (uint64_t)(mts.tv_nsec);
return time_ns;
}
#elif defined(__linux__) // Linux: use clock_gettime()
#include <time.h>
extern time_t __tv_sec_at_init;
inline uint64_t getTimeNs()
{
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
uint64_t time_sec = (uint64_t)(ts.tv_sec - __tv_sec_at_init);
uint64_t time_ns = time_sec * (uint64_t)(1000000000);
time_ns += (uint64_t)(ts.tv_nsec);
return time_ns;
}
#else // Fallback for other UN*X systems: use gettimeofday()
// http://stackoverflow.com/questions/275004/c-timer-function-to-provide-time-in-nano-seconds
extern time_t __tv_sec_at_init;
#include <sys/time.h>
inline uint64_t getTimeNs()
{
struct timeval tv;
gettimeofday(&tv, NULL);
uint64_t time_sec = (uint64_t)(ts.tv_sec - __tv_sec_at_init);
uint64_t time_ns = time_sec * (uint64_t)(1000000000);
time_ns += (uint64_t)(ts.tv_nsec);
return time_ns;
}
#endif
#endif // __HP_TIMER_H__
|
Funto/OpenGL-Timestamp-Profiler
|
camera.h
|
<gh_stars>1-10
// Camera.h
#ifndef CAMERA_H
#define CAMERA_H
#include "math_utils.h"
struct Camera
{
float view_matrix[16];
float proj_matrix[16];
void setPerspective(float fovy_degrees, float aspect_ratio,
float znear, float zfar)
{
matrixPerspective(proj_matrix, fovy_degrees, aspect_ratio, 1.0f, 100.0f);
}
void lookAt(const float eye[3],
const float target[3],
const float up[3])
{
matrixLookAt(view_matrix, eye, target, up);
}
};
#endif // CAMERA_H
|
Funto/OpenGL-Timestamp-Profiler
|
profiler.h
|
// profiler.h
#ifndef PROFILER_H
#define PROFILER_H
#include <GL/glew.h>
#include <string.h>
#include <assert.h>
#include <stdint.h>
#include "hole_array.h"
#include "thread.h"
#include "utils.h"
#define ENABLE_PROFILER // comment this to disable the profiler
#define INVALID_TIME ((uint64_t)(-1))
#define INVALID_QUERY ((GLuint)0)
#ifndef ENABLE_PROFILER
#define PROFILER_INIT(win_w, win_h, mouse_x, mouse_y)
#define PROFILER_SHUT()
#define PROFILER_ON_MOUSE_POS(mouse_x, mouse_y)
#define PROFILER_ON_RESIZE(win_w, win_h)
#define PROFILER_ON_LEFT_CLICK()
#define PROFILER_PUSH_CPU_MARKER(name, color)
#define PROFILER_POP_CPU_MARKER()
#define PROFILER_PUSH_GPU_MARKER(name, color)
#define PROFILER_POP_GPU_MARKER()
#define PROFILER_DRAW()
#define PROFILER_SYNC_FRAME()
#else
class Profiler;
extern Profiler profiler;
#define PROFILER_INIT(win_w, win_h, mouse_x, mouse_y) profiler.init(win_w, win_h, mouse_x, mouse_y)
#define PROFILER_SHUT() profiler.shut()
#define PROFILER_ON_MOUSE_POS(mouse_x, mouse_y) profiler.onMousePos(mouse_x, mouse_y)
#define PROFILER_ON_RESIZE(win_w, win_h) profiler.onResize(win_w, win_h)
#define PROFILER_ON_LEFT_CLICK() profiler.onLeftClick()
#define PROFILER_PUSH_CPU_MARKER(name, color) profiler.pushCpuMarker(name, color)
#define PROFILER_POP_CPU_MARKER() profiler.popCpuMarker()
#define PROFILER_PUSH_GPU_MARKER(name, color) profiler.pushGpuMarker(name, color)
#define PROFILER_POP_GPU_MARKER() profiler.popGpuMarker()
#define PROFILER_DRAW() profiler.draw()
#define PROFILER_SYNC_FRAME() profiler.synchronizeFrame()
class Profiler
{
private:
static const size_t NB_RECORDED_FRAMES = 3;
static const size_t NB_MAX_CPU_MARKERS_PER_FRAME = 100;
static const size_t NB_MARKERS_PER_CPU_THREAD = NB_RECORDED_FRAMES * NB_MAX_CPU_MARKERS_PER_FRAME;
static const size_t NB_MAX_GPU_MARKERS_PER_FRAME = 10;
static const size_t NB_GPU_MARKERS = NB_RECORDED_FRAMES * NB_MAX_GPU_MARKERS_PER_FRAME;
static const size_t NB_MAX_CPU_THREADS = 32;
//static const size_t NB_FRAMES_BEFORE_KICK_CPU_THREAD = 4; // TODO: remove threads that are not used anymore
static const size_t MARKER_NAME_MAX_LENGTH = 32;
struct Marker
{
uint64_t start; // Times of start and end, in nanoseconds,
uint64_t end; // relatively to the time of last synchronization
size_t layer; // Number of markers pushed at the time this one is pushed
int frame; // Frame at which the marker was started
char name[MARKER_NAME_MAX_LENGTH];
Color color;
Marker() : start(INVALID_TIME), end(INVALID_TIME), frame(-1) {} // unused by default
};
// --- Device-specific markers ---
typedef Marker CpuMarker;
struct GpuMarker : public Marker
{
GLuint id_query_start;
GLuint id_query_end;
GpuMarker() : Marker(), id_query_start(INVALID_QUERY), id_query_end(INVALID_QUERY) {}
};
// Markers for a CPU thread
struct CpuThreadInfo
{
ThreadId thread_id;
CpuMarker markers[NB_MARKERS_PER_CPU_THREAD];
int cur_read_id; // Index of the last pushed marker in the previous frame
int cur_write_id; // Index of the next cell we will write to
int next_read_id; // draw() writes next_read_id, synchronizeFrame() copies cur_read_id <- next_read_id
// This deferring is needed for handling freeze/unfreeze.
size_t nb_pushed_markers;
void init(ThreadId id) {cur_read_id=cur_write_id=next_read_id=0; thread_id = id; nb_pushed_markers=0;}
};
// Markers for the GPU
struct GpuThreadInfo
{
GpuMarker markers[NB_GPU_MARKERS];
int cur_read_id; // Index of the last pushed marker in the previous frame
int cur_write_id; // Index of the next cell we will write to
int next_read_id; // draw() writes next_read_id, synchronizeFrame() copies cur_read_id <- next_read_id.
// This deferring is needed for handling freeze/unfreeze.
size_t nb_pushed_markers;
void init() {cur_read_id=cur_write_id=next_read_id=0; nb_pushed_markers=0;}
};
typedef HoleArray<CpuThreadInfo, NB_MAX_CPU_THREADS> CpuThreadInfoList;
CpuThreadInfoList m_cpu_thread_infos;
Mutex m_cpu_mutex;
GpuThreadInfo m_gpu_thread_info;
volatile int m_cur_frame; // Global frame counter
// Frame time information
struct FrameInfo
{
int frame;
uint64_t time_sync_start;
uint64_t time_sync_end;
};
FrameInfo m_frame_info[NB_RECORDED_FRAMES];
// Handling freeze/unfreeze by clicking on the displayed profiler
enum FreezeState
{
UNFROZEN,
WAITING_FOR_FREEZE,
FROZEN,
WAITING_FOR_UNFREEZE,
};
FreezeState m_freeze_state;
bool m_visible;
// Handling interaction with the mouse
int m_mouse_x, m_mouse_y;
int m_win_w, m_win_h;
Rect m_back_rect; // Background
public:
Profiler() {}
virtual ~Profiler() {}
void init(int win_w, int win_h, int mouse_x, int mouse_y);
void shut();
void pushCpuMarker(const char* name, const Color& color);
void popCpuMarker();
void pushGpuMarker(const char* name, const Color& color);
void popGpuMarker();
void synchronizeFrame();
void draw();
void setVisible(bool visible) {m_visible=visible;}
bool isVisible() const {return m_visible;}
bool isFrozen() const {return m_freeze_state == FROZEN || m_freeze_state == WAITING_FOR_UNFREEZE;}
// Input handling
void onMousePos(int x, int y) {m_mouse_x=x; m_mouse_y=y;}
void onLeftClick();
void onResize(int w, int h) {m_win_w=w; m_win_h=h;}
protected:
// Get the CpuThreadInfo corresponding to the calling thread
CpuThreadInfo& getOrAddCpuThreadInfo();
void drawBackground();
void drawHoveredMarkersText(const int *read_indices, const FrameInfo* frame_info);
void updateBackgroundRect();
};
#endif // defined(ENABLE_PROFILER)
#endif // PROFILER_H
|
Funto/OpenGL-Timestamp-Profiler
|
drawer2D.h
|
// drawer2D.h
#ifndef __DRAWER2D_H__
#define __DRAWER2D_H__
#include <GL/glew.h>
#include "utils.h"
// Simple class to draw strings in a [-1;1]x[-1;1] coordinates system
class Drawer2D
{
private:
GLuint m_id_vbo; // General-purpose VBO
// Unicolor shader
GLuint m_id_vert_color;
GLuint m_id_frag_color;
GLuint m_id_prog_color;
GLint m_id_uniform_color;
// Font
GLuint m_id_tex_font;
GLint m_id_uniform_tex_font;
GLint m_id_uniform_font_color;
GLuint m_id_vert_font;
GLuint m_id_frag_font;
GLuint m_id_prog_font;
// Window size
int m_win_w;
int m_win_h;
public:
Drawer2D() {}
bool init(int win_w, int win_h);
void shut();
void onResize(int win_w, int win_h) {m_win_w = win_w; m_win_h = win_h; }
void drawRect(const Rect& rect, const Color& color=COLOR_WHITE, float alpha=1.0f);
void drawString(const char* str, float x, float y, const Color& color=COLOR_WHITE);
private:
bool initFont();
};
extern Drawer2D drawer2D;
#endif // __DRAWER2D_H__
|
Funto/OpenGL-Timestamp-Profiler
|
math_utils.h
|
<reponame>Funto/OpenGL-Timestamp-Profiler
// math_utils.h
#ifndef MAT_UTILS_H
#define MAT_UTILS_H
#include <math.h>
#ifndef PI_FLOAT
#define PI_FLOAT 3.14159265358979323846f
#endif
// -----------------------------------------
// Vectors
inline float vecLength(const float v[3])
{
return sqrtf(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);
}
inline float vecNormalize(float v[3])
{
float len = vecLength(v);
v[0] /= len;
v[1] /= len;
v[2] /= len;
return len;
}
inline void vecCross(float result[3], const float a[3], const float b[3])
{
result[0] = a[1] * b[2] - a[2] * b[1];
result[1] = - (a[0] * b[2] - a[2] * b[0]);
result[2] = a[0] * b[1] - a[1] * b[0];
}
inline float vecDot(const float a[3], const float b[3])
{
return a[0]*b[0] + a[1]*b[1] + a[2]*b[2];
}
// -----------------------------------------
// Matrices are stored following the OpenGL convention:
// float mat[16]; -> "column-major order": mat[0..3] is the first column, etc.
//
// 0 4 8 12
// 1 5 9 13
// 2 6 10 14
// 3 7 11 15
//
// mat[i] -> ith column
#define MATRIX_IDENTITY { 1.0f, 0.0f, 0.0f, 0.0f, \
0.0f, 1.0f, 0.0f, 0.0f, \
0.0f, 0.0f, 1.0f, 0.0f, \
0.0f, 0.0f, 0.0f, 1.0f }
// result = a*b
void matrixMult(float result[16], const float* a, const float* b);
// Translation
void matrixTranslate(float result[16], const float v[3]);
// Rotation
void matrixRotateX(float result[16], float theta_degrees);
void matrixRotateY(float result[16], float theta_degrees);
void matrixRotateZ(float result[16], float theta_degrees);
// Projection matrix handling - see http://www.opengl.org/wiki/GluPerspective_code
void matrixPerspective(float result[16], float fovy_degrees, float aspect_ratio,
float znear, float zfar);
// glFrustum() equivalent
void matrixFrustum( float result[16],
float left, float right,
float bottom, float top,
float znear, float zfar);
// gluLookAt() equivalent
void matrixLookAt( float result[16],
const float eye[3],
const float target[3],
const float up[3]);
#endif // MAT_UTILS_H
|
Funto/OpenGL-Timestamp-Profiler
|
scene.h
|
<reponame>Funto/OpenGL-Timestamp-Profiler
// scene.h
#ifndef SCENE_H
#define SCENE_H
#include "camera.h"
#include "grid.h"
#include "thread.h"
#include "utils.h"
class Scene
{
private:
static const int NB_GRIDS_X = 2;
static const int NB_GRIDS_Y = 2;
static const int NB_THREADS = NB_GRIDS_X * NB_GRIDS_Y;
Camera m_camera;
// Multithread update
struct ThreadData
{
Scene* p_scene;
Grid grid;
ThreadHandle thread_handle;
Event update_event;
Event main_event;
int index;
};
Color m_colors[NB_THREADS];
bool m_multithread;
ThreadData m_thread_data[NB_THREADS];
volatile bool m_shut;
volatile double m_elapsed_time;
volatile double m_update_time;
public:
bool init();
void shut();
void update(double elapsed, double t);
void draw(int win_w, int win_h);
void setMultithreaded(bool multithread) {m_multithread = multithread;}
bool isMultithreaded() const {return m_multithread;}
private:
void threadUpdate(ThreadData* data);
static void* threadUpdateWrapper(void* user_data);
};
#endif // SCENE_H
|
Funto/OpenGL-Timestamp-Profiler
|
grid.h
|
<reponame>Funto/OpenGL-Timestamp-Profiler
// grid.h
#ifndef GRID_H
#define GRID_H
#include <GL/glew.h>
#include "camera.h"
#include "utils.h"
class Grid
{
private:
static const int GRID_WIDTH;
static const int GRID_HEIGHT;
static const int GRID_NB_INDICES;
static const float GRID_WORLD_SIZE;
static const float GRID_Y_FLOOR;
static const float GRID_Y_DISTO;
struct Vertex
{
GLfloat pos[3];
GLfloat col[3];
};
Vertex* m_grid_vertices;
GLuint* m_grid_indices;
float* m_grid_temp_buffer;
float m_time_offset;
// Shader IDs
GLuint m_id_vert_grid;
GLuint m_id_frag_grid;
GLuint m_id_prog_grid;
// Shader uniforms
GLint m_id_uniform_mvp;
// VBO/IBO
GLuint m_id_ibo_grid;
GLuint m_id_vbo_grid;
Camera m_camera;
Color m_color;
public:
Grid();
bool init(float time_offset, const Color& color);
void shut();
const Color& getColor() const {return m_color;}
const Camera& getCamera() const {return m_camera;}
Camera& getCamera() {return m_camera;}
void update(double elapsed, double t);
void draw(const float mvp_matrix[16]);
};
#endif // GRID_H
|
boolgom/EntryArduino
|
EntryArduino/EntryArduino/sckt.h
|
#ifndef UNICODE
#define UNICODE 1
#endif
// link with Ws2_32.lib
#pragma comment(lib,"Ws2_32.lib")
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdio.h>
#include <stdlib.h>// for _wtoi
|
chamara-dev/ThreeSixtyPlayer
|
Example/ThreeSixtyPlayer/TSPViewController.h
|
//
// TSPViewController.h
// ThreeSixtyPlayer
//
// Created by <NAME> on 09/01/2016.
// Copyright (c) 2016 <NAME>. All rights reserved.
//
@import UIKit;
@interface TSPViewController : UIViewController
@end
|
chamara-dev/ThreeSixtyPlayer
|
Example/ThreeSixtyPlayer/TSPAppDelegate.h
|
<filename>Example/ThreeSixtyPlayer/TSPAppDelegate.h
//
// TSPAppDelegate.h
// ThreeSixtyPlayer
//
// Created by <NAME> on 09/01/2016.
// Copyright (c) 2016 <NAME>. All rights reserved.
//
@import UIKit;
@interface TSPAppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end
|
quim0/eWFA-GPU
|
utils/sequence_reader.h
|
<reponame>quim0/eWFA-GPU
/*
* Copyright (c) 2020 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef UTILS_H
#define UTILS_H
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "logger.h"
#include "wavefront_structures.h"
// TODO: Method to free the sequences memory
class SequenceReader {
public:
char *seq_file;
// Average length of the sequences
size_t seq_len;
// Maximum sequence length if error rate is 100%
size_t max_seq_len;
size_t max_seq_len_unpacked;
// Number of sequences pairs in the "sequences" list and in the file
size_t num_alignments;
FILE *fp;
// Chunk of memory where all the sequences will be stored, the final
// nullbytes doesn't need to be stored as we already know the sequence
// length.
SEQ_TYPE* sequences_mem_unpacked;
size_t batch_size;
int num_sequences_read;
// Array that will be filled with the sequences from the file
WF_element* sequences;
SequenceReader (char* seq_file, size_t seq_len, size_t num_alignments,
size_t batch_size) : \
seq_file(seq_file), \
seq_len(seq_len), \
num_alignments(num_alignments), \
batch_size(batch_size), \
sequences(NULL), \
sequences_mem_unpacked(NULL), \
fp(NULL), \
num_sequences_read(0) {
// Allow 100% of error rate, make sure it is 32 bits aligned
this->max_seq_len_unpacked = seq_len * 2;
this->max_seq_len_unpacked += (4 - (this->max_seq_len_unpacked % 4));
// Max sequence length in bytes, encoding the sequence elements in 2
// bits (4 elements per byte)
this->max_seq_len = this->max_seq_len_unpacked/4;
// Make sure sequences are 32 bits aligned
this->max_seq_len += (4 - (this->max_seq_len % 4));
DEBUG("SequenceReader created:\n"
" File: %s\n"
" Sequence avg length: %zu\n"
" Number of sequences: %zu\n"
" Max seq len unpacked: %zu\n"
" Max seq len packed: %zu",
seq_file, seq_len, num_alignments, this->max_seq_len_unpacked,
this->max_seq_len);
}
bool skip_n_alignments (int n);
bool read_n_alignments (int n);
bool read_batch_alignments () {
return read_n_alignments(this->batch_size);
}
bool read_file () {
return read_n_alignments(this->num_alignments);
}
SEQ_TYPE* get_sequences_buffer_unpacked ();
size_t sequences_buffer_size () const;
void destroy ();
private:
void initialize_sequences ();
size_t sequence_buffer_size ();
void create_sequences_buffer_unpacked ();
SEQ_TYPE* create_sequence_buffer ();
void pack_sequence (uint8_t* curr_seq_ptr, SEQ_TYPE* seq_buf, size_t buf_len);
};
#endif // Header guard UTLS_H
|
quim0/eWFA-GPU
|
src/wavefront_structures.h
|
/*
* Copyright (c) 2020 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef WAVEFRONT_STRUCTURES_H
#define WAVEFRONT_STRUCTURES_H
#include <stdint.h>
#define SEQ_TYPE char
typedef int32_t ewf_offset_t;
typedef signed char edit_cigar_t;
#define OFFSETS_TOTAL_ELEMENTS(max_d) (max_d * max_d + (max_d * 2 + 1))
#define WF_ELEMENTS(d) (d * 2 + 1)
#define OFFSETS_PTR(offsets_mem, d) (offsets_mem + ((d)*(d)) + (d))
struct edit_wavefronts_t {
uint32_t d;
ewf_offset_t* offsets;
};
#define PATTERN_PTR(idx, base_ptr, max_seq_len) ((SEQ_TYPE*)(base_ptr + idx * 2 * max_seq_len))
#define TEXT_PTR(idx, base_ptr, max_seq_len) ((SEQ_TYPE*)(base_ptr + (idx * 2 + 1) * max_seq_len))
struct WF_element {
// With the idx, the max_seq_length and the sequences memory base pointer,
// is possible to calculate the text/pattern address
int alignment_idx;
size_t tlen;
size_t plen;
};
// 128 bit backtrace data, max_distance = 64
struct WF_backtrace_t {
uint64_t words[2];
};
struct WF_backtrace_result_t {
uint64_t words[2];
int distance;
};
#define CURR_MAX_DISTANCE 64
// Backtrace operations encoded in 2 bits, using more than 2 bits will break the
// code, so don't do it.
typedef enum {
OP_NOOP, // Use for delimitation
OP_DEL = 3, // k + 1, "going up" 0b11
OP_SUB = 2, // k 0b10
OP_INS = 1 // k - 1, "going down" 0b01
} WF_backtrace_op_t;
// Encode sequence elements in two bytes, this is the bits [2:1] of the ASCII
// representation of the bases. So it can be obtained by doing (base & 6) >> 1
// Note that 6 is 0b110
// WARNING: Before changing this make sure is coherent with the translation
// array in generate_ascii_sequence(...) (wavefront.cuh)
typedef enum {
A, // 00
C, // 01
T, // 10
G // 11
} WF_sequence_element_t;
#endif
|
quim0/eWFA-GPU
|
utils/logger.h
|
<gh_stars>1-10
/*
* Copyright (c) 2020 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef LOGGER_H
#define LOGGER_H
#ifdef DEBUG_MODE
#define DEBUG(...) {\
char tmp[512];\
snprintf(tmp, 512, __VA_ARGS__); \
fprintf(stderr, "DEBUG: %s (%s:%d)\n", tmp, __FILE__, __LINE__); \
}
#define DEBUG_GREEN(...) {\
char tmp[512];\
snprintf(tmp, 512, __VA_ARGS__); \
fprintf(stderr, "\u001b[32mDEBUG: %s (%s:%d)\u001b[0m\n", tmp, __FILE__, __LINE__); \
}
#define DEBUG_RED(...) {\
char tmp[512];\
snprintf(tmp, 512, __VA_ARGS__); \
fprintf(stderr, "\u001b[31mDEBUG: %s (%s:%d)\u001b[0m\n", tmp, __FILE__, __LINE__); \
}
#define CLOCK_INIT() struct timespec now, tmstart; double seconds;
#define CLOCK_START() clock_gettime(CLOCK_REALTIME, &tmstart);
#define CLOCK_STOP(text) \
clock_gettime(CLOCK_REALTIME, &now); \
seconds = (double)((now.tv_sec+now.tv_nsec*1e-9) - (double)(tmstart.tv_sec+tmstart.tv_nsec*1e-9)); \
DEBUG("%s Wall time %fs", text, seconds);
#else
#define DEBUG(fmt, ...)
#define CLOCK_INIT()
#define CLOCK_START()
#define CLOCK_STOP(text)
#endif
#define CLOCK_INIT_NO_DEBUG() struct timespec now, tmstart; double seconds;
#define CLOCK_START_NO_DEBUG() clock_gettime(CLOCK_REALTIME, &tmstart);
#define CLOCK_STOP_NO_DEBUG(text) \
clock_gettime(CLOCK_REALTIME, &now); \
seconds = (double)((now.tv_sec+now.tv_nsec*1e-9) - (double)(tmstart.tv_sec+tmstart.tv_nsec*1e-9)); \
printf("%s Wall time %fs\n", text, seconds);
#define NOMEM_ERR_STR "Could not allocate memory.\n"
#define WF_ERROR(...) fprintf(stderr, __VA_ARGS__)
// TODO: Handle error before exiting? (free gpu memory?)
#define WF_FATAL(...) { \
WF_ERROR(__VA_ARGS__); fflush(stdout); fflush(stderr); exit(1); \
}
// https://developer.nvidia.com/blog/cuda-pro-tip-generate-custom-application-profile-timelines-nvtx/
#ifdef USE_NVTX
#include "nvToolsExt.h"
const uint32_t colors[] = { 0xff00ff00, 0xff0000ff, 0xffffff00, 0xffff00ff, 0xff00ffff, 0xffff0000, 0xffffffff };
const int num_colors = sizeof(colors)/sizeof(uint32_t);
#define PUSH_RANGE(name,cid) { \
int color_id = cid; \
color_id = color_id%num_colors;\
nvtxEventAttributes_t eventAttrib = {0}; \
eventAttrib.version = NVTX_VERSION; \
eventAttrib.size = NVTX_EVENT_ATTRIB_STRUCT_SIZE; \
eventAttrib.colorType = NVTX_COLOR_ARGB; \
eventAttrib.color = colors[color_id]; \
eventAttrib.messageType = NVTX_MESSAGE_TYPE_ASCII; \
eventAttrib.message.ascii = name; \
nvtxRangePushEx(&eventAttrib); \
}
#define POP_RANGE nvtxRangePop();
#else
#define PUSH_RANGE(name,cid)
#define POP_RANGE
#endif
#endif // Header guard
|
quim0/eWFA-GPU
|
utils/arg_handler.c
|
/*
* Copyright (c) 2021 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <stdio.h>
#include <stddef.h>
#include <string.h>
#include <stdlib.h>
#include "arg_handler.h"
// Check if current string arguent is in options, and return it. Return NULL if
// it's not found.
option_t* check_long_arg (const char* arg, const options_t options) {
for (int i=0; i<options.len; i++) {
if (!strcmp(options.options[i].long_arg, arg)) {
return &options.options[i];
}
}
return NULL;
}
// Check if current string arguent is in options, and return it. Return NULL if
// it's not found.
option_t* check_short_arg (const char* arg, const options_t options) {
for (int i=0; i<options.len; i++) {
if (options.options[i].short_arg == arg[0]) {
return &options.options[i];
}
}
return NULL;
}
bool parse_arg (char* const value, option_t* option) {
switch (option->type) {
case ARG_INT:
option->value.int_val = atoll(value);
break;
case ARG_STR:
option->value.str_val = value;
break;
case ARG_CHAR:
if (strlen(value) == 0) {
return false;
}
option->value.char_val = value[0];
break;
case ARG_FLOAT:
option->value.float_val = atof(value);
break;
case ARG_BOOL:
if (!strcmp(value, "false") || !strcmp(value, "0")) {
option->value.bool_val = false;
} else {
option->value.bool_val = true;
}
break;
default:
return false;
}
return true;
}
void clean_options (options_t* options) {
for (int i=0; i<options->len; i++) {
options->options[i].parsed = false;
}
}
bool parse_args (const int argc, char** argv, options_t options) {
clean_options(&options);
bool read_value = false;
option_t* curr_option = NULL;
for (int i=0; i<argc; i++) {
if (!read_value) {
int arg_len = strlen(argv[i]);
if (argv[i][0] == '-') {
if (arg_len >= 2 && (argv[i][1] == '-')) {
// Long form of the argument e.g. --arg
curr_option = check_long_arg(argv[i] + 2, options);
} else {
// Short form of the argument e.g. -a
curr_option = check_short_arg(argv[i] + 1, options);
}
if (curr_option != NULL) {
if (curr_option->type != ARG_NO_VALUE) {
// Read value the next iteration
read_value = true;
} else {
// For arguments without value associated, e.g --debug
curr_option->value.set = true;
curr_option->parsed = true;
}
}
}
} else {
bool success = parse_arg(argv[i], curr_option);
if (success) {
curr_option->parsed = true;
} else {
fprintf(stderr,
"Error parsing argument: %s.", curr_option->name);
return false;
}
read_value = false;
curr_option = NULL;
}
}
// Check if all required arguments have been parsed
for (int i=0; i<options.len; i++) {
option_t curr_option = options.options[i];
if (curr_option.required && !curr_option.parsed) {
return false;
}
}
return true;
}
void print_usage (const options_t options) {
fprintf(stderr, "Options:\n");
for (int i=0; i<options.len; i++) {
const option_t curr_option = options.options[i];
char* type_str;
switch (curr_option.type) {
case ARG_INT:
type_str = "int";
break;
case ARG_STR:
type_str = "string";
break;
case ARG_CHAR:
type_str = "char";
break;
case ARG_FLOAT:
type_str = "float";
break;
case ARG_BOOL:
type_str = "bool";
break;
}
if (curr_option.type == ARG_NO_VALUE) {
if (curr_option.required) {
fprintf(stderr, "\t-%c, --%-30s(required) %s: %s\n",
curr_option.short_arg, curr_option.long_arg,
curr_option.name, curr_option.description);
} else {
fprintf(stderr, "\t-%c, --%-30s%s: %s\n",
curr_option.short_arg, curr_option.long_arg,
curr_option.name, curr_option.description);
}
} else {
if (curr_option.required) {
fprintf(stderr, "\t-%c, --%-30s(%s, required) %s: %s\n",
curr_option.short_arg, curr_option.long_arg,
type_str, curr_option.name, curr_option.description);
} else {
fprintf(stderr, "\t-%c, --%-30s(%s) %s: %s\n",
curr_option.short_arg, curr_option.long_arg,
type_str, curr_option.name, curr_option.description);
}
}
}
}
|
quim0/eWFA-GPU
|
utils/arg_handler.h
|
<reponame>quim0/eWFA-GPU
/*
* Copyright (c) 2021 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef ARG_HANDLER_H
#define ARG_HANDLER_H
#include <stdbool.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef enum {
ARG_INT,
ARG_STR,
ARG_CHAR,
ARG_FLOAT,
ARG_BOOL,
ARG_NO_VALUE
} arg_type_t;
typedef union {
int64_t int_val;
char* str_val;
char char_val;
double float_val;
bool bool_val;
bool set;
} arg_value_t;
typedef struct {
const char* name;
const char* description;
char short_arg; // -a without the "-"
const char* long_arg; // --arg without the "--"
bool required;
bool parsed;
arg_type_t type;
arg_value_t value;
} option_t;
typedef struct {
option_t* options;
int len;
} options_t;
bool parse_args (const int argc, char** argv, options_t options);
void print_usage (const options_t options);
#ifdef __cplusplus
}
#endif // cplusplus
#endif // Header guard
|
obiwac/x-compositing-wm
|
src/cwm.h
|
// this file contains helpers for the compositing part of the window manager prototype
#include <wm.h>
#include <X11/extensions/Xcomposite.h>
// we need to use Xfixes because, for whatever reason, X (and even Xcomposite, which is even weirder) doesn't include a way to make windows transparent to events
#include <X11/extensions/Xfixes.h>
#include <X11/extensions/shape.h>
// we use GLEW to help us load most of the OpenGL functions we're using
// it is important that it goes before the 'glx.h' include
#include <GL/glew.h>
#include <GL/glx.h>
// standard library includes
#include <unistd.h>
#include <sys/time.h>
// defines and stuff for GLX
#define GLX_CONTEXT_MAJOR_VERSION_ARB 0x2091
#define GLX_CONTEXT_MINOR_VERSION_ARB 0x2092
typedef GLXContext (*glXCreateContextAttribsARB_t) (Display*, GLXFBConfig, GLXContext, Bool, const int*);
typedef void (*glXBindTexImageEXT_t) (Display*, GLXDrawable, int, const int*);
typedef void (*glXReleaseTexImageEXT_t) (Display*, GLXDrawable, int);
typedef void (*glXSwapIntervalEXT_t) (Display*, GLXDrawable, int);
// structures and types
typedef struct {
wm_t* wm;
int vsync;
struct timeval previous_time;
Window overlay_window;
Window output_window;
GLXContext glx_context;
int glx_config_count;
GLXFBConfig* glx_configs;
glXBindTexImageEXT_t glXBindTexImageEXT;
glXReleaseTexImageEXT_t glXReleaseTexImageEXT;
} cwm_t;
typedef struct {
GLXPixmap pixmap;
} cwm_window_internal_t;
// functions
void new_cwm(cwm_t* cwm, wm_t* wm) {
memset(cwm, 0, sizeof(*cwm));
cwm->wm = wm;
// make it so that our compositing window manager can be recognized as such by other processes
Window screen_owner = XCreateSimpleWindow(wm->display, wm->root_window, 0, 0, 1, 1, 0, 0, 0);
Xutf8SetWMProperties(wm->display, screen_owner, "xcompmgr", "xcompmgr", NULL, 0, NULL, NULL, NULL);
char name[] = "_NET_WM_CM_S##";
snprintf(name, sizeof(name), "_NET_WM_CM_S%d", cwm->wm->screen);
Atom atom = XInternAtom(wm->display, name, 0);
XSetSelectionOwner(wm->display, atom, screen_owner, 0);
// we want to enable manual redirection, because we want to track damage and flush updates ourselves
// if we were to pass 'CompositeRedirectAutomatic' instead, the server would handle all that internally
XCompositeRedirectSubwindows(wm->display, wm->root_window, CompositeRedirectManual);
// get the overlay window
// this window allows us to draw what we want on a layer between normal windows and the screensaver without interference
cwm->overlay_window = XCompositeGetOverlayWindow(wm->display, wm->root_window);
// explained in more detail in the comment before '#include <X11/extensions/Xfixes.h>'
// basically, make the overlay transparent to events and pass them on through to lower windows
XserverRegion region = XFixesCreateRegion(wm->display, NULL, 0);
XFixesSetWindowShapeRegion(wm->display, cwm->overlay_window, ShapeInput, 0, 0, region);
XFixesDestroyRegion(wm->display, region);
// create the output window
// this window is where the actual drawing is going to happen
/* const */ int default_visual_attributes[] = {
GLX_RGBA, GLX_DOUBLEBUFFER,
GLX_SAMPLE_BUFFERS, 1,
GLX_SAMPLES, 4,
GLX_RED_SIZE, 8,
GLX_GREEN_SIZE, 8,
GLX_BLUE_SIZE, 8,
GLX_ALPHA_SIZE, 8,
GLX_DEPTH_SIZE, 16, 0
};
XVisualInfo* default_visual = glXChooseVisual(wm->display, wm->screen, default_visual_attributes);
if (!default_visual) wm_error(wm, "Failed to get default GLX visual");
XSetWindowAttributes attributes = {
.colormap = XCreateColormap(wm->display, wm->root_window, default_visual->visual, AllocNone),
.border_pixel = 0,
};
cwm->output_window = XCreateWindow(
wm->display, wm->root_window, 0, 0, wm->width, wm->height, 0, default_visual->depth,
InputOutput, default_visual->visual, CWBorderPixel | CWColormap, &attributes);
XReparentWindow(wm->display, cwm->output_window, cwm->overlay_window, 0, 0);
XMapRaised(wm->display, cwm->output_window);
// get the GLX frame buffer configurations that match our specified attributes
// generally we'll just be using the first one ('glx_configs[0]')
const int config_attributes[] = {
GLX_BIND_TO_TEXTURE_RGBA_EXT, 1,
GLX_BIND_TO_TEXTURE_TARGETS_EXT, GLX_TEXTURE_2D_BIT_EXT,
GLX_RENDER_TYPE, GLX_RGBA_BIT,
GLX_DRAWABLE_TYPE, GLX_PIXMAP_BIT,
GLX_X_VISUAL_TYPE, GLX_TRUE_COLOR,
GLX_X_RENDERABLE, 1,
GLX_FRAMEBUFFER_SRGB_CAPABLE_EXT, (GLint) GLX_DONT_CARE,
GLX_BUFFER_SIZE, 32,
// GLX_SAMPLE_BUFFERS, 1,
// GLX_SAMPLES, 4,
GLX_DOUBLEBUFFER, 1,
GLX_RED_SIZE, 8,
GLX_GREEN_SIZE, 8,
GLX_BLUE_SIZE, 8,
GLX_ALPHA_SIZE, 8,
GLX_STENCIL_SIZE, 0,
GLX_DEPTH_SIZE, 16, 0
};
cwm->glx_configs = glXChooseFBConfig(wm->display, wm->screen, config_attributes, &cwm->glx_config_count);
if (!cwm->glx_configs) wm_error(wm, "Failed to get GLX frame buffer configurations");
// create our OpenGL context
// we must load the 'glXCreateContextAttribsARB' function ourselves
const int gl_version_attributes[] = { // we want OpenGL 3.3
GLX_CONTEXT_MAJOR_VERSION_ARB, 3,
GLX_CONTEXT_MINOR_VERSION_ARB, 3,
GLX_CONTEXT_FLAGS_ARB, GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB, 0
};
glXCreateContextAttribsARB_t glXCreateContextAttribsARB = (glXCreateContextAttribsARB_t) glXGetProcAddressARB((const GLubyte*) "glXCreateContextAttribsARB");
cwm->glx_context = glXCreateContextAttribsARB(wm->display, cwm->glx_configs[0], NULL, 1, gl_version_attributes);
if (!cwm->glx_context) wm_error(wm, "Failed to create OpenGL context");
// load the other two functions we need but don't have
cwm->glXBindTexImageEXT = (glXBindTexImageEXT_t) glXGetProcAddress((const GLubyte*) "glXBindTexImageEXT");
cwm->glXReleaseTexImageEXT = (glXReleaseTexImageEXT_t) glXGetProcAddress((const GLubyte*) "glXReleaseTexImageEXT");
// finally, make the context we just made the OpenGL context of this thread
glXMakeCurrent(wm->display, cwm->output_window, cwm->glx_context);
// initialize GLEW
// this will be needed for most modern OpenGL calls
glewExperimental = GL_TRUE;
if (glewInit() != GLEW_OK) wm_error(wm, "Failed to initialize GLEW");
// enable adaptive vsync (-1 for adaptive vsync, 1 for non-adaptive vsync, 0 for no vsync)
// this extension seems completely broken on NVIDIA
// glXSwapIntervalEXT_t glXSwapIntervalEXT = (glXSwapIntervalEXT_t) glXGetProcAddress((const GLubyte*) "glXSwapIntervalEXT");
// glXSwapIntervalEXT(wm->display, cwm->output_window, 0);
cwm->vsync = 1;
// blacklist the overlay and output windows for events
wm->event_blacklisted_windows = (Window*) realloc(wm->event_blacklisted_windows, (2 + wm->event_blacklisted_window_count) * sizeof(Window));
wm->event_blacklisted_windows[wm->event_blacklisted_window_count + 0] = cwm->overlay_window;
wm->event_blacklisted_windows[wm->event_blacklisted_window_count + 1] = cwm->output_window;
// wm->event_blacklisted_windows[wm->event_blacklisted_window_count + 2] = screen_owner;
wm->event_blacklisted_window_count += 2;
// setup the timing code (window managers don't seem to be able to vsync)
gettimeofday(&cwm->previous_time, 0);
}
uint64_t cwm_swap(cwm_t* cwm) {
glXSwapBuffers(cwm->wm->display, cwm->output_window);
// return the time in microseconds between this frame and the last
struct timeval current_time;
gettimeofday(¤t_time, 0);
int64_t delta = (current_time.tv_sec - cwm->previous_time.tv_sec) * 1000000 + current_time.tv_usec - cwm->previous_time.tv_usec;
cwm->previous_time = current_time;
return delta;
}
static cwm_window_internal_t* cwm_get_window_internal(cwm_t* cwm, wm_window_t* window) {
cwm_window_internal_t* window_internal = (cwm_window_internal_t*) window->internal;
if (!window_internal) {
window->internal = (void*) malloc(sizeof(cwm_window_internal_t));
memset(window->internal, 0, sizeof(cwm_window_internal_t));
}
return (cwm_window_internal_t*) window->internal;
}
// event handler functions
void cwm_create_event(cwm_t* cwm, unsigned window_index) {
wm_window_t* window = &cwm->wm->windows[window_index];
cwm_window_internal_t* window_internal = cwm_get_window_internal(cwm, window);
}
void cwm_modify_event(cwm_t* cwm, unsigned window_index) {
wm_window_t* window = &cwm->wm->windows[window_index];
cwm_window_internal_t* window_internal = cwm_get_window_internal(cwm, window);
// check to see if we already have a pixmap
// delete it if so since we're likely gonna need to update it
if (window_internal->pixmap) {
glXDestroyPixmap(cwm->wm->display, window_internal->pixmap);
window_internal->pixmap = 0;
}
}
void cwm_destroy_event(cwm_t* cwm, unsigned window_index) {
wm_window_t* window = &cwm->wm->windows[window_index];
cwm_window_internal_t* window_internal = cwm_get_window_internal(cwm, window);
free(window_internal);
}
// rendering functions
#define glXGetFBConfigAttribChecked(a, b, attr, c) \
if (glXGetFBConfigAttrib((a), (b), (attr), (c))) { \
fprintf(stderr, "WARNING Cannot get FBConfig attribute " #attr "\n"); \
}
void cwm_bind_window_texture(cwm_t* cwm, unsigned window_index) {
wm_window_t* window = &cwm->wm->windows[window_index];
cwm_window_internal_t* window_internal = cwm_get_window_internal(cwm, window);
if (!window->exists) return;
if (!window->visible) return;
// TODO 'XGrabServer'/'XUngrabServer' necessary?
// it seems to make things 10x faster for whatever reason
// which is actually good for recording using OBS with XSHM
if (!cwm->vsync) XGrabServer(cwm->wm->display);
// glXWaitX(); // same as 'XSync', but a tad more efficient
// update the window's pixmap
if (!window_internal->pixmap) {
XWindowAttributes attribs;
XGetWindowAttributes(cwm->wm->display, window->window, &attribs);
int format;
GLXFBConfig config;
for (int i = 0; i < cwm->glx_config_count; i++) {
config = cwm->glx_configs[i];
int has_alpha;
glXGetFBConfigAttribChecked(cwm->wm->display, config, GLX_BIND_TO_TEXTURE_RGBA_EXT, &has_alpha);
XVisualInfo* visual = glXGetVisualFromFBConfig(cwm->wm->display, config);
int visual_depth = visual->depth;
free(visual);
if (attribs.depth != visual_depth) {
continue;
}
// found the config we want, break
format = has_alpha ? GLX_TEXTURE_FORMAT_RGBA_EXT : GLX_TEXTURE_FORMAT_RGB_EXT;
break;
}
const int pixmap_attributes[] = {
GLX_TEXTURE_TARGET_EXT, GLX_TEXTURE_2D_EXT,
GLX_TEXTURE_FORMAT_EXT, format, 0 // GLX_TEXTURE_FORMAT_RGB_EXT
};
Pixmap x_pixmap = XCompositeNameWindowPixmap(cwm->wm->display, window->window);
window_internal->pixmap = glXCreatePixmap(cwm->wm->display, config, x_pixmap, pixmap_attributes);
XFreePixmap(cwm->wm->display, x_pixmap);
}
cwm->glXBindTexImageEXT(cwm->wm->display, window_internal->pixmap, GLX_FRONT_LEFT_EXT, NULL);
}
void cwm_unbind_window_texture(cwm_t* cwm, unsigned window_index) {
wm_window_t* window = &cwm->wm->windows[window_index];
cwm_window_internal_t* window_internal = cwm_get_window_internal(cwm, window);
cwm->glXReleaseTexImageEXT(cwm->wm->display, window_internal->pixmap, GLX_FRONT_LEFT_EXT);
if (!cwm->vsync) XUngrabServer(cwm->wm->display);
}
|
obiwac/x-compositing-wm
|
src/wm.h
|
<reponame>obiwac/x-compositing-wm
// this file contains helpers for the window manager
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/Xatom.h>
#include <X11/extensions/Xinerama.h>
#if !defined(DEBUGGING)
#define DEBUGGING 0
#endif
#define WM_NAME "Basic X compositing WM"
// structures and types
typedef void (*wm_keyboard_event_callback_t) (void*, unsigned window, unsigned press, unsigned modifiers, unsigned key);
typedef int (*wm_click_event_callback_t) (void*, unsigned window, unsigned press, unsigned modifiers, unsigned button, float x, float y);
typedef void (*wm_move_event_callback_t) (void*, unsigned window, unsigned modifiers, float x, float y);
typedef void (*wm_create_event_callback_t) (void*, unsigned window);
typedef void (*wm_modify_event_callback_t) (void*, unsigned window, int visible, float x, float y, float width, float height);
typedef void (*wm_destroy_event_callback_t) (void*, unsigned window);
typedef struct {
int exists;
Window window;
int visible;
int x, y;
int width, height;
// this is extra data that can be allocated by extensions such as a compositor
void* internal;
} wm_window_t;
typedef struct {
Display* display;
int screen;
Window root_window;
unsigned width;
unsigned height;
wm_window_t* windows;
int window_count;
// individual monitor information
int monitor_count;
XineramaScreenInfo* monitor_infos;
// atoms (used for communicating information about the window manager to other clients)
Atom client_list_atom;
// list of windows that are blacklisted for events
// this is mostly useful for non-application windows that the client doesn't care about
Window* event_blacklisted_windows;
int event_blacklisted_window_count;
// event callbacks
wm_keyboard_event_callback_t keyboard_event_callback;
wm_click_event_callback_t click_event_callback;
wm_move_event_callback_t move_event_callback;
wm_create_event_callback_t create_event_callback;
wm_modify_event_callback_t modify_event_callback;
wm_destroy_event_callback_t destroy_event_callback;
} wm_t;
// utility functions
static void wm_error(wm_t* wm, const char* message) {
fprintf(stderr, "[WM_ERROR:%p] %s\n", wm, message);
exit(1);
}
// don't forget for all the functions dealing with the y coordinate:
// X coordinates start from the top left, whereas AQUA coordinates start from the bottom left (where they should be!)
static inline float wm_width_dimension_to_float (wm_t* wm, int pixels) { return (float) pixels / wm->width * 2; }
static inline float wm_height_dimension_to_float(wm_t* wm, int pixels) { return (float) pixels / wm->height * 2; }
static inline float wm_x_coordinate_to_float(wm_t* wm, int pixels) { return wm_width_dimension_to_float (wm, pixels) - 1; }
static inline float wm_y_coordinate_to_float(wm_t* wm, int pixels) { return -wm_height_dimension_to_float(wm, pixels) + 1; }
static inline int wm_float_to_width_dimension (wm_t* wm, float x) { return (int) round(x / 2 * wm->width); }
static inline int wm_float_to_height_dimension(wm_t* wm, float x) { return (int) round(x / 2 * wm->height); }
static inline int wm_float_to_x_coordinate(wm_t* wm, float x) { return wm_float_to_width_dimension (wm, x + 1); }
static inline int wm_float_to_y_coordinate(wm_t* wm, float x) { return wm_float_to_height_dimension(wm, -x + 1); }
static int wm_event_blacklisted_window(wm_t* wm, Window window) {
for (int i = 0; i < wm->event_blacklisted_window_count; i++) {
if (window == wm->event_blacklisted_windows[i]) {
return 1;
}
}
return 0;
}
static int wm_find_window_by_xid(wm_t* wm, Window xid) {
for (int i = 0; i < wm->window_count; i++) {
wm_window_t* window = &wm->windows[i];
// it's really super important to verify our window actually exists
// we could have a window that doesn't exist anymore, but that had the same ID as one that currently exists
if (window->exists && window->window == xid) {
return i;
}
}
// this shouldn't ever happen normally
// we allow it when debugging, because sometimes it's useful to run our WM at the same time as another is running
// so even if *this* WM has never heard of a certain window, it's possible it's been modified in our previous WM
#if !defined(DEBUGGING)
wm_error(wm, "Nonexistant window XID");
#endif
return -1;
}
static void wm_sync_window(wm_t* wm, wm_window_t* window) {
XWindowAttributes attributes;
XGetWindowAttributes(wm->display, window->window, &attributes);
window->visible = attributes.map_state == IsViewable;
window->x = attributes.x;
window->y = attributes.y;
window->width = attributes.width;
window->height = attributes.height;
// TODO also get opacity of window here using the '_NET_WM_WINDOW_OPACITY' atom
// see if this also is useful for checking if a window actually uses transparency at all (so that programs like OBS don't break)
// (although I don't know how much of OBS breaking is due to GLX transparency not being properly implemented by me or due to some other reason where the alpha channel has garbage written in it)
// when you re-implement transparency, don't forget to set the 'GLX_TEXTURE_FORMAT_EXT' attribute in 'cwm.h' and uncomment opacity in the shader code in 'main.c'
}
static void wm_update_client_list(wm_t* wm) {
int existing_window_count = 0;
for (int i = 0; i < wm->window_count; i++) {
existing_window_count += wm->windows[i].exists;
}
Window client_list[existing_window_count];
for (int i = 0; i < existing_window_count; i++) {
client_list[i] = wm->windows[i].window;
}
XChangeProperty(wm->display, wm->root_window, wm->client_list_atom, XA_WINDOW, 32, PropModeReplace, (unsigned char*) client_list, existing_window_count);
}
static int wm_error_handler(Display* display, XErrorEvent* event) {
if (!event->resourceid) return 0; // invalid window
char buffer[1024];
XGetErrorText(display, event->error_code, buffer, sizeof(buffer));
printf("XError code = %d, string = %s, resource ID = 0x%lx\n", event->error_code, buffer, event->resourceid);
return 0;
}
// exposed wm functions
void new_wm(wm_t* wm) {
memset(wm, 0, sizeof(*wm));
wm->display = XOpenDisplay(NULL /* default to 'DISPLAY' environment variable */);
if (!wm->display) wm_error(wm, "Failed to open display");
// this call is here for debugging, so that errors are reported synchronously as they occur
XSynchronize(wm->display, DEBUGGING);
// get screen and root window
wm->screen = DefaultScreen(wm->display);
wm->root_window = DefaultRootWindow(wm->display);
// get width/height of root window
XWindowAttributes attributes;
XGetWindowAttributes(wm->display, wm->root_window, &attributes);
wm->width = attributes.width;
wm->height = attributes.height;
// tell X to send us all 'CreateNotify', 'ConfigureNotify', and 'DestroyNotify' events ('SubstructureNotifyMask' also sends back some other events but we're not using those)
XSelectInput(wm->display, wm->root_window, SubstructureNotifyMask | PointerMotionMask | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask);
XGrabKey(wm->display, XKeysymToKeycode(wm->display, XStringToKeysym("F1")), Mod4Mask, wm->root_window, 0, GrabModeAsync, GrabModeAsync);
XGrabKey(wm->display, XKeysymToKeycode(wm->display, XStringToKeysym("q")), Mod4Mask, wm->root_window, 0, GrabModeAsync, GrabModeAsync);
XGrabKey(wm->display, XKeysymToKeycode(wm->display, XStringToKeysym("f")), Mod4Mask | Mod1Mask, wm->root_window, 0, GrabModeAsync, GrabModeAsync);
XGrabKey(wm->display, XKeysymToKeycode(wm->display, XStringToKeysym("f")), Mod4Mask, wm->root_window, 0, GrabModeAsync, GrabModeAsync);
XGrabKey(wm->display, XKeysymToKeycode(wm->display, XStringToKeysym("t")), Mod4Mask, wm->root_window, 0, GrabModeAsync, GrabModeAsync);
XGrabKey(wm->display, XKeysymToKeycode(wm->display, XStringToKeysym("v")), Mod4Mask, wm->root_window, 0, GrabModeAsync, GrabModeAsync);
XGrabKey(wm->display, XKeysymToKeycode(wm->display, XStringToKeysym("r")), Mod4Mask, wm->root_window, 0, GrabModeAsync, GrabModeAsync);
XGrabKey(wm->display, XKeysymToKeycode(wm->display, XK_Print) /* PrtSc */, Mod4Mask | Mod1Mask, wm->root_window, 0, GrabModeAsync, GrabModeAsync);
XGrabKey(wm->display, XKeysymToKeycode(wm->display, XK_Print) /* PrtSc */, Mod4Mask, wm->root_window, 0, GrabModeAsync, GrabModeAsync);
// setup our atoms (explained in more detail in the 'wm_t' struct)
// we also need to specify which atoms are supported in '_NET_SUPPORTED'
wm->client_list_atom = XInternAtom(wm->display, "_NET_CLIENT_LIST", 0);
Atom supported_list_atom = XInternAtom(wm->display, "_NET_SUPPORTED", 0);
Atom supported_atoms[] = { supported_list_atom, wm->client_list_atom };
XChangeProperty(wm->display, wm->root_window, supported_list_atom, XA_ATOM, 32, PropModeReplace, (const unsigned char*) supported_atoms, sizeof(supported_atoms) / sizeof(*supported_atoms));
// now, we move on to '_NET_SUPPORTING_WM_CHECK'
// this is a bit weird, but it's all specified by the EWMH spec: https://developer.gnome.org/wm-spec/
Atom supporting_wm_check_atom = XInternAtom(wm->display, "_NET_SUPPORTING_WM_CHECK", 0);
Window support_window = XCreateSimpleWindow(wm->display, wm->root_window, 0, 0, 1, 1, 0, 0, 0);
Window support_window_list[1] = { support_window };
XChangeProperty(wm->display, wm->root_window, supporting_wm_check_atom, XA_WINDOW, 32, PropModeReplace, (const unsigned char*) support_window_list, 1);
XChangeProperty(wm->display, support_window, supporting_wm_check_atom, XA_WINDOW, 32, PropModeReplace, (const unsigned char*) support_window_list, 1);
Atom name_atom = XInternAtom(wm->display, "_NET_WM_NAME", 0);
XChangeProperty(wm->display, support_window, name_atom, XA_STRING, 8, PropModeReplace, (const unsigned char*) WM_NAME, sizeof(WM_NAME));
// get all monitors and their individual resolutions
wm->monitor_infos = XineramaQueryScreens(wm->display, &wm->monitor_count);
// TODO REMME, this was just for testing
// wm->monitor_count = 3; // virtual monitors
// wm->monitor_infos = (XineramaScreenInfo*) malloc(wm->monitor_count * sizeof(XineramaScreenInfo));
// // first virtual monitor (1920x1080+0+0)
// wm->monitor_infos[0].x_org = 0;
// wm->monitor_infos[0].y_org = 0;
// wm->monitor_infos[0].width = 1920;
// wm->monitor_infos[0].height = 1080;
// // second virtual monitor (640x1024+1920+56)
// wm->monitor_infos[1].x_org = 1920;
// wm->monitor_infos[1].y_org = 56;
// wm->monitor_infos[1].width = 640;
// wm->monitor_infos[1].height = 1024;
// // third virtual monitor (640x1024+2560+56)
// wm->monitor_infos[2].x_org = 2560;
// wm->monitor_infos[2].y_org = 56;
// wm->monitor_infos[2].width = 640;
// wm->monitor_infos[2].height = 1024;
// create our own error handler so X doesn't crash
XSetErrorHandler(wm_error_handler);
// setup event blacklist
// the first window we wanna blacklist is the root window (TODO really necessary? I think it works just fine without... investigate!)
// we also wanna blacklist the supporting window from earlier
wm->event_blacklisted_windows = (Window*) malloc(sizeof(Window));
wm->event_blacklisted_window_count = 1;
wm->event_blacklisted_windows[0] = support_window;
// wm->event_blacklisted_window_count = 1;
// wm->event_blacklisted_windows[0] = wm->root_window;
// setup windows
wm->windows = (wm_window_t*) malloc(1);
wm->window_count = 0;
}
int wm_x_resolution(wm_t* wm) { return wm->width; }
int wm_y_resolution(wm_t* wm) { return wm->height; }
int wm_monitor_count(wm_t* wm) { return wm->monitor_count; }
float wm_monitor_x(wm_t* wm, int monitor_index) { return wm_x_coordinate_to_float(wm, wm->monitor_infos[monitor_index].x_org + wm->monitor_infos[monitor_index].width / 2); }
float wm_monitor_y(wm_t* wm, int monitor_index) { return wm_y_coordinate_to_float(wm, wm->monitor_infos[monitor_index].y_org + wm->monitor_infos[monitor_index].height / 2); }
float wm_monitor_width (wm_t* wm, int monitor_index) { return wm_width_dimension_to_float (wm, wm->monitor_infos[monitor_index].width ); }
float wm_monitor_height(wm_t* wm, int monitor_index) { return wm_height_dimension_to_float(wm, wm->monitor_infos[monitor_index].height); }
// useful functions for managing windows
void wm_close_window(wm_t* wm, unsigned window_id) {
// all this fuss is to close a window softly
// use the 'wm_kill_window' to force-close a window
XEvent event;
event.xclient.type = ClientMessage;
event.xclient.window = wm->windows[window_id].window;
event.xclient.message_type = XInternAtom(wm->display, "WM_PROTOCOLS", 1);
event.xclient.format = 32;
event.xclient.data.l[0] = XInternAtom(wm->display, "WM_DELETE_WINDOW", 0);
event.xclient.data.l[1] = CurrentTime;
XSendEvent(wm->display, wm->windows[window_id].window, 0, NoEventMask, &event);
}
void wm_kill_window(wm_t* wm, unsigned window_id) {
// this function properly kills windows
// use this sparingly, when force-closing an unresponsive window for example
XDestroyWindow(wm->display, wm->windows[window_id].window);
}
void wm_move_window(wm_t* wm, unsigned window_id, float x, float y, float width, float height) {
XMoveResizeWindow(wm->display, wm->windows[window_id].window,
wm_float_to_x_coordinate(wm, x - width / 2), wm_float_to_y_coordinate(wm, y + height / 2),
wm_float_to_width_dimension(wm, width), wm_float_to_height_dimension(wm, height));
}
void wm_focus_window(wm_t* wm, unsigned window_id) {
Window window = wm->windows[window_id].window;
XSetInputFocus(wm->display, window, RevertToParent, CurrentTime);
XMapRaised(wm->display, window);
}
// event processing call
int wm_process_events(wm_t* wm, void* thing) {
int events_left = XPending(wm->display);
if (events_left) {
XEvent event;
XNextEvent(wm->display, &event);
int type = event.type;
if (type == KeyPress || type == KeyRelease) {
if (wm->keyboard_event_callback) {
wm->keyboard_event_callback(thing, wm_find_window_by_xid(wm, event.xkey.window),
event.xkey.type == KeyPress, event.xkey.state, event.xkey.keycode);
}
}
else if (type == ButtonPress || type == ButtonRelease) {
if (wm->click_event_callback) {
unsigned window = -1;
if (!wm_event_blacklisted_window(wm, event.xbutton.window)) {
window = wm_find_window_by_xid(wm, event.xbutton.window);
}
if (wm->click_event_callback(thing, window,
event.xbutton.type == ButtonPress, event.xbutton.state, event.xbutton.button,
wm_x_coordinate_to_float(wm, event.xbutton.x_root), wm_y_coordinate_to_float(wm, event.xbutton.y_root))) {
// pass the event on to the client
XAllowEvents(wm->display, ReplayPointer, CurrentTime);
}
else {
// if we shouldn't pass the event on to the client, we still need to sync the pointer or else we hang
XAllowEvents(wm->display, SyncPointer, CurrentTime);
}
}
}
else if (type == MotionNotify) {
if (wm->move_event_callback) {
wm->move_event_callback(thing, wm_find_window_by_xid(wm, event.xmotion.subwindow),
event.xmotion.state,
wm_x_coordinate_to_float(wm, event.xmotion.x_root), wm_y_coordinate_to_float(wm, event.xmotion.y_root));
}
}
// window notification events
else if (type == CreateNotify) {
Window x_window = event.xcreatewindow.window;
if (wm_event_blacklisted_window(wm, x_window)) goto done;
wm_window_t* window = (wm_window_t*) 0;
int window_index;
// search for an empty space in the window list
for (window_index = 0; window_index < wm->window_count; window_index++) {
if (!wm->windows[window_index].exists) {
window = &wm->windows[window_index];
break;
}
}
// if no empty space found, add one
if (!window) {
wm->windows = (wm_window_t*) realloc(wm->windows, (wm->window_count + 1) * sizeof(wm_window_t));
window_index = wm->window_count;
window = &wm->windows[window_index];
wm->window_count++;
}
memset(window, 0, sizeof(*window));
window->exists = 1;
window->window = x_window;
if (wm->create_event_callback) {
wm->create_event_callback(thing, window_index);
}
// set up some other stuff for the window
// this is saying we want focus change and button events from the window
XSelectInput(wm->display, x_window, FocusChangeMask);
XGrabButton(wm->display, AnyButton, AnyModifier, x_window, 1, ButtonPressMask | ButtonReleaseMask | ButtonMotionMask, GrabModeSync, GrabModeSync, 0, 0);
wm_update_client_list(wm);
}
// TODO 'VisibilityNotify'?
else if (type == ConfigureNotify || type == MapNotify /* show window */ || type == UnmapNotify /* hide window */) {
Window x_window;
if (type == ConfigureNotify) x_window = event.xconfigure.window;
else if (type == MapNotify) x_window = event.xmap.window;
else if (type == UnmapNotify) x_window = event.xunmap.window;
if (wm_event_blacklisted_window(wm, x_window)) goto done;
int window_index = wm_find_window_by_xid(wm, x_window);
if (window_index < 0) goto done;
wm_window_t* window = &wm->windows[window_index];
int was_visible = window->visible;
wm_sync_window(wm, window);
// if window wasn't visible before but is now, center it to the cursor position
if (window->visible && !was_visible && !window->x && !window->y) {
__attribute__((unused)) Window rw, cw; // root_return, child_return
__attribute__((unused)) int wx, wy; // win_x_return, win_y_return
__attribute__((unused)) unsigned int mask; // mask_return
int x, y;
XQueryPointer(wm->display, window->window, &rw, &cw, &x, &y, &wx, &wy, &mask);
window->x = x - window->width / 2;
window->y = y - window->height / 2;
XMoveWindow(wm->display, window->window, window->x, window->y);
}
if (wm->modify_event_callback) {
wm->modify_event_callback(thing, window_index, window->visible,
wm_x_coordinate_to_float(wm, window->x + window->width / 2), wm_y_coordinate_to_float(wm, window->y + window->height / 2),
wm_width_dimension_to_float (wm, window->width), wm_height_dimension_to_float(wm, window->height));
}
}
// else if (type == FocusIn) {
// Window x_window = event.xfocus.window;
// if (wm_event_blacklisted_window(wm, x_window)) goto done;
// int window_index = wm_find_window_by_xid(wm, x_window);
// if (window_index < 0) goto done;
// if (wm->focus_event_callback) {
// wm->focus_event_callback(thing, window_index);
// }
// }
else if (type == DestroyNotify) {
Window x_window = event.xdestroywindow.window;
if (!x_window) goto done;
int window_index = wm_find_window_by_xid(wm, x_window);
if (window_index < 0) goto done;
wm_window_t* window = &wm->windows[window_index];
if (wm->destroy_event_callback) {
wm->destroy_event_callback(thing, window_index);
}
// remove the window from our list
wm->windows[window_index].exists = 0;
wm_update_client_list(wm);
}
}
done:
return events_left;
}
|
obiwac/x-compositing-wm
|
src/opengl.h
|
<filename>src/opengl.h
// this file contains OpenGL helpers for the window manager
// shaders
static void gl_compile_shader_and_check_for_errors /* lmao */ (GLuint shader, const char* source) {
glShaderSource(shader, 1, &source, 0);
glCompileShader(shader);
GLint log_length;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &log_length);
char* log_buffer = (char*) malloc(log_length); // 'log_length' includes null character
glGetShaderInfoLog(shader, log_length, NULL, log_buffer);
if (log_length) {
fprintf(stderr, "[SHADER_ERROR] %s\n", log_buffer);
exit(1); // no real need to free 'log_buffer' here
}
free(log_buffer);
}
GLuint gl_create_shader_program(const char* vertex_source, const char* fragment_source) {
GLuint program = glCreateProgram();
GLuint vertex_shader = glCreateShader(GL_VERTEX_SHADER);
GLuint fragment_shader = glCreateShader(GL_FRAGMENT_SHADER);
gl_compile_shader_and_check_for_errors(vertex_shader, vertex_source);
gl_compile_shader_and_check_for_errors(fragment_shader, fragment_source);
glAttachShader(program, vertex_shader);
glAttachShader(program, fragment_shader);
glLinkProgram(program);
glDeleteShader(vertex_shader);
glDeleteShader(fragment_shader);
return program;
}
// VAO / VBO / IBO
void gl_create_vao_vbo_ibo(GLuint* vao, GLuint* vbo, GLuint* ibo) {
glGenVertexArrays(1, vao);
glBindVertexArray(*vao);
glGenBuffers(1, vbo);
glBindBuffer(GL_ARRAY_BUFFER, *vbo);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(0);
glGenBuffers(1, ibo);
}
void gl_set_vao_vbo_ibo_data(GLuint vao, GLuint vbo, GLsizeiptr vbo_size, const void* vbo_data, GLuint ibo, GLsizeiptr ibo_size, const void* ibo_data) {
glBindVertexArray(vao);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, vbo_size, vbo_data, GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, ibo_size, ibo_data, GL_STATIC_DRAW);
}
|
obiwac/x-compositing-wm
|
src/main.c
|
#define DEBUGGING 1
#include <cwm.h>
#include <opengl.h>
#include <math.h>
#include <unistd.h>
#include <sys/param.h>
// structures and types
typedef struct {
unsigned internal_id;
int exists;
int visible;
uint64_t farness;
float opacity;
float x, y;
float width, height;
float visual_opacity;
float visual_x, visual_y;
float visual_width, visual_height;
float visual_shadow_opacity;
float visual_shadow_radius;
float visual_shadow_y_offset;
int maximized;
float unmaximized_x, unmaximized_y;
float unmaximized_width, unmaximized_height;
int always_on_top; // TODO doesn't always on top mean always focused to X?
// it appears not, but this still needs to be implemented
// also maybe creating a proper linked list system for windows before implementing will make this easier
// OpenGL stuff
int index_count;
GLuint vao, vbo, ibo;
} window_t;
typedef enum {
ACTION_NONE = 0,
ACTION_MOVE, ACTION_RESIZE
} action_t;
typedef struct {
wm_t wm;
cwm_t cwm;
int x_resolution;
int y_resolution;
int running;
window_t* windows;
int window_count;
// focused window and current action stuff
unsigned focused_window_id;
float focused_window_x, focused_window_y;
action_t action;
// monitor configuration info
int monitor_count;
float* monitor_xs, *monitor_ys;
float* monitor_widths, *monitor_heights;
// OpenGL stuff
GLuint shader;
GLuint texture_uniform;
GLuint opacity_uniform;
GLuint depth_uniform;
GLuint position_uniform;
GLuint size_uniform;
// shadow stuff
int shadow_index_count;
GLuint shadow_vao, shadow_vbo, shadow_ibo;
GLuint shadow_shader;
GLuint shadow_strength_uniform;
GLuint shadow_depth_uniform;
GLuint shadow_position_uniform;
GLuint shadow_size_uniform;
GLuint shadow_spread_uniform;
} my_wm_t;
// useful functions
static unsigned window_internal_id_to_index(my_wm_t* wm, unsigned internal_id) {
for (int i = 0; i < wm->window_count; i++) {
window_t* window = &wm->windows[i];
// it's really super important to verify our window actually exists
// we could have a window that doesn't exist anymore, but that had the same ID as one that currently exists
if (window->exists && window->internal_id == internal_id) {
return i;
}
}
// no window with that internal id was found
return -1;
}
static void print_window_stack(my_wm_t* wm) { // debugging function
printf("Window stack (%d windows):\n", wm->window_count);
for (int i = 0; i < wm->window_count; i++) {
window_t* window = &wm->windows[i];
if (window->exists) printf("\t[%d]: internal_id = %d, visible = %d, farness = %lu\n", i, window->internal_id, window->visible, window->farness);
else printf("\t[%d]: empty space\n", i);
}
printf("\n");
}
static void focus_window(my_wm_t* wm, unsigned window_id, int internally) {
unsigned internal_id = wm->windows[window_id].internal_id;
if (internally) {
wm_focus_window(&wm->wm, internal_id);
}
for (int i = 0; i < wm->window_count; i++) {
window_t* window = &wm->windows[i];
/* if (window->always_on_top) window->farness = 0;
else */ window->farness++;
}
wm->windows[window_id].farness = 0;
// sort windows
// this could be a much more efficient system with linked lists (as I believe X does internally), but this is fine for now
for (int i = 0; i < wm->window_count; i++) {
for (int j = i + 1; j < wm->window_count; j++) {
if (wm->windows[i].farness < wm->windows[j].farness) {
window_t temp;
memcpy(&temp, &wm->windows[i], sizeof(window_t));
memcpy(&wm->windows[i], &wm->windows[j], sizeof(window_t));
memcpy(&wm->windows[j], &temp, sizeof(window_t));
}
}
}
wm->focused_window_id = window_internal_id_to_index(wm, internal_id);
}
static void unfocus_window(my_wm_t* wm) {
// loop backwards through all the windows and check if they're a valid candidate for refocusing
// we start at 'wm->window_count - 2', because we want the index and two ignore the last window on the stack (hopefully our focused window)
for (int i = wm->focused_window_id - 1; i >= 0; i--) {
if (i != wm->focused_window_id) { // just to make sure, but this shouldn't happen
window_t* window = &wm->windows[i];
if (window->exists && window->visible) {
focus_window(wm, i, 1);
break;
}
}
}
}
static void maximize_window(my_wm_t* wm, unsigned window_id, int single_monitor) {
window_t* window = &wm->windows[window_id];
if (window->maximized) {
window->maximized = 0;
wm_move_window(&wm->wm, window->internal_id, window->unmaximized_x, window->unmaximized_y, window->unmaximized_width, window->unmaximized_height);
return;
}
window->unmaximized_x = window->x;
window->unmaximized_y = window->y;
window->unmaximized_width = window->width;
window->unmaximized_height = window->height;
window->maximized = 1;
if (single_monitor) {
// find closest monitor to the centre of the window
for (int i = 0; i < wm->monitor_count; i++) {
float monitor_x = wm->monitor_xs [i];
float monitor_y = wm->monitor_ys [i];
float monitor_width = wm->monitor_widths [i];
float monitor_height = wm->monitor_heights[i];
if (window->x >= monitor_x - monitor_width / 2 && window->x <= monitor_x + monitor_width / 2 &&
window->y >= monitor_y - monitor_height / 2 && window->y <= monitor_y + monitor_height / 2) {
wm_move_window(&wm->wm, window->internal_id, monitor_x, monitor_y, monitor_width, monitor_height);
return;
}
}
// if we can't find a valid monitor, no worries, we'll just fill the whole screen
}
wm_move_window(&wm->wm, window->internal_id, 0.0, 0.0, 2.0, 2.0);
}
// event callback functions
static char* first_argument;
void keyboard_event(my_wm_t* wm, unsigned internal_id, unsigned press, unsigned modifiers, unsigned key) {
int alt = modifiers & 0x8;
int super = modifiers & 0x40;
if (press && super && key == 67) wm->running = 0; // Super+F1
if (press && super && key == 24) wm_close_window(&wm->wm, wm->windows[wm->focused_window_id].internal_id); // Super+Q (quit)
if (press && super && alt && key == 41) maximize_window(wm, wm->focused_window_id, 0); // Super+Alt+F (fullfullscreen)
if (press && super && !alt && key == 41) maximize_window(wm, wm->focused_window_id, 1); // Super+F (fullscreen)
if (press && super && key == 55) wm->cwm.vsync = !wm->cwm.vsync; // Super+V (vsync)
if (press && super && key == 27) { // Super+R (restart)
execl(first_argument, first_argument, NULL);
exit(1);
}
if (press && super && key == 28) { // Super+T (terminal)
/*if (!fork()) {
execl("/usr/local/bin/xterm", "/usr/local/bin/xterm", NULL);
exit(1);
}*/
system("xterm &");
}
if (press && super && !alt && key == 107) { // Super+PrtSc (screenshot of selection to clipboard)
system("scrot -fs '/tmp/screenshot-selection-aquabsd-%F-%T.png' -e 'xclip -selection clipboard -target image/png -i $f && rm $f' &");
}
if (press && super && alt && key == 107) { // Super+Alt+PrtSc (screenshot of window to clipboard)
system("scrot -u '/tmp/screenshot-selection-aquabsd-$wx$h-%F-%T.png' -e 'xclip -selection clipboard -target image/png -i $f && rm $f' &");
}
}
int click_event(my_wm_t* wm, unsigned internal_id, unsigned press, unsigned modifiers, unsigned button, float x, float y) {
int window_index;
if (press) {
if (internal_id == -1) return 0;
window_index = window_internal_id_to_index(wm, internal_id);
focus_window(wm, window_index, 1);
wm->focused_window_x = wm->windows[wm->focused_window_id].x - x;
wm->focused_window_y = wm->windows[wm->focused_window_id].y - y;
} else if (wm->action) { // releasing and were already doing something
window_t* window = &wm->windows[wm->focused_window_id];
window->opacity = 1.0;
wm_move_window(&wm->wm, window->internal_id, window->x, window->y, window->width, window->height);
wm->action = ACTION_NONE;
return 0;
}
if (modifiers & Mod4Mask && press) {
if (button == 1) wm->action = ACTION_MOVE;
else if (button == 3) wm->action = ACTION_RESIZE;
wm->windows[wm->focused_window_id].opacity = 0.9;
return 0;
}
return 1;
}
void move_event(my_wm_t* wm, unsigned internal_id, unsigned modifiers, float x, float y) {
if (wm->action && !wm->windows[wm->focused_window_id].maximized) {
window_t* window = &wm->windows[wm->focused_window_id];
if (wm->action == ACTION_MOVE) {
window->x = x + wm->focused_window_x;
window->y = y + wm->focused_window_y;
}
else if (wm->action == ACTION_RESIZE) {
window->width = 2 * fabs(x - window->x);
window->height = 2 * fabs(y - window->y);
// this is not ideal for performance in certain applications, but it looks hella cool for apps that work correctly nonetheless
// basically the problem is that you're calling a 'ConfigureNotify' event each time,
// which means the compositor needs to create a new pixmap for each frame
// not good...
wm_move_window(&wm->wm, window->internal_id, window->x, window->y, window->width, window->height);
}
}
}
void create_event(my_wm_t* wm, unsigned internal_id) {
cwm_create_event(&wm->cwm, internal_id);
int window_index = 0;
for (; window_index < wm->window_count; window_index++) {
if (!wm->windows[window_index].exists) {
goto got_space;
}
}
wm->windows = (window_t*) realloc(wm->windows, ++wm->window_count * sizeof(*wm->windows));
window_index = wm->window_count - 1;
got_space: {}
window_t* window = &wm->windows[window_index];
memset(window, 0, sizeof(*window));
window->internal_id = internal_id;
window->exists = 1;
window->opacity = 1.0;
gl_create_vao_vbo_ibo(&window->vao, &window->vbo, &window->ibo);
}
void modify_event(my_wm_t* wm, unsigned internal_id, int visible, float x, float y, float width, float height) {
cwm_modify_event(&wm->cwm, internal_id);
int window_index = window_internal_id_to_index(wm, internal_id);
window_t* window = &wm->windows[window_index];
int was_visible = window->visible;
window->visible = visible;
window->x = x;
window->y = y;
window->width = width;
window->height = height;
// regenerate vertex attributes and indices
#define TAU 6.283185
#define CORNER_RESOLUTION 8
#define CORNER_RADIUS 3 // pixels
float x_radius = 4 * (float) CORNER_RADIUS / wm->x_resolution / width;
float y_radius = 4 * (float) CORNER_RADIUS / wm->y_resolution / height;
// loop through all the vertex pairs
GLfloat vertex_positions[CORNER_RESOLUTION * 2 * 4 + 4];
GLubyte indices[CORNER_RESOLUTION * 2 * 6 + 3];
int prev_index_pair[2] = { -1 };
for (int i = 0; i < CORNER_RESOLUTION * 2 + 1; i++) {
// calculate indices
int index_pair[2] = { i * 2, i * 2 + 1 };
if (prev_index_pair[0] >= 0) {
indices[i * 6 + 0] = prev_index_pair[0];
indices[i * 6 + 1] = prev_index_pair[1];
indices[i * 6 + 2] = index_pair[1];
indices[i * 6 + 3] = prev_index_pair[0];
indices[i * 6 + 4] = index_pair[1];
indices[i * 6 + 5] = index_pair[0];
}
memcpy(prev_index_pair, index_pair, sizeof(prev_index_pair));
// calculate vertices
float theta = (float) (i - (i > CORNER_RESOLUTION / 2)) / CORNER_RESOLUTION * TAU / 2;
float corner_x = cos(theta) * x_radius;
float corner_y = sin(theta) * y_radius;
float x = (i <= CORNER_RESOLUTION / 2 ? 0.5 - x_radius : -0.5 + x_radius) + corner_x;
float y = 0.5 - y_radius + corner_y;
vertex_positions[i * 4 + 0] = x;
vertex_positions[i * 4 + 1] = y;
vertex_positions[i * 4 + 2] = x;
vertex_positions[i * 4 + 3] = -y;
}
window->index_count = sizeof(indices) / sizeof(*indices);
gl_set_vao_vbo_ibo_data(window->vao, window->vbo, sizeof(vertex_positions), vertex_positions, window->ibo, sizeof(indices), indices);
if (window->visible && !was_visible) {
window->opacity = 1.0;
window->visual_opacity = 0.0;
wm_move_window(&wm->wm, window->internal_id, window->x, window->y, window->width, window->height);
window->visual_x = window->x;
window->visual_y = window->y;
window->visual_width = window->width * 0.9;
window->visual_height = window->height * 0.9;
focus_window(wm, window_index, 0);
}
else if (window_index == wm->focused_window_id && !window->visible && was_visible) {
unfocus_window(wm);
}
}
void destroy_event(my_wm_t* wm, unsigned internal_id) {
cwm_destroy_event(&wm->cwm, internal_id);
unsigned window_index = window_internal_id_to_index(wm, internal_id);
window_t* window = &wm->windows[window_index];
window->exists = 0;
}
// main functions
static void render_window(my_wm_t* wm, unsigned window_id, float delta) {
window_t* window = &wm->windows[window_id];
if (!window->exists ) return;
if (!window->visible) return;
// calculate visual window coordinates and size (animation)
delta = MIN(0.1, delta); // just make sure this doesn't get too crazy
// TODO see if this actually does anything
window->visual_opacity += (window->opacity - window->visual_opacity) * delta * 10;
window->visual_x += (window->x - window->visual_x) * delta * 20;
window->visual_y += (window->y - window->visual_y) * delta * 20;
// TODO for some reason, when disabling vsync, windows take a real long time before starting their "appearing" animation
// maybe this is because of this?
window->visual_width += (window->width - window->visual_width ) * delta * 30;
window->visual_height += (window->height - window->visual_height) * delta * 30;
float x = window->visual_x;
float y = window->visual_y;
float width = window->visual_width;
float height = window->visual_height;
// check if window coordinates and size are pixel aligned
// rounding here instead of simply flooring to preserve proper subpixel rendering when animating
int width_pixels = (int) round(width / 2 * wm->x_resolution);
int height_pixels = (int) round(height / 2 * wm->y_resolution);
if (width_pixels % 2) x += 0.5 / wm->x_resolution * 2; // if width odd, add half a pixel to x
if (height_pixels % 2) y += 0.5 / wm->y_resolution * 2; // if height odd, subtract half a pixel to y
// calculate window depth
float depth = 1.0 - (float) window_id / wm->window_count;
// draw the window contents
glUseProgram(wm->shader);
glUniform1i(wm->texture_uniform, 0);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glActiveTexture(GL_TEXTURE0);
cwm_bind_window_texture(&wm->cwm, window->internal_id);
// actually draw the window
glUniform1f(wm->opacity_uniform, window->visual_opacity);
glUniform1f(wm->depth_uniform, depth);
glUniform2f(wm->position_uniform, x, y);
glUniform2f(wm->size_uniform, width, height);
glBindVertexArray(window->vao);
glDrawElements(GL_TRIANGLES, window->index_count, GL_UNSIGNED_BYTE, NULL);
cwm_unbind_window_texture(&wm->cwm, window->internal_id);
// draw the shadow
// we do this after drawing the window contents so we can take advantage of alpha sorting
glUseProgram(wm->shadow_shader);
float shadow_opacity = 0.15 + 0.1 * (window_id == wm->focused_window_id);
// TODO do I really want to disable shadows on maximized windows?
// if (window->maximized) { // we want to phase out the shadow much slower when maximizing our window
// window->visual_shadow_opacity -= window->visual_shadow_opacity * delta * 10;
// }
// else {
window->visual_shadow_opacity += (shadow_opacity - window->visual_shadow_opacity) * delta * 30;
// }
glUniform1f(wm->shadow_strength_uniform, window->visual_opacity * window->visual_shadow_opacity);
float shadow_radius = (float) (64 + (64 * (window_id == wm->focused_window_id))); // pixels
window->visual_shadow_radius += (shadow_radius - window->visual_shadow_radius) * delta * 20;
float spread_x = 4 * window->visual_shadow_radius / wm->x_resolution;
float spread_y = 4 * window->visual_shadow_radius / wm->y_resolution;
glUniform2f(wm->shadow_spread_uniform, spread_x, spread_y);
float y_offset = -spread_y / 32 - spread_y / 16 * (window_id == wm->focused_window_id);
window->visual_shadow_y_offset += (y_offset - window->visual_shadow_y_offset) * delta * 10;
glUniform1f(wm->shadow_depth_uniform, depth);
glUniform2f(wm->shadow_position_uniform, x, y /* + window->visual_shadow_y_offset / 2 */);
glUniform2f(wm->shadow_size_uniform, width, height);
glBindVertexArray(wm->shadow_vao);
glDrawElements(GL_TRIANGLES, wm->shadow_index_count, GL_UNSIGNED_BYTE, NULL);
}
int main(int argc, char* argv[]) {
first_argument = argv[0];
my_wm_t _wm;
my_wm_t* wm = &_wm;
memset(wm, 0, sizeof(*wm));
// create a compositing window manager
new_wm(&wm->wm);
new_cwm(&wm->cwm, &wm->wm);
wm->x_resolution = wm_x_resolution(&wm->wm);
wm->y_resolution = wm_y_resolution(&wm->wm);
// get info about the monitor configuration
wm->monitor_count = wm_monitor_count(&wm->wm);
wm->monitor_xs = (float*) malloc(wm->monitor_count * sizeof(float));
wm->monitor_ys = (float*) malloc(wm->monitor_count * sizeof(float));
wm->monitor_widths = (float*) malloc(wm->monitor_count * sizeof(float));
wm->monitor_heights = (float*) malloc(wm->monitor_count * sizeof(float));
for (int i = 0; i < wm->monitor_count; i++) {
wm->monitor_xs [i] = wm_monitor_x (&wm->wm, i);
wm->monitor_ys [i] = wm_monitor_y (&wm->wm, i);
wm->monitor_widths [i] = wm_monitor_width (&wm->wm, i);
wm->monitor_heights[i] = wm_monitor_height(&wm->wm, i);
}
// register all the event callbacks
// ideally, there would be proper functions to do this
wm->wm.keyboard_event_callback = (wm_keyboard_event_callback_t) keyboard_event;
wm->wm.click_event_callback = (wm_click_event_callback_t) click_event;
wm->wm.move_event_callback = (wm_move_event_callback_t) move_event;
wm->wm.create_event_callback = (wm_create_event_callback_t) create_event;
wm->wm.modify_event_callback = (wm_modify_event_callback_t) modify_event;
wm->wm.destroy_event_callback = (wm_destroy_event_callback_t) destroy_event;
// run any startup programs here
// system("code-oss");
// OpenGL stuff
const char* vertex_shader_source = "#version 330\n"
"layout(location = 0) in vec2 vertex_position;"
"out vec2 local_position;"
"uniform float depth;"
"uniform vec2 position;"
"uniform vec2 size;"
"void main(void) {"
" local_position = vertex_position;"
" gl_Position = vec4(vertex_position * size + position, depth, 1.0);"
"}";
const char* fragment_shader_source = "#version 330\n"
"in vec2 local_position;"
"out vec4 fragment_colour;"
"uniform float opacity;"
"uniform sampler2D texture_sampler;"
"void main(void) {"
" vec4 colour = texture(texture_sampler, local_position * vec2(1.0, -1.0) + vec2(0.5));"
" float alpha = opacity /* * (1.0 - colour.a) */;"
" fragment_colour = vec4(colour.rgb, alpha);"
"}";
wm->shader = gl_create_shader_program(vertex_shader_source, fragment_shader_source);
wm->texture_uniform = glGetUniformLocation(wm->shader, "texture_sampler");
wm->opacity_uniform = glGetUniformLocation(wm->shader, "opacity");
wm->depth_uniform = glGetUniformLocation(wm->shader, "depth");
wm->position_uniform = glGetUniformLocation(wm->shader, "position");
wm->size_uniform = glGetUniformLocation(wm->shader, "size");
// shadow stuff
const GLubyte shadow_indices[] = { 0, 1, 2, 0, 2, 3 };
const GLfloat shadow_vertex_positions[] = {
-0.5, 0.5,
-0.5, -0.5,
0.5, -0.5,
0.5, 0.5,
};
gl_create_vao_vbo_ibo(&wm->shadow_vao, &wm->shadow_vbo, &wm->shadow_ibo);
wm->shadow_index_count = sizeof(shadow_indices) / sizeof(*shadow_indices);
gl_set_vao_vbo_ibo_data(wm->shadow_vao, wm->shadow_vbo, sizeof(shadow_vertex_positions), shadow_vertex_positions, wm->shadow_ibo, sizeof(shadow_indices), shadow_indices);
const char* shadow_vertex_shader_source = "#version 330\n"
"layout(location = 0) in vec2 vertex_position;"
"out vec2 map_position;"
"uniform float depth;"
"uniform vec2 position;"
"uniform vec2 size;"
"uniform vec2 spread;"
"void main(void) {"
" map_position = vertex_position * (size + spread);"
" gl_Position = vec4(map_position + position, depth, 1.0);"
"}";
const char* shadow_fragment_shader_source = "#version 330\n"
"in vec2 map_position;"
"out vec4 fragment_colour;"
"uniform float strength;"
"uniform vec2 size;"
"uniform vec2 spread;"
"void main(void) {"
// find distance from point on shadow plane to window bounds
" float dx = (2 * abs(map_position.x) - size.x + spread.x / 8) / spread.x;"
" float dy = (2 * abs(map_position.y) - size.y + spread.y / 8) / spread.y;"
" if (map_position.y > 0) dy *= 1.5;"
" if (map_position.y < 0) dy /= 1.2;"
" dx = clamp(dx, 0, 1);"
" dy = clamp(dy, 0, 1);"
// calculate the shadow colour
" float value = 1.0 - clamp(length(vec2(dx, dy)), 0, 1);"
" fragment_colour = vec4(0.0, 0.0, 0.0, value * value) * strength;"
"}";
wm->shadow_shader = gl_create_shader_program(shadow_vertex_shader_source, shadow_fragment_shader_source);
wm->shadow_strength_uniform = glGetUniformLocation(wm->shadow_shader, "strength");
wm->shadow_depth_uniform = glGetUniformLocation(wm->shadow_shader, "depth");
wm->shadow_position_uniform = glGetUniformLocation(wm->shadow_shader, "position");
wm->shadow_size_uniform = glGetUniformLocation(wm->shadow_shader, "size");
wm->shadow_spread_uniform = glGetUniformLocation(wm->shadow_shader, "spread");
glEnable(GL_DEPTH_TEST);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
// main loop
float average_delta = 0.0;
wm->running = 1;
while (wm->running) {
while (wm_process_events(&wm->wm, wm));
// glClearColor(0.4, 0.2, 0.4, 1.0);
// gruvbox background colour (#292828)
glClearColor(0.16015625, 0.15625, 0.15625, 1.);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// render our windows
for (int i = 0; i < wm->window_count; i++) {
render_window(wm, i, average_delta);
}
float delta = (float) cwm_swap(&wm->cwm) / 1000000;
average_delta += delta;
average_delta /= 2;
// printf("average fps %f\n", 1 / average_delta);
}
}
|
shansfolder/Kiezzer
|
kiezzer/Kiezzer/Controllers/CameraViewController.h
|
//
// CameraViewController.h
// Kiezzer
//
// Created by Penergy on 13-10-27.
// Copyright (c) 2013年 com.Kiezzer. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface CameraViewController : UIViewController <UIImagePickerControllerDelegate, UINavigationControllerDelegate> {
UIImagePickerController *picker;
UIImagePickerController *picker2;
UIImage *image;
IBOutlet UIImageView *imageView;
}
- (IBAction)takePhoto:(id)sender;
- (IBAction)chooseExisting:(id)sender;
- (IBAction)uploading:(id)sender;
@end
|
shansfolder/Kiezzer
|
kiezzer/Kiezzer/Controllers/DetailViewController.h
|
//
// DetailViewController.h
// Kiezzer
//
// Created by <NAME> on 13-10-26.
// Copyright (c) 2013年 com.Kiezzer. All rights reserved.
//
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
@interface DetailViewController : UIViewController <MKMapViewDelegate>
- (IBAction)goToGeneralDataVC:(id)sender;
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet MKMapView *mapView;
@property (weak, nonatomic) IBOutlet UILabel *temperatureLabel;
@property (weak, nonatomic) IBOutlet UILabel *averageAgeLabel;
@property (weak, nonatomic) IBOutlet UILabel *maleLabel;
@property (weak, nonatomic) IBOutlet UILabel *femaleLabel;
@end
|
shansfolder/Kiezzer
|
kiezzer/Kiezzer/Controllers/ClubsTableViewController.h
|
//
// ClubTableViewController.h
// Kiezzer
//
// Created by Penergy on 13-10-23.
// Copyright (c) 2013年 com.Kiezzer. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface ClubsTableViewController : UITableViewController
@property (nonatomic, strong) NSMutableArray *clubs;
@end
|
shansfolder/Kiezzer
|
kiezzer/Kiezzer/Controllers/GallaryViewController.h
|
//
// GallaryViewController.h
// Kiezzer
//
// Created by Penergy on 13-10-27.
// Copyright (c) 2013年 com.Kiezzer. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface GallaryViewController : UICollectionViewController
@property (strong, nonatomic) IBOutlet UIImageView *gallaryImage;
@end
|
shansfolder/Kiezzer
|
kiezzer/Kiezzer/Views/FotosTableViewCell.h
|
//
// FotosTableViewCell.h
// Kiezzer
//
// Created by Penergy on 13-10-26.
// Copyright (c) 2013年 com.Kiezzer. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface FotosTableViewCell : UITableViewCell
@property (strong, nonatomic) IBOutlet UIImageView *cellBkImage;
@property (strong, nonatomic) IBOutlet UIImageView *cellWhiteBkImage;
@property (strong, nonatomic) IBOutlet UILabel *clubNameLabel;
@end
|
shansfolder/Kiezzer
|
kiezzer/Kiezzer/Views/ClubCell.h
|
//
// ClubCell.h
// Kiezzer
//
// Created by Penergy on 13-10-23.
// Copyright (c) 2013年 com.Kiezzer. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface ClubCell : UITableViewCell
@property (strong, nonatomic) IBOutlet UILabel *nameLabel;
@property (strong, nonatomic) IBOutlet UIImageView *ratingImageView;
@property (strong, nonatomic) IBOutlet UILabel *locationLabel;
@end
|
shansfolder/Kiezzer
|
kiezzer/Kiezzer/Controllers/ActivityIndicatorViewController.h
|
<gh_stars>0
//
// ActivityIndicatorViewController.h
// Kiezzer
//
// Created by <NAME> on 13-10-27.
// Copyright (c) 2013年 com.Kiezzer. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface ActivityIndicatorViewController : UIViewController
@end
|
shansfolder/Kiezzer
|
kiezzer/Kiezzer/Controllers/GallaryDetailViewController.h
|
//
// GallaryDetailViewController.h
// Kiezzer
//
// Created by <NAME> on 13-10-27.
// Copyright (c) 2013年 com.Kiezzer. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface GallaryDetailViewController : UIViewController
@property (weak, nonatomic) IBOutlet UIImageView *gallaryImage;
@property (strong, nonatomic) NSString *imageURL;
@end
|
shansfolder/Kiezzer
|
kiezzer/Kiezzer/Controllers/GeneralDataViewController.h
|
<gh_stars>0
//
// GeneralDataViewController.h
// Kiezzer
//
// Created by <NAME> on 13-10-26.
// Copyright (c) 2013年 com.Kiezzer. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface GeneralDataViewController : UIViewController
@property (weak, nonatomic) IBOutlet UILabel *temperatureLabel;
@property (weak, nonatomic) IBOutlet UILabel *girlsPctLabel;
@property (weak, nonatomic) IBOutlet UILabel *ageLabel;
@property (weak, nonatomic) IBOutlet UILabel *maleLabel;
@end
|
shansfolder/Kiezzer
|
kiezzer/Kiezzer/Controllers/FotosTableViewController.h
|
//
// FotosTableViewController.h
// Kiezzer
//
// Created by <NAME> on 13-10-26.
// Copyright (c) 2013年 com.Kiezzer. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface FotosTableViewController : UITableViewController
- (IBAction)intoPhoto:(id)sender;
@end
|
shansfolder/Kiezzer
|
kiezzer/Kiezzer/Views/GallaryViewCell.h
|
//
// GallaryViewCell.h
// Kiezzer
//
// Created by Penergy on 13-10-27.
// Copyright (c) 2013年 com.Kiezzer. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface GallaryViewCell : UICollectionViewCell
@property (strong, nonatomic) IBOutlet UIImageView *gallaryImage;
@end
|
shansfolder/Kiezzer
|
kiezzer/Kiezzer/ViewController.h
|
<filename>kiezzer/Kiezzer/ViewController.h
//
// ViewController.h
// Kiezzer
//
// Created by Penergy on 13-10-23.
// Copyright (c) 2013年 com.Kiezzer. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
- (IBAction)clubButton:(id)sender;
- (IBAction)userButton:(id)sender;
@end
|
yp/Heu-MCHC
|
include/util.h
|
<reponame>yp/Heu-MCHC<filename>include/util.h<gh_stars>1-10
/**
*
*
* Heu-MCHC
*
* A fast and accurate heuristic algorithm for the haplotype inference
* problem on pedigree data with recombinations and mutations
*
* Copyright (C) 2009,2010,2011 <NAME>
*
* Distributed under the terms of the GNU General Public License (GPL)
*
*
* This file is part of Heu-MCHC.
*
* Heu-MCHC is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Heu-MCHC is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Heu-MCHC. If not, see <http://www.gnu.org/licenses/>.
*
**/
/**
*
* @file util.h
*
* Funzioni di utilita' generale.
*
**/
#ifdef __cplusplus
using namespace std;
extern "C" {
#endif
#ifndef _UTIL_H_
#define _UTIL_H_
#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#ifdef i386
#define ST_FMTL( l ) "%" #l "u"
#define ST_FMT "%u"
#else
#define ST_FMTL( l ) "%" #l "lu"
#define ST_FMT "%lu"
#endif
double rnd_01(void);
unsigned int
rnd_in_range(unsigned int min, unsigned int max);
#define NPALLOC( type, dim ) (type*)palloc((dim)*sizeof(type))
#define PALLOC( type ) (type*)palloc(sizeof(type))
#define _SET_VECTOR( V, val, lim ) \
do { \
for (int ___i= 0; ___i<lim; V[___i]=val, ++___i); \
} while (0)
#define MY_SWAP( type, el1, el2 ) \
{ \
type tmp= (el1); \
(el1)= el2; \
(el2)= tmp; \
}
#define MIN( x, y ) (((x)<=(y))?(x):(y))
#define MAX( x, y ) (((x)>=(y))?(x):(y))
void* palloc(size_t dim) __attribute__ ((malloc));
void pfree(void* p)
#ifndef __ICC
__attribute__ ((nonnull))
#endif
;
char* c_palloc(size_t dim) __attribute__ ((malloc));
char* alloc_and_copy(char* source) __attribute__ ((malloc));
void noop_free(void* el __attribute__ ((unused)) ) __attribute__ ((const));
char* substring(const int, const char* ) __attribute__ ((pure));
// Chiama la getline e rimuove i caratteri non stampabili
// finali (ad es. \n)
ssize_t my_getline(char **lineptr, size_t *n, FILE *stream)
#ifndef __ICC
__attribute__ ((nonnull))
#endif
;
void print_repetitions(FILE* f, const char c, int rep);
void resource_usage_log(void);
#ifndef MYNDEBUG
#define fail() \
do { \
fprintf(stderr, "Failing at %s:%d.\n", __FILE__, __LINE__); \
char* pc= NULL; \
*pc= '\65'; \
exit(1); \
} while (0)
#define my_assert( cond ) \
do { \
if (!(cond)) { \
fprintf(stderr, "Assertion " #cond " failed at %s:%d.\n", __FILE__, __LINE__); \
fail(); \
} \
} while (0)
#else
#define fail() \
do { \
fprintf(stderr, "Failing at %s:%d.\n", __FILE__, __LINE__); \
char* pc= NULL; \
*pc= '\65'; \
exit(1); \
} while (0)
/* #define fail() \ */
/* do { \ */
/* fprintf(stderr, "Failing at %s:%d.\n", __FILE__, __LINE__); \ */
/* exit(1); \ */
/* } while (0) */
#define my_assert( cond ) do { } while (0)
#endif
#define assert_lims(lbound, var, ubound) { my_assert(lbound<=(var)); \
my_assert((var)<ubound); \
} while (0);
#define assert_ulim(var, ubound) { \
my_assert((var)<ubound); \
} while (0);
#endif
#define fail_if( cond ) if (cond) { \
fail(); \
}
#define fail_if_msg( cond , msg ) if (cond) { \
fprintf(stderr, "%s", msg); \
fail(); \
}
#ifdef __cplusplus
}
#endif
|
yp/Heu-MCHC
|
pers-lib/m4ri/testsuite/test_kernel.c
|
<reponame>yp/Heu-MCHC<gh_stars>1-10
/*******************************************************************
*
* M4RI: Linear Algebra over GF(2)
*
* Copyright (C) 2009 <NAME> <<EMAIL>>
*
* Distributed under the terms of the GNU General Public License (GPL)
* version 2 or higher.
*
* This code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* The full text of the GPL is available at:
*
* http://www.gnu.org/licenses/
*
********************************************************************/
#include <stdlib.h>
#include "m4ri/m4ri.h"
int test_kernel_left_pluq(size_t m, size_t n) {
mzd_t* A = mzd_init(m, n);
mzd_randomize(A);
mzd_t *Acopy = mzd_copy(NULL, A);
size_t r = mzd_echelonize_m4ri(A, 0, 0);
printf("kernel_left m: %4zu, n: %4zu, r: %4zu ",m, n, r);
mzd_free(Acopy);
Acopy = mzd_copy(NULL, A);
mzd_t *X = mzd_kernel_left_pluq(A, 0);
if (X == NULL) {
printf("passed\n");
mzd_free(A);
mzd_free(Acopy);
return 0;
}
mzd_t *Z = mzd_mul(NULL, Acopy, X, 0);
int status = 1 - mzd_is_zero(Z);
if (!status)
printf("passed\n");
else
printf("FAILED\n");
mzd_free(A);
mzd_free(Acopy);
mzd_free(X);
mzd_free(Z);
return status;
}
int main(int argc, char **argv) {
int status = 0;
status += test_kernel_left_pluq( 2, 4);
status += test_kernel_left_pluq( 4, 1);
status += test_kernel_left_pluq( 10, 20);
status += test_kernel_left_pluq( 20, 1);
status += test_kernel_left_pluq( 20, 20);
status += test_kernel_left_pluq( 30, 1);
status += test_kernel_left_pluq( 30, 30);
status += test_kernel_left_pluq( 80, 1);
status += test_kernel_left_pluq( 80, 20);
status += test_kernel_left_pluq( 80, 80);
status += test_kernel_left_pluq( 4, 2);
status += test_kernel_left_pluq( 1, 4);
status += test_kernel_left_pluq(20, 10);
status += test_kernel_left_pluq( 1, 20);
status += test_kernel_left_pluq(20, 20);
status += test_kernel_left_pluq( 1, 30);
status += test_kernel_left_pluq(30, 30);
status += test_kernel_left_pluq( 1, 80);
status += test_kernel_left_pluq(20, 80);
status += test_kernel_left_pluq(80, 80);
status += test_kernel_left_pluq(10, 20);
status += test_kernel_left_pluq(10, 80);
status += test_kernel_left_pluq(10, 20);
status += test_kernel_left_pluq(10, 80);
status += test_kernel_left_pluq(70, 20);
status += test_kernel_left_pluq(70, 80);
status += test_kernel_left_pluq(70, 20);
status += test_kernel_left_pluq(70, 80);
status += test_kernel_left_pluq(770, 1600);
status += test_kernel_left_pluq(1764, 1345);
if (!status) {
printf("All tests passed.\n");
} else {
return 1;
}
return 0;
}
|
yp/Heu-MCHC
|
include/gen-ped-IO.h
|
<filename>include/gen-ped-IO.h<gh_stars>1-10
/**
*
*
* Heu-MCHC
*
* A fast and accurate heuristic algorithm for the haplotype inference
* problem on pedigree data with recombinations and mutations
*
* Copyright (C) 2009,2010,2011 <NAME>
*
* Distributed under the terms of the GNU General Public License (GPL)
*
*
* This file is part of Heu-MCHC.
*
* Heu-MCHC is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Heu-MCHC is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Heu-MCHC. If not, see <http://www.gnu.org/licenses/>.
*
**/
#ifndef _GEN_PED_IO_H_
#define _GEN_PED_IO_H_
#ifdef __cplusplus
extern "C" {
#endif
#include <stdio.h>
/**
*
* Define the structure of a genotyped pedigree.
*
**/
#define GEN0 (0)
#define GEN1 (1)
#define GEN2 (2)
struct _indiv {
int id; // individual id
struct _indiv * f; // father (NULL if founder)
struct _indiv * m; // mother (NULL if founder)
int fi; // id of the father (-1 if founder)
int mi; // id of the mother (-1 if founder)
int* g; // genotype vector
int* p; // phase vector
int* df; // mutation vector from father
int* dm; // mutation vector from mother
int* rf; // recombination vector from father
int* rm; // recombination vector from mother
int h_f; // haplotype inherithed from the father
int h_m; // haplotype inherithed from the mother
int* hv_f; // haplotype vector inherited from the father
int* hv_m; // haplotype vector inherited from the mother
unsigned int n_children;
struct _indiv ** children;
};
typedef struct _indiv* pindiv;
pindiv indiv_create(const int n_loci, const int n_individuals);
void indiv_destroy(pindiv pi);
struct _genped {
unsigned int n_loci;
unsigned int n_indiv;
pindiv* individuals;
};
typedef struct _genped * pgenped;
pgenped gp_create(const int n_loci, const int n_individuals);
void gp_destroy(pgenped gp);
void gp_add_trio(pgenped gp,
const unsigned int fi,
const unsigned int mi,
const unsigned int ci);
pgenped gp_read_from_file(FILE* fin);
pgenped gp_copy(pgenped src);
#ifdef __cplusplus
}
#endif
#endif // _GEN_PED_IO_H_
|
yp/Heu-MCHC
|
pers-lib/m4ri/src/pluq_mmpf.h
|
<filename>pers-lib/m4ri/src/pluq_mmpf.h
/**
* \file lqup_mmpf.h
* \brief LQUP factorization using Gray codes.
*
*
* \author <NAME> <<EMAIL>>
*
* \example testsuite/test_lqup.c
*/
#ifndef LQUP_MMPF_H
#define LQUP_MMPF_H
/*******************************************************************
*
* M4RI: Linear Algebra over GF(2)
*
* Copyright (C) 2008 <NAME> <<EMAIL>>
*
* Distributed under the terms of the GNU General Public License (GPL)
* version 2 or higher.
*
* This code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* The full text of the GPL is available at:
*
* http://www.gnu.org/licenses/
*
********************************************************************/
#include "packedmatrix.h"
#include "permutation.h"
/**
* \brief LQUP matrix decomposition of A using Gray codes.
*
* If (L,Q,U,P) satisfy LQUP = A^T, this function returns
* (L,Q^T,U,P). The matrix L and U are stored in place over A.
*
* \param A Matrix.
* \param P Preallocated row permutation.
* \param Q Preallocated column permutation.
* \param k Size of Gray code tables.
*
* \wordoffset
*
* \return Rank of A.
*/
size_t _mzd_lqup_mmpf(mzd_t *A, mzp_t * P, mzp_t * Q, int k);
/**
* \brief PLUQ matrix decomposition of A using Gray codes.
*
* If (P,L,U,Q) satisfy PLUQ = A, it returns (P, L, U, Q^T).
*
* \param A Matrix.
* \param P Preallocated row permutation.
* \param Q Preallocated column permutation.
* \param k Size of Gray code tables.
*
* \wordoffset
*
* \return Rank of A.
*/
size_t _mzd_pluq_mmpf(mzd_t *A, mzp_t * P, mzp_t * Q, int k);
/**
* \brief LQUP matrix decomposition of a submatrix for up to k columns
* starting at (r,c).
*
* Updates P and Q and modifies A in place. The buffer done afterwards
* holds how far a particular row was already added.
*
* \param A Matrix.
* \param start_row Row Offset.
* \param stop_row Up to which row the matrix should be processed (exclusive).
* \param start_col Column Offset.
* \param k Size of Gray code tables.
* \param P Preallocated row permutation.
* \param Q Preallocated column permutation.
* \param done Preallocated temporary buffer.
* \param done_row Stores the last row which is already reduced processed after function execution.
*
* \retval kbar Maximum k for which a pivot could be found.
*/
size_t _mzd_lqup_submatrix(mzd_t *A, size_t start_row, size_t stop_row, size_t start_col, int k, mzp_t *P, mzp_t *Q, size_t *done, size_t *done_row);
#endif //LQUP_MMPF_H
|
yp/Heu-MCHC
|
pers-lib/m4ri/src/grayflex.c
|
<reponame>yp/Heu-MCHC
/******************************************************************************
*
* M4RI: Linear Algebra over GF(2)
*
* Copyright (C) 2007 <NAME> <<EMAIL>>
* Copyright (C) 2007 <NAME> <<EMAIL>>
*
* Distributed under the terms of the GNU General Public License (GPL)
* version 2 or higher.
*
* This code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* The full text of the GPL is available at:
*
* http://www.gnu.org/licenses/
******************************************************************************/
#include "grayflex.h"
#include <stdio.h>
code **codebook = NULL;
int m4ri_swap_bits(int v,int length) {
unsigned int r = v; /* r will be reversed bits of v; first get LSB of v */
int s = length - 1; /* extra shift needed at end */
for (v >>= 1; v; v >>= 1) {
r <<= 1;
r |= v & 1;
s--;
}
r <<= s;
return r;
}
int m4ri_gray_code(int number, int length) {
int lastbit = 0;
int res = 0;
int i,bit;
for(i=length-1; i>=0; i--) {
bit = number & (1<<i);
res |= ((lastbit>>1) ^ bit);
lastbit = bit;
};
return m4ri_swap_bits(res,length) & ((1<<length)-1);
}
void m4ri_build_code(int *ord, int *inc, int l) {
int i,j;
for(i=0 ; i < TWOPOW(l) ; i++) {
ord[i] = m4ri_gray_code(i, l);
}
for(i = l ; i>0 ; i--) {
for(j=1 ; j < TWOPOW(i) + 1 ; j++) {
inc[j *TWOPOW(l-i) -1 ] = l - i;
}
}
}
void m4ri_build_all_codes() {
if (codebook) {
return;
}
int k;
codebook=(code**)m4ri_mm_calloc(MAXKAY+1, sizeof(code *));
for(k=1 ; k<MAXKAY+1; k++) {
codebook[k] = (code *)m4ri_mm_calloc(sizeof(code),1);
codebook[k]->ord =(int *)m4ri_mm_calloc(TWOPOW(k),sizeof(int));
codebook[k]->inc =(int *)m4ri_mm_calloc(TWOPOW(k),sizeof(int));
m4ri_build_code(codebook[k]->ord, codebook[k]->inc, k);
}
}
void m4ri_destroy_all_codes() {
int i;
if (!codebook) {
return;
}
for(i=1; i<MAXKAY+1; i++) {
m4ri_mm_free(codebook[i]->inc);
m4ri_mm_free(codebook[i]->ord);
m4ri_mm_free(codebook[i]);
}
m4ri_mm_free(codebook);
codebook = NULL;
}
static inline int log2_floor(int n){
int i;
for(i=0;TWOPOW(i)<=n;i++){}
return i;
}
int m4ri_opt_k(int a,int b,int c) {
int n = MIN(a,b);
int res = MIN( MAXKAY, MAX(1, (int)(0.75*log2_floor(n))) );
return res;
}
|
yp/Heu-MCHC
|
pers-lib/m4ri/src/permutation.c
|
/******************************************************************************
*
* M4RI: Linear Algebra over GF(2)
*
* Copyright (C) 2008 <NAME> <<EMAIL>>
*
* Distributed under the terms of the GNU General Public License (GPL)
* version 2 or higher.
*
* This code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* The full text of the GPL is available at:
*
* http://www.gnu.org/licenses/
******************************************************************************/
#include "permutation.h"
#include "packedmatrix.h"
mzp_t *mzp_init(size_t length) {
size_t i;
mzp_t *P = (mzp_t*)m4ri_mm_malloc(sizeof(mzp_t));
P->values = (size_t*)m4ri_mm_malloc(sizeof(size_t)*length);
P->length = length;
for (i=0; i<length; i++) {
P->values[i] = i;
}
return P;
}
void mzp_free(mzp_t *P) {
m4ri_mm_free(P->values);
m4ri_mm_free(P);
}
mzp_t *mzp_init_window(mzp_t* P, size_t begin, size_t end){
mzp_t *window = (mzp_t *)m4ri_mm_malloc(sizeof(mzp_t));
window->values = P->values + begin;
window->length = end-begin;
return window;
}
void mzp_free_window(mzp_t* condemned){
m4ri_mm_free(condemned);
}
void mzp_set_ui(mzp_t *P, unsigned int value) {
size_t i;
for (i=0; i<P->length; i++) {
P->values[i] = i;
}
}
void mzd_apply_p_left(mzd_t *A, mzp_t *P) {
size_t i;
if(A->ncols == 0)
return;
const size_t length = MIN(P->length, A->nrows);
for (i=0; i<length; i++) {
assert(P->values[i] >= i);
mzd_row_swap(A, i, P->values[i]);
}
}
void mzd_apply_p_left_trans(mzd_t *A, mzp_t *P) {
long i;
if(A->ncols == 0)
return;
const size_t length = MIN(P->length, A->nrows);
for (i=length-1; i>=0; i--) {
assert(P->values[i] >= (size_t)i);
mzd_row_swap(A, i, P->values[i]);
}
}
/* optimised column swap operations */
static inline void mzd_write_col_to_rows_blockd(mzd_t *A, mzd_t *B, size_t *permutation, word *write_mask, const size_t start_row, const size_t stop_row, size_t length) {
assert(A->offset == 0);
for(size_t i=0; i<length; i+=RADIX) {
/* optimisation for identity permutations */
if (write_mask[i/RADIX] == FFFF)
continue;
const size_t todo = MIN(RADIX,length-i);
const size_t a_word = (A->offset+i)/RADIX;
size_t words[RADIX];
size_t bits[RADIX];
word bitmasks[RADIX];
/* we pre-compute bit access in advance */
for(size_t k=0;k<todo; k++) {
const size_t colb = permutation[i+k] + B->offset;
words[k] = colb/RADIX;
bits[k] = colb%RADIX;
bitmasks[k] = (ONE<<(RADIX - (bits[k]) - 1));
}
for (size_t r=start_row; r<stop_row; r++) {
word *Brow = B->rows[r-start_row];
word *Arow = A->rows[r];
register word value = 0;
/* we gather the bits in a register word */
switch(todo-1) {
case 63: value |= ((Brow[words[63]] & bitmasks[63]) << bits[63]) >> 63;
case 62: value |= ((Brow[words[62]] & bitmasks[62]) << bits[62]) >> 62;
case 61: value |= ((Brow[words[61]] & bitmasks[61]) << bits[61]) >> 61;
case 60: value |= ((Brow[words[60]] & bitmasks[60]) << bits[60]) >> 60;
case 59: value |= ((Brow[words[59]] & bitmasks[59]) << bits[59]) >> 59;
case 58: value |= ((Brow[words[58]] & bitmasks[58]) << bits[58]) >> 58;
case 57: value |= ((Brow[words[57]] & bitmasks[57]) << bits[57]) >> 57;
case 56: value |= ((Brow[words[56]] & bitmasks[56]) << bits[56]) >> 56;
case 55: value |= ((Brow[words[55]] & bitmasks[55]) << bits[55]) >> 55;
case 54: value |= ((Brow[words[54]] & bitmasks[54]) << bits[54]) >> 54;
case 53: value |= ((Brow[words[53]] & bitmasks[53]) << bits[53]) >> 53;
case 52: value |= ((Brow[words[52]] & bitmasks[52]) << bits[52]) >> 52;
case 51: value |= ((Brow[words[51]] & bitmasks[51]) << bits[51]) >> 51;
case 50: value |= ((Brow[words[50]] & bitmasks[50]) << bits[50]) >> 50;
case 49: value |= ((Brow[words[49]] & bitmasks[49]) << bits[49]) >> 49;
case 48: value |= ((Brow[words[48]] & bitmasks[48]) << bits[48]) >> 48;
case 47: value |= ((Brow[words[47]] & bitmasks[47]) << bits[47]) >> 47;
case 46: value |= ((Brow[words[46]] & bitmasks[46]) << bits[46]) >> 46;
case 45: value |= ((Brow[words[45]] & bitmasks[45]) << bits[45]) >> 45;
case 44: value |= ((Brow[words[44]] & bitmasks[44]) << bits[44]) >> 44;
case 43: value |= ((Brow[words[43]] & bitmasks[43]) << bits[43]) >> 43;
case 42: value |= ((Brow[words[42]] & bitmasks[42]) << bits[42]) >> 42;
case 41: value |= ((Brow[words[41]] & bitmasks[41]) << bits[41]) >> 41;
case 40: value |= ((Brow[words[40]] & bitmasks[40]) << bits[40]) >> 40;
case 39: value |= ((Brow[words[39]] & bitmasks[39]) << bits[39]) >> 39;
case 38: value |= ((Brow[words[38]] & bitmasks[38]) << bits[38]) >> 38;
case 37: value |= ((Brow[words[37]] & bitmasks[37]) << bits[37]) >> 37;
case 36: value |= ((Brow[words[36]] & bitmasks[36]) << bits[36]) >> 36;
case 35: value |= ((Brow[words[35]] & bitmasks[35]) << bits[35]) >> 35;
case 34: value |= ((Brow[words[34]] & bitmasks[34]) << bits[34]) >> 34;
case 33: value |= ((Brow[words[33]] & bitmasks[33]) << bits[33]) >> 33;
case 32: value |= ((Brow[words[32]] & bitmasks[32]) << bits[32]) >> 32;
case 31: value |= ((Brow[words[31]] & bitmasks[31]) << bits[31]) >> 31;
case 30: value |= ((Brow[words[30]] & bitmasks[30]) << bits[30]) >> 30;
case 29: value |= ((Brow[words[29]] & bitmasks[29]) << bits[29]) >> 29;
case 28: value |= ((Brow[words[28]] & bitmasks[28]) << bits[28]) >> 28;
case 27: value |= ((Brow[words[27]] & bitmasks[27]) << bits[27]) >> 27;
case 26: value |= ((Brow[words[26]] & bitmasks[26]) << bits[26]) >> 26;
case 25: value |= ((Brow[words[25]] & bitmasks[25]) << bits[25]) >> 25;
case 24: value |= ((Brow[words[24]] & bitmasks[24]) << bits[24]) >> 24;
case 23: value |= ((Brow[words[23]] & bitmasks[23]) << bits[23]) >> 23;
case 22: value |= ((Brow[words[22]] & bitmasks[22]) << bits[22]) >> 22;
case 21: value |= ((Brow[words[21]] & bitmasks[21]) << bits[21]) >> 21;
case 20: value |= ((Brow[words[20]] & bitmasks[20]) << bits[20]) >> 20;
case 19: value |= ((Brow[words[19]] & bitmasks[19]) << bits[19]) >> 19;
case 18: value |= ((Brow[words[18]] & bitmasks[18]) << bits[18]) >> 18;
case 17: value |= ((Brow[words[17]] & bitmasks[17]) << bits[17]) >> 17;
case 16: value |= ((Brow[words[16]] & bitmasks[16]) << bits[16]) >> 16;
case 15: value |= ((Brow[words[15]] & bitmasks[15]) << bits[15]) >> 15;
case 14: value |= ((Brow[words[14]] & bitmasks[14]) << bits[14]) >> 14;
case 13: value |= ((Brow[words[13]] & bitmasks[13]) << bits[13]) >> 13;
case 12: value |= ((Brow[words[12]] & bitmasks[12]) << bits[12]) >> 12;
case 11: value |= ((Brow[words[11]] & bitmasks[11]) << bits[11]) >> 11;
case 10: value |= ((Brow[words[10]] & bitmasks[10]) << bits[10]) >> 10;
case 9: value |= ((Brow[words[ 9]] & bitmasks[ 9]) << bits[ 9]) >> 9;
case 8: value |= ((Brow[words[ 8]] & bitmasks[ 8]) << bits[ 8]) >> 8;
case 7: value |= ((Brow[words[ 7]] & bitmasks[ 7]) << bits[ 7]) >> 7;
case 6: value |= ((Brow[words[ 6]] & bitmasks[ 6]) << bits[ 6]) >> 6;
case 5: value |= ((Brow[words[ 5]] & bitmasks[ 5]) << bits[ 5]) >> 5;
case 4: value |= ((Brow[words[ 4]] & bitmasks[ 4]) << bits[ 4]) >> 4;
case 3: value |= ((Brow[words[ 3]] & bitmasks[ 3]) << bits[ 3]) >> 3;
case 2: value |= ((Brow[words[ 2]] & bitmasks[ 2]) << bits[ 2]) >> 2;
case 1: value |= ((Brow[words[ 1]] & bitmasks[ 1]) << bits[ 1]) >> 1;
case 0: value |= ((Brow[words[ 0]] & bitmasks[ 0]) << bits[ 0]) >> 0;
default:
break;
}
/* for(register size_t k=0; k<todo; k++) { */
/* value |= ((Brow[words[k]] & bitmasks[k]) << bits[k]) >> k; */
/* } */
/* and write the word once */
Arow[a_word] |= value;
}
}
}
/**
* Implements both apply_p_right and apply_p_right_trans.
*/
void _mzd_apply_p_right_even(mzd_t *A, mzp_t *P, size_t start_row, size_t start_col, int notrans) {
assert(A->offset == 0);
if(A->nrows - start_row == 0)
return;
const size_t length = MIN(P->length,A->ncols);
const size_t width = A->width;
size_t step_size = MIN(A->nrows-start_row, MAX((CPU_L1_CACHE>>3)/A->width,1));
/* our temporary where we store the columns we want to swap around */
mzd_t *B = mzd_init(step_size, A->ncols);
word *Arow;
word *Brow;
/* setup mathematical permutation */
size_t *permutation = (size_t *)m4ri_mm_calloc(sizeof(size_t),A->ncols);
for(size_t i=0; i<A->ncols; i++)
permutation[i] = i;
if (!notrans) {
for(size_t i=start_col; i<length; i++) {
size_t t = permutation[i];
permutation[i] = permutation[P->values[i]];
permutation[P->values[i]] = t;
}
} else {
for(size_t i=start_col; i<length; i++) {
size_t t = permutation[length-i-1];
permutation[length-i-1] = permutation[P->values[length-i-1]];
permutation[P->values[length-i-1]] = t;
}
}
/* we have a bitmask to encode where to write to */
word *write_mask = (word*)m4ri_mm_calloc(sizeof(word), length);
for(size_t i=0; i<A->ncols; i+=RADIX) {
const size_t todo = MIN(RADIX,A->ncols-i);
for(size_t k=0; k<todo; k++) {
if(permutation[i+k] == i+k) {
write_mask[i/RADIX] |= ONE<<(RADIX - k - 1);
}
}
}
for(size_t i=start_row; i<A->nrows; i+=step_size) {
step_size = MIN(step_size, A->nrows-i);
for(size_t k=0; k<step_size; k++) {
Arow = A->rows[i+k];
Brow = B->rows[k];
/*copy row & clear those values which will be overwritten */
for(size_t j=0; j<width; j++) {
Brow[j] = Arow[j];
Arow[j] = Arow[j] & write_mask[j];
}
}
/* here we actually write out the permutation */
mzd_write_col_to_rows_blockd(A, B, permutation, write_mask, i, i+step_size, length);
}
m4ri_mm_free(permutation);
m4ri_mm_free(write_mask);
mzd_free(B);
}
void _mzd_apply_p_right_trans(mzd_t *A, mzp_t *P) {
size_t i;
if(A->nrows == 0)
return;
const size_t length = MIN(P->length, A->ncols);
const size_t step_size = MAX((CPU_L1_CACHE>>3)/A->width,1);
for(size_t j=0; j<A->nrows; j+=step_size) {
size_t stop_row = MIN(j+step_size, A->nrows);
for (i=0; i<length; ++i) {
assert(P->values[i] >= i);
mzd_col_swap_in_rows(A, i, P->values[i], j, stop_row);
}
}
/* for (i=0; i<P->length; i++) { */
/* assert(P->values[i] >= i); */
/* mzd_col_swap(A, i, P->values[i]); */
/* } */
}
void _mzd_apply_p_right(mzd_t *A, mzp_t *P) {
int i;
if(A->nrows == 0)
return;
const size_t step_size = MAX((CPU_L1_CACHE>>3)/A->width,1);
for(size_t j=0; j<A->nrows; j+=step_size) {
size_t stop_row = MIN(j+step_size, A->nrows);
for (i=P->length-1; i>=0; --i) {
assert(P->values[i] >= (size_t)i);
mzd_col_swap_in_rows(A, i, P->values[i], j, stop_row);
}
}
/* long i; */
/* for (i=P->length-1; i>=0; i--) { */
/* assert(P->values[i] >= i); */
/* mzd_col_swap(A, i, P->values[i]); */
/* } */
}
void mzd_apply_p_right_trans(mzd_t *A, mzp_t *P) {
if(!A->nrows)
return;
if(A->offset) {
_mzd_apply_p_right_trans(A,P);
return;
}
_mzd_apply_p_right_even(A, P, 0, 0, 0);
}
void mzd_apply_p_right(mzd_t *A, mzp_t *P) {
if(!A->nrows)
return;
if(A->offset) {
_mzd_apply_p_right(A,P);
return;
}
_mzd_apply_p_right_even(A, P, 0, 0, 1);
}
void mzd_apply_p_right_trans_even_capped(mzd_t *A, mzp_t *P, size_t start_row, size_t start_col) {
assert(A->offset == 0);
if(!A->nrows)
return;
_mzd_apply_p_right_even(A, P, start_row, start_col, 0);
}
void mzd_apply_p_right_even_capped(mzd_t *A, mzp_t *P, size_t start_row, size_t start_col) {
assert(A->offset == 0);
if(!A->nrows)
return;
_mzd_apply_p_right_even(A, P, start_row, start_col, 1);
}
/* void mzd_col_block_rotate(mzd_t *M, size_t zs, size_t ze, size_t de) { */
/* size_t i,j; */
/* const size_t ds = ze; */
/* /\* const size_t ld_f = (de - ds)/RADIX; *\/ */
/* /\* const size_t ld_r = (de - ds)%RADIX; *\/ */
/* const size_t lz_f = (ze - zs)/RADIX; */
/* const size_t lz_r = (ze - zs)%RADIX; */
/* const size_t le_f = (M->ncols - de)/RADIX; */
/* const size_t le_r = (M->ncols - de)%RADIX; */
/* size_t n1 = ze; */
/* size_t r1 = zs; */
/* size_t r2 = de - ds; */
/* for(i=0; i<M->nrows; i++) { */
/* /\* for(j=0; j < i; j++) /\\* copy out *\\/ *\/ */
/* /\* data->rows[0][j] = M->rows[i][j]; *\/ */
/* /\* write *\/ */
/* size_t im = (i+1<r2)?i+1:r2; */
/* size_t ld_f = im / RADIX; */
/* size_t ld_r = im % RADIX; */
/* for(j=0; j<ld_f; j++) { */
/* mzd_clear_bits(M, i, zs + j*RADIX, RADIX); */
/* mzd_xor_bits(M, i, zs + j*RADIX, RADIX, mzd_read_bits(M,i,ds+j*RADIX,RADIX)); */
/* } */
/* if(ld_r) { */
/* mzd_clear_bits(M, i, zs + ld_f*RADIX, ld_r); */
/* mzd_xor_bits(M, i, zs + ld_f*RADIX, ld_r, mzd_read_bits(M,i,ds+ld_f*RADIX,ld_r)); */
/* } */
/* //mzd_write_bit(M,i,i+r1,1); */
/* /\* Placing zeros *\/ */
/* for (j = r1+im; j<n1+im; ++j) */
/* mzd_write_bit(M,i,j,0); */
/* } */
/* // mzd_free(data); */
/* } */
void mzp_print(mzp_t *P) {
printf("[ ");
for(size_t i=0; i<P->length; i++) {
printf("%zu ",P->values[i]);
}
printf("]");
}
#if 0
void mzd_apply_p_right_tri (mzd_t * A, mzp_t * P, size_t rank){
assert(P->length==A->ncols);
for (size_t i =0 ; i<P->length; ++i) {
assert(P->values[i] >= i);
if (P->values[i] > i) {
mzd_col_swap_in_rows(A, i, P->values[i], 0, i);
}
}
}
#else
void mzd_apply_p_right_tri(mzd_t *A, mzp_t *P) {
assert(P->length==A->ncols);
const size_t step_size = MAX((CPU_L1_CACHE>>2)/A->width,1);
for(size_t r=0; r<A->nrows; r+=step_size) {
const size_t row_bound = MIN(r+step_size, A->nrows);
for (size_t i =0 ; i<A->ncols; ++i) {
assert(P->values[i] >= i);
if (P->values[i] > i) {
mzd_col_swap_in_rows(A, i, P->values[i], r, MIN(row_bound,i));
}
}
}
}
#endif
|
yp/Heu-MCHC
|
pers-lib/m4ri/src/lqup.h
|
/**
* \file lqup.h
*
* \brief PLUQ matrix decomposition routines.
*
* \author <NAME> <<EMAIL>>
*
* \note This file should be called pluq.h and will be renamed in the
* future.
*/
#ifndef PLUQ_H
#define PLUQ_H
/*******************************************************************
*
* M4RI: Linear Algebra over GF(2)
*
* Copyright (C) 2008 <NAME> <<EMAIL>>
*
* Distributed under the terms of the GNU General Public License (GPL)
* version 2 or higher.
*
* This code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* The full text of the GPL is available at:
*
* http://www.gnu.org/licenses/
*
********************************************************************/
#include "misc.h"
#include "packedmatrix.h"
/**
* Crossover point for PLUQ factorization.
*/
#define LQUP_CUTOFF MIN(524288,CPU_L2_CACHE>>3)
/**
* \brief PLUQ matrix decomposition.
*
* If (P,L,U,Q) satisfy PLUQ = A, it returns (P, L, U, Q^T).
*
* P and Q must be preallocated but they don't have to be
* identity permutations. If cutoff is zero a value is chosen
* automatically. It is recommended to set cutoff to zero for most
* applications.
*
* The row echelon form (not reduced) can be read from the upper
* triangular matrix U. See mzd_echelonize_pluq() for details.
*
* This is the wrapper function including bounds checks. See
* _mzd_pluq() for implementation details.
*
* \param A Input m x n matrix
* \param P Output row permutation of length m
* \param Qt Output column permutation matrix of length n
* \param cutoff Minimal dimension for Strassen recursion.
*
* \sa _mzd_pluq() _mzd_pluq_mmpf() mzd_echelonize_pluq()
*
* \wordoffset
*
* \return Rank of A.
*/
size_t mzd_pluq(mzd_t *A, mzp_t *P, mzp_t * Qt, const int cutoff);
/**
* \brief LQUP matrix decomposition.
*
* Computes the transposed LQUP matrix decomposition using a block
* recursive algorithm.
*
* If (L,Q,U,P) satisfy LQUP = A^T, it returns (L, Q^T, U, P).
*
* P and Qt must be preallocated but they don't have to be
* identity permutations. If cutoff is zero a value is chosen
* automatically. It is recommended to set cutoff to zero for most
* applications.
*
* This is the wrapper function including bounds checks. See
* _mzd_lqup() for implementation details.
*
* \param A Input m x n matrix
* \param P Output row permutation of length m
* \param Qt Output column permutation matrix of length n
* \param cutoff Minimal dimension for Strassen recursion.
*
* \sa _mzd_lqup() _mzd_pluq() _mzd_pluq_mmpf() mzd_echelonize_pluq()
*
* \wordoffset
*
* \return Rank of A.
*/
size_t mzd_lqup(mzd_t *A, mzp_t *P, mzp_t * Q, const int cutoff);
/**
* \brief PLUQ matrix decomposition.
*
* See mzd_pluq() for details.
*
* \param A Input matrix
* \param P Output row mzp_t matrix
* \param Q Output column mzp_t matrix
* \param cutoff Minimal dimension for Strassen recursion.
*
* \sa mzd_pluq()
*
* \wordoffset
* \return Rank of A.
*/
size_t _mzd_pluq(mzd_t *A, mzp_t * P, mzp_t * Q, const int cutoff);
/**
* \brief LQUP matrix decomposition.
*
* See mzd_lqup() for details.
*
* \param A Input matrix
* \param P Output row mzp_t matrix
* \param Qt Output column mzp_t matrix
* \param cutoff Minimal dimension for Strassen recursion.
*
* \sa mzd_lqup()
*
* \wordoffset
* \return Rank of A.
*/
size_t _mzd_lqup(mzd_t *A, mzp_t * P, mzp_t * Qt, const int cutoff);
/**
* \brief PLUQ matrix decomposition (naive base case).
*
* See mzd_pluq() for details.
*
* \param A Input matrix
* \param P Output row mzp_t matrix
* \param Q Output column mzp_t matrix
*
* \sa mzd_pluq()
*
* \wordoffset
* \return Rank of A.
*/
size_t _mzd_pluq_naive(mzd_t *A, mzp_t * P, mzp_t * Q);
/**
* \brief LQUP matrix decomposition (naive base case).
*
* See mzd_lqup() for details.
*
* \param A Input matrix
* \param P Output row mzp_t matrix
* \param Qt Output column mzp_t matrix
*
* \sa mzd_lqup()
*
* \wordoffset
* \return Rank of A.
*/
size_t _mzd_lqup_naive(mzd_t *A, mzp_t *P, mzp_t *Qt);
/**
* \brief (Reduced) row echelon form using PLUQ factorisation.
*
* \param A Matrix.
* \param full Return the reduced row echelon form, not only upper triangular form.
*
* \wordoffset
*
* \sa mzd_pluq()
*
* \return Rank of A.
*/
size_t mzd_echelonize_pluq(mzd_t *A, int full);
#endif
|
yp/Heu-MCHC
|
pers-lib/m4ri/src/trsm.c
|
/*******************************************************************
*
* M4RI: Linear Algebra over GF(2)
*
* Copyright (C) 2008 <NAME> <<EMAIL>>
*
* Distributed under the terms of the GNU General Public License (GPL)
* version 2 or higher.
*
* This code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* The full text of the GPL is available at:
*
* http://www.gnu.org/licenses/
*
********************************************************************/
#include "trsm.h"
#include "strassen.h"
#include "packedmatrix.h"
#include "misc.h"
#include "parity.h"
#include "stdio.h"
#define TRSM_THRESHOLD RADIX
/*****************
* UPPER RIGHT
****************/
/*
* This version assumes that the matrices are at an even position on
* the RADIX grid and that their dimension is a multiple of RADIX.
*/
void _mzd_trsm_upper_right_even(mzd_t *U, mzd_t *B, const int cutoff);
/*
* Variant where U and B start at an odd bit position. Assumes that
* U->ncols < 64
*/
void _mzd_trsm_upper_right_weird(mzd_t *U, mzd_t *B, const int cutoff);
void _mzd_trsm_upper_right_base(mzd_t* U, mzd_t* B, const int cutoff);
void mzd_trsm_upper_right(mzd_t *U, mzd_t *B, const int cutoff) {
if(U->nrows != B->ncols)
m4ri_die("mzd_trsm_upper_right: U nrows (%d) need to match B ncols (%d).\n", U->nrows, B->ncols);
if(U->nrows != U->ncols)
m4ri_die("mzd_trsm_upper_right: U must be square and is found to be (%d) x (%d).\n", U->nrows, U->ncols);
_mzd_trsm_upper_right(U, B, cutoff);
}
void _mzd_trsm_upper_right(mzd_t *U, mzd_t *B, const int cutoff) {
size_t nb = B->ncols;
size_t mb = B->nrows;
size_t n1 = RADIX-B->offset;
if (nb <= n1) {
_mzd_trsm_upper_right_weird(U, B, cutoff);
return;
}
/**
\verbatim
_________
\U00| |
\ |U01|
\ | |
\|___|
\U11|
\ |
\ |
\|
_______
|B0 |B1 |
|___|___|
\endverbatim
* \li U00 and B0 are possibly located at uneven locations.
* \li Their column dimension is lower than 64.
* \li The first column of U01, U11, B1 are aligned at words.
*/
mzd_t *B0 = mzd_init_window (B, 0, 0, mb, n1);
mzd_t *B1 = mzd_init_window (B, 0, n1, mb, nb);
mzd_t *U00 = mzd_init_window (U, 0, 0, n1, n1);
mzd_t *U01 = mzd_init_window (U, 0, n1, n1, nb);
mzd_t *U11 = mzd_init_window (U, n1, n1, nb, nb);
_mzd_trsm_upper_right_weird (U00, B0, cutoff);
mzd_addmul (B1, B0, U01, cutoff);
_mzd_trsm_upper_right_even (U11, B1, cutoff);
mzd_free_window(B0);
mzd_free_window(B1);
mzd_free_window(U00);
mzd_free_window(U01);
mzd_free_window(U11);
}
void _mzd_trsm_upper_right_weird(mzd_t *U, mzd_t *B, const int cutoff) {
size_t mb = B->nrows;
size_t nb = B->ncols;
size_t offset = B->offset;
for (size_t i=1; i < nb; ++i) {
/* Computes X_i = B_i + X_{0..i-1} U_{0..i-1,i} */
register word ucol = 0;
for (size_t k=0; k<i; ++k) {
if (GET_BIT (U->rows[k][0], i + U->offset))
SET_BIT (ucol, k+offset);
}
/* doing 64 dotproducts at a time, to use the parity64 parallelism */
size_t giantstep;
word tmp[64];
for (giantstep = 0; giantstep + RADIX < mb; giantstep += RADIX) {
for (size_t babystep = 0; babystep < RADIX; ++babystep)
tmp[babystep] = B->rows[babystep + giantstep][0] & ucol;
word dotprod = parity64 (tmp);
for (size_t babystep = 0; babystep < RADIX; ++babystep)
if (GET_BIT (dotprod, babystep))
FLIP_BIT(B->rows[giantstep + babystep][0], i + offset);
}
for (size_t babystep = 0; babystep < mb - giantstep; ++babystep){
tmp [babystep] = B->rows[babystep + giantstep][0] & ucol;
}
for (size_t babystep = mb-giantstep; babystep < 64; ++babystep){
tmp [babystep] = 0;
}
word dotprod = parity64 (tmp);
for (size_t babystep = 0; babystep < mb - giantstep; ++babystep)
if (GET_BIT (dotprod, babystep))
FLIP_BIT (B->rows[giantstep + babystep ][0], i + offset);
}
}
void _mzd_trsm_upper_right_even(mzd_t *U, mzd_t *B, const int cutoff) {
size_t mb = B->nrows;
size_t nb = B->ncols;
if (nb <= TRSM_THRESHOLD) {
/* base case */
_mzd_trsm_upper_right_base (U, B, cutoff);
return;
}
size_t nb1 = (((nb-1) / RADIX + 1) >> 1) * RADIX;
mzd_t *B0 = mzd_init_window(B, 0, 0, mb, nb1);
mzd_t *B1 = mzd_init_window(B, 0, nb1, mb, nb);
mzd_t *U00 = mzd_init_window(U, 0, 0, nb1, nb1);
mzd_t *U01 = mzd_init_window(U, 0, nb1, nb1, nb);
mzd_t *U11 = mzd_init_window(U, nb1, nb1, nb, nb);
_mzd_trsm_upper_right_even (U00, B0, cutoff);
mzd_addmul (B1, B0, U01, cutoff);
_mzd_trsm_upper_right_even (U11, B1, cutoff);
mzd_free_window(B0);
mzd_free_window(B1);
mzd_free_window(U00);
mzd_free_window(U01);
mzd_free_window(U11);
}
void _mzd_trsm_upper_right_base(mzd_t* U, mzd_t* B, const int cutoff) {
size_t mb = B->nrows;
size_t nb = B->ncols;
for (size_t i=1; i < nb; ++i) {
/* Computes X_i = B_i + X_{0..i-1} U_{0..i-1,i} */
register word ucol = 0;
for (size_t k=0; k<i; ++k) {
if (GET_BIT (U->rows[k][0], i))
SET_BIT (ucol, k);
}
/* doing 64 dotproducts at a time, to use the parity64 parallelism */
size_t giantstep;
word tmp[64];
for (giantstep = 0; giantstep + RADIX < mb; giantstep += RADIX) {
for (size_t babystep = 0; babystep < RADIX; ++babystep)
tmp [babystep] = B->rows[babystep + giantstep][0] & ucol;
word dotprod = parity64 (tmp);
for (size_t babystep = 0; babystep < RADIX; ++babystep)
if (GET_BIT (dotprod, babystep))
FLIP_BIT (B->rows[giantstep + babystep][0], i);
}
for (size_t babystep = 0; babystep < mb - giantstep; ++babystep)
tmp [babystep] = B->rows[babystep + giantstep][0] & ucol;
for (size_t babystep = mb-giantstep; babystep < 64; ++babystep)
tmp [babystep] = 0;
word dotprod = parity64 (tmp);
for (size_t babystep = 0; babystep < mb - giantstep; ++babystep)
if (GET_BIT (dotprod, babystep))
FLIP_BIT(B->rows[giantstep + babystep][0], i);
}
}
/*****************
* LOWER RIGHT
****************/
/*
* Variant where L and B start at an odd bit position Assumes that
* L->ncols < 64
*/
void _mzd_trsm_lower_right_weird(mzd_t *L, mzd_t *B, const int cutoff);
/*
* Variant where L and B start at an even bit position Assumes that
* L->ncols < 64
*/
void _mzd_trsm_lower_right_even(mzd_t *L, mzd_t *B, const int cutoff);
void _mzd_trsm_lower_right_base(mzd_t* L, mzd_t* B, const int cutoff);
void mzd_trsm_lower_right(mzd_t *L, mzd_t *B, const int cutoff) {
if(L->nrows != B->ncols)
m4ri_die("mzd_trsm_lower_right: L nrows (%d) need to match B ncols (%d).\n", L->nrows, B->ncols);
if(L->nrows != L->ncols)
m4ri_die("mzd_trsm_lower_right: L must be square and is found to be (%d) x (%d).\n", L->nrows, L->ncols);
_mzd_trsm_lower_right (L, B, cutoff);
}
void _mzd_trsm_lower_right(mzd_t *L, mzd_t *B, const int cutoff) {
size_t nb = B->ncols;
size_t mb = B->nrows;
size_t n1 = RADIX-B->offset;
if (nb <= n1)
_mzd_trsm_lower_right_weird (L, B, cutoff);
else{
/**
\verbatim
|\
| \
| \
|L00\
|____\
| |\
| | \
| | \
|L10 |L11\
|____|____\
_________
|B0 |B1 |
|____|____|
\endverbatim
* \li L00 and B0 are possibly located at uneven locations.
* \li Their column dimension is lower than 64.
* \li The first column of L10, L11, B1 are aligned to words.
*/
mzd_t *B0 = mzd_init_window (B, 0, 0, mb, n1);
mzd_t *B1 = mzd_init_window (B, 0, n1, mb, nb);
mzd_t *L00 = mzd_init_window (L, 0, 0, n1, n1);
mzd_t *L10 = mzd_init_window (L, n1, 0, nb, n1);
mzd_t *L11 = mzd_init_window (L, n1, n1, nb, nb);
_mzd_trsm_lower_right_even (L11, B1, cutoff);
mzd_addmul (B0, B1, L10, cutoff);
_mzd_trsm_lower_right_weird (L00, B0, cutoff);
mzd_free_window(B0);
mzd_free_window(B1);
mzd_free_window(L00);
mzd_free_window(L10);
mzd_free_window(L11);
}
}
void _mzd_trsm_lower_right_weird(mzd_t *L, mzd_t *B, const int cutoff) {
size_t mb = B->nrows;
size_t nb = B->ncols;
size_t offset = B->offset;
for (int i=nb-1; i >=0; --i) {
/* Computes X_i = B_i + X_{i+1,n} L_{i+1..n,i} */
register word ucol = 0;
for (size_t k=i+1; k<nb; ++k) {
if (GET_BIT (L->rows[k][0], i + L->offset))
SET_BIT (ucol, k+offset);
}
/* doing 64 dotproducts at a time, to use the parity64 parallelism */
size_t giantstep;
word tmp[64];
for (giantstep = 0; giantstep + RADIX < mb; giantstep += RADIX) {
for (size_t babystep = 0; babystep < RADIX; ++babystep)
tmp [babystep] = B->rows[babystep + giantstep][0] & ucol;
word dotprod = parity64 (tmp);
for (size_t babystep = 0; babystep < RADIX; ++babystep)
if (GET_BIT (dotprod, babystep))
FLIP_BIT (B->rows[giantstep + babystep][0], i + offset);
}
for (size_t babystep = 0; babystep < mb - giantstep; ++babystep){
tmp [babystep] = B->rows[babystep + giantstep][0] & ucol;
}
for (size_t babystep = mb-giantstep; babystep < 64; ++babystep){
tmp [babystep] = 0;
}
word dotprod = parity64 (tmp);
for (size_t babystep = 0; babystep < mb - giantstep; ++babystep)
if (GET_BIT (dotprod, babystep))
FLIP_BIT (B->rows [giantstep + babystep ][0], i + offset);
}
}
void _mzd_trsm_lower_right_even(mzd_t *L, mzd_t *B, const int cutoff) {
size_t mb = B->nrows;
size_t nb = B->ncols;
if (nb <= TRSM_THRESHOLD){
/* base case */
_mzd_trsm_lower_right_base (L, B, cutoff);
}
else {
size_t nb1 = (((nb-1) / RADIX + 1) >> 1) * RADIX;
mzd_t *B0 = mzd_init_window(B, 0, 0, mb, nb1);
mzd_t *B1 = mzd_init_window(B, 0, nb1, mb, nb);
mzd_t *L00 = mzd_init_window(L, 0, 0, nb1, nb1);
mzd_t *L10 = mzd_init_window(L, nb1, 0, nb, nb1);
mzd_t *L11 = mzd_init_window(L, nb1, nb1, nb, nb);
_mzd_trsm_lower_right_even (L11, B1, cutoff);
mzd_addmul (B0, B1, L10, cutoff);
_mzd_trsm_lower_right_even (L00, B0, cutoff);
mzd_free_window(B0);
mzd_free_window(B1);
mzd_free_window(L00);
mzd_free_window(L10);
mzd_free_window(L11);
}
}
void _mzd_trsm_lower_right_base(mzd_t* L, mzd_t* B, const int cutoff) {
size_t mb = B->nrows;
size_t nb = B->ncols;
for (int i=nb-1; i >=0; --i) {
/* Computes X_i = B_i + X_{i+1,n} L_{i+1..n,i} */
register word ucol = 0;
for (size_t k=i+1; k<nb; ++k) {
if (GET_BIT (L->rows[k][0], i))
SET_BIT (ucol, k);
}
/* doing 64 dotproducts at a time, to use the parity64 parallelism */
size_t giantstep;
word tmp[64];
for (giantstep = 0; giantstep + RADIX < mb; giantstep += RADIX) {
for (size_t babystep = 0; babystep < RADIX; ++babystep)
tmp [babystep] = B->rows[babystep + giantstep][0] & ucol;
word dotprod = parity64 (tmp);
for (size_t babystep = 0; babystep < RADIX; ++babystep)
if (GET_BIT (dotprod, babystep))
FLIP_BIT (B->rows[giantstep + babystep][0], i);
}
for (size_t babystep = 0; babystep < mb - giantstep; ++babystep)
tmp [babystep] = B->rows[babystep + giantstep][0] & ucol;
for (size_t babystep = mb-giantstep; babystep < 64; ++babystep)
tmp [babystep] = 0;
word dotprod = parity64 (tmp);
for (size_t babystep = 0; babystep < mb - giantstep; ++babystep)
if (GET_BIT (dotprod, babystep))
FLIP_BIT (B->rows[giantstep + babystep][0], i);
}
}
/*****************
* LOWER LEFT
****************/
/*
* Variant where U and B start at an odd bit position. Assumes that
* L->ncols < 64
*/
void _mzd_trsm_lower_left_weird(mzd_t *L, mzd_t *B, const int cutoff);
/*
* This version assumes that the matrices are at an even position on
* the RADIX grid and that their dimension is a multiple of RADIX.
*/
void _mzd_trsm_lower_left_even(mzd_t *L, mzd_t *B, const int cutoff);
void mzd_trsm_lower_left(mzd_t *L, mzd_t *B, const int cutoff) {
if(L->ncols != B->nrows)
m4ri_die("mzd_trsm_lower_left: L ncols (%d) need to match B nrows (%d).\n", L->ncols, B->nrows);
if(L->nrows != L->ncols)
m4ri_die("mzd_trsm_lower_left: L must be square and is found to be (%d) x (%d).\n", L->nrows, L->ncols);
_mzd_trsm_lower_left (L, B, cutoff);
}
void _mzd_trsm_lower_left(mzd_t *L, mzd_t *B, const int cutoff) {
if (!L->offset)
_mzd_trsm_lower_left_even(L, B, cutoff);
else{
size_t nb = B->ncols;
size_t mb = B->nrows;
size_t m1 = RADIX - L->offset;
if (mb <= m1) {
_mzd_trsm_lower_left_weird (L, B, cutoff);
return;
}
/**
\verbatim
|\ ______
| \ | |
| \ | B0 |
|L00\ | |
|____\ |______|
| |\ | |
| | \ | |
| | \ | B1 |
|L10 |L11\ | |
|____|____\ |______|
\endverbatim
* \li L00 L10 B0 and B1 are possibly located at uneven locations.
* \li Their column dimension is lower than 64.
* \li The first column of L01, L11, B1 are aligned to words.
*/
mzd_t *B0 = mzd_init_window (B, 0, 0, m1, nb);
mzd_t *B1 = mzd_init_window (B, m1, 0, mb, nb);
mzd_t *L00 = mzd_init_window (L, 0, 0, m1, m1);
mzd_t *L10 = mzd_init_window (L, m1, 0, mb, m1);
mzd_t *L11 = mzd_init_window (L, m1, m1, mb, mb);
_mzd_trsm_lower_left_weird (L00, B0, cutoff);
mzd_addmul (B1, L10, B0, cutoff);
_mzd_trsm_lower_left_even (L11, B1, cutoff);
mzd_free_window(B0);
mzd_free_window(B1);
mzd_free_window(L00);
mzd_free_window(L10);
mzd_free_window(L11);
}
}
void _mzd_trsm_lower_left_weird(mzd_t *L, mzd_t *B, const int cutoff) {
size_t mb = B->nrows;
size_t nb = B->ncols;
size_t Boffset = B->offset;
size_t nbrest = (nb + Boffset) % RADIX;
if (nb + B->offset >= RADIX) {
// Large B
word mask_begin = RIGHT_BITMASK(RADIX-B->offset);
word mask_end = LEFT_BITMASK(nbrest);
// L[0,0] = 1, so no work required for i=0
for (size_t i=1; i < mb; ++i) {
/* Computes X_i = B_i + L_{i,0..i-1} X_{0..i-1} */
/**
* \todo needs to be optimized!
**/
word * Lrow = L->rows[i];
word * Brow = B->rows[i];
for (size_t k=0; k<i; ++k) {
if (GET_BIT (Lrow[0], k + L->offset)){
Brow[0] ^= B->rows[k][0] & mask_begin;
for (size_t j = 1; j < B->width-1; ++j)
Brow[j] ^= B->rows[k][j];
Brow[B->width - 1] ^= B->rows[k][B->width - 1] & mask_end;
}
}
}
} else { // Small B
word mask = ((ONE << nb) - 1) ;
mask <<= (RADIX-nb-B->offset);
for (size_t i=1; i < mb; ++i) {
/* Computes X_i = B_i + L_{i,0..i-1} X_{0..i-1} */
/**
* \todo needs to be optimized!
**/
word *Lrow = L->rows[i];
word *Brow = B->rows[i];
for (size_t k=0; k<i; ++k) {
if (GET_BIT (Lrow[0], k + L->offset)){
Brow[0] ^= B->rows[k][0] & mask;
}
}
}
}
}
void _mzd_trsm_lower_left_even(mzd_t *L, mzd_t *B, const int cutoff) {
size_t mb = B->nrows;
size_t nb = B->ncols;
size_t Boffset = B->offset;
size_t nbrest = (nb + Boffset) % RADIX;
if (mb <= RADIX){
/* base case */
if (nb + B->offset > RADIX) {
// B is large
word mask_begin = RIGHT_BITMASK(RADIX-B->offset);
word mask_end = LEFT_BITMASK(nbrest);
for (size_t i=1; i < mb; ++i) {
/* Computes X_i = B_i + L_{i,0..i-1} X_{0..i-1} */
/**
* \todo needs to be optimized!
**/
word *Lrow = L->rows[i];
word *Brow = B->rows[i];
for (size_t k=0; k<i; ++k) {
if (GET_BIT (Lrow[0], k)){
Brow[0] ^= B->rows[k][0] & mask_begin;
for (size_t j = 1; j < B->width-1; ++j)
Brow[j] ^= B->rows[k][j];
Brow[B->width - 1] ^= B->rows[k][B->width - 1] & mask_end;
}
}
}
} else { // B is small
word mask = ((ONE << nb) - 1) ;
if (nb==RADIX)
mask = 0xFFFFFFFFFFFFFFFFll;
mask <<= (RADIX-nb-B->offset);
for (size_t i=1; i < mb; ++i) {
/* Computes X_i = B_i + L_{i,0..i-1} X_{0..i-1} */
/** Need to be optimized !!! **/
word *Lrow = L->rows [i];
word *Brow = B->rows [i];
for (size_t k=0; k<i; ++k) {
if (GET_BIT (Lrow[0], k)){
Brow[0] ^= B->rows[k][0] & mask;
}
}
}
}
} else {
size_t mb1 = (((mb-1) / RADIX + 1) >> 1) * RADIX;
mzd_t *B0 = mzd_init_window(B, 0, 0, mb1, nb);
mzd_t *B1 = mzd_init_window(B, mb1, 0, mb, nb);
mzd_t *L00 = mzd_init_window(L, 0, 0, mb1, mb1);
mzd_t *L10 = mzd_init_window(L, mb1, 0, mb, mb1);
mzd_t *L11 = mzd_init_window(L, mb1, mb1, mb, mb);
_mzd_trsm_lower_left_even (L00, B0, cutoff);
mzd_addmul (B1, L10, B0, cutoff);
_mzd_trsm_lower_left_even (L11, B1, cutoff);
mzd_free_window(B0);
mzd_free_window(B1);
mzd_free_window(L00);
mzd_free_window(L10);
mzd_free_window(L11);
}
}
/*****************
* UPPER LEFT
****************/
/*
* Variant where U and B start at an odd bit position
* Assumes that U->ncols < 64
*/
void _mzd_trsm_upper_left_weird (mzd_t *U, mzd_t *B, const int cutoff);
void _mzd_trsm_upper_left_even(mzd_t *U, mzd_t *B, const int cutoff);
void mzd_trsm_upper_left(mzd_t *U, mzd_t *B, const int cutoff) {
if(U->ncols != B->nrows)
m4ri_die("mzd_trsm_upper_left: U ncols (%d) need to match B nrows (%d).\n", U->ncols, B->nrows);
if(U->nrows != U->ncols)
m4ri_die("mzd_trsm_upper_left: U must be square and is found to be (%d) x (%d).\n", U->nrows, U->ncols);
_mzd_trsm_upper_left (U, B, cutoff);
}
void _mzd_trsm_upper_left(mzd_t *U, mzd_t *B, const int cutoff) {
if (!U->offset)
_mzd_trsm_upper_left_even (U, B, cutoff);
else{
size_t nb = B->ncols;
size_t mb = B->nrows;
size_t m1 = RADIX - U->offset;
if (mb <= m1) {
_mzd_trsm_upper_left_weird (U, B, cutoff);
return;
}
/**
\verbatim
__________ ______
\ U00| | | |
\ |U01 | | |
\ | | | B0 |
\ | | | |
\|____| |______|
\ | | |
\U11| | |
\ | | B1 |
\ | | |
\| |______|
\endverbatim
* \li U00, B0 and B1 are possibly located at uneven locations.
* \li Their column dimension is greater than 64
* \li The first column of U01, U11, B0 and B1 are aligned to words.
*/
mzd_t *B0 = mzd_init_window (B, 0, 0, m1, nb);
mzd_t *B1 = mzd_init_window (B, m1, 0, mb, nb);
mzd_t *U00 = mzd_init_window (U, 0, 0, m1, m1);
mzd_t *U01 = mzd_init_window (U, 0, m1, m1, mb);
mzd_t *U11 = mzd_init_window (U, m1, m1, mb, mb);
_mzd_trsm_upper_left_even (U11, B1, cutoff);
mzd_addmul (B0, U01, B1, cutoff);
_mzd_trsm_upper_left_weird (U00, B0, cutoff);
mzd_free_window(B0);
mzd_free_window(B1);
mzd_free_window(U00);
mzd_free_window(U01);
mzd_free_window(U11);
}
}
void _mzd_trsm_upper_left_weird (mzd_t *U, mzd_t *B, const int cutoff) {
size_t mb = B->nrows;
size_t nb = B->ncols;
size_t Boffset = B->offset;
size_t nbrest = (nb + Boffset) % RADIX;
if (nb + Boffset > RADIX) {
// Large B
word mask_begin = RIGHT_BITMASK(RADIX-B->offset);
word mask_end = LEFT_BITMASK(nbrest);
// U[mb-1,mb-1] = 1, so no work required for i=mb-1
for (int i=mb-2; i >= 0; --i) {
/* Computes X_i = B_i + U_{i,i+1..mb} X_{i+1..mb} */
word *Urow = U->rows[i];
word *Brow = B->rows[i];
for (size_t k=i+1; k<mb; ++k) {
if (GET_BIT (Urow[0], k + U->offset)){
Brow[0] ^= B->rows[k][0] & mask_begin;
for (size_t j = 1; j < B->width-1; ++j)
Brow[j] ^= B->rows[k][j];
Brow[B->width - 1] ^= B->rows[k][B->width - 1] & mask_end;
}
}
}
} else { // Small B
word mask = ((ONE << nb) - 1) ;
mask <<= (RADIX-nb-B->offset);
// U[mb-1,mb-1] = 1, so no work required for i=mb-1
for (int i=mb-2; i >= 0; --i) {
/* Computes X_i = B_i + U_{i,i+1..mb} X_{i+1..mb} */
word *Urow = U->rows[i];
word *Brow = B->rows[i];
for (size_t k=i+1; k<mb; ++k) {
if (GET_BIT (Urow[0], k + U->offset)){
Brow[0] ^= B->rows[k][0] & mask;
}
}
}
}
}
void _mzd_trsm_upper_left_even(mzd_t *U, mzd_t *B, const int cutoff) {
size_t mb = B->nrows;
size_t nb = B->ncols;
size_t Boffset = B->offset;
size_t nbrest = (nb + Boffset) % RADIX;
if (mb <= RADIX){
/* base case */
if (nb + B->offset > RADIX) {
// B is large
word mask_begin = RIGHT_BITMASK(RADIX-B->offset);
word mask_end = LEFT_BITMASK(nbrest);
// U[mb-1,mb-1] = 1, so no work required for i=mb-1
for (int i=mb-2; i >= 0; --i) {
/* Computes X_i = B_i + U_{i,i+1..mb} X_{i+1..mb} */
word* Urow = U->rows[i];
word *Brow = B->rows[i];
for (size_t k=i+1; k<mb; ++k) {
if (GET_BIT (Urow[0], k)){
Brow[0] ^= B->rows[k][0] & mask_begin;
for (size_t j = 1; j < B->width-1; ++j)
Brow[j] ^= B->rows[k][j];
Brow[B->width - 1] ^= B->rows[k][B->width - 1] & mask_end;
}
}
}
} else { // B is small
word mask = ((ONE << nb) - 1) ;
mask <<= (RADIX-nb-B->offset);
// U[mb-1,mb-1] = 1, so no work required for i=mb-1
for (int i=mb-2; i >= 0; --i) {
/* Computes X_i = B_i + U_{i,i+1..mb} X_{i+1..mb} */
word *Urow = U->rows [i];
word *Brow = B->rows [i];
for (size_t k=i+1; k<mb; ++k) {
if (GET_BIT (Urow[0], k)){
Brow[0] ^= B->rows[k][0] & mask;
}
}
}
}
} else {
size_t mb1 = (((mb-1) / RADIX + 1) >> 1) * RADIX;
mzd_t *B0 = mzd_init_window(B, 0, 0, mb1, nb);
mzd_t *B1 = mzd_init_window(B, mb1, 0, mb, nb);
mzd_t *U00 = mzd_init_window(U, 0, 0, mb1, mb1);
mzd_t *U01 = mzd_init_window(U, 0, mb1, mb1, mb);
mzd_t *U11 = mzd_init_window(U, mb1, mb1, mb, mb);
_mzd_trsm_upper_left_even (U11, B1, cutoff);
_mzd_addmul (B0, U01, B1, cutoff);
_mzd_trsm_upper_left_even (U00, B0, cutoff);
mzd_free_window(B0);
mzd_free_window(B1);
mzd_free_window(U00);
mzd_free_window(U01);
mzd_free_window(U11);
}
}
|
yp/Heu-MCHC
|
pers-lib/m4ri/testsuite/walltime.h
|
/* wall clock */
/* see "Software Optimization for High Performance Computing" p. 135 */
#include <time.h>
#include <sys/time.h>
double walltime( double *t0 )
{
double mic, time;
double mega = 0.000001;
struct timeval tp;
static long base_sec = 0;
static long base_usec = 0;
(void) gettimeofday(&tp,NULL);
if (base_sec == 0)
{
base_sec = tp.tv_sec;
base_usec = tp.tv_usec;
}
time = (double) (tp.tv_sec - base_sec);
mic = (double) (tp.tv_usec - base_usec);
time = (time + mic * mega) - *t0;
return(time);
}
|
yp/Heu-MCHC
|
pers-lib/m4ri/src/misc.h
|
/**
* \file misc.h
* \brief Helper functions.
*
* \author <NAME> <<EMAIL>>
* \author <NAME> <<EMAIL>>
*/
#ifndef MISC_H
#define MISC_H
/*******************************************************************
*
* M4RI: Linear Algebra over GF(2)
*
* Copyright (C) 2007, 2008 <NAME> <<EMAIL>>
* Copyright (C) 2008 <NAME> <<EMAIL>>
*
* Distributed under the terms of the GNU General Public License (GPL)
* version 2 or higher.
*
* This code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* The full text of the GPL is available at:
*
* http://www.gnu.org/licenses/
*
********************************************************************/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#ifdef HAVE_MM_MALLOC
#include <mm_malloc.h>
#endif
#include <stdlib.h>
#include <assert.h>
#include <string.h>
/*
* These define entirely the word width used in the library.
*/
/**
* A word is the typical packed data structure to represent packed
* bits.
*/
typedef unsigned long long word;
/**
* \brief The number of bits in a word.
*/
#define RADIX (sizeof(word)<<3)
/**
* \brief The number one as a word.
*/
#define ONE ((word)1)
/**
* \brief The number 2^64-1 as a word.
*/
#define FFFF ((word)0xffffffffffffffffull)
/**
* \brief Return the maximal element of x and y
*
* \param x Word
* \param y Word
*/
#ifndef MAX
#define MAX(x,y) (((x) > (y))?(x):(y))
#endif
/**
* \brief Return the minimal element of x and y
*
* \param x Word
* \param y Word
*/
#ifndef MIN
#define MIN(x,y) (((x) < (y))?(x):(y))
#endif
/**
* \brief Return r such that x elements fit into r blocks of length y.
*
* \param x Number of elements
* \param y Block size
*/
#define DIV_CEIL(x,y) (((x)%(y))?(x)/(y)+1:(x)/(y))
/**
*\brief Pretty for 1.
*/
#define TRUE 1
/**
*\brief Pretty for 0.
*/
#define FALSE 0
/**
* \brief $2^i$
*
* \param i Integer.
*/
#define TWOPOW(i) (ONE<<(i))
/**
* \brief Pretty for unsigned char.
*/
typedef unsigned char BIT;
/**
* \brief Clear the bit spot (counting from the left) in the word w
*
* \param w Word
* \param spot Integer with 0 <= spot < RADIX
*/
#define CLR_BIT(w, spot) ((w) &= ~(ONE<<(RADIX - (spot) - 1)))
/**
* \brief Set the bit spot (counting from the left) in the word w
*
* \param w Word
* \param spot Integer with 0 <= spot < RADIX
*/
#define SET_BIT(w, spot) ((w) |= (ONE<<(RADIX - (spot) - 1)))
/**
* \brief Get the bit spot (counting from the left) in the word w
*
* \param w Word
* \param spot Integer with 0 <= spot < RADIX
*/
#define GET_BIT(w, spot) (((w) & (ONE<<(RADIX - (spot) - 1))) >> (RADIX - (spot) - 1))
/**
* \brief Write the value to the bit spot in the word w
*
* \param w Word.
* \param spot Integer with 0 <= spot < RADIX.
* \param value Either 0 or 1.
*/
#define WRITE_BIT(w, spot, value) ((w) = (((w) &~(ONE<<(RADIX - (spot) - 1))) | (((word)(value))<<(RADIX - (spot) - 1))))
/**
* \brief Flip the spot in the word w
*
* \param w Word.
* \param spot Integer with 0 <= spot < RADIX.
*/
#define FLIP_BIT(w, spot) ((w) ^= (ONE<<(RADIX - (spot) - 1)))
/**
* \brief Return the n leftmost bits of the word w.
*
* \param w Word
* \param n Integer with 0 <= spot < RADIX
*/
#define LEFTMOST_BITS(w, n) ((w) & ~((ONE<<(RADIX-(n)))-1))>>(RADIX-(n))
/**
* \brief Return the n rightmost bits of the word w.
*
* \param w Word
* \param n Integer with 0 <= spot < RADIX
*/
#define RIGHTMOST_BITS(w, n) (((w)<<(RADIX-(n)-1))>>(RADIX-(n)-1))
/**
* \brief creat a bit mask to zero out all but the n%RADIX leftmost
* bits.
*
* \param n Integer
*/
#define LEFT_BITMASK(n) (~((ONE << ((RADIX - (n % RADIX))%RADIX) ) - 1))
/**
* \brief creat a bit mask to zero out all but the n%RADIX rightmost
* bits.
*
* \param n Integer
*
* \warning Does not handle multiples of RADIX correctly
*/
#define RIGHT_BITMASK(n) (FFFF>>( (RADIX - (n%RADIX))%RADIX ))
/**
* \brief creat a bit mask to zero out all but the n%RADIX bit.
*
* \param n Integer
*
*/
#define BITMASK(n) (ONE<<(RADIX-((n)%RADIX)-1))
/**
* \brief Return alignment of addr w.r.t. n. For example the address
* 17 would be 1 aligned w.r.t. 16.
*
* \param addr
* \param n
*/
#define ALIGNMENT(addr, n) (((unsigned long)(addr))%(n))
/**
* Return the index of the leftmost bit in a for a nonzero.
*
* \param a Word
*/
static inline int leftmost_bit(word a) {
int r = 0;
if(a>>32)
r+=32, a>>=32;
if(a>>16)
r+=16, a>>=16;
if(a>>8)
r+=8, a>>=8;
if(a>>4)
r+=4, a>>=4;
if(a>>2)
r+=2, a>>=2;
if(a>>1)
r+=1, a>>=1;
if(a)
r+=1, a>>=1;
return r;
}
/**** Error Handling *****/
/**
* \brief Print error message and abort().
*
* The function accepts additional
* parameters like printf, so e.g. m4ri_die("foo %d bar %f\n",1 ,2.0)
* is valid and will print the string "foo 1 bar 2.0" before dying.
*
* \param errormessage a string to be printed.
*
* \todo Allow user to register callback which is called on
* m4ri_die().
*
* \warning The provided string is not free'd.
*/
void m4ri_die(const char *errormessage, ...);
/**** IO *****/
/**
* \brief Write a sting representing the word data to destination.
*
* \param destination Address of buffer of length at least RADIX*1.3
* \param data Source word
* \param colon Insert a Colon after every 4-th bit.
* \warning Assumes destination has RADIX*1.3 bytes available
*/
void m4ri_word_to_str( char *destination, word data, int colon);
/**
* \brief Return 1 or 0 uniformly randomly distributed.
*
* \todo Allow user to provide her own random() function.
*/
//BIT m4ri_coin_flip(void);
static inline BIT m4ri_coin_flip() {
if (rand() < RAND_MAX/2) {
return 0;
} else {
return 1;
}
}
/**
* \brief Return uniformly randomly distributed random word.
*
* \todo Allow user to provide her own random() function.
*/
word m4ri_random_word();
/***** Initialization *****/
/**
* \brief Initialize global data structures for the M4RI library.
*
* On Linux/Solaris this is called automatically when the shared
* library is loaded, but it doesn't harm if it is called twice.
*/
#if defined(__GNUC__)
void __attribute__ ((constructor)) m4ri_init(void);
#else
void m4ri_init(void);
#endif
#ifdef __SUNPRO_C
#pragma init(m4ri_init)
#endif
/**
* \brief De-initialize global data structures from the M4RI library.
*
* On Linux/Solaris this is called automatically when the shared
* library is unloaded, but it doesn't harm if it is called twice.
*/
#if defined(__GNUC__)
void __attribute__ ((destructor)) m4ri_fini(void);
#else
void m4ri_fini(void);
#endif
#ifdef __SUNPRO_C
#pragma fini(m4ri_fini)
#endif
/***** Memory Management *****/
#if CPU_L2_CACHE == 0
/**
* Fix some standard value for L2 cache size if it couldn't be
* determined by configure.
*/
#undef CPU_L2_CACHE
#define CPU_L2_CACHE 524288
#endif //CPU_L2_CACHE
#if CPU_L1_CACHE == 0
/**
* Fix some standard value for L1 cache size if it couldn't be
* determined by configure.
*/
#undef CPU_L1_CACHE
#define CPU_L1_CACHE 16384
#endif //CPU_L1_CACHE
/**
* \brief Calloc wrapper.
*
* \param count Number of elements.
* \param size Size of each element.
*
* \todo Allow user to register calloc function.
*/
/* void *m4ri_mm_calloc( int count, int size ); */
static inline void *m4ri_mm_calloc( int count, int size ) {
void *newthing;
#ifdef HAVE_OPENMP
#pragma omp critical
{
#endif
#ifdef HAVE_MM_MALLOC
newthing = _mm_malloc(count*size, 16);
#else
newthing = calloc(count, size);
#endif
#ifdef HAVE_OPENMP
}
#endif
if (newthing==NULL) {
m4ri_die("m4ri_mm_calloc: calloc returned NULL\n");
return NULL; /* unreachable. */
}
#ifdef HAVE_MM_MALLOC
char *b = (char*)newthing;
memset(b, 0, count*size);
#endif
return newthing;
}
/**
* \brief Malloc wrapper.
*
* \param size Size in bytes.
*
* \todo Allow user to register malloc function.
*/
/* void *m4ri_mm_malloc( int size ); */
static inline void *m4ri_mm_malloc( int size ) {
void *newthing;
#ifdef HAVE_OPENMP
#pragma omp critical
{
#endif
#ifdef HAVE_MM_MALLOC
newthing = _mm_malloc(size, 16);
#else
newthing = malloc( size );
#endif
#ifdef HAVE_OPENMP
}
#endif
if (newthing==NULL && (size>0)) {
m4ri_die("m4ri_mm_malloc: malloc returned NULL\n");
return NULL; /* unreachable */
}
else return newthing;
}
/**
* \brief Free wrapper.
*
* \param condemned Pointer.
*
* \todo Allow user to register free function.
*/
/* void m4ri_mm_free(void *condemned, ...); */
static inline void m4ri_mm_free(void *condemned, ...) {
#ifdef HAVE_OPENMP
#pragma omp critical
{
#endif
#ifdef HAVE_MM_MALLOC
_mm_free(condemned);
#else
free(condemned);
#endif
#ifdef HAVE_OPENMP
}
#endif
}
/**
* \brief Maximum number of bytes allocated in one malloc() call.
*/
#define MM_MAX_MALLOC ((1ULL)<<30)
/**
* \brief Enable memory block cache (default: disabled)
*/
#define ENABLE_MMC
/**
* \brief Number of blocks that are cached.
*/
#define M4RI_MMC_NBLOCKS 16
/**
* \brief Maximal size of blocks stored in cache.
*/
#define M4RI_MMC_THRESHOLD CPU_L2_CACHE
/**
* The mmc memory management functions check a cache for re-usable
* unused memory before asking the system for it.
*/
typedef struct _mm_block {
/**
* Size in bytes of the data.
*/
size_t size;
/**
* Pointer to buffer of data.
*/
void *data;
} mmb_t;
/**
* The actual memory block cache.
*/
extern mmb_t m4ri_mmc_cache[M4RI_MMC_NBLOCKS];
/**
* \brief Return handle for locale memory management cache.
*
* \attention Not thread safe.
*/
static inline mmb_t *m4ri_mmc_handle(void) {
return m4ri_mmc_cache;
}
/**
* \brief Allocate size bytes.
*
* \param size Number of bytes.
*/
static inline void *m4ri_mmc_malloc(size_t size) {
#ifdef HAVE_OPENMP
#pragma omp critical
{
#endif
#ifdef ENABLE_MMC
mmb_t *mm = m4ri_mmc_handle();
if (size <= M4RI_MMC_THRESHOLD) {
size_t i;
for (i=0; i<M4RI_MMC_NBLOCKS; i++) {
if(mm[i].size == size) {
void *ret = mm[i].data;
mm[i].data = NULL;
mm[i].size = 0;
return ret;
}
}
}
#endif //ENABLE_MMC
#ifdef HAVE_OPENMP
}
#endif
return m4ri_mm_malloc(size);
}
/**
* \brief Allocate size times count zeroed bytes.
*
* \param size Number of bytes per block.
* \param count Number of blocks.
*
* \warning Not thread safe.
*/
static inline void *m4ri_mmc_calloc(size_t size, size_t count) {
void *ret = m4ri_mmc_malloc(size*count);
memset((char*)ret, 0, count*size);
return ret;
}
/**
* \brief Free the data pointed to by condemned of the given size.
*
* \param condemned Pointer to memory.
* \param size Number of bytes.
*
* \warning Not thread safe.
*/
static inline void m4ri_mmc_free(void *condemned, size_t size) {
#ifdef HAVE_OPENMP
#pragma omp critical
{
#endif
#ifdef ENABLE_MMC
static size_t j = 0;
mmb_t *mm = m4ri_mmc_handle();
if (size < M4RI_MMC_THRESHOLD) {
size_t i;
for(i=0; i<M4RI_MMC_NBLOCKS; i++) {
if(mm[i].size == 0) {
mm[i].size = size;
mm[i].data = condemned;
return;
}
}
m4ri_mm_free(mm[j].data);
mm[j].size = size;
mm[j].data = condemned;
j = (j+1) % M4RI_MMC_NBLOCKS;
return;
}
#endif //ENABLE_MMC
#ifdef HAVE_OPENMP
}
#endif
m4ri_mm_free(condemned);
}
/**
* \brief Cleans up the cache.
*
* This function is called automatically when the shared library is
* loaded.
*
* \warning Not thread safe.
*/
static inline void m4ri_mmc_cleanup(void) {
#ifdef HAVE_OPENMP
#pragma omp critical
{
#endif
mmb_t *mm = m4ri_mmc_handle();
size_t i;
for(i=0; i < M4RI_MMC_NBLOCKS; i++) {
if (mm[i].size)
m4ri_mm_free(mm[i].data);
mm[i].size = 0;
}
#ifdef HAVE_OPENMP
}
#endif
}
#endif //MISC_H
|
yp/Heu-MCHC
|
pers-lib/m4ri/src/brilliantrussian.h
|
<filename>pers-lib/m4ri/src/brilliantrussian.h
/**
* \file brilliantrussian.h
* \brief M4RI and M4RM.
*
* \author <NAME> <<EMAIL>>
* \author <NAME> <<EMAIL>>
*
* \note For reference see <NAME>; Accelerating Cryptanalysis with
* the Method of Four Russians; 2006;
* http://eprint.iacr.org/2006/251.pdf
*/
#ifndef BRILLIANTRUSSIAN_H
#define BRILLIANTRUSSIAN_H
/*******************************************************************
*
* M4RI: Linear Algebra over GF(2)
*
* Copyright (C) 2007, 2008 <NAME> <<EMAIL>>
* Copyright (C) 2008 <NAME> <<EMAIL>>
*
* Distributed under the terms of the GNU General Public License (GPL)
* version 2 or higher.
*
* This code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* The full text of the GPL is available at:
*
* http://www.gnu.org/licenses/
*
********************************************************************/
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include "misc.h"
#include "packedmatrix.h"
#include "permutation.h"
/**
* \brief Constructs all possible \f$2^k\f$ row combinations using the gray
* code table.
*
* \param M matrix to operate on
* \param r the starting row
* \param c the starting column (only exact up to block)
* \param k
* \param T prealloced matrix of dimension \f$2^k\f$ x m->ncols
* \param L prealloced table of length \f$2^k\f$
*
* \wordoffset
*/
void mzd_make_table( mzd_t *M, size_t r, size_t c, int k, mzd_t *T, size_t *L);
/**
* \brief The function looks up k bits from position i,startcol in
* each row and adds the appropriate row from T to the row i.
*
* This process is iterated for i from startrow to stoprow
* (exclusive).
*
* \param M Matrix to operate on
* \param startrow top row which is operated on
* \param endrow bottom row which is operated on
* \param startcol Starting column for addition
* \param k M4RI parameter
* \param T contains the correct row to be added
* \param L Contains row number to be added
*
* \wordoffset
*/
void mzd_process_rows(mzd_t *M, size_t startrow, size_t endrow, size_t startcol, int k, mzd_t *T, size_t *L);
/**
* \brief Same as mzd_process_rows but works with two Gray code tables
* in parallel.
*
* \param M Matrix to operate on
* \param startrow top row which is operated on
* \param endrow bottom row which is operated on
* \param startcol Starting column for addition
* \param k M4RI parameter
* \param T0 contains the correct row to be added
* \param L0 Contains row number to be added
* \param T1 contains the correct row to be added
* \param L1 Contains row number to be added
*
* \wordoffset
*/
void mzd_process_rows2(mzd_t *M, size_t startrow, size_t endrow, size_t startcol, int k, mzd_t *T0, size_t *L0, mzd_t *T1, size_t *L1);
/**
* \brief Same as mzd_process_rows but works with three Gray code tables
* in parallel.
*
* \param M Matrix to operate on
* \param startrow top row which is operated on
* \param endrow bottom row which is operated on
* \param startcol Starting column for addition
* \param k M4RI parameter
* \param T0 contains the correct row to be added
* \param L0 Contains row number to be added
* \param T1 contains the correct row to be added
* \param L1 Contains row number to be added
* \param T2 contains the correct row to be added
* \param L2 Contains row number to be added
*
* \wordoffset
*/
void mzd_process_rows3(mzd_t *M, size_t startrow, size_t endrow, size_t startcol, int k,
mzd_t *T0, size_t *L0, mzd_t *T1, size_t *L1,
mzd_t *T2, size_t *L2);
/**
* \brief Same as mzd_process_rows but works with four Gray code tables
* in parallel.
*
* \param M Matrix to operate on
* \param startrow top row which is operated on
* \param endrow bottom row which is operated on
* \param startcol Starting column for addition
* \param k M4RI parameter
* \param T0 contains the correct row to be added
* \param L0 Contains row number to be added
* \param T1 contains the correct row to be added
* \param L1 Contains row number to be added
* \param T2 contains the correct row to be added
* \param L2 Contains row number to be added
* \param T3 contains the correct row to be added
* \param L3 Contains row number to be added
*
* \wordoffset
*/
void mzd_process_rows4(mzd_t *M, size_t startrow, size_t endrow, size_t startcol, int k,
mzd_t *T0, size_t *L0, mzd_t *T1, size_t *L1,
mzd_t *T2, size_t *L2, mzd_t *T3, size_t *L3);
/**
* \brief Matrix elimination using the 'Method of the Four Russians'
* (M4RI).
*
* \param M Matrix to be reduced.
* \param full Return the reduced row echelon form, not only upper triangular form.
* \param k M4RI parameter, may be 0 for auto-choose.
*
* \example testsuite/test_elimination.c
* \example testsuite/bench_elimination.c
*
* \wordoffset
*
* \return Rank of A.
*/
size_t mzd_echelonize_m4ri(mzd_t *M, int full, int k);
/**
* \brief Given a matrix in upper triangular form compute the reduced row
* echelon form of that matrix.
*
* \param M Matrix to be reduced.
* \param k M4RI parameter, may be 0 for auto-choose.
*
* \wordoffset
*
* \note This function isn't as optimized as it should be.
*/
void mzd_top_echelonize_m4ri(mzd_t *M, int k);
/**
* \brief Invert the matrix M using Konrod's method.
*
* To avoid recomputing the identity matrix over and over again, I may
* be passed in as identity parameter.
*
* \param M Matrix to be reduced.
* \param I Identity matrix.
* \param k M4RI parameter, may be 0 for auto-choose.
*
* \wordoffset
*
* \return Inverse of M
*
* \note This function allocates a new matrix for the inverse which
* must be free'd using mzd_free() once not needed anymore.
*/
mzd_t *mzd_invert_m4ri(mzd_t *M, mzd_t *I, int k);
/**
* \brief Matrix multiplication using Konrod's method, i.e. compute C
* such that C == AB.
*
* This is the convenient wrapper function, please see _mzd_mul_m4rm
* for authors and implementation details.
*
* \param C Preallocated product matrix, may be NULL for automatic creation.
* \param A Input matrix A
* \param B Input matrix B
* \param k M4RI parameter, may be 0 for auto-choose.
*
* \wordoffset
*
* \return Pointer to C.
*/
mzd_t *mzd_mul_m4rm(mzd_t *C, mzd_t *A, mzd_t *B, int k);
/**
* Set C to C + AB using Konrod's method.
*
* \param C Preallocated product matrix, may be NULL for zero matrix.
* \param A Input matrix A
* \param B Input matrix B
* \param k M4RI parameter, may be 0 for auto-choose.
*
* \wordoffset
*
* \return Pointer to C.
*/
mzd_t *mzd_addmul_m4rm(mzd_t *C, mzd_t *A, mzd_t *B, int k);
/**
* \brief Matrix multiplication using Konrod's method, i.e. compute C such
* that C == AB.
*
* This is the actual implementation.
*
* \param C Preallocated product matrix.
* \param A Input matrix A
* \param B Input matrix B
* \param k M4RI parameter, may be 0 for auto-choose.
* \param clear clear the matrix C first
*
* \author <NAME> -- initial implementation
* \author <NAME> -- block matrix implementation, use of several Gray code tables, general speed-ups
*
* \wordoffset
*
* \return Pointer to C.
*/
mzd_t *_mzd_mul_m4rm(mzd_t *C, mzd_t *A, mzd_t *B, int k, int clear);
/**
* \brief If defined 8 Gray code tables are used in parallel.
*/
#define M4RM_GRAY8
#endif //BRILLIANTRUSSIAN_H
|
yp/Heu-MCHC
|
pers-lib/m4ri/src/parity.h
|
#ifndef PARITY_H
#define PARITY_H
/*******************************************************************
*
* M4RI: Linear Algebra over GF(2)
*
* Copyright (C) 2008 <NAME> <<EMAIL>>
*
* Distributed under the terms of the GNU General Public License (GPL)
* version 2 or higher.
*
* This code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* The full text of the GPL is available at:
*
* http://www.gnu.org/licenses/
*
********************************************************************/
/**
* \file parity.h
*
* \brief Compute the parity of 64 words in parallel.
*
* \author <NAME>
*/
/**
* \brief Step for mixing two 64-bit words to compute their parity.
*/
#define MIX32(a, b) (((((a) << 32) ^ (a)) >> 32) + \
((((b) >> 32) ^ (b)) << 32))
/**
* \brief Step for mixing two 64-bit words to compute their parity.
*/
#define MIX16(a, b) (((((a) >> 16) ^ (a)) & 0x0000FFFF0000FFFFll) + \
((((b) << 16) ^ (b)) & 0xFFFF0000FFFF0000ll));
/**
* \brief Step for mixing two 64-bit words to compute their parity.
*/
#define MIX8(a, b) (((((a) >> 8) ^ (a)) & 0x00FF00FF00FF00FFll) + \
((((b) << 8) ^ (b)) & 0xFF00FF00FF00FF00ll));
/**
* \brief Step for mixing two 64-bit words to compute their parity.
*/
#define MIX4(a, b) (((((a) >> 4) ^ (a)) & 0x0F0F0F0F0F0F0F0Fll) + \
((((b) << 4) ^ (b)) & 0xF0F0F0F0F0F0F0F0ll));
/**
* \brief Step for mixing two 64-bit words to compute their parity.
*/
#define MIX2(a, b) (((((a) >> 2) ^ (a)) & 0x3333333333333333ll) + \
((((b) << 2) ^ (b)) & 0xCCCCCCCCCCCCCCCCll));
/**
* \brief Step for mixing two 64-bit words to compute their parity.
*/
#define MIX1(a, b) (((((a) >> 1) ^ (a)) & 0x5555555555555555ll) + \
((((b) << 1) ^ (b)) & 0xAAAAAAAAAAAAAAAAll));
/**
* \brief See parity64.
*/
static inline word _parity64_helper(word* buf)
{
word a0, a1, b0, b1, c0, c1;
a0 = MIX32(buf[0x20], buf[0x00]);
a1 = MIX32(buf[0x30], buf[0x10]);
b0 = MIX16(a1, a0);
a0 = MIX32(buf[0x28], buf[0x08]);
a1 = MIX32(buf[0x38], buf[0x18]);
b1 = MIX16(a1, a0);
c0 = MIX8(b1, b0);
a0 = MIX32(buf[0x24], buf[0x04]);
a1 = MIX32(buf[0x34], buf[0x14]);
b0 = MIX16(a1, a0);
a0 = MIX32(buf[0x2C], buf[0x0C]);
a1 = MIX32(buf[0x3C], buf[0x1C]);
b1 = MIX16(a1, a0);
c1 = MIX8(b1, b0);
return MIX4(c1, c0);
}
/**
* \brief Computes parity of each of buf[0], buf[1], ..., buf[63].
* Returns single word whose bits are the parities of buf[0], ...,
* buf[63]. Assumes 64-bit machine unsigned long.
*
* \param buf buffer of words of length 64
*/
static inline word parity64(word* buf)
{
word d0, d1, e0, e1;
d0 = _parity64_helper(buf);
d1 = _parity64_helper(buf + 2);
e0 = MIX2(d1, d0);
d0 = _parity64_helper(buf + 1);
d1 = _parity64_helper(buf + 3);
e1 = MIX2(d1, d0);
return MIX1(e1, e0);
}
#endif
|
yp/Heu-MCHC
|
src/conversion-2pedphase.c
|
<reponame>yp/Heu-MCHC
/**
*
*
* Heu-MCHC
*
* A fast and accurate heuristic algorithm for the haplotype inference
* problem on pedigree data with recombinations and mutations
*
* Copyright (C) 2009,2010,2011 <NAME>
*
* Distributed under the terms of the GNU General Public License (GPL)
*
*
* This file is part of Heu-MCHC.
*
* Heu-MCHC is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Heu-MCHC is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Heu-MCHC. If not, see <http://www.gnu.org/licenses/>.
*
**/
/*
** conversion-2pedphase.c
**
** Made by (Yuri)
** Login <<EMAIL>>
**
** Started on Mon Jul 27 16:01:38 2009 Yuri
** Last update Sun May 12 01:17:25 2002 Speed Blue
*/
#include "gen-ped-IO.h"
#include "util.h"
#include "log-build-info.h"
int main() {
PRINT_SYSTEM_INFORMATIONS;
pgenped pg= gp_read_from_file(stdin);
int* gender= NPALLOC(int, pg->n_indiv);
for (size_t i= 0; i<pg->n_indiv; ++i) {
gender[i]= 1;
}
for (size_t i= 0; i<pg->n_indiv; ++i) {
if (pg->individuals[i]->fi>=0) {
gender[pg->individuals[i]->fi]= 1;
}
if (pg->individuals[i]->mi>=0) {
gender[pg->individuals[i]->mi]= 2;
}
}
for (size_t i= 0; i<pg->n_indiv; ++i) {
pindiv in= pg->individuals[i];
printf("1\t%d\t%d\t%d\t%d\t0\t0",
in->id+1, in->fi+1, in->mi+1,
gender[i]);
for (size_t j= 0; j<pg->n_loci; ++j) {
if (in->g[j]==2) {
printf("\t1\t2");
} else {
printf("\t%d\t%d", in->g[j]+1, in->g[j]+1);
}
}
printf("\n");
}
}
|
yp/Heu-MCHC
|
src/util.c
|
<reponame>yp/Heu-MCHC
/**
*
*
* Heu-MCHC
*
* A fast and accurate heuristic algorithm for the haplotype inference
* problem on pedigree data with recombinations and mutations
*
* Copyright (C) 2009,2010,2011 <NAME>
*
* Distributed under the terms of the GNU General Public License (GPL)
*
*
* This file is part of Heu-MCHC.
*
* Heu-MCHC is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Heu-MCHC is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Heu-MCHC. If not, see <http://www.gnu.org/licenses/>.
*
**/
#include "util.h"
#include "log.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/resource.h>
#include <unistd.h>
#ifndef NDEBUG
static unsigned long int memsize= 0;
static unsigned long int prev_memsize= 0;
#endif
void* palloc(size_t size)
{
#ifndef NDEBUG
memsize+= size;
#endif
void* p= malloc(size);
if (p==NULL) {
fprintf(stderr, "Allocation memory error. Trying to allocate %zu bytes.\n", size);
fail();
}
#ifndef NDEBUG
if ((memsize-prev_memsize)>>20>=256) {
WARN("Allocated %lu MB", memsize>>20);
prev_memsize= memsize;
}
if ((memsize>>20)>4096) {
WARN("Allocated %lu MB", memsize>>20);
FATAL("Currently allocated more than 2GB. Abort.");
fail();
}
#endif
return p;
}
char* c_palloc(size_t size)
{
return (char*)palloc(size*sizeof(char));
}
void pfree(void* p)
{
if (p==NULL) {
fprintf(stderr, "Cannot free a NULL pointer.\n");
fail();
}
free(p);
}
char* alloc_and_copy(char* source)
{
size_t len= strlen(source);
char* ris= c_palloc(len+1);
strncpy(ris, source, len+1);
return ris;
}
void noop_free(void* el)
{}
char* substring(const int index, const char* string){
my_assert(index>=0);
my_assert(string != NULL);
size_t slen= strlen(string);
char* ris = c_palloc(slen-index+1);
ris = (char*)memcpy(ris, (void*)(string+index), slen-index);
ris[slen-index] = '\0';
return ris;
}//end subString
ssize_t my_getline(char **lineptr, size_t *n, FILE *stream) {
ssize_t ris= getline(lineptr, n, stream);
while (ris>0 && (*lineptr)[ris-1]<' ') {
--ris;
(*lineptr)[ris]= '\0';
}
return ris;
}
void print_repetitions(FILE* f, const char c, int rep) {
char* s= c_palloc(rep+1);
for (int i= 0; i<rep; ++i)
s[i]= c;
s[rep]='\0';
fprintf(f, "%s", s);
pfree(s);
}
void resource_usage_log(void) {
struct rusage *rusage= PALLOC(struct rusage);
if (getrusage(RUSAGE_SELF, rusage)==0) {
STATS("user time %10ld s %7ld millisec.", rusage->ru_utime.tv_sec, rusage->ru_utime.tv_usec/1000);
STATS("system time %10ld s %7ld millisec.", rusage->ru_stime.tv_sec, rusage->ru_stime.tv_usec/1000);
char buf[1000];
snprintf(buf, 1000, "/proc/%u/statm", (unsigned)getpid());
FILE* pf = fopen(buf, "r");
if (pf) {
unsigned int size; // total program size
fscanf(pf, "%u", &size);
STATS("used memory %10u KB", size);
}
fclose(pf);
}
pfree(rusage);
}
double rnd_01(void) {
return ((double)rand())/RAND_MAX;
}
unsigned int
rnd_in_range(unsigned int min, unsigned int max) {
return min+(unsigned int)(rnd_01()*(max-min));
}
|
yp/Heu-MCHC
|
pers-lib/m4ri/testsuite/test_trsm.c
|
#include <stdlib.h>
#include "m4ri/m4ri.h"
int test_trsm_upper_right (int m, int n, int offset, const char* description){
printf("upper_right: %s m: %4d n: %4d offset: %4d ... ",description, m, n, offset);
mzd_t* Ubase = mzd_init (2048,2048);
mzd_t* Bbase = mzd_init (2048,2048);
mzd_randomize (Ubase);
mzd_randomize (Bbase);
mzd_t* Bbasecopy = mzd_copy (NULL, Bbase);
mzd_t* U = mzd_init_window (Ubase, 0, offset, n, offset + n);
mzd_t* B = mzd_init_window (Bbase, 0, offset, m, offset + n);
mzd_t* W = mzd_copy (NULL, B);
size_t i,j;
for (i=0; i<n; ++i){
for (j=0; j<i;++j)
mzd_write_bit(U,i,j, 0);
mzd_write_bit(U,i,i, 1);
}
mzd_trsm_upper_right (U, B, 2048);
mzd_addmul(W, B, U, 2048);
int status = 0;
for ( i=0; i<m; ++i)
for ( j=0; j<n; ++j){
if (mzd_read_bit (W,i,j)){
status = 1;
}
}
// Verifiying that nothing has been changed around the submatrices
mzd_addmul(W, B, U, 2048);
mzd_copy (B, W);
for ( i=0; i<2048; ++i)
for ( j=0; j<2048/RADIX; ++j){
if (Bbase->rows[i][j] != Bbasecopy->rows[i][j]){
status = 1;
}
}
mzd_free_window (U);
mzd_free_window (B);
mzd_free (W);
mzd_free(Ubase);
mzd_free(Bbase);
mzd_free(Bbasecopy);
if (!status)
printf("passed\n");
else
printf("FAILED\n");
return status;
}
int test_trsm_lower_right (int m, int n, int offset, const char *description){
printf("lower_right: %s m: %4d n: %4d offset: %4d ... ",description, m, n, offset);
mzd_t* Lbase = mzd_init (2048,2048);
mzd_t* Bbase = mzd_init (2048,2048);
mzd_randomize (Lbase);
mzd_randomize (Bbase);
mzd_t* Bbasecopy = mzd_copy (NULL, Bbase);
mzd_t* L = mzd_init_window (Lbase, 0, offset, n, offset + n);
mzd_t* B = mzd_init_window (Bbase, 0, offset, m, offset + n);
mzd_t* W = mzd_copy (NULL, B);
size_t i,j;
for (i=0; i<n; ++i){
for (j=i+1; j<n;++j)
mzd_write_bit(L,i,j, 0);
mzd_write_bit(L,i,i, 1);
}
mzd_trsm_lower_right (L, B, 2048);
mzd_addmul(W, B, L, 2048);
int status = 0;
for ( i=0; i<m; ++i)
for ( j=0; j<n; ++j){
if (mzd_read_bit (W,i,j)){
status = 1;
}
}
// Verifiying that nothing has been changed around the submatrices
mzd_addmul(W, B, L, 2048);
mzd_copy (B, W);
for ( i=0; i<2048; ++i)
for ( j=0; j<2048/RADIX; ++j){
if (Bbase->rows[i][j] != Bbasecopy->rows[i][j]){
status = 1;
}
}
mzd_free_window (L);
mzd_free_window (B);
mzd_free (W);
mzd_free(Lbase);
mzd_free(Bbase);
mzd_free(Bbasecopy);
if (!status)
printf("passed\n");
else
printf("FAILED\n");
return status;
}
int test_trsm_lower_left (int m, int n, int offsetL, int offsetB){
mzd_t* Lbase = mzd_init (2048,2048);
mzd_t* Bbase = mzd_init (2048,2048);
mzd_randomize (Lbase);
mzd_randomize (Bbase);
mzd_t* Bbasecopy = mzd_copy (NULL, Bbase);
mzd_t* L = mzd_init_window (Lbase, 0, offsetL, m, offsetL + m);
mzd_t* B = mzd_init_window (Bbase, 0, offsetB, m, offsetB + n);
mzd_t* W = mzd_copy (NULL, B);
size_t i,j;
for (i=0; i<m; ++i){
for (j=i+1; j<m;++j)
mzd_write_bit(L,i,j, 0);
mzd_write_bit(L,i,i, 1);
}
mzd_trsm_lower_left(L, B, 2048);
mzd_addmul(W, L, B, 2048);
int status = 0;
for ( i=0; i<m; ++i)
for ( j=0; j<n; ++j){
if (mzd_read_bit (W,i,j)){
status = 1;
}
}
// Verifiying that nothing has been changed around the submatrices
mzd_addmul(W, L, B, 2048);
mzd_copy (B, W);
for ( i=0; i<2048; ++i)
for ( j=0; j<2048/RADIX; ++j){
if (Bbase->rows[i][j] != Bbasecopy->rows[i][j]){
status = 1;
}
}
mzd_free_window (L);
mzd_free_window (B);
mzd_free_window (W);
mzd_free(Lbase);
mzd_free(Bbase);
mzd_free(Bbasecopy);
if (!status)
printf(" ... passed\n");
else
printf(" ... FAILED\n");
return status;
}
int test_trsm_upper_left (int m, int n, int offsetU, int offsetB, const char *description) {
printf("upper_left: %s m: %4d n: %4d offset: %4d ... ",description, m, n, offsetU);
mzd_t* Ubase = mzd_init (2048,2048);
mzd_t* Bbase = mzd_init (2048,2048);
mzd_randomize (Ubase);
mzd_randomize (Bbase);
mzd_t* Bbasecopy = mzd_copy (NULL, Bbase);
mzd_t* U = mzd_init_window (Ubase, 0, offsetU, m, offsetU + m);
mzd_t* B = mzd_init_window (Bbase, 0, offsetB, m, offsetB + n);
mzd_t* W = mzd_copy (NULL, B);
size_t i,j;
for (i=0; i<m; ++i){
for (j=0; j<i;++j)
mzd_write_bit(U,i,j, 0);
mzd_write_bit(U,i,i, 1);
}
mzd_trsm_upper_left(U, B, 2048);
mzd_addmul(W, U, B, 2048);
int status = 0;
for ( i=0; i<m; ++i)
for ( j=0; j<n; ++j){
if (mzd_read_bit (W,i,j)){
status = 1;
}
}
// Verifiying that nothing has been changed around the submatrices
mzd_addmul(W, U, B, 2048);
mzd_copy (B, W);
for ( i=0; i<2048; ++i)
for ( j=0; j<2048/RADIX; ++j){
if (Bbase->rows[i][j] != Bbasecopy->rows[i][j]){
status = 1;
}
}
mzd_free_window (U);
mzd_free_window (B);
mzd_free_window (W);
mzd_free(Ubase);
mzd_free(Bbase);
mzd_free(Bbasecopy);
if (!status)
printf("passed\n");
else
printf("FAILED\n");
return status;
}
int main(int argc, char **argv) {
int status = 0;
status += test_trsm_upper_right( 57, 10, 0, "small, even placed");
status += test_trsm_upper_right( 57, 150, 0, "large, even placed");
status += test_trsm_upper_right( 57, 3, 4, " small, odd placed");
status += test_trsm_upper_right( 57, 4, 62, "medium, odd placed");
status += test_trsm_upper_right( 57, 80, 60, " large, odd placed");
status += test_trsm_upper_right(1577, 1802, 189, "larger, odd placed");
printf("\n");
status += test_trsm_lower_right( 57, 10, 0,"small, even placed");
status += test_trsm_lower_right( 57, 150, 0,"large, even placed");
status += test_trsm_lower_right( 57, 3, 4," small, odd placed");
status += test_trsm_lower_right( 57, 4, 62,"medium, odd placed");
status += test_trsm_lower_right( 57, 80, 60," large, odd placed");
status += test_trsm_lower_right(1577, 1802,189,"larger, odd placed");
printf("\n");
printf("LowerLeft: small L even, small B even ");
status += test_trsm_lower_left (10, 20, 0, 0);
printf("LowerLeft: small L even, large B even ");
status += test_trsm_lower_left (10, 80, 0, 0);
printf("LowerLeft: small L even, small B odd ");
status += test_trsm_lower_left (10, 20, 0, 15);
printf("LowerLeft: small L even, large B odd ");
status += test_trsm_lower_left (10, 80, 0, 15);
printf("LowerLeft: small L odd, small B even ");
status += test_trsm_lower_left (10, 20, 15, 0);
printf("LowerLeft: small L odd, large B even ");
status += test_trsm_lower_left (10, 80, 15, 0);
printf("LowerLeft: small L odd, small B odd ");
status += test_trsm_lower_left (10, 20, 15, 20);
printf("LowerLeft: small L odd, large B odd ");
status += test_trsm_lower_left (10, 80, 15, 20);
printf("LowerLeft: large L even, small B even ");
status += test_trsm_lower_left (70, 20, 0, 0);
printf("LowerLeft: large L even, large B even ");
status += test_trsm_lower_left (70, 80, 0, 0);
printf("LowerLeft: large L even, small B odd ");
status += test_trsm_lower_left (70, 10, 0, 15);
printf("LowerLeft: large L even, large B odd ");
status += test_trsm_lower_left (70, 80, 0, 15);
printf("LowerLeft: large L odd, small B even ");
status += test_trsm_lower_left (70, 20, 15, 0);
printf("LowerLeft: large L odd, large B even ");
status += test_trsm_lower_left (70, 80, 15, 0);
printf("LowerLeft: large L odd, small B odd ");
status += test_trsm_lower_left (70, 20, 15, 20);
printf("LowerLeft: large L odd, large B odd ");
status += test_trsm_lower_left (70, 80, 15, 20);
printf("LowerLeft: larger L odd, larger B odd ");
status += test_trsm_lower_left (770, 1600, 75, 89);
printf("LowerLeft: larger L odd, larger B odd ");
status += test_trsm_lower_left (1764, 1345, 198, 123);
printf("\n");
status += test_trsm_upper_left( 10, 20, 0, 0,"small U even, small B even");
status += test_trsm_upper_left( 10, 80, 0, 0,"small U even, large B even");
status += test_trsm_upper_left( 10, 20, 0, 15," small U even, small B odd");
status += test_trsm_upper_left( 10, 80, 0, 15," small U even, large B odd");
status += test_trsm_upper_left( 10, 20, 15, 0," small U odd, small B even");
status += test_trsm_upper_left( 10, 80, 15, 0," small U odd, large B even");
status += test_trsm_upper_left( 10, 20, 15, 20," small U odd, small B odd");
status += test_trsm_upper_left( 10, 80, 15, 20," small U odd, large B odd");
status += test_trsm_upper_left( 70, 20, 0, 0,"large U even, small B even");
status += test_trsm_upper_left( 63, 1, 0, 0," ");
status += test_trsm_upper_left( 70, 80, 0, 0,"large U even, large B even");
status += test_trsm_upper_left( 70, 10, 0, 15," large U even, small B odd");
status += test_trsm_upper_left( 70, 80, 0, 15," large U even, large B odd");
status += test_trsm_upper_left( 70, 20, 15, 0," large U odd, small B even");
status += test_trsm_upper_left( 70, 80, 15, 0," large U odd, large B even");
status += test_trsm_upper_left( 70, 20, 15, 20," large U odd, small B odd");
status += test_trsm_upper_left( 70, 80, 15, 20," large U odd, large B odd");
status += test_trsm_upper_left( 770,1600, 75, 89,"larger U odd, larger B odd");
status += test_trsm_upper_left(1764,1345,198,123,"larger U odd, larger B odd");
if (!status) {
printf("All tests passed.\n");
return 0;
} else {
return -1;
}
}
|
yp/Heu-MCHC
|
pers-lib/m4ri/src/misc.c
|
/******************************************************************************
*
* M4RI: Linear Algebra over GF(2)
*
* Copyright (C) 2007 <NAME> <<EMAIL>>
*
* Distributed under the terms of the GNU General Public License (GPL)
* version 2 or higher.
*
* This code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* The full text of the GPL is available at:
*
* http://www.gnu.org/licenses/
******************************************************************************/
#ifdef _MSC_VER
#include <windows.h>
#endif
#ifndef HAVE_SSE2
#undef HAVE_MM_MALLOC
#endif
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include "misc.h"
#include "grayflex.h"
/* blocks of memory we like to keep around for later re-use */
mmb_t m4ri_mmc_cache[M4RI_MMC_NBLOCKS];
void m4ri_die(const char *errormessage, ...) {
va_list lst;
va_start(lst, errormessage);
vfprintf(stderr, errormessage, lst);
va_end(lst);
abort();
}
/* Warning: I assume *destination has RADIX+1 bytes available */
void m4ri_word_to_str( char *destination, word data, int colon) {
int i;
int j = 0;
if (colon == 0) {
for (i=0; i<RADIX; i++) {
if (GET_BIT(data,i))
destination[i]='1';
else
destination[i]=' ';
}
destination[RADIX]='\0';
} else {
for (i=0; i<RADIX; i++) {
if (GET_BIT(data,i))
destination[j]='1';
else
destination[j]=' ';
j++;
if (((i % 4)==3) && (i!=RADIX-1)) {
destination[j]=':';
j++;
}
}
destination[j]='\0';
}
}
#define RAND_SHORT ((word)(rand()&((1<<16)-1)))
word m4ri_random_word() {
return RAND_SHORT ^ RAND_SHORT<<16 ^ RAND_SHORT<<32 ^ RAND_SHORT<<48;
}
#ifdef __GNUC__
void __attribute__ ((constructor)) m4ri_init()
#else
void m4ri_init()
#endif
{
m4ri_build_all_codes();
}
#ifdef __GNUC__
void __attribute__ ((destructor)) m4ri_fini()
#else
void m4ri_fini()
#endif
{
m4ri_mmc_cleanup();
m4ri_destroy_all_codes();
}
#ifdef _MSC_VER
BOOL WINAPI DllMain(
HINSTANCE hinstDLL, // handle to DLL module
DWORD fdwReason, // reason for calling function
LPVOID lpReserved ) // reserved
{
// Perform actions based on the reason for calling.
switch( fdwReason )
{
case DLL_PROCESS_ATTACH:
m4ri_build_all_codes();
break;
case DLL_THREAD_ATTACH:
// Do thread-specific initialization.
break;
case DLL_THREAD_DETACH:
// Do thread-specific cleanup.
break;
case DLL_PROCESS_DETACH:
m4ri_mmc_cleanup();
m4ri_destroy_all_codes();
break;
}
return TRUE; // Successful DLL_PROCESS_ATTACH.
}
#endif
|
yp/Heu-MCHC
|
src/log.c
|
/**
*
*
* Heu-MCHC
*
* A fast and accurate heuristic algorithm for the haplotype inference
* problem on pedigree data with recombinations and mutations
*
* Copyright (C) 2009,2010,2011 <NAME>
*
* Distributed under the terms of the GNU General Public License (GPL)
*
*
* This file is part of Heu-MCHC.
*
* Heu-MCHC is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Heu-MCHC is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Heu-MCHC. If not, see <http://www.gnu.org/licenses/>.
*
**/
#include "log.h"
#include "util.h"
#include "string.h"
void log_format_str(const char* funz,
const char* srcf,
char* dst,
int max_len1,
int max_len2) {
const int lenf= strlen(funz);
const int lens= strlen(srcf);
const int tot= max_len1+max_len2+1;
int max_lenf;
if (max_len1>max_len2-lens)
max_lenf= max_len1;
else
max_lenf= max_len2-lens;
strncpy(dst, funz, max_lenf);
if (lenf>max_lenf)
dst[max_lenf-2]= dst[max_lenf-1]= '.';
int pos= MIN(lenf, max_lenf);
dst[pos]= '@';
++pos;
if (pos+lens>tot) {
strcpy(dst+pos, srcf+lens+pos-tot);
dst[pos]= dst[pos+1]= '.';
} else {
strncpy(dst+pos, srcf, max_len1+max_len2+1-pos);
pos= MIN(max_len1+max_len2+1, pos+lens);
for (int i= pos; i<max_len1+max_len2+1; ++i) {
dst[i]=' ';
}
}
dst[tot]= '\0';
}
|
yp/Heu-MCHC
|
pers-lib/m4ri/src/lqup.c
|
<filename>pers-lib/m4ri/src/lqup.c<gh_stars>1-10
/*******************************************************************
*
* M4RI: Linear Algebra over GF(2)
*
* Copyright (C) 2008 <NAME> <<EMAIL>>
*
* Distributed under the terms of the GNU General Public License (GPL)
* version 2 or higher.
*
* This code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* The full text of the GPL is available at:
*
* http://www.gnu.org/licenses/
*
********************************************************************/
#include "misc.h"
#include "packedmatrix.h"
#include "trsm.h"
#include "parity.h"
#include <stdio.h>
#include "pluq_mmpf.h"
#include "strassen.h"
#include "lqup.h"
size_t mzd_lqup (mzd_t *A, mzp_t * P, mzp_t * Q, const int cutoff) {
if (P->length != A->nrows)
m4ri_die("mzd_lqup: Permutation P length (%d) must match A nrows (%d)\n",P->length, A->nrows);
if (Q->length != A->ncols)
m4ri_die("mzd_lqup: Permutation Q length (%d) must match A ncols (%d)\n",Q->length, A->ncols);
return _mzd_lqup(A, P, Q, cutoff);
}
size_t mzd_pluq (mzd_t *A, mzp_t * P, mzp_t * Q, const int cutoff) {
if (P->length != A->nrows)
m4ri_die("mzd_pluq: Permutation P length (%d) must match A nrows (%d)\n",P->length, A->nrows);
if (Q->length != A->ncols)
m4ri_die("mzd_pluq: Permutation Q length (%d) must match A ncols (%d)\n",Q->length, A->ncols);
size_t r = _mzd_pluq(A, P, Q, cutoff);
return r;
}
size_t _mzd_pluq(mzd_t *A, mzp_t * P, mzp_t * Q, const int cutoff) {
size_t r = _mzd_lqup(A,P,Q,cutoff);
mzd_apply_p_right_tri(A, Q);
return r;
}
size_t _mzd_lqup(mzd_t *A, mzp_t * P, mzp_t * Q, const int cutoff) {
size_t ncols = A->ncols;
#if 1
size_t nrows = mzd_first_zero_row(A);
for(size_t i=nrows; i<A->nrows; i++)
P->values[i] = i;
for(size_t i=0; i<A->ncols; i++)
Q->values[i] = i;
if(!nrows) {
return 0;
}
#else
size_t nrows = A->nrows;
#endif
if (ncols <= RADIX || A->width*A->nrows <= LQUP_CUTOFF) {
/* if(ncols <= PLUQ_CUTOFF) { */
/* this improves data locality and runtime considerably */
mzd_t *Abar = mzd_copy(NULL, A);
size_t r = _mzd_lqup_mmpf(Abar, P, Q, 0);
mzd_copy(A, Abar);
mzd_free(Abar);
return r;
}
{
/* Block divide and conquer algorithm */
/* n1
* ------------------------------------------
* | A0 | A1 |
* | | |
* | | |
* | | |
* ------------------------------------------
*/
size_t i, j;
size_t n1 = (((ncols - 1) / RADIX + 1) >> 1) * RADIX;
mzd_t *A0 = mzd_init_window(A, 0, 0, nrows, n1);
mzd_t *A1 = mzd_init_window(A, 0, n1, nrows, ncols);
size_t r1, r2;
/* First recursive call */
mzp_t *P1 = mzp_init_window(P, 0, nrows);
mzp_t *Q1 = mzp_init_window(Q, 0, A0->ncols);
r1 = _mzd_lqup(A0, P1, Q1, cutoff);
/* r1 n1
* ------------------------------------------
* | A00 | | A01 |
* | | | |
* r1------------------------------------------
*
* | A10 | | A11 |
* | | | |
* ------------------------------------------
*/
mzd_t *A00 = mzd_init_window(A, 0, 0, r1, r1);
mzd_t *A10 = mzd_init_window(A, r1, 0, nrows, r1);
mzd_t *A01 = mzd_init_window(A, 0, n1, r1, ncols);
mzd_t *A11 = mzd_init_window(A, r1, n1, nrows, ncols);
if (r1) {
/* Computation of the Schur complement */
mzd_apply_p_left(A1, P1);
_mzd_trsm_lower_left(A00, A01, cutoff);
mzd_addmul(A11, A10, A01, cutoff);
}
mzp_free_window(P1);
mzp_free_window(Q1);
/* Second recursive call */
mzp_t *P2 = mzp_init_window(P, r1, nrows);
mzp_t *Q2 = mzp_init_window(Q, n1, ncols);
r2 = _mzd_lqup(A11, P2, Q2, cutoff);
/* n
* -------------------
* | A0b |
* | |
* r1-----------------
* | A1b |
* | |
* -------------------
*/
/* Update A10 */
mzd_apply_p_left(A10, P2);
/* Update P */
for (i = 0; i < nrows - r1; ++i)
P2->values[i] += r1;
// Update the A0b block (permutation + rotation)
for(i=0, j=n1; j<ncols; i++, j++)
Q2->values[i] += n1;
for(i=n1, j=r1; i<n1+r2; i++, j++)
Q->values[j] = Q->values[i];
/* Compressing L */
mzp_t *shift = mzp_init(A->ncols);
if (r1 < n1){
for (i=r1,j=n1;i<r1+r2;i++,j++){
mzd_col_swap_in_rows(A, i, j, i, r1+r2);
shift->values[i] = j;
}
}
mzd_apply_p_right_trans_even_capped(A, shift, r1+r2, 0);
mzp_free(shift);
mzp_free_window(Q2);
mzp_free_window(P2);
mzd_free_window(A0);
mzd_free_window(A1);
mzd_free_window(A00);
mzd_free_window(A01);
mzd_free_window(A10);
mzd_free_window(A11);
return r1 + r2;
}
}
size_t _mzd_pluq_naive(mzd_t *A, mzp_t *P, mzp_t *Q) {
size_t i, j, l, curr_pos;
int found;
curr_pos = 0;
for (curr_pos = 0; curr_pos < A->ncols; ) {
found = 0;
/* search for some pivot */
for (j = curr_pos; j < A->ncols; j++) {
for (i = curr_pos; i< A->nrows; i++ ) {
if (mzd_read_bit(A, i, j)) {
found = 1;
break;
}
}
if(found)
break;
}
if(found) {
P->values[curr_pos] = i;
Q->values[curr_pos] = j;
mzd_row_swap(A, curr_pos, i);
mzd_col_swap(A, curr_pos, j);
/* clear below but preserve transformation matrix */
if (curr_pos +1 < A->ncols){
for(l=curr_pos+1; l<A->nrows; l++) {
if (mzd_read_bit(A, l, curr_pos)) {
mzd_row_add_offset(A, l, curr_pos, curr_pos+1);
}
}
}
curr_pos++;
} else {
break;
}
}
for (i=curr_pos; i<A->nrows; ++i)
P->values[i]=i;
for (i=curr_pos; i<A->ncols; ++i)
Q->values[i]=i;
return curr_pos;
}
size_t _mzd_lqup_naive(mzd_t *A, mzp_t *P, mzp_t *Q) {
size_t i, j, l, col_pos, row_pos;
int found;
col_pos = 0;
row_pos = 0;
/* search for some pivot */
for (; row_pos<A->nrows && col_pos < A->ncols; ) {
found = 0;
for (j = col_pos; j < A->ncols; j++) {
for (i = row_pos; i< A->nrows; i++ ) {
if (mzd_read_bit(A, i, j)) {
found = 1;
break;
}
}
if(found)
break;
}
if(found) {
P->values[row_pos] = i;
Q->values[row_pos] = j;
mzd_row_swap(A, row_pos, i);
//mzd_col_swap(A, curr_pos, j);
/* clear below but preserve transformation matrix */
if (j+1 < A->ncols){
for(l=row_pos+1; l<A->nrows; l++) {
if (mzd_read_bit(A, l, j)) {
mzd_row_add_offset(A, l, row_pos, j+1);
}
}
}
row_pos++;
col_pos=j+1;
} else {
break;
}
}
for (i=row_pos; i<A->nrows; ++i)
P->values[i]=i;
for (i=row_pos; i<A->ncols; ++i)
Q->values[i]=i;
/* Now compressing L*/
for (j = 0; j<row_pos; ++j){
if (Q->values[j]>j){
// To be optimized by a copy_row function
mzd_col_swap_in_rows (A,Q->values[j], j, j, A->nrows);
}
}
return row_pos;
}
size_t mzd_echelonize_pluq(mzd_t *A, int full) {
mzp_t *P = mzp_init(A->nrows);
mzp_t *Q = mzp_init(A->ncols);
size_t r = mzd_pluq(A, P, Q, 0);
if(full) {
mzd_t *U = mzd_init_window(A, 0, 0, r, r);
mzd_t *B = mzd_init_window(A, 0, r, r, A->ncols);
if(r!=A->ncols)
mzd_trsm_upper_left(U, B, 0);
if(r!=0)
mzd_set_ui(U, 0);
size_t i;
for(i=0; i<r; i++) {
mzd_write_bit(A, i, i, 1);
}
mzd_free_window(U);
mzd_free_window(B);
} else {
size_t i, j;
for(i=0; i<r; i++) {
for(j=0; j<i; j+=RADIX) {
const size_t length = MIN(RADIX, i-j);
mzd_clear_bits(A, i, j, length);
}
}
}
if(r!=A->nrows) {
mzd_t *R = mzd_init_window(A, r, 0, A->nrows, A->ncols);
mzd_set_ui(R, 0);
mzd_free_window(R);
}
mzd_apply_p_right(A, Q);
mzp_free(P);
mzp_free(Q);
return r;
}
|
yp/Heu-MCHC
|
pers-lib/m4ri/src/pluq_mmpf.c
|
/*******************************************************************
*
* M4RI: Linear Algebra over GF(2)
*
* Copyright (C) 2008 <NAME> <<EMAIL>>
*
* Distributed under the terms of the GNU General Public License (GPL)
* version 2 or higher.
*
* This code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* The full text of the GPL is available at:
*
* http://www.gnu.org/licenses/
*
********************************************************************/
#include <assert.h>
#include "misc.h"
#ifdef HAVE_SSE2
#include <emmintrin.h>
#endif
#include "pluq_mmpf.h"
#include "brilliantrussian.h"
#include "grayflex.h"
static inline size_t _max_value(size_t *data, size_t length) {
size_t max = 0;
for(size_t i=0; i<length; i++) {
max = MAX(max, data[i]);
}
return max;
}
size_t _mzd_lqup_submatrix(mzd_t *A, size_t start_row, size_t stop_row, size_t start_col, int k, mzp_t *P, mzp_t *Q, size_t *done, size_t *done_row) {
size_t i, l, curr_pos;
int found;
word bm[4*MAXKAY];
size_t os[4*MAXKAY];
for(curr_pos=0; curr_pos < (size_t)k; curr_pos++) {
os[curr_pos] = (start_col+curr_pos)/RADIX;
bm[curr_pos] = ONE<<(RADIX-(start_col+curr_pos)%RADIX-1);
found = 0;
/* search for some pivot */
for(i = start_row + curr_pos; i < stop_row; i++) {
const word tmp = mzd_read_bits(A, i, start_col, curr_pos+1);
if(tmp) {
word *Arow = A->rows[i];
/* clear before but preserve transformation matrix */
for (l=0; l<curr_pos; l++)
if(done[l] < i) {
if(Arow[os[l]] & bm[l])
mzd_row_add_offset(A, i, start_row + l, start_col + l + 1);
done[l] = i; /* encode up to which row we added for l already */
}
if(mzd_read_bit(A, i, start_col + curr_pos)) {
found = 1;
break;
}
}
}
if(!found) {
break;
}
P->values[start_row + curr_pos] = i;
mzd_row_swap(A, i, start_row + curr_pos);
Q->values[start_row + curr_pos] = start_col + curr_pos;
done[curr_pos] = i;
}
/* finish submatrix */
*done_row = _max_value(done, curr_pos);
for(size_t c2=0; c2<curr_pos && start_col + c2 < A->ncols -1; c2++)
for(size_t r2=done[c2]+1; r2<=*done_row; r2++)
if(mzd_read_bit(A, r2, start_col + c2))
mzd_row_add_offset(A, r2, start_row + c2, start_col + c2 + 1);
return curr_pos;
}
/* create a table of all 2^k linear combinations */
void mzd_make_table_lqup( mzd_t *M, size_t r, size_t c, int k, mzd_t *T, size_t *L) {
assert(T->blocks[1].size == 0);
const size_t blockoffset= c/RADIX;
size_t i, rowneeded;
size_t twokay= TWOPOW(k);
size_t wide = T->width - blockoffset;
word *ti, *ti1, *m;
ti1 = T->rows[0] + blockoffset;
ti = ti1 + T->width;
#ifdef HAVE_SSE2
unsigned long incw = 0;
if (T->width & 1) incw = 1;
ti += incw;
#endif
L[0]=0;
for (i=1; i<twokay; i++) {
rowneeded = r + codebook[k]->inc[i-1];
m = M->rows[rowneeded] + blockoffset;
/* Duff's device loop unrolling */
register int n = (wide + 7) / 8;
switch (wide % 8) {
case 0: do { *(ti++) = *(m++) ^ *(ti1++);
case 7: *(ti++) = *(m++) ^ *(ti1++);
case 6: *(ti++) = *(m++) ^ *(ti1++);
case 5: *(ti++) = *(m++) ^ *(ti1++);
case 4: *(ti++) = *(m++) ^ *(ti1++);
case 3: *(ti++) = *(m++) ^ *(ti1++);
case 2: *(ti++) = *(m++) ^ *(ti1++);
case 1: *(ti++) = *(m++) ^ *(ti1++);
} while (--n > 0);
}
#ifdef HAVE_SSE2
ti+=incw; ti1+=incw;
#endif
ti += blockoffset;
ti1 += blockoffset;
/* U is a basis but not the canonical basis, so we need to read what
element we just created from T*/
L[(int)mzd_read_bits(T,i,c,k)] = i;
}
/* We need fix the table to update the transformation matrix
correctly; e.g. if the first row has [1 0 1] and we clear a row
below with [1 0 1] we need to encode that this row is cleared by
adding the first row only ([1 0 0]).*/
for(i=1; i < twokay; i++) {
const word correction = (word)codebook[k]->ord[i];
mzd_xor_bits(T, i,c, k, correction);
}
}
void mzd_process_rows2_lqup(mzd_t *M, size_t startrow, size_t stoprow, size_t startcol, int k, mzd_t *T0, size_t *L0, mzd_t *T1, size_t *L1) {
size_t r;
const int ka = k/2;
const int kb = k-k/2;
const size_t blocknuma=startcol/RADIX;
const size_t blocknumb=(startcol+ka)/RADIX;
const size_t blockoffset = blocknumb - blocknuma;
size_t wide = M->width - blocknuma;
if(wide < 3) {
mzd_process_rows(M, startrow, stoprow, startcol, ka, T0, L0);
mzd_process_rows(M, startrow, stoprow, startcol + ka, kb, T1, L1);
return;
}
wide -= 2;
#ifdef HAVE_OPENMP
#pragma omp parallel for private(r) shared(startrow, stoprow) schedule(dynamic,32) if(stoprow-startrow > 128)
#endif
for(r=startrow; r<stoprow; r++) {
const int x0 = L0[ (int)mzd_read_bits(M, r, startcol, ka) ];
word *t0 = T0->rows[x0] + blocknuma;
word *m0 = M->rows[r+0] + blocknuma;
m0[0] ^= t0[0];
m0[1] ^= t0[1];
const int x1 = L1[ (int)mzd_read_bits(M, r, startcol+ka, kb) ];
word *t1 = T1->rows[x1] + blocknumb;
for(size_t i=blockoffset; i<2; i++) {
m0[i] ^= t1[i-blockoffset];
}
t0+=2;
t1+=2-blockoffset;
m0+=2;
register int n = (wide + 7) / 8;
switch (wide % 8) {
case 0: do { *m0++ ^= *t0++ ^ *t1++;
case 7: *m0++ ^= *t0++ ^ *t1++;
case 6: *m0++ ^= *t0++ ^ *t1++;
case 5: *m0++ ^= *t0++ ^ *t1++;
case 4: *m0++ ^= *t0++ ^ *t1++;
case 3: *m0++ ^= *t0++ ^ *t1++;
case 2: *m0++ ^= *t0++ ^ *t1++;
case 1: *m0++ ^= *t0++ ^ *t1++;
} while (--n > 0);
}
}
}
void mzd_process_rows3_lqup(mzd_t *M, size_t startrow, size_t stoprow, size_t startcol, int k, mzd_t *T0, size_t *L0, mzd_t *T1, size_t *L1, mzd_t *T2, size_t *L2) {
size_t r;
const int rem = k%3;
const int ka = k/3 + ((rem>=2) ? 1 : 0);
const int kb = k/3 + ((rem>=1) ? 1 : 0);
const int kc = k/3;
const size_t blocknuma=startcol/RADIX;
const size_t blocknumb=(startcol+ka)/RADIX;
const size_t blocknumc=(startcol+ka+kb)/RADIX;
const size_t blockoffsetb = blocknumb - blocknuma;
const size_t blockoffsetc = blocknumc - blocknuma;
size_t wide = M->width - blocknuma;
if(wide < 4) {
mzd_process_rows(M, startrow, stoprow, startcol, ka, T0, L0);
mzd_process_rows(M, startrow, stoprow, startcol + ka, kb, T1, L1);
mzd_process_rows(M, startrow, stoprow, startcol + ka + kb, kc, T2, L2);
return;
}
wide -= 3;
#ifdef HAVE_OPENMP
#pragma omp parallel for private(r) shared(startrow, stoprow) schedule(dynamic,32) if(stoprow-startrow > 128)
#endif
for(r=startrow; r<stoprow; r++) {
const int x0 = L0[ (int)mzd_read_bits(M, r, startcol, ka) ];
word *t0 = T0->rows[x0] + blocknuma;
word *m0 = M->rows[r] + blocknuma;
m0[0] ^= t0[0];
m0[1] ^= t0[1];
m0[2] ^= t0[2];
t0+=3;
const int x1 = L1[ (int)mzd_read_bits(M, r, startcol+ka, kb) ];
word *t1 = T1->rows[x1] + blocknumb;
for(size_t i=blockoffsetb; i<3; i++) {
m0[i] ^= t1[i-blockoffsetb];
}
t1+=3-blockoffsetb;
const int x2 = L2[ (int)mzd_read_bits(M, r, startcol+ka+kb, kc) ];
word *t2 = T2->rows[x2] + blocknumc;
for(size_t i=blockoffsetc; i<3; i++) {
m0[i] ^= t2[i-blockoffsetc];
}
t2+=3-blockoffsetc;
m0+=3;
register int n = (wide + 7) / 8;
switch (wide % 8) {
case 0: do { *m0++ ^= *t0++ ^ *t1++ ^ *t2++;
case 7: *m0++ ^= *t0++ ^ *t1++ ^ *t2++;
case 6: *m0++ ^= *t0++ ^ *t1++ ^ *t2++;
case 5: *m0++ ^= *t0++ ^ *t1++ ^ *t2++;
case 4: *m0++ ^= *t0++ ^ *t1++ ^ *t2++;
case 3: *m0++ ^= *t0++ ^ *t1++ ^ *t2++;
case 2: *m0++ ^= *t0++ ^ *t1++ ^ *t2++;
case 1: *m0++ ^= *t0++ ^ *t1++ ^ *t2++;
} while (--n > 0);
}
}
}
void mzd_process_rows4_lqup(mzd_t *M, size_t startrow, size_t stoprow, size_t startcol, int k, mzd_t *T0, size_t *L0, mzd_t *T1, size_t *L1, mzd_t *T2, size_t *L2, mzd_t *T3, size_t *L3) {
size_t r;
const int rem = k%4;
const int ka = k/4 + ((rem>=3) ? 1 : 0);
const int kb = k/4 + ((rem>=2) ? 1 : 0);
const int kc = k/4 + ((rem>=1) ? 1 : 0);
const int kd = k/4;
const size_t blocknuma=startcol/RADIX;
const size_t blocknumb=(startcol+ka)/RADIX;
const size_t blocknumc=(startcol+ka+kb)/RADIX;
const size_t blocknumd=(startcol+ka+kb+kc)/RADIX;
const size_t blockoffsetb = blocknumb - blocknuma;
const size_t blockoffsetc = blocknumc - blocknuma;
const size_t blockoffsetd = blocknumd - blocknuma;
size_t wide = M->width - blocknuma;
if(wide < 5) {
mzd_process_rows(M, startrow, stoprow, startcol, ka, T0, L0);
mzd_process_rows(M, startrow, stoprow, startcol + ka, kb, T1, L1);
mzd_process_rows(M, startrow, stoprow, startcol + ka + kb, kc, T2, L2);
mzd_process_rows(M, startrow, stoprow, startcol + ka + kb + kc, kd, T3, L3);
return;
}
wide -= 4;
#ifdef HAVE_OPENMP
#pragma omp parallel for private(r) shared(startrow, stoprow) schedule(dynamic,32) if(stoprow-startrow > 128)
#endif
for(r=startrow; r<stoprow; r++) {
const int x0 = L0[ (int)mzd_read_bits(M, r, startcol, ka) ];
word *t0 = T0->rows[x0] + blocknuma;
word *m0 = M->rows[r] + blocknuma;
m0[0] ^= t0[0];
m0[1] ^= t0[1];
m0[2] ^= t0[2];
m0[3] ^= t0[3];
t0+=4;
const int x1 = L1[ (int)mzd_read_bits(M, r, startcol+ka, kb) ];
word *t1 = T1->rows[x1] + blocknumb;
for(size_t i=blockoffsetb; i<4; i++) {
m0[i] ^= t1[i-blockoffsetb];
}
t1+=4-blockoffsetb;
const int x2 = L2[ (int)mzd_read_bits(M, r, startcol+ka+kb, kc) ];
word *t2 = T2->rows[x2] + blocknumc;
for(size_t i=blockoffsetc; i<4; i++) {
m0[i] ^= t2[i-blockoffsetc];
}
t2+=4-blockoffsetc;
const int x3 = L3[ (int)mzd_read_bits(M, r, startcol+ka+kb+kc, kd) ];
word *t3 = T3->rows[x3] + blocknumd;
for(size_t i=blockoffsetd; i<4; i++) {
m0[i] ^= t3[i-blockoffsetd];
}
t3+=4-blockoffsetd;
m0+=4;
register int n = (wide + 7) / 8;
switch (wide % 8) {
case 0: do { *m0++ ^= *t0++ ^ *t1++ ^ *t2++ ^ *t3++;
case 7: *m0++ ^= *t0++ ^ *t1++ ^ *t2++ ^ *t3++;
case 6: *m0++ ^= *t0++ ^ *t1++ ^ *t2++ ^ *t3++;
case 5: *m0++ ^= *t0++ ^ *t1++ ^ *t2++ ^ *t3++;
case 4: *m0++ ^= *t0++ ^ *t1++ ^ *t2++ ^ *t3++;
case 3: *m0++ ^= *t0++ ^ *t1++ ^ *t2++ ^ *t3++;
case 2: *m0++ ^= *t0++ ^ *t1++ ^ *t2++ ^ *t3++;
case 1: *m0++ ^= *t0++ ^ *t1++ ^ *t2++ ^ *t3++;
} while (--n > 0);
}
}
}
/* extract U from A for table creation */
mzd_t *_mzd_lqup_to_u(mzd_t *U, mzd_t *A, size_t r, size_t c, int k) {
/* this function call is now rather cheap, but it could be avoided
completetly if needed */
assert(U->offset == 0);
assert(A->offset == 0);
size_t i, j;
size_t startcol = (c/RADIX)*RADIX;
mzd_submatrix(U, A, r, 0, r+k, A->ncols);
for(i=0; i<(size_t)k; i++)
for(j=startcol; j<c+i; j++)
mzd_write_bit(U, i, j, 0);
return U;
}
/* method of many people factorisation */
size_t _mzd_lqup_mmpf(mzd_t *A, mzp_t * P, mzp_t * Q, int k) {
assert(A->offset == 0);
const size_t nrows = A->nrows;//mzd_first_zero_row(A);
const size_t ncols = A->ncols;
size_t curr_row = 0;
size_t curr_col = 0;
size_t kbar = 0;
size_t done_row = 0;
if(k == 0) {
k = m4ri_opt_k(nrows, ncols, 0);
}
int kk = 4*k;
for(size_t i = 0; i<ncols; i++)
Q->values[i] = i;
for(size_t i = 0; i<A->nrows; i++)
P->values[i] = i;
mzd_t *T0 = mzd_init(TWOPOW(k), ncols);
mzd_t *T1 = mzd_init(TWOPOW(k), ncols);
mzd_t *T2 = mzd_init(TWOPOW(k), ncols);
mzd_t *T3 = mzd_init(TWOPOW(k), ncols);
mzd_t *U = mzd_init(kk, ncols);
size_t *L0 = (size_t *)m4ri_mm_calloc(TWOPOW(k), sizeof(size_t));
size_t *L1 = (size_t *)m4ri_mm_calloc(TWOPOW(k), sizeof(size_t));
size_t *L2 = (size_t *)m4ri_mm_calloc(TWOPOW(k), sizeof(size_t));
size_t *L3 = (size_t *)m4ri_mm_calloc(TWOPOW(k), sizeof(size_t));
size_t *done = (size_t *)m4ri_mm_malloc(kk * sizeof(size_t));
while(curr_col < ncols && curr_row < nrows) {
if(curr_col + kk > ncols)
kk = ncols - curr_col;
/* 1. compute LQUP factorisation for a kxk submatrix */
kbar = _mzd_lqup_submatrix(A, curr_row, nrows, curr_col, kk, P, Q, done, &done_row);
/* 2. extract U */
_mzd_lqup_to_u(U, A, curr_row, curr_col, kbar);
if(kbar > (size_t)3*k) {
const int rem = kbar%4;
const int ka = kbar/4 + ((rem>=3) ? 1 : 0);
const int kb = kbar/4 + ((rem>=2) ? 1 : 0);
const int kc = kbar/4 + ((rem>=1) ? 1 : 0);
const int kd = kbar/4;
if (kbar==kk) {
/* 2. generate table T */
mzd_make_table_lqup(U, 0, curr_col, ka, T0, L0);
mzd_make_table_lqup(U, 0+ka, curr_col+ka, kb, T1, L1);
mzd_make_table_lqup(U, 0+ka+kb, curr_col+ka+kb, kc, T2, L2);
mzd_make_table_lqup(U, 0+ka+kb+kc, curr_col+ka+kb+kc, kd, T3, L3);
/* 3. use that table to process remaining rows below */
mzd_process_rows4_lqup(A, done_row + 1, nrows, curr_col, kbar, T0, L0, T1, L1, T2, L2, T3, L3);
} else {
curr_col += 1;
}
} else if(kbar > (size_t)2*k) {
const int rem = kbar%3;
const int ka = kbar/3 + ((rem>=2) ? 1 : 0);
const int kb = kbar/3 + ((rem>=1) ? 1 : 0);
const int kc = kbar/3;
if (kbar==kk) {
/* 2. generate table T */
mzd_make_table_lqup(U, 0, curr_col, ka, T0, L0);
mzd_make_table_lqup(U, 0+ka, curr_col+ka, kb, T1, L1);
mzd_make_table_lqup(U, 0+ka+kb, curr_col+ka+kb, kc, T2, L2);
/* 3. use that table to process remaining rows below */
mzd_process_rows3_lqup(A, done_row + 1, nrows, curr_col, kbar, T0, L0, T1, L1, T2, L2);
} else {
curr_col += 1;
}
} else if(kbar > (size_t)k) {
const int ka = kbar/2;
const int kb = kbar - ka;
if(kbar==kk) {
/* 2. generate table T */
mzd_make_table_lqup(U, 0, curr_col, ka, T0, L0);
mzd_make_table_lqup(U, 0+ka, curr_col+ka, kb, T1, L1);
/* 3. use that table to process remaining rows below */
mzd_process_rows2_lqup(A, done_row + 1, nrows, curr_col, kbar, T0, L0, T1, L1);
} else {
curr_col += 1;
}
} else if(kbar > 0) {
if(kbar==kk) {
/* 2. generate table T */
mzd_make_table_lqup(U, 0, curr_col, kbar, T0, L0);
/* 3. use that table to process remaining rows below */
mzd_process_rows(A, done_row + 1, nrows, curr_col, kbar, T0, L0);
} else {
curr_col += 1;
}
} else {
curr_col += 1;
size_t i = curr_row;
size_t j = curr_col;
int found = mzd_find_pivot(A, curr_row, curr_col, &i, &j);
if(found) {
P->values[curr_row] = i;
Q->values[curr_row] = j;
mzd_row_swap(A, curr_row, i);
const size_t wrd = j/RADIX;
const word bm = ONE<<(RADIX-(j%RADIX)-1);
for(size_t l = curr_row+1; l<nrows; l++)
if(A->rows[l][wrd] & bm)
mzd_row_add_offset(A, l, curr_row, j + 1);
curr_col = j + 1;
curr_row++;
} else {
break;
}
}
curr_col += kbar;
curr_row += kbar;
if (kbar > 0)
if (kbar == kk && kk < 4*k)
kk = kbar + 1;
else
kk = kbar;
else if(kk>2)
kk = kk/2;
}
/* Now compressing L*/
for (size_t j = 0; j<curr_row; ++j){
if (Q->values[j]>j) {
mzd_col_swap_in_rows(A,Q->values[j], j, j, curr_row);
}
}
mzp_t *Qbar = mzp_init_window(Q,0,curr_row);
mzd_apply_p_right_trans_even_capped(A, Qbar, curr_row, 0);
mzp_free_window(Qbar);
mzd_free(U);
mzd_free(T0);
mzd_free(T1);
mzd_free(T2);
mzd_free(T3);
m4ri_mm_free(L0);
m4ri_mm_free(L1);
m4ri_mm_free(L2);
m4ri_mm_free(L3);
m4ri_mm_free(done);
return curr_row;
}
size_t _mzd_pluq_mmpf(mzd_t *A, mzp_t * P, mzp_t * Q, const int k) {
size_t r = _mzd_lqup_mmpf(A,P,Q,k);
mzd_apply_p_right_tri(A, Q);
return r;
}
|
yp/Heu-MCHC
|
pers-lib/m4ri/src/m4ri.h
|
<gh_stars>1-10
/**
* \file m4ri.h
* \brief Main include file for the M4RI library.
*
* \author <NAME> <<EMAIL>>
* \author <NAME> <<EMAIL>>
*/
/******************************************************************************
*
* M4RI: Linear Algebra over GF(2)
*
* Copyright (C) 2007 <NAME> <<EMAIL>>
* Copyright (C) 2007,2008 <NAME> <<EMAIL>>
*
* Distributed under the terms of the GNU General Public License (GPL)
* version 2 or higher.
*
* This code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* The full text of the GPL is available at:
*
* http://www.gnu.org/licenses/
******************************************************************************/
#ifndef M4RI_H
#define M4RI_H
/**
* \mainpage
*
* M4RI is a library to do fast arithmetic with dense matrices over
* \f$F_2\f$. M4RI is available under the GPLv2+ and used by the Sage
* mathematics software and the PolyBoRi library. See
* http://m4ri.sagemath.org for details.
*
* \example testsuite/test_multiplication.c
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#ifdef __cplusplus
extern "C" {
#endif //__cplusplus
#include "permutation.h"
#include "packedmatrix.h"
#include "brilliantrussian.h"
#include "strassen.h"
#include "grayflex.h"
#include "parity.h"
#include "trsm.h"
#include "lqup.h"
#include "pluq_mmpf.h"
#include "solve.h"
#ifdef __cplusplus
}
#endif //__cplusplus
#endif //M4RI_H
|
yp/Heu-MCHC
|
pers-lib/m4ri/testsuite/test_multiplication.c
|
#include <stdlib.h>
#include "m4ri/m4ri.h"
/**
* Check that the results of all implemented multiplication algorithms
* match up.
*
* \param m Number of rows of A
* \param l Number of columns of A/number of rows of B
* \param n Number of columns of B
* \param k Parameter k of M4RM algorithm, may be 0 for automatic choice.
* \param cutoff Cut off parameter at which dimension to switch from
* Strassen to M4RM
*/
int mul_test_equality(int m, int l, int n, int k, int cutoff) {
int ret = 0;
mzd_t *A, *B, *C, *D, *E;
printf(" mul: m: %4d, l: %4d, n: %4d, k: %2d, cutoff: %4d",m,l,n,k,cutoff);
/* we create two random matrices */
A = mzd_init(m, l);
B = mzd_init(l, n);
mzd_randomize(A);
mzd_randomize(B);
/* C = A*B via Strassen */
C = mzd_mul(NULL, A, B, cutoff);
/* D = A*B via M4RM, temporary buffers are managed internally */
D = mzd_mul_m4rm( NULL, A, B, k);
/* E = A*B via naive cubic multiplication */
E = mzd_mul_naive( NULL, A, B);
mzd_free(A);
mzd_free(B);
if (mzd_equal(C, D) != TRUE) {
printf(" Strassen != M4RM");
ret -=1;
}
if (mzd_equal(D, E) != TRUE) {
printf(" M4RM != Naiv");
ret -= 1;
}
if (mzd_equal(C, E) != TRUE) {
printf(" Strassen != Naiv");
ret -= 1;
}
mzd_free(C);
mzd_free(D);
mzd_free(E);
if(ret==0) {
printf(" ... passed\n");
} else {
printf(" ... FAILED\n");
}
return ret;
}
/**
* Check that the results of all implemented squaring algorithms match
* up.
*
* \param m Number of rows and columns of A
* \param k Parameter k of M4RM algorithm, may be 0 for automatic choice.
* \param cutoff Cut off parameter at which dimension to switch from
* Strassen to M4RM
*/
int sqr_test_equality(int m, int k, int cutoff) {
int ret = 0;
mzd_t *A, *C, *D, *E;
printf(" sqr: m: %4d, k: %2d, cutoff: %4d",m,k,cutoff);
/* we create one random matrix */
A = mzd_init(m, m);
mzd_randomize(A);
/* C = A*A via Strassen */
C = mzd_mul(NULL, A, A, cutoff);
/* D = A*A via M4RM, temporary buffers are managed internally */
D = mzd_mul_m4rm( NULL, A, A, k);
/* E = A*A via naive cubic multiplication */
E = mzd_mul_naive( NULL, A, A);
mzd_free(A);
if (mzd_equal(C, D) != TRUE) {
printf(" Strassen != M4RM");
ret -=1;
}
if (mzd_equal(D, E) != TRUE) {
printf(" M4RM != Naiv");
ret -= 1;
}
if (mzd_equal(C, E) != TRUE) {
printf(" Strassen != Naiv");
ret -= 1;
}
mzd_free(C);
mzd_free(D);
mzd_free(E);
if(ret==0) {
printf(" ... passed\n");
} else {
printf(" ... FAILED\n");
}
return ret;
}
int addmul_test_equality(int m, int l, int n, int k, int cutoff) {
int ret = 0;
mzd_t *A, *B, *C, *D, *E, *F;
printf("addmul: m: %4d, l: %4d, n: %4d, k: %2d, cutoff: %4d",m,l,n,k,cutoff);
/* we create two random matrices */
A = mzd_init(m, l);
B = mzd_init(l, n);
C = mzd_init(m, n);
mzd_randomize(A);
mzd_randomize(B);
mzd_randomize(C);
/* D = C + A*B via M4RM, temporary buffers are managed internally */
D = mzd_copy(NULL, C);
D = mzd_addmul_m4rm(D, A, B, k);
/* E = C + A*B via naiv cubic multiplication */
E = mzd_mul_m4rm(NULL, A, B, k);
mzd_add(E, E, C);
/* F = C + A*B via naiv cubic multiplication */
F = mzd_copy(NULL, C);
F = mzd_addmul(F, A, B, cutoff);
mzd_free(A);
mzd_free(B);
mzd_free(C);
if (mzd_equal(D, E) != TRUE) {
printf(" M4RM != add,mul");
ret -=1;
}
if (mzd_equal(E, F) != TRUE) {
printf(" add,mul = addmul");
ret -=1;
}
if (mzd_equal(F, D) != TRUE) {
printf(" M4RM != addmul");
ret -=1;
}
if (ret==0)
printf(" ... passed\n");
else
printf(" ... FAILED\n");
mzd_free(D);
mzd_free(E);
mzd_free(F);
return ret;
}
int addsqr_test_equality(int m, int k, int cutoff) {
int ret = 0;
mzd_t *A, *C, *D, *E, *F;
printf("addsqr: m: %4d, k: %2d, cutoff: %4d",m,k,cutoff);
/* we create two random matrices */
A = mzd_init(m, m);
C = mzd_init(m, m);
mzd_randomize(A);
mzd_randomize(C);
/* D = C + A*B via M4RM, temporary buffers are managed internally */
D = mzd_copy(NULL, C);
D = mzd_addmul_m4rm(D, A, A, k);
/* E = C + A*B via naive cubic multiplication */
E = mzd_mul_m4rm(NULL, A, A, k);
mzd_add(E, E, C);
/* F = C + A*B via naive cubic multiplication */
F = mzd_copy(NULL, C);
F = mzd_addmul(F, A, A, cutoff);
mzd_free(A);
mzd_free(C);
if (mzd_equal(D, E) != TRUE) {
printf(" M4RM != add,mul");
ret -=1;
}
if (mzd_equal(E, F) != TRUE) {
printf(" add,mul = addmul");
ret -=1;
}
if (mzd_equal(F, D) != TRUE) {
printf(" M4RM != addmul");
ret -=1;
}
if (ret==0)
printf(" ... passed\n");
else
printf(" ... FAILED\n");
mzd_free(D);
mzd_free(E);
mzd_free(F);
return ret;
}
int main(int argc, char **argv) {
int status = 0;
status += mul_test_equality(1, 1, 1, 0, 1024);
status += mul_test_equality(1, 128, 128, 0, 0);
status += mul_test_equality(3, 131, 257, 0, 0);
status += mul_test_equality(64, 64, 64, 0, 64);
status += mul_test_equality(128, 128, 128, 0, 64);
status += mul_test_equality(21, 171, 31, 0, 63);
status += mul_test_equality(21, 171, 31, 0, 131);
status += mul_test_equality(193, 65, 65, 10, 64);
status += mul_test_equality(1025, 1025, 1025, 3, 256);
status += mul_test_equality(2048, 2048, 4096, 0, 1024);
status += mul_test_equality(4096, 3528, 4096, 0, 1024);
status += mul_test_equality(1024, 1025, 1, 0, 1024);
status += mul_test_equality(1000,1000,1000, 0, 256);
status += mul_test_equality(1000,10,20, 0, 64);
status += mul_test_equality(1710,1290,1000, 0, 256);
status += mul_test_equality(1290, 1710, 200, 0, 64);
status += mul_test_equality(1290, 1710, 2000, 0, 256);
status += mul_test_equality(1290, 1290, 2000, 0, 64);
status += mul_test_equality(1000, 210, 200, 0, 64);
status += addmul_test_equality(1, 128, 128, 0, 0);
status += addmul_test_equality(3, 131, 257, 0, 0);
status += addmul_test_equality(64, 64, 64, 0, 64);
status += addmul_test_equality(128, 128, 128, 0, 64);
status += addmul_test_equality(21, 171, 31, 0, 63);
status += addmul_test_equality(21, 171, 31, 0, 131);
status += addmul_test_equality(193, 65, 65, 10, 64);
status += addmul_test_equality(1025, 1025, 1025, 3, 256);
status += addmul_test_equality(4096, 4096, 4096, 0, 2048);
status += addmul_test_equality(1000,1000,1000, 0, 256);
status += addmul_test_equality(1000,10,20, 0, 64);
status += addmul_test_equality(1710,1290,1000, 0, 256);
status += addmul_test_equality(1290, 1710, 200, 0, 64);
status += addmul_test_equality(1290, 1710, 2000, 0, 256);
status += addmul_test_equality(1290, 1290, 2000, 0, 64);
status += addmul_test_equality(1000, 210, 200, 0, 64);
status += sqr_test_equality(1, 0, 1024);
status += sqr_test_equality(128, 0, 0);
status += sqr_test_equality(131, 0, 0);
status += sqr_test_equality(64, 0, 64);
status += sqr_test_equality(128, 0, 64);
status += sqr_test_equality(171, 0, 63);
status += sqr_test_equality(171, 0, 131);
status += sqr_test_equality(193, 10, 64);
status += sqr_test_equality(1025, 3, 256);
status += sqr_test_equality(2048, 0, 1024);
status += sqr_test_equality(3528, 0, 1024);
status += sqr_test_equality(1000, 0, 256);
status += sqr_test_equality(1000, 0, 64);
status += sqr_test_equality(1710, 0, 256);
status += sqr_test_equality(1290, 0, 64);
status += sqr_test_equality(2000, 0, 256);
status += sqr_test_equality(2000, 0, 64);
status += sqr_test_equality(210, 0, 64);
status += addsqr_test_equality(1, 0, 0);
status += addsqr_test_equality(131, 0, 0);
status += addsqr_test_equality(64, 0, 64);
status += addsqr_test_equality(128, 0, 64);
status += addsqr_test_equality(171, 0, 63);
status += addsqr_test_equality(171, 0, 131);
status += addsqr_test_equality(193, 10, 64);
status += addsqr_test_equality(1025, 3, 256);
status += addsqr_test_equality(4096, 0, 2048);
status += addsqr_test_equality(1000, 0, 256);
status += addsqr_test_equality(1000, 0, 64);
status += addsqr_test_equality(1710, 0, 256);
status += addsqr_test_equality(1290, 0, 64);
status += addsqr_test_equality(2000, 0, 256);
status += addsqr_test_equality(2000, 0, 64);
status += addsqr_test_equality(210, 0, 64);
if (status == 0) {
printf("All tests passed.\n");
return 0;
} else {
return -1;
}
}
|
yp/Heu-MCHC
|
pers-lib/m4ri/testsuite/test_elimination.c
|
<reponame>yp/Heu-MCHC
#include <stdlib.h>
#include "m4ri/m4ri.h"
int elim_test_equality(int nr, int nc) {
int ret = 0;
printf("elim: m: %4d, n: %4d ",nr,nc);
mzd_t *A = mzd_init(nr, nc);
mzd_randomize(A);
mzd_t *B = mzd_copy(NULL, A);
mzd_t *C = mzd_copy(NULL, A);
mzd_t *D = mzd_copy(NULL, A);
mzd_t *E = mzd_copy(NULL, A);
mzd_t *F = mzd_copy(NULL, A);
mzd_t *G = mzd_copy(NULL, A);
/* M4RI k=auto */
mzd_echelonize_m4ri(A, 1, 0);
/* M4RI k=8 */
mzd_echelonize_m4ri(B, 1, 8);
/* M4RI Upper Triangular k=auto*/
mzd_echelonize_m4ri(C, 0, 0);
mzd_top_echelonize_m4ri(C, 0);
/* M4RI Upper Triangular k=4*/
mzd_echelonize_m4ri(D, 0, 4);
mzd_top_echelonize_m4ri(D, 4);
/* Gauss */
mzd_echelonize_naive(E, 1);
/* Gauss Upper Triangular */
mzd_echelonize_naive(F, 0);
mzd_top_echelonize_m4ri(F, 0);
/* PLUQ */
mzd_echelonize_pluq(G, 1);
if(mzd_equal(A, B) != TRUE) {
printf("A != B ");
ret -= 1;
}
if(mzd_equal(B, C) != TRUE) {
printf("B != C ");
ret -= 1;
}
if(mzd_equal(D, E) != TRUE) {
printf("D != E ");
ret -= 1;
}
if(mzd_equal(E, F) != TRUE) {
printf("E != F ");
ret -= 1;
}
if(mzd_equal(F, G) != TRUE) {
printf("F != G ");
ret -= 1;
}
if(mzd_equal(G, A) != TRUE) {
printf("G != A ");
ret -= 1;
}
mzd_free(A);
mzd_free(B);
mzd_free(C);
mzd_free(D);
mzd_free(E);
mzd_free(F);
mzd_free(G);
if(ret == 0) {
printf(" ... passed\n");
} else {
printf(" ... FAILED\n");
}
return ret;
}
int main(int argc, char **argv) {
int status = 0;
status += elim_test_equality(100, 100);
status += elim_test_equality(21, 171);
status += elim_test_equality(31, 121);
status += elim_test_equality(193, 65);
status += elim_test_equality(1025, 1025);
status += elim_test_equality(2048, 2048);
status += elim_test_equality(64, 64);
status += elim_test_equality(128, 128);
status += elim_test_equality(4096, 3528);
status += elim_test_equality(1024, 1025);
status += elim_test_equality(1000,1000);
status += elim_test_equality(1000,10);
status += elim_test_equality(1710,1290);
status += elim_test_equality(1290, 1710);
status += elim_test_equality(1290, 1710);
status += elim_test_equality(1290, 1290);
status += elim_test_equality(1000, 210);
if (status == 0) {
printf("All tests passed.\n");
return 0;
} else {
return -1;
}
}
|
yp/Heu-MCHC
|
pers-lib/m4ri/testsuite/test_lqup.c
|
<filename>pers-lib/m4ri/testsuite/test_lqup.c
#include <stdlib.h>
#include "m4ri/m4ri.h"
int test_lqup_full_rank (size_t m, size_t n){
printf("pluq: testing full rank m: %5zu, n: %5zu",m,n);
mzd_t* U = mzd_init (m,n);
mzd_t* L = mzd_init (m,m);
mzd_t* U2 = mzd_init (m,n);
mzd_t* L2 = mzd_init (m,m);
mzd_t* A = mzd_init (m,n);
mzd_randomize (U);
mzd_randomize (L);
size_t i,j;
for (i=0; i<m; ++i){
for (j=0; j<i && j<n;++j)
mzd_write_bit(U,i,j, 0);
for (j=i+1; j<m;++j)
mzd_write_bit(L,i,j, 0);
if(i<n)
mzd_write_bit(U,i,i, 1);
mzd_write_bit(L,i,i, 1);
}
mzd_mul(A, L, U, 2048);
mzd_t* Acopy = mzd_copy (NULL,A);
mzp_t* P = mzp_init(m);
mzp_t* Q = mzp_init(n);
mzd_pluq(A, P, Q, 2048);
for (i=0; i<m; ++i){
for (j=0; j<i && j <n;++j)
mzd_write_bit (L2, i, j, mzd_read_bit(A,i,j));
for (j=i+1; j<n;++j)
mzd_write_bit (U2, i, j, mzd_read_bit(A,i,j));
}
for (i=0; i<n && i<m; ++i){
mzd_write_bit(L2,i,i, 1);
mzd_write_bit(U2,i,i, 1);
}
mzd_addmul(Acopy,L2,U2,0);
int status = 0;
for ( i=0; i<m; ++i)
for ( j=0; j<n; ++j){
if (mzd_read_bit (Acopy,i,j)){
status = 1;
}
}
if (status){
printf(" ... FAILED\n");
} else
printf (" ... passed\n");
mzd_free(U);
mzd_free(L);
mzd_free(U2);
mzd_free(L2);
mzd_free(A);
mzd_free(Acopy);
mzp_free(P);
mzp_free(Q);
return status;
}
int test_lqup_half_rank(size_t m, size_t n) {
printf("pluq: testing half rank m: %5zd, n: %5zd",m,n);
mzd_t* U = mzd_init(m, n);
mzd_t* L = mzd_init(m, m);
mzd_t* U2 = mzd_init(m, n);
mzd_t* L2 = mzd_init(m, m);
mzd_t* A = mzd_init(m, n);
mzd_randomize (U);
mzd_randomize (L);
size_t i,j;
for (i=0; i<m && i<n; ++i){
mzd_write_bit(U,i,i, 1);
for (j=0; j<i;++j)
mzd_write_bit(U,i,j, 0);
if (i%2)
for (j=i; j<n;++j)
mzd_write_bit(U,i,j, 0);
for (j=i+1; j<m;++j)
mzd_write_bit(L,i,j, 0);
mzd_write_bit(L,i,i, 1);
}
mzd_mul(A, L, U, 0);
mzd_t* Acopy = mzd_copy (NULL,A);
mzp_t* Pt = mzp_init(m);
mzp_t* Q = mzp_init(n);
int r = mzd_pluq(A, Pt, Q, 0);
for (i=0; i<r; ++i){
for (j=0; j<i;++j)
mzd_write_bit (L2, i, j, mzd_read_bit(A,i,j));
for (j=i+1; j<n;++j)
mzd_write_bit (U2, i, j, mzd_read_bit(A,i,j));
}
for (i=r; i<m; i++)
for (j=0; j<r;++j)
mzd_write_bit (L2, i, j, mzd_read_bit(A,i,j));
for (i=0; i<r; ++i){
mzd_write_bit(L2,i,i, 1);
mzd_write_bit(U2,i,i, 1);
}
mzd_apply_p_left(Acopy, Pt);
mzd_apply_p_right_trans(Acopy, Q);
mzd_addmul(Acopy,L2,U2,0);
int status = 0;
for ( i=0; i<m; ++i) {
for ( j=0; j<n; ++j){
if (mzd_read_bit(Acopy,i,j)){
status = 1;
}
}
if(status)
break;
}
if (status)
printf(" ... FAILED\n");
else
printf (" ... passed\n");
mzd_free(U);
mzd_free(L);
mzd_free(U2);
mzd_free(L2);
mzd_free(A);
mzd_free(Acopy);
mzp_free(Pt);
mzp_free(Q);
return status;
}
int test_lqup_structured(size_t m, size_t n) {
printf("pluq: testing structured m: %5zd, n: %5zd", m, n);
size_t i,j;
mzd_t* A = mzd_init(m, n);
mzd_t* L = mzd_init(m, m);
mzd_t* U = mzd_init(m, n);
for(i=0; i<m; i+=2)
for (j=i; j<n; j++)
mzd_write_bit(A, i, j, 1);
mzd_t* Acopy = mzd_copy (NULL,A);
mzp_t* P = mzp_init(m);
mzp_t* Q = mzp_init(n);
int r;
r=mzd_pluq(A, P, Q, 0);
printf(", rank: %5d ",r);
for (i=0; i<r; ++i){
for (j=0; j<i;++j)
mzd_write_bit(L, i, j, mzd_read_bit(A,i,j));
for (j=i+1; j<n;++j)
mzd_write_bit(U, i, j, mzd_read_bit(A,i,j));
}
for (i=r; i<m; i++)
for (j=0; j<r;++j)
mzd_write_bit(L, i, j, mzd_read_bit(A,i,j));
for (i=0; i<r; ++i){
mzd_write_bit(L,i,i, 1);
mzd_write_bit(U,i,i, 1);
}
mzd_apply_p_left(Acopy, P);
mzd_apply_p_right_trans(Acopy, Q);
mzd_addmul(Acopy, L, U, 0);
int status = 0;
for ( i=0; i<m; ++i)
for ( j=0; j<n; ++j){
if (mzd_read_bit (Acopy,i,j)){
status = 1;
break;
}
}
if (status) {
printf("\n");
printf(" ... FAILED\n");
} else
printf (" ... passed\n");
mzd_free(U);
mzd_free(L);
mzd_free(A);
mzd_free(Acopy);
mzp_free(P);
mzp_free(Q);
return status;
}
int test_lqup_random(size_t m, size_t n) {
printf("pluq: testing random m: %5zd, n: %5zd",m,n);
size_t i,j;
mzd_t* U = mzd_init(m, n);
mzd_t* L = mzd_init(m, m);
mzd_t* A = mzd_init(m, n);
mzd_randomize(A);
mzd_t* Acopy = mzd_copy (NULL,A);
mzp_t* P = mzp_init(m);
mzp_t* Q = mzp_init(n);
int r;
r=mzd_pluq(A, P, Q, 0);
printf(", rank: %5d ",r);
for (i=0; i<r; ++i){
for (j=0; j<i;++j)
mzd_write_bit(L, i, j, mzd_read_bit(A,i,j));
for (j=i+1; j<n;++j)
mzd_write_bit(U, i, j, mzd_read_bit(A,i,j));
}
for (i=r; i<m; i++)
for (j=0; j<r;++j)
mzd_write_bit(L, i, j, mzd_read_bit(A,i,j));
for (i=0; i<r; ++i){
mzd_write_bit(L,i,i, 1);
mzd_write_bit(U,i,i, 1);
}
mzd_apply_p_left(Acopy, P);
mzd_apply_p_right_trans(Acopy, Q);
mzd_addmul(Acopy, L, U, 0);
int status = 0;
for ( i=0; i<m; ++i)
for ( j=0; j<n; ++j){
if (mzd_read_bit (Acopy,i,j)){
status = 1;
break;
}
}
if (status) {
printf(" ... FAILED\n");
} else
printf (" ... passed\n");
mzd_free(U);
mzd_free(L);
mzd_free(A);
mzd_free(Acopy);
mzp_free(P);
mzp_free(Q);
return status;
}
int main(int argc, char **argv) {
int status = 0;
status += test_lqup_structured(37, 37);
status += test_lqup_structured(63, 63);
status += test_lqup_structured(64, 64);
status += test_lqup_structured(65, 65);
status += test_lqup_structured(128, 128);
status += test_lqup_structured(37, 137);
status += test_lqup_structured(65, 5);
status += test_lqup_structured(128, 18);
status += test_lqup_full_rank(13,13);
status += test_lqup_full_rank(37,37);
status += test_lqup_full_rank(63,63);
status += test_lqup_full_rank(64,64);
status += test_lqup_full_rank(65,65);
status += test_lqup_full_rank(97,97);
status += test_lqup_full_rank(128,128);
status += test_lqup_full_rank(150,150);
status += test_lqup_full_rank(256,256);
status += test_lqup_full_rank(1024,1024);
status += test_lqup_full_rank(13,11);
status += test_lqup_full_rank(37,39);
status += test_lqup_full_rank(64,164);
status += test_lqup_full_rank(97,92);
status += test_lqup_full_rank(128,121);
status += test_lqup_full_rank(150,153);
status += test_lqup_full_rank(256,258);
status += test_lqup_full_rank(1024,1023);
status += test_lqup_half_rank(64,64);
status += test_lqup_half_rank(65,65);
status += test_lqup_half_rank(66,66);
status += test_lqup_half_rank(127,127);
status += test_lqup_half_rank(129,129);
status += test_lqup_half_rank(148,148);
status += test_lqup_half_rank(132,132);
status += test_lqup_half_rank(256,256);
status += test_lqup_half_rank(1024,1024);
status += test_lqup_half_rank(129,127);
status += test_lqup_half_rank(132,136);
status += test_lqup_half_rank(256,251);
status += test_lqup_half_rank(1024,2100);
status += test_lqup_random(63,63);
status += test_lqup_random(64,64);
status += test_lqup_random(65,65);
status += test_lqup_random(128,128);
status += test_lqup_random(128, 131);
status += test_lqup_random(132, 731);
status += test_lqup_random(150,150);
status += test_lqup_random(252, 24);
status += test_lqup_random(256,256);
status += test_lqup_random(1024,1022);
status += test_lqup_random(1024,1024);
status += test_lqup_random(128,1280);
status += test_lqup_random(128, 130);
status += test_lqup_random(132, 132);
status += test_lqup_random(150,151);
status += test_lqup_random(252, 2);
status += test_lqup_random(256,251);
status += test_lqup_random(1024,1025);
status += test_lqup_random(1024,1021);
if (!status) {
printf("All tests passed.\n");
return 0;
} else {
return -1;
}
}
|
yp/Heu-MCHC
|
pers-lib/m4ri/src/solve.h
|
<gh_stars>1-10
/**
* \file solve.h
*
* \brief System solving with matrix routines.
*
* \author <NAME> <<EMAIL>>
*
* \attention This file is currently broken.
*/
#ifndef SOLVE_H
#define SOLVE_H
/*******************************************************************
*
* M4RI: Linear Algebra over GF(2)
*
* Copyright (C) 2008 <EMAIL>
*
* Distributed under the terms of the GNU General Public License (GPL)
*
* This code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* The full text of the GPL is available at:
*
* http://www.gnu.org/licenses/
*
********************************************************************/
#include <stdio.h>
#include "misc.h"
#include "permutation.h"
#include "packedmatrix.h"
/**
* \brief Solves A X = B with A and B matrices.
*
* The solution X is stored inplace on B.
*
* \param A Input matrix (overwritten).
* \param B Input matrix, being overwritten by the solution matrix X
* \param cutoff Minimal dimension for Strassen recursion (default: 0).
* \param inconsistency_check decide wether or not to check for
* incosistency (faster without but output not defined if
* system is not consistent).
*
*/
void mzd_solve_left(mzd_t *A, mzd_t *B, const int cutoff,
const int inconsistency_check);
/**
* \brief Solves (P L U Q) X = B
*
* A is an input matrix supposed to store both:
* \li an upper right triangular matrix U
* \li a lower left unitary triangular matrix L.
*
* The solution X is stored inplace on B
*
* This version assumes that the matrices are at an even position on
* the RADIX grid and that their dimension is a multiple of RADIX.
*
* \param A Input upper/lower triangular matrices.
* \param rank is rank of A.
* \param P Input row permutation matrix.
* \param Q Input column permutation matrix.
* \param B Input matrix, being overwritten by the solution matrix X.
* \param cutoff Minimal dimension for Strassen recursion (default: 0).
* \param inconsistency_check decide whether or not to check for
* incosistency (faster without but output not defined if
* system is not consistent).
*/
void mzd_pluq_solve_left (mzd_t *A, size_t rank,
mzp_t *P, mzp_t *Q,
mzd_t *B, const int cutoff, const int inconsistency_check);
/**
* \brief Solves (P L U Q) X = B
*
* A is an input matrix supposed to store both:
* \li an upper right triangular matrix U
* \li a lower left unitary triangular matrix L.
* The solution X is stored inplace on B.
*
* This version assumes that the matrices are at an even position on
* the RADIX grid and that their dimension is a multiple of RADIX.
*
* \param A Input upper/lower triangular matrices.
* \param rank is rank of A.
* \param P Input row permutation matrix.
* \param Q Input column permutation matrix.
* \param B Input matrix, being overwritten by the solution matrix X.
* \param cutoff Minimal dimension for Strassen recursion (default: 0).
* \param inconsistency_check decide whether or not to check for
* incosistency (faster without but output not defined if
* system is not consistent).
*
*/
void _mzd_pluq_solve_left(mzd_t *A, size_t rank,
mzp_t *P, mzp_t *Q,
mzd_t *B, const int cutoff, const int inconsistency_check);
/**
* \brief Solves A X = B with A and B matrices.
*
* The solution X is stored inplace on B.
*
* This version assumes that the matrices are at an even position on
* the RADIX grid and that their dimension is a multiple of RADIX.
*
* \param A Input matrix.
* \param B Input matrix, being overwritten by the solution matrix X.
* \param cutoff Minimal dimension for Strassen recursion (default: 0).
* \param inconsistency_check decide whether or not to check for
* incosistency (faster without but output not defined if
* system is not consistent).
*/
void _mzd_solve_left(mzd_t *A, mzd_t *B, const int cutoff, const int inconsistency_check);
/**
* \brief Solve X for A X = 0.
*
* If r is the rank of the nr x nc matrix A, return the nc x (nc-r)
* matrix X such that A*X == 0 and that the columns of X are linearly
* independent.
*
* \param A Matrix.
* \param cutoff Minimal dimension for Strassen recursion (default: 0).
*
* \wordoffset
*
* \sa mzd_pluq()
*
* \return X
*/
mzd_t *mzd_kernel_left_pluq(mzd_t *A, const int cutoff);
#endif // SOLVE_H
|
yp/Heu-MCHC
|
include/my_time.h
|
<reponame>yp/Heu-MCHC
/**
*
*
* Heu-MCHC
*
* A fast and accurate heuristic algorithm for the haplotype inference
* problem on pedigree data with recombinations and mutations
*
* Copyright (C) 2009,2010,2011 <NAME>
*
* Distributed under the terms of the GNU General Public License (GPL)
*
*
* This file is part of Heu-MCHC.
*
* Heu-MCHC is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Heu-MCHC is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Heu-MCHC. If not, see <http://www.gnu.org/licenses/>.
*
**/
#ifndef _MYTIME_H_
#define _MYTIME_H_
#ifdef __cplusplus
extern "C" {
#endif
#include <stdbool.h>
#include <time.h>
#include <sys/time.h>
#include <stdio.h>
#include "log.h"
#define MYTIME_LOG( timer ) \
do { \
STATS("timer %-22s %15lu microsec", \
MYTIME_getname(timer), \
MYTIME_getinterval(timer)); \
} while (0)
typedef struct _mytime* pmytime;
void
MYTIME_print_interval(FILE*, pmytime);
void
MYTIME_print_current(FILE*, pmytime);
pmytime
MYTIME_create(void);
pmytime
MYTIME_create_with_name(const char*);
void
MYTIME_destroy(pmytime pt);
void
MYTIME_start(pmytime pt);
void
MYTIME_reset(pmytime pt);
void
MYTIME_stop(pmytime pt);
const char*
MYTIME_getname(pmytime pt);
unsigned long
MYTIME_getinterval(pmytime pt);
#ifdef __cplusplus
}
#endif
#endif
|
yp/Heu-MCHC
|
include/log-build-info.h
|
<reponame>yp/Heu-MCHC
/**
*
*
* Heu-MCHC
*
* A fast and accurate heuristic algorithm for the haplotype inference
* problem on pedigree data with recombinations and mutations
*
* Copyright (C) 2009,2010,2011 <NAME>
*
* Distributed under the terms of the GNU General Public License (GPL)
*
*
* This file is part of Heu-MCHC.
*
* Heu-MCHC is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Heu-MCHC is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Heu-MCHC. If not, see <http://www.gnu.org/licenses/>.
*
**/
/*
** log-build-info.h
**
** Made by <NAME>
** Login <yuri@yuri>
**
** Started on Mon Aug 24 00:38:28 2009 <NAME>
** Last update Mon Aug 24 00:38:28 2009 <NAME>
*/
#ifndef __LOG_BUILD_INFO_H__
#define __LOG_BUILD_INFO_H__
#include "log.h"
#ifndef __SRC_DESC
#define __SRC_DESC "not available"
#endif
#ifndef __BUILD_DESC
#define __BUILD_DESC "not available"
#endif
#ifndef __BUILD_DATETIME
#define __BUILD_DATETIME "unknown"
#endif
#ifndef __BUILD_HOST
#define __BUILD_HOST "unknown"
#endif
#ifndef __COMPILER_VER
#ifdef __VERSION__
#define QUOTEME( x ) #x
#define __COMPILER_VER QUOTEME(__VERSION__)
#else
#define __COMPILER_VER "unknown"
#endif
#endif
#define PRINT_SYSTEM_INFORMATIONS \
do { \
INFO("Program compiled %s @ %s.", __BUILD_DATETIME, \
__BUILD_HOST); \
INFO("Source version >%s<.", __SRC_DESC); \
INFO("Configuration %s.", __BUILD_DESC); \
INFO("Compiler %s", __COMPILER_VER); \
} while (0)
#endif /* !LOG-BUILD-INFO_H_ */
|
yp/Heu-MCHC
|
pers-lib/m4ri/src/brilliantrussian.c
|
<filename>pers-lib/m4ri/src/brilliantrussian.c
/*******************************************************************
*
* M4RI: Linear Algebra over GF(2)
*
* Copyright (C) 2007, 2008 <NAME> <<EMAIL>>
* Copyright (C) 2008 <NAME> <<EMAIL>>
*
* Distributed under the terms of the GNU General Public License (GPL)
* version 2 or higher.
*
* This code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* The full text of the GPL is available at:
*
* http://www.gnu.org/licenses/
*
********************************************************************/
#include "misc.h"
#ifdef HAVE_SSE2
#include <emmintrin.h>
#endif
#include <assert.h>
#include "brilliantrussian.h"
#include "grayflex.h"
/**
* \brief Perform Gaussian reduction to reduced row echelon form on a
* submatrix.
*
* The submatrix has dimension at most k starting at r x c of A. Checks
* for pivot rows up to row endrow (exclusive). Terminates as soon as
* finding a pivot column fails.
*
* \param A Matrix.
* \param r First row.
* \param c First column.
* \param k Maximal dimension of identity matrix to produce.
* \param end_row Maximal row index (exclusive) for rows to consider
* for inclusion.
*/
static inline int _mzd_gauss_submatrix_full(mzd_t *A, size_t r, size_t c, size_t end_row, int k) {
assert(k<=RADIX);
size_t i,j,l;
size_t start_row = r;
int found;
for (j=c; j<c+k; j++) {
found = 0;
for (i=start_row; i< end_row; i++) {
/* first we need to clear the first columns */
const word tmp = mzd_read_bits(A,i,c,j-c+1);
const size_t offset = RADIX-(j-c+1);
if(tmp) {
for (l=0; l<j-c; l++)
if (GET_BIT(tmp, offset+l))
mzd_row_add_offset(A, i, r+l, c+l);
/* pivot? */
if (mzd_read_bit(A, i, j)) {
mzd_row_swap(A, i, start_row);
/* clear above */
for (l=r; l<start_row; l++) {
if (mzd_read_bit(A, l, j)) {
mzd_row_add_offset(A, l, start_row, j);
}
}
start_row++;
found = 1;
break;
}
}
}
if (found==0) {
return j - c;
}
}
return j - c;
}
/**
* \brief Perform Gaussian reduction to upper triangular matrix on a
* submatrix.
*
* The submatrix has dimension at most k starting at r x c of A. Checks
* for pivot rows up to row end_row (exclusive). Terminates as soon as
* finding a pivot column fails.
*
* \param A Matrix.
* \param r First row.
* \param c First column.
* \param k Maximal dimension of identity matrix to produce.
* \param end_row Maximal row index (exclusive) for rows to consider
* for inclusion.
*/
static inline int _mzd_gauss_submatrix(mzd_t *A, size_t r, size_t c, size_t end_row, int k) {
size_t i,j,l;
size_t start_row = r;
int found;
for (j=c; j<c+k; j++) {
found = 0;
for (i=start_row; i< end_row; i++) {
/* first we need to clear the first columns */
for (l=0; l<j-c; l++)
if (mzd_read_bit(A, i, c+l))
mzd_row_add_offset(A, i, r+l, c+l);
/* pivot? */
if (mzd_read_bit(A, i, j)) {
mzd_row_swap(A, i, start_row);
start_row++;
found = 1;
break;
}
}
if (found==0) {
return j - c;
}
}
return j - c;
}
/**
* \brief Given a submatrix in upper triangular form compute the
* reduced row echelon form.
*
* The submatrix has dimension at most k starting at r x c of A. Checks
* for pivot rows up to row end_row (exclusive). Terminates as soon as
* finding a pivot column fails.
*
* \param A Matrix.
* \param r First row.
* \param c First column.
* \param k Maximal dimension of identity matrix to produce.
* \param end_row Maximal row index (exclusive) for rows to consider
* for inclusion.
*/
static inline int _mzd_gauss_submatrix_top(mzd_t *A, size_t r, size_t c, int k) {
size_t j,l;
size_t start_row = r;
for (j=c; j<c+k; j++) {
for (l=r; l<start_row; l++) {
if (mzd_read_bit(A, l, j)) {
mzd_row_add_offset(A, l, start_row, j);
}
}
start_row++;
}
return k;
}
static inline void _mzd_copy_back_rows(mzd_t *A, mzd_t *U, size_t r, size_t c, size_t k) {
size_t startblock = c/RADIX;
size_t width = A->width - startblock;
size_t i, j;
for (i=0 ; i < k ; i++) {
const word * const src = U->rows[i] + startblock;
word *const dst = A->rows[r+i] + startblock;
for (j=0; j< width; j++) {
dst[j] = src[j];
}
}
}
void mzd_make_table( mzd_t *M, size_t r, size_t c, int k, mzd_t *T, size_t *L) {
assert(T->blocks[1].size == 0);
const size_t homeblock= c/RADIX;
size_t i, j, rowneeded, id;
size_t twokay= TWOPOW(k);
size_t wide = T->width - homeblock;
word *ti, *ti1, *m;
ti1 = T->rows[0] + homeblock;
ti = ti1 + T->width;
#ifdef HAVE_SSE2
unsigned long incw = 0;
if (T->width & 1) incw = 1;
ti += incw;
#endif
L[0]=0;
for (i=1; i<twokay; i++) {
rowneeded = r + codebook[k]->inc[i-1];
id = codebook[k]->ord[i];
L[id] = i;
if (rowneeded >= M->nrows) {
for (j = 0; j < wide; j++) {
*ti++ = *ti1++;
}
#ifdef HAVE_SSE2
ti+=incw; ti1+=incw;
#endif
} else {
m = M->rows[rowneeded] + homeblock;
/* Duff's device loop unrolling */
register int n = (wide + 7) / 8;
switch (wide % 8) {
case 0: do { *(ti++) = *(m++) ^ *(ti1++);
case 7: *(ti++) = *(m++) ^ *(ti1++);
case 6: *(ti++) = *(m++) ^ *(ti1++);
case 5: *(ti++) = *(m++) ^ *(ti1++);
case 4: *(ti++) = *(m++) ^ *(ti1++);
case 3: *(ti++) = *(m++) ^ *(ti1++);
case 2: *(ti++) = *(m++) ^ *(ti1++);
case 1: *(ti++) = *(m++) ^ *(ti1++);
} while (--n > 0);
}
#ifdef HAVE_SSE2
ti+=incw; ti1+=incw;
#endif
ti += homeblock;
ti1 += homeblock;
}
}
}
void mzd_process_rows(mzd_t *M, size_t startrow, size_t stoprow, size_t startcol, int k, mzd_t *T, size_t *L) {
size_t r;
const size_t blocknum=startcol/RADIX;
size_t wide = M->width - blocknum;
if(k==1) {
word bm = ONE << ((RADIX - startcol - 1) % RADIX);
for (r=startrow; r+2<=stoprow; r+=2) {
word *t = T->rows[1] + blocknum;
word *m0 = M->rows[r+0] + blocknum;
word *m1 = M->rows[r+1] + blocknum;
register int n = (wide + 7) / 8;
if(*m0 & bm) {
if(*m1 & bm) {
switch (wide % 8) {
case 0: do { *m0++ ^= *t; *m1++ ^= *t++;
case 7: *m0++ ^= *t; *m1++ ^= *t++;
case 6: *m0++ ^= *t; *m1++ ^= *t++;
case 5: *m0++ ^= *t; *m1++ ^= *t++;
case 4: *m0++ ^= *t; *m1++ ^= *t++;
case 3: *m0++ ^= *t; *m1++ ^= *t++;
case 2: *m0++ ^= *t; *m1++ ^= *t++;
case 1: *m0++ ^= *t; *m1++ ^= *t++;
} while (--n > 0);
}
} else {
switch (wide % 8) {
case 0: do { *m0++ ^= *t++;
case 7: *m0++ ^= *t++;
case 6: *m0++ ^= *t++;
case 5: *m0++ ^= *t++;
case 4: *m0++ ^= *t++;
case 3: *m0++ ^= *t++;
case 2: *m0++ ^= *t++;
case 1: *m0++ ^= *t++;
} while (--n > 0);
}
}
} else if(*m1 & bm) {
switch (wide % 8) {
case 0: do { *m1++ ^= *t++;
case 7: *m1++ ^= *t++;
case 6: *m1++ ^= *t++;
case 5: *m1++ ^= *t++;
case 4: *m1++ ^= *t++;
case 3: *m1++ ^= *t++;
case 2: *m1++ ^= *t++;
case 1: *m1++ ^= *t++;
} while (--n > 0);
}
}
}
for( ; r<stoprow; r++) {
const int x0 = L[ (int)mzd_read_bits(M, r, startcol, k) ];
word *m0 = M->rows[r] + blocknum;
word *t0 = T->rows[x0] + blocknum;
register int n = (wide + 7) / 8;
switch (wide % 8) {
case 0: do { *m0++ ^= *t0++;
case 7: *m0++ ^= *t0++;
case 6: *m0++ ^= *t0++;
case 5: *m0++ ^= *t0++;
case 4: *m0++ ^= *t0++;
case 3: *m0++ ^= *t0++;
case 2: *m0++ ^= *t0++;
case 1: *m0++ ^= *t0++;
} while (--n > 0);
}
}
return;
}
for (r=startrow; r+2<=stoprow; r+=2) {
const int x0 = L[ (int)mzd_read_bits(M, r+0, startcol, k) ];
const int x1 = L[ (int)mzd_read_bits(M, r+1, startcol, k) ];
word *m0 = M->rows[r+0] + blocknum;
word *t0 = T->rows[x0] + blocknum;
word *m1 = M->rows[r+1] + blocknum;
word *t1 = T->rows[x1] + blocknum;
register int n = (wide + 7) / 8;
switch (wide % 8) {
case 0: do { *m0++ ^= *t0++; *m1++ ^= *t1++;
case 7: *m0++ ^= *t0++; *m1++ ^= *t1++;
case 6: *m0++ ^= *t0++; *m1++ ^= *t1++;
case 5: *m0++ ^= *t0++; *m1++ ^= *t1++;
case 4: *m0++ ^= *t0++; *m1++ ^= *t1++;
case 3: *m0++ ^= *t0++; *m1++ ^= *t1++;
case 2: *m0++ ^= *t0++; *m1++ ^= *t1++;
case 1: *m0++ ^= *t0++; *m1++ ^= *t1++;
} while (--n > 0);
}
}
for( ; r<stoprow; r++) {
const int x0 = L[ (int)mzd_read_bits(M, r, startcol, k) ];
word *m0 = M->rows[r] + blocknum;
word *t0 = T->rows[x0] + blocknum;
register int n = (wide + 7) / 8;
switch (wide % 8) {
case 0: do { *m0++ ^= *t0++;
case 7: *m0++ ^= *t0++;
case 6: *m0++ ^= *t0++;
case 5: *m0++ ^= *t0++;
case 4: *m0++ ^= *t0++;
case 3: *m0++ ^= *t0++;
case 2: *m0++ ^= *t0++;
case 1: *m0++ ^= *t0++;
} while (--n > 0);
}
}
}
void mzd_process_rows2(mzd_t *M, size_t startrow, size_t stoprow, size_t startcol, int k, mzd_t *T0, size_t *L0, mzd_t *T1, size_t *L1) {
size_t r;
const size_t blocknum=startcol/RADIX;
const size_t wide = M->width - blocknum;
const int ka = k/2;
const int kb = k-k/2;
#ifdef HAVE_OPENMP
#pragma omp parallel for private(r) shared(startrow, stoprow) schedule(dynamic,32) if(stoprow-startrow > 128)
#endif
for(r=startrow; r<stoprow; r++) {
const int x0 = L0[ (int)mzd_read_bits(M, r, startcol, ka)];
const int x1 = L1[ (int)mzd_read_bits(M, r, startcol+ka, kb)];
if(x0 == 0 && x1 == 0)
continue;
word * m0 = M->rows[r] + blocknum;
const word *t0 = T0->rows[x0] + blocknum;
const word *t1 = T1->rows[x1] + blocknum;
register int n = (wide + 7) / 8;
switch (wide % 8) {
case 0: do { *m0++ ^= *t0++ ^ *t1++;
case 7: *m0++ ^= *t0++ ^ *t1++;
case 6: *m0++ ^= *t0++ ^ *t1++;
case 5: *m0++ ^= *t0++ ^ *t1++;
case 4: *m0++ ^= *t0++ ^ *t1++;
case 3: *m0++ ^= *t0++ ^ *t1++;
case 2: *m0++ ^= *t0++ ^ *t1++;
case 1: *m0++ ^= *t0++ ^ *t1++;
} while (--n > 0);
}
}
}
void mzd_process_rows3(mzd_t *M, size_t startrow, size_t stoprow, size_t startcol, int k, mzd_t *T0, size_t *L0, mzd_t *T1, size_t *L1, mzd_t *T2, size_t *L2) {
size_t r;
const size_t blocknum=startcol/RADIX;
const size_t wide = M->width - blocknum;
int rem = k%3;
const int ka = k/3 + ((rem>=2) ? 1 : 0);
const int kb = k/3 + ((rem>=1) ? 1 : 0);
const int kc = k/3;
#ifdef HAVE_OPENMP
#pragma omp parallel for private(r) shared(startrow, stoprow) schedule(dynamic,32) if(stoprow-startrow > 128)
#endif
for(r=startrow; r<stoprow; r++) {
const int x0 = L0[ (int)mzd_read_bits(M, r, startcol, ka)];
const int x1 = L1[ (int)mzd_read_bits(M, r, startcol+ka, kb)];
const int x2 = L2[ (int)mzd_read_bits(M, r, startcol+ka+kb, kc)];
if(x0 == 0 && x1 == 0 && x2 == 0)
continue;
word * m0 = M->rows[r] + blocknum;
const word *t0 = T0->rows[x0] + blocknum;
const word *t1 = T1->rows[x1] + blocknum;
const word *t2 = T2->rows[x2] + blocknum;
register int n = (wide + 7) / 8;
switch (wide % 8) {
case 0: do { *m0++ ^= *t0++ ^ *t1++ ^ *t2++;
case 7: *m0++ ^= *t0++ ^ *t1++ ^ *t2++;
case 6: *m0++ ^= *t0++ ^ *t1++ ^ *t2++;
case 5: *m0++ ^= *t0++ ^ *t1++ ^ *t2++;
case 4: *m0++ ^= *t0++ ^ *t1++ ^ *t2++;
case 3: *m0++ ^= *t0++ ^ *t1++ ^ *t2++;
case 2: *m0++ ^= *t0++ ^ *t1++ ^ *t2++;
case 1: *m0++ ^= *t0++ ^ *t1++ ^ *t2++;
} while (--n > 0);
}
}
}
void mzd_process_rows4(mzd_t *M, size_t startrow, size_t stoprow, size_t startcol, int k,
mzd_t *T0, size_t *L0, mzd_t *T1, size_t *L1, mzd_t *T2, size_t *L2, mzd_t *T3, size_t *L3) {
size_t r;
const size_t blocknum=startcol/RADIX;
const size_t wide = M->width - blocknum;
int rem = k%4;
const int ka = k/4 + ((rem>=3) ? 1 : 0);
const int kb = k/4 + ((rem>=2) ? 1 : 0);
const int kc = k/4 + ((rem>=1) ? 1 : 0);
const int kd = k/4;
#ifdef HAVE_OPENMP
#pragma omp parallel for private(r) shared(startrow, stoprow) schedule(dynamic,32) if(stoprow-startrow > 128)
#endif
for(r=startrow; r<stoprow; r++) {
const int x0 = L0[ (int)mzd_read_bits(M, r, startcol, ka)];
const int x1 = L1[ (int)mzd_read_bits(M, r, startcol+ka, kb)];
const int x2 = L2[ (int)mzd_read_bits(M, r, startcol+ka+kb, kc)];
const int x3 = L3[ (int)mzd_read_bits(M, r, startcol+ka+kb+kc, kd)];
if(x0 == 0 && x1 == 0 && x2 == 0 && x3 == 0)
continue;
word * m0 = M->rows[r] + blocknum;
const word *t0 = T0->rows[x0] + blocknum;
const word *t1 = T1->rows[x1] + blocknum;
const word *t2 = T2->rows[x2] + blocknum;
const word *t3 = T3->rows[x3] + blocknum;
register int n = (wide + 7) / 8;
switch (wide % 8) {
case 0: do { *m0++ ^= *t0++ ^ *t1++ ^ *t2++ ^ *t3++;
case 7: *m0++ ^= *t0++ ^ *t1++ ^ *t2++ ^ *t3++;
case 6: *m0++ ^= *t0++ ^ *t1++ ^ *t2++ ^ *t3++;
case 5: *m0++ ^= *t0++ ^ *t1++ ^ *t2++ ^ *t3++;
case 4: *m0++ ^= *t0++ ^ *t1++ ^ *t2++ ^ *t3++;
case 3: *m0++ ^= *t0++ ^ *t1++ ^ *t2++ ^ *t3++;
case 2: *m0++ ^= *t0++ ^ *t1++ ^ *t2++ ^ *t3++;
case 1: *m0++ ^= *t0++ ^ *t1++ ^ *t2++ ^ *t3++;
} while (--n > 0);
}
}
}
void mzd_process_rows5(mzd_t *M, size_t startrow, size_t stoprow, size_t startcol, int k,
mzd_t *T0, size_t *L0, mzd_t *T1, size_t *L1, mzd_t *T2, size_t *L2, mzd_t *T3, size_t *L3,
mzd_t *T4, size_t *L4) {
size_t r;
const size_t blocknum=startcol/RADIX;
const size_t wide = M->width - blocknum;
int rem = k%5;
const int ka = k/5 + ((rem>=4) ? 1 : 0);
const int kb = k/5 + ((rem>=3) ? 1 : 0);
const int kc = k/5 + ((rem>=2) ? 1 : 0);
const int kd = k/5 + ((rem>=1) ? 1 : 0);
const int ke = k/5;
#ifdef HAVE_OPENMP
#pragma omp parallel for private(r) shared(startrow, stoprow) schedule(dynamic,32) if(stoprow-startrow > 128)
#endif
for(r=startrow; r<stoprow; r++) {
const int x0 = L0[ (int)mzd_read_bits(M, r, startcol, ka)];
const int x1 = L1[ (int)mzd_read_bits(M, r, startcol+ka, kb)];
const int x2 = L2[ (int)mzd_read_bits(M, r, startcol+ka+kb, kc)];
const int x3 = L3[ (int)mzd_read_bits(M, r, startcol+ka+kb+kc, kd)];
const int x4 = L4[ (int)mzd_read_bits(M, r, startcol+ka+kb+kc+kd, ke)];
if(x0 == 0 && x1 == 0 && x2 == 0 && x3 == 0 && x4 == 0)
continue;
word * m0 = M->rows[r] + blocknum;
const word *t0 = T0->rows[x0] + blocknum;
const word *t1 = T1->rows[x1] + blocknum;
const word *t2 = T2->rows[x2] + blocknum;
const word *t3 = T3->rows[x3] + blocknum;
const word *t4 = T4->rows[x4] + blocknum;
register int n = (wide + 7) / 8;
switch (wide % 8) {
case 0: do { *m0++ ^= *t0++ ^ *t1++ ^ *t2++ ^ *t3++ ^ *t4++;
case 7: *m0++ ^= *t0++ ^ *t1++ ^ *t2++ ^ *t3++ ^ *t4++;
case 6: *m0++ ^= *t0++ ^ *t1++ ^ *t2++ ^ *t3++ ^ *t4++;
case 5: *m0++ ^= *t0++ ^ *t1++ ^ *t2++ ^ *t3++ ^ *t4++;
case 4: *m0++ ^= *t0++ ^ *t1++ ^ *t2++ ^ *t3++ ^ *t4++;
case 3: *m0++ ^= *t0++ ^ *t1++ ^ *t2++ ^ *t3++ ^ *t4++;
case 2: *m0++ ^= *t0++ ^ *t1++ ^ *t2++ ^ *t3++ ^ *t4++;
case 1: *m0++ ^= *t0++ ^ *t1++ ^ *t2++ ^ *t3++ ^ *t4++;
} while (--n > 0);
}
}
}
void mzd_process_rows6(mzd_t *M, size_t startrow, size_t stoprow, size_t startcol, int k,
mzd_t *T0, size_t *L0, mzd_t *T1, size_t *L1, mzd_t *T2, size_t *L2, mzd_t *T3, size_t *L3,
mzd_t *T4, size_t *L4, mzd_t *T5, size_t *L5) {
size_t r;
const size_t blocknum=startcol/RADIX;
const size_t wide = M->width - blocknum;
int rem = k%6;
const int ka = k/6 + ((rem>=5) ? 1 : 0);
const int kb = k/6 + ((rem>=4) ? 1 : 0);
const int kc = k/6 + ((rem>=3) ? 1 : 0);
const int kd = k/6 + ((rem>=2) ? 1 : 0);
const int ke = k/6 + ((rem>=1) ? 1 : 0);;
const int kf = k/6;
#ifdef HAVE_OPENMP
#pragma omp parallel for private(r) shared(startrow, stoprow) schedule(dynamic,32) if(stoprow-startrow > 128)
#endif
for(r=startrow; r<stoprow; r++) {
const int x0 = L0[ (int)mzd_read_bits(M, r, startcol, ka)];
const int x1 = L1[ (int)mzd_read_bits(M, r, startcol+ka, kb)];
const int x2 = L2[ (int)mzd_read_bits(M, r, startcol+ka+kb, kc)];
const int x3 = L3[ (int)mzd_read_bits(M, r, startcol+ka+kb+kc, kd)];
const int x4 = L4[ (int)mzd_read_bits(M, r, startcol+ka+kb+kc+kd, ke)];
const int x5 = L5[ (int)mzd_read_bits(M, r, startcol+ka+kb+kc+kd+ke, kf)];
if(x0 == 0 && x1 == 0 && x2 == 0 && x3 == 0 && x4 == 0 && x5 == 0)
continue;
word * m0 = M->rows[r] + blocknum;
const word *t0 = T0->rows[x0] + blocknum;
const word *t1 = T1->rows[x1] + blocknum;
const word *t2 = T2->rows[x2] + blocknum;
const word *t3 = T3->rows[x3] + blocknum;
const word *t4 = T4->rows[x4] + blocknum;
const word *t5 = T5->rows[x5] + blocknum;
register int n = (wide + 7) / 8;
switch (wide % 8) {
case 0: do { *m0++ ^= *t0++ ^ *t1++ ^ *t2++ ^ *t3++ ^ *t4++ ^ *t5++;
case 7: *m0++ ^= *t0++ ^ *t1++ ^ *t2++ ^ *t3++ ^ *t4++ ^ *t5++;
case 6: *m0++ ^= *t0++ ^ *t1++ ^ *t2++ ^ *t3++ ^ *t4++ ^ *t5++;
case 5: *m0++ ^= *t0++ ^ *t1++ ^ *t2++ ^ *t3++ ^ *t4++ ^ *t5++;
case 4: *m0++ ^= *t0++ ^ *t1++ ^ *t2++ ^ *t3++ ^ *t4++ ^ *t5++;
case 3: *m0++ ^= *t0++ ^ *t1++ ^ *t2++ ^ *t3++ ^ *t4++ ^ *t5++;
case 2: *m0++ ^= *t0++ ^ *t1++ ^ *t2++ ^ *t3++ ^ *t4++ ^ *t5++;
case 1: *m0++ ^= *t0++ ^ *t1++ ^ *t2++ ^ *t3++ ^ *t4++ ^ *t5++;
} while (--n > 0);
}
}
}
size_t mzd_echelonize_m4ri(mzd_t *A, int full, int k) {
/**
* \par General algorithm
* \li Step 1.Denote the first column to be processed in a given
* iteration as \f$a_i\f$. Then, perform Gaussian elimination on the
* first \f$3k\f$ rows after and including the \f$i\f$-th row to
* produce an identity matrix in \f$a_{i,i} ... a_{i+k-1,i+k-1},\f$
* and zeroes in \f$a_{i+k,i} ... a_{i+3k-1,i+k-1}\f$.
*
* \li Step 2. Construct a table consisting of the \f$2^k\f$ binary strings of
* length k in a Gray code. Thus with only \f$2^k\f$ vector
* additions, all possible linear combinations of these k rows
* have been precomputed.
*
* \li Step 3. One can rapidly process the remaining rows from \f$i +
* 3k\f$ until row \f$m\f$ (the last row) by using the table. For
* example, suppose the \f$j\f$-th row has entries \f$a_{j,i}
* ... a_{j,i+k-1}\f$ in the columns being processed. Selecting the
* row of the table associated with this k-bit string, and adding it
* to row j will force the k columns to zero, and adjust the
* remaining columns from \f$ i + k\f$ to n in the appropriate way,
* as if Gaussian elimination had been performed.
*
* \li Step 4. While the above form of the algorithm will reduce a
* system of boolean linear equations to unit upper triangular form,
* and thus permit a system to be solved with back substitution, the
* M4RI algorithm can also be used to invert a matrix, or put the
* system into reduced row echelon form (RREF). Simply run Step 3
* on rows \f$0 ... i-1\f$ as well as on rows \f$i + 3k
* ... m\f$. This only affects the complexity slightly, changing the
* 2.5 coeffcient to 3.
*
* \attention This function implements a variant of the algorithm
* described above.
*/
const size_t ncols = A->ncols;
size_t r = 0;
size_t c = 0;
int kbar = 0;
if (k == 0) {
k = m4ri_opt_k(A->nrows, A->ncols, 0);
if (k>=7)
k = 7;
if ( (6*(1<<k)*A->ncols / 8.0) > CPU_L2_CACHE / 2.0 )
k -= 1;
}
/*printf("k: %d\n",k);*/
int kk = 6*k;
mzd_t *U = mzd_init(kk, A->ncols);
mzd_t *T0 = mzd_init(TWOPOW(k), A->ncols);
mzd_t *T1 = mzd_init(TWOPOW(k), A->ncols);
mzd_t *T2 = mzd_init(TWOPOW(k), A->ncols);
mzd_t *T3 = mzd_init(TWOPOW(k), A->ncols);
mzd_t *T4 = mzd_init(TWOPOW(k), A->ncols);
mzd_t *T5 = mzd_init(TWOPOW(k), A->ncols);
size_t *L0 = (size_t *)m4ri_mm_calloc(TWOPOW(k), sizeof(size_t));
size_t *L1 = (size_t *)m4ri_mm_calloc(TWOPOW(k), sizeof(size_t));
size_t *L2 = (size_t *)m4ri_mm_calloc(TWOPOW(k), sizeof(size_t));
size_t *L3 = (size_t *)m4ri_mm_calloc(TWOPOW(k), sizeof(size_t));
size_t *L4 = (size_t *)m4ri_mm_calloc(TWOPOW(k), sizeof(size_t));
size_t *L5 = (size_t *)m4ri_mm_calloc(TWOPOW(k), sizeof(size_t));
while(c<ncols) {
if(c+kk > A->ncols) {
kk = ncols - c;
}
if (full) {
kbar = _mzd_gauss_submatrix_full(A, r, c, A->nrows, kk);
} else {
kbar = _mzd_gauss_submatrix(A, r, c, A->nrows, kk);
/* this isn't necessary, adapt make_table */
U = mzd_submatrix(U, A, r, 0, r+kbar, A->ncols);
_mzd_gauss_submatrix_top(A, r, c, kbar);
}
if (kbar>5*k) {
const int rem = kbar%6;
const int ka = kbar/6 + ((rem>=5) ? 1 : 0);
const int kb = kbar/6 + ((rem>=4) ? 1 : 0);
const int kc = kbar/6 + ((rem>=3) ? 1 : 0);
const int kd = kbar/6 + ((rem>=2) ? 1 : 0);
const int ke = kbar/6 + ((rem>=1) ? 1 : 0);;
const int kf = kbar/6;
if(full || kbar==kk) {
mzd_make_table(A, r, c, ka, T0, L0);
mzd_make_table(A, r+ka, c, kb, T1, L1);
mzd_make_table(A, r+ka+kb, c, kc, T2, L2);
mzd_make_table(A, r+ka+kb+kc, c, kd, T3, L3);
mzd_make_table(A, r+ka+kb+kc+kd, c, ke, T4, L4);
mzd_make_table(A, r+ka+kb+kc+kd+ke, c, kf, T5, L5);
}
if(kbar==kk)
mzd_process_rows6(A, r+kbar, A->nrows, c, kbar, T0, L0, T1, L1, T2, L2, T3, L3, T4, L4, T5, L5);
if(full)
mzd_process_rows6(A, 0, r, c, kbar, T0, L0, T1, L1, T2, L2, T3, L3, T4, L4, T5, L5);
} else if (kbar>4*k) {
const int rem = kbar%5;
const int ka = kbar/5 + ((rem>=4) ? 1 : 0);
const int kb = kbar/5 + ((rem>=3) ? 1 : 0);
const int kc = kbar/5 + ((rem>=2) ? 1 : 0);
const int kd = kbar/5 + ((rem>=1) ? 1 : 0);
const int ke = kbar/5;
if(full || kbar==kk) {
mzd_make_table(A, r, c, ka, T0, L0);
mzd_make_table(A, r+ka, c, kb, T1, L1);
mzd_make_table(A, r+ka+kb, c, kc, T2, L2);
mzd_make_table(A, r+ka+kb+kc, c, kd, T3, L3);
mzd_make_table(A, r+ka+kb+kc+kd, c, ke, T4, L4);
}
if(kbar==kk)
mzd_process_rows5(A, r+kbar, A->nrows, c, kbar, T0, L0, T1, L1, T2, L2, T3, L3, T4, L4);
if(full)
mzd_process_rows5(A, 0, r, c, kbar, T0, L0, T1, L1, T2, L2, T3, L3, T4, L4);
} else if (kbar>3*k) {
const int rem = kbar%4;
const int ka = kbar/4 + ((rem>=3) ? 1 : 0);
const int kb = kbar/4 + ((rem>=2) ? 1 : 0);
const int kc = kbar/4 + ((rem>=1) ? 1 : 0);
const int kd = kbar/4;
if(full || kbar==kk) {
mzd_make_table(A, r, c, ka, T0, L0);
mzd_make_table(A, r+ka, c, kb, T1, L1);
mzd_make_table(A, r+ka+kb, c, kc, T2, L2);
mzd_make_table(A, r+ka+kb+kc, c, kd, T3, L3);
}
if(kbar==kk)
mzd_process_rows4(A, r+kbar, A->nrows, c, kbar, T0, L0, T1, L1, T2, L2, T3, L3);
if(full)
mzd_process_rows4(A, 0, r, c, kbar, T0, L0, T1, L1, T2, L2, T3, L3);
} else if (kbar>2*k) {
int rem = kbar%3;
int ka = kbar/3 + ((rem>=2) ? 1 : 0);
int kb = kbar/3 + ((rem>=1) ? 1 : 0);
int kc = kbar/3;
if(full || kbar==kk) {
mzd_make_table(A, r, c, ka, T0, L0);
mzd_make_table(A, r+ka, c, kb, T1, L1);
mzd_make_table(A, r+ka+kb, c, kc, T2, L2);
}
if(kbar==kk)
mzd_process_rows3(A, r+kbar, A->nrows, c, kbar, T0, L0, T1, L1, T2, L2);
if(full)
mzd_process_rows3(A, 0, r, c, kbar, T0, L0, T1, L1, T2, L2);
} else if (kbar>k) {
const int ka = kbar/2;
const int kb = kbar - ka;
if(full || kbar==kk) {
mzd_make_table(A, r, c, ka, T0, L0);
mzd_make_table(A, r+ka, c, kb, T1, L1);
}
if(kbar==kk)
mzd_process_rows2(A, r+kbar, A->nrows, c, kbar, T0, L0, T1, L1);
if(full)
mzd_process_rows2(A, 0, r, c, kbar, T0, L0, T1, L1);
} else if(kbar > 0) {
if(full || kbar==kk) {
mzd_make_table(A, r, c, kbar, T0, L0);
}
if(kbar==kk)
mzd_process_rows(A, r+kbar, A->nrows, c, kbar, T0, L0);
if(full)
mzd_process_rows(A, 0, r, c, kbar, T0, L0);
}
if (!full) {
_mzd_copy_back_rows(A, U, r, c, kbar);
}
r += kbar;
c += kbar;
if(kk!=kbar) {
size_t cbar;
size_t rbar;
if (mzd_find_pivot(A, r, c, &rbar, &cbar)) {
c = cbar;
mzd_row_swap(A, r, rbar);
} else {
break;
}
//c++;
}
}
mzd_free(T0);
m4ri_mm_free(L0);
mzd_free(T1);
m4ri_mm_free(L1);
mzd_free(T2);
m4ri_mm_free(L2);
mzd_free(T3);
m4ri_mm_free(L3);
mzd_free(T4);
m4ri_mm_free(L4);
mzd_free(T5);
m4ri_mm_free(L5);
mzd_free(U);
return r;
}
void mzd_top_echelonize_m4ri(mzd_t *A, int k) {
const size_t ncols = A->ncols;
size_t r = 0;
size_t c = 0;
int kbar = 0;
if (k == 0) {
k = m4ri_opt_k(A->nrows, A->ncols, 0);
if (k>5) {
k -= 4;
}
}
int kk = 4*k;
mzd_t *T0 = mzd_init(TWOPOW(k), A->ncols);
mzd_t *T1 = mzd_init(TWOPOW(k), A->ncols);
mzd_t *T2 = mzd_init(TWOPOW(k), A->ncols);
mzd_t *T3 = mzd_init(TWOPOW(k), A->ncols);
size_t *L0 = (size_t *)m4ri_mm_calloc(TWOPOW(k), sizeof(size_t));
size_t *L1 = (size_t *)m4ri_mm_calloc(TWOPOW(k), sizeof(size_t));
size_t *L2 = (size_t *)m4ri_mm_calloc(TWOPOW(k), sizeof(size_t));
size_t *L3 = (size_t *)m4ri_mm_calloc(TWOPOW(k), sizeof(size_t));
while(c<ncols) {
if(c+kk > A->ncols) {
kk = ncols - c;
}
kbar = _mzd_gauss_submatrix_full(A, r, c, A->nrows, kk);
if (kbar>3*k) {
const int rem = kbar%4;
const int ka = kbar/4 + ((rem>=3) ? 1 : 0);
const int kb = kbar/4 + ((rem>=2) ? 1 : 0);
const int kc = kbar/4 + ((rem>=1) ? 1 : 0);
const int kd = kbar/4;
mzd_make_table(A, r, c, ka, T0, L0);
mzd_make_table(A, r+ka, c, kb, T1, L1);
mzd_make_table(A, r+ka+kb, c, kc, T2, L2);
mzd_make_table(A, r+ka+kb+kc, c, kd, T3, L3);
mzd_process_rows4(A, 0, r, c, kbar, T0, L0, T1, L1, T2, L2, T3, L3);
} else if (kbar>2*k) {
int rem = kbar%3;
int ka = kbar/3 + ((rem>=2) ? 1 : 0);
int kb = kbar/3 + ((rem>=1) ? 1 : 0);
int kc = kbar/3;
mzd_make_table(A, r, c, ka, T0, L0);
mzd_make_table(A, r+ka, c, kb, T1, L1);
mzd_make_table(A, r+ka+kb, c, kc, T2, L2);
mzd_process_rows3(A, 0, r, c, kbar, T0, L0, T1, L1, T2, L2);
} else if (kbar>k) {
const int ka = kbar/2;
const int kb = kbar - ka;
mzd_make_table(A, r, c, ka, T0, L0);
mzd_make_table(A, r+ka, c, kb, T1, L1);
mzd_process_rows2(A, 0, r, c, kbar, T0, L0, T1, L1);
} else if(kbar > 0) {
mzd_make_table(A, r, c, kbar, T0, L0);
mzd_process_rows(A, 0, r, c, kbar, T0, L0);
}
r += kbar;
c += kbar;
if(kk!=kbar) {
c++;
}
}
mzd_free(T0);
m4ri_mm_free(L0);
mzd_free(T1);
m4ri_mm_free(L1);
mzd_free(T2);
m4ri_mm_free(L2);
mzd_free(T3);
m4ri_mm_free(L3);
}
mzd_t *mzd_invert_m4ri(mzd_t *m, mzd_t *I, int k) {
mzd_t *big = mzd_concat(NULL, m, I);
size_t size=m->ncols;
if (k == 0) {
k = m4ri_opt_k(m->nrows, m->ncols, 0);
}
size_t twokay=TWOPOW(k);
size_t i;
mzd_t *T=mzd_init(twokay, size*2);
size_t *L=(size_t *)m4ri_mm_malloc(twokay * sizeof(size_t));
mzd_t *answer;
mzd_echelonize_m4ri(big, TRUE, k);
for(i=0; i < size; i++) {
if (!mzd_read_bit(big, i,i )) {
answer = NULL;
break;
}
}
if (i == size)
answer=mzd_submatrix(NULL, big, 0, size, size, size*2);
m4ri_mm_free(L);
mzd_free(T);
mzd_free(big);
return answer;
}
mzd_t *mzd_mul_m4rm(mzd_t *C, mzd_t *A, mzd_t *B, int k) {
size_t a = A->nrows;
size_t c = B->ncols;
if(A->ncols != B->nrows)
m4ri_die("mzd_mul_m4rm: A ncols (%d) need to match B nrows (%d).\n", A->ncols, B->nrows);
if (C == NULL) {
C = mzd_init(a, c);
} else {
if (C->nrows != a || C->ncols != c)
m4ri_die("mzd_mul_m4rm: C (%d x %d) has wrong dimensions.\n", C->nrows, C->ncols);
}
return _mzd_mul_m4rm(C, A, B, k, TRUE);
}
mzd_t *mzd_addmul_m4rm(mzd_t *C, mzd_t *A, mzd_t *B, int k) {
size_t a = A->nrows;
size_t c = B->ncols;
if(C->ncols == 0 || C->nrows == 0)
return C;
if(A->ncols != B->nrows)
m4ri_die("mzd_mul_m4rm A ncols (%d) need to match B nrows (%d) .\n", A->ncols, B->nrows);
if (C == NULL) {
C = mzd_init(a, c);
} else {
if (C->nrows != a || C->ncols != c)
m4ri_die("mzd_mul_m4rm: C has wrong dimensions.\n");
}
return _mzd_mul_m4rm(C, A, B, k, FALSE);
}
#ifdef HAVE_SSE2
static inline void _mzd_combine8(word *c, word *t1, word *t2, word *t3, word *t4, word *t5, word *t6, word *t7, word *t8, int wide) {
size_t i;
/* assuming t1 ... t8 are aligned, but c might not be */
if (ALIGNMENT(c,16)==0) {
__m128i *__c = (__m128i*)c;
__m128i *__t1 = (__m128i*)t1;
__m128i *__t2 = (__m128i*)t2;
__m128i *__t3 = (__m128i*)t3;
__m128i *__t4 = (__m128i*)t4;
__m128i *__t5 = (__m128i*)t5;
__m128i *__t6 = (__m128i*)t6;
__m128i *__t7 = (__m128i*)t7;
__m128i *__t8 = (__m128i*)t8;
const __m128i *eof = (__m128i*)((unsigned long)(c + wide) & ~0xF);
__m128i xmm1;
while(__c < eof) {
xmm1 = _mm_xor_si128(*__c, *__t1++);
xmm1 = _mm_xor_si128(xmm1, *__t2++);
xmm1 = _mm_xor_si128(xmm1, *__t3++);
xmm1 = _mm_xor_si128(xmm1, *__t4++);
xmm1 = _mm_xor_si128(xmm1, *__t5++);
xmm1 = _mm_xor_si128(xmm1, *__t6++);
xmm1 = _mm_xor_si128(xmm1, *__t7++);
xmm1 = _mm_xor_si128(xmm1, *__t8++);
*__c++ = xmm1;
}
c = (word*)__c;
t1 = (word*)__t1;
t2 = (word*)__t2;
t3 = (word*)__t3;
t4 = (word*)__t4;
t5 = (word*)__t5;
t6 = (word*)__t6;
t7 = (word*)__t7;
t8 = (word*)__t8;
wide = ((sizeof(word)*wide)%16)/sizeof(word);
}
for(i=0; i<wide; i++) {
c[i] ^= t1[i] ^ t2[i] ^ t3[i] ^ t4[i] ^ t5[i] ^ t6[i] ^ t7[i] ^ t8[i];
}
}
#else
#define _mzd_combine8(c,t1,t2,t3,t4,t5,t6,t7,t8,wide) for(ii=0; ii<wide ; ii++) c[ii] ^= t1[ii] ^ t2[ii] ^ t3[ii] ^ t4[ii] ^ t5[ii] ^ t6[ii] ^ t7[ii] ^ t8[ii]
#endif
#ifdef HAVE_SSE2
static inline void _mzd_combine4(word *c, word *t1, word *t2, word *t3, word *t4, size_t wide) {
size_t i;
/* assuming t1 ... t4 are aligned, but c might not be */
if (ALIGNMENT(c,16)==0) {
__m128i *__c = (__m128i*)c;
__m128i *__t1 = (__m128i*)t1;
__m128i *__t2 = (__m128i*)t2;
__m128i *__t3 = (__m128i*)t3;
__m128i *__t4 = (__m128i*)t4;
const __m128i *eof = (__m128i*)((unsigned long)(c + wide) & ~0xF);
__m128i xmm1;
while(__c < eof) {
xmm1 = _mm_xor_si128(*__c, *__t1++);
xmm1 = _mm_xor_si128(xmm1, *__t2++);
xmm1 = _mm_xor_si128(xmm1, *__t3++);
xmm1 = _mm_xor_si128(xmm1, *__t4++);
*__c++ = xmm1;
}
c = (word*)__c;
t1 = (word*)__t1;
t2 = (word*)__t2;
t3 = (word*)__t3;
t4 = (word*)__t4;
wide = ((sizeof(word)*wide)%16)/sizeof(word);
}
for(i=0; i<wide; i++) {
c[i] ^= t1[i] ^ t2[i] ^ t3[i] ^ t4[i];
}
}
#else
#define _mzd_combine4(c, t1, t2, t3, t4, wide) for(ii=0; ii<wide ; ii++) c[ii] ^= t1[ii] ^ t2[ii] ^ t3[ii] ^ t4[ii]
#endif //HAVE_SSE2
#ifdef HAVE_SSE2
static inline void _mzd_combine2(word *c, word *t1, word *t2, size_t wide) {
size_t i;
/* assuming t1 ... t2 are aligned, but c might not be */
if (ALIGNMENT(c,16)==0) {
__m128i *__c = (__m128i*)c;
__m128i *__t1 = (__m128i*)t1;
__m128i *__t2 = (__m128i*)t2;
const __m128i *eof = (__m128i*)((unsigned long)(c + wide) & ~0xF);
__m128i xmm1;
while(__c < eof) {
xmm1 = _mm_xor_si128(*__c, *__t1++);
xmm1 = _mm_xor_si128(xmm1, *__t2++);
*__c++ = xmm1;
}
c = (word*)__c;
t1 = (word*)__t1;
t2 = (word*)__t2;
wide = ((sizeof(word)*wide)%16)/sizeof(word);
}
for(i=0; i<wide; i++) {
c[i] ^= t1[i] ^ t2[i];
}
}
#else
#define _mzd_combine2(c, t1, t2, wide) for(ii=0; ii<wide ; ii++) c[ii] ^= t1[ii] ^ t2[ii]
#endif //HAVE_SSE2
#ifdef M4RM_GRAY8
#define _MZD_COMBINE _mzd_combine8(c, t1, t2, t3, t4, t5, t6, t7, t8, wide)
#else //M4RM_GRAY8
#define _MZD_COMBINE _mzd_combine4(c, t1, t2, t3, t4, wide)
#endif //M4RM_GRAY8
mzd_t *_mzd_mul_m4rm(mzd_t *C, mzd_t *A, mzd_t *B, int k, int clear) {
/**
* The algorithm proceeds as follows:
*
* Step 1. Make a Gray code table of all the \f$2^k\f$ linear combinations
* of the \f$k\f$ rows of \f$B_i\f$. Call the \f$x\f$-th row
* \f$T_x\f$.
*
* Step 2. Read the entries
* \f$a_{j,(i-1)k+1}, a_{j,(i-1)k+2} , ... , a_{j,(i-1)k+k}.\f$
*
* Let \f$x\f$ be the \f$k\f$ bit binary number formed by the
* concatenation of \f$a_{j,(i-1)k+1}, ... , a_{j,ik}\f$.
*
* Step 3. for \f$h = 1,2, ... , c\f$ do
* calculate \f$C_{jh} = C_{jh} + T_{xh}\f$.
*/
assert(A->offset==0);
assert(B->offset==0);
assert(C->offset==0);
size_t i,j;
size_t ii;
unsigned int x1, x2, x3, x4;
word *t1, *t2, *t3, *t4;
#ifdef M4RM_GRAY8
unsigned int x5, x6, x7, x8;
word *t5, *t6, *t7, *t8;
#endif
word *c;
size_t a_nr = A->nrows;
size_t a_nc = A->ncols;
size_t b_nc = B->ncols;
if (b_nc < RADIX-10 || a_nr < 16) {
if(clear)
return mzd_mul_naive(C, A, B);
else
return mzd_addmul_naive(C, A, B);
}
size_t wide = C->width;
/* clear first */
if (clear) {
mzd_set_ui(C, 0);
}
const size_t blocksize = MZD_MUL_BLOCKSIZE;
if (k == 0) {
k = m4ri_opt_k(blocksize, a_nc, b_nc);
#ifdef M4RM_GRAY8
if (k>3)
k -= 2;
/* reduce k further if that has a chance of hitting L1 */
const size_t tsize = (int)(0.8*(TWOPOW(k) * b_nc));
if(tsize > CPU_L1_CACHE && tsize/2 <= CPU_L1_CACHE)
k -= 1;
#else
if (k>2)
k -= 1;
#endif
}
#ifndef M4RM_GRAY8
size_t *buffer = (size_t*)m4ri_mm_malloc(4 * TWOPOW(k) * sizeof(size_t));
#else
size_t *buffer = (size_t*)m4ri_mm_malloc(8 * TWOPOW(k) * sizeof(size_t));
#endif
mzd_t *T1 = mzd_init(TWOPOW(k), b_nc);
size_t *L1 = buffer;
mzd_t *T2 = mzd_init(TWOPOW(k), b_nc);
size_t *L2 = buffer + 1*TWOPOW(k);
mzd_t *T3 = mzd_init(TWOPOW(k), b_nc);
size_t *L3 = buffer + 2*TWOPOW(k);
mzd_t *T4 = mzd_init(TWOPOW(k), b_nc);
size_t *L4 = buffer + 3*TWOPOW(k);
#ifdef M4RM_GRAY8
mzd_t *T5 = mzd_init(TWOPOW(k), b_nc);
size_t *L5 = buffer + 4*TWOPOW(k);
mzd_t *T6 = mzd_init(TWOPOW(k), b_nc);
size_t *L6 = buffer + 5*TWOPOW(k);
mzd_t *T7 = mzd_init(TWOPOW(k), b_nc);
size_t *L7 = buffer + 6*TWOPOW(k);
mzd_t *T8 = mzd_init(TWOPOW(k), b_nc);
size_t *L8 = buffer + 7*TWOPOW(k);
#endif
/* process stuff that fits into multiple of k first, but blockwise (babystep-giantstep)*/
size_t babystep, giantstep;
#ifdef M4RM_GRAY8
const int kk = 8*k;
#else
const int kk = 4*k;
#endif
const size_t end = a_nc/kk;
for (giantstep=0; giantstep + blocksize <= a_nr; giantstep += blocksize) {
for(i=0; i < end; i++) {
mzd_make_table( B, i*kk, 0, k, T1, L1);
mzd_make_table( B, i*kk+k, 0, k, T2, L2);
mzd_make_table( B, i*kk+k+k, 0, k, T3, L3);
mzd_make_table( B, i*kk+k+k+k, 0, k, T4, L4);
#ifdef M4RM_GRAY8
mzd_make_table( B, i*kk+k+k+k+k, 0, k, T5, L5);
mzd_make_table( B, i*kk+k+k+k+k+k, 0, k, T6, L6);
mzd_make_table( B, i*kk+k+k+k+k+k+k, 0, k, T7, L7);
mzd_make_table( B, i*kk+k+k+k+k+k+k+k, 0, k, T8, L8);
#endif
for(babystep = 0; babystep < blocksize; babystep++) {
j = giantstep + babystep;
x1 = L1[ (int)mzd_read_bits(A, j, i*kk, k) ];
x2 = L2[ (int)mzd_read_bits(A, j, i*kk+k, k) ];
x3 = L3[ (int)mzd_read_bits(A, j, i*kk+k+k, k) ];
x4 = L4[ (int)mzd_read_bits(A, j, i*kk+k+k+k, k) ];
#ifdef M4RM_GRAY8
x5 = L5[ (int)mzd_read_bits(A, j, i*kk+k+k+k+k, k) ];
x6 = L6[ (int)mzd_read_bits(A, j, i*kk+k+k+k+k+k, k) ];
x7 = L7[ (int)mzd_read_bits(A, j, i*kk+k+k+k+k+k+k, k) ];
x8 = L8[ (int)mzd_read_bits(A, j, i*kk+k+k+k+k+k+k+k, k) ];
#endif
c = C->rows[j];
t1 = T1->rows[x1];
t2 = T2->rows[x2];
t3 = T3->rows[x3];
t4 = T4->rows[x4];
#ifdef M4RM_GRAY8
t5 = T5->rows[x5];
t6 = T6->rows[x6];
t7 = T7->rows[x7];
t8 = T8->rows[x8];
#endif
_MZD_COMBINE;
}
}
}
for(i=0; i < end; i++) {
mzd_make_table( B, i*kk, 0, k, T1, L1);
mzd_make_table( B, i*kk+k, 0, k, T2, L2);
mzd_make_table( B, i*kk+k+k, 0, k, T3, L3);
mzd_make_table( B, i*kk+k+k+k, 0, k, T4, L4);
#ifdef M4RM_GRAY8
mzd_make_table( B, i*kk+k+k+k+k, 0, k, T5, L5);
mzd_make_table( B, i*kk+k+k+k+k+k, 0, k, T6, L6);
mzd_make_table( B, i*kk+k+k+k+k+k+k, 0, k, T7, L7);
mzd_make_table( B, i*kk+k+k+k+k+k+k+k, 0, k, T8, L8);
#endif
for(babystep = 0; babystep < a_nr - giantstep; babystep++) {
j = giantstep + babystep;
x1 = L1[ (int)mzd_read_bits(A, j, i*kk, k) ];
x2 = L2[ (int)mzd_read_bits(A, j, i*kk+k, k) ];
x3 = L3[ (int)mzd_read_bits(A, j, i*kk+k+k, k) ];
x4 = L4[ (int)mzd_read_bits(A, j, i*kk+k+k+k, k) ];
#ifdef M4RM_GRAY8
x5 = L5[ (int)mzd_read_bits(A, j, i*kk+k+k+k+k, k) ];
x6 = L6[ (int)mzd_read_bits(A, j, i*kk+k+k+k+k+k, k) ];
x7 = L7[ (int)mzd_read_bits(A, j, i*kk+k+k+k+k+k+k, k) ];
x8 = L8[ (int)mzd_read_bits(A, j, i*kk+k+k+k+k+k+k+k, k) ];
#endif
c = C->rows[j];
t1 = T1->rows[x1];
t2 = T2->rows[x2];
t3 = T3->rows[x3];
t4 = T4->rows[x4];
#ifdef M4RM_GRAY8
t5 = T5->rows[x5];
t6 = T6->rows[x6];
t7 = T7->rows[x7];
t8 = T8->rows[x8];
#endif
_MZD_COMBINE;
}
}
/* handle stuff that doesn't fit into multiple of kk */
if (a_nc%kk) {
for (i=end*kk/k; i < (a_nc)/k; i++) {
mzd_make_table( B, i*k, 0, k, T1, L1);
for(j = 0; j<a_nr; j++) {
x1 = L1[ (int)mzd_read_bits(A, j, i*k, k) ];
c = C->rows[j];
t1 = T1->rows[x1];
for(ii=0; ii<wide; ii++) {
c[ii] ^= t1[ii];
}
}
}
/* handle stuff that doesn't fit into multiple of k */
if (a_nc%k) {
mzd_make_table( B, a_nc/k * k , 0, a_nc%k, T1, L1);
for(j = 0; j<a_nr; j++) {
x1 = L1[ (int)mzd_read_bits(A, j, i*k, a_nc%k) ];
c = C->rows[j];
t1 = T1->rows[x1];
for(ii=0; ii<wide; ii++) {
c[ii] ^= t1[ii];
}
}
}
}
mzd_free(T1);
mzd_free(T2);
mzd_free(T3);
mzd_free(T4);
#ifdef M4RM_GRAY8
mzd_free(T5);
mzd_free(T6);
mzd_free(T7);
mzd_free(T8);
#endif
m4ri_mm_free(buffer);
return C;
}
|
yp/Heu-MCHC
|
src/conversion-2bob.c
|
<filename>src/conversion-2bob.c<gh_stars>1-10
/**
*
*
* Heu-MCHC
*
* A fast and accurate heuristic algorithm for the haplotype inference
* problem on pedigree data with recombinations and mutations
*
* Copyright (C) 2009,2010,2011 <NAME>
*
* Distributed under the terms of the GNU General Public License (GPL)
*
*
* This file is part of Heu-MCHC.
*
* Heu-MCHC is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Heu-MCHC is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Heu-MCHC. If not, see <http://www.gnu.org/licenses/>.
*
**/
/*
** conversion-2bob.c
**
** Made by (Yuri)
** Login <<EMAIL>>
**
** Started on Mon Jul 27 16:01:38 2009 Yuri
** Last update Sun May 12 01:17:25 2002 Speed Blue
*/
#include "gen-ped-IO.h"
#include "util.h"
#include "log-build-info.h"
int main() {
PRINT_SYSTEM_INFORMATIONS;
pgenped pg= gp_read_from_file(stdin);
int* gender= NPALLOC(int, pg->n_indiv);
for (size_t i= 0; i<pg->n_indiv; ++i) {
gender[i]= 1;
}
for (size_t i= 0; i<pg->n_indiv; ++i) {
if (pg->individuals[i]->fi>=0) {
gender[pg->individuals[i]->fi]= 1;
}
if (pg->individuals[i]->mi>=0) {
gender[pg->individuals[i]->mi]= 2;
}
}
FILE* fgen= fopen("genotypes.txt", "w");
if (fgen == NULL) {
FATAL("Impossible to open file genotypes.txt for writing!");
fail();
}
FILE* fped= fopen("pedigree.txt", "w");
if (fped == NULL) {
FATAL("Impossible to open file pedigree.txt for writing!");
fail();
}
fprintf(fped, "%d\n", pg->n_indiv);
fprintf(fgen, "%d %d\n", pg->n_indiv, pg->n_loci);
for (size_t i= 0; i<pg->n_indiv; ++i) {
DEBUG("Saving individual %d", i+1);
pindiv in= pg->individuals[i];
fprintf(fped, "%d\t%c",
in->id+1, (gender[i]==1)?'M':'F');
if (in->fi >= 0) {
fprintf(fped, "\t%d\t%d\n",
in->fi+1, in->mi+1);
} else {
fprintf(fped, "\tN\tN\n");
}
for (size_t j= 0; j<pg->n_loci-1; ++j) {
fprintf(fgen, "%d ", in->g[j]);
}
fprintf(fgen, "%d\n", in->g[pg->n_loci-1]);
}
fclose(fgen);
fclose(fped);
}
|
yp/Heu-MCHC
|
src/my_time.c
|
/**
*
*
* Heu-MCHC
*
* A fast and accurate heuristic algorithm for the haplotype inference
* problem on pedigree data with recombinations and mutations
*
* Copyright (C) 2009,2010,2011 <NAME>
*
* Distributed under the terms of the GNU General Public License (GPL)
*
*
* This file is part of Heu-MCHC.
*
* Heu-MCHC is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Heu-MCHC is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Heu-MCHC. If not, see <http://www.gnu.org/licenses/>.
*
**/
#include "my_time.h"
#include "util.h"
#include <stdio.h>
#define DTYPE unsigned long
static const char* default_timer_name= "generic timer";
struct _mytime {
const char* timer_name;
DTYPE interval;
struct timeval start;
struct timeval stop;
bool active;
};
static DTYPE
diff_usec(struct timeval start, struct timeval stop) {
DTYPE start_usec= ((DTYPE)start.tv_sec*(DTYPE)1000000)+(DTYPE)start.tv_usec;
DTYPE stop_usec= ((DTYPE)stop.tv_sec*(DTYPE)1000000)+(DTYPE)stop.tv_usec;
return stop_usec-start_usec;
}
static void
compute_difference(pmytime pt) {
pt->interval+= diff_usec(pt->start, pt->stop);
}
void
MYTIME_print_interval(FILE* file, pmytime pt) {
my_assert(pt!=NULL);
my_assert(file!=NULL);
DTYPE diff= pt->interval;
if (diff>=(DTYPE)1000) {
// in secs
fprintf(file, "@Timer %s. Time elapsed: ", pt->timer_name);
DTYPE min= diff/60000000;
diff= diff%60000000;
if (min>0)
fprintf(file, "%lum ", min);
fprintf(file, "%.3fs\n", ((double)diff/1000000.0));
} else {
fprintf(file, "@Timer %s. Time elapsed: %lumicrosec", pt->timer_name, diff);
}
}
void
MYTIME_print_current(FILE* file, pmytime pt) {
MYTIME_stop(pt);
MYTIME_print_interval(file, pt);
MYTIME_start(pt);
}
pmytime
MYTIME_create(void) {
return MYTIME_create_with_name(default_timer_name);
}
pmytime
MYTIME_create_with_name(const char* timer_name) {
my_assert(timer_name!=NULL);
pmytime pt= PALLOC(struct _mytime);
pt->active= false;
pt->interval= 0;
pt->timer_name= timer_name;
return pt;
}
void
MYTIME_destroy(pmytime pt)
{
my_assert(pt!=NULL);
pfree(pt);
}
void
MYTIME_start(pmytime pt) {
my_assert(pt!=NULL);
pt->active= true;
gettimeofday(&pt->start, NULL);
}
void
MYTIME_reset(pmytime pt)
{
my_assert(pt!=NULL);
pt->active= false;
pt->interval= 0;
}
void
MYTIME_stop(pmytime pt)
{
my_assert(pt!=NULL);
gettimeofday(&(pt->stop), NULL);
pt->active= false;
compute_difference(pt);
}
const char*
MYTIME_getname(pmytime pt)
{
my_assert(pt!=NULL);
return pt->timer_name;
}
DTYPE
MYTIME_getinterval(pmytime pt)
{
my_assert(pt!=NULL);
return pt->interval;
}
#undef TOUT
#undef DTYPE
|
yp/Heu-MCHC
|
pers-lib/m4ri/testsuite/bench_elimination.c
|
<reponame>yp/Heu-MCHC
#include <stdlib.h>
#include "m4ri/m4ri.h"
#include "cpucycles.h"
#include "walltime.h"
int main(int argc, char **argv) {
int halfrank = 0;
size_t m, n, r;
const char *algorithm;
unsigned long long t;
double wt;
double clockZero = 0.0;
if (argc < 3) {
m4ri_die("Parameters m,n expected.\n");
}
if (argc == 4)
algorithm = argv[3];
else
algorithm = "m4ri";
m = atoi(argv[1]);
n = atoi(argv[2]);
mzd_t *A = mzd_init(m, n);
if (!halfrank) {
mzd_randomize(A);
} else {
mzd_t *L, *U;
L = mzd_init(m, m);
U = mzd_init(m, n);
mzd_randomize(U);
mzd_randomize(L);
size_t i,j;
for (i=0; i<m; ++i){
mzd_write_bit(U,i,i, 1);
for (j=0; j<i;++j)
mzd_write_bit(U,i,j, 0);
if (i%2)
for (j=i; j<n;++j)
mzd_write_bit(U,i,j, 0);
for (j=i+1; j<m;++j)
mzd_write_bit(L,i,j, 0);
mzd_write_bit(L,i,i, 1);
}
mzd_mul(A,L,U,0);
mzd_free(L);
mzd_free(U);
}
wt = walltime(&clockZero);
t = cpucycles();
if(strcmp(algorithm,"m4ri")==0)
r = mzd_echelonize_m4ri(A, 1, 0);
else if(strcmp(algorithm,"pluq")==0)
r = mzd_echelonize_pluq(A, 1);
else if(strcmp(algorithm,"naive")==0)
r = mzd_echelonize_naive(A, 1);
printf("m: %5d, n: %5d, r: %5d, cpu cycles: %llu wall time: %lf\n",m, n, r, cpucycles() - t, walltime(&wt));
mzd_free(A);
}
|
yp/Heu-MCHC
|
pers-lib/m4ri/testsuite/bench_multiplication.c
|
<filename>pers-lib/m4ri/testsuite/bench_multiplication.c<gh_stars>1-10
#include <stdlib.h>
#include "cpucycles.h"
#include "walltime.h"
#include "m4ri/m4ri.h"
int main(int argc, char **argv) {
int n, cutoff;
unsigned long long t;
double wt;
double clockZero = 0.0;
if (argc != 3) {
m4ri_die("Parameters n and cutoff expected.\n");
}
n = atoi(argv[1]);
cutoff = atoi(argv[2]);
if (n<=0) {
m4ri_die("Parameter n must be > 0\n");
}
if (cutoff<=0) {
m4ri_die("Parameter cutoff must be > 0\n");
}
mzd_t *A = mzd_init(n, n);
mzd_t *B = mzd_init(n, n);
mzd_randomize(A);
mzd_randomize(B);
wt = walltime(&clockZero);
t = cpucycles();
mzd_t *C = mzd_mul(NULL, A, B, cutoff);
printf("n: %5d, cutoff: %5d, cpu cycles: %llu wall time: %lf\n",n, cutoff, cpucycles() - t, walltime(&wt));
mzd_free(A);
mzd_free(B);
mzd_free(C);
}
|
yp/Heu-MCHC
|
include/bp_double.h
|
/**
*
*
* Heu-MCHC
*
* A fast and accurate heuristic algorithm for the haplotype inference
* problem on pedigree data with recombinations and mutations
*
* Copyright (C) 2009,2010,2011 <NAME>
*
* Distributed under the terms of the GNU General Public License (GPL)
*
*
* This file is part of Heu-MCHC.
*
* Heu-MCHC is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Heu-MCHC is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Heu-MCHC. If not, see <http://www.gnu.org/licenses/>.
*
**/
#ifndef _BP_DOUBLE_H_
#define _BP_DOUBLE_H_
/**
* Header defining the type of the values of the
* Belief Propagation Algorithm using the basic
* type double (or float)
**/
#include <cmath>
#ifdef BP_T
#error "Only a single definition for BP_T is admitted in the same program."
#endif
#define BP_T double
// Transform an element into a double
#define BP2D( v ) (v)
// Get the absolute value of an expression
#define BPABS( v ) (fabs(v))
// Condition to establish if a value is not a propability
#define BPINVALID( v ) (((v)>1.0) || ((v)<0.0) || isnan(v))
// Zero, One and Minimum constants
#define BP0 0.0
#define BP1 1.0
#define BP2 2.0
#define BP0_5 0.5
#define BP_MIN 1e-60
#define BP1THRESHOLD (BP1-BP_MIN)
#endif // _BP_DOUBLE_H_
|
yp/Heu-MCHC
|
pers-lib/m4ri/testsuite/bench_lqup.c
|
<gh_stars>1-10
#include <stdlib.h>
#include "m4ri/m4ri.h"
#include "cpucycles.h"
#include "walltime.h"
int main(int argc, char **argv) {
int halfrank = 1;
int n,m;
unsigned long long t;
double wt;
double clockZero = 0.0;
if (argc != 3) {
m4ri_die("Parameters m, n expected.\n");
}
m = atoi(argv[1]);
n = atoi(argv[2]);
mzd_t *L, *U;
mzd_t *A = mzd_init(m, n);
if(halfrank) {
L = mzd_init(m, m);
U = mzd_init(m, n);
mzd_randomize(U);
mzd_randomize(L);
/* size_t i,j; */
/* for (i=0; i<m; ++i){ */
/* for (j=i+1; j<m;++j) */
/* mzd_write_bit(L,i,j, 0); */
/* mzd_write_bit(L,i,i, 1); */
/* } */
/* for(i=0; i<MIN(m,n); ++i) { */
/* for (j=0; j<i;++j) */
/* mzd_write_bit(U,i,j, 0); */
/* mzd_write_bit(U,i,i, 1); */
/* } */
size_t i,j;
for (i=0; i<m; ++i){
mzd_write_bit(U,i,i, 1);
for (j=0; j<i;++j)
mzd_write_bit(U,i,j, 0);
if (i%2)
for (j=i; j<n;++j)
mzd_write_bit(U,i,j, 0);
for (j=i+1; j<m;++j)
mzd_write_bit(L,i,j, 0);
mzd_write_bit(L,i,i, 1);
}
mzd_mul(A,L,U,0);
} else {
mzd_randomize(A);
}
mzp_t* P = mzp_init(m);
mzp_t* Q = mzp_init(n);
wt = walltime(&clockZero);
t = cpucycles();
size_t r = mzd_pluq(A, P, Q, 0);
printf("m: %5d, n: %5d, r: %5d, cpu cycles: %12llu, wall time: %6.3lf\n", m, n, r, cpucycles() - t, walltime(&wt));
mzd_free(A);
mzp_free(P);
mzp_free(Q);
if(halfrank) {
mzd_free(U);
mzd_free(L);
}
}
|
yp/Heu-MCHC
|
pers-lib/m4ri/src/strassen.c
|
<reponame>yp/Heu-MCHC
/*******************************************************************
*
* M4RI: Linear Algebra over GF(2)
*
* Copyright (C) 2008 <NAME> <<EMAIL>>
* Copyright (C) 2008 <NAME> <<EMAIL>>
* Copyright (C) 2008 <NAME> <<EMAIL>>
*
* Distributed under the terms of the GNU General Public License (GPL)
* version 2 or higher.
*
* This code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* The full text of the GPL is available at:
*
* http://www.gnu.org/licenses/
*
********************************************************************/
#include "grayflex.h"
#include "strassen.h"
#include "misc.h"
#include "parity.h"
#define CLOSER(a,b,target) (abs((long)a-(long)target)<abs((long)b-(long)target))
#ifndef MIN
#define MIN(a,b) (((a)<(b))?(a):(b))
#endif
#ifdef HAVE_OPENMP
#include <omp.h>
#endif
/**
* Simple blockwise product
*/
mzd_t *_mzd_addmul_mp_even(mzd_t *C, mzd_t *A, mzd_t *B, int cutoff);
mzd_t *_mzd_mul_even_orig(mzd_t *C, mzd_t *A, mzd_t *B, int cutoff) {
size_t a,b,c;
size_t anr, anc, bnr, bnc;
a = A->nrows;
b = A->ncols;
c = B->ncols;
if(C->nrows == 0 || C->ncols == 0)
return C;
/* handle case first, where the input matrices are too small already */
if (CLOSER(A->nrows, A->nrows/2, cutoff) || CLOSER(A->ncols, A->ncols/2, cutoff) || CLOSER(B->ncols, B->ncols/2, cutoff)) {
/* we copy the matrix first since it is only constant memory
overhead and improves data locality, if you remove it make sure
there are no speed regressions */
/* C = _mzd_mul_m4rm(C, A, B, 0, TRUE); */
/* return C; */
mzd_t *Cbar = mzd_init(C->nrows, C->ncols);
Cbar = _mzd_mul_m4rm(Cbar, A, B, 0, FALSE);
mzd_copy(C, Cbar);
mzd_free(Cbar);
return C;
}
/* adjust cutting numbers to work on words */
unsigned long mult = 1;
long width = MIN(MIN(a,b),c);
while (width > 2*cutoff) {
width/=2;
mult*=2;
}
a -= a%(RADIX*mult);
b -= b%(RADIX*mult);
c -= c%(RADIX*mult);
anr = ((a/RADIX) >> 1) * RADIX;
anc = ((b/RADIX) >> 1) * RADIX;
bnr = anc;
bnc = ((c/RADIX) >> 1) * RADIX;
mzd_t *A00 = mzd_init_window(A, 0, 0, anr, anc);
mzd_t *A01 = mzd_init_window(A, 0, anc, anr, 2*anc);
mzd_t *A10 = mzd_init_window(A, anr, 0, 2*anr, anc);
mzd_t *A11 = mzd_init_window(A, anr, anc, 2*anr, 2*anc);
mzd_t *B00 = mzd_init_window(B, 0, 0, bnr, bnc);
mzd_t *B01 = mzd_init_window(B, 0, bnc, bnr, 2*bnc);
mzd_t *B10 = mzd_init_window(B, bnr, 0, 2*bnr, bnc);
mzd_t *B11 = mzd_init_window(B, bnr, bnc, 2*bnr, 2*bnc);
mzd_t *C00 = mzd_init_window(C, 0, 0, anr, bnc);
mzd_t *C01 = mzd_init_window(C, 0, bnc, anr, 2*bnc);
mzd_t *C10 = mzd_init_window(C, anr, 0, 2*anr, bnc);
mzd_t *C11 = mzd_init_window(C, anr, bnc, 2*anr, 2*bnc);
/**
* \note See <NAME>, <NAME>, <NAME>; "Memory
* efficient scheduling of Strassen-Winograd's matrix multiplication
* algorithm"; http://arxiv.org/pdf/0707.2347v3 for reference on the
* used operation scheduling.
*/
/* change this to mzd_init(anr, MAX(bnc,anc)) to fix the todo below */
mzd_t *X0 = mzd_init(anr, anc);
mzd_t *X1 = mzd_init(bnr, bnc);
_mzd_add(X0, A00, A10); /*1 X0 = A00 + A10 */
_mzd_add(X1, B11, B01); /*2 X1 = B11 + B01 */
_mzd_mul_even_orig(C10, X0, X1, cutoff); /*3 C10 = X0*X1 */
_mzd_add(X0, A10, A11); /*4 X0 = A10 + A11 */
_mzd_add(X1, B01, B00); /*5 X1 = B01 + B00*/
_mzd_mul_even_orig(C11, X0, X1, cutoff); /*6 C11 = X0*X1 */
_mzd_add(X0, X0, A00); /*7 X0 = X0 + A00 */
_mzd_add(X1, X1, B11); /*8 X1 = B11 + X1 */
_mzd_mul_even_orig(C01, X0, X1, cutoff); /*9 C01 = X0*X1 */
_mzd_add(X0, X0, A01); /*10 X0 = A01 + X0 */
_mzd_mul_even_orig(C00, X0, B11, cutoff); /*11 C00 = X0*B11 */
/**
* \todo ideally we would use the same X0 throughout the function
* but some called function doesn't like that and we end up with a
* wrong result if we use virtual X0 matrices. Ideally, this should
* be fixed not worked around. The check whether the bug has been
* fixed, use only one X0 and check if mzd_mul(4096, 3528, 4096,
* 1024) still returns the correct answer.
*/
mzd_free(X0);
X0 = mzd_mul(NULL, A00, B00, cutoff);/*12 X0 = A00*B00*/
_mzd_add(C01, X0, C01); /*13 C01 = X0 + C01 */
_mzd_add(C10, C01, C10); /*14 C10 = C01 + C10 */
_mzd_add(C01, C01, C11); /*15 C01 = C01 + C11 */
_mzd_add(C11, C10, C11); /*16 C11 = C10 + C11 */
_mzd_add(C01, C01, C00); /*17 C01 = C01 + C00 */
_mzd_add(X1, X1, B10); /*18 X1 = X1 + B10 */
_mzd_mul_even_orig(C00, A11, X1, cutoff); /*19 C00 = A11*X1 */
_mzd_add(C10, C10, C00); /*20 C10 = C10 + C00 */
_mzd_mul_even_orig(C00, A01, B10, cutoff);/*21 C00 = A01*B10 */
_mzd_add(C00, C00, X0); /*22 C00 = X0 + C00 */
/* deal with rest */
if (B->ncols > (int)(2*bnc)) {
mzd_t *B_last_col = mzd_init_window(B, 0, 2*bnc, A->ncols, B->ncols);
mzd_t *C_last_col = mzd_init_window(C, 0, 2*bnc, A->nrows, C->ncols);
_mzd_mul_m4rm(C_last_col, A, B_last_col, 0, TRUE);
mzd_free_window(B_last_col);
mzd_free_window(C_last_col);
}
if (A->nrows > (int)(2*anr)) {
mzd_t *A_last_row = mzd_init_window(A, 2*anr, 0, A->nrows, A->ncols);
mzd_t *C_last_row = mzd_init_window(C, 2*anr, 0, C->nrows, C->ncols);
_mzd_mul_m4rm(C_last_row, A_last_row, B, 0, TRUE);
mzd_free_window(A_last_row);
mzd_free_window(C_last_row);
}
if (A->ncols > (int)(2*anc)) {
mzd_t *A_last_col = mzd_init_window(A, 0, 2*anc, 2*anr, A->ncols);
mzd_t *B_last_row = mzd_init_window(B, 2*bnr, 0, B->nrows, 2*bnc);
mzd_t *C_bulk = mzd_init_window(C, 0, 0, 2*anr, bnc*2);
mzd_addmul_m4rm(C_bulk, A_last_col, B_last_row, 0);
mzd_free_window(A_last_col);
mzd_free_window(B_last_row);
mzd_free_window(C_bulk);
}
/* clean up */
mzd_free_window(A00); mzd_free_window(A01);
mzd_free_window(A10); mzd_free_window(A11);
mzd_free_window(B00); mzd_free_window(B01);
mzd_free_window(B10); mzd_free_window(B11);
mzd_free_window(C00); mzd_free_window(C01);
mzd_free_window(C10); mzd_free_window(C11);
mzd_free(X0);
mzd_free(X1);
return C;
}
mzd_t *_mzd_mul_even(mzd_t *C, mzd_t *A, mzd_t *B, int cutoff) {
size_t m,k,n;
size_t mmm, kkk, nnn;
if(C->nrows == 0 || C->ncols == 0)
return C;
m = A->nrows;
k = A->ncols;
n = B->ncols;
/* handle case first, where the input matrices are too small already */
if (CLOSER(m, m/2, cutoff) || CLOSER(k, k/2, cutoff) || CLOSER(n, n/2, cutoff)) {
/* we copy the matrix first since it is only constant memory
overhead and improves data locality, if you remove it make sure
there are no speed regressions */
/* C = _mzd_mul_m4rm(C, A, B, 0, TRUE); */
mzd_t *Cbar = mzd_init(m, n);
_mzd_mul_m4rm(Cbar, A, B, 0, FALSE);
mzd_copy(C, Cbar);
mzd_free(Cbar);
return C;
}
#ifdef HAVE_OPENMP
if (omp_get_num_threads() < omp_get_max_threads()) {
mzd_set_ui(C, 0);
return _mzd_addmul_mp_even(C, A, B, cutoff);
}
#endif
/* adjust cutting numbers to work on words */
{
unsigned long mult = RADIX;
unsigned long width = MIN(MIN(m,n),k)/2;
while (width > (unsigned long)cutoff) {
width>>=1;
mult<<=1;
}
mmm = (((m - m%mult)/RADIX) >> 1) * RADIX;
kkk = (((k - k%mult)/RADIX) >> 1) * RADIX;
nnn = (((n - n%mult)/RADIX) >> 1) * RADIX;
}
/* |A | |B | |C |
* Compute | | x | | = | | */
{
mzd_t *A11 = mzd_init_window(A, 0, 0, mmm, kkk);
mzd_t *A12 = mzd_init_window(A, 0, kkk, mmm, 2*kkk);
mzd_t *A21 = mzd_init_window(A, mmm, 0, 2*mmm, kkk);
mzd_t *A22 = mzd_init_window(A, mmm, kkk, 2*mmm, 2*kkk);
mzd_t *B11 = mzd_init_window(B, 0, 0, kkk, nnn);
mzd_t *B12 = mzd_init_window(B, 0, nnn, kkk, 2*nnn);
mzd_t *B21 = mzd_init_window(B, kkk, 0, 2*kkk, nnn);
mzd_t *B22 = mzd_init_window(B, kkk, nnn, 2*kkk, 2*nnn);
mzd_t *C11 = mzd_init_window(C, 0, 0, mmm, nnn);
mzd_t *C12 = mzd_init_window(C, 0, nnn, mmm, 2*nnn);
mzd_t *C21 = mzd_init_window(C, mmm, 0, 2*mmm, nnn);
mzd_t *C22 = mzd_init_window(C, mmm, nnn, 2*mmm, 2*nnn);
/**
* \note See <NAME>; "A Strassen-like Matrix Multiplication
* Suited for Squaring and Highest Power Computation";
* http://bodrato.it/papres/#CIVV2008 for reference on the used
* sequence of operations.
*/
/* change this to mzd_init(mmm, MAX(nnn,kkk)) to fix the todo below */
mzd_t *Wmk = mzd_init(mmm, kkk);
mzd_t *Wkn = mzd_init(kkk, nnn);
_mzd_add(Wkn, B22, B12); /* Wkn = B22 + B12 */
_mzd_add(Wmk, A22, A12); /* Wmk = A22 + A12 */
_mzd_mul_even(C21, Wmk, Wkn, cutoff);/* C21 = Wmk * Wkn */
_mzd_add(Wmk, A22, A21); /* Wmk = A22 - A21 */
_mzd_add(Wkn, B22, B21); /* Wkn = B22 - B21 */
_mzd_mul_even(C22, Wmk, Wkn, cutoff);/* C22 = Wmk * Wkn */
_mzd_add(Wkn, Wkn, B12); /* Wkn = Wkn + B12 */
_mzd_add(Wmk, Wmk, A12); /* Wmk = Wmk + A12 */
_mzd_mul_even(C11, Wmk, Wkn, cutoff);/* C11 = Wmk * Wkn */
_mzd_add(Wmk, Wmk, A11); /* Wmk = Wmk - A11 */
_mzd_mul_even(C12, Wmk, B12, cutoff);/* C12 = Wmk * B12 */
_mzd_add(C12, C12, C22); /* C12 = C12 + C22 */
/**
* \todo ideally we would use the same Wmk throughout the function
* but some called function doesn't like that and we end up with a
* wrong result if we use virtual Wmk matrices. Ideally, this should
* be fixed not worked around. The check whether the bug has been
* fixed, use only one Wmk and check if mzd_mul(4096, 3528,
* 4096, 2124) still returns the correct answer.
*/
mzd_free(Wmk);
Wmk = mzd_mul(NULL, A12, B21, cutoff);/*Wmk = A12 * B21 */
_mzd_add(C11, C11, Wmk); /* C11 = C11 + Wmk */
_mzd_add(C12, C11, C12); /* C12 = C11 - C12 */
_mzd_add(C11, C21, C11); /* C11 = C21 - C11 */
_mzd_add(Wkn, Wkn, B11); /* Wkn = Wkn - B11 */
_mzd_mul_even(C21, A21, Wkn, cutoff);/* C21 = A21 * Wkn */
mzd_free(Wkn);
_mzd_add(C21, C11, C21); /* C21 = C11 - C21 */
_mzd_add(C22, C22, C11); /* C22 = C22 + C11 */
_mzd_mul_even(C11, A11, B11, cutoff);/* C11 = A11 * B11 */
_mzd_add(C11, C11, Wmk); /* C11 = C11 + Wmk */
/* clean up */
mzd_free_window(A11); mzd_free_window(A12);
mzd_free_window(A21); mzd_free_window(A22);
mzd_free_window(B11); mzd_free_window(B12);
mzd_free_window(B21); mzd_free_window(B22);
mzd_free_window(C11); mzd_free_window(C12);
mzd_free_window(C21); mzd_free_window(C22);
mzd_free(Wmk);
}
/* deal with rest */
nnn*=2;
if (n > nnn) {
/* |AA| | B| | C|
* Compute |AA| x | B| = | C| */
mzd_t *B_last_col = mzd_init_window(B, 0, nnn, k, n);
mzd_t *C_last_col = mzd_init_window(C, 0, nnn, m, n);
_mzd_mul_m4rm(C_last_col, A, B_last_col, 0, TRUE);
mzd_free_window(B_last_col);
mzd_free_window(C_last_col);
}
mmm*=2;
if (m > mmm) {
/* | | |B | | |
* Compute |AA| x |B | = |C | */
mzd_t *A_last_row = mzd_init_window(A, mmm, 0, m, k);
mzd_t *B_first_col= mzd_init_window(B, 0, 0, k, nnn);
mzd_t *C_last_row = mzd_init_window(C, mmm, 0, m, nnn);
_mzd_mul_m4rm(C_last_row, A_last_row, B_first_col, 0, TRUE);
mzd_free_window(A_last_row);
mzd_free_window(B_first_col);
mzd_free_window(C_last_row);
}
kkk*=2;
if (k > kkk) {
/* Add to | | | B| |C |
* result |A | x | | = | | */
mzd_t *A_last_col = mzd_init_window(A, 0, kkk, mmm, k);
mzd_t *B_last_row = mzd_init_window(B, kkk, 0, k, nnn);
mzd_t *C_bulk = mzd_init_window(C, 0, 0, mmm, nnn);
mzd_addmul_m4rm(C_bulk, A_last_col, B_last_row, 0);
mzd_free_window(A_last_col);
mzd_free_window(B_last_row);
mzd_free_window(C_bulk);
}
return C;
}
mzd_t *_mzd_sqr_even(mzd_t *C, mzd_t *A, int cutoff) {
size_t m;
size_t mmm;
m = A->nrows;
/* handle case first, where the input matrices are too small already */
if (CLOSER(m, m/2, cutoff)) {
/* we copy the matrix first since it is only constant memory
overhead and improves data locality, if you remove it make sure
there are no speed regressions */
/* C = _mzd_mul_m4rm(C, A, B, 0, TRUE); */
mzd_t *Cbar = mzd_init(m, m);
_mzd_mul_m4rm(Cbar, A, A, 0, FALSE);
mzd_copy(C, Cbar);
mzd_free(Cbar);
return C;
}
/* adjust cutting numbers to work on words */
{
unsigned long mult = RADIX;
unsigned long width = m>>1;
while (width > (unsigned long)cutoff) {
width>>=1;
mult<<=1;
}
mmm = (((m - m%mult)/RADIX) >> 1) * RADIX;
}
/* |A | |A | |C |
* Compute | | x | | = | | */
{
mzd_t *A11 = mzd_init_window(A, 0, 0, mmm, mmm);
mzd_t *A12 = mzd_init_window(A, 0, mmm, mmm, 2*mmm);
mzd_t *A21 = mzd_init_window(A, mmm, 0, 2*mmm, mmm);
mzd_t *A22 = mzd_init_window(A, mmm, mmm, 2*mmm, 2*mmm);
mzd_t *C11 = mzd_init_window(C, 0, 0, mmm, mmm);
mzd_t *C12 = mzd_init_window(C, 0, mmm, mmm, 2*mmm);
mzd_t *C21 = mzd_init_window(C, mmm, 0, 2*mmm, mmm);
mzd_t *C22 = mzd_init_window(C, mmm, mmm, 2*mmm, 2*mmm);
/**
* \note See <NAME>; "A Strassen-like Matrix Multiplication
* Suited for Squaring and Highest Power Computation";
* http://bodrato.it/papres/#CIVV2008 for reference on the used
* sequence of operations.
*/
mzd_t *Wmk;
mzd_t *Wkn = mzd_init(mmm, mmm);
_mzd_add(Wkn, A22, A12); /* Wkn = A22 + A12 */
_mzd_sqr_even(C21, Wkn, cutoff); /* C21 = Wkn^2 */
_mzd_add(Wkn, A22, A21); /* Wkn = A22 - A21 */
_mzd_sqr_even(C22, Wkn, cutoff); /* C22 = Wkn^2 */
_mzd_add(Wkn, Wkn, A12); /* Wkn = Wkn + A12 */
_mzd_sqr_even(C11, Wkn, cutoff); /* C11 = Wkn^2 */
_mzd_add(Wkn, Wkn, A11); /* Wkn = Wkn - A11 */
_mzd_mul_even(C12, Wkn, A12, cutoff);/* C12 = Wkn * A12 */
_mzd_add(C12, C12, C22); /* C12 = C12 + C22 */
Wmk = mzd_mul(NULL, A12, A21, cutoff);/*Wmk = A12 * A21 */
_mzd_add(C11, C11, Wmk); /* C11 = C11 + Wmk */
_mzd_add(C12, C11, C12); /* C12 = C11 - C12 */
_mzd_add(C11, C21, C11); /* C11 = C21 - C11 */
_mzd_mul_even(C21, A21, Wkn, cutoff);/* C21 = A21 * Wkn */
mzd_free(Wkn);
_mzd_add(C21, C11, C21); /* C21 = C11 - C21 */
_mzd_add(C22, C22, C11); /* C22 = C22 + C11 */
_mzd_sqr_even(C11, A11, cutoff); /* C11 = A11^2 */
_mzd_add(C11, C11, Wmk); /* C11 = C11 + Wmk */
/* clean up */
mzd_free_window(A11); mzd_free_window(A12);
mzd_free_window(A21); mzd_free_window(A22);
mzd_free_window(C11); mzd_free_window(C12);
mzd_free_window(C21); mzd_free_window(C22);
mzd_free(Wmk);
}
/* deal with rest */
mmm*=2;
if (m > mmm) {
/* |AA| | A| | C|
* Compute |AA| x | A| = | C| */
{
mzd_t *A_last_col = mzd_init_window(A, 0, mmm, m, m);
mzd_t *C_last_col = mzd_init_window(C, 0, mmm, m, m);
_mzd_mul_m4rm(C_last_col, A, A_last_col, 0, TRUE);
mzd_free_window(A_last_col);
mzd_free_window(C_last_col);
}
/* | | |A | | |
* Compute |AA| x |A | = |C | */
{
mzd_t *A_last_row = mzd_init_window(A, mmm, 0, m, m);
mzd_t *A_first_col= mzd_init_window(A, 0, 0, m, mmm);
mzd_t *C_last_row = mzd_init_window(C, mmm, 0, m, mmm);
_mzd_mul_m4rm(C_last_row, A_last_row, A_first_col, 0, TRUE);
mzd_free_window(A_last_row);
mzd_free_window(A_first_col);
mzd_free_window(C_last_row);
}
/* Add to | | | A| |C |
* result |A | x | | = | | */
{
mzd_t *A_last_col = mzd_init_window(A, 0, mmm, mmm, m);
mzd_t *A_last_row = mzd_init_window(A, mmm, 0, m, mmm);
mzd_t *C_bulk = mzd_init_window(C, 0, 0, mmm, mmm);
mzd_addmul_m4rm(C_bulk, A_last_col, A_last_row, 0);
mzd_free_window(A_last_col);
mzd_free_window(A_last_row);
mzd_free_window(C_bulk);
}
}
return C;
}
#ifdef HAVE_OPENMP
mzd_t *_mzd_addmul_mp_even(mzd_t *C, mzd_t *A, mzd_t *B, int cutoff) {
/**
* \todo make sure not to overwrite crap after ncols and before width*RADIX
*/
size_t a,b,c;
size_t anr, anc, bnr, bnc;
a = A->nrows;
b = A->ncols;
c = B->ncols;
/* handle case first, where the input matrices are too small already */
if (CLOSER(A->nrows, A->nrows/2, cutoff) || CLOSER(A->ncols, A->ncols/2, cutoff) || CLOSER(B->ncols, B->ncols/2, cutoff)) {
/* we copy the matrix first since it is only constant memory
overhead and improves data locality, if you remove it make sure
there are no speed regressions */
/* C = _mzd_mul_m4rm(C, A, B, 0, TRUE); */
mzd_t *Cbar = mzd_init(C->nrows, C->ncols);
Cbar = _mzd_mul_m4rm(Cbar, A, B, 0, FALSE);
mzd_copy(C, Cbar);
mzd_free(Cbar);
return C;
}
/* adjust cutting numbers to work on words */
unsigned long mult = 2;
/* long width = a; */
/* while (width > 2*cutoff) { */
/* width/=2; */
/* mult*=2; */
/* } */
a -= a%(RADIX*mult);
b -= b%(RADIX*mult);
c -= c%(RADIX*mult);
anr = ((a/RADIX) >> 1) * RADIX;
anc = ((b/RADIX) >> 1) * RADIX;
bnr = anc;
bnc = ((c/RADIX) >> 1) * RADIX;
mzd_t *A00 = mzd_init_window(A, 0, 0, anr, anc);
mzd_t *A01 = mzd_init_window(A, 0, anc, anr, 2*anc);
mzd_t *A10 = mzd_init_window(A, anr, 0, 2*anr, anc);
mzd_t *A11 = mzd_init_window(A, anr, anc, 2*anr, 2*anc);
mzd_t *B00 = mzd_init_window(B, 0, 0, bnr, bnc);
mzd_t *B01 = mzd_init_window(B, 0, bnc, bnr, 2*bnc);
mzd_t *B10 = mzd_init_window(B, bnr, 0, 2*bnr, bnc);
mzd_t *B11 = mzd_init_window(B, bnr, bnc, 2*bnr, 2*bnc);
mzd_t *C00 = mzd_init_window(C, 0, 0, anr, bnc);
mzd_t *C01 = mzd_init_window(C, 0, bnc, anr, 2*bnc);
mzd_t *C10 = mzd_init_window(C, anr, 0, 2*anr, bnc);
mzd_t *C11 = mzd_init_window(C, anr, bnc, 2*anr, 2*bnc);
#pragma omp parallel sections num_threads(4)
{
#pragma omp section
{
_mzd_addmul_even(C00, A00, B00, cutoff);
_mzd_addmul_even(C00, A01, B10, cutoff);
}
#pragma omp section
{
_mzd_addmul_even(C01, A00, B01, cutoff);
_mzd_addmul_even(C01, A01, B11, cutoff);
}
#pragma omp section
{
_mzd_addmul_even(C10, A10, B00, cutoff);
_mzd_addmul_even(C10, A11, B10, cutoff);
}
#pragma omp section
{
_mzd_addmul_even(C11, A10, B01, cutoff);
_mzd_addmul_even(C11, A11, B11, cutoff);
}
}
/* deal with rest */
if (B->ncols > 2*bnc) {
mzd_t *B_last_col = mzd_init_window(B, 0, 2*bnc, A->ncols, B->ncols);
mzd_t *C_last_col = mzd_init_window(C, 0, 2*bnc, A->nrows, C->ncols);
mzd_addmul_m4rm(C_last_col, A, B_last_col, 0);
mzd_free_window(B_last_col);
mzd_free_window(C_last_col);
}
if (A->nrows > 2*anr) {
mzd_t *A_last_row = mzd_init_window(A, 2*anr, 0, A->nrows, A->ncols);
mzd_t *B_bulk = mzd_init_window(B, 0, 0, B->nrows, 2*bnc);
mzd_t *C_last_row = mzd_init_window(C, 2*anr, 0, C->nrows, 2*bnc);
mzd_addmul_m4rm(C_last_row, A_last_row, B_bulk, 0);
mzd_free_window(A_last_row);
mzd_free_window(B_bulk);
mzd_free_window(C_last_row);
}
if (A->ncols > 2*anc) {
mzd_t *A_last_col = mzd_init_window(A, 0, 2*anc, 2*anr, A->ncols);
mzd_t *B_last_row = mzd_init_window(B, 2*bnr, 0, B->nrows, 2*bnc);
mzd_t *C_bulk = mzd_init_window(C, 0, 0, 2*anr, bnc*2);
mzd_addmul_m4rm(C_bulk, A_last_col, B_last_row, 0);
mzd_free_window(A_last_col);
mzd_free_window(B_last_row);
mzd_free_window(C_bulk);
}
/* clean up */
mzd_free_window(A00); mzd_free_window(A01);
mzd_free_window(A10); mzd_free_window(A11);
mzd_free_window(B00); mzd_free_window(B01);
mzd_free_window(B10); mzd_free_window(B11);
mzd_free_window(C00); mzd_free_window(C01);
mzd_free_window(C10); mzd_free_window(C11);
return C;
}
#endif
mzd_t *mzd_mul(mzd_t *C, mzd_t *A, mzd_t *B, int cutoff) {
if(A->ncols != B->nrows)
m4ri_die("mzd_mul: A ncols (%d) need to match B nrows (%d).\n", A->ncols, B->nrows);
if (cutoff < 0)
m4ri_die("mzd_mul: cutoff must be >= 0.\n");
if(cutoff == 0) {
cutoff = STRASSEN_MUL_CUTOFF;
}
cutoff = cutoff/RADIX * RADIX;
if (cutoff < RADIX) {
cutoff = RADIX;
};
if (C == NULL) {
C = mzd_init(A->nrows, B->ncols);
} else if (C->nrows != A->nrows || C->ncols != B->ncols){
m4ri_die("mzd_mul: C (%d x %d) has wrong dimensions, expected (%d x %d)\n",
C->nrows, C->ncols, A->nrows, B->ncols);
}
if(A->offset || B->offset || C->offset) {
mzd_set_ui(C, 0);
mzd_addmul(C, A, B, cutoff);
return C;
}
C = (A==B)?_mzd_sqr_even(C, A, cutoff):_mzd_mul_even(C, A, B, cutoff);
return C;
}
mzd_t *_mzd_addmul_even_orig(mzd_t *C, mzd_t *A, mzd_t *B, int cutoff) {
/**
* \todo make sure not to overwrite crap after ncols and before width*RADIX
*/
size_t a,b,c;
size_t anr, anc, bnr, bnc;
if(C->nrows == 0 || C->ncols == 0)
return C;
a = A->nrows;
b = A->ncols;
c = B->ncols;
/* handle case first, where the input matrices are too small already */
if (CLOSER(A->nrows, A->nrows/2, cutoff) || CLOSER(A->ncols, A->ncols/2, cutoff) || CLOSER(B->ncols, B->ncols/2, cutoff)) {
/* we copy the matrix first since it is only constant memory
overhead and improves data locality, if you remove it make sure
there are no speed regressions */
mzd_t *Cbar = mzd_copy(NULL, C);
mzd_addmul_m4rm(Cbar, A, B, 0);
mzd_copy(C, Cbar);
mzd_free(Cbar);
return C;
}
/* adjust cutting numbers to work on words */
unsigned long mult = 1;
long width = MIN(MIN(a,b),c);
while (width > 2*cutoff) {
width/=2;
mult*=2;
}
a -= a%(RADIX*mult);
b -= b%(RADIX*mult);
c -= c%(RADIX*mult);
anr = ((a/RADIX) >> 1) * RADIX;
anc = ((b/RADIX) >> 1) * RADIX;
bnr = anc;
bnc = ((c/RADIX) >> 1) * RADIX;
mzd_t *A00 = mzd_init_window(A, 0, 0, anr, anc);
mzd_t *A01 = mzd_init_window(A, 0, anc, anr, 2*anc);
mzd_t *A10 = mzd_init_window(A, anr, 0, 2*anr, anc);
mzd_t *A11 = mzd_init_window(A, anr, anc, 2*anr, 2*anc);
mzd_t *B00 = mzd_init_window(B, 0, 0, bnr, bnc);
mzd_t *B01 = mzd_init_window(B, 0, bnc, bnr, 2*bnc);
mzd_t *B10 = mzd_init_window(B, bnr, 0, 2*bnr, bnc);
mzd_t *B11 = mzd_init_window(B, bnr, bnc, 2*bnr, 2*bnc);
mzd_t *C00 = mzd_init_window(C, 0, 0, anr, bnc);
mzd_t *C01 = mzd_init_window(C, 0, bnc, anr, 2*bnc);
mzd_t *C10 = mzd_init_window(C, anr, 0, 2*anr, bnc);
mzd_t *C11 = mzd_init_window(C, anr, bnc, 2*anr, 2*bnc);
/**
* \note See <NAME>, <NAME>, <NAME>; "Memory
* efficient scheduling of Strassen-Winograd's matrix multiplication
* algorithm"; http://arxiv.org/pdf/0707.2347v3 for reference on the
* used operation scheduling.
*/
mzd_t *X0 = mzd_init(anr, anc);
mzd_t *X1 = mzd_init(bnr, bnc);
mzd_t *X2 = mzd_init(anr, bnc);
_mzd_add(X0, A10, A11); /* 1 S1 = A21 + A22 X1 */
_mzd_add(X1, B01, B00); /* 2 T1 = B12 - B11 X2 */
_mzd_mul_even_orig(X2, X0, X1, cutoff); /* 3 P5 = S1 T1 X3 */
_mzd_add(C11, X2, C11); /* 4 C22 = P5 + C22 C22 */
_mzd_add(C01, X2, C01); /* 5 C12 = P5 + C12 C12 */
_mzd_add(X0, X0, A00); /* 6 S2 = S1 - A11 X1 */
_mzd_add(X1, B11, X1); /* 7 T2 = B22 - T1 X2 */
_mzd_mul_even_orig(X2, A00, B00, cutoff); /* 8 P1 = A11 B11 X3 */
_mzd_add(C00, X2, C00); /* 9 C11 = P1 + C11 C11 */
_mzd_addmul_even_orig(X2, X0, X1, cutoff); /* 10 U2 = S2 T2 + P1 X3 */
_mzd_addmul_even_orig(C00, A01, B10, cutoff); /* 11 U1 = A12 B21 + C11 C11 */
_mzd_add(X0, A01, X0); /* 12 S4 = A12 - S2 X1 */
_mzd_add(X1, X1, B10); /* 13 T4 = T2 - B21 X2 */
_mzd_addmul_even_orig(C01, X0, B11, cutoff); /* 14 C12 = S4 B22 + C12 C12 */
_mzd_add(C01, X2, C01); /* 15 U5 = U2 + C12 C12 */
_mzd_addmul_even_orig(C10, A11, X1, cutoff); /* 16 P4 = A22 T4 - C21 C21 */
_mzd_add(X0, A00, A10); /* 17 S3 = A11 - A21 X1 */
_mzd_add(X1, B11, B01); /* 18 T3 = B22 - B12 X2 */
_mzd_addmul_even_orig(X2, X0, X1, cutoff); /* 19 U3 = S3 T3 + U2 X3 */
_mzd_add(C11, X2, C11); /* 20 U7 = U3 + C22 C22 */
_mzd_add(C10, X2, C10); /* 21 U6 = U3 - C21 C21 */
/* deal with rest */
if (B->ncols > 2*bnc) {
mzd_t *B_last_col = mzd_init_window(B, 0, 2*bnc, A->ncols, B->ncols);
mzd_t *C_last_col = mzd_init_window(C, 0, 2*bnc, A->nrows, C->ncols);
mzd_addmul_m4rm(C_last_col, A, B_last_col, 0);
mzd_free_window(B_last_col);
mzd_free_window(C_last_col);
}
if (A->nrows > 2*anr) {
mzd_t *A_last_row = mzd_init_window(A, 2*anr, 0, A->nrows, A->ncols);
mzd_t *B_bulk = mzd_init_window(B, 0, 0, B->nrows, 2*bnc);
mzd_t *C_last_row = mzd_init_window(C, 2*anr, 0, C->nrows, 2*bnc);
mzd_addmul_m4rm(C_last_row, A_last_row, B_bulk, 0);
mzd_free_window(A_last_row);
mzd_free_window(B_bulk);
mzd_free_window(C_last_row);
}
if (A->ncols > 2*anc) {
mzd_t *A_last_col = mzd_init_window(A, 0, 2*anc, 2*anr, A->ncols);
mzd_t *B_last_row = mzd_init_window(B, 2*bnr, 0, B->nrows, 2*bnc);
mzd_t *C_bulk = mzd_init_window(C, 0, 0, 2*anr, bnc*2);
mzd_addmul_m4rm(C_bulk, A_last_col, B_last_row, 0);
mzd_free_window(A_last_col);
mzd_free_window(B_last_row);
mzd_free_window(C_bulk);
}
/* clean up */
mzd_free_window(A00); mzd_free_window(A01);
mzd_free_window(A10); mzd_free_window(A11);
mzd_free_window(B00); mzd_free_window(B01);
mzd_free_window(B10); mzd_free_window(B11);
mzd_free_window(C00); mzd_free_window(C01);
mzd_free_window(C10); mzd_free_window(C11);
mzd_free(X0);
mzd_free(X1);
mzd_free(X2);
return C;
}
mzd_t *_mzd_addmul_even(mzd_t *C, mzd_t *A, mzd_t *B, int cutoff) {
/**
* \todo make sure not to overwrite crap after ncols and before width*RADIX
*/
size_t m,k,n;
size_t mmm, kkk, nnn;
if(C->nrows == 0 || C->ncols == 0)
return C;
m = A->nrows;
k = A->ncols;
n = B->ncols;
/* handle case first, where the input matrices are too small already */
if (CLOSER(m, m/2, cutoff) || CLOSER(k, k/2, cutoff) || CLOSER(n, n/2, cutoff)) {
/* we copy the matrix first since it is only constant memory
overhead and improves data locality, if you remove it make sure
there are no speed regressions */
mzd_t *Cbar = mzd_copy(NULL, C);
mzd_addmul_m4rm(Cbar, A, B, 0);
mzd_copy(C, Cbar);
mzd_free(Cbar);
return C;
}
#ifdef HAVE_OPENMP
if (omp_get_num_threads() < omp_get_max_threads()) {
return _mzd_addmul_mp_even(C, A, B, cutoff);
}
#endif
/* adjust cutting numbers to work on words */
{
unsigned long mult = RADIX;
unsigned long width = MIN(MIN(m,n),k)/2;
while (width > (unsigned long)cutoff) {
width>>=1;
mult<<=1;
}
mmm = (((m - m%mult)/RADIX) >> 1) * RADIX;
kkk = (((k - k%mult)/RADIX) >> 1) * RADIX;
nnn = (((n - n%mult)/RADIX) >> 1) * RADIX;
}
/* |C | |A | |B |
* Compute | | += | | x | | */
{
mzd_t *A11 = mzd_init_window(A, 0, 0, mmm, kkk);
mzd_t *A12 = mzd_init_window(A, 0, kkk, mmm, 2*kkk);
mzd_t *A21 = mzd_init_window(A, mmm, 0, 2*mmm, kkk);
mzd_t *A22 = mzd_init_window(A, mmm, kkk, 2*mmm, 2*kkk);
mzd_t *B11 = mzd_init_window(B, 0, 0, kkk, nnn);
mzd_t *B12 = mzd_init_window(B, 0, nnn, kkk, 2*nnn);
mzd_t *B21 = mzd_init_window(B, kkk, 0, 2*kkk, nnn);
mzd_t *B22 = mzd_init_window(B, kkk, nnn, 2*kkk, 2*nnn);
mzd_t *C11 = mzd_init_window(C, 0, 0, mmm, nnn);
mzd_t *C12 = mzd_init_window(C, 0, nnn, mmm, 2*nnn);
mzd_t *C21 = mzd_init_window(C, mmm, 0, 2*mmm, nnn);
mzd_t *C22 = mzd_init_window(C, mmm, nnn, 2*mmm, 2*nnn);
/**
* \note See <NAME>; "A Strassen-like Matrix Multiplication
* Suited for Squaring and Highest Power Computation";
* http://bodrato.it/papres/#CIVV2008 for reference on the used
* sequence of operations.
*/
mzd_t *S = mzd_init(mmm, kkk);
mzd_t *T = mzd_init(kkk, nnn);
mzd_t *U = mzd_init(mmm, nnn);
_mzd_add(S, A22, A21); /* 1 S = A22 - A21 */
_mzd_add(T, B22, B21); /* 2 T = B22 - B21 */
_mzd_mul_even(U, S, T, cutoff); /* 3 U = S*T */
_mzd_add(C22, U, C22); /* 4 C22 = U + C22 */
_mzd_add(C12, U, C12); /* 5 C12 = U + C12 */
_mzd_mul_even(U, A12, B21, cutoff); /* 8 U = A12*B21 */
_mzd_add(C11, U, C11); /* 9 C11 = U + C11 */
_mzd_addmul_even(C11, A11, B11, cutoff);/* 11 C11 = A11*B11 + C11 */
_mzd_add(S, S, A12); /* 6 S = S - A12 */
_mzd_add(T, T, B12); /* 7 T = T - B12 */
_mzd_addmul_even(U, S, T, cutoff); /* 10 U = S*T + U */
_mzd_add(C12, C12, U); /* 15 C12 = U + C12 */
_mzd_add(S, A11, S); /* 12 S = A11 - S */
_mzd_addmul_even(C12, S, B12, cutoff); /* 14 C12 = S*B12 + C12 */
_mzd_add(T, B11, T); /* 13 T = B11 - T */
_mzd_addmul_even(C21, A21, T, cutoff); /* 16 C21 = A21*T + C21 */
_mzd_add(S, A22, A12); /* 17 S = A22 + A21 */
_mzd_add(T, B22, B12); /* 18 T = B22 + B21 */
_mzd_addmul_even(U, S, T, cutoff); /* 19 U = U - S*T */
_mzd_add(C21, C21, U); /* 20 C21 = C21 - U3 */
_mzd_add(C22, C22, U); /* 21 C22 = C22 - U3 */
/* clean up */
mzd_free_window(A11); mzd_free_window(A12);
mzd_free_window(A21); mzd_free_window(A22);
mzd_free_window(B11); mzd_free_window(B12);
mzd_free_window(B21); mzd_free_window(B22);
mzd_free_window(C11); mzd_free_window(C12);
mzd_free_window(C21); mzd_free_window(C22);
mzd_free(S);
mzd_free(T);
mzd_free(U);
}
/* deal with rest */
nnn*=2;
if (n > nnn) {
/* | C| |AA| | B|
* Compute | C| += |AA| x | B| */
mzd_t *B_last_col = mzd_init_window(B, 0, nnn, k, n);
mzd_t *C_last_col = mzd_init_window(C, 0, nnn, m, n);
mzd_addmul_m4rm(C_last_col, A, B_last_col, 0);
mzd_free_window(B_last_col);
mzd_free_window(C_last_col);
}
mmm*=2;
if (m > mmm) {
/* | | | | |B |
* Compute |C | += |AA| x |B | */
mzd_t *A_last_row = mzd_init_window(A, mmm, 0, m, k);
mzd_t *B_first_col= mzd_init_window(B, 0, 0, k, nnn);
mzd_t *C_last_row = mzd_init_window(C, mmm, 0, m, nnn);
mzd_addmul_m4rm(C_last_row, A_last_row, B_first_col, 0);
mzd_free_window(A_last_row);
mzd_free_window(B_first_col);
mzd_free_window(C_last_row);
}
kkk*=2;
if (k > kkk) {
/* Add to | | | B| |C |
* result |A | x | | = | | */
mzd_t *A_last_col = mzd_init_window(A, 0, kkk, mmm, k);
mzd_t *B_last_row = mzd_init_window(B, kkk, 0, k, nnn);
mzd_t *C_bulk = mzd_init_window(C, 0, 0, mmm, nnn);
mzd_addmul_m4rm(C_bulk, A_last_col, B_last_row, 0);
mzd_free_window(A_last_col);
mzd_free_window(B_last_row);
mzd_free_window(C_bulk);
}
return C;
}
mzd_t *_mzd_addsqr_even(mzd_t *C, mzd_t *A, int cutoff) {
/**
* \todo make sure not to overwrite crap after ncols and before width*RADIX
*/
size_t m;
size_t mmm;
if(C->nrows == 0)
return C;
m = A->nrows;
/* handle case first, where the input matrices are too small already */
if (CLOSER(m, m/2, cutoff)) {
/* we copy the matrix first since it is only constant memory
overhead and improves data locality, if you remove it make sure
there are no speed regressions */
mzd_t *Cbar = mzd_copy(NULL, C);
mzd_addmul_m4rm(Cbar, A, A, 0);
mzd_copy(C, Cbar);
mzd_free(Cbar);
return C;
}
/* adjust cutting numbers to work on words */
{
unsigned long mult = RADIX;
unsigned long width = m>>1;
while (width > (unsigned long)cutoff) {
width>>=1;
mult<<=1;
}
mmm = (((m - m%mult)/RADIX) >> 1) * RADIX;
}
/* |C | |A | |B |
* Compute | | += | | x | | */
{
mzd_t *A11 = mzd_init_window(A, 0, 0, mmm, mmm);
mzd_t *A12 = mzd_init_window(A, 0, mmm, mmm, 2*mmm);
mzd_t *A21 = mzd_init_window(A, mmm, 0, 2*mmm, mmm);
mzd_t *A22 = mzd_init_window(A, mmm, mmm, 2*mmm, 2*mmm);
mzd_t *C11 = mzd_init_window(C, 0, 0, mmm, mmm);
mzd_t *C12 = mzd_init_window(C, 0, mmm, mmm, 2*mmm);
mzd_t *C21 = mzd_init_window(C, mmm, 0, 2*mmm, mmm);
mzd_t *C22 = mzd_init_window(C, mmm, mmm, 2*mmm, 2*mmm);
/**
* \note See <NAME>; "A Strassen-like Matrix Multiplication
* Suited for Squaring and Highest Power Computation"; on-line v.
* http://bodrato.it/papres/#CIVV2008 for reference on the used
* sequence of operations.
*/
mzd_t *S = mzd_init(mmm, mmm);
mzd_t *U = mzd_init(mmm, mmm);
_mzd_add(S, A22, A21); /* 1 S = A22 - A21 */
_mzd_sqr_even(U, S, cutoff); /* 3 U = S^2 */
_mzd_add(C22, U, C22); /* 4 C22 = U + C22 */
_mzd_add(C12, U, C12); /* 5 C12 = U + C12 */
_mzd_mul_even(U, A12, A21, cutoff); /* 8 U = A12*A21 */
_mzd_add(C11, U, C11); /* 9 C11 = U + C11 */
_mzd_addsqr_even(C11, A11, cutoff); /* 11 C11 = A11^2 + C11 */
_mzd_add(S, S, A12); /* 6 S = S + A12 */
_mzd_addsqr_even(U, S, cutoff); /* 10 U = S^2 + U */
_mzd_add(C12, C12, U); /* 15 C12 = U + C12 */
_mzd_add(S, A11, S); /* 12 S = A11 - S */
_mzd_addmul_even(C12, S, A12, cutoff); /* 14 C12 = S*B12 + C12 */
_mzd_addmul_even(C21, A21, S, cutoff); /* 16 C21 = A21*T + C21 */
_mzd_add(S, A22, A12); /* 17 S = A22 + A21 */
_mzd_addsqr_even(U, S, cutoff); /* 19 U = U - S^2 */
_mzd_add(C21, C21, U); /* 20 C21 = C21 - U3 */
_mzd_add(C22, C22, U); /* 21 C22 = C22 - U3 */
/* clean up */
mzd_free_window(A11); mzd_free_window(A12);
mzd_free_window(A21); mzd_free_window(A22);
mzd_free_window(C11); mzd_free_window(C12);
mzd_free_window(C21); mzd_free_window(C22);
mzd_free(S);
mzd_free(U);
}
/* deal with rest */
mmm*=2;
if (m > mmm) {
/* | C| |AA| | B|
* Compute | C| += |AA| x | B| */
{
mzd_t *A_last_col = mzd_init_window(A, 0, mmm, m, m);
mzd_t *C_last_col = mzd_init_window(C, 0, mmm, m, m);
mzd_addmul_m4rm(C_last_col, A, A_last_col, 0);
mzd_free_window(A_last_col);
mzd_free_window(C_last_col);
}
/* | | | | |B |
* Compute |C | += |AA| x |B | */
{
mzd_t *A_last_row = mzd_init_window(A, mmm, 0, m, m);
mzd_t *A_first_col= mzd_init_window(A, 0, 0, m, mmm);
mzd_t *C_last_row = mzd_init_window(C, mmm, 0, m, mmm);
mzd_addmul_m4rm(C_last_row, A_last_row, A_first_col, 0);
mzd_free_window(A_last_row);
mzd_free_window(A_first_col);
mzd_free_window(C_last_row);
}
/* Add to | | | B| |C |
* result |A | x | | = | | */
{
mzd_t *A_last_col = mzd_init_window(A, 0, mmm, mmm, m);
mzd_t *A_last_row = mzd_init_window(A, mmm, 0, m, mmm);
mzd_t *C_bulk = mzd_init_window(C, 0, 0, mmm, mmm);
mzd_addmul_m4rm(C_bulk, A_last_col, A_last_row, 0);
mzd_free_window(A_last_col);
mzd_free_window(A_last_row);
mzd_free_window(C_bulk);
}
}
return C;
}
mzd_t *_mzd_addmul(mzd_t *C, mzd_t *A, mzd_t *B, int cutoff){
/**
* Assumes that B and C are aligned in the same manner (as in a Schur complement)
*/
if (!A->offset){
if (!B->offset) /* A even, B even */
return (A==B) ? _mzd_addsqr_even(C, A, cutoff) : _mzd_addmul_even(C, A, B, cutoff);
else { /* A even, B weird */
size_t bnc = RADIX - B->offset;
if (B->ncols <= bnc){
_mzd_addmul_even_weird (C, A, B, cutoff);
} else {
mzd_t * B0 = mzd_init_window (B, 0, 0, B->nrows, bnc);
mzd_t * C0 = mzd_init_window (C, 0, 0, C->nrows, bnc);
mzd_t * B1 = mzd_init_window (B, 0, bnc, B->nrows, B->ncols);
mzd_t * C1 = mzd_init_window (C, 0, bnc, C->nrows, C->ncols);
_mzd_addmul_even_weird (C0, A, B0, cutoff);
_mzd_addmul_even(C1, A, B1, cutoff);
mzd_free_window (B0); mzd_free_window (B1);
mzd_free_window (C0); mzd_free_window (C1);
}
}
} else if (B->offset) { /* A weird, B weird */
size_t anc = RADIX - A->offset;
size_t bnc = RADIX - B->offset;
if (B->ncols <= bnc){
if (A->ncols <= anc)
_mzd_addmul_weird_weird (C, A, B, cutoff);
else {
mzd_t * A0 = mzd_init_window (A, 0, 0, A->nrows, anc);
mzd_t * A1 = mzd_init_window (A, 0, anc, A->nrows, A->ncols);
mzd_t * B0 = mzd_init_window (B, 0, 0, anc, B->ncols);
mzd_t * B1 = mzd_init_window (B, anc, 0, B->nrows, B->ncols);
_mzd_addmul_weird_weird (C, A0, B0, cutoff);
_mzd_addmul_even_weird (C, A1, B1, cutoff);
mzd_free_window (A0); mzd_free_window (A1);
mzd_free_window (B0); mzd_free_window (B1);
}
} else if (A->ncols <= anc) {
mzd_t * B0 = mzd_init_window (B, 0, 0, B->nrows, bnc);
mzd_t * B1 = mzd_init_window (B, 0, bnc, B->nrows, B->ncols);
mzd_t * C0 = mzd_init_window (C, 0, 0, C->nrows, bnc);
mzd_t * C1 = mzd_init_window (C, 0, bnc, C->nrows, C->ncols);
_mzd_addmul_weird_weird (C0, A, B0, cutoff);
_mzd_addmul_weird_even (C1, A, B1, cutoff);
mzd_free_window (B0); mzd_free_window (B1);
mzd_free_window (C0); mzd_free_window (C1);
} else {
mzd_t * A0 = mzd_init_window (A, 0, 0, A->nrows, anc);
mzd_t * A1 = mzd_init_window (A, 0, anc, A->nrows, A->ncols);
mzd_t * B00 = mzd_init_window (B, 0, 0, anc, bnc);
mzd_t * B01 = mzd_init_window (B, 0, bnc, anc, B->ncols);
mzd_t * B10 = mzd_init_window (B, anc, 0, B->nrows, bnc);
mzd_t * B11 = mzd_init_window (B, anc, bnc, B->nrows, B->ncols);
mzd_t * C0 = mzd_init_window (C, 0, 0, C->nrows, bnc);
mzd_t * C1 = mzd_init_window (C, 0, bnc, C->nrows, C->ncols);
_mzd_addmul_weird_weird (C0, A0, B00, cutoff);
_mzd_addmul_even_weird (C0, A1, B10, cutoff);
_mzd_addmul_weird_even (C1, A0, B01, cutoff);
_mzd_addmul_even (C1, A1, B11, cutoff);
mzd_free_window (A0); mzd_free_window (A1);
mzd_free_window (C0); mzd_free_window (C1);
mzd_free_window (B00); mzd_free_window (B01);
mzd_free_window (B10); mzd_free_window (B11);
}
} else { /* A weird, B even */
size_t anc = RADIX - A->offset;
if (A->ncols <= anc){
_mzd_addmul_weird_even (C, A, B, cutoff);
} else {
mzd_t * A0 = mzd_init_window (A, 0, 0, A->nrows, anc);
mzd_t * A1 = mzd_init_window (A, 0, anc, A->nrows, A->ncols);
mzd_t * B0 = mzd_init_window (B, 0, 0, anc, B->ncols);
mzd_t * B1 = mzd_init_window (B, anc, 0, B->nrows, B->ncols);
_mzd_addmul_weird_even (C, A0, B0, cutoff);
_mzd_addmul_even (C, A1, B1, cutoff);
mzd_free_window (A0); mzd_free_window (A1);
mzd_free_window (B0); mzd_free_window (B1);
}
}
return C;
}
mzd_t *_mzd_addmul_weird_even (mzd_t *C, mzd_t *A, mzd_t *B, int cutoff){
mzd_t * tmp = mzd_init (A->nrows, MIN(RADIX- A->offset, A->ncols));
for (size_t i=0; i < A->nrows; ++i){
tmp->rows[i][0] = (A->rows[i][0] << A->offset);
}
_mzd_addmul_even (C, tmp, B, cutoff);
mzd_free(tmp);
return C;
}
mzd_t *_mzd_addmul_even_weird (mzd_t *C, mzd_t *A, mzd_t *B, int cutoff){
mzd_t * tmp = mzd_init (B->nrows, RADIX);
size_t offset = C->offset;
size_t cncols = C->ncols;
C->offset=0;
C->ncols = RADIX;
word mask = ((ONE << B->ncols) - 1) << (RADIX-B->offset - B->ncols);
for (size_t i=0; i < B->nrows; ++i)
tmp->rows[i][0] = B->rows[i][0] & mask;
_mzd_addmul_even (C, A, tmp, cutoff);
C->offset=offset;
C->ncols = cncols;
mzd_free (tmp);
return C;
}
mzd_t* _mzd_addmul_weird_weird (mzd_t* C, mzd_t* A, mzd_t *B, int cutoff){
mzd_t *BT;
word* temp;
BT = mzd_init( B->ncols, B->nrows );
for (size_t i = 0; i < B->ncols; ++i) {
temp = BT->rows[i];
for (size_t k = 0; k < B->nrows; k++) {
*temp |= ((word)mzd_read_bit (B, k, i)) << (RADIX-1-k-A->offset);
}
}
word parity[64];
for (size_t i = 0; i < 64; i++) {
parity[i] = 0;
}
for (size_t i = 0; i < A->nrows; ++i) {
word * a = A->rows[i];
word * c = C->rows[i];
for (size_t k=0; k< C->ncols; k++) {
word *b = BT->rows[k];
parity[k+C->offset] = (*a) & (*b);
}
word par = parity64(parity);
*c ^= par;//parity64(parity);
}
mzd_free (BT);
return C;
}
mzd_t *mzd_addmul(mzd_t *C, mzd_t *A, mzd_t *B, int cutoff) {
if(A->ncols != B->nrows)
m4ri_die("mzd_addmul: A ncols (%d) need to match B nrows (%d).\n", A->ncols, B->nrows);
if (cutoff < 0)
m4ri_die("mzd_addmul: cutoff must be >= 0.\n");
if(cutoff == 0) {
cutoff = STRASSEN_MUL_CUTOFF;
}
cutoff = cutoff/RADIX * RADIX;
if (cutoff < RADIX) {
cutoff = RADIX;
};
if (C == NULL) {
C = mzd_init(A->nrows, B->ncols);
} else if (C->nrows != A->nrows || C->ncols != B->ncols){
m4ri_die("mzd_addmul: C (%d x %d) has wrong dimensions, expected (%d x %d)\n",
C->nrows, C->ncols, A->nrows, B->ncols);
}
C = _mzd_addmul(C, A, B, cutoff);
return C;
}
|
yp/Heu-MCHC
|
pers-lib/m4ri/src/packedmatrix.h
|
<filename>pers-lib/m4ri/src/packedmatrix.h<gh_stars>1-10
/**
* \file packedmatrix.h
* \brief Dense matrices over GF(2) represented as a bit field.
*
* \author <NAME> <<EMAIL>>
* \author <NAME> <<EMAIL>>
*/
#ifndef PACKEDMATRIX_H
#define PACKEDMATRIX_H
/*******************************************************************
*
* M4RI: Linear Algebra over GF(2)
*
* Copyright (C) 2007, 2008 <NAME> <<EMAIL>>
* Copyright (C) 2008 <NAME> <<EMAIL>>
*
* Distributed under the terms of the GNU General Public License (GPL)
* version 2 or higher.
*
* This code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* The full text of the GPL is available at:
*
* http://www.gnu.org/licenses/
*
********************************************************************/
#include <math.h>
#include <assert.h>
#include <stdio.h>
#include "misc.h"
#ifdef HAVE_SSE2
#include <emmintrin.h>
#endif
#ifdef HAVE_SSE2
/**
* \brief SSE2 curoff in words.
*
* Cutoff in words after which row length SSE2 instructions should be
* used.
*/
#define SSE2_CUTOFF 20
#endif
/**
* \brief Matrix multiplication block-ing dimension.
*
* Defines the number of rows of the matrix A that are
* processed as one block during the execution of a multiplication
* algorithm.
*/
#define MZD_MUL_BLOCKSIZE MIN(((int)sqrt((double)(4*CPU_L2_CACHE)))/2,2048)
/**
* \brief Dense matrices over GF(2).
*
* The most fundamental data type in this library.
*/
typedef struct {
/**
* Contains pointers to the actual blocks of memory containing the
* values packed into words of size RADIX.
*/
mmb_t *blocks;
/**
* Number of rows.
*/
size_t nrows;
/**
* Number of columns.
*/
size_t ncols;
/**
* width = ceil(ncols/RADIX)
*/
size_t width;
/**
* column offset of the first column.
*/
size_t offset;
/**
* Address of first word in each row, so the first word of row i is
* is m->rows[i]
*/
word **rows;
size_t *rowperm;
} mzd_t;
/**
* \brief Create a new matrix of dimension r x c.
*
* Use mzd_free to kill it.
*
* \param r Number of rows
* \param c Number of columns
*
*/
mzd_t *mzd_init(const size_t r, const size_t c);
/**
* \brief Free a matrix created with mzd_init.
*
* \param A Matrix
*/
void mzd_free(mzd_t *A);
/**
* \brief Create a window/view into the matrix M.
*
* A matrix window for M is a meta structure on the matrix M. It is
* setup to point into the matrix so M \em must \em not be freed while the
* matrix window is used.
*
* This function puts the restriction on the provided parameters that
* all parameters must be within range for M which is not enforced
* currently .
*
* Use mzd_free_window to free the window.
*
* \param M Matrix
* \param lowr Starting row (inclusive)
* \param lowc Starting column (inclusive)
* \param highr End row (exclusive)
* \param highc End column (exclusive)
*
*/
mzd_t *mzd_init_window(const mzd_t *M, const size_t lowr, const size_t lowc, const size_t highr, const size_t highc);
/**
* \brief Free a matrix window created with mzd_init_window.
*
* \param A Matrix
*/
#define mzd_free_window mzd_free
/**
* \brief Swap the two rows rowa and rowb.
*
* \param M Matrix
* \param rowa Row index.
* \param rowb Row index.
*/
static inline void mzd_row_swap(mzd_t *M, const size_t rowa, const size_t rowb) {
if(rowa == rowb)
return;
size_t i;
size_t width = M->width - 1;
word *a = M->rows[rowa];
word *b = M->rows[rowb];
if (M->rowperm!=NULL) {
size_t tperm= M->rowperm[rowa];
M->rowperm[rowa]= M->rowperm[rowb];
M->rowperm[rowb]= tperm;
}
word tmp;
word mask_begin = RIGHT_BITMASK(RADIX - M->offset);
word mask_end = LEFT_BITMASK( (M->offset + M->ncols)%RADIX );
if (width != 0) {
tmp = a[0];
a[0] = (a[0] & ~mask_begin) | (b[0] & mask_begin);
b[0] = (b[0] & ~mask_begin) | (tmp & mask_begin);
for(i = 1; i<width; i++) {
tmp = a[i];
a[i] = b[i];
b[i] = tmp;
}
tmp = a[width];
a[width] = (a[width] & ~mask_end) | (b[width] & mask_end);
b[width] = (b[width] & ~mask_end) | (tmp & mask_end);
} else {
tmp = a[0];
a[0] = (a[0] & ~mask_begin) | (b[0] & mask_begin & mask_end) | (a[0] & ~mask_end);
b[0] = (b[0] & ~mask_begin) | (tmp & mask_begin & mask_end) | (b[0] & ~mask_end);
}
}
/**
* \brief copy row j from A to row i from B.
*
* The offsets of A and B must match and the number of columns of A
* must be less than or equal to the number of columns of B.
*
* \param B Target matrix.
* \param i Target row index.
* \param A Source matrix.
* \param j Source row index.
*/
void mzd_copy_row(mzd_t* B, size_t i, const mzd_t* A, size_t j);
/**
* \brief Swap the two columns cola and colb.
*
* \param M Matrix.
* \param cola Column index.
* \param colb Column index.
*/
void mzd_col_swap(mzd_t *M, const size_t cola, const size_t colb);
/**
* \brief Swap the two columns cola and colb but only between start_row and stop_row.
*
* \param M Matrix.
* \param cola Column index.
* \param colb Column index.
* \param start_row Row index.
* \param stop_row Row index (exclusive).
*/
static inline void mzd_col_swap_in_rows(mzd_t *M, const size_t cola, const size_t colb, const size_t start_row, const size_t stop_row) {
if (cola == colb)
return;
const size_t _cola = cola + M->offset;
const size_t _colb = colb + M->offset;
const size_t a_word = _cola/RADIX;
const size_t b_word = _colb/RADIX;
const size_t a_bit = _cola%RADIX;
const size_t b_bit = _colb%RADIX;
word a, b, *base;
size_t i;
if(a_word == b_word) {
const word ai = RADIX - a_bit - 1;
const word bi = RADIX - b_bit - 1;
for (i=start_row; i<stop_row; i++) {
base = (M->rows[i] + a_word);
register word b = *base;
register word x = ((b >> ai) ^ (b >> bi)) & 1; // XOR temporary
*base = b ^ ((x << ai) | (x << bi));
}
return;
}
const word a_bm = (ONE<<(RADIX - (a_bit) - 1));
const word b_bm = (ONE<<(RADIX - (b_bit) - 1));
if(a_bit > b_bit) {
const size_t offset = a_bit - b_bit;
for (i=start_row; i<stop_row; i++) {
base = M->rows[i];
a = *(base + a_word);
b = *(base + b_word);
a ^= (b & b_bm) >> offset;
b ^= (a & a_bm) << offset;
a ^= (b & b_bm) >> offset;
*(base + a_word) = a;
*(base + b_word) = b;
}
} else {
const size_t offset = b_bit - a_bit;
for (i=start_row; i<stop_row; i++) {
base = M->rows[i];
a = *(base + a_word);
b = *(base + b_word);
a ^= (b & b_bm) << offset;
b ^= (a & a_bm) >> offset;
a ^= (b & b_bm) << offset;
*(base + a_word) = a;
*(base + b_word) = b;
}
}
}
/**
* \brief Read the bit at position M[row,col].
*
* \param M Matrix
* \param row Row index
* \param col Column index
*
* \note No bounds checks whatsoever are performed.
*
*/
static inline BIT mzd_read_bit(const mzd_t *M, const size_t row, const size_t col ) {
return GET_BIT(M->rows[row][(col+M->offset)/RADIX], (col+M->offset) % RADIX);
}
/**
* \brief Write the bit value to position M[row,col]
*
* \param M Matrix
* \param row Row index
* \param col Column index
* \param value Either 0 or 1
*
* \note No bounds checks whatsoever are performed.
*
*/
static inline void mzd_write_bit(mzd_t *M, const size_t row, const size_t col, const BIT value) {
if (value==1)
SET_BIT(M->rows[row][(col+M->offset)/RADIX], (col+M->offset) % RADIX);
else
CLR_BIT(M->rows[row][(col+M->offset)/RADIX], (col+M->offset) % RADIX);
}
/**
* \brief Print a matrix to stdout.
*
* The output will contain colons between every 4-th column.
*
* \param M Matrix
*/
void mzd_print(const mzd_t *M);
/**
* \brief Print the matrix to stdout.
*
* \param M Matrix
*/
void mzd_print_tight(const mzd_t *M);
/**
* \brief Add the rows sourcerow and destrow and stores the total in the row
* destrow, but only begins at the column coloffset.
*
* \param M Matrix
* \param dstrow Index of target row
* \param srcrow Index of source row
* \param coloffset Column offset
*/
/*void mzd_row_add_offset(mzd_t *M, size_t dstrow, size_t srcrow, size_t coloffset); */
static inline void mzd_row_add_offset(mzd_t *M, size_t dstrow, size_t srcrow, size_t coloffset) {
coloffset += M->offset;
const size_t startblock= coloffset/RADIX;
size_t wide = M->width - startblock;
word *src = M->rows[srcrow] + startblock;
word *dst = M->rows[dstrow] + startblock;
if(!wide)
return;
word temp = *src++;
if (coloffset%RADIX)
temp = RIGHTMOST_BITS(temp, (RADIX-(coloffset%RADIX)-1));
*dst++ ^= temp;
wide--;
#ifdef HAVE_SSE2
if (ALIGNMENT(src,16)==8 && wide) {
*dst++ ^= *src++;
wide--;
}
__m128i *__src = (__m128i*)src;
__m128i *__dst = (__m128i*)dst;
const __m128i *eof = (__m128i*)((unsigned long)(src + wide) & ~0xF);
__m128i xmm1;
while(__src < eof) {
xmm1 = _mm_xor_si128(*__dst, *__src++);
*__dst++ = xmm1;
}
src = (word*)__src;
dst = (word*)__dst;
wide = ((sizeof(word)*wide)%16)/sizeof(word);
#endif
size_t i;
for(i=0; i<wide; i++) {
dst[i] ^= src[i];
}
}
/**
* \brief Add the rows sourcerow and destrow and stores the total in
* the row destrow.
*
* \param M Matrix
* \param sourcerow Index of source row
* \param destrow Index of target row
*
* \note this can be done much faster with mzd_combine.
*/
void mzd_row_add(mzd_t *M, const size_t sourcerow, const size_t destrow);
/**
* \brief Transpose a matrix.
*
* This function uses the fact that:
\verbatim
[ A B ]T [AT CT]
[ C D ] = [BT DT]
\endverbatim
* and thus rearranges the blocks recursively.
*
* \param DST Preallocated return matrix, may be NULL for automatic creation.
* \param A Matrix
*/
mzd_t *mzd_transpose(mzd_t *DST, const mzd_t *A );
/**
* \brief Naive cubic matrix multiplication.
*
* That is, compute C such that C == AB.
*
* \param C Preallocated product matrix, may be NULL for automatic creation.
* \param A Input matrix A.
* \param B Input matrix B.
*
* \note Normally, if you will multiply several times by b, it is
* smarter to calculate bT yourself, and keep it, and then use the
* function called _mzd_mul_naive
*
*/
mzd_t *mzd_mul_naive(mzd_t *C, const mzd_t *A, const mzd_t *B);
/**
* \brief Naive cubic matrix multiplication and addition
*
* That is, compute C such that C == C + AB.
*
* \param C Preallocated product matrix.
* \param A Input matrix A.
* \param B Input matrix B.
*
* \note Normally, if you will multiply several times by b, it is
* smarter to calculate bT yourself, and keep it, and then use the
* function called _mzd_mul_naive
*/
mzd_t *mzd_addmul_naive(mzd_t *C, const mzd_t *A, const mzd_t *B);
/**
* \brief Naive cubic matrix multiplication with the pre-transposed B.
*
* That is, compute C such that C == AB^t.
*
* \param C Preallocated product matrix.
* \param A Input matrix A.
* \param B Pre-transposed input matrix B.
* \param clear Whether to clear C before accumulating AB
*/
mzd_t *_mzd_mul_naive(mzd_t *C, const mzd_t *A, const mzd_t *B, const int clear);
/**
* \brief Matrix multiplication optimized for v*A where v is a vector.
*
* \param C Preallocated product matrix.
* \param v Input matrix v.
* \param A Input matrix A.
* \param clear If set clear C first, otherwise add result to C.
*
*/
mzd_t *_mzd_mul_va(mzd_t *C, const mzd_t *v, const mzd_t *A, const int clear);
/**
* \brief Fill matrix M with uniformly distributed bits.
*
* \param M Matrix
*
* \todo Allow the user to provide a RNG callback.
*
* \wordoffset
*/
void mzd_randomize(mzd_t *M);
/**
* \brief Set the matrix M to the value equivalent to the integer
* value provided.
*
* Specifically, this function does nothing if value%2 == 0 and
* returns the identity matrix if value%2 == 1.
*
* If the matrix is not square then the largest possible square
* submatrix is set to the identity matrix.
*
* \param M Matrix
* \param value Either 0 or 1
*/
void mzd_set_ui(mzd_t *M, const unsigned value);
/**
* \brief Gaussian elimination.
*
* This will do Gaussian elimination on the matrix m but will start
* not at column 0 necc but at column startcol. If full=FALSE, then it
* will do triangular style elimination, and if full=TRUE, it will do
* Gauss-Jordan style, or full elimination.
*
* \param M Matrix
* \param startcol First column to consider for reduction.
* \param full Gauss-Jordan style or upper triangular form only.
*
* \wordoffset
*/
int mzd_gauss_delayed(mzd_t *M, const size_t startcol, const int full);
/**
* \brief Gaussian elimination.
*
* This will do Gaussian elimination on the matrix m. If full=FALSE,
* then it will do triangular style elimination, and if full=TRUE,
* it will do Gauss-Jordan style, or full elimination.
*
* \param M Matrix
* \param full Gauss-Jordan style or upper triangular form only.
*
* \wordoffset
*
* \sa mzd_echelonize_m4ri(), mzd_echelonize_pluq()
*/
int mzd_echelonize_naive(mzd_t *M, const int full);
/**
* \brief Return TRUE if A == B.
*
* \param A Matrix
* \param B Matrix
*
* \wordoffset
*/
BIT mzd_equal(const mzd_t *A, const mzd_t *B );
/**
* \brief Return -1,0,1 if if A < B, A == B or A > B respectively.
*
* \param A Matrix.
* \param B Matrix.
*
* \note This comparison is not well defined mathematically and
* relatively arbitrary since elements of GF(2) don't have an
* ordering.
*
* \wordoffset
*/
int mzd_cmp(const mzd_t *A, const mzd_t *B);
/**
* \brief Copy matrix A to DST.
*
* \param DST May be NULL for automatic creation.
* \param A Source matrix.
*
* \wordoffset
*/
mzd_t *mzd_copy(mzd_t *DST, const mzd_t *A);
/**
* \brief Concatenate B to A and write the result to C.
*
* That is,
*
\verbatim
[ A ], [ B ] -> [ A B ] = C
\endverbatim
*
* The inputs are not modified but a new matrix is created.
*
* \param C Matrix, may be NULL for automatic creation
* \param A Matrix
* \param B Matrix
*
* \note This is sometimes called augment.
*
* \wordoffset
*/
mzd_t *mzd_concat(mzd_t *C, const mzd_t *A, const mzd_t *B);
/**
* \brief Stack A on top of B and write the result to C.
*
* That is,
*
\verbatim
[ A ], [ B ] -> [ A ] = C
[ B ]
\endverbatim
*
* The inputs are not modified but a new matrix is created.
*
* \param C Matrix, may be NULL for automatic creation
* \param A Matrix
* \param B Matrix
*
* \wordoffset
*/
mzd_t *mzd_stack(mzd_t *C, const mzd_t *A, const mzd_t *B);
/**
* \brief Copy a submatrix.
*
* Note that the upper bounds are not included.
*
* \param S Preallocated space for submatrix, may be NULL for automatic creation.
* \param M Matrix
* \param lowr start rows
* \param lowc start column
* \param highr stop row (this row is \em not included)
* \param highc stop column (this column is \em not included)
*/
mzd_t *mzd_submatrix(mzd_t *S, const mzd_t *M, const size_t lowr, const size_t lowc, const size_t highr, const size_t highc);
/**
* \brief Invert the matrix target using Gaussian elimination.
*
* To avoid recomputing the identity matrix over and over again, I may
* be passed in as identity parameter.
*
* \param INV Preallocated space for inversion matrix, may be NULL for automatic creation.
* \param A Matrix to be reduced.
* \param I Identity matrix.
*
* \wordoffset
*/
mzd_t *mzd_invert_naive(mzd_t *INV, mzd_t *A, const mzd_t *I);
/**
* \brief Set C = A+B.
*
* C is also returned. If C is NULL then a new matrix is created which
* must be freed by mzd_free.
*
* \param C Preallocated sum matrix, may be NULL for automatic creation.
* \param A Matrix
* \param B Matrix
*/
mzd_t *mzd_add(mzd_t *C, const mzd_t *A, const mzd_t *B);
/**
* \brief Same as mzd_add but without any checks on the input.
*
* \param C Preallocated sum matrix, may be NULL for automatic creation.
* \param A Matrix
* \param B Matrix
*
* \wordoffset
*/
mzd_t *_mzd_add(mzd_t *C, const mzd_t *A, const mzd_t *B);
/**
* \brief Same as mzd_add.
*
* \param C Preallocated difference matrix, may be NULL for automatic creation.
* \param A Matrix
* \param B Matrix
*
* \wordoffset
*/
#define mzd_sub mzd_add
/**
* \brief Same as mzd_sub but without any checks on the input.
*
* \param C Preallocated difference matrix, may be NULL for automatic creation.
* \param A Matrix
* \param B Matrix
*
* \wordoffset
*/
#define _mzd_sub _mzd_add
/**
* \brief row3[col3:] = row1[col1:] + row2[col2:]
*
* Adds row1 of SC1, starting with startblock1 to the end, to
* row2 of SC2, starting with startblock2 to the end. This gets stored
* in DST, in row3, starting with startblock3.
*
* \param DST destination matrix
* \param row3 destination row for matrix dst
* \param startblock3 starting block to work on in matrix dst
* \param SC1 source matrix
* \param row1 source row for matrix sc1
* \param startblock1 starting block to work on in matrix sc1
* \param SC2 source matrix
* \param startblock2 starting block to work on in matrix sc2
* \param row2 source row for matrix sc2
*
* \wordoffset
*/
void mzd_combine(mzd_t * DST, const size_t row3, const size_t startblock3,
const mzd_t * SC1, const size_t row1, const size_t startblock1,
const mzd_t * SC2, const size_t row2, const size_t startblock2);
/**
* Get n bits starting a position (x,y) from the matrix M.
*
* \param M Source matrix.
* \param x Starting row.
* \param y Starting column.
* \param n Number of bits (<= RADIX);
*/
static inline word mzd_read_bits(const mzd_t *M, const size_t x, const size_t y, const int n) {
word temp;
/* there are two possible situations. Either all bits are in one
* word or they are spread across two words. */
if ( ((y+M->offset)%RADIX + n - 1) < RADIX ) {
/* everything happens in one word here */
temp = M->rows[x][(y+M->offset) / RADIX]; /* get the value */
temp <<= (y+M->offset)%RADIX; /* clear upper bits */
temp >>= RADIX - n; /* clear lower bits and move to correct position.*/
return temp;
} else {
/* two words are affected */
const size_t block = (y+M->offset) / RADIX; /* correct block */
const size_t spot = (y+M->offset+n) % RADIX; /* correct offset */
/* make room by shifting spot times to the right, and add stuff from the second word */
temp = (M->rows[x][block] << spot) | ( M->rows[x][block + 1] >> (RADIX - spot) );
return (temp << (RADIX-n)) >> (RADIX-n); /* clear upper bits and return */
}
}
/**
* \brief XOR n bits from values to M starting a position (x,y).
*
* \param M Source matrix.
* \param x Starting row.
* \param y Starting column.
* \param n Number of bits (<= RADIX);
* \param values Word with values;
*/
static inline void mzd_xor_bits(const mzd_t *M, const size_t x, const size_t y, const int n, word values) {
word *temp;
/* there are two possible situations. Either all bits are in one
* word or they are spread across two words. */
if ( ((y+M->offset)%RADIX + n - 1) < RADIX ) {
/* everything happens in one word here */
temp = M->rows[x] + (y+M->offset) / RADIX;
*temp ^= values<<(RADIX-((y+M->offset)%RADIX)-n);
} else {
/* two words are affected */
const size_t block = (y+M->offset) / RADIX; /* correct block */
const size_t spot = (y+M->offset+n) % RADIX; /* correct offset */
M->rows[x][block] ^= values >> (spot);
M->rows[x][block + 1] ^= values<<(RADIX-spot);
}
}
/**
* \brief AND n bits from values to M starting a position (x,y).
*
* \param M Source matrix.
* \param x Starting row.
* \param y Starting column.
* \param n Number of bits (<= RADIX);
* \param values Word with values;
*/
static inline void mzd_and_bits(const mzd_t *M, const size_t x, const size_t y, const int n, word values) {
word *temp;
/* there are two possible situations. Either all bits are in one
* word or they are spread across two words. */
if ( ((y+M->offset)%RADIX + n - 1) < RADIX ) {
/* everything happens in one word here */
temp = M->rows[x] + (y+M->offset) / RADIX;
*temp &= values<<(RADIX-((y+M->offset)%RADIX)-n);
} else {
/* two words are affected */
const size_t block = (y+M->offset) / RADIX; /* correct block */
const size_t spot = (y+M->offset+n) % RADIX; /* correct offset */
M->rows[x][block] &= values >> (spot);
M->rows[x][block + 1] &= values<<(RADIX-spot);
}
}
/**
* \brief Clear n bits in M starting a position (x,y).
*
* \param M Source matrix.
* \param x Starting row.
* \param y Starting column.
* \param n Number of bits (<= RADIX);
*/
static inline void mzd_clear_bits(const mzd_t *M, const size_t x, const size_t y, const int n) {
word temp;
/* there are two possible situations. Either all bits are in one
* word or they are spread across two words. */
if ( ((y+M->offset)%RADIX + n - 1) < RADIX ) {
/* everything happens in one word here */
temp = M->rows[x][(y+M->offset) / RADIX];
temp <<= (y+M->offset)%RADIX; /* clear upper bits */
temp >>= RADIX-n; /* clear lower bits and move to correct position.*/
temp <<= RADIX-n - (y+M->offset)%RADIX;
M->rows[x][(y+M->offset) / RADIX] ^= temp;
} else {
/* two words are affected */
const size_t block = (y+M->offset) / RADIX; /* correct block */
const size_t spot = (y+M->offset+n) % RADIX; /* correct offset */
M->rows[x][block] ^= M->rows[x][block] & ((ONE<<(n-spot))-1);
M->rows[x][block+1] ^= (M->rows[x][block+1]>>(RADIX-spot))<<(RADIX-spot);
}
}
/**
* \brief Zero test for matrix.
*
* \param A Input matrix.
*
*/
int mzd_is_zero(mzd_t *A);
/**
* \brief Clear the given row, but only begins at the column coloffset.
*
* \param M Matrix
* \param row Index of row
* \param coloffset Column offset
*/
void mzd_row_clear_offset(mzd_t *M, const size_t row, const size_t coloffset);
/**
* \brief Find the next nonzero entry in M starting at start_row and start_col.
*
* This function walks down rows in the inner loop and columns in the
* outer loop. If a nonzero entry is found this function returns 1 and
* zero otherwise.
*
* If and only if a nonzero entry is found r and c are updated.
*
* \param M Matrix
* \param start_row Index of row where to start search
* \param start_col Index of column where to start search
* \param r Row index updated if pivot is found
* \param c Column index updated if pivot is found
*/
int mzd_find_pivot(mzd_t *M, size_t start_row, size_t start_col, size_t *r, size_t *c);
/**
* \brief Return the number of nonzero entries divided by nrows *
* ncols
*
* If res = 0 then 100 samples per row are made, if res > 0 the
* function takes res sized steps within each row (res = 1 uses every
* word).
*
* \param A Matrix
* \param res Resolution of sampling
*/
double mzd_density(mzd_t *A, int res);
/**
* \brief Return the first row with all zero entries.
*
* If no such row can be found returns nrows.
*
* \param A Matrix
*/
size_t mzd_first_zero_row(mzd_t *A);
#endif //PACKEDMATRIX_H
|
yp/Heu-MCHC
|
pers-lib/m4ri/src/trsm.h
|
/**
* \file trsm.h
*
* \brief Triangular system solving with Matrix routines.
*
* \author <NAME> <<EMAIL>>
*/
#ifndef TRSM_H
#define TRSM_H
/*******************************************************************
*
* M4RI: Linear Algebra over GF(2)
*
* Copyright (C) 2008 <NAME> <<EMAIL>>
*
* Distributed under the terms of the GNU General Public License (GPL)
* version 2 or higher.
*
* This code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* The full text of the GPL is available at:
*
* http://www.gnu.org/licenses/
*
********************************************************************/
#include "misc.h"
#include "packedmatrix.h"
/**
* \brief Solves X U = B with X and B matrices and U upper triangular.
*
* X is stored inplace on B.
*
* \attention Note, that the 'right' variants of TRSM are slower than
* the 'left' variants.
*
* This is the wrapper function including bounds checks. See
* _mzd_trsm_upper_right() for implementation details.
*
* \param U Input upper triangular matrix.
* \param B Input matrix, being overwritten by the solution matrix X
* \param cutoff Minimal dimension for Strassen recursion.
*/
void mzd_trsm_upper_right(mzd_t *U, mzd_t *B, const int cutoff);
/**
* \brief Solves X U = B with X and B matrices and U upper triangular.
*
* X is stored inplace on B.
*
* \attention Note, that the 'right' variants of TRSM are slower than
* the 'left' variants.
*
* \param U Input upper triangular matrix.
* \param B Input matrix, being overwritten by the solution matrix X
* \param cutoff Minimal dimension for Strassen recursion.
*/
void _mzd_trsm_upper_right(mzd_t *U, mzd_t *B, const int cutoff);
/**
* \brief Solves X L = B with X and B matrices and L lower triangular.
*
* X is stored inplace on B.
*
* This is the wrapper function including bounds checks. See
* _mzd_trsm_upper_right() for implementation details.
*
* \attention Note, that the 'right' variants of TRSM are slower than the 'left'
* variants.
*
* \param L Input upper triangular matrix.
* \param B Input matrix, being overwritten by the solution matrix X
* \param cutoff Minimal dimension for Strassen recursion.
*/
void mzd_trsm_lower_right(mzd_t *L, mzd_t *B, const int cutoff);
/**
* \brief Solves X L = B with X and B with matrices and L lower
* triangular.
*
* This version assumes that the matrices are at an even position on
* the RADIX grid and that their dimension is a multiple of RADIX. X
* is stored inplace on B.
*
* \attention Note, that the 'right' variants of TRSM are slower than
* the 'left' variants.
*
* \param L Input lower triangular matrix.
* \param B Input matrix, being overwritten by the solution matrix X
* \param cutoff Minimal dimension for Strassen recursion.
*
*/
void _mzd_trsm_lower_right(mzd_t *L, mzd_t *B, const int cutoff);
/**
* \brief Solves L X = B with X and B matrices and L lower triangular.
*
* X is stored inplace on B.
*
* This is the wrapper function including bounds checks. See
* _mzd_trsm_lower_left() for implementation details.
*
* \param L Input lower triangular matrix.
* \param B Input matrix, being overwritten by the solution matrix X
* \param cutoff Minimal dimension for Strassen recursion.
*/
void mzd_trsm_lower_left(mzd_t *L, mzd_t *B, const int cutoff);
/**
* \brief Solves L X = B with X and B matrices and L lower triangular.
*
* X is stored inplace on B.
*
* \param L Input lower triangular matrix.
* \param B Input matrix, being overwritten by the solution matrix X
* \param cutoff Minimal dimension for Strassen recursion.
*/
void _mzd_trsm_lower_left(mzd_t *L, mzd_t *B, const int cutoff);
/**
* \brief Solves U X = B with X and B matrices and U upper triangular.
*
* X is stored inplace on B.
*
* This is the wrapper function including bounds checks. See
* _mzd_trsm_upper_left() for implementation details.
*
* \param U Input upper triangular matrix.
* \param B Input matrix, being overwritten by the solution matrix X
* \param cutoff Minimal dimension for Strassen recursion.
*/
void mzd_trsm_upper_left(mzd_t *U, mzd_t *B, const int cutoff);
/**
* \brief Solves U X = B with X and B matrices and U upper triangular.
*
* X is stored inplace on B.
*
* \param U Input upper triangular matrix.
* \param B Input matrix, being overwritten by the solution matrix X
* \param cutoff Minimal dimension for Strassen recursion.
*/
void _mzd_trsm_upper_left (mzd_t *U, mzd_t *B, const int cutoff);
#endif
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.