<commit_before>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkVolumeProVG500Mapper.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

Copyright (c) 1993-1998 Ken Martin, Will Schroeder, Bill Lorensen.

This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.

The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.

IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.  THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.

=========================================================================*/

#include <math.h>
#include "vtkVolumeProVG500Mapper.h"
#include "vtkOpenGLVolumeProVG500Mapper.h"
#include "vtkRenderWindow.h"
#include "vtkObjectFactory.h"

vtkVolumeProVG500Mapper *vtkVolumeProVG500Mapper::New()
{
  // First try to create the object from the vtkObjectFactory
  vtkObject* ret = vtkObjectFactory::CreateInstance("vtkVolumeProVG500Mapper");
  if(ret)
    {
    return (vtkVolumeProVG500Mapper*)ret;
    }
  // If the factory was unable to create the object, then create it here.
  char *temp = vtkRenderWindow::GetRenderLibrary();

#ifdef VTK_USE_OGLR
  if (!strcmp("OpenGL",temp))
    {
    return vtkOpenGLVolumeProVG500Mapper::New();
    }
#endif
#ifdef _WIN32
  if (!strcmp("Win32OpenGL",temp))
    {
    return vtkOpenGLVolumeProVG500Mapper::New();
    }
#endif

  vtkGenericWarningMacro( << "This mapper is only supported under OpenGL" );
  return new vtkVolumeProVG500Mapper;
}

<commit_msg>minor change<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkVolumeProVG500Mapper.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

Copyright (c) 1993-1998 Ken Martin, Will Schroeder, Bill Lorensen.

This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.

The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.

IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.  THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.

=========================================================================*/

#include <math.h>
#include "vtkVolumeProVG500Mapper.h"
#include "vtkOpenGLVolumeProVG500Mapper.h"
#include "vtkRenderWindow.h"
#include "vtkObjectFactory.h"
#include "vtkGraphicsFactory.h"

vtkVolumeProVG500Mapper *vtkVolumeProVG500Mapper::New()
{
  // First try to create the object from the vtkObjectFactory
  vtkObject* ret = vtkObjectFactory::CreateInstance("vtkVolumeProVG500Mapper");
  if(ret)
    {
    return (vtkVolumeProVG500Mapper*)ret;
    }
  // If the factory was unable to create the object, then create it here.
  const char *temp = vtkGraphicsFactory::GetRenderLibrary();

#ifdef VTK_USE_OGLR
  if (!strcmp("OpenGL",temp))
    {
    return vtkOpenGLVolumeProVG500Mapper::New();
    }
#endif
#ifdef _WIN32
  if (!strcmp("Win32OpenGL",temp))
    {
    return vtkOpenGLVolumeProVG500Mapper::New();
    }
#endif

  vtkGenericWarningMacro( << "This mapper is only supported under OpenGL" );
  return new vtkVolumeProVG500Mapper;
}

<|endoftext|>


<commit_before><commit_msg>Context menu on RMB-down, not up, on Linux.<commit_after><|endoftext|>


<commit_before>#include <itkAffineTransform.h>
#include <itkTransformFileWriter.h>
#include <itkImageFileReader.h>
#include <string>
#include <itkPoint.h>
#include <itkVector.h>
#include "transforms.h"
#include <sstream>

void GetImageCenter( itk::Image<unsigned short, 3>::Pointer image,
                     itk::Image<unsigned short, 3>::PointType & center
                     )
{
  typedef itk::Image<unsigned short, 3> ImageType;
  // Get lower corner position
  ImageType::PointType origin;
  origin = image->GetOrigin();
  // Get higher corner position
  ImageType::SizeType size;
  size = image->GetLargestPossibleRegion().GetSize();
  ImageType::IndexType index;
  for( int i = 0; i < 3; i++ )
    {
    index[i] = size[i] - 1;
    }
  ImageType::PointType corner;
  image->TransformIndexToPhysicalPoint( index, corner );
  // Compute image center position
  for( int i = 0; i < 3; i++ )
    {
    center[i] = ( corner[i] + origin[i] ) / 2.0;
    }
}

template <class Precision>
int ComputeTransform(  const std::string doffile,
                       std::string sourceFileName,
                       const std::string targetFileName,
                       const std::string outputFileName,
                       bool rview_old
                       )
{
  typedef itk::Image<unsigned short, 3>   ImageType;
  typedef itk::ImageFileReader<ImageType> ImageReaderType;
  ImageReaderType::Pointer reader = ImageReaderType::New();
  reader->SetFileName( targetFileName.c_str() );
  reader->UpdateOutputInformation();
  // Get the target image information to set the center of transform
  // to the center of the target image
  ImageType::SpacingType spacing = reader->GetOutput()->GetSpacing();
  ImageType::SizeType    size = reader->GetOutput()->GetLargestPossibleRegion().GetSize();
  ImageType::PointType   origin = reader->GetOutput()->GetOrigin();

  typedef itk::AffineTransform<Precision, 3> AffineTransformType;
// After ITK_VERSION 4.5 (Acutally after June 20th, 2013) the ITK Transform
// classes are now templated.  This requires forward declarations to be defined
// differently.
#if ( ( ITK_VERSION_MAJOR == 4 ) && ( ITK_VERSION_MINOR < 5 ) )
  //This is trying to use the double presion writer to write
  //a single precision transform.  This is not a robust operation
  //and was not guaranteed to work in ITK v4.4 and less with
  //all transform writer types.  I think that the .txt writer
  //would have worked, but .mat and .hdf5 should have thrown
  //an exception.
  typedef itk::TransformFileWriter           TransformWriterType;
  typedef itk::TransformFileWriter::Pointer  TransformWriterTypePointer;
#else
  // As of ITKv4.5 there are both double and single precision transform writers.
  typedef          itk::TransformFileWriterTemplate<Precision>          TransformWriterType;
  typedef typename itk::TransformFileWriterTemplate<Precision>::Pointer TransformWriterTypePointer;
#endif
  TransformWriterTypePointer twriter = TransformWriterType::New();
  typename AffineTransformType::Pointer aff;
  // Handle the old version of rview (the one where the dof files were in ASCII)
  if( rview_old )
    {
    RViewTransform<Precision> dof = readDOFFile<Precision>( doffile );
    aff = createITKAffine( dof,
                           size,
                           spacing,
                           origin
                           );
    }
  // Handle the new version of rview (where the dof files are binary
  // files and have to be converted into txt files with dof2mat)
  else
    {
    newRViewTransform<Precision> dof = readDOF2MATFile<Precision>( doffile );
    aff = createnewITKAffine( dof,
                              size,
                              spacing,
                              origin
                              );
    }
  // If the source image is given, add a translation that moves
  // the center of the target image to the center of the source image
  if( sourceFileName.compare( "" ) )
    {
    ImageReaderType::Pointer sourceReader = ImageReaderType::New();
    sourceReader->SetFileName( sourceFileName.c_str() );
    sourceReader->UpdateOutputInformation();
    ImageType::PointType targetCenter;
    GetImageCenter( reader->GetOutput(), targetCenter );
    ImageType::PointType sourceCenter;
    GetImageCenter( sourceReader->GetOutput(), sourceCenter );
    itk::Vector<Precision, 3> translation;
    translation = sourceCenter - targetCenter;
    translation += aff->GetTranslation();
    aff->SetTranslation( translation );
    }
  twriter->AddTransform( aff );
  twriter->SetFileName( outputFileName );
  try
    {
    twriter->Update();
    }
  catch( ... )
    {
    return EXIT_FAILURE;
    }
  return EXIT_SUCCESS;
}

int main(int argc, char* argv[])
{
  typedef float  Precision;
  typedef double doublePrecision;
  std::string sourceFileName;
  // Check if source is specified
  bool sourceSet = false;
  int  numberOfArgs = argc;
  int  outFilePos = 3;
  if( argc >= 6 && !strcmp( argv[3], "-s") )
    {
    sourceSet = true;
    numberOfArgs -= 2;
    sourceFileName.assign( argv[4] );
    outFilePos = 5;
    }
  // check if old or new rview
  bool rview_old = true;
  int  transformTypePos = outFilePos;
  if( argc > outFilePos + 1 )
    {
    std::istringstream inputType;
    inputType.str( argv[outFilePos + 1] );
    inputType >> rview_old;
    if( inputType.fail() )
      {
      transformTypePos = outFilePos + 1;
      }
    else
      {
      numberOfArgs--;
      transformTypePos = outFilePos + 2;
      }
    }
  // Check if float or double
  bool doubleSet = false;
  if( argc > transformTypePos && !strcmp( argv[transformTypePos], "-d" ) )
    {
    doubleSet = true;
    numberOfArgs--;
    }

  if( numberOfArgs != 4 )
    {
    std::cerr << "Usage: " << argv[0]
              <<
    " doffile targetimagefile [-s sourceImageFileName] outputfile [inputtype] [-d (outputTransform as doubles instead of floats) ]"
              << std::endl;
    std::cerr << "with inputtype = " << std::endl;
    std::cerr << "0: new rview (output txt file of dof2mat)" << std::endl; // this was inverted
    std::cerr << "1: old rview" << std::endl;
    return EXIT_FAILURE;
    }

  const std::string doffile( argv[1] );
  const std::string targetFileName( argv[2] );
  const std::string outputFileName( argv[outFilePos] );

  if( doubleSet )
    {
    return ComputeTransform<doublePrecision>( doffile,
                                              sourceFileName,
                                              targetFileName,
                                              outputFileName,
                                              rview_old
                                              );
    }
  else
    {
    return ComputeTransform<Precision>( doffile,
                                        sourceFileName,
                                        targetFileName,
                                        outputFileName,
                                        rview_old
                                        );
    }
}
<commit_msg>COMP: Fix -Wunused-but-set-variable warning in Applications/tio.cxx<commit_after>#include <itkAffineTransform.h>
#include <itkTransformFileWriter.h>
#include <itkImageFileReader.h>
#include <string>
#include <itkPoint.h>
#include <itkVector.h>
#include "transforms.h"
#include <sstream>

void GetImageCenter( itk::Image<unsigned short, 3>::Pointer image,
                     itk::Image<unsigned short, 3>::PointType & center
                     )
{
  typedef itk::Image<unsigned short, 3> ImageType;
  // Get lower corner position
  ImageType::PointType origin;
  origin = image->GetOrigin();
  // Get higher corner position
  ImageType::SizeType size;
  size = image->GetLargestPossibleRegion().GetSize();
  ImageType::IndexType index;
  for( int i = 0; i < 3; i++ )
    {
    index[i] = size[i] - 1;
    }
  ImageType::PointType corner;
  image->TransformIndexToPhysicalPoint( index, corner );
  // Compute image center position
  for( int i = 0; i < 3; i++ )
    {
    center[i] = ( corner[i] + origin[i] ) / 2.0;
    }
}

