<commit_before>/*
 * This file is open source software, licensed to you under the terms
 * of the Apache License, Version 2.0 (the "License").  See the NOTICE file
 * distributed with this work for additional information regarding copyright
 * ownership.  You may not use this file except in compliance with the License.
 *
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
/*
 * Copyright 2021 ScyllaDB
 */

#pragma once

#include <boost/intrusive/list.hpp>
#include <boost/intrusive/slist.hpp>
#include <boost/container/small_vector.hpp>
#include <seastar/core/internal/io_intent.hh>
#include <seastar/core/io_priority_class.hh>

namespace bi = boost::intrusive;

namespace seastar {

/// \example file_demo.cc
/// A handle confirming the caller's intent to do the IO
///
/// When a pointer to an intent is passed to the \ref io_queue
/// "io_queue"::queue_request() method, the issued request is pinned
/// to the intent and is only processed as long as the intent object
/// is alive and the **cancel()** method is not called.
///
/// If no intent is provided, then the request is processed till its
/// completion be it success or error
class io_intent {
    struct intents_for_queue {
        dev_t dev;
        io_priority_class_id qid;
        internal::cancellable_queue cq;

        intents_for_queue(dev_t dev_, io_priority_class_id qid_) noexcept
            : dev(dev_), qid(qid_), cq() {}

        intents_for_queue(intents_for_queue&&) noexcept = default;
        intents_for_queue& operator=(intents_for_queue&&) noexcept = default;
    };

    struct references {
        internal::intent_reference::container_type list;

        references(references&& o) noexcept : list(std::move(o.list)) {}
        references() noexcept : list() {}
        ~references() { clear(); }

        void clear() {
            list.clear_and_dispose([] (internal::intent_reference* r) { r->on_cancel(); });
        }

        void bind(internal::intent_reference& iref) noexcept {
            list.push_back(iref);
        }
    };

    boost::container::small_vector<intents_for_queue, 1> _intents;
    references _refs;
    friend internal::intent_reference::intent_reference(io_intent*) noexcept;

public:
    io_intent() = default;
    ~io_intent() = default;

    io_intent(const io_intent&) = delete;
    io_intent& operator=(const io_intent&) = delete;
    io_intent& operator=(io_intent&&) = delete;
    io_intent(io_intent&& o) noexcept : _intents(std::move(o._intents)), _refs(std::move(o._refs)) {
        for (auto&& r : _refs.list) {
            r._intent = this;
        }
    }

    /// Explicitly cancels all the requests attached to this intent
    /// so far. The respective futures are resolved into the \ref
    /// cancelled_error "cancelled_error"
    void cancel() noexcept {
        _refs.clear();
        _intents.clear();
    }

    /// @private
    internal::cancellable_queue& find_or_create_cancellable_queue(dev_t dev, io_priority_class_id qid) {
        for (auto&& i : _intents) {
            if (i.dev == dev && i.qid == qid) {
                return i.cq;
            }
        }

        _intents.emplace_back(dev, qid);
        return _intents.back().cq;
    }
};

} // namespace seastar
<commit_msg>intent: drop unused headers<commit_after>/*
 * This file is open source software, licensed to you under the terms
 * of the Apache License, Version 2.0 (the "License").  See the NOTICE file
 * distributed with this work for additional information regarding copyright
 * ownership.  You may not use this file except in compliance with the License.
 *
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
/*
 * Copyright 2021 ScyllaDB
 */

#pragma once

#include <boost/container/small_vector.hpp>
#include <seastar/core/internal/io_intent.hh>
#include <seastar/core/io_priority_class.hh>

namespace seastar {

/// \example file_demo.cc
/// A handle confirming the caller's intent to do the IO
///
/// When a pointer to an intent is passed to the \ref io_queue
/// "io_queue"::queue_request() method, the issued request is pinned
/// to the intent and is only processed as long as the intent object
/// is alive and the **cancel()** method is not called.
///
/// If no intent is provided, then the request is processed till its
/// completion be it success or error
class io_intent {
    struct intents_for_queue {
        dev_t dev;
        io_priority_class_id qid;
        internal::cancellable_queue cq;

        intents_for_queue(dev_t dev_, io_priority_class_id qid_) noexcept
            : dev(dev_), qid(qid_), cq() {}

        intents_for_queue(intents_for_queue&&) noexcept = default;
        intents_for_queue& operator=(intents_for_queue&&) noexcept = default;
    };

    struct references {
        internal::intent_reference::container_type list;

        references(references&& o) noexcept : list(std::move(o.list)) {}
        references() noexcept : list() {}
        ~references() { clear(); }

        void clear() {
            list.clear_and_dispose([] (internal::intent_reference* r) { r->on_cancel(); });
        }

        void bind(internal::intent_reference& iref) noexcept {
            list.push_back(iref);
        }
    };

    boost::container::small_vector<intents_for_queue, 1> _intents;
    references _refs;
    friend internal::intent_reference::intent_reference(io_intent*) noexcept;

public:
    io_intent() = default;
    ~io_intent() = default;

    io_intent(const io_intent&) = delete;
    io_intent& operator=(const io_intent&) = delete;
    io_intent& operator=(io_intent&&) = delete;
    io_intent(io_intent&& o) noexcept : _intents(std::move(o._intents)), _refs(std::move(o._refs)) {
        for (auto&& r : _refs.list) {
            r._intent = this;
        }
    }

    /// Explicitly cancels all the requests attached to this intent
    /// so far. The respective futures are resolved into the \ref
    /// cancelled_error "cancelled_error"
    void cancel() noexcept {
        _refs.clear();
        _intents.clear();
    }

    /// @private
    internal::cancellable_queue& find_or_create_cancellable_queue(dev_t dev, io_priority_class_id qid) {
        for (auto&& i : _intents) {
            if (i.dev == dev && i.qid == qid) {
                return i.cq;
            }
        }

        _intents.emplace_back(dev, qid);
        return _intents.back().cq;
    }
};

} // namespace seastar
<|endoftext|>


<commit_before>/******************************************************************************
 * The MIT License (MIT)
 *
 * Copyright (c) 2019-2020 Baldur Karlsson
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 ******************************************************************************/

#include "CustomPaintWidget.h"
#include <math.h>
#include <QEvent>
#include <QPainter>
#include "Code/Interface/QRDInterface.h"

CustomPaintWidget::CustomPaintWidget(QWidget *parent) : QWidget(parent)
{
  m_Ctx = NULL;
  m_Output = NULL;
  setAttribute(Qt::WA_OpaquePaintEvent);
  setMouseTracking(true);
  m_Tag = QFormatStr("custompaint%1").arg((uintptr_t) this);
}

CustomPaintWidget::CustomPaintWidget(ICaptureContext *c, QWidget *parent) : QWidget(parent)
{
  m_Ctx = c;
  m_Output = NULL;
  setAttribute(Qt::WA_OpaquePaintEvent);
  if(c)
    setAttribute(Qt::WA_PaintOnScreen);
  setMouseTracking(true);
  m_Tag = QFormatStr("custompaint%1").arg((uintptr_t) this);
}

CustomPaintWidget::~CustomPaintWidget()
{
}

void CustomPaintWidget::mousePressEvent(QMouseEvent *e)
{
  emit clicked(e);
}

void CustomPaintWidget::mouseDoubleClickEvent(QMouseEvent *event)
{
  emit(doubleClicked(event));
}

void CustomPaintWidget::mouseMoveEvent(QMouseEvent *e)
{
  emit mouseMove(e);
}

void CustomPaintWidget::wheelEvent(QWheelEvent *e)
{
  emit mouseWheel(e);
}

void CustomPaintWidget::resizeEvent(QResizeEvent *e)
{
  emit resize(e);
}

void CustomPaintWidget::keyPressEvent(QKeyEvent *e)
{
  emit keyPress(e);
}

void CustomPaintWidget::keyReleaseEvent(QKeyEvent *e)
{
  emit keyRelease(e);
}

void CustomPaintWidget::paintEvent(QPaintEvent *e)
{
  if(m_Ctx)
  {
    if(m_Output != NULL)
    {
      QPointer<CustomPaintWidget> me(this);
      m_Ctx->Replay().AsyncInvoke(m_Tag, [me](IReplayController *r) {
        if(me && me->m_Output)
          me->m_Output->Display();
      });
    }
  }
  else if(m_Dark == m_Light)
  {
    QPainter p(this);
    p.fillRect(rect(), m_Dark);
  }
  else
  {
    int numX = (int)ceil((float)rect().width() / 64.0f);
    int numY = (int)ceil((float)rect().height() / 64.0f);

    QPainter p(this);
    for(int x = 0; x < numX; x++)
    {
      for(int y = 0; y < numY; y++)
      {
        QColor &col = ((x % 2) == (y % 2)) ? m_Dark : m_Light;

        p.fillRect(QRect(x * 64, y * 64, 64, 64), col);
      }
    }
  }
}

#if defined(RENDERDOC_PLATFORM_APPLE)
bool CustomPaintWidget::event(QEvent *e)
{
  if(m_Ctx && e->type() == QEvent::UpdateRequest)
    paintEvent(NULL);
  return QWidget::event(e);
}
#endif
<commit_msg>Fix #1898: Add missing QPointer include<commit_after>/******************************************************************************
 * The MIT License (MIT)
 *
 * Copyright (c) 2019-2020 Baldur Karlsson
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 ******************************************************************************/

#include "CustomPaintWidget.h"
#include <math.h>
#include <QEvent>
#include <QPainter>
#include <QPointer>
#include "Code/Interface/QRDInterface.h"

CustomPaintWidget::CustomPaintWidget(QWidget *parent) : QWidget(parent)
{
  m_Ctx = NULL;
  m_Output = NULL;
  setAttribute(Qt::WA_OpaquePaintEvent);
  setMouseTracking(true);
  m_Tag = QFormatStr("custompaint%1").arg((uintptr_t) this);
}

CustomPaintWidget::CustomPaintWidget(ICaptureContext *c, QWidget *parent) : QWidget(parent)
{
  m_Ctx = c;
  m_Output = NULL;
  setAttribute(Qt::WA_OpaquePaintEvent);
  if(c)
    setAttribute(Qt::WA_PaintOnScreen);
  setMouseTracking(true);
  m_Tag = QFormatStr("custompaint%1").arg((uintptr_t) this);
}

CustomPaintWidget::~CustomPaintWidget()
{
}

void CustomPaintWidget::mousePressEvent(QMouseEvent *e)
{
  emit clicked(e);
}

void CustomPaintWidget::mouseDoubleClickEvent(QMouseEvent *event)
{
  emit(doubleClicked(event));
}

void CustomPaintWidget::mouseMoveEvent(QMouseEvent *e)
{
  emit mouseMove(e);
}

void CustomPaintWidget::wheelEvent(QWheelEvent *e)
{
  emit mouseWheel(e);
}

void CustomPaintWidget::resizeEvent(QResizeEvent *e)
{
  emit resize(e);
}

void CustomPaintWidget::keyPressEvent(QKeyEvent *e)
{
  emit keyPress(e);
}

void CustomPaintWidget::keyReleaseEvent(QKeyEvent *e)
{
  emit keyRelease(e);
}

void CustomPaintWidget::paintEvent(QPaintEvent *e)
{
  if(m_Ctx)
  {
    if(m_Output != NULL)
    {
      QPointer<CustomPaintWidget> me(this);
      m_Ctx->Replay().AsyncInvoke(m_Tag, [me](IReplayController *r) {
        if(me && me->m_Output)
          me->m_Output->Display();
      });
    }
  }
  else if(m_Dark == m_Light)
  {
    QPainter p(this);
    p.fillRect(rect(), m_Dark);
  }
  else
  {
    int numX = (int)ceil((float)rect().width() / 64.0f);
    int numY = (int)ceil((float)rect().height() / 64.0f);

    QPainter p(this);
    for(int x = 0; x < numX; x++)
    {
      for(int y = 0; y < numY; y++)
      {
        QColor &col = ((x % 2) == (y % 2)) ? m_Dark : m_Light;

        p.fillRect(QRect(x * 64, y * 64, 64, 64), col);
      }
    }
  }
}

#if defined(RENDERDOC_PLATFORM_APPLE)
bool CustomPaintWidget::event(QEvent *e)
{
  if(m_Ctx && e->type() == QEvent::UpdateRequest)
    paintEvent(NULL);
  return QWidget::event(e);
}
#endif
<|endoftext|>


<commit_before>/*
 *  RecursiveFilter.cpp
 *
 * Copyright 2011 Michael Bell
 *  All rights reserved.
 *
 */

#include "RecursiveFilter.h"
#include <iostream>
#include <cmath>

RecursiveFilter::RecursiveFilter(const int& fOrder, const int& fLengthScale)
{

	// Create a filter based on the specified order and lengthscale
	order = fOrder;
	lengthScale = fLengthScale;
	getFilterCoefficients();

}

RecursiveFilter::~RecursiveFilter()
{
}

