Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add ISOP expression printing to print.hpp #135

Merged
merged 1 commit into from
Mar 27, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
89 changes: 89 additions & 0 deletions include/kitty/print.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
\brief Implements functions to print truth tables
\author Mathias Soeken
\author Rassul Bairamkulov
*/

#pragma once
Expand All @@ -45,6 +46,7 @@
#include "karnaugh_map.hpp"
#include "operations.hpp"
#include "constructors.hpp"
#include "isop.hpp"

namespace kitty
{
Expand Down Expand Up @@ -478,4 +480,91 @@ std::string anf_to_expression( const ternary_truth_table<TT>& anf )
return anf_to_expression( anf._bits );
}

/*! \brief Creates an expression in the sum of products format.
Does not perform any optimizations. Useful when constructing GENLIB-compatible expressions
\param tt Truth table
\param os Output stream
*/
template<typename TT, typename = std::enable_if_t<is_completely_specified_truth_table<TT>::value>>
void print_sop_expression( TT tt, std::ostream& os = std::cout )
{
/* compare to constants */
if ( is_const0( tt ) )
{
os << "CONST0";
return;
}
else if ( is_const0( ~tt ) )
{
os << "CONST1";
return;
}

/* extract product terms */
auto cubes = kitty::isop( tt );

bool first_cube = true; // Controls insertion of '|'. It's false for the first cube to avoid leading '|'.

/* write product terms */
for ( auto cube : cubes )
{
auto bits = cube._bits;
auto mask = cube._mask;

bool brackets = __builtin_popcount( mask ) > 1;

if ( !first_cube )
{
os << '|';
}

if ( brackets )
{
os << '(';
}

bool first_literal = true;
for ( auto i = 0u; i < tt.num_vars(); ++i )
{
if ( mask & 1 )
{
if ( !first_literal )
{
os << '&';
}
if ( !( bits & 1 ) )
{
os << '!';
}
os << static_cast<char>( 'a' + i );
first_literal = false;
}
bits >>= 1;
mask >>= 1;
}

if ( brackets )
{
os << ')';
}
first_cube = false;
}
}

/*! \brief Creates an expression in the sum of products format.
Does not perform any optimizations. Useful when constructing GENLIB-compatible expressions
\param tt Truth table
*/
template<typename TT, typename = std::enable_if_t<is_completely_specified_truth_table<TT>::value>>
std::string to_sop_expression( TT tt )
{
std::stringstream os;
print_sop_expression( tt, os ); // Use the function to write into the stringstream
return os.str(); // Convert the stringstream to string and return it
}

} /* namespace kitty */