template <class Precision>
int ComputeTransform(  const std::string doffile,
                       std::string sourceFileName,
                       const std::string targetFileName,
                       const std::string outputFileName,
                       bool rview_old
                       )
{
  typedef itk::Image<unsigned short, 3>   ImageType;
  typedef itk::ImageFileReader<ImageType> ImageReaderType;
  ImageReaderType::Pointer reader = ImageReaderType::New();
  reader->SetFileName( targetFileName.c_str() );
  reader->UpdateOutputInformation();
  // Get the target image information to set the center of transform
  // to the center of the target image
  ImageType::SpacingType spacing = reader->GetOutput()->GetSpacing();
  ImageType::SizeType    size = reader->GetOutput()->GetLargestPossibleRegion().GetSize();
  ImageType::PointType   origin = reader->GetOutput()->GetOrigin();

  typedef itk::AffineTransform<Precision, 3> AffineTransformType;
// After ITK_VERSION 4.5 (Acutally after June 20th, 2013) the ITK Transform
// classes are now templated.  This requires forward declarations to be defined
// differently.
#if ( ( ITK_VERSION_MAJOR == 4 ) && ( ITK_VERSION_MINOR < 5 ) )
  //This is trying to use the double presion writer to write
  //a single precision transform.  This is not a robust operation
  //and was not guaranteed to work in ITK v4.4 and less with
  //all transform writer types.  I think that the .txt writer
  //would have worked, but .mat and .hdf5 should have thrown
  //an exception.
  typedef itk::TransformFileWriter           TransformWriterType;
  typedef itk::TransformFileWriter::Pointer  TransformWriterTypePointer;
#else
  // As of ITKv4.5 there are both double and single precision transform writers.
  typedef          itk::TransformFileWriterTemplate<Precision>          TransformWriterType;
  typedef typename itk::TransformFileWriterTemplate<Precision>::Pointer TransformWriterTypePointer;
#endif
  TransformWriterTypePointer twriter = TransformWriterType::New();
  typename AffineTransformType::Pointer aff;
  // Handle the old version of rview (the one where the dof files were in ASCII)
  if( rview_old )
    {
    RViewTransform<Precision> dof = readDOFFile<Precision>( doffile );
    aff = createITKAffine( dof,
                           size,
                           spacing,
                           origin
                           );
    }
  // Handle the new version of rview (where the dof files are binary
  // files and have to be converted into txt files with dof2mat)
  else
    {
    newRViewTransform<Precision> dof = readDOF2MATFile<Precision>( doffile );
    aff = createnewITKAffine( dof,
                              size,
                              spacing,
                              origin
                              );
    }
  // If the source image is given, add a translation that moves
  // the center of the target image to the center of the source image
  if( sourceFileName.compare( "" ) )
    {
    ImageReaderType::Pointer sourceReader = ImageReaderType::New();
    sourceReader->SetFileName( sourceFileName.c_str() );
    sourceReader->UpdateOutputInformation();
    ImageType::PointType targetCenter;
    GetImageCenter( reader->GetOutput(), targetCenter );
    ImageType::PointType sourceCenter;
    GetImageCenter( sourceReader->GetOutput(), sourceCenter );
    itk::Vector<Precision, 3> translation;
    translation = sourceCenter - targetCenter;
    translation += aff->GetTranslation();
    aff->SetTranslation( translation );
    }
  twriter->AddTransform( aff );
  twriter->SetFileName( outputFileName );
  try
    {
    twriter->Update();
    }
  catch( ... )
    {
    return EXIT_FAILURE;
    }
  return EXIT_SUCCESS;
}

int main(int argc, char* argv[])
{
  typedef float  Precision;
  typedef double doublePrecision;
  std::string sourceFileName;
  // Check if source is specified
  int  numberOfArgs = argc;
  int  outFilePos = 3;
  if( argc >= 6 && !strcmp( argv[3], "-s") )
    {
    numberOfArgs -= 2;
    sourceFileName.assign( argv[4] );
    outFilePos = 5;
    }
  // check if old or new rview
  bool rview_old = true;
  int  transformTypePos = outFilePos;
  if( argc > outFilePos + 1 )
    {
    std::istringstream inputType;
    inputType.str( argv[outFilePos + 1] );
    inputType >> rview_old;
    if( inputType.fail() )
      {
      transformTypePos = outFilePos + 1;
      }
    else
      {
      numberOfArgs--;
      transformTypePos = outFilePos + 2;
      }
    }
  // Check if float or double
  bool doubleSet = false;
  if( argc > transformTypePos && !strcmp( argv[transformTypePos], "-d" ) )
    {
    doubleSet = true;
    numberOfArgs--;
    }

  if( numberOfArgs != 4 )
    {
    std::cerr << "Usage: " << argv[0]
              <<
    " doffile targetimagefile [-s sourceImageFileName] outputfile [inputtype] [-d (outputTransform as doubles instead of floats) ]"
              << std::endl;
    std::cerr << "with inputtype = " << std::endl;
    std::cerr << "0: new rview (output txt file of dof2mat)" << std::endl; // this was inverted
    std::cerr << "1: old rview" << std::endl;
    return EXIT_FAILURE;
    }

  const std::string doffile( argv[1] );
  const std::string targetFileName( argv[2] );
  const std::string outputFileName( argv[outFilePos] );

  if( doubleSet )
    {
    return ComputeTransform<doublePrecision>( doffile,
                                              sourceFileName,
                                              targetFileName,
                                              outputFileName,
                                              rview_old
                                              );
    }
  else
    {
    return ComputeTransform<Precision>( doffile,
                                        sourceFileName,
                                        targetFileName,
                                        outputFileName,
                                        rview_old
                                        );
    }
}
<|endoftext|>


<commit_before>#include "AssetCache.h"
#include "AssetAPI.h"
#include "IAsset.h"
#include "LoggingFunctions.h"

#include <QFileInfo>
#include <boost/filesystem.hpp>

DEFINE_POCO_LOGGING_FUNCTIONS("AssetCache")

QString SanitateAssetRefForCache(QString assetRef)
{
    assetRef.replace("/", "_");
    assetRef.replace("\\", "_");
    assetRef.replace(":", "_");
    assetRef.replace("*", "_");
    assetRef.replace("?", "_");
    assetRef.replace("\"", "_");
    assetRef.replace("'", "_");
    assetRef.replace("<", "_");
    assetRef.replace(">", "_");
    assetRef.replace("|", "_");
    return assetRef;
}

AssetCache::AssetCache(QString assetCacheDirectory)
:cacheDirectory(GuaranteeTrailingSlash(assetCacheDirectory))
{
    LogInfo("Using AssetCache in directory \"" + assetCacheDirectory.toStdString() + "\".");
}

QString AssetCache::FindAsset(QString assetRef)
{
    QString fileSource = cacheDirectory + SanitateAssetRefForCache(assetRef);
    if (QFile::exists(fileSource))
        return fileSource;
    else
        return "";
}

QString AssetCache::FindAssetByContentHash(QString contentHash)
{
    ///\todo Implement.
    return "";
}

void AssetCache::DeleteAsset(QString assetRef)
{
    QString fileSource = cacheDirectory + SanitateAssetRefForCache(assetRef);
    boost::filesystem::remove(fileSource.toStdString());
}

void AssetCache::ClearAssetCache()
{
    ///\todo Implement.
}

QString AssetCache::StoreAsset(const u8 *data, size_t numBytes, QString assetName, QString assetContentHash)
{
    QString filename = cacheDirectory + SanitateAssetRefForCache(assetName);

    bool success = SaveAssetFromMemoryToFile(data, numBytes, filename.toStdString().c_str());
    if (success)
    {
        LogDebug("Saved asset \"" + assetName.toStdString() + "\" to cache into file \"" + filename.toStdString() + "\"");
        return filename;
    }
    else
        return "";
}

void AssetCache::StoreAsset(AssetPtr asset)
{
    std::vector<u8> data;
    asset->SerializeTo(data);
    StoreAsset(&data[0], data.size(), asset->Name(), asset->ContentHash()); ///\todo Content hash can mismatch here.
}
<commit_msg>Remove the saved to cache print all together, its bleeding to the console in release mode. Very annoying and seems that the cache is working well so no need to print this out imo. Add back locally if you are debugging cache stuff.<commit_after>#include "AssetCache.h"
#include "AssetAPI.h"
#include "IAsset.h"
#include "LoggingFunctions.h"

#include <QFileInfo>
#include <boost/filesystem.hpp>

DEFINE_POCO_LOGGING_FUNCTIONS("AssetCache")

QString SanitateAssetRefForCache(QString assetRef)
{
    assetRef.replace("/", "_");
    assetRef.replace("\\", "_");
    assetRef.replace(":", "_");
    assetRef.replace("*", "_");
    assetRef.replace("?", "_");
    assetRef.replace("\"", "_");
    assetRef.replace("'", "_");
    assetRef.replace("<", "_");
    assetRef.replace(">", "_");
    assetRef.replace("|", "_");
    return assetRef;
}

AssetCache::AssetCache(QString assetCacheDirectory)
:cacheDirectory(GuaranteeTrailingSlash(assetCacheDirectory))
{
    LogInfo("Using AssetCache in directory \"" + assetCacheDirectory.toStdString() + "\".");
}

QString AssetCache::FindAsset(QString assetRef)
{
    QString fileSource = cacheDirectory + SanitateAssetRefForCache(assetRef);
    if (QFile::exists(fileSource))
        return fileSource;
    else
        return "";
}

QString AssetCache::FindAssetByContentHash(QString contentHash)
{
    ///\todo Implement.
    return "";
}

void AssetCache::DeleteAsset(QString assetRef)
{
    QString fileSource = cacheDirectory + SanitateAssetRefForCache(assetRef);
    boost::filesystem::remove(fileSource.toStdString());
}

void AssetCache::ClearAssetCache()
{
    ///\todo Implement.
}

QString AssetCache::StoreAsset(const u8 *data, size_t numBytes, QString assetName, QString assetContentHash)
{
    QString filename = cacheDirectory + SanitateAssetRefForCache(assetName);

    bool success = SaveAssetFromMemoryToFile(data, numBytes, filename.toStdString().c_str());
    if (success)
    {
        //LogDebug("Saved asset \"" + assetName.toStdString() + "\" to cache into file \"" + filename.toStdString() + "\"");
        return filename;
    }
    else
        return "";
}