void RecursiveFilter::getFilterCoefficients()
{
	real sigma = (lengthScale*lengthScale)/2;
	real b[5][5];
	real a[201][201];
	real p[201];
	real K[9];
	real D[9];

	// b coefficients
	b[1][1] = 1;
	b[1][2] = 1/12;
	b[1][3] = 1/90;
	b[1][4] = 1/560;
	b[2][2] = 1;
	b[2][3] = 1/6;
	b[2][4] = 7/240;
	b[3][3] = 1;
	b[3][4] = 1/4;
	b[4][4] = 1;

    // Compute polynomial coefficients
	K[2] = b[1][1]*sigma;
	K[4] = b[1][2]*sigma + b[2][2]*(pow(sigma,2))/factorial(2);
	K[6] = b[1][3]*sigma + b[2][3]*(pow(sigma,2))/factorial(2)
		+ b[3][3]*(pow(sigma,3))/factorial(3);
	K[8] = b[1][4]*sigma + b[2][4]*(pow(sigma,2))/factorial(2)
		+ b[3][4]*(pow(sigma,3))/factorial(3) + b[4][4]*(pow(sigma,4))/factorial(4);

	for (int i=0;i<=order*2;i++) {
		D[i] = 0;
	}

	for (int n=2;n<=order*2;n+=2) {
		for (int i=0;i<=n;i++) {
			int index = n/2 - i;
			real coeff = (pow((-1),(n/2)))*(pow((-1),i))*factorial(n)/(factorial(n-i)*factorial(i));
			D[index+order] += K[n]*coeff;
		}
	}
	D[order] += 1;

	for (int i=0;i<=200;i++) {
		for (int j=0;j<=200;j++) {
			if (abs(j-i) <= order) {
				a[i][j] = D[j-i+order];
			} else {
				a[i][j] = 0;
			}
		}
	}

	// Cholesky decomp
	for (int i=0;i<=200;i++) {
		for (int j=0;j<=200;j++) {
			real sum=a[i][j];
			for (int k=i-1;k>=0;k--) {
				sum -= a[i][k]*a[j][k];
			}
			if (i == j) {
				if (sum <= 0.0) {
					std::cout << "cholesky failed at i,j sum\n";
					break;
				} else {
					p[i] = sqrt(sum);
				}
			} else {
				a[j][i]=sum/p[i];
			}
		}
	}
	beta = 1/p[200];
	alpha[1]=-beta*a[200][199];
	if (order > 1) {
		alpha[2]=-beta*a[200][198];
	} else {
		alpha[2]=0;
	}
	if (order > 2) {
		alpha[3]=-beta*a[200][197];
	} else {
		alpha[3]=0;
	}
	if (order > 3) {
		alpha[4]=-beta*a[200][196];
	} else {
		alpha[4]=0;
	}

	std::cout << "4th Order Recursive Filter coefficients computed for lengthscale "
		<< lengthScale << " Delta R" << std::endl;
	std::cout << "\tBeta: " << beta << std::endl;
	std::cout << "\tAlpha[1]: " << alpha[1] << std::endl;
	std::cout << "\tAlpha[2]: " << alpha[2] << std::endl;
	std::cout << "\tAlpha[3]: " << alpha[3] << std::endl;
	std::cout << "\tAlpha[4]: " << alpha[4] << std::endl;

	// Boundary conditions
	real L[5][5];
	real U[5][5];
	real LT[5][5];
	real UT[5][5];
	real LI[5][5];
	real col[5];
	real colinv[5];

	for (int i=1;i<=order;i++) {
		for (int j=1;j<=order;j++) {
			L[i][j]=0.;
			U[i][j]=0.;
		}
	}

	for (int i=1;i<=order;i++) {
		for (int j=0;j<=order;j++) {
			int index = i+j;
			if (index <= order) {
				L[i+j][i] = -alpha[j];
				U[i][i+j] = alpha[order-j];
			}
		}
		L[i][i] = 1.;
	}

	// Invert L
	for (int j=1;j<=order;j++) {
		for (int i=1;i<=order;i++) { col[i] = 0.0; }
		col[j] = 1;
		colinv[0] = col[0];
		for (int i=1;i<=order;i++) {
			colinv[i] = col[i];
			for (int k=i-1;k>=1;k--) {
				colinv[i] -= L[i][k]*colinv[k];
			}
		}
		for (int i=1;i<=order;i++) {
			LI[i][j] = colinv[i];
		}
	}

	// Transpose L & T
	for (int i=1;i<=order;i++) {
		for (int j=1;j<=order;j++) {
			LT[i][j] = L[j][i];
			UT[i][j] = U[j][i];
		}
	}

	// Get Sn matrix
	real tmp[5][5];
	real tmp2[5][5];
	for (int i=1;i<=order;i++) {
		for (int j=1;j<=order;j++) {
			tmp[i][j] = 0.;
			for (int k=1;k<=order;k++) {
				tmp[i][j] += UT[i][k]*LI[k][j];
			}
		}
	}
	for (int i=1;i<=order;i++) {
		for (int j=1;j<=order;j++) {
			tmp2[i][j] = 0.;
			for (int k=1;k<=order;k++) {
				tmp2[i][j] += tmp[i][k]*U[k][j];
			}
		}
	}

	for (int i=1;i<=order;i++) {
		for (int j=1;j<=order;j++) {
			Sn[i-1][j-1] = (LT[i][j] - tmp2[i][j])/beta;
		}
	}

}

bool RecursiveFilter::filterArray(real* array, const int& arrLength)
{
	int maxi = arrLength-1;
	real* p = array;
	real* q = new real[arrLength];
	real* s = new real[arrLength];

	for (int i=0; i<= maxi; i++) {
		q[i] = 0;
		s[i] = 0;
	}

	q[0]=beta*p[0];
	q[1]=beta*p[1] + alpha[1]*q[0];
	q[2]=beta*p[2] + alpha[1]*q[1] + alpha[2]*q[0];
	q[3]=beta*p[3] + alpha[1]*q[2] + alpha[2]*q[1] + alpha[3]*q[0];
	for (int i=order; i<= maxi; i++) {
		q[i] = beta*p[i] + alpha[1]*q[i-1]
		+ alpha[2]*q[i-2] + alpha[3]*q[i-3] + alpha[4]*q[i-4];
	}

    // Invert Sn
	real* A = new real[4];
	real* B = new real[4];
	for (int i=maxi-order+1; i<= maxi; i++) {
		B[i-(maxi-order+1)] = q[i];
	}
	solveBC(A, B);
	for (int i=maxi; i>= (maxi-order+1); i--) {
		s[i] = A[i-(maxi-order+1)];
	}
	for (int i=maxi-order;i>=0;i--) {
		s[i] = beta*q[i] + alpha[1]*s[i+1]
		+ alpha[2]*s[i+2] + alpha[3]*s[i+3] + alpha[4]*s[i+4];
		// std::cout << s[i] << std::endl;
	}
	delete[] A;
	delete[] B;

	for (int i=0; i<= maxi; i++) {
		// To get a 'true' Gaussian, need to scale by this factor
		// To preserve total quantity (needed for Variational analysis)
		// Do not scale resulting vector
		//real Pi = 3.141592653589793238462643;
		//array[i] = s[i]*sqrt(2*Pi)*lengthScale;
		array[i] = s[i];
	}
	delete[] q;
	delete[] s;

	return true;

}

real RecursiveFilter::factorial(const real& max)
{
	real n = 1;
	for (real i=2;i<=max;i++) {
		n *= i;
	}
	return n;

}

void RecursiveFilter::solveBC(real* A, real*B)
{

	int n = order-1;
	for(int j=0;j<=n-1;j++) {
		for (int i=j+1;i<=n;i++) {
			Sn[i][j]=Sn[i][j]/Sn[j][j];
		}
		for	(int i=j+1;i<=n;i++) {
			for (int k=j+1;k<=n;k++) {
				Sn[i][k]=Sn[i][k]-Sn[i][j]*Sn[j][k];
			}
			B[i]=B[i]-Sn[i][j]*B[j];
		}
	}
	A[n]=B[n]/Sn[n][n];
	for(int j=n-1;j>=0;j--) {
		A[j]=B[j];
		for(int k=n;k>=j+1;k--) {
			A[j]=A[j]-A[k]*Sn[j][k];
		}
		A[j]=A[j]/Sn[j][j];
	}
}
<commit_msg>Fix abs command to use std::abs<commit_after>/*
 *  RecursiveFilter.cpp
 *
 * Copyright 2011 Michael Bell
 *  All rights reserved.
 *
 */

#include "RecursiveFilter.h"
#include <iostream>
#include <cmath>

RecursiveFilter::RecursiveFilter(const int& fOrder, const int& fLengthScale)
{

	// Create a filter based on the specified order and lengthscale
	order = fOrder;
	lengthScale = fLengthScale;
	getFilterCoefficients();

}

RecursiveFilter::~RecursiveFilter()
{
}

void RecursiveFilter::getFilterCoefficients()
{
	real sigma = (lengthScale*lengthScale)/2;
	real b[5][5];
	real a[201][201];
	real p[201];
	real K[9];
	real D[9];

	// b coefficients
	b[1][1] = 1;
	b[1][2] = 1/12;
	b[1][3] = 1/90;
	b[1][4] = 1/560;
	b[2][2] = 1;
	b[2][3] = 1/6;
	b[2][4] = 7/240;
	b[3][3] = 1;
	b[3][4] = 1/4;
	b[4][4] = 1;

    // Compute polynomial coefficients
	K[2] = b[1][1]*sigma;
	K[4] = b[1][2]*sigma + b[2][2]*(pow(sigma,2))/factorial(2);
	K[6] = b[1][3]*sigma + b[2][3]*(pow(sigma,2))/factorial(2)
		+ b[3][3]*(pow(sigma,3))/factorial(3);
	K[8] = b[1][4]*sigma + b[2][4]*(pow(sigma,2))/factorial(2)
		+ b[3][4]*(pow(sigma,3))/factorial(3) + b[4][4]*(pow(sigma,4))/factorial(4);

	for (int i=0;i<=order*2;i++) {
		D[i] = 0;
	}

	for (int n=2;n<=order*2;n+=2) {
		for (int i=0;i<=n;i++) {
			int index = n/2 - i;
			real coeff = (pow((-1),(n/2)))*(pow((-1),i))*factorial(n)/(factorial(n-i)*factorial(i));
			D[index+order] += K[n]*coeff;
		}
	}
	D[order] += 1;

	for (int i=0;i<=200;i++) {
		for (int j=0;j<=200;j++) {
			if (std::abs((double)(j-i)) <= order) {
				a[i][j] = D[j-i+order];
			} else {
				a[i][j] = 0;
			}
		}
	}

	// Cholesky decomp
	for (int i=0;i<=200;i++) {
		for (int j=0;j<=200;j++) {
			real sum=a[i][j];
			for (int k=i-1;k>=0;k--) {
				sum -= a[i][k]*a[j][k];
			}
			if (i == j) {
				if (sum <= 0.0) {
					std::cout << "cholesky failed at i,j sum\n";
					break;
				} else {
					p[i] = sqrt(sum);
				}
			} else {
				a[j][i]=sum/p[i];
			}
		}
	}
	beta = 1/p[200];
	alpha[1]=-beta*a[200][199];
	if (order > 1) {
		alpha[2]=-beta*a[200][198];
	} else {
		alpha[2]=0;
	}
	if (order > 2) {
		alpha[3]=-beta*a[200][197];
	} else {
		alpha[3]=0;
	}
	if (order > 3) {
		alpha[4]=-beta*a[200][196];
	} else {
		alpha[4]=0;
	}

	std::cout << "4th Order Recursive Filter coefficients computed for lengthscale "
		<< lengthScale << " Delta R" << std::endl;
	std::cout << "\tBeta: " << beta << std::endl;
	std::cout << "\tAlpha[1]: " << alpha[1] << std::endl;
	std::cout << "\tAlpha[2]: " << alpha[2] << std::endl;
	std::cout << "\tAlpha[3]: " << alpha[3] << std::endl;
	std::cout << "\tAlpha[4]: " << alpha[4] << std::endl;

	// Boundary conditions
	real L[5][5];
	real U[5][5];
	real LT[5][5];
	real UT[5][5];
	real LI[5][5];
	real col[5];
	real colinv[5];

	for (int i=1;i<=order;i++) {
		for (int j=1;j<=order;j++) {
			L[i][j]=0.;
			U[i][j]=0.;
		}
	}

	for (int i=1;i<=order;i++) {
		for (int j=0;j<=order;j++) {
			int index = i+j;
			if (index <= order) {
				L[i+j][i] = -alpha[j];
				U[i][i+j] = alpha[order-j];
			}
		}
		L[i][i] = 1.;
	}

	// Invert L
	for (int j=1;j<=order;j++) {
		for (int i=1;i<=order;i++) { col[i] = 0.0; }
		col[j] = 1;
		colinv[0] = col[0];
		for (int i=1;i<=order;i++) {
			colinv[i] = col[i];
			for (int k=i-1;k>=1;k--) {
				colinv[i] -= L[i][k]*colinv[k];
			}
		}
		for (int i=1;i<=order;i++) {
			LI[i][j] = colinv[i];
		}
	}

	// Transpose L & T
	for (int i=1;i<=order;i++) {
		for (int j=1;j<=order;j++) {
			LT[i][j] = L[j][i];
			UT[i][j] = U[j][i];
		}
	}

	// Get Sn matrix
	real tmp[5][5];
	real tmp2[5][5];
	for (int i=1;i<=order;i++) {
		for (int j=1;j<=order;j++) {
			tmp[i][j] = 0.;
			for (int k=1;k<=order;k++) {
				tmp[i][j] += UT[i][k]*LI[k][j];
			}
		}
	}
	for (int i=1;i<=order;i++) {
		for (int j=1;j<=order;j++) {
			tmp2[i][j] = 0.;
			for (int k=1;k<=order;k++) {
				tmp2[i][j] += tmp[i][k]*U[k][j];
			}
		}
	}

	for (int i=1;i<=order;i++) {
		for (int j=1;j<=order;j++) {
			Sn[i-1][j-1] = (LT[i][j] - tmp2[i][j])/beta;
		}
	}

}

