How to use an existing DL4J trained model to classify new input - dl4j

I have a DL4J LSTM model that generates a binary classification of sequential input. i have trained and tested the model and am happy with the precision/recall. Now I want to use this model to predict the binary classification of new inputs. How do I do this? i.e. how do I give the trained neural network a single Input (file containing the sequence of feature rows) and get the binary classification of this input file.
Here is my original training data set iterator:
SequenceRecordReader trainFeatures = new CSVSequenceRecordReader(0, ","); //skip no header lines
try {
trainFeatures.initialize( new NumberedFileInputSplit(featureBaseDir + "/s_%d.csv", 0,this._modelDefinition.getNB_TRAIN_EXAMPLES()-1));
} catch (IOException e) {
trainFeatures.close();
throw new IOException(String.format("IO error %s. during trainFeatures", e.getMessage()));
} catch (InterruptedException e) {
trainFeatures.close();
throw new IOException(String.format("Interrupted exception error %s. during trainFeatures", e.getMessage()));
}
SequenceRecordReader trainLabels = new CSVSequenceRecordReader();
try {
trainLabels.initialize(new NumberedFileInputSplit(labelBaseDir + "/s_%d.csv", 0,this._modelDefinition.getNB_TRAIN_EXAMPLES()-1));
} catch (InterruptedException e) {
trainLabels.close();
trainFeatures.close();
throw new IOException(String.format("Interrupted exception error %s. during trainLabels initialise", e.getMessage()));
}
DataSetIterator trainData = new SequenceRecordReaderDataSetIterator(trainFeatures, trainLabels,
this._modelDefinition.getBATCH_SIZE(),this._modelDefinition.getNUM_LABEL_CLASSES(), false, SequenceRecordReaderDataSetIterator.AlignmentMode.ALIGN_END);
Here is my model:
MultiLayerConfiguration conf = new NeuralNetConfiguration.Builder()
.seed(this._modelDefinition.getRANDOM_SEED()) //Random number generator seed for improved repeatability. Optional.
.weightInit(WeightInit.XAVIER)
.updater(new Nesterovs(this._modelDefinition.getLEARNING_RATE()))
.gradientNormalization(GradientNormalization.ClipElementWiseAbsoluteValue) //Not always required, but helps with this data set
.gradientNormalizationThreshold(0.5)
.list()
.layer(0, new LSTM.Builder().activation(Activation.TANH).nIn(this._modelDefinition.getNB_INPUTS()).nOut(this._modelDefinition.getLSTM_LAYER_SIZE()).build())
.layer(1, new LSTM.Builder().activation(Activation.TANH).nIn(this._modelDefinition.getLSTM_LAYER_SIZE()).nOut(this._modelDefinition.getLSTM_LAYER_SIZE()).build())
.layer(2,new DenseLayer.Builder().nIn(this._modelDefinition.getLSTM_LAYER_SIZE()).nOut(this._modelDefinition.getLSTM_LAYER_SIZE())
.weightInit(WeightInit.XAVIER)
.build())
.layer(3, new RnnOutputLayer.Builder(LossFunctions.LossFunction.MCXENT)
.activation(Activation.SOFTMAX).nIn(this._modelDefinition.getLSTM_LAYER_SIZE()).nOut(this._modelDefinition.getNUM_LABEL_CLASSES()).build())
.pretrain(false).backprop(true).build();
I train the model over N epochs to get my optimal scores. I save the model, now I want to open the model and get classifications for new sequential feature files.
If there is an example of this - please let me know where.
thanks
anton