void AssetCache::StoreAsset(AssetPtr asset)
{
    std::vector<u8> data;
    asset->SerializeTo(data);
    StoreAsset(&data[0], data.size(), asset->Name(), asset->ContentHash()); ///\todo Content hash can mismatch here.
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 1999-2009 Stephen Williams (steve@icarus.com)
 *
 *    This source code is free software; you can redistribute it
 *    and/or modify it in source code form under the terms of the GNU
 *    General Public License as published by the Free Software
 *    Foundation; either version 2 of the License, or (at your option)
 *    any later version.
 *
 *    This program 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 this program; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
 */

# include "config.h"

/*
 * This functor scans the design looking for dangling objects and
 * excess local signals. These deletions are not necessarily required
 * for proper functioning of anything, but they can clean up the
 * appearance of design files that are generated.
 */
# include  "functor.h"
# include  "netlist.h"
# include  "compiler.h"

class nodangle_f  : public functor_t {
    public:
      void event(Design*des, NetEvent*ev);
      void signal(Design*des, NetNet*sig);

      unsigned iteration;
      unsigned stotal, etotal;
      bool scontinue, econtinue;
      bool scomplete, ecomplete;
};

void nodangle_f::event(Design*des, NetEvent*ev)
{
      if (ecomplete) return;

	/* If there are no references to this event, then go right
	   ahead and delete it. There is no use looking further at
	   it. */
      if ((ev->nwait() + ev->ntrig() + ev->nexpr()) == 0) {
	    delete ev;
	    etotal += 1;
	    return;
      }

      if (iteration == 0) {
              /* Try to remove duplicate probes from the event. This
                 is done as a separate initial pass to ensure similar
                 events are detected as soon as possible in subsequent
                 iterations. */
            for (unsigned idx = 0 ;  idx < ev->nprobe() ;  idx += 1) {
                  unsigned jdx = idx + 1;
                  while (jdx < ev->nprobe()) {
                        NetEvProbe*ip = ev->probe(idx);
                        NetEvProbe*jp = ev->probe(jdx);

                        if (ip->edge() != jp->edge()) {
                              jdx += 1;
                              continue;
                        }

                        bool fully_connected = true;
                        for (unsigned jpin = 0; jpin < jp->pin_count(); jpin += 1) {
                              unsigned ipin = 0;
                              bool connected_flag = false;
                              for (ipin = 0 ; ipin < ip->pin_count(); ipin += 1)
                                    if (connected(ip->pin(ipin), jp->pin(jpin))) {
                                          connected_flag = true;
                                          break;
                                    }

                              if (!connected_flag) {
                                    fully_connected = false;
                                    break;
                              }
                        }

                        if (fully_connected) {
                              delete jp;
                        } else {
                              jdx += 1;
                        }
                  }
            }
            econtinue = true;
      } else {
              /* Postpone examining events in an automatic scope until the
                 third (optional) pass. This will mean similar events are
                 biased towards being stored in static scopes. */
            if (ev->scope()->is_auto()) {
                  if (iteration == 1) {
                        econtinue = true;
                        return;
                  }
            } else {
                  if (iteration == 2) {
                        return;
                  }
            }

              /* Try to find all the events that are similar to me, and
                 replace their references with references to me. */
            list<NetEvent*> match;
            ev->find_similar_event(match);
            for (list<NetEvent*>::iterator idx = match.begin()
                       ; idx != match.end() ;  idx ++) {

                  NetEvent*tmp = *idx;
                  assert(tmp != ev);
                  tmp ->replace_event(ev);
            }
      }
}

void nodangle_f::signal(Design*des, NetNet*sig)
{
      if (scomplete) return;

	/* Cannot delete signals referenced in an expression
	   or an l-value. */
      if (sig->get_refs() > 0)
	    return;

	/* Cannot delete the ports of tasks or functions. There are
	   too many places where they are referenced. */
      if ((sig->port_type() != NetNet::NOT_A_PORT)
	  && (sig->scope()->type() == NetScope::TASK))
	    return;

      if ((sig->port_type() != NetNet::NOT_A_PORT)
	  && (sig->scope()->type() == NetScope::FUNC))
	    return;

	/* Can't delete ports of cells. */
      if ((sig->port_type() != NetNet::NOT_A_PORT)
	  && (sig->scope()->attribute(perm_string::literal("ivl_synthesis_cell")) != verinum()))
	    return;

	/* Check to see if the signal is completely unconnected. If
	   all the bits are unlinked, then delete it. */
      if (! sig->is_linked()) {
	    delete sig;
	    stotal += 1;
	    return;
      }

	/* The remaining things can only be done to synthesized
	   signals, not ones that appear in the original Verilog. */
      if (! sig->local_flag())
	    return;

	/* Check to see if there is some significant signal connected
	   to every pin of this signal. */
      unsigned significant_flags = 0;
      for (unsigned idx = 0 ;  idx < sig->pin_count() ;  idx += 1) {
	    Nexus*nex = sig->pin(idx).nexus();

	    for (Link*cur = nex->first_nlink()
		       ; cur ;  cur = cur->next_nlink()) {

		  if (cur == &sig->pin(idx))
			continue;

		  NetNet*cursig = dynamic_cast<NetNet*>(cur->get_obj());
		  if (cursig == 0)
			continue;

		  if (cursig->local_flag())
			continue;

		  significant_flags += 1;
		  break;
	    }

	    if (significant_flags <= idx)
		  break;
      }

	/* If every pin is connected to another significant signal,
	   then I can delete this one. */
      if (significant_flags == sig->pin_count()) {
	    scontinue = true;
	    delete sig;
	    stotal += 1;
      }
}

void nodangle(Design*des)
{
      nodangle_f fun;
      fun.iteration = 0;
      fun.stotal = 0;
      fun.etotal = 0;
      fun.scomplete = false;
      fun.ecomplete = false;
      do {
            fun.scontinue = false;
            fun.econtinue = false;
	    des->functor(&fun);
	    fun.iteration += 1;
            fun.scomplete = !fun.scontinue;
            fun.ecomplete = !fun.econtinue;

	    if (verbose_flag) {
		  cout << " ... " << fun.iteration << " iterations"
		       << " deleted " << fun.stotal << " dangling signals"
		       << " and " << fun.etotal << " events." << endl;
	    }

      } while (fun.scontinue || fun.econtinue);

}
<commit_msg>More verbose detail for nodangle functor.<commit_after>/*
 * Copyright (c) 1999-2009 Stephen Williams (steve@icarus.com)
 *
 *    This source code is free software; you can redistribute it
 *    and/or modify it in source code form under the terms of the GNU
 *    General Public License as published by the Free Software
 *    Foundation; either version 2 of the License, or (at your option)
 *    any later version.
 *
 *    This program 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 this program; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
 */

# include "config.h"

/*
 * This functor scans the design looking for dangling objects and
 * excess local signals. These deletions are not necessarily required
 * for proper functioning of anything, but they can clean up the
 * appearance of design files that are generated.
 */
# include  "functor.h"
# include  "netlist.h"
# include  "compiler.h"

class nodangle_f  : public functor_t {
    public:
      void event(Design*des, NetEvent*ev);
      void signal(Design*des, NetNet*sig);

      unsigned iteration;
      unsigned stotal, etotal;
      bool scontinue, econtinue;
      bool scomplete, ecomplete;
};

void nodangle_f::event(Design*des, NetEvent*ev)
{
      if (ecomplete) return;

	/* If there are no references to this event, then go right
	   ahead and delete it. There is no use looking further at
	   it. */
      if ((ev->nwait() + ev->ntrig() + ev->nexpr()) == 0) {
	    delete ev;
	    etotal += 1;
	    return;
      }

      if (iteration == 0) {
              /* Try to remove duplicate probes from the event. This
                 is done as a separate initial pass to ensure similar
                 events are detected as soon as possible in subsequent
                 iterations. */
            for (unsigned idx = 0 ;  idx < ev->nprobe() ;  idx += 1) {
                  unsigned jdx = idx + 1;
                  while (jdx < ev->nprobe()) {
                        NetEvProbe*ip = ev->probe(idx);
                        NetEvProbe*jp = ev->probe(jdx);

                        if (ip->edge() != jp->edge()) {
                              jdx += 1;
                              continue;
                        }

                        bool fully_connected = true;
                        for (unsigned jpin = 0; jpin < jp->pin_count(); jpin += 1) {
                              unsigned ipin = 0;
                              bool connected_flag = false;
                              for (ipin = 0 ; ipin < ip->pin_count(); ipin += 1)
                                    if (connected(ip->pin(ipin), jp->pin(jpin))) {
                                          connected_flag = true;
                                          break;
                                    }

                              if (!connected_flag) {
                                    fully_connected = false;
                                    break;
                              }
                        }

                        if (fully_connected) {
                              delete jp;
                        } else {
                              jdx += 1;
                        }
                  }
            }
            econtinue = true;
      } else {
              /* Postpone examining events in an automatic scope until the
                 third (optional) pass. This will mean similar events are
                 biased towards being stored in static scopes. */
            if (ev->scope()->is_auto()) {
                  if (iteration == 1) {
                        econtinue = true;
                        return;
                  }
            } else {
                  if (iteration == 2) {
                        return;
                  }
            }

              /* Try to find all the events that are similar to me, and
                 replace their references with references to me. */
            list<NetEvent*> match;
            ev->find_similar_event(match);
            for (list<NetEvent*>::iterator idx = match.begin()
                       ; idx != match.end() ;  idx ++) {

                  NetEvent*tmp = *idx;
                  assert(tmp != ev);
                  tmp ->replace_event(ev);
            }
      }
}

void nodangle_f::signal(Design*des, NetNet*sig)
{
      if (scomplete) return;

	/* Cannot delete signals referenced in an expression
	   or an l-value. */
      if (sig->get_refs() > 0)
	    return;

	/* Cannot delete the ports of tasks or functions. There are
	   too many places where they are referenced. */
      if ((sig->port_type() != NetNet::NOT_A_PORT)
	  && (sig->scope()->type() == NetScope::TASK))
	    return;

      if ((sig->port_type() != NetNet::NOT_A_PORT)
	  && (sig->scope()->type() == NetScope::FUNC))
	    return;

	/* Can't delete ports of cells. */
      if ((sig->port_type() != NetNet::NOT_A_PORT)
	  && (sig->scope()->attribute(perm_string::literal("ivl_synthesis_cell")) != verinum()))
	    return;

	/* Check to see if the signal is completely unconnected. If
	   all the bits are unlinked, then delete it. */
      if (! sig->is_linked()) {
	    delete sig;
	    stotal += 1;
	    return;
      }

	/* The remaining things can only be done to synthesized
	   signals, not ones that appear in the original Verilog. */
      if (! sig->local_flag())
	    return;

	/* Check to see if there is some significant signal connected
	   to every pin of this signal. */
      unsigned significant_flags = 0;
      for (unsigned idx = 0 ;  idx < sig->pin_count() ;  idx += 1) {
	    Nexus*nex = sig->pin(idx).nexus();

	    for (Link*cur = nex->first_nlink()
		       ; cur ;  cur = cur->next_nlink()) {

		  if (cur == &sig->pin(idx))
			continue;

		  NetNet*cursig = dynamic_cast<NetNet*>(cur->get_obj());
		  if (cursig == 0)
			continue;

		  if (cursig->local_flag())
			continue;

		  significant_flags += 1;
		  break;
	    }

	    if (significant_flags <= idx)
		  break;
      }

	/* If every pin is connected to another significant signal,
	   then I can delete this one. */
      if (significant_flags == sig->pin_count()) {
	    scontinue = true;
	    delete sig;
	    stotal += 1;
      }
}

void nodangle(Design*des)
{
      nodangle_f fun;
      fun.iteration = 0;
      fun.stotal = 0;
      fun.etotal = 0;
      fun.scomplete = false;
      fun.ecomplete = false;
      do {
	    if (verbose_flag) {
		  cout << " ... scan for dangling signal and event nodes. "
		       << "(scomplete=" << (fun.scomplete? "T" : "F")
		       << ", ecomplete=" << (fun.ecomplete? "T" : "F")
		       << ")" << endl << flush;
	    }

            fun.scontinue = false;
            fun.econtinue = false;
	    des->functor(&fun);
	    fun.iteration += 1;
            fun.scomplete = !fun.scontinue;
            fun.ecomplete = !fun.econtinue;

	    if (verbose_flag) {
		  cout << " ... " << fun.iteration << " iterations"
		       << " deleted " << fun.stotal << " dangling signals"
		       << " and " << fun.etotal << " events." << endl << flush;
	    }

      } while (fun.scontinue || fun.econtinue);

      if (verbose_flag) {
	    cout << " ... done" << endl << flush;
      }
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: Date.cxx,v $
 *
 *  $Revision: 1.17 $
 *
 *  last change: $Author: vg $ $Date: 2005-03-23 11:29:03 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library 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
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _FORMS_DATE_HXX_
#include "Date.hxx"
#endif

#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _DATE_HXX
#include <tools/date.hxx>
#endif
#ifndef _COMPHELPER_DATETIME_HXX_
#include <comphelper/datetime.hxx>
#endif
#ifndef _DBHELPER_DBCONVERSION_HXX_
#include <connectivity/dbconversion.hxx>
#endif

#ifndef _COM_SUN_STAR_SDBC_DATATYPE_HPP_
#include <com/sun/star/sdbc/DataType.hpp>
#endif

using namespace dbtools;

//.........................................................................
namespace frm
{
//.........................................................................

using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::sdb;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::util;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::form;
using namespace ::com::sun::star::awt;
using namespace ::com::sun::star::io;
using namespace ::com::sun::star::lang;

//------------------------------------------------------------------
ODateControl::ODateControl(const Reference<XMultiServiceFactory>& _rxFactory)
               :OBoundControl(_rxFactory, VCL_CONTROL_DATEFIELD)
{
}

//------------------------------------------------------------------
InterfaceRef SAL_CALL ODateControl_CreateInstance(const Reference<XMultiServiceFactory>& _rxFactory)
{
    return *(new ODateControl(_rxFactory));
}

//------------------------------------------------------------------------------
Sequence<Type> ODateControl::_getTypes()
{
    return OBoundControl::_getTypes();
}

//------------------------------------------------------------------------------
StringSequence SAL_CALL ODateControl::getSupportedServiceNames() throw()
{
    StringSequence aSupported = OBoundControl::getSupportedServiceNames();
    aSupported.realloc(aSupported.getLength() + 1);

    ::rtl::OUString*pArray = aSupported.getArray();
    pArray[aSupported.getLength()-1] = FRM_SUN_CONTROL_DATEFIELD;
    return aSupported;
}

/*************************************************************************/
//------------------------------------------------------------------
InterfaceRef SAL_CALL ODateModel_CreateInstance(const Reference<XMultiServiceFactory>& _rxFactory)
{
    return *(new ODateModel(_rxFactory));
}

//------------------------------------------------------------------------------
Sequence<Type> ODateModel::_getTypes()
{
    return OEditBaseModel::_getTypes();
}

//------------------------------------------------------------------
DBG_NAME( ODateModel )
//------------------------------------------------------------------
ODateModel::ODateModel(const Reference<XMultiServiceFactory>& _rxFactory)
            :OEditBaseModel( _rxFactory, VCL_CONTROLMODEL_DATEFIELD, FRM_SUN_CONTROL_DATEFIELD, sal_True, sal_True )
                        // use the old control name for compytibility reasons
            ,OLimitedFormats( _rxFactory, FormComponentType::DATEFIELD )
{
    DBG_CTOR( ODateModel, NULL );

    m_nClassId = FormComponentType::DATEFIELD;
    initValueProperty( PROPERTY_DATE, PROPERTY_ID_DATE );

    setAggregateSet(m_xAggregateFastSet, getOriginalHandle(PROPERTY_ID_DATEFORMAT));

    osl_incrementInterlockedCount( &m_refCount );
    try
    {
        if ( m_xAggregateSet.is() )
            m_xAggregateSet->setPropertyValue( PROPERTY_DATEMIN, makeAny( (sal_Int32)( ::Date( 1, 1, 1800 ).GetDate() ) ) );
    }
    catch( const Exception& )
    {
        OSL_ENSURE( sal_False, "ODateModel::ODateModel: caught an exception!" );
    }
    osl_decrementInterlockedCount( &m_refCount );
}

//------------------------------------------------------------------------------
ODateModel::ODateModel( const ODateModel* _pOriginal, const Reference<XMultiServiceFactory>& _rxFactory )
    :OEditBaseModel( _pOriginal, _rxFactory )
    ,OLimitedFormats( _rxFactory, FormComponentType::DATEFIELD )
{
    DBG_CTOR( ODateModel, NULL );

    setAggregateSet( m_xAggregateFastSet, getOriginalHandle( PROPERTY_ID_DATEFORMAT ) );
}

//------------------------------------------------------------------------------
ODateModel::~ODateModel( )
{
    setAggregateSet(Reference< XFastPropertySet >(), -1);
    DBG_DTOR( ODateModel, NULL );
}

// XCloneable
//------------------------------------------------------------------------------
IMPLEMENT_DEFAULT_CLONING( ODateModel )

// XServiceInfo
//------------------------------------------------------------------------------
StringSequence SAL_CALL ODateModel::getSupportedServiceNames() throw()
{
    StringSequence aSupported = OBoundControlModel::getSupportedServiceNames();

    sal_Int32 nOldLen = aSupported.getLength();
    aSupported.realloc( nOldLen + 8 );
    ::rtl::OUString* pStoreTo = aSupported.getArray() + nOldLen;

    *pStoreTo++ = BINDABLE_CONTROL_MODEL;
    *pStoreTo++ = DATA_AWARE_CONTROL_MODEL;
    *pStoreTo++ = VALIDATABLE_CONTROL_MODEL;

    *pStoreTo++ = BINDABLE_DATA_AWARE_CONTROL_MODEL;
    *pStoreTo++ = VALIDATABLE_BINDABLE_CONTROL_MODEL;

    *pStoreTo++ = FRM_SUN_COMPONENT_DATEFIELD;
    *pStoreTo++ = FRM_SUN_COMPONENT_DATABASE_DATEFIELD;
    *pStoreTo++ = BINDABLE_DATABASE_DATE_FIELD;

    return aSupported;
}

//------------------------------------------------------------------------------
::rtl::OUString SAL_CALL ODateModel::getServiceName() throw ( ::com::sun::star::uno::RuntimeException)
{
    return FRM_COMPONENT_DATEFIELD; // old (non-sun) name for compatibility !
}

// XPropertySet
//------------------------------------------------------------------------------
Reference<XPropertySetInfo> SAL_CALL ODateModel::getPropertySetInfo() throw( RuntimeException )
{
    Reference<XPropertySetInfo>  xInfo( createPropertySetInfo( getInfoHelper() ) );
    return xInfo;
}

//------------------------------------------------------------------------------
void ODateModel::fillProperties(
        Sequence< Property >& _rProps,
        Sequence< Property >& _rAggregateProps ) const
{
    BEGIN_DESCRIBE_PROPERTIES( 4, OEditBaseModel )
        DECL_PROP3(DEFAULT_DATE,            sal_Int32,              BOUND, MAYBEDEFAULT, MAYBEVOID);
        DECL_PROP1(TABINDEX,                sal_Int16,              BOUND);
        DECL_PROP1(FORMATKEY,               sal_Int32,              TRANSIENT);
        DECL_IFACE_PROP2(FORMATSSUPPLIER,   XNumberFormatsSupplier, READONLY, TRANSIENT);
    END_DESCRIBE_PROPERTIES();
}

//------------------------------------------------------------------------------
::cppu::IPropertyArrayHelper& ODateModel::getInfoHelper()
{
    return *const_cast<ODateModel*>(this)->getArrayHelper();
}

//------------------------------------------------------------------------------
void SAL_CALL ODateModel::getFastPropertyValue(Any& _rValue, sal_Int32 _nHandle ) const
{
    switch (_nHandle)
    {
        case PROPERTY_ID_FORMATKEY:
            getFormatKeyPropertyValue(_rValue);
            break;
        case PROPERTY_ID_FORMATSSUPPLIER:
            _rValue <<= getFormatsSupplier();
            break;
        default:
            OEditBaseModel::getFastPropertyValue(_rValue, _nHandle);
            break;
    }
}

//------------------------------------------------------------------------------
sal_Bool SAL_CALL ODateModel::convertFastPropertyValue(Any& _rConvertedValue, Any& _rOldValue,
        sal_Int32 _nHandle, const Any& _rValue ) throw(IllegalArgumentException)
{
    if (PROPERTY_ID_FORMATKEY == _nHandle)
        return convertFormatKeyPropertyValue(_rConvertedValue, _rOldValue, _rValue);
    else
        return OEditBaseModel::convertFastPropertyValue(_rConvertedValue, _rOldValue, _nHandle, _rValue );
}

//------------------------------------------------------------------------------
void SAL_CALL ODateModel::setFastPropertyValue_NoBroadcast(sal_Int32 _nHandle, const Any& _rValue) throw ( ::com::sun::star::uno::Exception)
{
    if (PROPERTY_ID_FORMATKEY == _nHandle)
        setFormatKeyPropertyValue(_rValue);
    else
        OEditBaseModel::setFastPropertyValue_NoBroadcast(_nHandle, _rValue);
}

// XLoadListener
//------------------------------------------------------------------------------
void ODateModel::onConnectedDbColumn( const Reference< XInterface >& _rxForm )
{
    OBoundControlModel::onConnectedDbColumn( _rxForm );
    Reference<XPropertySet> xField = getField();
    if (xField.is())
    {
        m_bDateTimeField = sal_False;
        try
        {
            sal_Int32 nFieldType;
            xField->getPropertyValue(PROPERTY_FIELDTYPE) >>= nFieldType;
            m_bDateTimeField = (nFieldType == DataType::TIMESTAMP);
        }
        catch(Exception&)
        {
        }
    }
}

//------------------------------------------------------------------------------
sal_Bool ODateModel::commitControlValueToDbColumn( bool _bPostReset )
{
    Any aControlValue( m_xAggregateFastSet->getFastPropertyValue( getValuePropertyAggHandle() ) );
    if ( !compare( aControlValue, m_aSaveValue ) )
    {
        if ( !aControlValue.hasValue() )
            m_xColumnUpdate->updateNull();
        else
        {
            try
            {
                util::Date aDate;
                if ( !( aControlValue >>= aDate ) )
                {
                    sal_Int32 nAsInt(0);
                    aControlValue >>= nAsInt;
                    aDate = DBTypeConversion::toDate(nAsInt);
                }

                if ( !m_bDateTimeField )
                    m_xColumnUpdate->updateDate( aDate );
                else
                {
                    util::DateTime aDateTime = m_xColumn->getTimestamp();
                    aDateTime.Day = aDate.Day;
                    aDateTime.Month = aDate.Month;
                    aDateTime.Year = aDate.Year;
                    m_xColumnUpdate->updateTimestamp( aDateTime );
                }
            }
            catch(Exception&)
            {
                return sal_False;
            }
        }
        m_aSaveValue = aControlValue;
    }
    return sal_True;
}

//------------------------------------------------------------------------------
Any ODateModel::translateControlValueToExternalValue( ) const
{
    Any aExternalValue( getControlValue() );
    if ( aExternalValue.hasValue() )
    {
        sal_Int32 nDate = 0;
        OSL_VERIFY( aExternalValue >>= nDate );
        aExternalValue <<= DBTypeConversion::toDate( nDate );
    }
    return aExternalValue;
}

//------------------------------------------------------------------------------
Any ODateModel::translateExternalValueToControlValue( ) const
{
    OSL_PRECOND( hasExternalValueBinding(),
        "ODateModel::translateExternalValueToControlValue: precondition not met!" );

    Any aControlValue;
    if ( hasExternalValueBinding() )
    {
        Any aExternalValue = getExternalValueBinding()->getValue( ::getCppuType( static_cast< util::Date* >( NULL ) ) );
        if ( aExternalValue.hasValue() )
        {
            util::Date aDate;
            OSL_VERIFY( aExternalValue >>= aDate );
            aControlValue <<= DBTypeConversion::toINT32( aDate );
        }
    }
    return aControlValue;
}

//------------------------------------------------------------------------------
Any ODateModel::translateDbColumnToControlValue()
{
    util::Date aDate = m_xColumn->getDate();
    if (m_xColumn->wasNull())
        m_aSaveValue.clear();
    else
        // the aggregated set expects an Int32 as value ...
        m_aSaveValue <<= DBTypeConversion::toINT32(aDate);

    return m_aSaveValue;
}

//------------------------------------------------------------------------------
Any ODateModel::getDefaultForReset() const
{
    Any aValue;
    if (m_aDefault.getValueType().getTypeClass() == TypeClass_LONG)
        aValue = m_aDefault;
    else
    {   // aktuelles Datum einstellen
        ::Date aCurrentDate;
        aValue <<= (sal_Int32)aCurrentDate.GetDate();
    }

    return aValue;
}

//------------------------------------------------------------------------------
sal_Bool ODateModel::approveValueBinding( const Reference< binding::XValueBinding >& _rxBinding )
{
    OSL_PRECOND( _rxBinding.is(), "ODateModel::approveValueBinding: invalid binding!" );

    return  _rxBinding.is()
        &&  _rxBinding->supportsType( ::getCppuType( static_cast< util::Date* >( NULL ) ) );
}

//.........................................................................
}   // namespace frm
//.........................................................................

<commit_msg>INTEGRATION: CWS ooo19126 (1.17.56); FILE MERGED 2005/09/05 13:50:15 rt 1.17.56.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: Date.cxx,v $
 *
 *  $Revision: 1.18 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 22:36:53 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library 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
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _FORMS_DATE_HXX_
#include "Date.hxx"
#endif

#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _DATE_HXX
#include <tools/date.hxx>
#endif
#ifndef _COMPHELPER_DATETIME_HXX_
#include <comphelper/datetime.hxx>
#endif
#ifndef _DBHELPER_DBCONVERSION_HXX_
#include <connectivity/dbconversion.hxx>
#endif

#ifndef _COM_SUN_STAR_SDBC_DATATYPE_HPP_
#include <com/sun/star/sdbc/DataType.hpp>
#endif

using namespace dbtools;

//.........................................................................
namespace frm
{
//.........................................................................

using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::sdb;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::util;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::form;
using namespace ::com::sun::star::awt;
using namespace ::com::sun::star::io;
using namespace ::com::sun::star::lang;

//------------------------------------------------------------------
ODateControl::ODateControl(const Reference<XMultiServiceFactory>& _rxFactory)
               :OBoundControl(_rxFactory, VCL_CONTROL_DATEFIELD)
{
}

//------------------------------------------------------------------
InterfaceRef SAL_CALL ODateControl_CreateInstance(const Reference<XMultiServiceFactory>& _rxFactory)
{
    return *(new ODateControl(_rxFactory));
}

//------------------------------------------------------------------------------
Sequence<Type> ODateControl::_getTypes()
{
    return OBoundControl::_getTypes();
}

//------------------------------------------------------------------------------
StringSequence SAL_CALL ODateControl::getSupportedServiceNames() throw()
{
    StringSequence aSupported = OBoundControl::getSupportedServiceNames();
    aSupported.realloc(aSupported.getLength() + 1);

    ::rtl::OUString*pArray = aSupported.getArray();
    pArray[aSupported.getLength()-1] = FRM_SUN_CONTROL_DATEFIELD;
    return aSupported;
}

/*************************************************************************/
//------------------------------------------------------------------
InterfaceRef SAL_CALL ODateModel_CreateInstance(const Reference<XMultiServiceFactory>& _rxFactory)
{
    return *(new ODateModel(_rxFactory));
}

//------------------------------------------------------------------------------
Sequence<Type> ODateModel::_getTypes()
{
    return OEditBaseModel::_getTypes();
}

//------------------------------------------------------------------
DBG_NAME( ODateModel )
//------------------------------------------------------------------
ODateModel::ODateModel(const Reference<XMultiServiceFactory>& _rxFactory)
            :OEditBaseModel( _rxFactory, VCL_CONTROLMODEL_DATEFIELD, FRM_SUN_CONTROL_DATEFIELD, sal_True, sal_True )
                        // use the old control name for compytibility reasons
            ,OLimitedFormats( _rxFactory, FormComponentType::DATEFIELD )
{
    DBG_CTOR( ODateModel, NULL );

    m_nClassId = FormComponentType::DATEFIELD;
    initValueProperty( PROPERTY_DATE, PROPERTY_ID_DATE );

    setAggregateSet(m_xAggregateFastSet, getOriginalHandle(PROPERTY_ID_DATEFORMAT));

    osl_incrementInterlockedCount( &m_refCount );
    try
    {
        if ( m_xAggregateSet.is() )
            m_xAggregateSet->setPropertyValue( PROPERTY_DATEMIN, makeAny( (sal_Int32)( ::Date( 1, 1, 1800 ).GetDate() ) ) );
    }
    catch( const Exception& )
    {
        OSL_ENSURE( sal_False, "ODateModel::ODateModel: caught an exception!" );
    }
    osl_decrementInterlockedCount( &m_refCount );
}

//------------------------------------------------------------------------------
ODateModel::ODateModel( const ODateModel* _pOriginal, const Reference<XMultiServiceFactory>& _rxFactory )
    :OEditBaseModel( _pOriginal, _rxFactory )
    ,OLimitedFormats( _rxFactory, FormComponentType::DATEFIELD )
{
    DBG_CTOR( ODateModel, NULL );

    setAggregateSet( m_xAggregateFastSet, getOriginalHandle( PROPERTY_ID_DATEFORMAT ) );
}

//------------------------------------------------------------------------------
ODateModel::~ODateModel( )
{
    setAggregateSet(Reference< XFastPropertySet >(), -1);
    DBG_DTOR( ODateModel, NULL );
}

// XCloneable
//------------------------------------------------------------------------------
IMPLEMENT_DEFAULT_CLONING( ODateModel )

// XServiceInfo
//------------------------------------------------------------------------------
StringSequence SAL_CALL ODateModel::getSupportedServiceNames() throw()
{
    StringSequence aSupported = OBoundControlModel::getSupportedServiceNames();

    sal_Int32 nOldLen = aSupported.getLength();
    aSupported.realloc( nOldLen + 8 );
    ::rtl::OUString* pStoreTo = aSupported.getArray() + nOldLen;

    *pStoreTo++ = BINDABLE_CONTROL_MODEL;
    *pStoreTo++ = DATA_AWARE_CONTROL_MODEL;
    *pStoreTo++ = VALIDATABLE_CONTROL_MODEL;

    *pStoreTo++ = BINDABLE_DATA_AWARE_CONTROL_MODEL;
    *pStoreTo++ = VALIDATABLE_BINDABLE_CONTROL_MODEL;

    *pStoreTo++ = FRM_SUN_COMPONENT_DATEFIELD;
    *pStoreTo++ = FRM_SUN_COMPONENT_DATABASE_DATEFIELD;
    *pStoreTo++ = BINDABLE_DATABASE_DATE_FIELD;

    return aSupported;
}

//------------------------------------------------------------------------------
::rtl::OUString SAL_CALL ODateModel::getServiceName() throw ( ::com::sun::star::uno::RuntimeException)
{
    return FRM_COMPONENT_DATEFIELD; // old (non-sun) name for compatibility !
}

// XPropertySet
//------------------------------------------------------------------------------
Reference<XPropertySetInfo> SAL_CALL ODateModel::getPropertySetInfo() throw( RuntimeException )
{
    Reference<XPropertySetInfo>  xInfo( createPropertySetInfo( getInfoHelper() ) );
    return xInfo;
}

//------------------------------------------------------------------------------
void ODateModel::fillProperties(
        Sequence< Property >& _rProps,
        Sequence< Property >& _rAggregateProps ) const
{
    BEGIN_DESCRIBE_PROPERTIES( 4, OEditBaseModel )
        DECL_PROP3(DEFAULT_DATE,            sal_Int32,              BOUND, MAYBEDEFAULT, MAYBEVOID);
        DECL_PROP1(TABINDEX,                sal_Int16,              BOUND);
        DECL_PROP1(FORMATKEY,               sal_Int32,              TRANSIENT);
        DECL_IFACE_PROP2(FORMATSSUPPLIER,   XNumberFormatsSupplier, READONLY, TRANSIENT);
    END_DESCRIBE_PROPERTIES();
}

//------------------------------------------------------------------------------
::cppu::IPropertyArrayHelper& ODateModel::getInfoHelper()
{
    return *const_cast<ODateModel*>(this)->getArrayHelper();
}

//------------------------------------------------------------------------------
void SAL_CALL ODateModel::getFastPropertyValue(Any& _rValue, sal_Int32 _nHandle ) const
{
    switch (_nHandle)
    {
        case PROPERTY_ID_FORMATKEY:
            getFormatKeyPropertyValue(_rValue);
            break;
        case PROPERTY_ID_FORMATSSUPPLIER:
            _rValue <<= getFormatsSupplier();
            break;
        default:
            OEditBaseModel::getFastPropertyValue(_rValue, _nHandle);
            break;
    }
}

//------------------------------------------------------------------------------
sal_Bool SAL_CALL ODateModel::convertFastPropertyValue(Any& _rConvertedValue, Any& _rOldValue,
        sal_Int32 _nHandle, const Any& _rValue ) throw(IllegalArgumentException)
{
    if (PROPERTY_ID_FORMATKEY == _nHandle)
        return convertFormatKeyPropertyValue(_rConvertedValue, _rOldValue, _rValue);
    else
        return OEditBaseModel::convertFastPropertyValue(_rConvertedValue, _rOldValue, _nHandle, _rValue );
}

//------------------------------------------------------------------------------
void SAL_CALL ODateModel::setFastPropertyValue_NoBroadcast(sal_Int32 _nHandle, const Any& _rValue) throw ( ::com::sun::star::uno::Exception)
{
    if (PROPERTY_ID_FORMATKEY == _nHandle)
        setFormatKeyPropertyValue(_rValue);
    else
        OEditBaseModel::setFastPropertyValue_NoBroadcast(_nHandle, _rValue);
}

// XLoadListener
//------------------------------------------------------------------------------
void ODateModel::onConnectedDbColumn( const Reference< XInterface >& _rxForm )
{
    OBoundControlModel::onConnectedDbColumn( _rxForm );
    Reference<XPropertySet> xField = getField();
    if (xField.is())
    {
        m_bDateTimeField = sal_False;
        try
        {
            sal_Int32 nFieldType;
            xField->getPropertyValue(PROPERTY_FIELDTYPE) >>= nFieldType;
            m_bDateTimeField = (nFieldType == DataType::TIMESTAMP);
        }
        catch(Exception&)
        {
        }
    }
}

//------------------------------------------------------------------------------
sal_Bool ODateModel::commitControlValueToDbColumn( bool _bPostReset )
{
    Any aControlValue( m_xAggregateFastSet->getFastPropertyValue( getValuePropertyAggHandle() ) );
    if ( !compare( aControlValue, m_aSaveValue ) )
    {
        if ( !aControlValue.hasValue() )
            m_xColumnUpdate->updateNull();
        else
        {
            try
            {
                util::Date aDate;
                if ( !( aControlValue >>= aDate ) )
                {
                    sal_Int32 nAsInt(0);
                    aControlValue >>= nAsInt;
                    aDate = DBTypeConversion::toDate(nAsInt);
                }

                if ( !m_bDateTimeField )
                    m_xColumnUpdate->updateDate( aDate );
                else
                {
                    util::DateTime aDateTime = m_xColumn->getTimestamp();
                    aDateTime.Day = aDate.Day;
                    aDateTime.Month = aDate.Month;
                    aDateTime.Year = aDate.Year;
                    m_xColumnUpdate->updateTimestamp( aDateTime );
                }
            }
            catch(Exception&)
            {
                return sal_False;
            }
        }
        m_aSaveValue = aControlValue;
    }
    return sal_True;
}

//------------------------------------------------------------------------------
Any ODateModel::translateControlValueToExternalValue( ) const
{
    Any aExternalValue( getControlValue() );
    if ( aExternalValue.hasValue() )
    {
        sal_Int32 nDate = 0;
        OSL_VERIFY( aExternalValue >>= nDate );
        aExternalValue <<= DBTypeConversion::toDate( nDate );
    }
    return aExternalValue;
}

//------------------------------------------------------------------------------
Any ODateModel::translateExternalValueToControlValue( ) const
{
    OSL_PRECOND( hasExternalValueBinding(),
        "ODateModel::translateExternalValueToControlValue: precondition not met!" );

    Any aControlValue;
    if ( hasExternalValueBinding() )
    {
        Any aExternalValue = getExternalValueBinding()->getValue( ::getCppuType( static_cast< util::Date* >( NULL ) ) );
        if ( aExternalValue.hasValue() )
        {
            util::Date aDate;
            OSL_VERIFY( aExternalValue >>= aDate );
            aControlValue <<= DBTypeConversion::toINT32( aDate );
        }
    }
    return aControlValue;
}

//------------------------------------------------------------------------------
Any ODateModel::translateDbColumnToControlValue()
{
    util::Date aDate = m_xColumn->getDate();
    if (m_xColumn->wasNull())
        m_aSaveValue.clear();
    else
        // the aggregated set expects an Int32 as value ...
        m_aSaveValue <<= DBTypeConversion::toINT32(aDate);

    return m_aSaveValue;
}

//------------------------------------------------------------------------------
Any ODateModel::getDefaultForReset() const
{
    Any aValue;
    if (m_aDefault.getValueType().getTypeClass() == TypeClass_LONG)
        aValue = m_aDefault;
    else
    {   // aktuelles Datum einstellen
        ::Date aCurrentDate;
        aValue <<= (sal_Int32)aCurrentDate.GetDate();
    }

    return aValue;
}

//------------------------------------------------------------------------------
sal_Bool ODateModel::approveValueBinding( const Reference< binding::XValueBinding >& _rxBinding )
{
    OSL_PRECOND( _rxBinding.is(), "ODateModel::approveValueBinding: invalid binding!" );

    return  _rxBinding.is()
        &&  _rxBinding->supportsType( ::getCppuType( static_cast< util::Date* >( NULL ) ) );
}

//.........................................................................
}   // namespace frm
//.........................................................................

<|endoftext|>


<commit_before>/****************************************************************/
/*               DO NOT MODIFY THIS HEADER                      */
/* MOOSE - Multiphysics Object Oriented Simulation Environment  */
/*                                                              */
/*           (c) 2010 Battelle Energy Alliance, LLC             */
/*                   ALL RIGHTS RESERVED                        */
/*                                                              */
/*          Prepared by Battelle Energy Alliance, LLC           */
/*            Under Contract No. DE-AC07-05ID14517              */
/*            With the U. S. Department of Energy               */
/*                                                              */
/*            See COPYRIGHT for full restrictions               */
/****************************************************************/

#include "TimeScheme.h"
#include "NonlinearSystem.h"
#include "PetscSupport.h"

// libMesh
#include "nonlinear_solver.h"
#include "quadrature_gauss.h"
#include "dense_vector.h"
#include "boundary_info.h"
#include "petsc_matrix.h"
#include "petsc_vector.h"
#include "petsc_nonlinear_solver.h"
#include "numeric_vector.h"
#include "mesh.h"
#include "dense_subvector.h"
#include "dense_submatrix.h"
#include "dof_map.h"
// PETSc
#ifdef LIBMESH_HAVE_PETSC
#include "petscsnes.h"
#endif

#include <iostream>

TimeScheme::TimeScheme(NonlinearSystem * c) :
_nl(c),
_solution_u_dot(c->_sys.add_vector("u_dot", false, GHOSTED)),
_solution_du_dot_du(c->_sys.add_vector("du_dot_du", false, GHOSTED)),
_residual_old( c->_sys.add_vector("residual_old", false, GHOSTED)),
_predicted_solution(c->_sys.add_vector("predicted_solution", false, GHOSTED)),
_trash1(c->_sys.add_vector("trash1", false, GHOSTED)),
_trash2(c->_sys.add_vector("trash2", false, GHOSTED)),
_trash3(c->_sys.add_vector("trash3", false, GHOSTED)),
_mmatrix(c->_sys.add_vector("mmatrix", false, GHOSTED)),
_dt(c->_dt),
_dt_old( c->_dt_old),
_time_weight( c->_time_weight),
_time_stepping_scheme( c->_time_stepping_scheme),
_t_step(c->_t_step),
_time_stack(std::deque<TimeStep>()),
_workvecs(std::vector<NumericVector<Number> *>()),
_apply_predictor(true),
_use_AB2(false),
_dt2_check(NULL),
_dt2_bool(false)
{

}

TimeScheme::~TimeScheme(){
  delete _dt2_check;
}

void TimeScheme::reclaimTimeStep(TimeStep &timestep)
{
  // time derivative first because it is not zeroed
  _workvecs.push_back(&timestep.getTimeDerivitive());
  _workvecs.push_back(&timestep.getSolution());
}

void
TimeScheme::onTimestepBegin()
{
  if (_time_stack.empty())
  {
    _time_stack.push_back(TimeStep((_nl->_t - _dt), 0, _nl, _workvecs));
    _time_stack.back().setDt(_dt_old);
  }

  if(_dt2_bool)
  {
    //fix stack if DT2Transient
    for (int i=0; i<2; i++)
    { // reject last two short steps
      reclaimTimeStep(_time_stack.back());
      _time_stack.pop_back();
    }
    _time_stack.push_back(*_dt2_check);
    _dt2_check = NULL;
    _dt2_bool = false;
  }
  _time_stepping_scheme = _nl->_time_stepping_scheme;
  //set Solution to previous solve
  _time_stack.back().setSolution(_nl->solutionOld());
  _dt_old = _time_stack.back().getDt();
  if(_time_stack.size()!=0 && _time_stack.back().getTimeStep() == _t_step)
  {
    if(_dt != _dt_old)
    {
     //Solve Fail
      if (_dt2_check)
      {
        reclaimTimeStep(*_dt2_check);
        delete _dt2_check;
      }
      _dt2_check = new TimeStep(_time_stack.back());
      _time_stack.pop_back();
    }
    else
    {
      //DT2Transient
      _dt2_bool = true;
    }
  }
  else
  {
    //This 4 should be tied to the order of the time scheme.
    if(_time_stack.size()>4)
    {
      reclaimTimeStep(_time_stack.front());
      _time_stack.pop_front();
    }
  }
  _dt_old = _time_stack.back().getDt();
  ///Set solution to right values
  _nl->_solution.localize( _time_stack.back().getSolution());
  _nl->_solution_old.localize(_time_stack.back().getSolution());
  if(_t_step>1)
  {
    _nl->_solution_older = _time_stack[_time_stack.size()-2].getSolution();
  }
  ///push back the current time step
  _time_stack.push_back(TimeStep(_nl->_t, _t_step, _nl, _workvecs));
  _time_stack.back().setDt(_dt);
  Real sum;
  if(_t_step > 1)
  {
    _time_stack[_time_stack.size()-2].setTimeDerivitive(_solution_u_dot);
  }
  switch (_time_stepping_scheme)
  {
  case Moose::CRANK_NICOLSON:
    {
      computeLittlef(_time_stack[_time_stack.size()-2].getSolution(), _residual_old, -1, false);
    }
    break;

  case Moose::BDF2:
    sum = _dt+ _dt_old;
    _time_weight[0] = 1.+_dt/sum;
    _time_weight[1] =-sum/ _dt_old;
    _time_weight[2] =_dt*_dt/_dt_old/sum;
    break;

  default:
    break;
  }

}

void TimeScheme::Adams_Bashforth2P(NumericVector<Number> & initial_solution)
{
  if(_dt ==0 || _dt_old == 0 || _t_step<3){
    return;
  }
  initial_solution.localize(_predicted_solution);
  NumericVector<Number> & my_old_solution_u_dot = _trash1; //change to trash1
  _time_stack[_time_stack.size()-3].getTimeDerivitive().localize(my_old_solution_u_dot);
  my_old_solution_u_dot *= -1.0;
  my_old_solution_u_dot += _time_stack[_time_stack.size()-2].getTimeDerivitive();
  my_old_solution_u_dot *= (.5*_dt*_dt)/ _time_stack[_time_stack.size()-2].getDt();
  NumericVector<Number> & _old_solution_u_dot = _trash2;
  _time_stack[_time_stack.size()-2].getTimeDerivitive().localize(_old_solution_u_dot);
  _old_solution_u_dot *= _dt;
  _predicted_solution += my_old_solution_u_dot;
  _predicted_solution += _old_solution_u_dot;
  if(_apply_predictor)
  {
    my_old_solution_u_dot *= _nl->_predictor_scale;
    _old_solution_u_dot *= _nl->_predictor_scale;
    initial_solution += my_old_solution_u_dot;
    initial_solution += _old_solution_u_dot;
  }
}
/*void TimeScheme::Adams_Bashforth2P(NumericVector<Number> & initial_solution)
{

  NumericVector<Number> & residual_older = _trash1;
  NumericVector<Number> & residual_old = _trash2;

  computeLittlef(_time_stack[_time_stack.size()-3].getSolution(), residual_older);
  computeLittlef(_time_stack[_time_stack.size() -2].getSolution(), residual_old);
  if(_dt ==0 || _dt_old == 0){
    std::cout<<"help me!!"<<std::endl;
  }
  residual_older *= -1.0*(_dt*_dt)/(2.0*_dt_old);
  residual_old *= -1.0*(_dt + (_dt*_dt)/(2.0*_dt_old));
  initial_solution +=  (residual_old);
  initial_solution -= residual_older;
  initial_solution.localize(_predicted_solution);
}*/

Real
TimeScheme::estimateTimeError(NumericVector<Number> & solution)
{
  Real ret = -1;
  if(_dt_old >0){
    switch (_time_stepping_scheme)
    {
      case Moose::CRANK_NICOLSON:
      {
        _predicted_solution -= solution;
         _predicted_solution *= (_dt)/(3.0 * (_dt +_dt_old));
         ret = _predicted_solution.l2_norm();
         return ret;
      }
      case Moose::BDF2:
      {
        _predicted_solution *= -1.0;
        _predicted_solution += solution;
        Real topcalc = 2.0*(_dt + _dt_old)*(_dt +_dt_old);
        Real bottomcalc = 6.0*_dt*_dt + 12.0*_dt*_dt_old + 5.0*_dt_old*_dt_old;
        _predicted_solution *= topcalc/bottomcalc;
        ret = _predicted_solution.l2_norm();
        return ret;
      }
      default:
        break;
    }
  }
  return ret;
}

void
TimeScheme::applyPredictor(NumericVector<Number> & initial_solution)
{
  // A Predictor is an algorithm that will predict the next solution based on
  // previous solutions.  Basically, it works like:
  //
  //             sol - prev_sol
  // sol = sol + -------------- * dt * scale_factor
  //                 dt_old
  //
  // The scale factor can be set to 1 for times when the solution is expected
  // to change linearly or smoothly.  If the solution is less continuous over
  // time, it may be better to set to to 0.
  //   In the ideal case of a linear model with linearly changing bcs, the Predictor
  // can determine the solution before the solver is invoked (a solution is computed
  // in zero solver iterations).  Even outside the ideal case, a good Predictor
  // significantly reduces the number of solver iterations required.
  //   It is important to compute the initial residual to be used as a relative
  // convergence criterion before applying the predictor.  If this is not done,
  // the residual is likely to be much lower after applying the predictor, which would
  // result in a much more stringent criterion for convergence than would have been
  // used if the predictor were not enabled.
  if(_use_AB2){
    if(_t_step >2)
    {
      Adams_Bashforth2P(initial_solution);
    }
    return;
  }
  if (_dt_old > 0)
  {
    std::streamsize cur_precision(std::cout.precision());
    std::cout << "  Applying predictor with scale factor = "<<std::fixed<<std::setprecision(2)<<_nl->_predictor_scale<<"\n";
    std::cout << std::scientific << std::setprecision(cur_precision);
    Real dt_adjusted_scale_factor = _nl->_predictor_scale *_dt/_dt_old;
    NumericVector<Number> & previous_solution = _trash1;
    _time_stack[_time_stack.size()-3].getSolution().localize(previous_solution);
    if (dt_adjusted_scale_factor != 0.0)
    {
      initial_solution *= (1.0 + dt_adjusted_scale_factor);
      previous_solution *= dt_adjusted_scale_factor;
      initial_solution -= previous_solution;
    }
  }
}

void TimeScheme::computeLittlef(const NumericVector<Number> & bigF, NumericVector<Number> & littlef, Real time, bool mass)
{
  NumericVector<Number> & my_solution_u_dot = _trash3;

   if(mass)
   {
     _solution_u_dot.localize(my_solution_u_dot);
     _solution_u_dot = 1.0;
   }
  Real currenttime = _nl->_t;
  const NumericVector<Real> *current_solution = _nl->currentSolution();
  if(time != -1)
  {
    _nl->_t = time;
  }
  _nl->set_solution(bigF);// use old_solution for computing with correct solution vector
  littlef.close();
  _nl->computeNonTimeResidual(littlef);
  if(mass)
  {
#ifdef LIBMESH_HAVE_PETSC
    _nl->computeTimeResidual(_mmatrix);
    PetscVector<Number> cls((static_cast<PetscVector<Number> & > (_mmatrix)).vec());
    if( VecReciprocal(cls.vec()) != 0)
      mooseError("VecReciprocal");
    cls.close();
    littlef.pointwise_mult(littlef, _mmatrix);
    _mmatrix.close();
#endif
  }

  _nl->set_solution(*current_solution);
  _nl->_t = currenttime;
  if(mass)
  {
    my_solution_u_dot.localize(_solution_u_dot);
  }
}

NumericVector<Number> & TimeScheme::finishResidual(NumericVector<Number> & residual){
  switch (_time_stepping_scheme)
  {
  case Moose::CRANK_NICOLSON:
    residual.add(_residual_old);
    residual.close();
    break;

  default:
    break;
  }
  return residual;
}

void
TimeScheme::computeTimeDerivatives()
{

  switch (_time_stepping_scheme)
  {
  case Moose::IMPLICIT_EULER:
  case Moose::EXPLICIT_EULER:
    _solution_u_dot = *_nl->currentSolution();
    _solution_u_dot -= _time_stack[_time_stack.size() -2].getSolution();
    _solution_u_dot /= _dt;

    _solution_du_dot_du = 1.0 / _dt;
    break;

  case Moose::CRANK_NICOLSON:
    _solution_u_dot = *_nl->currentSolution();
    _solution_u_dot -=  _time_stack[_time_stack.size() -2].getSolution();
    _solution_u_dot *=  2.0/_dt;
    //_solution_u_dot += *_residual_old;
    _solution_du_dot_du = 1.0/_dt;
    break;

  case Moose::BDF2:
    if (_t_step == 1)
    {
      // Use backward-euler for the first step
      _solution_u_dot = *_nl->currentSolution();
      _solution_u_dot -=  _time_stack[_time_stack.size() -2].getSolution();
      _solution_u_dot /= _dt;

      _solution_du_dot_du = 1.0/_dt;
    }
    else
    {

      _solution_u_dot.zero();
      _solution_u_dot.add(_time_weight[0], *_nl->currentSolution());
      _solution_u_dot.add(_time_weight[1], _time_stack[_time_stack.size() -2].getSolution());

      _solution_u_dot.add(_time_weight[2], _time_stack[_time_stack.size()-3].getSolution()); //_time_stack[_time_stack.size()-2].getSolution());
      _solution_u_dot.scale(1./_dt);
      _solution_du_dot_du = _time_weight[0]/_dt;
    }
    break;

  default:
    break;
  }
  _solution_u_dot.close();
  _solution_du_dot_du.close();
}
ot_du = _time_weight[0]/_dt;
    }
    break;

  default:
    break;
  }
  _solution_u_dot.close();
  _solution_du_dot_du.close();
}
<commit_msg>fixed CH problem ref #1288<commit_after>/****************************************************************/
/*               DO NOT MODIFY THIS HEADER                      */
/* MOOSE - Multiphysics Object Oriented Simulation Environment  */
/*                                                              */
/*           (c) 2010 Battelle Energy Alliance, LLC             */
/*                   ALL RIGHTS RESERVED                        */
/*                                                              */
/*          Prepared by Battelle Energy Alliance, LLC           */
/*            Under Contract No. DE-AC07-05ID14517              */
/*            With the U. S. Department of Energy               */
/*                                                              */
/*            See COPYRIGHT for full restrictions               */
/****************************************************************/