bool RecursiveFilter::filterArray(real* array, const int& arrLength)
{
	int maxi = arrLength-1;
	real* p = array;
	real* q = new real[arrLength];
	real* s = new real[arrLength];

	for (int i=0; i<= maxi; i++) {
		q[i] = 0;
		s[i] = 0;
	}

	q[0]=beta*p[0];
	q[1]=beta*p[1] + alpha[1]*q[0];
	q[2]=beta*p[2] + alpha[1]*q[1] + alpha[2]*q[0];
	q[3]=beta*p[3] + alpha[1]*q[2] + alpha[2]*q[1] + alpha[3]*q[0];
	for (int i=order; i<= maxi; i++) {
		q[i] = beta*p[i] + alpha[1]*q[i-1]
		+ alpha[2]*q[i-2] + alpha[3]*q[i-3] + alpha[4]*q[i-4];
	}

    // Invert Sn
	real* A = new real[4];
	real* B = new real[4];
	for (int i=maxi-order+1; i<= maxi; i++) {
		B[i-(maxi-order+1)] = q[i];
	}
	solveBC(A, B);
	for (int i=maxi; i>= (maxi-order+1); i--) {
		s[i] = A[i-(maxi-order+1)];
	}
	for (int i=maxi-order;i>=0;i--) {
		s[i] = beta*q[i] + alpha[1]*s[i+1]
		+ alpha[2]*s[i+2] + alpha[3]*s[i+3] + alpha[4]*s[i+4];
		// std::cout << s[i] << std::endl;
	}
	delete[] A;
	delete[] B;

	for (int i=0; i<= maxi; i++) {
		// To get a 'true' Gaussian, need to scale by this factor
		// To preserve total quantity (needed for Variational analysis)
		// Do not scale resulting vector
		//real Pi = 3.141592653589793238462643;
		//array[i] = s[i]*sqrt(2*Pi)*lengthScale;
		array[i] = s[i];
	}
	delete[] q;
	delete[] s;

	return true;

}

real RecursiveFilter::factorial(const real& max)
{
	real n = 1;
	for (real i=2;i<=max;i++) {
		n *= i;
	}
	return n;

}

void RecursiveFilter::solveBC(real* A, real*B)
{

	int n = order-1;
	for(int j=0;j<=n-1;j++) {
		for (int i=j+1;i<=n;i++) {
			Sn[i][j]=Sn[i][j]/Sn[j][j];
		}
		for	(int i=j+1;i<=n;i++) {
			for (int k=j+1;k<=n;k++) {
				Sn[i][k]=Sn[i][k]-Sn[i][j]*Sn[j][k];
			}
			B[i]=B[i]-Sn[i][j]*B[j];
		}
	}
	A[n]=B[n]/Sn[n][n];
	for(int j=n-1;j>=0;j--) {
		A[j]=B[j];
		for(int k=n;k>=j+1;k--) {
			A[j]=A[j]-A[k]*Sn[j][k];
		}
		A[j]=A[j]/Sn[j][j];
	}
}
<|endoftext|>


<commit_before>#include "kwm.h"

extern uint32_t MaxDisplayCount;
extern uint32_t ActiveDisplaysCount;
extern CGDirectDisplayID ActiveDisplays[];

extern screen_info *Screen;
extern int CurrentSpace;

extern std::map<unsigned int, screen_info> DisplayMap;
extern std::vector<window_info> WindowLst;
extern std::vector<window_info> FloatingAppLst;
extern window_info *FocusedWindow;

extern int DefaultPaddingLeft, DefaultPaddingRight;
extern int DefaultPaddingTop, DefaultPaddingBottom;
extern int DefaultGapVertical, DefaultGapHorizontal;

void DisplayReconfigurationCallBack(CGDirectDisplayID Display, CGDisplayChangeSummaryFlags Flags, void *UserInfo)
{
    if (Flags & kCGDisplayAddFlag)
    {
        // display has been added
        DEBUG("New display detected!")
    }
    else if (Flags & kCGDisplayRemoveFlag)
    {
        // display has been removed
        DEBUG("Display has been removed!")
    }
}

void GetActiveDisplays()
{
    CGGetActiveDisplayList(MaxDisplayCount, (CGDirectDisplayID*)&ActiveDisplays, &ActiveDisplaysCount);
    for(int DisplayIndex = 0; DisplayIndex < ActiveDisplaysCount; ++DisplayIndex)
    {
        CGRect DisplayRect = CGDisplayBounds(ActiveDisplays[DisplayIndex]);
        unsigned int DisplayID = ActiveDisplays[DisplayIndex];

        screen_info Screen;
        Screen.ID = DisplayIndex;
        Screen.ForceContainerUpdate = false;
        Screen.ActiveSpace = -1;
        Screen.OldWindowListCount = -1;

        Screen.X = DisplayRect.origin.x;
        Screen.Y = DisplayRect.origin.y;
        Screen.Width = DisplayRect.size.width;
        Screen.Height = DisplayRect.size.height;

        Screen.PaddingTop = DefaultPaddingTop;
        Screen.PaddingLeft = DefaultPaddingLeft;
        Screen.PaddingRight = DefaultPaddingRight;
        Screen.PaddingBottom = DefaultPaddingBottom;

        Screen.VerticalGap = DefaultGapVertical;
        Screen.HorizontalGap = DefaultGapHorizontal;

        DisplayMap[DisplayID] = Screen;
    }

    Screen = GetDisplayOfMousePointer();
    CGDisplayRegisterReconfigurationCallback(DisplayReconfigurationCallBack, NULL);
}

screen_info *GetDisplayFromScreenID(int ID)
{
    std::map<unsigned int, screen_info>::iterator It;
    for(It = DisplayMap.begin(); It != DisplayMap.end(); ++It)
    {
        screen_info *Screen = &It->second;
        if(Screen->ID == ID)
            return Screen;
    }

    return NULL;
}

screen_info *GetDisplayOfMousePointer()
{
    CGEventRef Event = CGEventCreate(NULL);
    CGPoint Cursor = CGEventGetLocation(Event);
    CFRelease(Event);

    std::map<unsigned int, screen_info>::iterator It;
    for(It = DisplayMap.begin(); It != DisplayMap.end(); ++It)
    {
        screen_info *Screen = &It->second;
        if(Cursor.x >= Screen->X && Cursor.x <= Screen->X + Screen->Width &&
           Cursor.y >= Screen->Y && Cursor.y <= Screen->Y + Screen->Height)
               return Screen;
    }

    return NULL;
}

screen_info *GetDisplayOfWindow(window_info *Window)
{
    if(Window)
    {
        std::map<unsigned int, screen_info>::iterator It;
        for(It = DisplayMap.begin(); It != DisplayMap.end(); ++It)
        {
            screen_info *Screen = &It->second;
            if(Window->X >= Screen->X && Window->X <= Screen->X + Screen->Width)
                return Screen;
        }
    }

    return NULL;
}

std::vector<window_info*> GetAllWindowsOnDisplay(int ScreenIndex)
{
    screen_info *Screen = GetDisplayFromScreenID(ScreenIndex);
    std::vector<window_info*> ScreenWindowLst;
    for(int WindowIndex = 0; WindowIndex < WindowLst.size(); ++WindowIndex)
    {
        window_info *Window = &WindowLst[WindowIndex];
        if(!IsApplicationFloating(&WindowLst[WindowIndex]))
        {
            if(Window->X >= Screen->X && Window->X <= Screen->X + Screen->Width)
                ScreenWindowLst.push_back(Window);
        }
    }

    return ScreenWindowLst;
}

std::vector<int> GetAllWindowIDsOnDisplay(int ScreenIndex)
{
    screen_info *Screen = GetDisplayFromScreenID(ScreenIndex);
    std::vector<int> ScreenWindowIDLst;
    for(int WindowIndex = 0; WindowIndex < WindowLst.size(); ++WindowIndex)
    {
        window_info *Window = &WindowLst[WindowIndex];
        if(!IsApplicationFloating(&WindowLst[WindowIndex]))
        {
            if(Window->X >= Screen->X && Window->X <= Screen->X + Screen->Width)
                ScreenWindowIDLst.push_back(Window->WID);
        }
    }

    return ScreenWindowIDLst;
}

void SetDefaultPaddingOfDisplay(const std::string &Side, int Offset)
{
    if(Side == "left")
        DefaultPaddingLeft = Offset;
    else if(Side == "right")
        DefaultPaddingRight = Offset;
    else if(Side == "top")
        DefaultPaddingTop = Offset;
    else if(Side == "bottom")
        DefaultPaddingBottom = Offset;
}

void SetDefaultGapOfDisplay(const std::string &Side, int Offset)
{
    if(Side == "vertical")
        DefaultGapVertical = Offset;
    else if(Side == "horizontal")
        DefaultGapHorizontal = Offset;
}

void ChangePaddingOfDisplay(const std::string &Side, int Offset)
{
    screen_info *Screen = GetDisplayOfMousePointer();
    if(Side == "left")
        Screen->Space[CurrentSpace].PaddingLeft += Offset;
    else if(Side == "right")
        Screen->Space[CurrentSpace].PaddingRight += Offset;
    else if(Side == "top")
        Screen->Space[CurrentSpace].PaddingTop += Offset;
    else if(Side == "bottom")
        Screen->Space[CurrentSpace].PaddingBottom += Offset;

    SetRootNodeContainer(Screen, Screen->Space[CurrentSpace].RootNode);
    CreateNodeContainers(Screen, Screen->Space[CurrentSpace].RootNode, true);
    ApplyNodeContainer(Screen->Space[CurrentSpace].RootNode);
}

void ChangeGapOfDisplay(const std::string &Side, int Offset)
{
    screen_info *Screen = GetDisplayOfMousePointer();
    if(Side == "vertical")
        Screen->Space[CurrentSpace].VerticalGap += Offset;
    else if(Side == "horizontal")
        Screen->Space[CurrentSpace].HorizontalGap += Offset;

    CreateNodeContainers(Screen, Screen->Space[CurrentSpace].RootNode, true);
    ApplyNodeContainer(Screen->Space[CurrentSpace].RootNode);
}

void CycleFocusedWindowDisplay(int Shift)
{
    screen_info *Screen = GetDisplayOfWindow(FocusedWindow);
    int NewScreenIndex = -1;

    if(Shift == 1)
        NewScreenIndex = (Screen->ID + 1 >= ActiveDisplaysCount) ? 0 : Screen->ID + 1;
    else if(Shift == -1)
        NewScreenIndex = (Screen->ID - 1 < 0) ? ActiveDisplaysCount - 1 : Screen->ID - 1;

    if(NewScreenIndex != Screen->ID)
    {
        screen_info *NewScreen = GetDisplayFromScreenID(NewScreenIndex);
        AddWindowToTreeOfUnfocusedMonitor(NewScreen);
    }
}
<commit_msg>kwm must no longer be restarted when a monitor is connected / disconnected<commit_after>#include "kwm.h"

extern uint32_t MaxDisplayCount;
extern uint32_t ActiveDisplaysCount;
extern CGDirectDisplayID ActiveDisplays[];

extern screen_info *Screen;
extern int CurrentSpace;

extern std::map<unsigned int, screen_info> DisplayMap;
extern std::vector<window_info> WindowLst;
extern std::vector<window_info> FloatingAppLst;
extern window_info *FocusedWindow;

extern int DefaultPaddingLeft, DefaultPaddingRight;
extern int DefaultPaddingTop, DefaultPaddingBottom;
extern int DefaultGapVertical, DefaultGapHorizontal;

void DisplayReconfigurationCallBack(CGDirectDisplayID Display, CGDisplayChangeSummaryFlags Flags, void *UserInfo)
{
    if (Flags & kCGDisplayAddFlag)
    {
        // display has been added
        DisplayMap[Display] = CreateDefaultScreenInfo(Display, ActiveDisplaysCount++);
        DEBUG("New display detected!")
    }
    else if (Flags & kCGDisplayRemoveFlag)
    {
        // display has been removed
        DisplayMap.erase(Display);
        DEBUG("Display has been removed!")
    }
}

screen_info CreateDefaultScreenInfo(int DisplayIndex, int ScreenIndex)
{
    CGRect DisplayRect = CGDisplayBounds(DisplayIndex);
    screen_info Screen;

    Screen.ID = ScreenIndex;
    Screen.ForceContainerUpdate = false;
    Screen.ActiveSpace = -1;
    Screen.OldWindowListCount = -1;

    Screen.X = DisplayRect.origin.x;
    Screen.Y = DisplayRect.origin.y;
    Screen.Width = DisplayRect.size.width;
    Screen.Height = DisplayRect.size.height;

    Screen.PaddingTop = DefaultPaddingTop;
    Screen.PaddingLeft = DefaultPaddingLeft;
    Screen.PaddingRight = DefaultPaddingRight;
    Screen.PaddingBottom = DefaultPaddingBottom;

    Screen.VerticalGap = DefaultGapVertical;
    Screen.HorizontalGap = DefaultGapHorizontal;

    return Screen;
}