The answer is to feed the model the exact same input as we trained with, except set the labels to -1. The output will be an INDarray containing the probability of 0 in one array and the probability of 1 in the other array, showing up in the last sequence line.
Here is the code:
public void getOutputsForTheseInputsUsingThisNet(String netFilePath,String inputFileDir) throws Exception {
//open the network file
File locationToSave = new File(netFilePath);
MultiLayerNetwork nNet = null;
logger.info("Trying to open the model");
try {
nNet = ModelSerializer.restoreMultiLayerNetwork(locationToSave);
logger.info("Success: Model opened");
} catch (IOException e) {
throw new Exception(String.format("Unable to open model from %s because of error %s", locationToSave.getAbsolutePath(),e.getMessage()));
}
logger.info("Loading test data");
SequenceRecordReader testFeatures = new CSVSequenceRecordReader(0, ","); //skip no lines at the top - i.e. no header
try {
testFeatures.initialize(new NumberedFileInputSplit(inputFileDir + "/features/s_4180%d.csv", 0, 4));
} catch (InterruptedException e) {
testFeatures.close();
throw new Exception(String.format("IO error %s. during testFeatures", e.getMessage()));
}
logger.info("Loading label data");
SequenceRecordReader testLabels = new CSVSequenceRecordReader();
try {
testLabels.initialize(new NumberedFileInputSplit(inputFileDir + "/labels/s_4180%d.csv", 0,4));
} catch (InterruptedException e) {
testLabels.close();
testFeatures.close();
throw new IOException(String.format("Interrupted exception error %s. during testLabels initialise", e.getMessage()));
}
//DataSetIterator inputData = new Seque
logger.info("creating iterator");
DataSetIterator testData = new SequenceRecordReaderDataSetIterator(testFeatures, testLabels,
this._modelDefinition.getBATCH_SIZE(),this._modelDefinition.getNUM_LABEL_CLASSES(), false, SequenceRecordReaderDataSetIterator.AlignmentMode.ALIGN_END);
//now use it to classify some data
logger.info("classifying examples");
INDArray output = nNet.output(testData);
logger.info("outputing the classifications");
if(output==null||output.isEmpty())
throw new Exception("There is no output");
System.out.println(output);
//sample output
// [[[ 0, 0, 0, 0, 0.9882, 0, 0, 0, 0],
// [ 0, 0, 0, 0, 0.0118, 0, 0, 0, 0]],
//
// [[ 0, 0.1443, 0, 0, 0, 0, 0, 0, 0],
// [ 0, 0.8557, 0, 0, 0, 0, 0, 0, 0]],
//
// [[ 0, 0, 0, 0, 0, 0, 0, 0, 0.9975],
// [ 0, 0, 0, 0, 0, 0, 0, 0, 0.0025]],
//
// [[ 0, 0, 0, 0, 0, 0, 0.8482, 0, 0],
// [ 0, 0, 0, 0, 0, 0, 0.1518, 0, 0]],
//
// [[ 0, 0, 0, 0.8760, 0, 0, 0, 0, 0],
// [ 0, 0, 0, 0.1240, 0, 0, 0, 0, 0]]]
}

Related

Image processing: pointer becomes nullptr without resetting it