#include "TimeScheme.h"
#include "NonlinearSystem.h"
#include "PetscSupport.h"

// libMesh
#include "nonlinear_solver.h"
#include "quadrature_gauss.h"
#include "dense_vector.h"
#include "boundary_info.h"
#include "petsc_matrix.h"
#include "petsc_vector.h"
#include "petsc_nonlinear_solver.h"
#include "numeric_vector.h"
#include "mesh.h"
#include "dense_subvector.h"
#include "dense_submatrix.h"
#include "dof_map.h"
// PETSc
#ifdef LIBMESH_HAVE_PETSC
#include "petscsnes.h"
#endif

#include <iostream>

TimeScheme::TimeScheme(NonlinearSystem * c) :
_nl(c),
_solution_u_dot(c->_sys.add_vector("u_dot", false, GHOSTED)),
_solution_du_dot_du(c->_sys.add_vector("du_dot_du", false, GHOSTED)),
_residual_old( c->_sys.add_vector("residual_old", false, GHOSTED)),
_predicted_solution(c->_sys.add_vector("predicted_solution", false, GHOSTED)),
_trash1(c->_sys.add_vector("trash1", false, GHOSTED)),
_trash2(c->_sys.add_vector("trash2", false, GHOSTED)),
_trash3(c->_sys.add_vector("trash3", false, GHOSTED)),
_mmatrix(c->_sys.add_vector("mmatrix", false, GHOSTED)),
_dt(c->_dt),
_dt_old( c->_dt_old),
_time_weight( c->_time_weight),
_time_stepping_scheme( c->_time_stepping_scheme),
_t_step(c->_t_step),
_time_stack(std::deque<TimeStep>()),
_workvecs(std::vector<NumericVector<Number> *>()),
_apply_predictor(true),
_use_AB2(false),
_dt2_check(NULL),
_dt2_bool(false)
{

}