void GetActiveDisplays()
{
    CGGetActiveDisplayList(MaxDisplayCount, (CGDirectDisplayID*)&ActiveDisplays, &ActiveDisplaysCount);
    for(int DisplayIndex = 0; DisplayIndex < ActiveDisplaysCount; ++DisplayIndex)
    {
        unsigned int DisplayID = ActiveDisplays[DisplayIndex];
        DisplayMap[DisplayID] = CreateDefaultScreenInfo(DisplayID, DisplayIndex);;
    }

    Screen = GetDisplayOfMousePointer();
    CGDisplayRegisterReconfigurationCallback(DisplayReconfigurationCallBack, NULL);
}

screen_info *GetDisplayFromScreenID(int ID)
{
    std::map<unsigned int, screen_info>::iterator It;
    for(It = DisplayMap.begin(); It != DisplayMap.end(); ++It)
    {
        screen_info *Screen = &It->second;
        if(Screen->ID == ID)
            return Screen;
    }

    return NULL;
}

screen_info *GetDisplayOfMousePointer()
{
    CGEventRef Event = CGEventCreate(NULL);
    CGPoint Cursor = CGEventGetLocation(Event);
    CFRelease(Event);

    std::map<unsigned int, screen_info>::iterator It;
    for(It = DisplayMap.begin(); It != DisplayMap.end(); ++It)
    {
        screen_info *Screen = &It->second;
        if(Cursor.x >= Screen->X && Cursor.x <= Screen->X + Screen->Width &&
           Cursor.y >= Screen->Y && Cursor.y <= Screen->Y + Screen->Height)
               return Screen;
    }

    return NULL;
}

screen_info *GetDisplayOfWindow(window_info *Window)
{
    if(Window)
    {
        std::map<unsigned int, screen_info>::iterator It;
        for(It = DisplayMap.begin(); It != DisplayMap.end(); ++It)
        {
            screen_info *Screen = &It->second;
            if(Window->X >= Screen->X && Window->X <= Screen->X + Screen->Width)
                return Screen;
        }
    }

    return NULL;
}

std::vector<window_info*> GetAllWindowsOnDisplay(int ScreenIndex)
{
    screen_info *Screen = GetDisplayFromScreenID(ScreenIndex);
    std::vector<window_info*> ScreenWindowLst;
    for(int WindowIndex = 0; WindowIndex < WindowLst.size(); ++WindowIndex)
    {
        window_info *Window = &WindowLst[WindowIndex];
        if(!IsApplicationFloating(&WindowLst[WindowIndex]))
        {
            if(Window->X >= Screen->X && Window->X <= Screen->X + Screen->Width)
                ScreenWindowLst.push_back(Window);
        }
    }

    return ScreenWindowLst;
}

std::vector<int> GetAllWindowIDsOnDisplay(int ScreenIndex)
{
    screen_info *Screen = GetDisplayFromScreenID(ScreenIndex);
    std::vector<int> ScreenWindowIDLst;
    for(int WindowIndex = 0; WindowIndex < WindowLst.size(); ++WindowIndex)
    {
        window_info *Window = &WindowLst[WindowIndex];
        if(!IsApplicationFloating(&WindowLst[WindowIndex]))
        {
            if(Window->X >= Screen->X && Window->X <= Screen->X + Screen->Width)
                ScreenWindowIDLst.push_back(Window->WID);
        }
    }

    return ScreenWindowIDLst;
}

void SetDefaultPaddingOfDisplay(const std::string &Side, int Offset)
{
    if(Side == "left")
        DefaultPaddingLeft = Offset;
    else if(Side == "right")
        DefaultPaddingRight = Offset;
    else if(Side == "top")
        DefaultPaddingTop = Offset;
    else if(Side == "bottom")
        DefaultPaddingBottom = Offset;
}

void SetDefaultGapOfDisplay(const std::string &Side, int Offset)
{
    if(Side == "vertical")
        DefaultGapVertical = Offset;
    else if(Side == "horizontal")
        DefaultGapHorizontal = Offset;
}

void ChangePaddingOfDisplay(const std::string &Side, int Offset)
{
    screen_info *Screen = GetDisplayOfMousePointer();
    if(Side == "left")
        Screen->Space[CurrentSpace].PaddingLeft += Offset;
    else if(Side == "right")
        Screen->Space[CurrentSpace].PaddingRight += Offset;
    else if(Side == "top")
        Screen->Space[CurrentSpace].PaddingTop += Offset;
    else if(Side == "bottom")
        Screen->Space[CurrentSpace].PaddingBottom += Offset;

    SetRootNodeContainer(Screen, Screen->Space[CurrentSpace].RootNode);
    CreateNodeContainers(Screen, Screen->Space[CurrentSpace].RootNode, true);
    ApplyNodeContainer(Screen->Space[CurrentSpace].RootNode);
}

void ChangeGapOfDisplay(const std::string &Side, int Offset)
{
    screen_info *Screen = GetDisplayOfMousePointer();
    if(Side == "vertical")
        Screen->Space[CurrentSpace].VerticalGap += Offset;
    else if(Side == "horizontal")
        Screen->Space[CurrentSpace].HorizontalGap += Offset;

    CreateNodeContainers(Screen, Screen->Space[CurrentSpace].RootNode, true);
    ApplyNodeContainer(Screen->Space[CurrentSpace].RootNode);
}

void CycleFocusedWindowDisplay(int Shift)
{
    screen_info *Screen = GetDisplayOfWindow(FocusedWindow);
    int NewScreenIndex = -1;

    if(Shift == 1)
        NewScreenIndex = (Screen->ID + 1 >= ActiveDisplaysCount) ? 0 : Screen->ID + 1;
    else if(Shift == -1)
        NewScreenIndex = (Screen->ID - 1 < 0) ? ActiveDisplaysCount - 1 : Screen->ID - 1;

    if(NewScreenIndex != Screen->ID)
    {
        screen_info *NewScreen = GetDisplayFromScreenID(NewScreenIndex);
        AddWindowToTreeOfUnfocusedMonitor(NewScreen);
    }
}
<|endoftext|>


<commit_before>#include "jakmuse_common.h"

#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <cctype>
#include <cmath>
#include <cassert>

#include <iostream>
#include <string>

static signed translate_note(char name)
{
    switch(name) {
    case 'C': return 0;
    case 'D': return 2;
    case 'E': return 4;
    case 'F': return 5;
    case 'G': return 7;
    case 'A': return 9;
    case 'B': return 11;
    default: abort();
    }
}

static unsigned short get_frequency(char name, signed scale, char accidental)
{
    signed Ascale = 4;
    signed A = 9;
    signed note = translate_note(name);

    signed step = (scale - Ascale) * 12 + note - A;

    switch(accidental) {
    case '#':
        ++step;
        break;
    case 'b':
        --step;
        break;
    default:
        break;
    }

    return (unsigned short)(440.0f * std::pow(2.0f, (float)step / 12.0f));
}

static bool isnote(char c)
{
    static char notes[] = "CDEFGAB";
    return strchr(notes, c) != NULL;
}

void parse()
{
    while(!std::cin.eof()) {
        // get channel
        unsigned channel(255);
        std::cin >> channel;
        if(!std::cin.good()) break;
        assert(channel < 5);
        // get fill factor
        unsigned fill(128);
        std::cin >> fill;
        // get scale factor
        unsigned scale(1);
        std::cin >> scale;
        assert(scale);
        // start reading notes
        std::string s;
        do {
            std::cin >> s;
            if(s.empty() || s.compare(";") == 0) break;

            size_t i = 0;
            size_t const ns = s.size();

            int length = 0;
            do {
                if(i >= ns || !isdigit(s[i])) break;
                length *= 10;
                length += s[i++] - '0';
            } while(1);
            assert(length);
            assert(i < ns);

            char note = s[i++];
            unsigned short frequency(0);

            if(isnote(note)) {
                assert(i < ns);
                char accidental = '\0';
                if(s[i] == '#' || s[i] == 'b') {
                    accidental = s[i++];
                }
                assert(i < ns);

                signed offset = 0;
                do {
                    if(i >= ns || !isdigit(s[i])) break;
                    offset *= 10;
                    offset += s[i++] - '0';
                } while(1);
                assert(i >= ns);

                frequency = get_frequency(note, offset, accidental);
            }

            for(size_t i = 0; i < length * scale; ++i) {
                pwm el = { frequency, fill };
                g_channels[channel].push_back(el);
            }

            g_maxChannelLen = std::max(g_maxChannelLen, g_channels[channel].size());
        } while(1);
    }
}
<commit_msg>parser tells you things<commit_after>#include "jakmuse_common.h"

#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <cctype>
#include <cmath>
#include <cassert>

#include <iostream>
#include <string>
#include <sstream>

static int toknum = 0;
static std::string token("");

#define ENSURE(a) do{ \
    if(!(a)) cancel(#a); \
}while(0)

#define TOKEN(a) do{ \
    std::string STR; \
    std::cin >> STR; \
    std::stringstream S1; \
    S1 << STR; \
    S1 >> a; \
    std::stringstream S; \
    ++toknum; \
    token.assign(STR); \
}while(0)

static void cancel(const char* assertion)
{
    fprintf(stderr, "Syntax error near token %d \"%s\"\n", toknum, token.c_str());
    fprintf(stderr, "Failed assertion '%s'\n", assertion);
    return abort();
}

static bool isnote(char c)
{
    static char notes[] = "CDEFGAB";
    return strchr(notes, c) != NULL;
}

static signed translate_note(char name)
{
    switch(name) {
    case 'C': return 0;
    case 'D': return 2;
    case 'E': return 4;
    case 'F': return 5;
    case 'G': return 7;
    case 'A': return 9;
    case 'B': return 11;
    default: ENSURE(isnote(name));
    }
}

static unsigned short get_frequency(char name, signed scale, char accidental)
{
    signed Ascale = 4;
    signed A = 9;
    signed note = translate_note(name);

    signed step = (scale - Ascale) * 12 + note - A;

    switch(accidental) {
    case '#':
        ++step;
        break;
    case 'b':
        --step;
        break;
    default:
        break;
    }

    return (unsigned short)(440.0f * std::pow(2.0f, (float)step / 12.0f));
}

void parse()
{
    while(!std::cin.eof()) {
        // get channel
        unsigned channel(255);
        TOKEN(channel);
        if(!std::cin.good()) break;
        ENSURE(channel < 5);
        // get fill factor
        unsigned fill(128);
        TOKEN(fill);
        // get scale factor
        unsigned scale(1);
        TOKEN(scale);
        ENSURE(scale > 0);
        // start reading notes
        std::string s;
        do {
            TOKEN(s);
            if(s.empty() || s.compare(";") == 0) break;

            size_t i = 0;
            size_t const ns = s.size();

            int length = 0;
            do {
                if(i >= ns || !isdigit(s[i])) break;
                length *= 10;
                length += s[i++] - '0';
            } while(1);
            ENSURE(length > 0);
            ENSURE(i < ns);

            char note = s[i++];
            unsigned short frequency(0);

            if(isnote(note)) {
                ENSURE(i < ns);
                char accidental = '\0';
                if(s[i] == '#' || s[i] == 'b') {
                    accidental = s[i++];
                }
                ENSURE(i < ns);

                signed offset = 0;
                do {
                    if(i >= ns || !isdigit(s[i])) break;
                    offset *= 10;
                    offset += s[i++] - '0';
                } while(1);
                ENSURE(i >= ns);

                frequency = get_frequency(note, offset, accidental);
            }

            for(size_t i = 0; i < length * scale; ++i) {
                pwm el = { frequency, fill };
                g_channels[channel].push_back(el);
            }

            g_maxChannelLen = std::max(g_maxChannelLen, g_channels[channel].size());
        } while(1);
        ENSURE(std::cin.good());
    }
}
<|endoftext|>


<commit_before>#include <iostream>
#include <cmath>
#include <unistd.h>
#include <gtest/gtest.h>
#include "dronelink.h"

using namespace dronelink;