I am working on a project which recovers an image line by line and has to recolor any objects that are inside the image. Our image is gathered in real time and we receive a 1D byte[] array on each call. Placing each 1D array on top of each other reconstructs the 2D image. This program has a buffer of 300 arrays which is large enough to display each object.
The data inside the array is a numeric value corresponding to a color. Objects often have several colors and this code has to recolor each object with the most present color.
Initially, this code was written in C#, but I had several performance issues so this program was adapted to a CLI/CLR project with C++ to have access to pointers which would hugely improve speed.
For each pixel in the array, I instanciate a Product class which contains data about the current pixel. Each Product class contains a pointer to a Info class containing data about the current object. The program looks at previous adjacent pixels and determines if the pixel belongs to the same object. If so, the Info pointer in the Product class of the current pixel will point to the Info class of the previous pixel. In this way, when counting each color of the whole object, I only have to update the most present color index in the Info class to update the color of each pixel, and thus recolor the whole object.
Here is the main code with the loop:
void ProductsClipping::ProcessClippingFrame(array<unsigned char>^% CurrentProcessingFrame) {
Monitor::Enter(obj);
try {
// Update Current Buffer Index
BufferIndex++;
if (BufferIndex >= BufferSize) BufferIndex = 0;
// Get Current Frame
CurrentProductFrame = ProductResult[BufferIndex];
// Update Result Buffer Index
ResultBufferIndex++;
if (ResultBufferIndex >= BufferSize) ResultBufferIndex = 0;
// Get Result Frame
ResultFrame = ProductResult[ResultBufferIndex];
// Process each pixel
for (int i = 0; i < PixelsCount; i++) {
Product^ LastProduct = LastProductFrame[i];
if (LastProduct != nullptr && LastProduct->ProductInfo != nullptr && LastProduct->ProductInfo->BufferIndex != BufferIndex) {
LastProduct->ProductInfo->Height++;
LastProduct->ProductInfo->BufferIndex = BufferIndex;
LastProduct->ProductInfo->isResetMax = true;
LastProduct->ProductInfo->isActive = false;
LastProduct->UpdateProductIndex();
}
// If product in this pixel
if (CurrentProcessingFrame[i] > 0) {
bool hasParent = false;
// If last pixel don't belong to this product
if (CurrentProductFrame[i] == nullptr) CurrentProductFrame[i] = gcnew Product;
Product^ CurrentProduct = CurrentProductFrame[i];
// Check if has a particle in above pixel
if (LastProduct != nullptr && LastProduct->ProductID > 0) {
CurrentProduct->Update_Info(LastProduct->ProductInfo, LastProduct->ProductID, false);
hasParent = true;
}
Product^ PreviousProduct = i > 0 ? CurrentProductFrame[i - 1] : nullptr;
// Check if is a particle in the left of the pixel
if (PreviousProduct != nullptr && PreviousProduct->ProductID > 0) {
// If has particle above and in the left of pixel and the two particle is not the same
if (hasParent) {
if (PreviousProduct->ProductID != CurrentProduct->ProductID) {
PreviousProduct->Update_Info(CurrentProduct->ProductInfo, CurrentProduct->ProductID, true);
}
} else {
CurrentProduct->Update_Info(PreviousProduct->ProductInfo, PreviousProduct->ProductID, false);
hasParent = true;
}
}
if (!hasParent) {
if (i + 1 < CurrentProcessingFrame->Length && CurrentProcessingFrame[i + 1] > 0) {
CurrentProductFrame[i + 1] = CurrentProduct;
// End of product
if (LastProduct != nullptr && LastProduct->IsEndOfProduct && i == LastProduct->ProductInfo->LastMax) {
LastProduct->Close();
}
continue;
} else {
CurrentProduct->ProductID = ProductID;
ProductID++;
}
}
// If first pixel of product. Initialize information data
if (CurrentProduct->ProductInfo == nullptr) {
CurrentProduct->Initialize_Info(gcnew Info());
CurrentProduct->ProductInfo->ID = CurrentProduct->ProductID;
CurrentProduct->ProductInfo->BufferIndex = BufferIndex;
}
CurrentProduct->ProductInfo->LastMax = (CurrentProduct->ProductInfo->isResetMax) ? i : Math::Max(i, CurrentProduct->ProductInfo->LastMax);
}
// If End of product
if (LastProduct != nullptr && LastProduct->IsEndOfProduct && i == LastProduct->ProductInfo->LastMax) LastProduct->Close();
ResultFrame[i] = nullptr;
}
LastProductFrame = CurrentProductFrame;
} finally { Monitor::Exit(obj); }
}
This is the code of the Product class with the Info pointer.
ref class Product {
private:
Info^ *_ProductInfo = nullptr;
public:
unsigned int ProductID;
property Info^ ProductInfo {
Info^ get() {
if (!_ProductInfo) return nullptr;
return *_ProductInfo;
}
}
property bool IsEndOfProduct {
bool get() { return ProductInfo != nullptr && ProductInfo->isOpen && !ProductInfo->isActive; }
}
void Update_Info(Info^ NewInfo, unsigned int NewProductID, bool isBelongOtherProduct) {
if (NewInfo != nullptr) NewInfo->isActive = true;
ProductID = NewProductID;
_ProductInfo = &NewInfo;
}
void Initialize_Info(Info^ NewInfo) {
_ProductInfo = &NewInfo;
}
void Close() {
ProductInfo->isOpen = false;
}
};
The issue I experience is that for the first pixel in the object, the pointer points correctly towards the Info class, but on the next iteration, when wanting to set the next pixel to the same Info class, the first pointer becomes nullptr
EDIT: Added test code calling the loop:
public partial class Form1 : Form
{
byte[][] Frame = new byte[][]
{
new byte[]{ 0, 0, 1, 0, 0, 0, 1, 0, 0, 0 },
new byte[]{ 0, 1, 1, 0, 0, 1, 1, 0, 0, 0 },
new byte[]{ 0, 1, 1, 1, 1, 1, 1, 1, 0, 0 },
new byte[]{ 0, 0, 1, 1, 1, 1, 0, 1, 0, 0 },
new byte[]{ 0, 0, 0, 1, 0, 1, 0, 1, 0, 0 },
new byte[]{ 0, 0, 1, 0, 0, 1, 1, 1, 0, 0 },
new byte[]{ 0, 0, 1, 1, 1, 1, 1, 0, 0, 0 },
new byte[]{ 0, 0, 0, 0, 0, 0, 1, 1, 0, 0 },
new byte[]{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
new byte[]{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
new byte[]{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
new byte[]{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
};
ProductsClipping ClippingFrame;
public Form1()
{
InitializeComponent();
int NbArrays = Frame.Length;
for (int i = 0; i < NbArrays; i++)
{
ClippingFrame.ProcessClippingFrame(ref Frame[i]);
}
}
}

Is there a way to overload a constructor with a 2D array (int)?

When I utilize the default constructor, I expect it to call the constructor that accepts an argument; however, this does not occur correctly. When debugging, as far as I can tell it is assigning the values and then the instance simply isn't maintained. I'm not sure if I need to create a helper method instead to pass the object, array, assign out values, and then pass back the object?
My goal is to have a default constructor that passes a hard-coded set of values and then a constructor that accepts the same type of array passed as values.
I've tried passing the array as an argument for the constructors, and while it seems to work for the derived class, it does not work for the base class. I ended up moving the functionality of the overloaded constructor to the default constructor and that works correctly.
This is the base class:
// Puzzle.h
class Puzzle
{
public:
Puzzle();
Puzzle(int grid[gridLength][gridLength]);
~Puzzle();
void Print_Puzzle(); // Displays puzzle in console
protected:
int grid[gridLength][gridLength]; // Our board
private:
};
This is the definition:
Puzzle::Puzzle()
{
int grid[gridLength][gridLength] = // Taken from https://www.puzzles.ca/sudoku_puzzles/sudoku_easy_505.html
{
{ 0, 7, 0, 0, 0, 2, 0, 0, 0 },
{ 0, 9, 0, 3, 7, 0, 0, 0, 0 },
{ 0, 0, 5, 0, 8, 0, 0, 0, 1 },
{ 0, 0, 4, 7, 0, 0, 0, 0, 9 },
{ 0, 0, 0, 0, 9, 6, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 8, 6, 5, 4 },
{ 0, 2, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 1, 0, 4, 3 },
{ 4, 0, 7, 9, 5, 0, 2, 6, 0 }
};
for (int x = 0; x < gridLength; x++)
{
for (int y = 0; y < gridLength; y++)
Puzzle::grid[x][y] = grid[x][y];
}
// Puzzle::Puzzle(grid) // Doesn't work. Not sure how to properly pass the array values.
}
Puzzle::Puzzle(int grid[gridLength][gridLength])
{
for (int row = 0; row < gridLength; row++)
{
for (int col = 0; col < gridLength; col++)
this->grid[row][col] = grid[row][col];
}
}
I expect the default constructor to pass the grid variable and the receiving constructor to assign those values to the instance's member property.
A more convenient way and no less efficient is to use std::array which can be copied, so that you do not have to copy it element-wise:
#include <array>
constexpr int gridLength = 9;
using Grid = std::array<std::array<int, gridLength>, gridLength>;
Grid const grid = {{ // Taken from https://www.puzzles.ca/sudoku_puzzles/sudoku_easy_505.html
{ 0, 7, 0, 0, 0, 2, 0, 0, 0 },
{ 0, 9, 0, 3, 7, 0, 0, 0, 0 },
{ 0, 0, 5, 0, 8, 0, 0, 0, 1 },
{ 0, 0, 4, 7, 0, 0, 0, 0, 9 },
{ 0, 0, 0, 0, 9, 6, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 8, 6, 5, 4 },
{ 0, 2, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 1, 0, 4, 3 },
{ 4, 0, 7, 9, 5, 0, 2, 6, 0 }
}};
class Puzzle {
Grid grid_;
public:
Puzzle(Grid const& grid)
: grid_(grid) // Copy grid into grid_.
{}
};
int main() {
Puzzle p(grid);
}
Alternatively:
class Puzzle {
Grid grid_;
static Grid make_grid() {
Grid grid;
// Your code to fill the grid.
return grid;
}
public:
Puzzle()
: Puzzle(make_grid())
{}
Puzzle(Grid const& grid)
: grid_(grid) // Copy the grid.
{}
};
In my opinion, you are committing a design error.
Never use C arrays in C++, use std::vector or std::array instead.
Try this.
class Sudoku
{
public:
Sudoku(const std::vector<std::vector<int>> initData = { {/* Write your default values here */} })
{
data = initData;
}
private:
std::vector<std::vector<int>> data;
};
if you want to use C-like arrays you will need to understand the only way to pass arrays is via pointers, and is a messy solution.
template <uint32_t width, uint32_t height>
class Sudoku
{
public:
Sudoku(int** initData, int maxX, int maxY)
{
for (int i = 0; i < maxX; i++) {
for (int j = 0; j < maxY; j++) {
data[i][j] = initData[i][j];
}
}
}
private:
std::array<width, std::array<height, int>> data;
};

How to create .swf file from multi .JPG images using swflib library in Visual C++?

I'm writing a c++ code to create a animate SWF file from multi JPG pictures.
Now, I have pictures like "image_0" to "image_100". I find a swflib library. I think it will help. So far, I can use this library's method to create .SWF file and the size of .SWF file is the sum of pictures in .JPG format.
So, I think I almost done. But ,SWF does not play. I am crazy.
Below this is the code which I modified:
`void CSWFLIBTestProjectDlg::CreateSWFMovie_Bitmap()
{
// Set movie params
SIZE_F movieSize = {100, 100};
int frameRate = 14;
POINT_F pt;
// Create empty .SWF file
CSWFMovie swfMovie;
swfMovie.OpenSWFFile(_T("SWF Sample Movies/Sample2.swf"), movieSize, frameRate);
SWF_RGB bgColor = {255, 255, 255};
swfMovie.SetBackgroundColor(bgColor);
// Define bitmap object
CSWFBitmap bitmap(2, (UCHAR*)"gif_0.jpg");//bm128
swfMovie.DefineObject(&bitmap, -1, true);
// Define custom shape
RECT_F shapeRect = {0, 0, 1000, 1000};
CSWFShape shape(1, shapeRect, 1);
SWF_RGBA lineColor = {0, 0, 0, 255};
shape.AddLineStyle(0, lineColor);
RECT_F bitmapRect = {0, 0, 1246, 622}; // size of the bitmap
RECT_F clipRect = {0, 0, 100, 100}; // where to fill
shape.AddBitmapFillStyle(bitmap.m_ID, SWF_FILLSTYLETYPE_BITMAP_0, bitmapRect, clipRect);
pt.x = 0;
pt.y = 0;
shape.ChangeStyle(1, 1, 0, &pt);
shape.AddLineSegment(100, 0);
shape.AddLineSegment(0, 100);
shape.AddLineSegment(-100, 0);
shape.AddLineSegment(0, -100);
swfMovie.DefineObject(&shape, shape.m_Depth, true);
swfMovie.ShowFrame();
/****************************************
* move
****************************************/
float i;
for (i=0; i<10; i++)
{
shape.Translate(i, 0);
swfMovie.UpdateObject(&shape, shape.m_Depth, NULL, -1);
swfMovie.ShowFrame();
//if (i>200)
//{
// swfMovie.RemoveObject(shape.m_Depth);
//}
}
/****************************************
* add jpg
****************************************/
swfMovie.RemoveObject(shape.m_Depth);
for (int i=1;i<=100;i++)
{
char filename[100];
sprintf(filename,"gif_%d%s",i,".jpg");
CSWFBitmap bitmap2(3, (UCHAR*)filename);//gif_0
swfMovie.DefineObject(&bitmap2, -1, true);//
// Define custom shape
RECT_F shapeRect2 = {0, 0, 1000, 1000};
CSWFShape shape2(1, shapeRect2, 1);
SWF_RGBA lineColor2 = {0, 0, 0, 255};
shape2.AddLineStyle(0, lineColor2);
RECT_F bitmapRect2 = {0, 0, 1246, 622}; // size of the bitmap
RECT_F clipRect2 = {0, 0, 100, 100}; // where to fill
shape2.AddBitmapFillStyle(bitmap2.m_ID, SWF_FILLSTYLETYPE_BITMAP_0, bitmapRect2, clipRect2);
pt.x = 0;
pt.y = 0;
shape2.ChangeStyle(1, 1, 0, &pt);
shape2.AddLineSegment(100, 0);
shape2.AddLineSegment(0, 100);
shape2.AddLineSegment(-100, 0);
shape2.AddLineSegment(0, -100);
swfMovie.UpdateObject(&shape2, shape2.m_Depth, NULL, -1);
//swfMovie.DefineObject(&shape2, shape2.m_Depth, true);
swfMovie.ShowFrame();
//swfMovie.RemoveObject(shape2.m_Depth);
}
// Close .SWF file
swfMovie.CloseSWFFile();
}`
can you tell me what's wrong with my code ? Thanks in advance.
I have found a way to create a .SWF file from a set of image using C++,and a swflib library.you can download it from the lib file website .in which there is a method named :CreateSWFMovie_Bitmap() here is the code i modified
void CSWFLIBTestProjectDlg::CreateSWFMovie_Bitmap()
{
SIZE_F movieSize = {4000, 4000};
int frameRate = 40;
POINT_F pt;
CSWFMovie swfMovie;
swfMovie.OpenSWFFile(_T("SWF Sample Movies/Sample2.swf"), movieSize, frameRate);
SWF_RGB bgColor = {255, 255, 255};
swfMovie.SetBackgroundColor(bgColor);
CSWFBitmap bitmap(2, (UCHAR*)"bm128.jpg");
swfMovie.DefineObject(&bitmap, -1, false);
RECT_F shapeRect = {0, 0, 1000, 1000};//shape大小
CSWFShape shape(1, shapeRect, 1);
SWF_RGBA lineColor = {0, 0, 0, 255};
shape.AddLineStyle(3, lineColor);
RECT_F bitmapRect = {0, 0, 128, 128}; // size of the bitmap
RECT_F clipRect = {0, 0, 100, 100}; // where to fill
shape.AddBitmapFillStyle(bitmap.m_ID, SWF_FILLSTYLETYPE_BITMAP_0, bitmapRect, clipRect);
pt.x = 0;
pt.y = 0;
shape.ChangeStyle(1, 1, 0, &pt);
shape.AddLineSegment(100, 0);
shape.AddLineSegment(0, 100);
shape.AddLineSegment(-100, 0);
shape.AddLineSegment(0, -100);
swfMovie.DefineObject(&shape, shape.m_Depth, true);
swfMovie.ShowFrame();
for (int i=0; i<100; i++)
{
char filename[50]="";
sprintf(filename,"gif_%d%s",i,".jpg");
CSWFBitmap bitmap2(300+i, (UCHAR*)filename);
swfMovie.DefineObject(&bitmap2, -1, false);//false
CSWFShape shape2(7+i,shapeRect,2+i);//depth值也不能一样 id不能重复
shape2.AddLineStyle(3, lineColor);
RECT_F bitmapRect2 = {0, 0, 128, 128};
RECT_F clipRect2 = {0, 0, 100, 100};
shape2.AddBitmapFillStyle(bitmap2.m_ID, SWF_FILLSTYLETYPE_BITMAP_0, bitmapRect2, clipRect2);
pt.x = 0;
pt.y = 0;
shape2.ChangeStyle(1, 1, 0, &pt);
shape2.AddLineSegment(1000, 0);
shape2.AddLineSegment(0, 1000);
shape2.AddLineSegment(-1000, 0);
shape2.AddLineSegment(0, -1000);
shape2.Translate(80, 0);
swfMovie.DefineObject(&shape2, shape2.m_Depth, true);//必须define才能动 可以不update
swfMovie.ShowFrame();
}
}

Comparison of floating point arrays using google test and google mock

I am new to Google's test products and trying them out with some signal processing code. I am trying to assert that to floating point arrays are equal to within some bounds, using google mock as suggested by the answer to this question. I would like to know the recommended method for adding some error tolerance to an expression like the following . . .
EXPECT_THAT( impulse, testing::ElementsAreArray( std::vector<float>({
0, 0, 0, 1, 1, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0
}) ) );
I want the test to pass if the element-wise values in the arrays are within 10-8 of one another.
The following works for me:
using ::testing::Pointwise;
using ::testing::FloatNear;
auto const max_abs_error = 1 / 1024.f;
ASSERT_THAT(
test,
Pointwise(FloatNear(max_abs_error), ref));
Where test and ref are of type std::vector<float>.
One approach is to use the googletest rather than googlemock macros, which results in a more compact assert:
#define EXPECT_FLOATS_NEARLY_EQ(expected, actual, thresh) \
EXPECT_EQ(expected.size(), actual.size()) << "Array sizes differ.";\
for (size_t idx = 0; idx < std::min(expected.size(), actual.size()); ++idx) \
{ \
EXPECT_NEAR(expected[idx], actual[idx], thresh) << "at index: " << idx;\
}
// define expected_array as in the other answer
EXPECT_FLOATS_NEARLY_EQ(impulse, expected_array, 0.001);
Here is one method. First define a matcher outside of the test scope. According to the documentation, the matcher cannot be defined in a class or function . .
MATCHER_P(FloatNearPointwise, tol, "Out of range") {
return (std::get<0>(arg)>std::get<1>(arg)-tol && std::get<0>(arg)<std::get<1>(arg)+tol) ;
}
Then is can be used with Pointwise int the test . . .
std::vector<float> expected_array({
0, 0, 0, 1, 1, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0
});
EXPECT_THAT( impulse, Pointwise( FloatNearPointwise(1e-8), expected_array ) );
But it would be neater if there was a solution that used the builtin FloatNear directly.

Creating an empty .zip file in C++

I am using a code snippet from this page on how to create a zip file and add and a compress a directory to that zip file. I am running the following on Windows 7 but it does not seem to create the zip file at all.
BSTR bstrFolderOutName = L"C:\\Test\\Archive.zip";
BYTE startBuffer[] = {80, 75, 5, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
FILE *f = _wfopen(bstrFolderOutName, L"wb");
fwrite(startBuffer,sizeof(startBuffer),1,f);
fclose(f);
The stated problem, that no file is created, is impossible to answer with the information given. It is most likely due to an invalid file path. However, the OP states in a comment that the path in his example is not the real code.
EDIT: the hex string example that I cited originally was wrong, I just tested.
This code works:
#include <stdio.h>
auto main() -> int
{
FILE* f = fopen("foo.zip", "wb");
//fwrite( "\x80\x75\x05\x06\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", 22, 1, f );
fwrite( "\x50\x4B\x05\x06\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", 22, 1, f );
fclose(f);
}
Harumph, one cannot even trust Stack Overflow comments. Not to mention accepted answers.
Original text:
Assuming that the OP now has edited the code so that the part below is the real code, then this constant
{80, 75, 5, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
is not identical to
"\x80\x75\x05\x06\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
Can the OP spot the relevant difference?
Further, given that, can the OP infer anything about his source of information?
My example from a comment elsewhere.