TimeScheme::~TimeScheme(){
  delete _dt2_check;
}

void TimeScheme::reclaimTimeStep(TimeStep &timestep)
{
  // time derivative first because it is not zeroed
  _workvecs.push_back(&timestep.getTimeDerivitive());
  _workvecs.push_back(&timestep.getSolution());
}

void
TimeScheme::onTimestepBegin()
{
  if (_time_stack.empty())
  {
    _time_stack.push_back(TimeStep((_nl->_t - _dt), 0, _nl, _workvecs));
    _time_stack.back().setDt(_dt_old);
  }

  if(_dt2_bool)
  {
    //fix stack if DT2Transient
    for (int i=0; i<2; i++)
    { // reject last two short steps
      reclaimTimeStep(_time_stack.back());
      _time_stack.pop_back();
    }
    _time_stack.push_back(*_dt2_check);
    _dt2_check = NULL;
    _dt2_bool = false;
  }
  _time_stepping_scheme = _nl->_time_stepping_scheme;
  //set Solution to previous solve
  _time_stack.back().setSolution(_nl->solutionOld());
  _dt_old = _time_stack.back().getDt();
  if(_time_stack.size()!=0 && _time_stack.back().getTimeStep() == _t_step)
  {
    if(_dt != _dt_old)
    {
     //Solve Fail
      if (_dt2_check)
      {
        reclaimTimeStep(*_dt2_check);
        delete _dt2_check;
      }
      _dt2_check = new TimeStep(_time_stack.back());
      _time_stack.pop_back();
    }
    else
    {
      //DT2Transient
      _dt2_bool = true;
    }
  }
  else
  {
    //This 4 should be tied to the order of the time scheme.
    if(_time_stack.size()>4)
    {
      reclaimTimeStep(_time_stack.front());
      _time_stack.pop_front();
    }
  }
  _dt_old = _time_stack.back().getDt();
  ///Set solution to right values
  _nl->_solution.localize( _time_stack.back().getSolution());
  _nl->_solution_old.localize(_time_stack.back().getSolution());
  if(_t_step>1)
  {
    _nl->_solution_older = _time_stack[_time_stack.size()-2].getSolution();
  }
  ///push back the current time step
  _time_stack.push_back(TimeStep(_nl->_t, _t_step, _nl, _workvecs));
  _time_stack.back().setDt(_dt);
  Real sum;
  if(_t_step > 1)
  {
    _time_stack[_time_stack.size()-2].setTimeDerivitive(_solution_u_dot);
  }
  switch (_time_stepping_scheme)
  {
  case Moose::CRANK_NICOLSON:
    {
      computeLittlef(_time_stack[_time_stack.size()-2].getSolution(), _residual_old, -1, false);
    }
    break;

  case Moose::BDF2:
    sum = _dt+ _dt_old;
    _time_weight[0] = 1.+_dt/sum;
    _time_weight[1] =-sum/ _dt_old;
    _time_weight[2] =_dt*_dt/_dt_old/sum;
    break;

  default:
    break;
  }

}