int test_offboard_velocity()
{
    DroneLink dl;

    DroneLink::ConnectionResult ret = dl.add_udp_connection();
    if (ret != DroneLink::ConnectionResult::SUCCESS) {
        std::cout << "failed to add connection." << std::endl;
        return -1;
    }

    // Wait for device to connect via heartbeat.
    usleep(1500000);

    std::vector<uint64_t> uuids = dl.device_uuids();

    for (auto it = uuids.begin(); it != uuids.end(); ++it) {
        std::cout << "found device with UUID: " << *it << std::endl;
    }

    if (uuids.size() > 1) {
        std::cout << "found more than one device, not sure which one to use." << std::endl;
        return -1;
    } else if (uuids.size() == 0) {
        std::cout << "no device found." << std::endl;
        return -1;
    }

    uint64_t uuid = uuids.at(0);

    Action::Result action_ret = dl.device(uuid).action().arm();
    if (action_ret != Action::Result::SUCCESS) {
        std::cout << "failed to arm" <<  std::endl;
    }

    usleep(500000);

    action_ret = dl.device(uuid).action().takeoff();
    if (action_ret != Action::Result::SUCCESS) {
        std::cout << "failed to takeoff" << std::endl;
    }

    usleep(5000000);

    // Send it once before starting offboard, otherwise it will be rejected.
    dl.device(uuid).offboard().set_velocity({0.0f, 0.0f, 0.0f, 0.0f});

    Offboard::Result offboard_result = dl.device(uuid).offboard().start();

    if (offboard_result != Offboard::Result::SUCCESS) {
        std::cout << "failed to start offboard" << std::endl;
        return 1;
    }

    for (unsigned i = 0; i < 1000; ++i) {
        float vx = 5.0f * sinf(i * 0.01f);
        std::cout << "vx: " << vx << std::endl;
        dl.device(uuid).offboard().set_velocity({vx, 0.0f, 0.0f, 90.0f});
        usleep(10000);
    }

    offboard_result = dl.device(uuid).offboard().stop();

    if (offboard_result != Offboard::Result::SUCCESS) {
        std::cout << "failed to stop offboard" << std::endl;
        return 1;
    }

    action_ret = dl.device(uuid).action().land();
    if (action_ret != Action::Result::SUCCESS) {
        std::cout << "failed to land" << std::endl;
    }

    return 0;
}

TEST(Offboard, Velocity)
{
    ASSERT_EQ(test_offboard_velocity(), 0);
}

<commit_msg>offboard_velocity: improve test<commit_after>#include <iostream>
#include <cmath>
#include <unistd.h>
#include <gtest/gtest.h>
#include "dronelink.h"

using namespace dronelink;

int test_offboard_velocity()
{
    DroneLink dl;

    DroneLink::ConnectionResult ret = dl.add_udp_connection();
    if (ret != DroneLink::ConnectionResult::SUCCESS) {
        std::cout << "failed to add connection." << std::endl;
        return -1;
    }

    // Wait for device to connect via heartbeat.
    usleep(1500000);

    std::vector<uint64_t> uuids = dl.device_uuids();

    for (auto it = uuids.begin(); it != uuids.end(); ++it) {
        std::cout << "found device with UUID: " << *it << std::endl;
    }

    if (uuids.size() > 1) {
        std::cout << "found more than one device, not sure which one to use." << std::endl;
        return -1;
    } else if (uuids.size() == 0) {
        std::cout << "no device found." << std::endl;
        return -1;
    }

    uint64_t uuid = uuids.at(0);

    Action::Result action_ret = dl.device(uuid).action().arm();
    if (action_ret != Action::Result::SUCCESS) {
        std::cout << "failed to arm" <<  std::endl;
    }

    usleep(500000);

    action_ret = dl.device(uuid).action().takeoff();
    if (action_ret != Action::Result::SUCCESS) {
        std::cout << "failed to takeoff" << std::endl;
    }

    usleep(5000000);

    // Send it once before starting offboard, otherwise it will be rejected.
    dl.device(uuid).offboard().set_velocity({0.0f, 0.0f, 0.0f, 0.0f});

    Offboard::Result offboard_result = dl.device(uuid).offboard().start();

    if (offboard_result != Offboard::Result::SUCCESS) {
        std::cout << "failed to start offboard" << std::endl;
        return 1;
    }

    for (unsigned i = 0; i < 750; ++i) {
        float vx = 5.0f * sinf(i * 0.01f);
        //std::cout << "vx: " << vx << std::endl;
        dl.device(uuid).offboard().set_velocity({vx, 0.0f, 0.0f, 90.0f});
        usleep(10000);
    }

    for (unsigned i = 0; i < 100; ++i) {
        dl.device(uuid).offboard().set_velocity({0.0f, 0.0f, 0.0f, 270.0f});
        usleep(10000);
    }

    for (unsigned i = 0; i < 100; ++i) {
        dl.device(uuid).offboard().set_velocity({0.0f, 0.0f, -2.0f, 180.0f});
        usleep(10000);
    }

    dl.device(uuid).offboard().set_velocity({0.0f, 0.0f, 0.0f, 90.0f});
    for (unsigned i = 0; i < 100; ++i) {
        usleep(10000);
    }

    for (unsigned i = 0; i < 100; ++i) {
        dl.device(uuid).offboard().set_velocity({0.0f, 0.0f, -1.0f, 0.0f});
        usleep(10000);
    }

    offboard_result = dl.device(uuid).offboard().stop();

    if (offboard_result != Offboard::Result::SUCCESS) {
        std::cout << "failed to stop offboard" << std::endl;
        return 1;
    }

    action_ret = dl.device(uuid).action().land();
    if (action_ret != Action::Result::SUCCESS) {
        std::cout << "failed to land" << std::endl;
    }

    return 0;
}

TEST(Offboard, Velocity)
{
    ASSERT_EQ(test_offboard_velocity(), 0);
}

<|endoftext|>


<commit_before>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "content/child/runtime_features.h"

#include "base/command_line.h"
#include "content/public/common/content_switches.h"
#include "third_party/WebKit/public/web/WebRuntimeFeatures.h"

#if defined(OS_ANDROID)
#include <cpu-features.h>
#include "media/base/android/media_codec_bridge.h"
#endif

using blink::WebRuntimeFeatures;

namespace content {

static void SetRuntimeFeatureDefaultsForPlatform() {
#if defined(OS_ANDROID)
#if !defined(GOOGLE_TV)
  // MSE/EME implementation needs Android MediaCodec API.
  if (!media::MediaCodecBridge::IsAvailable()) {
    WebRuntimeFeatures::enableWebKitMediaSource(false);
    WebRuntimeFeatures::enableMediaSource(false);
    WebRuntimeFeatures::enablePrefixedEncryptedMedia(false);
  }
#endif  // !defined(GOOGLE_TV)
  // WebAudio is enabled by default only on ARM and only when the
  // MediaCodec API is available.
  WebRuntimeFeatures::enableWebAudio(
      media::MediaCodecBridge::IsAvailable() &&
      (android_getCpuFamily() == ANDROID_CPU_FAMILY_ARM));
  // Android does not support the Gamepad API.
  WebRuntimeFeatures::enableGamepad(false);
  // Android does not have support for PagePopup
  WebRuntimeFeatures::enablePagePopup(false);
  // Android does not yet support the Web Notification API. crbug.com/115320
  WebRuntimeFeatures::enableNotifications(false);
  // Android does not yet support SharedWorker. crbug.com/154571
  WebRuntimeFeatures::enableSharedWorker(false);
  // Android does not yet support NavigatorContentUtils.
  WebRuntimeFeatures::enableNavigatorContentUtils(false);
  WebRuntimeFeatures::enableTouchIconLoading(true);
#else
  WebRuntimeFeatures::enableNavigatorContentUtils(true);
#endif  // defined(OS_ANDROID)
}

void SetRuntimeFeaturesDefaultsAndUpdateFromArgs(
    const CommandLine& command_line) {
  WebRuntimeFeatures::enableStableFeatures(true);

  if (command_line.HasSwitch(switches::kEnableExperimentalWebPlatformFeatures))
    WebRuntimeFeatures::enableExperimentalFeatures(true);

  SetRuntimeFeatureDefaultsForPlatform();

  if (command_line.HasSwitch(switches::kDisableDatabases))
    WebRuntimeFeatures::enableDatabase(false);

  if (command_line.HasSwitch(switches::kDisableApplicationCache))
    WebRuntimeFeatures::enableApplicationCache(false);

  if (command_line.HasSwitch(switches::kDisableDesktopNotifications))
    WebRuntimeFeatures::enableNotifications(false);

  if (command_line.HasSwitch(switches::kDisableNavigatorContentUtils))
    WebRuntimeFeatures::enableNavigatorContentUtils(false);

  if (command_line.HasSwitch(switches::kDisableLocalStorage))
    WebRuntimeFeatures::enableLocalStorage(false);

  if (command_line.HasSwitch(switches::kDisableSessionStorage))
    WebRuntimeFeatures::enableSessionStorage(false);

  if (command_line.HasSwitch(switches::kDisableGeolocation))
    WebRuntimeFeatures::enableGeolocation(false);

  if (command_line.HasSwitch(switches::kDisableWebKitMediaSource))
    WebRuntimeFeatures::enableWebKitMediaSource(false);

  if (command_line.HasSwitch(switches::kDisableUnprefixedMediaSource))
    WebRuntimeFeatures::enableMediaSource(false);

  if (command_line.HasSwitch(switches::kDisableSharedWorkers))
    WebRuntimeFeatures::enableSharedWorker(false);

#if defined(OS_ANDROID)
  if (command_line.HasSwitch(switches::kDisableWebRTC)) {
    WebRuntimeFeatures::enableMediaStream(false);
    WebRuntimeFeatures::enablePeerConnection(false);
  }

  if (!command_line.HasSwitch(switches::kEnableSpeechRecognition))
    WebRuntimeFeatures::enableScriptedSpeech(false);
#endif

  if (command_line.HasSwitch(switches::kEnableServiceWorker))
    WebRuntimeFeatures::enableServiceWorker(true);

#if defined(OS_ANDROID)
  // WebAudio requires the MediaCodec API.
#if defined(ARCH_CPU_X86)
  // WebAudio is disabled by default on x86.
  WebRuntimeFeatures::enableWebAudio(
      command_line.HasSwitch(switches::kEnableWebAudio) &&
      media::MediaCodecBridge::IsAvailable());
#elif defined(ARCH_CPU_ARMEL)
  // WebAudio is enabled by default on ARM.
  WebRuntimeFeatures::enableWebAudio(
      !command_line.HasSwitch(switches::kDisableWebAudio) &&
      media::MediaCodecBridge::IsAvailable());
#else
  WebRuntimeFeatures::enableWebAudio(false);
#endif
#else
  if (command_line.HasSwitch(switches::kDisableWebAudio))
    WebRuntimeFeatures::enableWebAudio(false);
#endif

  if (command_line.HasSwitch(switches::kDisableFullScreen))
    WebRuntimeFeatures::enableFullscreen(false);

  if (command_line.HasSwitch(switches::kEnableEncryptedMedia))
    WebRuntimeFeatures::enableEncryptedMedia(true);

  if (command_line.HasSwitch(switches::kDisablePrefixedEncryptedMedia))
    WebRuntimeFeatures::enablePrefixedEncryptedMedia(false);

  // FIXME: Remove the enable switch once Web Animations CSS is enabled by
  // default in Blink.
  if (command_line.HasSwitch(switches::kEnableWebAnimationsCSS))
    WebRuntimeFeatures::enableWebAnimationsCSS(true);
  else if (command_line.HasSwitch(switches::kDisableWebAnimationsCSS))
    WebRuntimeFeatures::enableWebAnimationsCSS(false);

  if (command_line.HasSwitch(switches::kEnableWebAnimationsSVG))
    WebRuntimeFeatures::enableWebAnimationsSVG(true);

  if (command_line.HasSwitch(switches::kEnableWebMIDI))
    WebRuntimeFeatures::enableWebMIDI(true);

  if (command_line.HasSwitch(switches::kDisableDeviceMotion))
    WebRuntimeFeatures::enableDeviceMotion(false);

  if (command_line.HasSwitch(switches::kDisableDeviceOrientation))
    WebRuntimeFeatures::enableDeviceOrientation(false);

  if (command_line.HasSwitch(switches::kDisableSpeechInput))
    WebRuntimeFeatures::enableSpeechInput(false);

  if (command_line.HasSwitch(switches::kDisableFileSystem))
    WebRuntimeFeatures::enableFileSystem(false);

#if defined(OS_WIN)
  if (command_line.HasSwitch(switches::kEnableDirectWrite))
    WebRuntimeFeatures::enableDirectWrite(true);
#endif

  if (command_line.HasSwitch(switches::kEnableExperimentalCanvasFeatures))
    WebRuntimeFeatures::enableExperimentalCanvasFeatures(true);

  if (command_line.HasSwitch(switches::kEnableSpeechSynthesis))
    WebRuntimeFeatures::enableSpeechSynthesis(true);

  if (command_line.HasSwitch(switches::kEnableWebGLDraftExtensions))
    WebRuntimeFeatures::enableWebGLDraftExtensions(true);

  if (command_line.HasSwitch(switches::kEnableHTMLImports))
    WebRuntimeFeatures::enableHTMLImports(true);

  if (command_line.HasSwitch(switches::kEnableOverlayFullscreenVideo))
    WebRuntimeFeatures::enableOverlayFullscreenVideo(true);

  if (command_line.HasSwitch(switches::kEnableOverlayScrollbars))
    WebRuntimeFeatures::enableOverlayScrollbars(true);

  if (command_line.HasSwitch(switches::kEnableInputModeAttribute))
    WebRuntimeFeatures::enableInputModeAttribute(true);

  if (command_line.HasSwitch(switches::kEnableFastTextAutosizing))
    WebRuntimeFeatures::enableFastTextAutosizing(true);

  if (command_line.HasSwitch(switches::kEnableRepaintAfterLayout))
    WebRuntimeFeatures::enableRepaintAfterLayout(true);
}

}  // namespace content
<commit_msg>Enable OrientationEvent only for android.<commit_after>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "content/child/runtime_features.h"

