Skip to content

Commit

Permalink
Add ISOP expression printing to print.hpp
Browse files Browse the repository at this point in the history
SOP expressions are useful when constructing the GENLIB library for technology mapping
  • Loading branch information
brainkz committed Mar 26, 2024
1 parent 1b2f49f commit f3415ce
Showing 1 changed file with 89 additions and 0 deletions.
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 */

0 comments on commit f3415ce

Please sign in to comment.