void TimeScheme::Adams_Bashforth2P(NumericVector<Number> & initial_solution)
{
  if(_dt ==0 || _dt_old == 0 || _t_step<3){
    return;
  }
  initial_solution.localize(_predicted_solution);
  NumericVector<Number> & my_old_solution_u_dot = _trash1; //change to trash1
  _time_stack[_time_stack.size()-3].getTimeDerivitive().localize(my_old_solution_u_dot);
  my_old_solution_u_dot *= -1.0;
  my_old_solution_u_dot += _time_stack[_time_stack.size()-2].getTimeDerivitive();
  my_old_solution_u_dot *= (.5*_dt*_dt)/ _time_stack[_time_stack.size()-2].getDt();
  NumericVector<Number> & _old_solution_u_dot = _trash2;
  _time_stack[_time_stack.size()-2].getTimeDerivitive().localize(_old_solution_u_dot);
  _old_solution_u_dot *= _dt;
  _predicted_solution += my_old_solution_u_dot;
  _predicted_solution += _old_solution_u_dot;
  if(_apply_predictor)
  {
    my_old_solution_u_dot *= _nl->_predictor_scale;
    _old_solution_u_dot *= _nl->_predictor_scale;
    initial_solution += my_old_solution_u_dot;
    initial_solution += _old_solution_u_dot;
  }
}
/*void TimeScheme::Adams_Bashforth2P(NumericVector<Number> & initial_solution)
{

  NumericVector<Number> & residual_older = _trash1;
  NumericVector<Number> & residual_old = _trash2;

  computeLittlef(_time_stack[_time_stack.size()-3].getSolution(), residual_older);
  computeLittlef(_time_stack[_time_stack.size() -2].getSolution(), residual_old);
  if(_dt ==0 || _dt_old == 0){
    std::cout<<"help me!!"<<std::endl;
  }
  residual_older *= -1.0*(_dt*_dt)/(2.0*_dt_old);
  residual_old *= -1.0*(_dt + (_dt*_dt)/(2.0*_dt_old));
  initial_solution +=  (residual_old);
  initial_solution -= residual_older;
  initial_solution.localize(_predicted_solution);
}*/