#include "base/command_line.h"
#include "content/public/common/content_switches.h"
#include "third_party/WebKit/public/web/WebRuntimeFeatures.h"

#if defined(OS_ANDROID)
#include <cpu-features.h>
#include "media/base/android/media_codec_bridge.h"
#endif

using blink::WebRuntimeFeatures;

namespace content {

static void SetRuntimeFeatureDefaultsForPlatform() {
#if defined(OS_ANDROID)
#if !defined(GOOGLE_TV)
  // MSE/EME implementation needs Android MediaCodec API.
  if (!media::MediaCodecBridge::IsAvailable()) {
    WebRuntimeFeatures::enableWebKitMediaSource(false);
    WebRuntimeFeatures::enableMediaSource(false);
    WebRuntimeFeatures::enablePrefixedEncryptedMedia(false);
  }
#endif  // !defined(GOOGLE_TV)
  // WebAudio is enabled by default only on ARM and only when the
  // MediaCodec API is available.
  WebRuntimeFeatures::enableWebAudio(
      media::MediaCodecBridge::IsAvailable() &&
      (android_getCpuFamily() == ANDROID_CPU_FAMILY_ARM));
  // Android does not support the Gamepad API.
  WebRuntimeFeatures::enableGamepad(false);
  // Android does not have support for PagePopup
  WebRuntimeFeatures::enablePagePopup(false);
  // Android does not yet support the Web Notification API. crbug.com/115320
  WebRuntimeFeatures::enableNotifications(false);
  // Android does not yet support SharedWorker. crbug.com/154571
  WebRuntimeFeatures::enableSharedWorker(false);
  // Android does not yet support NavigatorContentUtils.
  WebRuntimeFeatures::enableNavigatorContentUtils(false);
  WebRuntimeFeatures::enableTouchIconLoading(true);
  WebRuntimeFeatures::enableOrientationEvent(true);
#else
  WebRuntimeFeatures::enableNavigatorContentUtils(true);
#endif  // defined(OS_ANDROID)
}

void SetRuntimeFeaturesDefaultsAndUpdateFromArgs(
    const CommandLine& command_line) {
  WebRuntimeFeatures::enableStableFeatures(true);

  if (command_line.HasSwitch(switches::kEnableExperimentalWebPlatformFeatures))
    WebRuntimeFeatures::enableExperimentalFeatures(true);

  SetRuntimeFeatureDefaultsForPlatform();

  if (command_line.HasSwitch(switches::kDisableDatabases))
    WebRuntimeFeatures::enableDatabase(false);

  if (command_line.HasSwitch(switches::kDisableApplicationCache))
    WebRuntimeFeatures::enableApplicationCache(false);

  if (command_line.HasSwitch(switches::kDisableDesktopNotifications))
    WebRuntimeFeatures::enableNotifications(false);

  if (command_line.HasSwitch(switches::kDisableNavigatorContentUtils))
    WebRuntimeFeatures::enableNavigatorContentUtils(false);

  if (command_line.HasSwitch(switches::kDisableLocalStorage))
    WebRuntimeFeatures::enableLocalStorage(false);

  if (command_line.HasSwitch(switches::kDisableSessionStorage))
    WebRuntimeFeatures::enableSessionStorage(false);

  if (command_line.HasSwitch(switches::kDisableGeolocation))
    WebRuntimeFeatures::enableGeolocation(false);

  if (command_line.HasSwitch(switches::kDisableWebKitMediaSource))
    WebRuntimeFeatures::enableWebKitMediaSource(false);

  if (command_line.HasSwitch(switches::kDisableUnprefixedMediaSource))
    WebRuntimeFeatures::enableMediaSource(false);

  if (command_line.HasSwitch(switches::kDisableSharedWorkers))
    WebRuntimeFeatures::enableSharedWorker(false);

#if defined(OS_ANDROID)
  if (command_line.HasSwitch(switches::kDisableWebRTC)) {
    WebRuntimeFeatures::enableMediaStream(false);
    WebRuntimeFeatures::enablePeerConnection(false);
  }

  if (!command_line.HasSwitch(switches::kEnableSpeechRecognition))
    WebRuntimeFeatures::enableScriptedSpeech(false);
#endif

  if (command_line.HasSwitch(switches::kEnableServiceWorker))
    WebRuntimeFeatures::enableServiceWorker(true);

#if defined(OS_ANDROID)
  // WebAudio requires the MediaCodec API.
#if defined(ARCH_CPU_X86)
  // WebAudio is disabled by default on x86.
  WebRuntimeFeatures::enableWebAudio(
      command_line.HasSwitch(switches::kEnableWebAudio) &&
      media::MediaCodecBridge::IsAvailable());
#elif defined(ARCH_CPU_ARMEL)
  // WebAudio is enabled by default on ARM.
  WebRuntimeFeatures::enableWebAudio(
      !command_line.HasSwitch(switches::kDisableWebAudio) &&
      media::MediaCodecBridge::IsAvailable());
#else
  WebRuntimeFeatures::enableWebAudio(false);
#endif
#else
  if (command_line.HasSwitch(switches::kDisableWebAudio))
    WebRuntimeFeatures::enableWebAudio(false);
#endif

  if (command_line.HasSwitch(switches::kDisableFullScreen))
    WebRuntimeFeatures::enableFullscreen(false);

  if (command_line.HasSwitch(switches::kEnableEncryptedMedia))
    WebRuntimeFeatures::enableEncryptedMedia(true);

  if (command_line.HasSwitch(switches::kDisablePrefixedEncryptedMedia))
    WebRuntimeFeatures::enablePrefixedEncryptedMedia(false);

  // FIXME: Remove the enable switch once Web Animations CSS is enabled by
  // default in Blink.
  if (command_line.HasSwitch(switches::kEnableWebAnimationsCSS))
    WebRuntimeFeatures::enableWebAnimationsCSS(true);
  else if (command_line.HasSwitch(switches::kDisableWebAnimationsCSS))
    WebRuntimeFeatures::enableWebAnimationsCSS(false);

  if (command_line.HasSwitch(switches::kEnableWebAnimationsSVG))
    WebRuntimeFeatures::enableWebAnimationsSVG(true);

  if (command_line.HasSwitch(switches::kEnableWebMIDI))
    WebRuntimeFeatures::enableWebMIDI(true);

  if (command_line.HasSwitch(switches::kDisableDeviceMotion))
    WebRuntimeFeatures::enableDeviceMotion(false);

  if (command_line.HasSwitch(switches::kDisableDeviceOrientation))
    WebRuntimeFeatures::enableDeviceOrientation(false);

  if (command_line.HasSwitch(switches::kDisableSpeechInput))
    WebRuntimeFeatures::enableSpeechInput(false);

  if (command_line.HasSwitch(switches::kDisableFileSystem))
    WebRuntimeFeatures::enableFileSystem(false);

#if defined(OS_WIN)
  if (command_line.HasSwitch(switches::kEnableDirectWrite))
    WebRuntimeFeatures::enableDirectWrite(true);
#endif

  if (command_line.HasSwitch(switches::kEnableExperimentalCanvasFeatures))
    WebRuntimeFeatures::enableExperimentalCanvasFeatures(true);

  if (command_line.HasSwitch(switches::kEnableSpeechSynthesis))
    WebRuntimeFeatures::enableSpeechSynthesis(true);

  if (command_line.HasSwitch(switches::kEnableWebGLDraftExtensions))
    WebRuntimeFeatures::enableWebGLDraftExtensions(true);

  if (command_line.HasSwitch(switches::kEnableHTMLImports))
    WebRuntimeFeatures::enableHTMLImports(true);

  if (command_line.HasSwitch(switches::kEnableOverlayFullscreenVideo))
    WebRuntimeFeatures::enableOverlayFullscreenVideo(true);

  if (command_line.HasSwitch(switches::kEnableOverlayScrollbars))
    WebRuntimeFeatures::enableOverlayScrollbars(true);

  if (command_line.HasSwitch(switches::kEnableInputModeAttribute))
    WebRuntimeFeatures::enableInputModeAttribute(true);

  if (command_line.HasSwitch(switches::kEnableFastTextAutosizing))
    WebRuntimeFeatures::enableFastTextAutosizing(true);

  if (command_line.HasSwitch(switches::kEnableRepaintAfterLayout))
    WebRuntimeFeatures::enableRepaintAfterLayout(true);
}

}  // namespace content
<|endoftext|>


<commit_before>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#include <dune/stuff/test/main.hxx>

#include "prolongations/l2-global.hh"
#include "spaces/cg/fem.hh"

using namespace Dune::GDT::Test;

#if HAVE_DUNE_FEM

typedef testing::Types<SPACES_CG_FEM_LEVEL(1)
#if HAVE_ALUGRID
                           ,
                       SPACES_CG_FEM_ALUGRID_LEVEL(1)
#endif
                       > SpaceTypes;

TYPED_TEST_CASE(L2GlobalProlongationLocalizableOperatorTest, SpaceTypes);
TYPED_TEST(L2GlobalProlongationLocalizableOperatorTest, constructible_by_ctor)
{
  this->constructible_by_ctor();
}
TYPED_TEST(L2GlobalProlongationLocalizableOperatorTest, constructible_by_factory)
{
  this->constructible_by_factory();
}
TYPED_TEST(L2GlobalProlongationLocalizableOperatorTest, produces_correct_results)
{
  this->produces_correct_results();
}

#else // HAVE_DUNE_FEM

TEST(DISABLED_L2GlobalProlongationLocalizableOperatorTest, constructible_by_ctor)
{
}
TEST(DISABLED_L2GlobalProlongationLocalizableOperatorTest, constructible_by_factory)
{
}
TEST(DISABLED_L2GlobalProlongationLocalizableOperatorTest, produces_correct_results)
{
}

#endif // HAVE_DUNE_FEM
<commit_msg>[test.prolongations.l2_global] update expected results<commit_after>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#include <dune/stuff/test/main.hxx>

#include "prolongations/l2-global.hh"
#include "spaces/cg/fem.hh"

using namespace Dune::GDT::Test;

#if HAVE_DUNE_FEM

typedef testing::Types<SPACES_CG_FEM_LEVEL(1)
#if HAVE_ALUGRID
                           ,
                       SPACES_CG_FEM_ALUGRID_LEVEL(1)
#endif
                       > SpaceTypes;

TYPED_TEST_CASE(L2GlobalProlongationLocalizableOperatorTest, SpaceTypes);
TYPED_TEST(L2GlobalProlongationLocalizableOperatorTest, constructible_by_ctor)
{
  this->constructible_by_ctor();
}
TYPED_TEST(L2GlobalProlongationLocalizableOperatorTest, constructible_by_factory)
{
  this->constructible_by_factory();
}
TYPED_TEST(L2GlobalProlongationLocalizableOperatorTest, produces_correct_results)
{
  this->produces_correct_results(2.49e-14);
}

#else // HAVE_DUNE_FEM

TEST(DISABLED_L2GlobalProlongationLocalizableOperatorTest, constructible_by_ctor)
{
}
TEST(DISABLED_L2GlobalProlongationLocalizableOperatorTest, constructible_by_factory)
{
}
TEST(DISABLED_L2GlobalProlongationLocalizableOperatorTest, produces_correct_results)
{
}

#endif // HAVE_DUNE_FEM
<|endoftext|>


<commit_before>// $Id$

// The libMesh Finite Element Library.
// Copyright (C) 2002-2008 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner

// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.

// 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

#include "libmesh_common.h"

#ifdef LIBMESH_HAVE_PETSC

// C++ includes

// Local Includes
#include "nonlinear_implicit_system.h"
#include "petsc_nonlinear_solver.h"
#include "petsc_linear_solver.h"
#include "petsc_vector.h"
#include "petsc_matrix.h"
#include "system.h"
#include "dof_map.h"
#include "preconditioner.h"

//--------------------------------------------------------------------
// Functions with C linkage to pass to PETSc.  PETSc will call these
// methods as needed.
//
// Since they must have C linkage they have no knowledge of a namespace.
// Give them an obscure name to avoid namespace pollution.
extern "C"
{
  // Older versions of PETSc do not have the different int typedefs.
  // On 64-bit machines, PetscInt may actually be a long long int.
  // This change occurred in Petsc-2.2.1.
#if PETSC_VERSION_LESS_THAN(2,2,1)
  typedef int PetscErrorCode;
  typedef int PetscInt;
#endif

  //-------------------------------------------------------------------
  // this function is called by PETSc at the end of each nonlinear step
  PetscErrorCode
  __libmesh_petsc_snes_monitor (SNES, PetscInt its, PetscReal fnorm, void *)
  {
    //int ierr=0;

    //if (its > 0)
      libMesh::out << "  NL step "
		    << std::setw(2) << its
		    << std::scientific
		    << ", |residual|_2 = " << fnorm
		    << std::endl;

    //return ierr;
    return 0;
  }

  //---------------------------------------------------------------
  // this function is called by PETSc to evaluate the residual at X
  PetscErrorCode
  __libmesh_petsc_snes_residual (SNES, Vec x, Vec r, void *ctx)
  {
    int ierr=0;

    libmesh_assert (x   != NULL);
    libmesh_assert (r   != NULL);
    libmesh_assert (ctx != NULL);

    PetscNonlinearSolver<Number>* solver =
      static_cast<PetscNonlinearSolver<Number>*> (ctx);

    NonlinearImplicitSystem &sys = solver->system();

    PetscVector<Number>& X_sys = *libmesh_cast_ptr<PetscVector<Number>*>(sys.solution.get());
    PetscVector<Number>& R_sys = *libmesh_cast_ptr<PetscVector<Number>*>(sys.rhs);
    PetscVector<Number> X_global(x), R(r);

    // Use the systems update() to get a good local version of the parallel solution
    X_global.swap(X_sys);
    R.swap(R_sys);

    sys.get_dof_map().enforce_constraints_exactly(sys);

    sys.update();

    //Swap back
    X_global.swap(X_sys);
    R.swap(R_sys);

    R.zero();

    if      (solver->residual != NULL) solver->residual (*sys.current_local_solution.get(), R);
    else if (solver->matvec   != NULL) solver->matvec   (*sys.current_local_solution.get(), &R, NULL);
    else libmesh_error();

    R.close();
    X_global.close();

    return ierr;
  }

  //---------------------------------------------------------------
  // this function is called by PETSc to evaluate the Jacobian at X
  PetscErrorCode
  __libmesh_petsc_snes_jacobian (SNES, Vec x, Mat *jac, Mat *pc, MatStructure *msflag, void *ctx)
  {
    int ierr=0;

    libmesh_assert (ctx != NULL);

    PetscNonlinearSolver<Number>* solver =
      static_cast<PetscNonlinearSolver<Number>*> (ctx);

    NonlinearImplicitSystem &sys = solver->system();

    PetscMatrix<Number> PC(*pc);
    PetscMatrix<Number> Jac(*jac);
    PetscVector<Number>& X_sys = *libmesh_cast_ptr<PetscVector<Number>*>(sys.solution.get());
    PetscMatrix<Number>& Jac_sys = *libmesh_cast_ptr<PetscMatrix<Number>*>(sys.matrix);
    PetscVector<Number> X_global(x);

    // Set the dof maps
    PC.attach_dof_map(sys.get_dof_map());
    Jac.attach_dof_map(sys.get_dof_map());

    // Use the systems update() to get a good local version of the parallel solution
    X_global.swap(X_sys);
    Jac.swap(Jac_sys);

    sys.get_dof_map().enforce_constraints_exactly(sys);
    sys.update();

    X_global.swap(X_sys);
    Jac.swap(Jac_sys);

    PC.zero();

    if      (solver->jacobian != NULL) solver->jacobian (*sys.current_local_solution.get(), PC);
    else if (solver->matvec   != NULL) solver->matvec   (*sys.current_local_solution.get(), NULL, &PC);
    else libmesh_error();

    PC.close();
    Jac.close();
    X_global.close();

    *msflag = SAME_NONZERO_PATTERN;

    return ierr;
  }

} // end extern "C"
//---------------------------------------------------------------------

//---------------------------------------------------------------------
// PetscNonlinearSolver<> methods
template <typename T>
void PetscNonlinearSolver<T>::clear ()
{
  if (this->initialized())
    {
      this->_is_initialized = false;

      int ierr=0;

      ierr = SNESDestroy(_snes);
             CHKERRABORT(libMesh::COMM_WORLD,ierr);
    }
}

template <typename T>
void PetscNonlinearSolver<T>::init ()
{
  // Initialize the data structures if not done so already.
  if (!this->initialized())
    {
      this->_is_initialized = true;

      int ierr=0;

#if PETSC_VERSION_LESS_THAN(2,1,2)
      // At least until Petsc 2.1.1, the SNESCreate had a different calling syntax.
      // The second argument was of type SNESProblemType, and could have a value of
      // either SNES_NONLINEAR_EQUATIONS or SNES_UNCONSTRAINED_MINIMIZATION.
      ierr = SNESCreate(libMesh::COMM_WORLD, SNES_NONLINEAR_EQUATIONS, &_snes);
             CHKERRABORT(libMesh::COMM_WORLD,ierr);

#else

      ierr = SNESCreate(libMesh::COMM_WORLD,&_snes);
             CHKERRABORT(libMesh::COMM_WORLD,ierr);

#endif

#if PETSC_VERSION_LESS_THAN(2,3,3)
      ierr = SNESSetMonitor (_snes, __libmesh_petsc_snes_monitor,
			     this, PETSC_NULL);
#else
      // API name change in PETSc 2.3.3
      ierr = SNESMonitorSet (_snes, __libmesh_petsc_snes_monitor,
			     this, PETSC_NULL);
#endif
             CHKERRABORT(libMesh::COMM_WORLD,ierr);

      ierr = SNESSetFromOptions(_snes);
             CHKERRABORT(libMesh::COMM_WORLD,ierr);

      if(this->_preconditioner)
      {
        KSP ksp;
        ierr = SNESGetKSP (_snes, &ksp);
               CHKERRABORT(libMesh::COMM_WORLD,ierr);
        PC pc;
        ierr = KSPGetPC(ksp,&pc);
               CHKERRABORT(libMesh::COMM_WORLD,ierr);

        PCSetType(pc, PCSHELL);
        PCShellSetContext(pc,(void*)this->_preconditioner);

        //Re-Use the shell functions from petsc_linear_solver
        PCShellSetSetUp(pc,__libmesh_petsc_preconditioner_setup);
        PCShellSetApply(pc,__libmesh_petsc_preconditioner_apply);
      }
    }
}

template <typename T>
std::pair<unsigned int, Real>
PetscNonlinearSolver<T>::solve (SparseMatrix<T>&  jac_in,  // System Jacobian Matrix
				NumericVector<T>& x_in,    // Solution vector
				NumericVector<T>& r_in,    // Residual vector
				const double,              // Stopping tolerance
				const unsigned int)
{
  this->init ();

  // Make sure the data passed in are really of Petsc types
  PetscMatrix<T>* jac = libmesh_cast_ptr<PetscMatrix<T>*>(&jac_in);
  PetscVector<T>* x   = libmesh_cast_ptr<PetscVector<T>*>(&x_in);
  PetscVector<T>* r   = libmesh_cast_ptr<PetscVector<T>*>(&r_in);

  int ierr=0;
  int n_iterations =0;
  // Should actually be a PetscReal, but I don't know which version of PETSc first introduced PetscReal
  Real final_residual_norm=0.;

  ierr = SNESSetFunction (_snes, r->vec(), __libmesh_petsc_snes_residual, this);
         CHKERRABORT(libMesh::COMM_WORLD,ierr);

  ierr = SNESSetJacobian (_snes, jac->mat(), jac->mat(), __libmesh_petsc_snes_jacobian, this);
         CHKERRABORT(libMesh::COMM_WORLD,ierr);

   // Have the Krylov subspace method use our good initial guess rather than 0
   KSP ksp;
   ierr = SNESGetKSP (_snes, &ksp);
          CHKERRABORT(libMesh::COMM_WORLD,ierr);

  // Set the tolerances for the iterative solver.  Use the user-supplied
  // tolerance for the relative residual & leave the others at default values
  ierr = KSPSetTolerances (ksp, this->initial_linear_tolerance, PETSC_DEFAULT,
                           PETSC_DEFAULT, this->max_linear_iterations);
         CHKERRABORT(libMesh::COMM_WORLD,ierr);

  // Set the tolerances for the non-linear solver.
  ierr = SNESSetTolerances(_snes, this->absolute_residual_tolerance, this->relative_residual_tolerance,
                           this->absolute_step_tolerance, this->max_nonlinear_iterations, this->max_function_evaluations);
         CHKERRABORT(libMesh::COMM_WORLD,ierr);

  //Pull in command-line options
  KSPSetFromOptions(ksp);
  SNESSetFromOptions(_snes);

  //Set the preconditioning matrix
  if(this->_preconditioner)
    this->_preconditioner->set_matrix(jac_in);

//    ierr = KSPSetInitialGuessNonzero (ksp, PETSC_TRUE);
//           CHKERRABORT(libMesh::COMM_WORLD,ierr);

// Older versions (at least up to 2.1.5) of SNESSolve took 3 arguments,
// the last one being a pointer to an int to hold the number of iterations required.
# if PETSC_VERSION_LESS_THAN(2,2,0)

 ierr = SNESSolve (_snes, x->vec(), &n_iterations);
        CHKERRABORT(libMesh::COMM_WORLD,ierr);

// 2.2.x style
#elif PETSC_VERSION_LESS_THAN(2,3,0)

 ierr = SNESSolve (_snes, x->vec());
        CHKERRABORT(libMesh::COMM_WORLD,ierr);

// 2.3.x & newer style
#else

 ierr = SNESSolve (_snes, PETSC_NULL, x->vec());
        CHKERRABORT(libMesh::COMM_WORLD,ierr);

#endif

  SNESConvergedReason reason;
  SNESGetConvergedReason(_snes,&reason);
  SNESGetIterationNumber(_snes,&n_iterations);
  SNESGetFunctionNorm(_snes,&final_residual_norm);

  //Based on Petsc 2.3.3 documentation all diverged reasons are negative
  this->converged = reason >= 0;

  this->clear();

  // return the # of its. and the final residual norm.
  return std::make_pair(n_iterations, final_residual_norm);
}

//------------------------------------------------------------------
// Explicit instantiations
template class PetscNonlinearSolver<Number>;

#endif // #ifdef LIBMESH_HAVE_PETSC
<commit_msg>Move calls to SNESGetIterationNumber and SNESGetFunctionNorm to within PETSc 2.3.x and greater codepaths.<commit_after>// $Id$

// The libMesh Finite Element Library.
// Copyright (C) 2002-2008 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner

// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.

// 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

#include "libmesh_common.h"

#ifdef LIBMESH_HAVE_PETSC

// C++ includes

// Local Includes
#include "nonlinear_implicit_system.h"
#include "petsc_nonlinear_solver.h"
#include "petsc_linear_solver.h"
#include "petsc_vector.h"
#include "petsc_matrix.h"
#include "system.h"
#include "dof_map.h"
#include "preconditioner.h"

//--------------------------------------------------------------------
// Functions with C linkage to pass to PETSc.  PETSc will call these
// methods as needed.
//
// Since they must have C linkage they have no knowledge of a namespace.
// Give them an obscure name to avoid namespace pollution.
extern "C"
{
  // Older versions of PETSc do not have the different int typedefs.
  // On 64-bit machines, PetscInt may actually be a long long int.
  // This change occurred in Petsc-2.2.1.
#if PETSC_VERSION_LESS_THAN(2,2,1)
  typedef int PetscErrorCode;
  typedef int PetscInt;
#endif

  //-------------------------------------------------------------------
  // this function is called by PETSc at the end of each nonlinear step
  PetscErrorCode
  __libmesh_petsc_snes_monitor (SNES, PetscInt its, PetscReal fnorm, void *)
  {
    //int ierr=0;

    //if (its > 0)
      libMesh::out << "  NL step "
		    << std::setw(2) << its
		    << std::scientific
		    << ", |residual|_2 = " << fnorm
		    << std::endl;

    //return ierr;
    return 0;
  }

  //---------------------------------------------------------------
  // this function is called by PETSc to evaluate the residual at X
  PetscErrorCode
  __libmesh_petsc_snes_residual (SNES, Vec x, Vec r, void *ctx)
  {
    int ierr=0;

    libmesh_assert (x   != NULL);
    libmesh_assert (r   != NULL);
    libmesh_assert (ctx != NULL);

    PetscNonlinearSolver<Number>* solver =
      static_cast<PetscNonlinearSolver<Number>*> (ctx);

    NonlinearImplicitSystem &sys = solver->system();

    PetscVector<Number>& X_sys = *libmesh_cast_ptr<PetscVector<Number>*>(sys.solution.get());
    PetscVector<Number>& R_sys = *libmesh_cast_ptr<PetscVector<Number>*>(sys.rhs);
    PetscVector<Number> X_global(x), R(r);

    // Use the systems update() to get a good local version of the parallel solution
    X_global.swap(X_sys);
    R.swap(R_sys);

    sys.get_dof_map().enforce_constraints_exactly(sys);

    sys.update();

    //Swap back
    X_global.swap(X_sys);
    R.swap(R_sys);

    R.zero();

    if      (solver->residual != NULL) solver->residual (*sys.current_local_solution.get(), R);
    else if (solver->matvec   != NULL) solver->matvec   (*sys.current_local_solution.get(), &R, NULL);
    else libmesh_error();

    R.close();
    X_global.close();

    return ierr;
  }

  //---------------------------------------------------------------
  // this function is called by PETSc to evaluate the Jacobian at X
  PetscErrorCode
  __libmesh_petsc_snes_jacobian (SNES, Vec x, Mat *jac, Mat *pc, MatStructure *msflag, void *ctx)
  {
    int ierr=0;

    libmesh_assert (ctx != NULL);

    PetscNonlinearSolver<Number>* solver =
      static_cast<PetscNonlinearSolver<Number>*> (ctx);

    NonlinearImplicitSystem &sys = solver->system();

    PetscMatrix<Number> PC(*pc);
    PetscMatrix<Number> Jac(*jac);
    PetscVector<Number>& X_sys = *libmesh_cast_ptr<PetscVector<Number>*>(sys.solution.get());
    PetscMatrix<Number>& Jac_sys = *libmesh_cast_ptr<PetscMatrix<Number>*>(sys.matrix);
    PetscVector<Number> X_global(x);

    // Set the dof maps
    PC.attach_dof_map(sys.get_dof_map());
    Jac.attach_dof_map(sys.get_dof_map());

    // Use the systems update() to get a good local version of the parallel solution
    X_global.swap(X_sys);
    Jac.swap(Jac_sys);

    sys.get_dof_map().enforce_constraints_exactly(sys);
    sys.update();

    X_global.swap(X_sys);
    Jac.swap(Jac_sys);

    PC.zero();

    if      (solver->jacobian != NULL) solver->jacobian (*sys.current_local_solution.get(), PC);
    else if (solver->matvec   != NULL) solver->matvec   (*sys.current_local_solution.get(), NULL, &PC);
    else libmesh_error();

    PC.close();
    Jac.close();
    X_global.close();

    *msflag = SAME_NONZERO_PATTERN;

    return ierr;
  }

} // end extern "C"
//---------------------------------------------------------------------