Real
TimeScheme::estimateTimeError(NumericVector<Number> & solution)
{
  Real ret = -1;
  if(_dt_old >0){
    switch (_time_stepping_scheme)
    {
      case Moose::CRANK_NICOLSON:
      {
        _predicted_solution -= solution;
         _predicted_solution *= (_dt)/(3.0 * (_dt +_dt_old));
         ret = _predicted_solution.l2_norm();
         return ret;
      }
      case Moose::BDF2:
      {
        _predicted_solution *= -1.0;
        _predicted_solution += solution;
        Real topcalc = 2.0*(_dt + _dt_old)*(_dt +_dt_old);
        Real bottomcalc = 6.0*_dt*_dt + 12.0*_dt*_dt_old + 5.0*_dt_old*_dt_old;
        _predicted_solution *= topcalc/bottomcalc;
        ret = _predicted_solution.l2_norm();
        return ret;
      }
      default:
        break;
    }
  }
  return ret;
}

void
TimeScheme::applyPredictor(NumericVector<Number> & initial_solution)
{
  // A Predictor is an algorithm that will predict the next solution based on
  // previous solutions.  Basically, it works like:
  //
  //             sol - prev_sol
  // sol = sol + -------------- * dt * scale_factor
  //                 dt_old
  //
  // The scale factor can be set to 1 for times when the solution is expected
  // to change linearly or smoothly.  If the solution is less continuous over
  // time, it may be better to set to to 0.
  //   In the ideal case of a linear model with linearly changing bcs, the Predictor
  // can determine the solution before the solver is invoked (a solution is computed
  // in zero solver iterations).  Even outside the ideal case, a good Predictor
  // significantly reduces the number of solver iterations required.
  //   It is important to compute the initial residual to be used as a relative
  // convergence criterion before applying the predictor.  If this is not done,
  // the residual is likely to be much lower after applying the predictor, which would
  // result in a much more stringent criterion for convergence than would have been
  // used if the predictor were not enabled.
  if(_use_AB2){
    if(_t_step >2)
    {
      Adams_Bashforth2P(initial_solution);
    }
    return;
  }
  if (_dt_old > 0)
  {
    std::streamsize cur_precision(std::cout.precision());
    std::cout << "  Applying predictor with scale factor = "<<std::fixed<<std::setprecision(2)<<_nl->_predictor_scale<<"\n";
    std::cout << std::scientific << std::setprecision(cur_precision);
    Real dt_adjusted_scale_factor = _nl->_predictor_scale *_dt/_dt_old;
    NumericVector<Number> & previous_solution = _trash1;
    _time_stack[_time_stack.size()-3].getSolution().localize(previous_solution);
    if (dt_adjusted_scale_factor != 0.0)
    {
      initial_solution *= (1.0 + dt_adjusted_scale_factor);
      previous_solution *= dt_adjusted_scale_factor;
      initial_solution -= previous_solution;
    }
  }
}

void TimeScheme::computeLittlef(const NumericVector<Number> & bigF, NumericVector<Number> & littlef, Real time, bool mass)
{
  NumericVector<Number> & my_solution_u_dot = _trash3;

   if(mass)
   {
     _solution_u_dot.localize(my_solution_u_dot);
     _solution_u_dot = 1.0;
   }
  Real currenttime = _nl->_t;
  const NumericVector<Real> *current_solution = _nl->currentSolution();
  if(time != -1)
  {
    _nl->_t = time;
  }
  _nl->set_solution(bigF);// use old_solution for computing with correct solution vector
  littlef.close();
  _nl->computeNonTimeResidual(littlef);
  if(mass)
  {
#ifdef LIBMESH_HAVE_PETSC
    _nl->computeTimeResidual(_mmatrix);
    PetscVector<Number> cls((static_cast<PetscVector<Number> & > (_mmatrix)).vec());
    if( VecReciprocal(cls.vec()) != 0)
      mooseError("VecReciprocal");
    cls.close();
    littlef.pointwise_mult(littlef, _mmatrix);
    _mmatrix.close();
#endif
  }

  _nl->set_solution(*current_solution);
  _nl->_t = currenttime;
  if(mass)
  {
    my_solution_u_dot.localize(_solution_u_dot);
  }
}

NumericVector<Number> & TimeScheme::finishResidual(NumericVector<Number> & residual){
  switch (_time_stepping_scheme)
  {
  case Moose::CRANK_NICOLSON:
    residual.add(_residual_old);
    residual.close();
    break;

  default:
    break;
  }
  return residual;
}

void
TimeScheme::computeTimeDerivatives()
{

  switch (_time_stepping_scheme)
  {
  case Moose::IMPLICIT_EULER:
  case Moose::EXPLICIT_EULER:
    _solution_u_dot = *_nl->currentSolution();
    _solution_u_dot -= _time_stack[_time_stack.size() -2].getSolution();
    _solution_u_dot /= _dt;

    _solution_du_dot_du = 1.0 / _dt;
    break;

  case Moose::CRANK_NICOLSON:
    _solution_u_dot = *_nl->currentSolution();
    _solution_u_dot -=  _time_stack[_time_stack.size() -2].getSolution();
    _solution_u_dot *=  2.0/_dt;
    //_solution_u_dot += *_residual_old;
    _solution_du_dot_du = 1.0/_dt;
    break;

  case Moose::BDF2:
    if (_t_step == 1)
    {
      // Use backward-euler for the first step
      _solution_u_dot = *_nl->currentSolution();
      _solution_u_dot -=  _time_stack[_time_stack.size() -2].getSolution();
      _solution_u_dot /= _dt;

      _solution_du_dot_du = 1.0/_dt;
    }
    else
    {

      _solution_u_dot.zero();
      _solution_u_dot.add(_time_weight[0], *_nl->currentSolution());
      _solution_u_dot.add(_time_weight[1], _time_stack[_time_stack.size() -2].getSolution());

      _solution_u_dot.add(_time_weight[2], _time_stack[_time_stack.size()-3].getSolution()); //_time_stack[_time_stack.size()-2].getSolution());
      _solution_u_dot.scale(1./_dt);
      _solution_du_dot_du = _time_weight[0]/_dt;
    }
    break;

  default:
    break;
  }
  _solution_u_dot.close();
  _solution_du_dot_du.close();
}
<|endoftext|>