//---------------------------------------------------------------------
// PetscNonlinearSolver<> methods
template <typename T>
void PetscNonlinearSolver<T>::clear ()
{
  if (this->initialized())
    {
      this->_is_initialized = false;

      int ierr=0;

      ierr = SNESDestroy(_snes);
             CHKERRABORT(libMesh::COMM_WORLD,ierr);
    }
}

template <typename T>
void PetscNonlinearSolver<T>::init ()
{
  // Initialize the data structures if not done so already.
  if (!this->initialized())
    {
      this->_is_initialized = true;

      int ierr=0;

#if PETSC_VERSION_LESS_THAN(2,1,2)
      // At least until Petsc 2.1.1, the SNESCreate had a different calling syntax.
      // The second argument was of type SNESProblemType, and could have a value of
      // either SNES_NONLINEAR_EQUATIONS or SNES_UNCONSTRAINED_MINIMIZATION.
      ierr = SNESCreate(libMesh::COMM_WORLD, SNES_NONLINEAR_EQUATIONS, &_snes);
             CHKERRABORT(libMesh::COMM_WORLD,ierr);

#else

      ierr = SNESCreate(libMesh::COMM_WORLD,&_snes);
             CHKERRABORT(libMesh::COMM_WORLD,ierr);

#endif

#if PETSC_VERSION_LESS_THAN(2,3,3)
      ierr = SNESSetMonitor (_snes, __libmesh_petsc_snes_monitor,
			     this, PETSC_NULL);
#else
      // API name change in PETSc 2.3.3
      ierr = SNESMonitorSet (_snes, __libmesh_petsc_snes_monitor,
			     this, PETSC_NULL);
#endif
             CHKERRABORT(libMesh::COMM_WORLD,ierr);

      ierr = SNESSetFromOptions(_snes);
             CHKERRABORT(libMesh::COMM_WORLD,ierr);

      if(this->_preconditioner)
      {
        KSP ksp;
        ierr = SNESGetKSP (_snes, &ksp);
               CHKERRABORT(libMesh::COMM_WORLD,ierr);
        PC pc;
        ierr = KSPGetPC(ksp,&pc);
               CHKERRABORT(libMesh::COMM_WORLD,ierr);

        PCSetType(pc, PCSHELL);
        PCShellSetContext(pc,(void*)this->_preconditioner);

        //Re-Use the shell functions from petsc_linear_solver
        PCShellSetSetUp(pc,__libmesh_petsc_preconditioner_setup);
        PCShellSetApply(pc,__libmesh_petsc_preconditioner_apply);
      }
    }
}

template <typename T>
std::pair<unsigned int, Real>
PetscNonlinearSolver<T>::solve (SparseMatrix<T>&  jac_in,  // System Jacobian Matrix
				NumericVector<T>& x_in,    // Solution vector
				NumericVector<T>& r_in,    // Residual vector
				const double,              // Stopping tolerance
				const unsigned int)
{
  this->init ();

  // Make sure the data passed in are really of Petsc types
  PetscMatrix<T>* jac = libmesh_cast_ptr<PetscMatrix<T>*>(&jac_in);
  PetscVector<T>* x   = libmesh_cast_ptr<PetscVector<T>*>(&x_in);
  PetscVector<T>* r   = libmesh_cast_ptr<PetscVector<T>*>(&r_in);

  int ierr=0;
  int n_iterations =0;
  // Should actually be a PetscReal, but I don't know which version of PETSc first introduced PetscReal
  Real final_residual_norm=0.;

  ierr = SNESSetFunction (_snes, r->vec(), __libmesh_petsc_snes_residual, this);
         CHKERRABORT(libMesh::COMM_WORLD,ierr);

  ierr = SNESSetJacobian (_snes, jac->mat(), jac->mat(), __libmesh_petsc_snes_jacobian, this);
         CHKERRABORT(libMesh::COMM_WORLD,ierr);

   // Have the Krylov subspace method use our good initial guess rather than 0
   KSP ksp;
   ierr = SNESGetKSP (_snes, &ksp);
          CHKERRABORT(libMesh::COMM_WORLD,ierr);

  // Set the tolerances for the iterative solver.  Use the user-supplied
  // tolerance for the relative residual & leave the others at default values
  ierr = KSPSetTolerances (ksp, this->initial_linear_tolerance, PETSC_DEFAULT,
                           PETSC_DEFAULT, this->max_linear_iterations);
         CHKERRABORT(libMesh::COMM_WORLD,ierr);

  // Set the tolerances for the non-linear solver.
  ierr = SNESSetTolerances(_snes, this->absolute_residual_tolerance, this->relative_residual_tolerance,
                           this->absolute_step_tolerance, this->max_nonlinear_iterations, this->max_function_evaluations);
         CHKERRABORT(libMesh::COMM_WORLD,ierr);

  //Pull in command-line options
  KSPSetFromOptions(ksp);
  SNESSetFromOptions(_snes);

  //Set the preconditioning matrix
  if(this->_preconditioner)
    this->_preconditioner->set_matrix(jac_in);

//    ierr = KSPSetInitialGuessNonzero (ksp, PETSC_TRUE);
//           CHKERRABORT(libMesh::COMM_WORLD,ierr);

// Older versions (at least up to 2.1.5) of SNESSolve took 3 arguments,
// the last one being a pointer to an int to hold the number of iterations required.
# if PETSC_VERSION_LESS_THAN(2,2,0)

 ierr = SNESSolve (_snes, x->vec(), &n_iterations);
        CHKERRABORT(libMesh::COMM_WORLD,ierr);

// 2.2.x style
#elif PETSC_VERSION_LESS_THAN(2,3,0)

 ierr = SNESSolve (_snes, x->vec());
        CHKERRABORT(libMesh::COMM_WORLD,ierr);

// 2.3.x & newer style
#else

  ierr = SNESSolve (_snes, PETSC_NULL, x->vec());
         CHKERRABORT(libMesh::COMM_WORLD,ierr);

  ierr = SNESGetIterationNumber(_snes,&n_iterations);
         CHKERRABORT(libMesh::COMM_WORLD,ierr);

  ierr = SNESGetFunctionNorm(_snes,&final_residual_norm);
	 CHKERRABORT(libMesh::COMM_WORLD,ierr);

#endif

  SNESConvergedReason reason;
  SNESGetConvergedReason(_snes,&reason);

  //Based on Petsc 2.3.3 documentation all diverged reasons are negative
  this->converged = reason >= 0;

  this->clear();

  // return the # of its. and the final residual norm.
  return std::make_pair(n_iterations, final_residual_norm);
}

//------------------------------------------------------------------
// Explicit instantiations
template class PetscNonlinearSolver<Number>;

#endif // #ifdef LIBMESH_HAVE_PETSC
<|endoftext|>


<commit_before>#include <iostream>
#include <cassert>
#include <algorithm>
#include <numeric>
#include <vector>
#include <agency/experimental/vector.hpp>

void test_reallocating_range_assign()
{
  using namespace agency::experimental;

  {
    // test range assign into empty vector

    vector<int> v;

    size_t num_elements_to_assign = 5;
    std::vector<int> assign_me(num_elements_to_assign);
    std::iota(assign_me.begin(), assign_me.end(), 0);

    v.assign(assign_me.begin(), assign_me.end());

    assert(v.size() == num_elements_to_assign);
    assert(std::equal(v.begin(), v.end(), assign_me.begin()));
  }

  {
    // test range assign into small vector

    vector<int> v(3);

    size_t num_elements_to_assign = 5;
    std::vector<int> assign_me(num_elements_to_assign);
    std::iota(assign_me.begin(), assign_me.end(), 0);

    v.assign(assign_me.begin(), assign_me.end());

    assert(v.size() == num_elements_to_assign);
    assert(std::equal(v.begin(), v.end(), assign_me.begin()));
  }
}

void test_nonreallocating_range_assign()
{
  using namespace agency::experimental;

  {
    // test range assign into empty vector with capacity

    vector<int> v;

    size_t num_elements_to_assign = 5;
    v.reserve(5);

    std::vector<int> assign_me(num_elements_to_assign);
    std::iota(assign_me.begin(), assign_me.end(), 0);

    v.assign(assign_me.begin(), assign_me.end());

    assert(v.size() == num_elements_to_assign);
    assert(std::equal(v.begin(), v.end(), assign_me.begin()));
  }

  {
    // test range assign into small vector with capacity

    vector<int> v(3);

    size_t num_elements_to_assign = 5;
    v.reserve(5);

    std::vector<int> assign_me(num_elements_to_assign);
    std::iota(assign_me.begin(), assign_me.end(), 0);

    v.assign(assign_me.begin(), assign_me.end());

    assert(v.size() == num_elements_to_assign);
    assert(std::equal(v.begin(), v.end(), assign_me.begin()));
  }

  {
    // test range assign into large vector
    size_t num_elements_to_assign = 5;

    vector<int> v(2 * num_elements_to_assign);

    std::vector<int> assign_me(num_elements_to_assign);
    std::iota(assign_me.begin(), assign_me.end(), 0);

    v.assign(assign_me.begin(), assign_me.end());

    assert(v.size() == num_elements_to_assign);
    assert(std::equal(v.begin(), v.end(), assign_me.begin()));
  }
}

int main()
{
  test_reallocating_range_assign();

  std::cout << "OK" << std::endl;

  return 0;
}

<commit_msg>Call test function<commit_after>#include <iostream>
#include <cassert>
#include <algorithm>
#include <numeric>
#include <vector>
#include <agency/experimental/vector.hpp>

void test_reallocating_range_assign()
{
  using namespace agency::experimental;

  {
    // test range assign into empty vector

    vector<int> v;

    size_t num_elements_to_assign = 5;
    std::vector<int> assign_me(num_elements_to_assign);
    std::iota(assign_me.begin(), assign_me.end(), 0);

    v.assign(assign_me.begin(), assign_me.end());

    assert(v.size() == num_elements_to_assign);
    assert(std::equal(v.begin(), v.end(), assign_me.begin()));
  }

  {
    // test range assign into small vector

    vector<int> v(3);

    size_t num_elements_to_assign = 5;
    std::vector<int> assign_me(num_elements_to_assign);
    std::iota(assign_me.begin(), assign_me.end(), 0);

    v.assign(assign_me.begin(), assign_me.end());

    assert(v.size() == num_elements_to_assign);
    assert(std::equal(v.begin(), v.end(), assign_me.begin()));
  }
}

void test_nonreallocating_range_assign()
{
  using namespace agency::experimental;

  {
    // test range assign into empty vector with capacity

    vector<int> v;

    size_t num_elements_to_assign = 5;
    v.reserve(5);

    std::vector<int> assign_me(num_elements_to_assign);
    std::iota(assign_me.begin(), assign_me.end(), 0);

    v.assign(assign_me.begin(), assign_me.end());

    assert(v.size() == num_elements_to_assign);
    assert(std::equal(v.begin(), v.end(), assign_me.begin()));
  }

  {
    // test range assign into small vector with capacity

    vector<int> v(3);

    size_t num_elements_to_assign = 5;
    v.reserve(5);

    std::vector<int> assign_me(num_elements_to_assign);
    std::iota(assign_me.begin(), assign_me.end(), 0);

    v.assign(assign_me.begin(), assign_me.end());

    assert(v.size() == num_elements_to_assign);
    assert(std::equal(v.begin(), v.end(), assign_me.begin()));
  }

  {
    // test range assign into large vector
    size_t num_elements_to_assign = 5;

    vector<int> v(2 * num_elements_to_assign);

    std::vector<int> assign_me(num_elements_to_assign);
    std::iota(assign_me.begin(), assign_me.end(), 0);

    v.assign(assign_me.begin(), assign_me.end());

    assert(v.size() == num_elements_to_assign);
    assert(std::equal(v.begin(), v.end(), assign_me.begin()));
  }
}

int main()
{
  test_reallocating_range_assign();
  test_nonreallocating_range_assign();

  std::cout << "OK" << std::endl;

  return 0;
}

<|endoftext|>